randfile.c 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /*
  2. * Copyright 1995-2025 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #if defined (__TANDEM) && defined (_SPT_MODEL_)
  10. /*
  11. * These definitions have to come first in SPT due to scoping of the
  12. * declarations in c99 associated with SPT use of stat.
  13. */
  14. # include <sys/types.h>
  15. # include <sys/stat.h>
  16. #endif
  17. #include "internal/e_os.h"
  18. #include "internal/cryptlib.h"
  19. #include <errno.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <openssl/crypto.h>
  24. #include <openssl/rand.h>
  25. #include <openssl/buffer.h>
  26. #ifdef OPENSSL_SYS_VMS
  27. # include <unixio.h>
  28. #endif
  29. #include <sys/types.h>
  30. #ifndef OPENSSL_NO_POSIX_IO
  31. # include <sys/stat.h>
  32. # include <fcntl.h>
  33. # if defined(_WIN32) && !defined(_WIN32_WCE)
  34. # include <windows.h>
  35. # include <io.h>
  36. # define stat _stat
  37. # define chmod _chmod
  38. # define open _open
  39. # define fdopen _fdopen
  40. # define fstat _fstat
  41. # define fileno _fileno
  42. # endif
  43. #endif
  44. /*
  45. * Following should not be needed, and we could have been stricter
  46. * and demand S_IS*. But some systems just don't comply... Formally
  47. * below macros are "anatomically incorrect", because normally they
  48. * would look like ((m) & MASK == TYPE), but since MASK availability
  49. * is as questionable, we settle for this poor-man fallback...
  50. */
  51. # if !defined(S_ISREG)
  52. # define S_ISREG(m) ((m) & S_IFREG)
  53. # endif
  54. #define RAND_BUF_SIZE 1024
  55. #define RFILE ".rnd"
  56. #ifdef OPENSSL_SYS_VMS
  57. /*
  58. * __FILE_ptr32 is a type provided by DEC C headers (types.h specifically)
  59. * to make sure the FILE* is a 32-bit pointer no matter what. We know that
  60. * stdio functions return this type (a study of stdio.h proves it).
  61. *
  62. * This declaration is a nasty hack to get around vms' extension to fopen for
  63. * passing in sharing options being disabled by /STANDARD=ANSI89
  64. */
  65. static __FILE_ptr32 (*const vms_fopen)(const char *, const char *, ...) =
  66. (__FILE_ptr32 (*)(const char *, const char *, ...))fopen;
  67. # define VMS_OPEN_ATTRS \
  68. "shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0"
  69. # define openssl_fopen(fname, mode) vms_fopen((fname), (mode), VMS_OPEN_ATTRS)
  70. #endif
  71. /*
  72. * Note that these functions are intended for seed files only. Entropy
  73. * devices and EGD sockets are handled in rand_unix.c If |bytes| is
  74. * -1 read the complete file; otherwise read the specified amount.
  75. */
  76. int RAND_load_file(const char *file, long bytes)
  77. {
  78. /*
  79. * The load buffer size exceeds the chunk size by the comfortable amount
  80. * of 'RAND_DRBG_STRENGTH' bytes (not bits!). This is done on purpose
  81. * to avoid calling RAND_add() with a small final chunk. Instead, such
  82. * a small final chunk will be added together with the previous chunk
  83. * (unless it's the only one).
  84. */
  85. #define RAND_LOAD_BUF_SIZE (RAND_BUF_SIZE + RAND_DRBG_STRENGTH)
  86. unsigned char buf[RAND_LOAD_BUF_SIZE];
  87. #ifndef OPENSSL_NO_POSIX_IO
  88. struct stat sb;
  89. #endif
  90. int i, n, ret = 0;
  91. FILE *in;
  92. if (bytes == 0)
  93. return 0;
  94. if ((in = openssl_fopen(file, "rb")) == NULL) {
  95. ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
  96. "Filename=%s", file);
  97. return -1;
  98. }
  99. #ifndef OPENSSL_NO_POSIX_IO
  100. if (fstat(fileno(in), &sb) < 0) {
  101. ERR_raise_data(ERR_LIB_RAND, RAND_R_INTERNAL_ERROR,
  102. "Filename=%s", file);
  103. fclose(in);
  104. return -1;
  105. }
  106. if (bytes < 0) {
  107. if (S_ISREG(sb.st_mode))
  108. bytes = sb.st_size;
  109. else
  110. bytes = RAND_DRBG_STRENGTH;
  111. }
  112. #endif
  113. /*
  114. * On VMS, setbuf() will only take 32-bit pointers, and a compilation
  115. * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
  116. * However, we trust that the C RTL will never give us a FILE pointer
  117. * above the first 4 GB of memory, so we simply turn off the warning
  118. * temporarily.
  119. */
  120. #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
  121. # pragma environment save
  122. # pragma message disable maylosedata2
  123. #endif
  124. /*
  125. * Don't buffer, because even if |file| is regular file, we have
  126. * no control over the buffer, so why would we want a copy of its
  127. * contents lying around?
  128. */
  129. setbuf(in, NULL);
  130. #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
  131. # pragma environment restore
  132. #endif
  133. for (;;) {
  134. if (bytes > 0)
  135. n = (bytes <= RAND_LOAD_BUF_SIZE) ? (int)bytes : RAND_BUF_SIZE;
  136. else
  137. n = RAND_LOAD_BUF_SIZE;
  138. i = fread(buf, 1, n, in);
  139. #ifdef EINTR
  140. if (ferror(in) && errno == EINTR) {
  141. clearerr(in);
  142. if (i == 0)
  143. continue;
  144. }
  145. #endif
  146. if (i == 0)
  147. break;
  148. RAND_add(buf, i, (double)i);
  149. ret += i;
  150. /* If given a bytecount, and we did it, break. */
  151. if (bytes > 0 && (bytes -= i) <= 0)
  152. break;
  153. /* We can hit a signed integer overflow on the next iteration */
  154. if (ret > INT_MAX - RAND_LOAD_BUF_SIZE)
  155. break;
  156. }
  157. OPENSSL_cleanse(buf, sizeof(buf));
  158. fclose(in);
  159. if (!RAND_status()) {
  160. ERR_raise_data(ERR_LIB_RAND, RAND_R_RESEED_ERROR, "Filename=%s", file);
  161. return -1;
  162. }
  163. return ret;
  164. }
  165. int RAND_write_file(const char *file)
  166. {
  167. unsigned char buf[RAND_BUF_SIZE];
  168. int ret = -1;
  169. FILE *out = NULL;
  170. #ifndef OPENSSL_NO_POSIX_IO
  171. struct stat sb;
  172. if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) {
  173. ERR_raise_data(ERR_LIB_RAND, RAND_R_NOT_A_REGULAR_FILE,
  174. "Filename=%s", file);
  175. return -1;
  176. }
  177. #endif
  178. /* Collect enough random data. */
  179. if (RAND_priv_bytes(buf, (int)sizeof(buf)) != 1)
  180. return -1;
  181. #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \
  182. !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS)
  183. {
  184. # ifndef O_BINARY
  185. # define O_BINARY 0
  186. # endif
  187. /*
  188. * chmod(..., 0600) is too late to protect the file, permissions
  189. * should be restrictive from the start
  190. */
  191. int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
  192. if (fd != -1) {
  193. out = fdopen(fd, "wb");
  194. if (out == NULL) {
  195. close(fd);
  196. ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
  197. "Filename=%s", file);
  198. return -1;
  199. }
  200. }
  201. }
  202. #endif
  203. #ifdef OPENSSL_SYS_VMS
  204. /*
  205. * VMS NOTE: Prior versions of this routine created a _new_ version of
  206. * the rand file for each call into this routine, then deleted all
  207. * existing versions named ;-1, and finally renamed the current version
  208. * as ';1'. Under concurrent usage, this resulted in an RMS race
  209. * condition in rename() which could orphan files (see vms message help
  210. * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
  211. * the top-level version of the rand file. Note that there may still be
  212. * conditions where the top-level rand file is locked. If so, this code
  213. * will then create a new version of the rand file. Without the delete
  214. * and rename code, this can result in ascending file versions that stop
  215. * at version 32767, and this routine will then return an error. The
  216. * remedy for this is to recode the calling application to avoid
  217. * concurrent use of the rand file, or synchronize usage at the
  218. * application level. Also consider whether or not you NEED a persistent
  219. * rand file in a concurrent use situation.
  220. */
  221. out = openssl_fopen(file, "rb+");
  222. #endif
  223. if (out == NULL)
  224. out = openssl_fopen(file, "wb");
  225. if (out == NULL) {
  226. ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
  227. "Filename=%s", file);
  228. return -1;
  229. }
  230. #if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
  231. /*
  232. * Yes it's late to do this (see above comment), but better than nothing.
  233. */
  234. chmod(file, 0600);
  235. #endif
  236. ret = fwrite(buf, 1, RAND_BUF_SIZE, out);
  237. fclose(out);
  238. OPENSSL_cleanse(buf, RAND_BUF_SIZE);
  239. return ret;
  240. }
  241. const char *RAND_file_name(char *buf, size_t size)
  242. {
  243. char *s = NULL;
  244. size_t len;
  245. int use_randfile = 1;
  246. #if defined(_WIN32) && defined(CP_UTF8) && !defined(_WIN32_WCE)
  247. DWORD envlen;
  248. WCHAR *var;
  249. /* Look up various environment variables. */
  250. if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) {
  251. use_randfile = 0;
  252. if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0
  253. && (envlen = GetEnvironmentVariableW(var = L"USERPROFILE",
  254. NULL, 0)) == 0)
  255. envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0);
  256. }
  257. /* If we got a value, allocate space to hold it and then get it. */
  258. if (envlen != 0) {
  259. int sz;
  260. WCHAR *val = _alloca(envlen * sizeof(WCHAR));
  261. if (GetEnvironmentVariableW(var, val, envlen) < envlen
  262. && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0,
  263. NULL, NULL)) != 0) {
  264. s = _alloca(sz);
  265. if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz,
  266. NULL, NULL) == 0)
  267. s = NULL;
  268. }
  269. }
  270. #else
  271. if ((s = ossl_safe_getenv("RANDFILE")) == NULL || *s == '\0') {
  272. use_randfile = 0;
  273. s = ossl_safe_getenv("HOME");
  274. }
  275. #endif
  276. #ifdef DEFAULT_HOME
  277. if (!use_randfile && s == NULL)
  278. s = DEFAULT_HOME;
  279. #endif
  280. if (s == NULL || *s == '\0')
  281. return NULL;
  282. len = strlen(s);
  283. if (use_randfile) {
  284. if (len + 1 >= size)
  285. return NULL;
  286. strcpy(buf, s);
  287. } else {
  288. if (len + 1 + strlen(RFILE) + 1 >= size)
  289. return NULL;
  290. strcpy(buf, s);
  291. #ifndef OPENSSL_SYS_VMS
  292. strcat(buf, "/");
  293. #endif
  294. strcat(buf, RFILE);
  295. }
  296. return buf;
  297. }