Cryptographic Functions
***********************

Theglibc includes only a few special-purpose cryptographic functions: one-way hash functions for passphrase storage, and access to a cryptographic randomness source, if one is provided by the operating system.  Programs that need general-purpose cryptography should use a dedicated cryptography library, such as libgcrypt.

Many countries place legal restrictions on the import, export, possession, or use of cryptographic software.  We deplore these restrictions, but we must still warn you that theglibc may be subject to them, even if you do not use the functions in this chapter yourself.  The restrictions vary from place to place and are changed often, so we cannot give any more specific advice than this warning.

Passphrase Storage
==================

Sometimes it is necessary to be sure that a user is authorized to use some service a machine provides---for instance, to log in as a particular user id (see Users and Groups).  One traditional way of doing this is for each user to choose a secret passphrase; then, the system can ask someone claiming to be a user what the user's passphrase is, and if the person gives the correct passphrase then the system can grant the appropriate privileges.  (Traditionally, these were called ``passwords,'' but nowadays a single word is too easy to guess.)

Programs that handle passphrases must take special care not to reveal them to anyone, no matter what.  It is not enough to keep them in a file that is only accessible with special privileges.  The file might be ``leaked'' via a bug or misconfiguration, and system administrators shouldn't learn everyone's passphrase even if they have to edit that file for some reason.  To avoid this, passphrases should also be converted into one-way hashes, using a one-way function, before they are stored.

A one-way function is easy to compute, but there is no known way to compute its inverse.  This means the system can easily check passphrases, by hashing them and comparing the result with the stored hash.  But an attacker who discovers someone's passphrase hash can only discover the passphrase it corresponds to by guessing and checking.  The one-way functions are designed to make this process impractically slow, for all but the most obvious guesses.  (Do not use a word from the dictionary as your passphrase.)

Theglibc provides an interface to four one-way functions, based on the SHA-2-512, SHA-2-256, MD5, and DES cryptographic primitives.  New passphrases should be hashed with either of the SHA-based functions. The others are too weak for newly set passphrases, but we continue to support them for verifying old passphrases.  The DES-based hash is especially weak, because it ignores all but the first eight characters of its input.

 -- Function: char * crypt (const char *PHRASE, const char *SALT)
     X/Open, unistd.h GNU, crypt.h prelim:crypt

     The function crypt converts a passphrase string, PHRASE, into a one-way hash suitable for storage in the user database.  The string that it returns will consist entirely of printable ASCII characters.  It will not contain whitespace, nor any of the characters :, ;, *, !, or \.

     The SALT parameter controls which one-way function is used, and it also ensures that the output of the one-way function is different for every user, even if they have the same passphrase.  This makes it harder to guess passphrases from a large user database.  Without salt, the attacker could make a guess, run crypt on it once, and compare the result with all the hashes.  Salt forces the attacker to make separate calls to crypt for each user.

     To verify a passphrase, pass the previously hashed passphrase as the SALT.  To hash a new passphrase for storage, set SALT to a string consisting of a prefix plus a sequence of randomly chosen characters, according to this table:

     One-way function   Prefix   Random sequence
     SHA-2-512
     $6$
     16 characters
     SHA-2-256
     $5$
     16 characters
     MD5
     $1$
     8 characters
     DES

     2 characters

     In all cases, the random characters should be chosen from the alphabet ./0-9A-Za-z.

     With all of the hash functions except DES, PHRASE can be arbitrarily long, and all eight bits of each byte are significant. With DES, only the first eight characters of PHRASE affect the output, and the eighth bit of each byte is also ignored.

     crypt can fail.  Some implementations return NULL on failure, and others return an invalid hashed passphrase, which will begin with a * and will not be the same as SALT.  In either case, errno will be set to indicate the problem.  Some of the possible error codes are:

     EINVAL
          SALT is invalid; neither a previously hashed passphrase, nor a well-formed new salt for any of the supported hash functions.

     EPERM
          The system configuration forbids use of the hash function selected by SALT.

     ENOMEM
          Failed to allocate internal scratch storage.

     ENOSYS
     EOPNOTSUPP
          Hashing passphrases is not supported at all, or the hash function selected by SALT is not supported.  Theglibc does not use these error codes, but they may be encountered on other operating systems.

     crypt uses static storage for both internal scratchwork and the string it returns.  It is not safe to call crypt from multiple threads simultaneously, and the string it returns will be overwritten by any subsequent call to crypt.

     crypt is specified in the X/Open Portability Guide and is present on nearly all historical Unix systems.  However, the XPG does not specify any one-way functions.

     crypt is declared in unistd.h.  Theglibc also declares this function in crypt.h.

 -- Function: char * crypt_r (const char *PHRASE, const char *SALT, struct crypt_data *DATA)
     GNU, crypt.h

     The function crypt_r is a thread-safe version of crypt. Instead of static storage, it uses the memory pointed to by its DATA argument for both scratchwork and the string it returns. It can safely be used from multiple threads, as long as different DATA objects are used in each thread.  The string it returns will still be overwritten by another call with the same DATA.

     DATA must point to a struct crypt_data object allocated by the caller.  All of the fields of struct crypt_data are private, but before one of these objects is used for the first time, it must be initialized to all zeroes, using memset or similar. After that, it can be reused for many calls to crypt_r without erasing it again.  struct crypt_data is very large, so it is best to allocate it with malloc rather than as a local variable.  See Memory Allocation.

     crypt_r is a GNU extension.  It is declared in crypt.h, as is struct crypt_data.

