Debian Codegraph @

debian/rust-vendor/aws-lc-sys/aws-lc/crypto/test/test_util.cc

raw
1 // Copyright (c) 2015, Google Inc.
2 // SPDX-License-Identifier: ISC
3
4 #include "test_util.h"
5
6 #include <fstream>
7 #include <ostream>
8 #include <inttypes.h>
9
10 #include <openssl/bn.h>
11 #include <openssl/err.h>
12
13 #include <thread>
14 #if !defined(OPENSSL_WINDOWS)
15 #include <sys/wait.h>
16 #endif
17
18 #include <inttypes.h>
19
20 #include <openssl/err.h>
21
22 #include "../internal.h"
23 #include "../ube/fork_ube_detect.h"
24 #include "openssl/pem.h"
25 #include "openssl/rand.h"
26
27
28 void hexdump(FILE *fp, const char *msg, const void *in, size_t len) {
29 const uint8_t *data = reinterpret_cast<const uint8_t *>(in);
30
31 fputs(msg, fp);
32 for (size_t i = 0; i < len; i++) {
33 fprintf(fp, "%02x", data[i]);
34 }
35 fputs("\n", fp);
36 }
37
38 std::ostream &operator<<(std::ostream &os, const Bytes &in) {
39 if (in.span_.empty()) {
40 return os << "<empty Bytes>";
41 }
42
43 // Print a byte slice as hex.
44 os << EncodeHex(in.span_);
45 return os;
46 }
47
48 bool DecodeHex(std::vector<uint8_t> *out, const std::string &in) {
49 out->clear();
50 if (in.size() % 2 != 0) {
51 return false;
52 }
53 out->reserve(in.size() / 2);
54 for (size_t i = 0; i < in.size(); i += 2) {
55 uint8_t hi, lo;
56 if (!OPENSSL_fromxdigit(&hi, in[i]) ||
57 !OPENSSL_fromxdigit(&lo, in[i + 1])) {
58 return false;
59 }
60 out->push_back((hi << 4) | lo);
61 }
62 return true;
63 }
64
65 std::vector<uint8_t> HexToBytes(const char *str) {
66 std::vector<uint8_t> ret;
67 if (!DecodeHex(&ret, str)) {
68 abort();
69 }
70 return ret;
71 }
72
73 std::string EncodeHex(bssl::Span<const uint8_t> in) {
74 static const char kHexDigits[] = "0123456789abcdef";
75 std::string ret;
76 ret.reserve(in.size() * 2);
77 for (uint8_t b : in) {
78 ret += kHexDigits[b >> 4];
79 ret += kHexDigits[b & 0xf];
80 }
81 return ret;
82 }
83
84 testing::AssertionResult ErrorEquals(uint32_t err, int lib, int reason) {
85 if (ERR_GET_LIB(err) == lib && ERR_GET_REASON(err) == reason) {
86 return testing::AssertionSuccess();
87 }
88
89 char buf[128], expected[128];
90 return testing::AssertionFailure()
91 << "Got \"" << ERR_error_string_n(err, buf, sizeof(buf))
92 << "\", wanted \""
93 << ERR_error_string_n(ERR_PACK(lib, reason), expected,
94 sizeof(expected))
95 << "\"";
96 }
97 // CertFromPEM parses the given, NUL-terminated pem block and returns an
98 // |X509*|.
99 bssl::UniquePtr<X509> CertFromPEM(const char *pem) {
100 bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(pem, strlen(pem)));
101 if (!bio) {
102 return nullptr;
103 }
104 return bssl::UniquePtr<X509>(
105 PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
106 }
107
108 bssl::UniquePtr<RSA> RSAFromPEM(const char *pem) {
109 bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(pem, strlen(pem)));
110 if (!bio) {
111 return nullptr;
112 }
113 return bssl::UniquePtr<RSA>(
114 PEM_read_bio_RSAPrivateKey(bio.get(), nullptr, nullptr, nullptr));
115 }
116
117 bssl::UniquePtr<X509> MakeTestCert(const char *issuer,
118 const char *subject, EVP_PKEY *key,
119 bool is_ca) {
120 bssl::UniquePtr<X509> cert(X509_new());
121 if (!cert || //
122 !X509_set_version(cert.get(), X509_VERSION_3) ||
123 !X509_NAME_add_entry_by_txt(
124 X509_get_issuer_name(cert.get()), "CN", MBSTRING_UTF8,
125 reinterpret_cast<const uint8_t *>(issuer), -1, -1, 0) ||
126 !X509_NAME_add_entry_by_txt(
127 X509_get_subject_name(cert.get()), "CN", MBSTRING_UTF8,
128 reinterpret_cast<const uint8_t *>(subject), -1, -1, 0) ||
129 !X509_set_pubkey(cert.get(), key) ||
130 !ASN1_TIME_adj(X509_getm_notBefore(cert.get()), kReferenceTime, -1, 0) ||
131 !ASN1_TIME_adj(X509_getm_notAfter(cert.get()), kReferenceTime, 1, 0)) {
132 return nullptr;
133 }
134 bssl::UniquePtr<BASIC_CONSTRAINTS> bc(BASIC_CONSTRAINTS_new());
135 if (!bc) {
136 return nullptr;
137 }
138 bc->ca = is_ca ? ASN1_BOOLEAN_TRUE : ASN1_BOOLEAN_FALSE;
139 if (!X509_add1_ext_i2d(cert.get(), NID_basic_constraints, bc.get(),
140 /*crit=*/1, /*flags=*/0)) {
141 return nullptr;
142 }
143 return cert;
144 }
145
146 bssl::UniquePtr<STACK_OF(X509)> CertsToStack(
147 const std::vector<X509 *> &certs) {
148 bssl::UniquePtr<STACK_OF(X509)> stack(sk_X509_new_null());
149 if (!stack) {
150 return nullptr;
151 }
152 for (auto cert : certs) {
153 if (!bssl::PushToStack(stack.get(), bssl::UpRef(cert))) {
154 return nullptr;
155 }
156 }
157 return stack;
158 }
159
160 bool PEM_to_DER(const char *pem_str, uint8_t **out_der, long *out_der_len) {
161 char *name = nullptr;
162 char *header = nullptr;
163
164 // Create BIO from memory
165 bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(pem_str, strlen(pem_str)));
166 if (!bio) {
167 return false;
168 }
169
170 // Read PEM into DER
171 if (PEM_read_bio(bio.get(), &name, &header, out_der, out_der_len) <= 0) {
172 OPENSSL_free(name);
173 OPENSSL_free(header);
174 OPENSSL_free(*out_der);
175 *out_der = nullptr;
176 return false;
177 }
178
179 OPENSSL_free(name);
180 OPENSSL_free(header);
181 return true;
182 }
183
184 #if defined(OPENSSL_WINDOWS)
185 // GetTempPathA falls back to the Windows directory (e.g. C:\Windows\) when the
186 // TMP, TEMP, and USERPROFILE environment variables are all unset. This commonly
187 // happens when running as SYSTEM in Docker containers or CI agents. The Windows
188 // directory has special protections that cause file rename operations to fail
189 // intermittently. Detect this case and redirect to C:\Windows\Temp\ instead.
190 static DWORD GetSafeTempPathA(DWORD nBufferLength, LPSTR lpBuffer) {
191 DWORD ret = GetTempPathA(nBufferLength, lpBuffer);
192 if (ret == 0 || ret >= nBufferLength) {
193 return ret;
194 }
195 char win_dir[PATH_MAX];
196 UINT win_len = GetWindowsDirectoryA(win_dir, sizeof(win_dir));
197 if (win_len == 0 || win_len >= sizeof(win_dir)) {
198 return ret;
199 }
200 // Append trailing backslash to match GetTempPathA's format for comparison.
201 if (win_len + 1 >= sizeof(win_dir)) {
202 return ret;
203 }
204 win_dir[win_len] = '\\';
205 win_dir[win_len + 1] = '\0';
206 if (_stricmp(lpBuffer, win_dir) == 0) {
207 int written = snprintf(lpBuffer, nBufferLength, "%sTemp\\", win_dir);
208 if (written < 0 || (DWORD)written >= nBufferLength) {
209 return 0;
210 }
211 ret = (DWORD)written;
212 }
213 return ret;
214 }
215
216 size_t createTempFILEpath(char buffer[PATH_MAX]) {
217 // On Windows, tmpfile() may attempt to create temp files in the root
218 // directory of the drive, which requires Admin privileges, resulting in test
219 // failure.
220 //
221 // We deliberately avoid GetTempFileNameA for unique-name generation: it
222 // silently truncates the name prefix to 3 characters and, when uUnique is 0,
223 // combines that prefix with a 16-bit time-derived value. That gives only
224 // 65,536 possible filenames, and the empty stub file it creates on disk
225 // persists. In long CI runs (e.g. the Windows SDE job, which executes the
226 // full gtest binary multiple times) many tests accumulate "aws????.tmp"
227 // files in the shared temp directory. Once the namespace is crowded, the
228 // internal collision-retry loop inside GetTempFileNameA can fail to find a
229 // free name and return 0, producing intermittent test failures.
230 //
231 // Instead, mirror createTempDirPath: generate a 64-bit random suffix with
232 // RAND_bytes and create the file atomically with CREATE_NEW so that any
233 // collision with a concurrent caller is detected and retried.
234 char temp_path[PATH_MAX];
235 if (0 == GetSafeTempPathA(PATH_MAX, temp_path)) {
236 return 0;
237 }
238
239 static const int kMaxAttempts = 10;
240 for (int attempt = 0; attempt < kMaxAttempts; attempt++) {
241 union {
242 uint8_t bytes[8];
243 uint64_t value;
244 } random_bytes;
245 if (!RAND_bytes(random_bytes.bytes, sizeof(random_bytes.bytes))) {
246 return 0;
247 }
248
249 int written = snprintf(buffer, PATH_MAX, "%sawslctest_%" PRIX64 ".tmp",
250 temp_path, random_bytes.value);
251 // Check for truncation of the path.
252 if (written < 0 || written >= PATH_MAX) {
253 return 0;
254 }
255
256 // CREATE_NEW atomically fails with ERROR_FILE_EXISTS if the file already
257 // exists, so we never race with another caller that picked the same name.
258 HANDLE h = CreateFileA(buffer, GENERIC_WRITE, 0, NULL, CREATE_NEW,
259 FILE_ATTRIBUTE_NORMAL, NULL);
260 if (h != INVALID_HANDLE_VALUE) {
261 CloseHandle(h);
262 return (size_t)written;
263 }
264 if (GetLastError() != ERROR_FILE_EXISTS) {
265 return 0;
266 }
267 }
268 return 0;
269 }
270
271 size_t createTempDirPath(char buffer[PATH_MAX]) {
272 char temp_path[PATH_MAX];
273 union {
274 uint8_t bytes[8];
275 uint64_t value;
276 } random_bytes;
277
278 // Get the temporary path
279 if (0 == GetSafeTempPathA(PATH_MAX, temp_path)) {
280 return 0;
281 }
282
283 if (!RAND_bytes(random_bytes.bytes, sizeof(random_bytes.bytes))) {
284 return 0;
285 }
286
287 int written = snprintf(buffer, PATH_MAX, "%s\\awslctest_%" PRIX64, temp_path, random_bytes.value);
288
289 // Check for truncation of dirname
290 if (written < 0 || written >= PATH_MAX) {
291 return 0;
292 }
293
294 if (!CreateDirectoryA(buffer, NULL)) {
295 return 0;
296 }
297
298 return (size_t)written;
299 }
300
301 FILE* createRawTempFILE() {
302 char filename[PATH_MAX];
303 if(createTempFILEpath(filename) == 0) {
304 return nullptr;
305 }
306 return fopen(filename, "w+b");
307 }
308
309 testing::AssertionResult WaitForFileAccessible(const char *path) {
310 // On Windows, antivirus software, file indexing services, or other
311 // background processes can briefly lock files after they are written,
312 // causing transient ERROR_SHARING_VIOLATION failures when callers
313 // immediately try to reopen the file for reading. Retry opening the file
314 // with a short delay to wait out the lock. These values mirror the retry
315 // strategy used by WIN32_rename in tool-openssl/ca.cc.
316 //
317 // We use CreateFileA with GENERIC_READ rather than fopen(): GetLastError()
318 // is only contractually reliable after a direct Win32 API call, and the
319 // MSVC CRT may clobber it during fopen()'s internal cleanup path. The
320 // FILE_SHARE flags ensure the probe does not itself introduce a lock that
321 // would interfere with the caller's subsequent open.
322 static const int kMaxRetries = 10;
323 static const DWORD kRetryDelayMs = 200;
324 for (int attempt = 0; attempt <= kMaxRetries; attempt++) {
325 if (attempt > 0) {
326 Sleep(kRetryDelayMs);
327 }
328 HANDLE h = CreateFileA(path, GENERIC_READ,
329 FILE_SHARE_READ | FILE_SHARE_WRITE |
330 FILE_SHARE_DELETE,
331 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
332 if (h != INVALID_HANDLE_VALUE) {
333 CloseHandle(h);
334 return testing::AssertionSuccess();
335 }
336 DWORD err = GetLastError();
337 // ERROR_ACCESS_DENIED is deliberately retried alongside the obvious
338 // sharing/lock violations: on Windows it can manifest transiently from
339 // pending-deletion state, AV scans, or the Search Indexer briefly holding
340 // the file. If the permission failure is genuine, the retries will all
341 // fail identically and the test fails correctly after the retry budget.
342 if (err != ERROR_ACCESS_DENIED && err != ERROR_SHARING_VIOLATION &&
343 err != ERROR_LOCK_VIOLATION) {
344 break;
345 }
346 }
347 return testing::AssertionFailure()
348 << "File not accessible after retries: " << path;
349 }
350
351 #else
352 #include <cstdlib>
353 #include <unistd.h>
354 size_t createTempFILEpath(char buffer[PATH_MAX]) {
355 snprintf(buffer, PATH_MAX, "awslcTestTmpFileXXXXXX");
356
357 int fd = mkstemp(buffer);
358 if (fd == -1) {
359 return 0;
360 }
361
362 close(fd);
363 return strnlen(buffer, PATH_MAX);
364 }
365
366 size_t createTempDirPath(char buffer[PATH_MAX]) {
367 snprintf(buffer, PATH_MAX, "/tmp/awslcTestDirXXXXXX");
368 if (mkdtemp(buffer) == NULL) {
369 return 0;
370 }
371 return strnlen(buffer, PATH_MAX);
372 }
373
374 FILE* createRawTempFILE() {
375 return tmpfile();
376 }
377 #endif
378
379
380 TempFILE createTempFILE() {
381 return TempFILE(createRawTempFILE());
382 }
383
384 void CustomDataFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
385 int index, long argl, void *argp) {
386 free(ptr);
387 }
388
389 bool osIsAmazonLinux(void) {
390 bool res = false;
391 #if defined(OPENSSL_LINUX)
392 // Per https://docs.aws.amazon.com/linux/al2023/ug/naming-and-versioning.html.
393 std::ifstream amazonLinuxSpecificFile("/etc/amazon-linux-release-cpe");
394 if (amazonLinuxSpecificFile.is_open()) {
395 // Definitely on Amazon Linux.
396 amazonLinuxSpecificFile.close();
397 return true;
398 }
399
400 // /etc/amazon-linux-release-cpe was introduced in AL2023. For earlier, parse
401 // and read /etc/system-release-cpe.
402 std::ifstream osRelease("/etc/system-release-cpe");
403 if (!osRelease.is_open()) {
404 return false;
405 }
406
407 std::string line;
408 while (std::getline(osRelease, line)) {
409 // AL2:
410 // $ cat /etc/system-release-cpe
411 // cpe:2.3:o:amazon:amazon_linux:2
412 //
413 // AL2023:
414 // $ cat /etc/system-release-cpe
415 // cpe:2.3:o:amazon:amazon_linux:2023
416 if (line.find("amazon") != std::string::npos) {
417 res = true;
418 } else if (line.find("amazon_linux") != std::string::npos) {
419 res = true;
420 }
421 }
422 osRelease.close();
423 #endif
424 return res;
425 }
426
427 bool threadTest(const size_t numberOfThreads, std::function<void(bool*)> testFunc) {
428 bool res = true;
429
430 #if defined(OPENSSL_THREADS)
431 // char to be able to pass-as-reference.
432 std::vector<char> retValueVec(numberOfThreads, 0);
433 std::vector<std::thread> threadVec;
434
435 for (size_t i = 0; i < numberOfThreads; i++) {
436 threadVec.emplace_back(testFunc, reinterpret_cast<bool*>(&retValueVec[i]));
437 }
438
439 for (auto& thread : threadVec) {
440 thread.join();
441 }
442
443 for (size_t i = 0; i < numberOfThreads; i++) {
444 if (!static_cast<bool>(retValueVec[i])) {
445 fprintf(stderr, "Thread %lu failed\n", (long unsigned int) i);
446 res = false;
447 }
448 }
449
450 #else
451 testFunc(&res);
452 #endif
453
454 return res;
455 }
456
457 bool forkAndRunTest(std::function<bool()> child_func,
458 std::function<bool()> parent_func) {
459
460 #if defined(OPENSSL_WINDOWS)
461 // fork() is not supported on Windows. We could potentially add support for
462 // the CreateProcess API at some point.
463 return false;
464 #else
465 pid_t pid = fork();
466 if (pid == 0) { // Child
467 bool success = child_func();
468 exit(success ? 0 : 1);
469 } else if (pid > 0) { // Parent
470 bool parent_success = parent_func();
471 int status;
472 waitpid(pid, &status, 0);
473 return parent_success && WIFEXITED(status) && WEXITSTATUS(status) == 0;
474 }
475
476 // Fork failed
477 return false;
478 #endif
479 }
480
481 void maybeDisableSomeForkUbeDetectMechanisms(void) {
482 if (getenv("AWSLC_IGNORE_FORK_UBE_DETECTION")) {
483 CRYPTO_fork_detect_ignore_wipeonfork_FOR_TESTING();
484 CRYPTO_fork_detect_ignore_inheritzero_FOR_TESTING();
485 }
486 }
487
488 bool runtimeEmulationIsIntelSde(void) {
489 if (getenv("RUNTIME_EMULATION_SDE")) {
490 return true;
491 }
492 return false;
493 }
494
495 bool addressSanitizerIsEnabled(void) {
496 #if defined(OPENSSL_ASAN)
497 return true;
498 #else
499 return false;
500 #endif
501 }
502
503 bssl::UniquePtr<BIGNUM> HexToBIGNUM(const char *hex) {
504 BIGNUM *bn = nullptr;
505 BN_hex2bn(&bn, hex);
506 return bssl::UniquePtr<BIGNUM>(bn);
507 }