tempname.c 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /* Copyright (C) 1991-2023 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. The GNU C Library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. The GNU C Library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with the GNU C Library; if not, see
  13. <https://www.gnu.org/licenses/>. */
  14. #if !_LIBC
  15. # include <libc-config.h>
  16. # include "tempname.h"
  17. #endif
  18. #include <errno.h>
  19. #include <stdio.h>
  20. #ifndef TMP_MAX
  21. # define TMP_MAX 238328
  22. #endif
  23. #ifndef __GT_FILE
  24. # define __GT_FILE 0
  25. # define __GT_DIR 1
  26. # define __GT_NOCREATE 2
  27. #endif
  28. #if !_LIBC && (GT_FILE != __GT_FILE || GT_DIR != __GT_DIR \
  29. || GT_NOCREATE != __GT_NOCREATE)
  30. # error report this to bug-gnulib@gnu.org
  31. #endif
  32. #include <stdlib.h>
  33. #include <string.h>
  34. #include <fcntl.h>
  35. #include <stdint.h>
  36. #include <sys/random.h>
  37. #include <sys/stat.h>
  38. #include <time.h>
  39. #if _LIBC
  40. # define struct_stat64 struct __stat64_t64
  41. #else
  42. # define struct_stat64 struct stat
  43. # define __gen_tempname gen_tempname
  44. # define __mkdir mkdir
  45. # define __open open
  46. # define __lstat64_time64(file, buf) lstat (file, buf)
  47. # define __getrandom getrandom
  48. # define __clock_gettime64 clock_gettime
  49. # define __timespec64 timespec
  50. #endif
  51. /* Use getrandom if it works, falling back on a 64-bit linear
  52. congruential generator that starts with Var's value
  53. mixed in with a clock's low-order bits if available. */
  54. typedef uint_fast64_t random_value;
  55. #define RANDOM_VALUE_MAX UINT_FAST64_MAX
  56. #define BASE_62_DIGITS 10 /* 62**10 < UINT_FAST64_MAX */
  57. #define BASE_62_POWER (62LL * 62 * 62 * 62 * 62 * 62 * 62 * 62 * 62 * 62)
  58. /* Return the result of mixing the entropy from R and S.
  59. Assume that R and S are not particularly random,
  60. and that the result should look randomish to an untrained eye. */
  61. static random_value
  62. mix_random_values (random_value r, random_value s)
  63. {
  64. /* As this code is used only when high-quality randomness is neither
  65. available nor necessary, there is no need for fancier polynomials
  66. such as those in the Linux kernel's 'random' driver. */
  67. return (2862933555777941757 * r + 3037000493) ^ s;
  68. }
  69. /* Set *R to a random value.
  70. Return true if *R is set to high-quality value taken from getrandom.
  71. Otherwise return false, falling back to a low-quality *R that might
  72. depend on S.
  73. This function returns false only when getrandom fails.
  74. On GNU systems this should happen only early in the boot process,
  75. when the fallback should be good enough for programs using tempname
  76. because any attacker likely has root privileges already. */
  77. static bool
  78. random_bits (random_value *r, random_value s)
  79. {
  80. /* Without GRND_NONBLOCK it can be blocked for minutes on some systems. */
  81. if (__getrandom (r, sizeof *r, GRND_NONBLOCK) == sizeof *r)
  82. return true;
  83. /* If getrandom did not work, use ersatz entropy based on low-order
  84. clock bits. On GNU systems getrandom should fail only
  85. early in booting, when ersatz should be good enough.
  86. Do not use ASLR-based entropy, as that would leak ASLR info into
  87. the resulting file name which is typically public.
  88. Of course we are in a state of sin here. */
  89. random_value v = s;
  90. #if _LIBC || (defined CLOCK_REALTIME && HAVE_CLOCK_GETTIME)
  91. struct __timespec64 tv;
  92. __clock_gettime64 (CLOCK_REALTIME, &tv);
  93. v = mix_random_values (v, tv.tv_sec);
  94. v = mix_random_values (v, tv.tv_nsec);
  95. #endif
  96. *r = mix_random_values (v, clock ());
  97. return false;
  98. }
  99. #if _LIBC
  100. static int try_tempname_len (char *, int, void *, int (*) (char *, void *),
  101. size_t);
  102. #endif
  103. static int
  104. try_file (char *tmpl, void *flags)
  105. {
  106. int *openflags = flags;
  107. return __open (tmpl,
  108. (*openflags & ~O_ACCMODE)
  109. | O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
  110. }
  111. static int
  112. try_dir (char *tmpl, _GL_UNUSED void *flags)
  113. {
  114. return __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR);
  115. }
  116. static int
  117. try_nocreate (char *tmpl, _GL_UNUSED void *flags)
  118. {
  119. struct_stat64 st;
  120. if (__lstat64_time64 (tmpl, &st) == 0 || errno == EOVERFLOW)
  121. __set_errno (EEXIST);
  122. return errno == ENOENT ? 0 : -1;
  123. }
  124. /* These are the characters used in temporary file names. */
  125. static const char letters[] =
  126. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  127. /* Generate a temporary file name based on TMPL. TMPL must match the
  128. rules for mk[s]temp (i.e., end in at least X_SUFFIX_LEN "X"s,
  129. possibly with a suffix).
  130. The name constructed does not exist at the time of the call to
  131. this function. TMPL is overwritten with the result.
  132. KIND may be one of:
  133. __GT_NOCREATE: simply verify that the name does not exist
  134. at the time of the call.
  135. __GT_FILE: create the file using open(O_CREAT|O_EXCL)
  136. and return a read-write fd. The file is mode 0600.
  137. __GT_DIR: create a directory, which will be mode 0700.
  138. */
  139. #ifdef _LIBC
  140. static
  141. #endif
  142. int
  143. gen_tempname_len (char *tmpl, int suffixlen, int flags, int kind,
  144. size_t x_suffix_len)
  145. {
  146. static int (*const tryfunc[]) (char *, void *) =
  147. {
  148. [__GT_FILE] = try_file,
  149. [__GT_DIR] = try_dir,
  150. [__GT_NOCREATE] = try_nocreate
  151. };
  152. return try_tempname_len (tmpl, suffixlen, &flags, tryfunc[kind],
  153. x_suffix_len);
  154. }
  155. #ifdef _LIBC
  156. static
  157. #endif
  158. int
  159. try_tempname_len (char *tmpl, int suffixlen, void *args,
  160. int (*tryfunc) (char *, void *), size_t x_suffix_len)
  161. {
  162. size_t len;
  163. char *XXXXXX;
  164. unsigned int count;
  165. int fd = -1;
  166. int save_errno = errno;
  167. /* A lower bound on the number of temporary files to attempt to
  168. generate. The maximum total number of temporary file names that
  169. can exist for a given template is 62**6. It should never be
  170. necessary to try all of these combinations. Instead if a reasonable
  171. number of names is tried (we define reasonable as 62**3) fail to
  172. give the system administrator the chance to remove the problems.
  173. This value requires that X_SUFFIX_LEN be at least 3. */
  174. #define ATTEMPTS_MIN (62 * 62 * 62)
  175. /* The number of times to attempt to generate a temporary file. To
  176. conform to POSIX, this must be no smaller than TMP_MAX. */
  177. #if ATTEMPTS_MIN < TMP_MAX
  178. unsigned int attempts = TMP_MAX;
  179. #else
  180. unsigned int attempts = ATTEMPTS_MIN;
  181. #endif
  182. /* A random variable. */
  183. random_value v = 0;
  184. /* A value derived from the random variable, and how many random
  185. base-62 digits can currently be extracted from VDIGBUF. */
  186. random_value vdigbuf;
  187. int vdigits = 0;
  188. /* Least biased value for V. If V is less than this, V can generate
  189. BASE_62_DIGITS unbiased digits. Otherwise the digits are biased. */
  190. random_value const biased_min
  191. = RANDOM_VALUE_MAX - RANDOM_VALUE_MAX % BASE_62_POWER;
  192. len = strlen (tmpl);
  193. if (len < x_suffix_len + suffixlen
  194. || strspn (&tmpl[len - x_suffix_len - suffixlen], "X") < x_suffix_len)
  195. {
  196. __set_errno (EINVAL);
  197. return -1;
  198. }
  199. /* This is where the Xs start. */
  200. XXXXXX = &tmpl[len - x_suffix_len - suffixlen];
  201. for (count = 0; count < attempts; ++count)
  202. {
  203. for (size_t i = 0; i < x_suffix_len; i++)
  204. {
  205. if (vdigits == 0)
  206. {
  207. /* Worry about bias only if the bits are high quality. */
  208. while (random_bits (&v, v) && biased_min <= v)
  209. continue;
  210. vdigbuf = v;
  211. vdigits = BASE_62_DIGITS;
  212. }
  213. XXXXXX[i] = letters[vdigbuf % 62];
  214. vdigbuf /= 62;
  215. vdigits--;
  216. }
  217. fd = tryfunc (tmpl, args);
  218. if (fd >= 0)
  219. {
  220. __set_errno (save_errno);
  221. return fd;
  222. }
  223. else if (errno != EEXIST)
  224. return -1;
  225. }
  226. /* We got out of the loop because we ran out of combinations to try. */
  227. __set_errno (EEXIST);
  228. return -1;
  229. }
  230. int
  231. __gen_tempname (char *tmpl, int suffixlen, int flags, int kind)
  232. {
  233. return gen_tempname_len (tmpl, suffixlen, flags, kind, 6);
  234. }
  235. #if !_LIBC
  236. int
  237. try_tempname (char *tmpl, int suffixlen, void *args,
  238. int (*tryfunc) (char *, void *))
  239. {
  240. return try_tempname_len (tmpl, suffixlen, args, tryfunc, 6);
  241. }
  242. #endif