1 @node Cryptographic Functions, Debugging Support, System Configuration, Top
2 @chapter Cryptographic Functions
3 @c %MENU% Passphrase storage and strongly unpredictable bytes.
5 @Theglibc{} includes only a few special-purpose cryptographic
6 functions: one-way hash functions for passphrase storage, and access
7 to a cryptographic randomness source, if one is provided by the
8 operating system. Programs that need general-purpose cryptography
9 should use a dedicated cryptography library, such as
10 @uref{https://www.gnu.org/software/libgcrypt/,,libgcrypt}.
12 Many countries place legal restrictions on the import, export,
13 possession, or use of cryptographic software. We deplore these
14 restrictions, but we must still warn you that @theglibc{} may be
15 subject to them, even if you do not use the functions in this chapter
16 yourself. The restrictions vary from place to place and are changed
17 often, so we cannot give any more specific advice than this warning.
20 * Passphrase Storage:: One-way hashing for passphrases.
21 * Unpredictable Bytes:: Randomness for cryptographic purposes.
24 @node Passphrase Storage
25 @section Passphrase Storage
26 @cindex passphrase hashing
27 @cindex one-way hashing
28 @cindex hashing, passphrase
30 Sometimes it is necessary to be sure that a user is authorized
31 to use some service a machine provides---for instance, to log in as a
32 particular user id (@pxref{Users and Groups}). One traditional way of
33 doing this is for each user to choose a secret @dfn{passphrase}; then, the
34 system can ask someone claiming to be a user what the user's passphrase
35 is, and if the person gives the correct passphrase then the system can
36 grant the appropriate privileges. (Traditionally, these were called
37 ``passwords,'' but nowadays a single word is too easy to guess.)
39 Programs that handle passphrases must take special care not to reveal
40 them to anyone, no matter what. It is not enough to keep them in a
41 file that is only accessible with special privileges. The file might
42 be ``leaked'' via a bug or misconfiguration, and system administrators
43 shouldn't learn everyone's passphrase even if they have to edit that
44 file for some reason. To avoid this, passphrases should also be
45 converted into @dfn{one-way hashes}, using a @dfn{one-way function},
46 before they are stored.
48 A one-way function is easy to compute, but there is no known way to
49 compute its inverse. This means the system can easily check
50 passphrases, by hashing them and comparing the result with the stored
51 hash. But an attacker who discovers someone's passphrase hash can
52 only discover the passphrase it corresponds to by guessing and
53 checking. The one-way functions are designed to make this process
54 impractically slow, for all but the most obvious guesses. (Do not use
55 a word from the dictionary as your passphrase.)
57 @Theglibc{} provides an interface to four one-way functions, based on
58 the SHA-2-512, SHA-2-256, MD5, and DES cryptographic primitives. New
59 passphrases should be hashed with either of the SHA-based functions.
60 The others are too weak for newly set passphrases, but we continue to
61 support them for verifying old passphrases. The DES-based hash is
62 especially weak, because it ignores all but the first eight characters
65 @deftypefun {char *} crypt (const char *@var{phrase}, const char *@var{salt})
66 @standards{X/Open, unistd.h}
67 @standards{GNU, crypt.h}
68 @safety{@prelim{}@mtunsafe{@mtasurace{:crypt}}@asunsafe{@asucorrupt{} @asulock{} @ascuheap{} @ascudlopen{}}@acunsafe{@aculock{} @acsmem{}}}
69 @c Besides the obvious problem of returning a pointer into static
70 @c storage, the DES initializer takes an internal lock with the usual
71 @c set of problems for AS- and AC-Safety.
72 @c The NSS implementations may leak file descriptors if cancelled.
73 @c The MD5, SHA256 and SHA512 implementations will malloc on long keys,
74 @c and NSS relies on dlopening, which brings about another can of worms.
76 The function @code{crypt} converts a passphrase string, @var{phrase},
77 into a one-way hash suitable for storage in the user database. The
78 string that it returns will consist entirely of printable ASCII
79 characters. It will not contain whitespace, nor any of the characters
80 @samp{:}, @samp{;}, @samp{*}, @samp{!}, or @samp{\}.
82 The @var{salt} parameter controls which one-way function is used, and
83 it also ensures that the output of the one-way function is different
84 for every user, even if they have the same passphrase. This makes it
85 harder to guess passphrases from a large user database. Without salt,
86 the attacker could make a guess, run @code{crypt} on it once, and
87 compare the result with all the hashes. Salt forces the attacker to
88 make separate calls to @code{crypt} for each user.
90 To verify a passphrase, pass the previously hashed passphrase as the
91 @var{salt}. To hash a new passphrase for storage, set @var{salt} to a
92 string consisting of a prefix plus a sequence of randomly chosen
93 characters, according to this table:
95 @multitable @columnfractions .2 .1 .3
96 @headitem One-way function @tab Prefix @tab Random sequence
111 In all cases, the random characters should be chosen from the alphabet
114 With all of the hash functions @emph{except} DES, @var{phrase} can be
115 arbitrarily long, and all eight bits of each byte are significant.
116 With DES, only the first eight characters of @var{phrase} affect the
117 output, and the eighth bit of each byte is also ignored.
119 @code{crypt} can fail. Some implementations return @code{NULL} on
120 failure, and others return an @emph{invalid} hashed passphrase, which
121 will begin with a @samp{*} and will not be the same as @var{salt}. In
122 either case, @code{errno} will be set to indicate the problem. Some
123 of the possible error codes are:
127 @var{salt} is invalid; neither a previously hashed passphrase, nor a
128 well-formed new salt for any of the supported hash functions.
131 The system configuration forbids use of the hash function selected by
135 Failed to allocate internal scratch storage.
139 Hashing passphrases is not supported at all, or the hash function
140 selected by @var{salt} is not supported. @Theglibc{} does not use
141 these error codes, but they may be encountered on other operating
145 @code{crypt} uses static storage for both internal scratchwork and the
146 string it returns. It is not safe to call @code{crypt} from multiple
147 threads simultaneously, and the string it returns will be overwritten
148 by any subsequent call to @code{crypt}.
150 @code{crypt} is specified in the X/Open Portability Guide and is
151 present on nearly all historical Unix systems. However, the XPG does
152 not specify any one-way functions.
154 @code{crypt} is declared in @file{unistd.h}. @Theglibc{} also
155 declares this function in @file{crypt.h}.
158 @deftypefun {char *} crypt_r (const char *@var{phrase}, const char *@var{salt}, struct crypt_data *@var{data})
159 @standards{GNU, crypt.h}
160 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{} @asulock{} @ascuheap{} @ascudlopen{}}@acunsafe{@aculock{} @acsmem{}}}
161 @tindex struct crypt_data
162 @c Compared with crypt, this function fixes the @mtasurace:crypt
163 @c problem, but nothing else.
165 The function @code{crypt_r} is a thread-safe version of @code{crypt}.
166 Instead of static storage, it uses the memory pointed to by its
167 @var{data} argument for both scratchwork and the string it returns.
168 It can safely be used from multiple threads, as long as different
169 @var{data} objects are used in each thread. The string it returns
170 will still be overwritten by another call with the same @var{data}.
172 @var{data} must point to a @code{struct crypt_data} object allocated
173 by the caller. All of the fields of @code{struct crypt_data} are
174 private, but before one of these objects is used for the first time,
175 it must be initialized to all zeroes, using @code{memset} or similar.
176 After that, it can be reused for many calls to @code{crypt_r} without
177 erasing it again. @code{struct crypt_data} is very large, so it is
178 best to allocate it with @code{malloc} rather than as a local
179 variable. @xref{Memory Allocation}.
181 @code{crypt_r} is a GNU extension. It is declared in @file{crypt.h},
182 as is @code{struct crypt_data}.
185 The following program shows how to use @code{crypt} the first time a
186 passphrase is entered. It uses @code{getentropy} to make the salt as
187 unpredictable as possible; @pxref{Unpredictable Bytes}.
190 @include genpass.c.texi
193 The next program demonstrates how to verify a passphrase. It checks a
194 hash hardcoded into the program, because looking up real users' hashed
195 passphrases may require special privileges (@pxref{User Database}).
196 It also shows that different one-way functions produce different
197 hashes for the same passphrase.
200 @include testpass.c.texi
203 @node Unpredictable Bytes
204 @section Generating Unpredictable Bytes
205 @cindex randomness source
206 @cindex random numbers, cryptographic
207 @cindex pseudo-random numbers, cryptographic
208 @cindex cryptographic random number generator
209 @cindex deterministic random bit generator
214 Cryptographic applications often need some random data that will be as
215 difficult as possible for a hostile eavesdropper to guess. For
216 instance, encryption keys should be chosen at random, and the ``salt''
217 strings used by @code{crypt} (@pxref{Passphrase Storage}) should also
220 Some pseudo-random number generators do not provide unpredictable-enough
221 output for cryptographic applications; @pxref{Pseudo-Random Numbers}.
222 Such applications need to use a @dfn{cryptographic random number
223 generator} (CRNG), also sometimes called a @dfn{cryptographically strong
224 pseudo-random number generator} (CSPRNG) or @dfn{deterministic random
225 bit generator} (DRBG).
227 Currently, @theglibc{} does not provide a cryptographic random number
228 generator, but it does provide functions that read random data from a
229 @dfn{randomness source} supplied by the operating system. The
230 randomness source is a CRNG at heart, but it also continually
231 ``re-seeds'' itself from physical sources of randomness, such as
232 electronic noise and clock jitter. This means applications do not need
233 to do anything to ensure that the random numbers it produces are
234 different on each run.
236 The catch, however, is that these functions will only produce
237 relatively short random strings in any one call. Often this is not a
238 problem, but applications that need more than a few kilobytes of
239 cryptographically strong random data should call these functions once
240 and use their output to seed a CRNG.
242 Most applications should use @code{getentropy}. The @code{getrandom}
243 function is intended for low-level applications which need additional
244 control over blocking behavior.
246 @deftypefun int getentropy (void *@var{buffer}, size_t @var{length})
247 @standards{GNU, sys/random.h}
248 @safety{@mtsafe{}@assafe{}@acsafe{}}
250 This function writes exactly @var{length} bytes of random data to the
251 array starting at @var{buffer}. @var{length} can be no more than 256.
252 On success, it returns zero. On failure, it returns @math{-1}, and
253 @code{errno} is set to indicate the problem. Some of the possible
254 errors are listed below.
258 The operating system does not implement a randomness source, or does
259 not support this way of accessing it. (For instance, the system call
260 used by this function was added to the Linux kernel in version 3.17.)
263 The combination of @var{buffer} and @var{length} arguments specifies
264 an invalid memory range.
267 @var{length} is larger than 256, or the kernel entropy pool has
268 suffered a catastrophic failure.
271 A call to @code{getentropy} can only block when the system has just
272 booted and the randomness source has not yet been initialized.
273 However, if it does block, it cannot be interrupted by signals or
274 thread cancellation. Programs intended to run in very early stages of
275 the boot process may need to use @code{getrandom} in non-blocking mode
276 instead, and be prepared to cope with random data not being available
279 The @code{getentropy} function is declared in the header file
280 @file{sys/random.h}. It is derived from OpenBSD.
283 @deftypefun ssize_t getrandom (void *@var{buffer}, size_t @var{length}, unsigned int @var{flags})
284 @standards{GNU, sys/random.h}
285 @safety{@mtsafe{}@assafe{}@acsafe{}}
287 This function writes up to @var{length} bytes of random data to the
288 array starting at @var{buffer}. The @var{flags} argument should be
289 either zero, or the bitwise OR of some of the following flags:
293 Use the @file{/dev/random} (blocking) source instead of the
294 @file{/dev/urandom} (non-blocking) source to obtain randomness.
296 If this flag is specified, the call may block, potentially for quite
297 some time, even after the randomness source has been initialized. If it
298 is not specified, the call can only block when the system has just
299 booted and the randomness source has not yet been initialized.
302 Instead of blocking, return to the caller immediately if no data is
306 Write random data that may not be cryptographically secure.
309 Unlike @code{getentropy}, the @code{getrandom} function is a
310 cancellation point, and if it blocks, it can be interrupted by
313 On success, @code{getrandom} returns the number of bytes which have
314 been written to the buffer, which may be less than @var{length}. On
315 error, it returns @math{-1}, and @code{errno} is set to indicate the
316 problem. Some of the possible errors are:
320 The operating system does not implement a randomness source, or does
321 not support this way of accessing it. (For instance, the system call
322 used by this function was added to the Linux kernel in version 3.17.)
325 No random data was available and @code{GRND_NONBLOCK} was specified in
329 The combination of @var{buffer} and @var{length} arguments specifies
330 an invalid memory range.
333 The system call was interrupted. During the system boot process, before
334 the kernel randomness pool is initialized, this can happen even if
338 The @var{flags} argument contains an invalid combination of flags.
341 The @code{getrandom} function is declared in the header file
342 @file{sys/random.h}. It is a GNU extension.