randfile.c 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /*
  2. * Copyright 1995-2024 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. }
  154. OPENSSL_cleanse(buf, sizeof(buf));
  155. fclose(in);
  156. if (!RAND_status()) {
  157. ERR_raise_data(ERR_LIB_RAND, RAND_R_RESEED_ERROR, "Filename=%s", file);
  158. return -1;
  159. }
  160. return ret;
  161. }
  162. int RAND_write_file(const char *file)
  163. {
  164. unsigned char buf[RAND_BUF_SIZE];
  165. int ret = -1;
  166. FILE *out = NULL;
  167. #ifndef OPENSSL_NO_POSIX_IO
  168. struct stat sb;
  169. if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) {
  170. ERR_raise_data(ERR_LIB_RAND, RAND_R_NOT_A_REGULAR_FILE,
  171. "Filename=%s", file);
  172. return -1;
  173. }
  174. #endif
  175. /* Collect enough random data. */
  176. if (RAND_priv_bytes(buf, (int)sizeof(buf)) != 1)
  177. return -1;
  178. #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \
  179. !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS)
  180. {
  181. # ifndef O_BINARY
  182. # define O_BINARY 0
  183. # endif
  184. /*
  185. * chmod(..., 0600) is too late to protect the file, permissions
  186. * should be restrictive from the start
  187. */
  188. int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
  189. if (fd != -1) {
  190. out = fdopen(fd, "wb");
  191. if (out == NULL) {
  192. close(fd);
  193. ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
  194. "Filename=%s", file);
  195. return -1;
  196. }
  197. }
  198. }
  199. #endif
  200. #ifdef OPENSSL_SYS_VMS
  201. /*
  202. * VMS NOTE: Prior versions of this routine created a _new_ version of
  203. * the rand file for each call into this routine, then deleted all
  204. * existing versions named ;-1, and finally renamed the current version
  205. * as ';1'. Under concurrent usage, this resulted in an RMS race
  206. * condition in rename() which could orphan files (see vms message help
  207. * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
  208. * the top-level version of the rand file. Note that there may still be
  209. * conditions where the top-level rand file is locked. If so, this code
  210. * will then create a new version of the rand file. Without the delete
  211. * and rename code, this can result in ascending file versions that stop
  212. * at version 32767, and this routine will then return an error. The
  213. * remedy for this is to recode the calling application to avoid
  214. * concurrent use of the rand file, or synchronize usage at the
  215. * application level. Also consider whether or not you NEED a persistent
  216. * rand file in a concurrent use situation.
  217. */
  218. out = openssl_fopen(file, "rb+");
  219. #endif
  220. if (out == NULL)
  221. out = openssl_fopen(file, "wb");
  222. if (out == NULL) {
  223. ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
  224. "Filename=%s", file);
  225. return -1;
  226. }
  227. #if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
  228. /*
  229. * Yes it's late to do this (see above comment), but better than nothing.
  230. */
  231. chmod(file, 0600);
  232. #endif
  233. ret = fwrite(buf, 1, RAND_BUF_SIZE, out);
  234. fclose(out);
  235. OPENSSL_cleanse(buf, RAND_BUF_SIZE);
  236. return ret;
  237. }
  238. const char *RAND_file_name(char *buf, size_t size)
  239. {
  240. char *s = NULL;
  241. size_t len;
  242. int use_randfile = 1;
  243. #if defined(_WIN32) && defined(CP_UTF8) && !defined(_WIN32_WCE)
  244. DWORD envlen;
  245. WCHAR *var;
  246. /* Look up various environment variables. */
  247. if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) {
  248. use_randfile = 0;
  249. if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0
  250. && (envlen = GetEnvironmentVariableW(var = L"USERPROFILE",
  251. NULL, 0)) == 0)
  252. envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0);
  253. }
  254. /* If we got a value, allocate space to hold it and then get it. */
  255. if (envlen != 0) {
  256. int sz;
  257. WCHAR *val = _alloca(envlen * sizeof(WCHAR));
  258. if (GetEnvironmentVariableW(var, val, envlen) < envlen
  259. && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0,
  260. NULL, NULL)) != 0) {
  261. s = _alloca(sz);
  262. if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz,
  263. NULL, NULL) == 0)
  264. s = NULL;
  265. }
  266. }
  267. #else
  268. if ((s = ossl_safe_getenv("RANDFILE")) == NULL || *s == '\0') {
  269. use_randfile = 0;
  270. s = ossl_safe_getenv("HOME");
  271. }
  272. #endif
  273. #ifdef DEFAULT_HOME
  274. if (!use_randfile && s == NULL)
  275. s = DEFAULT_HOME;
  276. #endif
  277. if (s == NULL || *s == '\0')
  278. return NULL;
  279. len = strlen(s);
  280. if (use_randfile) {
  281. if (len + 1 >= size)
  282. return NULL;
  283. strcpy(buf, s);
  284. } else {
  285. if (len + 1 + strlen(RFILE) + 1 >= size)
  286. return NULL;
  287. strcpy(buf, s);
  288. #ifndef OPENSSL_SYS_VMS
  289. strcat(buf, "/");
  290. #endif
  291. strcat(buf, RFILE);
  292. }
  293. return buf;
  294. }