randfile.c 9.4 KB

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