]> git.ipfire.org Git - thirdparty/glibc.git/blob - manual/crypt.texi
C-SKY: add elf header definition for elfutils
[thirdparty/glibc.git] / manual / crypt.texi
1 @node Cryptographic Functions, Debugging Support, System Configuration, Top
2 @chapter Cryptographic Functions
3 @c %MENU% Passphrase storage and strongly unpredictable bytes.
4
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}.
11
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.
18
19 @menu
20 * Passphrase Storage:: One-way hashing for passphrases.
21 * Unpredictable Bytes:: Randomness for cryptographic purposes.
22 @end menu
23
24 @node Passphrase Storage
25 @section Passphrase Storage
26 @cindex passphrase hashing
27 @cindex one-way hashing
28 @cindex hashing, passphrase
29
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.)
38
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.
47
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.)
56
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
63 of its input.
64
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.
75
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{\}.
81
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.
89
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:
94
95 @multitable @columnfractions .2 .1 .3
96 @headitem One-way function @tab Prefix @tab Random sequence
97 @item SHA-2-512
98 @tab @samp{$6$}
99 @tab 16 characters
100 @item SHA-2-256
101 @tab @samp{$5$}
102 @tab 16 characters
103 @item MD5
104 @tab @samp{$1$}
105 @tab 8 characters
106 @item DES
107 @tab @samp{}
108 @tab 2 characters
109 @end multitable
110
111 In all cases, the random characters should be chosen from the alphabet
112 @code{./0-9A-Za-z}.
113
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.
118
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:
124
125 @table @code
126 @item EINVAL
127 @var{salt} is invalid; neither a previously hashed passphrase, nor a
128 well-formed new salt for any of the supported hash functions.
129
130 @item EPERM
131 The system configuration forbids use of the hash function selected by
132 @var{salt}.
133
134 @item ENOMEM
135 Failed to allocate internal scratch storage.
136
137 @item ENOSYS
138 @itemx EOPNOTSUPP
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
142 systems.
143 @end table
144
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}.
149
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.
153
154 @code{crypt} is declared in @file{unistd.h}. @Theglibc{} also
155 declares this function in @file{crypt.h}.
156 @end deftypefun
157
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.
164
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}.
171
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}.
180
181 @code{crypt_r} is a GNU extension. It is declared in @file{crypt.h},
182 as is @code{struct crypt_data}.
183 @end deftypefun
184
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}.
188
189 @smallexample
190 @include genpass.c.texi
191 @end smallexample
192
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.
198
199 @smallexample
200 @include testpass.c.texi
201 @end smallexample
202
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
210 @cindex CRNG
211 @cindex CSPRNG
212 @cindex DRBG
213
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
218 be chosen at random.
219
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).
226
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.
235
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.
241
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.
245
246 @deftypefun int getentropy (void *@var{buffer}, size_t @var{length})
247 @standards{GNU, sys/random.h}
248 @safety{@mtsafe{}@assafe{}@acsafe{}}
249
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.
255
256 @table @code
257 @item ENOSYS
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.)
261
262 @item EFAULT
263 The combination of @var{buffer} and @var{length} arguments specifies
264 an invalid memory range.
265
266 @item EIO
267 @var{length} is larger than 256, or the kernel entropy pool has
268 suffered a catastrophic failure.
269 @end table
270
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
277 at all.
278
279 The @code{getentropy} function is declared in the header file
280 @file{sys/random.h}. It is derived from OpenBSD.
281 @end deftypefun
282
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{}}
286
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:
290
291 @table @code
292 @item GRND_RANDOM
293 Use the @file{/dev/random} (blocking) source instead of the
294 @file{/dev/urandom} (non-blocking) source to obtain randomness.
295
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.
300
301 @item GRND_NONBLOCK
302 Instead of blocking, return to the caller immediately if no data is
303 available.
304 @end table
305
306 Unlike @code{getentropy}, the @code{getrandom} function is a
307 cancellation point, and if it blocks, it can be interrupted by
308 signals.
309
310 On success, @code{getrandom} returns the number of bytes which have
311 been written to the buffer, which may be less than @var{length}. On
312 error, it returns @math{-1}, and @code{errno} is set to indicate the
313 problem. Some of the possible errors are:
314
315 @table @code
316 @item ENOSYS
317 The operating system does not implement a randomness source, or does
318 not support this way of accessing it. (For instance, the system call
319 used by this function was added to the Linux kernel in version 3.17.)
320
321 @item EAGAIN
322 No random data was available and @code{GRND_NONBLOCK} was specified in
323 @var{flags}.
324
325 @item EFAULT
326 The combination of @var{buffer} and @var{length} arguments specifies
327 an invalid memory range.
328
329 @item EINTR
330 The system call was interrupted. During the system boot process, before
331 the kernel randomness pool is initialized, this can happen even if
332 @var{flags} is zero.
333
334 @item EINVAL
335 The @var{flags} argument contains an invalid combination of flags.
336 @end table
337
338 The @code{getrandom} function is declared in the header file
339 @file{sys/random.h}. It is a GNU extension.
340
341 @end deftypefun