The following program shows how to use crypt the first time a passphrase is entered.  It uses getentropy to make the salt as unpredictable as possible; see Unpredictable Bytes.

          [file genpass.c.texi not included]

The next program demonstrates how to verify a passphrase.  It checks a hash hardcoded into the program, because looking up real users' hashed passphrases may require special privileges (see User Database). It also shows that different one-way functions produce different hashes for the same passphrase.

          [file testpass.c.texi not included]

Generating Unpredictable Bytes
==============================

Cryptographic applications often need some random data that will be as difficult as possible for a hostile eavesdropper to guess.  For instance, encryption keys should be chosen at random, and the ``salt'' strings used by crypt (see Passphrase Storage) should also be chosen at random.

Some pseudo-random number generators do not provide unpredictable-enough output for cryptographic applications; see Pseudo-Random Numbers. Such applications need to use a cryptographic random number generator (CRNG), also sometimes called a cryptographically strong pseudo-random number generator (CSPRNG) or deterministic random bit generator (DRBG).

Currently, theglibc does not provide a cryptographic random number generator, but it does provide functions that read random data from a randomness source supplied by the operating system.  The randomness source is a CRNG at heart, but it also continually ``re-seeds'' itself from physical sources of randomness, such as electronic noise and clock jitter.  This means applications do not need to do anything to ensure that the random numbers it produces are different on each run.

The catch, however, is that these functions will only produce relatively short random strings in any one call.  Often this is not a problem, but applications that need more than a few kilobytes of cryptographically strong random data should call these functions once and use their output to seed a CRNG.

Most applications should use getentropy.  The getrandom function is intended for low-level applications which need additional control over blocking behavior.

 -- Function: int getentropy (void *BUFFER, size_t LENGTH)
     GNU, sys/random.h

     This function writes exactly LENGTH bytes of random data to the array starting at BUFFER.  LENGTH can be no more than 256. On success, it returns zero.  On failure, it returns -1, and errno is set to indicate the problem.  Some of the possible errors are listed below.

     ENOSYS
          The operating system does not implement a randomness source, or does not support this way of accessing it.  (For instance, the system call used by this function was added to the Linux kernel in version 3.17.)

     EFAULT
          The combination of BUFFER and LENGTH arguments specifies an invalid memory range.

     EIO
          LENGTH is larger than 256, or the kernel entropy pool has suffered a catastrophic failure.

     A call to getentropy can only block when the system has just booted and the randomness source has not yet been initialized. However, if it does block, it cannot be interrupted by signals or thread cancellation.  Programs intended to run in very early stages of the boot process may need to use getrandom in non-blocking mode instead, and be prepared to cope with random data not being available at all.

     The getentropy function is declared in the header file sys/random.h.  It is derived from OpenBSD.

 -- Function: ssize_t getrandom (void *BUFFER, size_t LENGTH, unsigned int FLAGS)
     GNU, sys/random.h

     This function writes up to LENGTH bytes of random data to the array starting at BUFFER.  The FLAGS argument should be either zero, or the bitwise OR of some of the following flags:

     GRND_RANDOM
          Use the /dev/random (blocking) source instead of the /dev/urandom (non-blocking) source to obtain randomness.

          If this flag is specified, the call may block, potentially for quite some time, even after the randomness source has been initialized.  If it is not specified, the call can only block when the system has just booted and the randomness source has not yet been initialized.

     GRND_NONBLOCK
          Instead of blocking, return to the caller immediately if no data is available.

     GRND_INSECURE
          Write random data that may not be cryptographically secure.

     Unlike getentropy, the getrandom function is a cancellation point, and if it blocks, it can be interrupted by signals.

     On success, getrandom returns the number of bytes which have been written to the buffer, which may be less than LENGTH.  On error, it returns -1, and errno is set to indicate the problem.  Some of the possible errors are:

     ENOSYS
          The operating system does not implement a randomness source, or does not support this way of accessing it.  (For instance, the system call used by this function was added to the Linux kernel in version 3.17.)

     EAGAIN
          No random data was available and GRND_NONBLOCK was specified in FLAGS.

     EFAULT
          The combination of BUFFER and LENGTH arguments specifies an invalid memory range.

     EINTR
          The system call was interrupted.  During the system boot process, before the kernel randomness pool is initialized, this can happen even if FLAGS is zero.

     EINVAL
          The FLAGS argument contains an invalid combination of flags.

     The getrandom function is declared in the header file sys/random.h.  It is a GNU extension.