1  /* Portability glue for libcrypt.
       2  
       3     Copyright 2007-2017 Thorsten Kukuk and Zack Weinberg
       4     Copyright 2018-2019 Björn Esser
       5  
       6     This library is free software; you can redistribute it and/or
       7     modify it under the terms of the GNU Lesser General Public License
       8     as published by the Free Software Foundation; either version 2.1 of
       9     the License, or (at your option) any later version.
      10  
      11     This library is distributed in the hope that it will be useful,
      12     but WITHOUT ANY WARRANTY; without even the implied warranty of
      13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      14     GNU Lesser General Public License for more details.
      15  
      16     You should have received a copy of the GNU Lesser General Public
      17     License along with this library; if not, see
      18     <https://www.gnu.org/licenses/>.  */
      19  
      20  #ifndef _CRYPT_PORT_H
      21  #define _CRYPT_PORT_H 1
      22  
      23  #ifndef HAVE_CONFIG_H
      24  #error "Run configure before compiling; see INSTALL for instructions"
      25  #endif
      26  
      27  #include "config.h"
      28  
      29  #undef NDEBUG
      30  #include <assert.h>
      31  
      32  #include <stdbool.h>
      33  #include <stddef.h>
      34  #include <stdint.h>
      35  #include <string.h>
      36  #include <limits.h>
      37  #ifdef HAVE_SYS_TYPES_H
      38  #include <sys/types.h>
      39  #endif
      40  #ifdef HAVE_SYS_CDEFS_H
      41  #include <sys/cdefs.h>
      42  #endif
      43  #ifdef HAVE_ENDIAN_H
      44  #include <endian.h>
      45  #endif
      46  #ifdef HAVE_SYS_ENDIAN_H
      47  #include <sys/endian.h>
      48  #endif
      49  #ifdef HAVE_SYS_PARAM_H
      50  #include <sys/param.h>
      51  #endif
      52  
      53  /* unistd.h may contain declarations of crypt, crypt_r, crypt_data,
      54     encrypt, and setkey; if present, they may be incompatible with our
      55     declarations.  Rename them out of the way with macros.  This needs
      56     to be done before we include crypt-symbol-vers.h, which defines
      57     macros with the same names for symbol-versioning purposes.  */
      58  #ifdef HAVE_UNISTD_H
      59  #define crypt unistd_crypt_is_incompatible
      60  #define crypt_r unistd_crypt_r_is_incompatible
      61  #define crypt_data unistd_crypt_data_is_incompatible
      62  #define encrypt unistd_encrypt_is_incompatible
      63  #define setkey unistd_setkey_is_incompatible
      64  #include <unistd.h>
      65  #undef crypt
      66  #undef crypt_r
      67  #undef crypt_data
      68  #undef encrypt
      69  #undef setkey
      70  #endif
      71  
      72  #ifndef HAVE_SYS_CDEFS_THROW
      73  #define __THROW /* nothing */
      74  #endif
      75  
      76  /* Suppression of unused-argument warnings.  */
      77  #if defined __GNUC__ && __GNUC__ >= 3
      78  # define ARG_UNUSED(x) x __attribute__ ((__unused__))
      79  #else
      80  # define ARG_UNUSED(x) x
      81  #endif
      82  
      83  /* Functions that should not be inlined.  */
      84  #if defined __GNUC__ && __GNUC__ >= 3
      85  # define NO_INLINE __attribute__ ((__noinline__))
      86  #else
      87  # error "Don't know how to prevent function inlining"
      88  #endif
      89  
      90  /* C99 Static array indices in function parameter declarations.  Syntax
      91     such as:  void bar(int myArray[static 10]);  is allowed in C99, but
      92     not all compiler support it properly.  Define MIN_SIZE appropriately
      93     so headers using it can be compiled using any compiler.
      94     Use like this:  void bar(int myArray[MIN_SIZE(10)]);  */
      95  #if (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L) && \
      96      ((defined __GNUC__ && __GNUC__ > 4) || defined __clang__)
      97  #define MIN_SIZE(x) static (x)
      98  #else
      99  #define MIN_SIZE(x) (x)
     100  #endif
     101  
     102  /* Detect system endianness.  */
     103  #if ENDIANNESS_IS_BIG
     104  # define XCRYPT_USE_BIGENDIAN 1
     105  #elif ENDIANNESS_IS_LITTLE
     106  # define XCRYPT_USE_BIGENDIAN 0
     107  #elif ENDIANNESS_IS_PDP
     108  # error "Byte-order sensitive code in libxcrypt does not support PDP-endianness"
     109  #else
     110  # error "Unable to determine byte ordering"
     111  #endif
     112  
     113  /* static_assert shim.  */
     114  #ifdef HAVE_STATIC_ASSERT_IN_ASSERT_H
     115  /* nothing to do */
     116  #elif defined HAVE__STATIC_ASSERT
     117  # define static_assert(expr, message) _Static_assert(expr, message)
     118  #else
     119  /* This fallback is known to work with most C99-compliant compilers.
     120     See verify.h in gnulib for extensive discussion.  */
     121  # define static_assert(expr, message) \
     122    extern int (*xcrypt_static_assert_fn (void)) \
     123    [!!sizeof (struct { int xcrypt_error_if_negative: (expr) ? 2 : -1; })]
     124  #endif
     125  
     126  /* max_align_t shim.  In the absence of official word from the
     127     compiler, we guess that one of long double, uintmax_t, void *, and
     128     void (*)(void) will have the maximum alignment.  This is probably
     129     not true in the presence of vector types, but we currently don't
     130     use vector types, and hopefully any compiler with extra-aligned
     131     vector types will provide max_align_t.  */
     132  #ifndef HAVE_MAX_ALIGN_T
     133  typedef union
     134  {
     135    long double ld;
     136    uintmax_t ui;
     137    void *vp;
     138    void (*vpf)(void);
     139  } max_align_t;
     140  #endif
     141  
     142  /* Several files expect the traditional definitions of these macros.
     143     (We don't trust sys/param.h to define them correctly.)  */
     144  #undef MIN
     145  #define MIN(a, b) (((a) < (b)) ? (a) : (b))
     146  #undef MAX
     147  #define MAX(a, b) (((a) > (b)) ? (a) : (b))
     148  
     149  /* Size of a declared array.  */
     150  #define ARRAY_SIZE(a_)  (sizeof (a_) / sizeof ((a_)[0]))
     151  
     152  /* Not all systems provide a library function usable for erasing
     153     memory containing sensitive data, and among those that do, there is
     154     no standard for what it should be called.  (Plain memset and bzero
     155     are not usable for this purpose, because the compiler may remove
     156     calls to these functions if it thinks the stores are dead.)
     157  
     158     All code in libxcrypt is standardized on explicit_bzero() as the
     159     name for the function that does this job; here, we map that name
     160     to whatever platform routine is available, or to our own fallback
     161     implementation.  */
     162  #define INCLUDE_explicit_bzero 0
     163  #if defined HAVE_EXPLICIT_BZERO
     164  /* nothing to do */
     165  #elif defined HAVE_EXPLICIT_MEMSET
     166  #define explicit_bzero(s, len) explicit_memset(s, 0, len)
     167  #elif defined HAVE_MEMSET_S
     168  #define explicit_bzero(s, len) memset_s(s, len, 0, len)
     169  #else
     170  /* activate our fallback implementation */
     171  #undef INCLUDE_explicit_bzero
     172  #define INCLUDE_explicit_bzero 1
     173  #define explicit_bzero _crypt_explicit_bzero
     174  extern void explicit_bzero (void *, size_t);
     175  #endif
     176  
     177  /* Provide a safe way to copy strings with the guarantee src,
     178     including its terminating '\0', will fit d_size bytes.
     179     The trailing bytes of d_size will be filled with '\0'.
     180     dst and src must not be NULL.  Returns strlen (src).
     181     Note: dst and src are declared as void * instead of char *
     182     because some of the hashing methods want to call this
     183     function with unsigned char * arguments.  */
     184  #define strcpy_or_abort _crypt_strcpy_or_abort
     185  extern size_t strcpy_or_abort (void *dst, size_t d_size, const void *src);
     186  
     187  
     188  /* Define ALIASNAME as a strong alias for NAME.  */
     189  #define strong_alias(name, aliasname) _strong_alias(name, aliasname)
     190  
     191  /* Darwin (Mach-O) doesn't support alias attributes or symbol versioning.
     192     It does, however, support symbol aliasing at the object file level.  */
     193  #ifdef __APPLE__
     194  
     195  # define _strong_alias(name, aliasname)         \
     196    __asm__(".globl _" #aliasname);               \
     197    __asm__(".set _" #aliasname ", _" #name);     \
     198    extern __typeof(name) aliasname __THROW
     199  
     200  # define symver_set(extstr, intname, version, mode)     \
     201    __asm__(".globl _" extstr);                           \
     202    __asm__(".set _" extstr ", _" #intname)
     203  
     204  #elif defined _WIN32
     205  
     206  /* .symver is only supported for ELF format, Windows uses COFF/PE */
     207  # define symver_set(extstr, intname, version, mode)
     208  
     209  #elif defined __GNUC__ && __GNUC__ >= 3
     210  
     211  # define _strong_alias(name, aliasname) \
     212    extern __typeof (name) aliasname __THROW __attribute__ ((alias (#name)))
     213  
     214  /* Starting with GCC 10, we can use the symver attribute, which is also
     215     needed at the point we decide to enable link-time optimization.  */
     216  # if defined HAVE_FUNC_ATTRIBUTE_SYMVER
     217  
     218  /* Set the symbol version for EXTNAME, which uses INTNAME as its
     219     implementation.  */
     220  # define symver_set(extstr, intname, version, mode) \
     221    extern __typeof (intname) intname __THROW \
     222      __attribute__((symver (extstr mode #version)))
     223  
     224  /* Referencing specific _compatibility_ symbols still needs inline asm.  */
     225  # define _symver_ref(extstr, intname, version) \
     226    __asm__ (".symver " #intname "," extstr "@" #version)
     227  
     228  # else
     229  
     230  /* Set the symbol version for EXTNAME, which uses INTNAME as its
     231     implementation.  */
     232  # define symver_set(extstr, intname, version, mode) \
     233    __asm__ (".symver " #intname "," extstr mode #version)
     234  
     235  # endif
     236  
     237  #else
     238  # error "Don't know how to do symbol versioning with this compiler"
     239  #endif
     240  
     241  /* A construct with the same syntactic role as the expansion of symver_set,
     242     but which does nothing.  */
     243  #define symver_nop() __asm__ ("")
     244  
     245  /* The macros for versioned symbols work differently in this library
     246     than they do in glibc.  They are mostly auto-generated
     247     (see build-aux/scripts/gen-crypt-symbol-vers-h)
     248     and we currently don't support compatibility symbols that need a different
     249     definition from the default version.
     250  
     251     Each definition of a public symbol should look like this:
     252     #if INCLUDE_foo
     253     int foo(arguments)
     254     {
     255       body
     256     }
     257     SYMVER_foo;
     258     #endif
     259  
     260     and the macros take care of the rest.  Normally, to call a public
     261     symbol you do nothing special.  The macro symver_ref() forces
     262     all uses of a particular name (in the file where it's used) to refer
     263     to a particular version of a public symbol, e.g. for testing.  */
     264  
     265  #ifdef IN_LIBCRYPT
     266  
     267  #include "crypt-symbol-vers.h"
     268  
     269  #ifdef PIC
     270  
     271  #define symver_compat(n, extstr, extname, intname, version) \
     272    strong_alias (intname, extname ## __ ## n); \
     273    symver_set (extstr, extname ## __ ## n, version, "@")
     274  
     275  #define symver_compat0(extstr, intname, version) \
     276    symver_set (extstr, intname, version, "@")
     277  
     278  #define symver_default(extstr, intname, version) \
     279    symver_set (extstr, intname, version, "@@")
     280  
     281  #else
     282  
     283  /* When not building the shared library, don't do any of this.  */
     284  #define symver_compat(n, extstr, extname, intname, version) symver_nop ()
     285  #define symver_compat0(extstr, intname, version) symver_nop ()
     286  #define symver_default(extstr, intname, version) symver_nop ()
     287  
     288  #endif
     289  #endif
     290  
     291  /* Tests may need to _refer_ to compatibility symbols, but should never need
     292     to _define_ them.  */
     293  #define symver_ref(extstr, intname, version) \
     294    _symver_ref(extstr, intname, version)
     295  
     296  /* Generic way for referencing specific _compatibility_ symbols.  */
     297  #ifndef _symver_ref
     298  #define _symver_ref(extstr, intname, version) \
     299    symver_set(extstr, intname, version, "@")
     300  #endif
     301  
     302  /* Define configuration macros used during compile-time by the
     303     GOST R 34.11-2012 "Streebog" hash function.  */
     304  #if XCRYPT_USE_BIGENDIAN
     305  #define __GOST3411_BIG_ENDIAN__ 1
     306  #else
     307  #define __GOST3411_LITTLE_ENDIAN__ 1
     308  #endif
     309  
     310  /* Get the set of hash algorithms to be included and some related
     311     definitions.  */
     312  #include "crypt-hashes.h"
     313  
     314  /* Rename all of the internal-but-global symbols with a _crypt_ prefix
     315     so that they do not interfere with other people's code when linking
     316     statically.  This list cannot be autogenerated, but is validated by
     317     test-symbols.sh.  */
     318  
     319  #define ascii64                  _crypt_ascii64
     320  #define get_random_bytes         _crypt_get_random_bytes
     321  #define make_failure_token       _crypt_make_failure_token
     322  
     323  #if INCLUDE_descrypt || INCLUDE_bsdicrypt || INCLUDE_bigcrypt
     324  #define des_crypt_block          _crypt_des_crypt_block
     325  #define des_set_key              _crypt_des_set_key
     326  #define des_set_salt             _crypt_des_set_salt
     327  #define comp_maskl               _crypt_comp_maskl
     328  #define comp_maskr               _crypt_comp_maskr
     329  #define fp_maskl                 _crypt_fp_maskl
     330  #define fp_maskr                 _crypt_fp_maskr
     331  #define ip_maskl                 _crypt_ip_maskl
     332  #define ip_maskr                 _crypt_ip_maskr
     333  #define key_perm_maskl           _crypt_key_perm_maskl
     334  #define key_perm_maskr           _crypt_key_perm_maskr
     335  #define m_sbox                   _crypt_m_sbox
     336  #define psbox                    _crypt_psbox
     337  #endif
     338  
     339  #if INCLUDE_nt
     340  #define MD4_Init   _crypt_MD4_Init
     341  #define MD4_Update _crypt_MD4_Update
     342  #define MD4_Final  _crypt_MD4_Final
     343  #endif
     344  
     345  #if INCLUDE_md5crypt || INCLUDE_sunmd5
     346  #define MD5_Init   _crypt_MD5_Init
     347  #define MD5_Update _crypt_MD5_Update
     348  #define MD5_Final  _crypt_MD5_Final
     349  #endif
     350  
     351  #if INCLUDE_sha1crypt
     352  #define hmac_sha1_process_data   _crypt_hmac_sha1_process_data
     353  #define sha1_finish_ctx          _crypt_sha1_finish_ctx
     354  #define sha1_init_ctx            _crypt_sha1_init_ctx
     355  #define sha1_process_bytes       _crypt_sha1_process_bytes
     356  #endif
     357  
     358  #if INCLUDE_sha512crypt
     359  #define libcperciva_SHA512_Init   _crypt_SHA512_Init
     360  #define libcperciva_SHA512_Update _crypt_SHA512_Update
     361  #define libcperciva_SHA512_Final  _crypt_SHA512_Final
     362  #define libcperciva_SHA512_Buf    _crypt_SHA512_Buf
     363  #endif
     364  
     365  #if INCLUDE_md5crypt || INCLUDE_sha256crypt || INCLUDE_sha512crypt
     366  #define gensalt_sha_rn           _crypt_gensalt_sha_rn
     367  #endif
     368  
     369  #if INCLUDE_yescrypt || INCLUDE_scrypt || INCLUDE_gost_yescrypt
     370  #define PBKDF2_SHA256            _crypt_PBKDF2_SHA256
     371  #define crypto_scrypt            _crypt_crypto_scrypt
     372  #define yescrypt                 _crypt_yescrypt
     373  #define yescrypt_decode64        _crypt_yescrypt_decode64
     374  #define yescrypt_digest_shared   _crypt_yescrypt_digest_shared
     375  #define yescrypt_encode64        _crypt_yescrypt_encode64
     376  #define yescrypt_encode_params   _crypt_yescrypt_encode_params
     377  #define yescrypt_encode_params_r _crypt_yescrypt_encode_params_r
     378  #define yescrypt_free_local      _crypt_yescrypt_free_local
     379  #define yescrypt_free_shared     _crypt_yescrypt_free_shared
     380  #define yescrypt_init_local      _crypt_yescrypt_init_local
     381  #define yescrypt_init_shared     _crypt_yescrypt_init_shared
     382  #define yescrypt_kdf             _crypt_yescrypt_kdf
     383  #define yescrypt_r               _crypt_yescrypt_r
     384  #define yescrypt_reencrypt       _crypt_yescrypt_reencrypt
     385  
     386  #define libcperciva_HMAC_SHA256_Init _crypt_HMAC_SHA256_Init
     387  #define libcperciva_HMAC_SHA256_Update _crypt_HMAC_SHA256_Update
     388  #define libcperciva_HMAC_SHA256_Final _crypt_HMAC_SHA256_Final
     389  #define libcperciva_HMAC_SHA256_Buf _crypt_HMAC_SHA256_Buf
     390  #endif
     391  
     392  #if INCLUDE_sha256crypt || INCLUDE_scrypt || INCLUDE_yescrypt || \
     393      INCLUDE_gost_yescrypt
     394  #define libcperciva_SHA256_Init  _crypt_SHA256_Init
     395  #define libcperciva_SHA256_Update _crypt_SHA256_Update
     396  #define libcperciva_SHA256_Final _crypt_SHA256_Final
     397  #define libcperciva_SHA256_Buf   _crypt_SHA256_Buf
     398  #endif
     399  
     400  #if INCLUDE_gost_yescrypt
     401  #define GOST34112012Init       _crypt_GOST34112012_Init
     402  #define GOST34112012Update     _crypt_GOST34112012_Update
     403  #define GOST34112012Final      _crypt_GOST34112012_Final
     404  #define GOST34112012Cleanup    _crypt_GOST34112012_Cleanup
     405  #define gost_hash256           _crypt_gost_hash256
     406  #define gost_hmac256           _crypt_gost_hmac256
     407  
     408  /* Those are not present, if gost-yescrypt is selected,
     409     but yescrypt is not. */
     410  #if !INCLUDE_yescrypt
     411  #define gensalt_yescrypt_rn _crypt_gensalt_yescrypt_rn
     412  extern void gensalt_yescrypt_rn
     413  (unsigned long, const uint8_t *, size_t, uint8_t *, size_t);
     414  #endif
     415  #endif
     416  
     417  /* Those are not present, if des-big is selected, but des is not. */
     418  #if INCLUDE_bigcrypt && !INCLUDE_descrypt
     419  #define gensalt_descrypt_rn _crypt_gensalt_descrypt_rn
     420  extern void gensalt_descrypt_rn
     421  (unsigned long, const uint8_t *, size_t, uint8_t *, size_t);
     422  #endif
     423  
     424  /* Those are not present, if scrypt is selected, but yescrypt is not. */
     425  #if INCLUDE_scrypt && !INCLUDE_yescrypt
     426  #define crypt_yescrypt_rn _crypt_crypt_yescrypt_rn
     427  extern void crypt_yescrypt_rn (const char *, size_t, const char *,
     428                                 size_t, uint8_t *, size_t, void *, size_t);
     429  #endif
     430  
     431  /* We need a prototype for fcrypt for some tests.  */
     432  #if ENABLE_OBSOLETE_API
     433  extern char *fcrypt (const char *key, const char *setting);
     434  #endif
     435  
     436  /* Utility functions */
     437  
     438  /* Fill BUF with BUFLEN bytes whose values are chosen uniformly at
     439     random, using a cryptographically strong RNG provided by the
     440     operating system.  BUFLEN may not be greater than 256.  Returns
     441     true if all BUFLEN bytes were successfully filled, false otherwise;
     442     sets errno when it returns false.  Can block.  */
     443  extern bool get_random_bytes (void *buf, size_t buflen);
     444  
     445  /* Generate a setting string in the format common to md5crypt,
     446     sha256crypt, and sha512crypt.  */
     447  extern void gensalt_sha_rn (char tag, size_t maxsalt, unsigned long defcount,
     448                              unsigned long mincount, unsigned long maxcount,
     449                              unsigned long count,
     450                              const uint8_t *rbytes, size_t nrbytes,
     451                              uint8_t *output, size_t output_size);
     452  
     453  /* For historical reasons, crypt and crypt_r are not expected ever
     454     to return 0, and for internal implementation reasons (see
     455     call_crypt_fn, in crypt.c), it is simpler if the individual
     456     algorithms' crypt and gensalt functions return nothing.
     457  
     458     This function generates a "failure token" in the output buffer,
     459     which is guaranteed not to be equal to any valid password hash or
     460     setting string, nor to the setting(+hash) string that was passed
     461     in; thus, a subsequent blind attempt to authenticate someone by
     462     comparing the output to a previously recorded hash string will
     463     fail, even if that string is itself one of these "failure tokens".
     464  
     465     We always call this function on the output buffer as the first
     466     step.  If the individual algorithm's crypt or gensalt function
     467     succeeds, it overwrites the failure token with real output;
     468     otherwise the token is left intact, and the API functions that
     469     _can_ return 0 on error notice it.  */
     470  extern void
     471  make_failure_token (const char *setting, char *output, int size);
     472  
     473  /* The base-64 encoding table used by most hashing methods.
     474     (bcrypt uses a slightly different encoding.)  Size 65
     475     because it's used as a C string in a few places.  */
     476  extern const unsigned char ascii64[65];
     477  
     478  /* Same table gets used with other names in various places.  */
     479  #define b64t   ((const char *) ascii64)
     480  #define itoa64 ascii64
     481  
     482  /* Calculate the size of a base64 encoding of N bytes:
     483     6 bits per output byte, rounded up.  */
     484  #define BASE64_LEN(bytes) ((((bytes) * 8) + 5) / 6)
     485  
     486  /* The "scratch" area passed to each of the individual hash functions is
     487     this big.  */
     488  #define ALG_SPECIFIC_SIZE 8192
     489  
     490  #include "crypt.h"
     491  
     492  #endif /* crypt-port.h */