randfile.c 8.7 KB

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