randfile.c 9.5 KB

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