randfile.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. /* crypto/rand/randfile.c */
  2. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  3. * All rights reserved.
  4. *
  5. * This package is an SSL implementation written
  6. * by Eric Young (eay@cryptsoft.com).
  7. * The implementation was written so as to conform with Netscapes SSL.
  8. *
  9. * This library is free for commercial and non-commercial use as long as
  10. * the following conditions are aheared to. The following conditions
  11. * apply to all code found in this distribution, be it the RC4, RSA,
  12. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  13. * included with this distribution is covered by the same copyright terms
  14. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  15. *
  16. * Copyright remains Eric Young's, and as such any Copyright notices in
  17. * the code are not to be removed.
  18. * If this package is used in a product, Eric Young should be given attribution
  19. * as the author of the parts of the library used.
  20. * This can be in the form of a textual message at program startup or
  21. * in documentation (online or textual) provided with the package.
  22. *
  23. * Redistribution and use in source and binary forms, with or without
  24. * modification, are permitted provided that the following conditions
  25. * are met:
  26. * 1. Redistributions of source code must retain the copyright
  27. * notice, this list of conditions and the following disclaimer.
  28. * 2. Redistributions in binary form must reproduce the above copyright
  29. * notice, this list of conditions and the following disclaimer in the
  30. * documentation and/or other materials provided with the distribution.
  31. * 3. All advertising materials mentioning features or use of this software
  32. * must display the following acknowledgement:
  33. * "This product includes cryptographic software written by
  34. * Eric Young (eay@cryptsoft.com)"
  35. * The word 'cryptographic' can be left out if the rouines from the library
  36. * being used are not cryptographic related :-).
  37. * 4. If you include any Windows specific code (or a derivative thereof) from
  38. * the apps directory (application code) you must include an acknowledgement:
  39. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  40. *
  41. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  42. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  43. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  44. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  45. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  46. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  47. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  48. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  49. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  50. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  51. * SUCH DAMAGE.
  52. *
  53. * The licence and distribution terms for any publically available version or
  54. * derivative of this code cannot be changed. i.e. this code cannot simply be
  55. * copied and put under another distribution licence
  56. * [including the GNU Public Licence.]
  57. */
  58. /* We need to define this to get macros like S_IFBLK and S_IFCHR */
  59. #if !defined(OPENSSL_SYS_VXWORKS)
  60. # define _XOPEN_SOURCE 500
  61. #endif
  62. #include <errno.h>
  63. #include <stdio.h>
  64. #include <stdlib.h>
  65. #include <string.h>
  66. #include "e_os.h"
  67. #include <openssl/crypto.h>
  68. #include <openssl/rand.h>
  69. #include <openssl/buffer.h>
  70. #ifdef OPENSSL_SYS_VMS
  71. # include <unixio.h>
  72. #endif
  73. #ifndef NO_SYS_TYPES_H
  74. # include <sys/types.h>
  75. #endif
  76. #ifndef OPENSSL_NO_POSIX_IO
  77. # include <sys/stat.h>
  78. # include <fcntl.h>
  79. #endif
  80. #ifdef _WIN32
  81. # define stat _stat
  82. # define chmod _chmod
  83. # define open _open
  84. # define fdopen _fdopen
  85. #endif
  86. #undef BUFSIZE
  87. #define BUFSIZE 1024
  88. #define RAND_DATA 1024
  89. #ifdef OPENSSL_SYS_VMS
  90. /*
  91. * This declaration is a nasty hack to get around vms' extension to fopen for
  92. * passing in sharing options being disabled by our /STANDARD=ANSI89
  93. */
  94. static FILE *(*const vms_fopen)(const char *, const char *, ...) =
  95. (FILE *(*)(const char *, const char *, ...))fopen;
  96. # define VMS_OPEN_ATTRS "shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0"
  97. #endif
  98. /* #define RFILE ".rnd" - defined in ../../e_os.h */
  99. /*
  100. * Note that these functions are intended for seed files only. Entropy
  101. * devices and EGD sockets are handled in rand_unix.c
  102. */
  103. int RAND_load_file(const char *file, long bytes)
  104. {
  105. /*-
  106. * If bytes >= 0, read up to 'bytes' bytes.
  107. * if bytes == -1, read complete file.
  108. */
  109. MS_STATIC unsigned char buf[BUFSIZE];
  110. #ifndef OPENSSL_NO_POSIX_IO
  111. struct stat sb;
  112. #endif
  113. int i, ret = 0, n;
  114. FILE *in;
  115. if (file == NULL)
  116. return (0);
  117. #ifndef OPENSSL_NO_POSIX_IO
  118. # ifdef PURIFY
  119. /*
  120. * struct stat can have padding and unused fields that may not be
  121. * initialized in the call to stat(). We need to clear the entire
  122. * structure before calling RAND_add() to avoid complaints from
  123. * applications such as Valgrind.
  124. */
  125. memset(&sb, 0, sizeof(sb));
  126. # endif
  127. if (stat(file, &sb) < 0)
  128. return (0);
  129. RAND_add(&sb, sizeof(sb), 0.0);
  130. #endif
  131. if (bytes == 0)
  132. return (ret);
  133. #ifdef OPENSSL_SYS_VMS
  134. in = vms_fopen(file, "rb", VMS_OPEN_ATTRS);
  135. #else
  136. in = fopen(file, "rb");
  137. #endif
  138. if (in == NULL)
  139. goto err;
  140. #if defined(S_IFBLK) && defined(S_IFCHR) && !defined(OPENSSL_NO_POSIX_IO)
  141. if (sb.st_mode & (S_IFBLK | S_IFCHR)) {
  142. /*
  143. * this file is a device. we don't want read an infinite number of
  144. * bytes from a random device, nor do we want to use buffered I/O
  145. * because we will waste system entropy.
  146. */
  147. bytes = (bytes == -1) ? 2048 : bytes; /* ok, is 2048 enough? */
  148. # ifndef OPENSSL_NO_SETVBUF_IONBF
  149. setvbuf(in, NULL, _IONBF, 0); /* don't do buffered reads */
  150. # endif /* ndef OPENSSL_NO_SETVBUF_IONBF */
  151. }
  152. #endif
  153. for (;;) {
  154. if (bytes > 0)
  155. n = (bytes < BUFSIZE) ? (int)bytes : BUFSIZE;
  156. else
  157. n = BUFSIZE;
  158. i = fread(buf, 1, n, in);
  159. if (i <= 0)
  160. break;
  161. #ifdef PURIFY
  162. RAND_add(buf, i, (double)i);
  163. #else
  164. /* even if n != i, use the full array */
  165. RAND_add(buf, n, (double)i);
  166. #endif
  167. ret += i;
  168. if (bytes > 0) {
  169. bytes -= n;
  170. if (bytes <= 0)
  171. break;
  172. }
  173. }
  174. fclose(in);
  175. OPENSSL_cleanse(buf, BUFSIZE);
  176. err:
  177. return (ret);
  178. }
  179. int RAND_write_file(const char *file)
  180. {
  181. unsigned char buf[BUFSIZE];
  182. int i, ret = 0, rand_err = 0;
  183. FILE *out = NULL;
  184. int n;
  185. #ifndef OPENSSL_NO_POSIX_IO
  186. struct stat sb;
  187. i = stat(file, &sb);
  188. if (i != -1) {
  189. # if defined(S_ISBLK) && defined(S_ISCHR)
  190. if (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode)) {
  191. /*
  192. * this file is a device. we don't write back to it. we
  193. * "succeed" on the assumption this is some sort of random
  194. * device. Otherwise attempting to write to and chmod the device
  195. * causes problems.
  196. */
  197. return (1);
  198. }
  199. # endif
  200. }
  201. #endif
  202. #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && !defined(OPENSSL_SYS_VMS)
  203. {
  204. # ifndef O_BINARY
  205. # define O_BINARY 0
  206. # endif
  207. /*
  208. * chmod(..., 0600) is too late to protect the file, permissions
  209. * should be restrictive from the start
  210. */
  211. int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
  212. if (fd != -1)
  213. out = fdopen(fd, "wb");
  214. }
  215. #endif
  216. #ifdef OPENSSL_SYS_VMS
  217. /*
  218. * VMS NOTE: Prior versions of this routine created a _new_ version of
  219. * the rand file for each call into this routine, then deleted all
  220. * existing versions named ;-1, and finally renamed the current version
  221. * as ';1'. Under concurrent usage, this resulted in an RMS race
  222. * condition in rename() which could orphan files (see vms message help
  223. * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
  224. * the top-level version of the rand file. Note that there may still be
  225. * conditions where the top-level rand file is locked. If so, this code
  226. * will then create a new version of the rand file. Without the delete
  227. * and rename code, this can result in ascending file versions that stop
  228. * at version 32767, and this routine will then return an error. The
  229. * remedy for this is to recode the calling application to avoid
  230. * concurrent use of the rand file, or synchronize usage at the
  231. * application level. Also consider whether or not you NEED a persistent
  232. * rand file in a concurrent use situation.
  233. */
  234. out = vms_fopen(file, "rb+", VMS_OPEN_ATTRS);
  235. if (out == NULL)
  236. out = vms_fopen(file, "wb", VMS_OPEN_ATTRS);
  237. #else
  238. if (out == NULL)
  239. out = fopen(file, "wb");
  240. #endif
  241. if (out == NULL)
  242. goto err;
  243. #ifndef NO_CHMOD
  244. chmod(file, 0600);
  245. #endif
  246. n = RAND_DATA;
  247. for (;;) {
  248. i = (n > BUFSIZE) ? BUFSIZE : n;
  249. n -= BUFSIZE;
  250. if (RAND_bytes(buf, i) <= 0)
  251. rand_err = 1;
  252. i = fwrite(buf, 1, i, out);
  253. if (i <= 0) {
  254. ret = 0;
  255. break;
  256. }
  257. ret += i;
  258. if (n <= 0)
  259. break;
  260. }
  261. fclose(out);
  262. OPENSSL_cleanse(buf, BUFSIZE);
  263. err:
  264. return (rand_err ? -1 : ret);
  265. }
  266. const char *RAND_file_name(char *buf, size_t size)
  267. {
  268. char *s = NULL;
  269. #ifdef __OpenBSD__
  270. struct stat sb;
  271. #endif
  272. if (OPENSSL_issetugid() == 0)
  273. s = getenv("RANDFILE");
  274. if (s != NULL && *s && strlen(s) + 1 < size) {
  275. if (BUF_strlcpy(buf, s, size) >= size)
  276. return NULL;
  277. } else {
  278. if (OPENSSL_issetugid() == 0)
  279. s = getenv("HOME");
  280. #ifdef DEFAULT_HOME
  281. if (s == NULL) {
  282. s = DEFAULT_HOME;
  283. }
  284. #endif
  285. if (s && *s && strlen(s) + strlen(RFILE) + 2 < size) {
  286. BUF_strlcpy(buf, s, size);
  287. #ifndef OPENSSL_SYS_VMS
  288. BUF_strlcat(buf, "/", size);
  289. #endif
  290. BUF_strlcat(buf, RFILE, size);
  291. } else
  292. buf[0] = '\0'; /* no file name */
  293. }
  294. #ifdef __OpenBSD__
  295. /*
  296. * given that all random loads just fail if the file can't be seen on a
  297. * stat, we stat the file we're returning, if it fails, use /dev/arandom
  298. * instead. this allows the user to use their own source for good random
  299. * data, but defaults to something hopefully decent if that isn't
  300. * available.
  301. */
  302. if (!buf[0])
  303. if (BUF_strlcpy(buf, "/dev/arandom", size) >= size) {
  304. return (NULL);
  305. }
  306. if (stat(buf, &sb) == -1)
  307. if (BUF_strlcpy(buf, "/dev/arandom", size) >= size) {
  308. return (NULL);
  309. }
  310. #endif
  311. return (buf);
  312. }