1 #include <stdlib.h> 2 #include <sys/sysctl.h> 3 #include <darwintest.h> 4 #include <perfdata/perfdata.h> 5 6 typedef uint32_t entropy_sample_t; 7 8 T_GLOBAL_META(T_META_NAMESPACE("xnu.crypto"), 9 T_META_RADAR_COMPONENT_NAME("xnu"), 10 T_META_RADAR_COMPONENT_VERSION("crypto")); 11 12 T_DECL(entropy_collect, "Collect entropy for offline analysis", 13 T_META_REQUIRES_SYSCTL_EQ("kern.development", 1), 14 T_META_BOOTARGS_SET("entropy-analysis-sample-count=1000")) 15 { 16 int ret; 17 uint32_t entropy_size = 0; 18 size_t size = sizeof(entropy_size); 19 20 ret = sysctlbyname("kern.entropy.analysis.buffer_size", &entropy_size, &size, NULL, 0); 21 T_ASSERT_POSIX_SUCCESS(ret, "sysctlbyname kern.entropy.analysis.buffer_size"); 22 23 uint32_t entropy_count = entropy_size / sizeof(entropy_sample_t); 24 entropy_sample_t *entropy = calloc(entropy_count, sizeof(entropy_sample_t)); 25 size = entropy_size; 26 27 ret = sysctlbyname("kern.entropy.analysis.buffer", entropy, &size, NULL, 0); 28 T_ASSERT_POSIX_SUCCESS(ret, "sysctlbyname kern.entropy.analysis.buffer"); 29 30 // This test is not an entropy assessment. We're just checking to 31 // make sure the machinery of the entropy collection sysctl seems 32 // to be working. 33 for (uint32_t i = 0; i < entropy_count; i += 1) { 34 T_QUIET; T_EXPECT_NE(entropy[i], 0, "entropy buffer null sample %u", i); 35 } 36 37 free(entropy); 38 } 39 40 T_DECL(entropy_filter_rate, "Sample entropy filter rate") 41 { 42 int ret; 43 uint64_t total_sample_count = 0; 44 uint64_t rejected_sample_count = 0; 45 size_t size = sizeof(total_sample_count); 46 47 ret = sysctlbyname("kern.entropy.filter.total_sample_count", &total_sample_count, &size, NULL, 0); 48 T_ASSERT_POSIX_SUCCESS(ret, "kern.entropy.filter.total_sample_count"); 49 50 size = sizeof(rejected_sample_count); 51 ret = sysctlbyname("kern.entropy.filter.rejected_sample_count", &rejected_sample_count, &size, NULL, 0); 52 T_ASSERT_POSIX_SUCCESS(ret, "kern.entropy.filter.rejected_sample_count"); 53 54 double rejection_rate = (double) rejected_sample_count / (double) total_sample_count; 55 56 pdwriter_t writer = pdwriter_open_tmp("xnu", "entropy_filter_rate", 0, 0, NULL, 0); 57 T_ASSERT_NOTNULL(writer, "pdwriter_open_tmp"); 58 59 pdwriter_new_value(writer, "Rejection Rate", PDUNIT_CUSTOM(rejectrate), rejection_rate); 60 61 pdwriter_close(writer); 62 } 63