repo
stringlengths 1
152
⌀ | file
stringlengths 14
221
| code
stringlengths 501
25k
| file_length
int64 501
25k
| avg_line_length
float64 20
99.5
| max_line_length
int64 21
134
| extension_type
stringclasses 2
values |
---|---|---|---|---|---|---|
openssl | openssl-master/providers/implementations/include/prov/md5_sha1.h | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_PROV_MD5_SHA1_H
# define OSSL_PROV_MD5_SHA1_H
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_MD5
# include <openssl/e_os2.h>
# include <stddef.h>
# include <openssl/md5.h>
# include <openssl/sha.h>
# define MD5_SHA1_DIGEST_LENGTH (MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH)
# define MD5_SHA1_CBLOCK MD5_CBLOCK
typedef struct md5_sha1_st {
MD5_CTX md5;
SHA_CTX sha1;
} MD5_SHA1_CTX;
int ossl_md5_sha1_init(MD5_SHA1_CTX *mctx);
int ossl_md5_sha1_update(MD5_SHA1_CTX *mctx, const void *data, size_t count);
int ossl_md5_sha1_final(unsigned char *md, MD5_SHA1_CTX *mctx);
int ossl_md5_sha1_ctrl(MD5_SHA1_CTX *mctx, int cmd, int mslen, void *ms);
# endif /* OPENSSL_NO_MD5 */
#endif /* OSSL_PROV_MD5_SHA1_H */
| 1,079 | 28.189189 | 77 | h |
openssl | openssl-master/providers/implementations/include/prov/names.h | /*
* Copyright 2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Macros for use as names and descriptions in our providers' OSSL_ALGORITHM.
*
* All the strings are formatted the same way:
*
* Our primary name[:other names][:numeric OID]
*
* 'other names' include historical OpenSSL names, NIST names, ASN.1 OBJECT
* IDENTIFIER names, and commonly known aliases.
*
* Where it matters, our primary names follow this format:
*
* ALGNAME[VERSION?][-SUBNAME[VERSION?]?][-SIZE?][-MODE?]
*
* VERSION is only present if there are multiple versions of
* an alg (MD2, MD4, MD5). It may be omitted if there is only
* one version (if a subsequent version is released in the future,
* we can always change the canonical name, and add the old name
* as an alias).
*
* SUBNAME may be present where we are combining multiple
* algorithms together, e.g. MD5-SHA1.
*
* SIZE is only present if multiple versions of an algorithm exist
* with different sizes (e.g. AES-128-CBC, AES-256-CBC)
*
* MODE is only present where applicable.
*/
/*-
* Symmetric ciphers
* -----------------
*/
#define PROV_NAMES_AES_256_ECB "AES-256-ECB:2.16.840.1.101.3.4.1.41"
#define PROV_NAMES_AES_192_ECB "AES-192-ECB:2.16.840.1.101.3.4.1.21"
#define PROV_NAMES_AES_128_ECB "AES-128-ECB:2.16.840.1.101.3.4.1.1"
#define PROV_NAMES_AES_256_CBC "AES-256-CBC:AES256:2.16.840.1.101.3.4.1.42"
#define PROV_NAMES_AES_192_CBC "AES-192-CBC:AES192:2.16.840.1.101.3.4.1.22"
#define PROV_NAMES_AES_128_CBC "AES-128-CBC:AES128:2.16.840.1.101.3.4.1.2"
#define PROV_NAMES_AES_256_CBC_CTS "AES-256-CBC-CTS"
#define PROV_NAMES_AES_192_CBC_CTS "AES-192-CBC-CTS"
#define PROV_NAMES_AES_128_CBC_CTS "AES-128-CBC-CTS"
#define PROV_NAMES_AES_256_OFB "AES-256-OFB:2.16.840.1.101.3.4.1.43"
#define PROV_NAMES_AES_192_OFB "AES-192-OFB:2.16.840.1.101.3.4.1.23"
#define PROV_NAMES_AES_128_OFB "AES-128-OFB:2.16.840.1.101.3.4.1.3"
#define PROV_NAMES_AES_256_CFB "AES-256-CFB:2.16.840.1.101.3.4.1.44"
#define PROV_NAMES_AES_192_CFB "AES-192-CFB:2.16.840.1.101.3.4.1.24"
#define PROV_NAMES_AES_128_CFB "AES-128-CFB:2.16.840.1.101.3.4.1.4"
#define PROV_NAMES_AES_256_CFB1 "AES-256-CFB1"
#define PROV_NAMES_AES_192_CFB1 "AES-192-CFB1"
#define PROV_NAMES_AES_128_CFB1 "AES-128-CFB1"
#define PROV_NAMES_AES_256_CFB8 "AES-256-CFB8"
#define PROV_NAMES_AES_192_CFB8 "AES-192-CFB8"
#define PROV_NAMES_AES_128_CFB8 "AES-128-CFB8"
#define PROV_NAMES_AES_256_CTR "AES-256-CTR"
#define PROV_NAMES_AES_192_CTR "AES-192-CTR"
#define PROV_NAMES_AES_128_CTR "AES-128-CTR"
#define PROV_NAMES_AES_256_XTS "AES-256-XTS:1.3.111.2.1619.0.1.2"
#define PROV_NAMES_AES_128_XTS "AES-128-XTS:1.3.111.2.1619.0.1.1"
#define PROV_NAMES_AES_256_GCM "AES-256-GCM:id-aes256-GCM:2.16.840.1.101.3.4.1.46"
#define PROV_NAMES_AES_192_GCM "AES-192-GCM:id-aes192-GCM:2.16.840.1.101.3.4.1.26"
#define PROV_NAMES_AES_128_GCM "AES-128-GCM:id-aes128-GCM:2.16.840.1.101.3.4.1.6"
#define PROV_NAMES_AES_256_CCM "AES-256-CCM:id-aes256-CCM:2.16.840.1.101.3.4.1.47"
#define PROV_NAMES_AES_192_CCM "AES-192-CCM:id-aes192-CCM:2.16.840.1.101.3.4.1.27"
#define PROV_NAMES_AES_128_CCM "AES-128-CCM:id-aes128-CCM:2.16.840.1.101.3.4.1.7"
#define PROV_NAMES_AES_256_WRAP "AES-256-WRAP:id-aes256-wrap:AES256-WRAP:2.16.840.1.101.3.4.1.45"
#define PROV_NAMES_AES_192_WRAP "AES-192-WRAP:id-aes192-wrap:AES192-WRAP:2.16.840.1.101.3.4.1.25"
#define PROV_NAMES_AES_128_WRAP "AES-128-WRAP:id-aes128-wrap:AES128-WRAP:2.16.840.1.101.3.4.1.5"
#define PROV_NAMES_AES_256_WRAP_PAD "AES-256-WRAP-PAD:id-aes256-wrap-pad:AES256-WRAP-PAD:2.16.840.1.101.3.4.1.48"
#define PROV_NAMES_AES_192_WRAP_PAD "AES-192-WRAP-PAD:id-aes192-wrap-pad:AES192-WRAP-PAD:2.16.840.1.101.3.4.1.28"
#define PROV_NAMES_AES_128_WRAP_PAD "AES-128-WRAP-PAD:id-aes128-wrap-pad:AES128-WRAP-PAD:2.16.840.1.101.3.4.1.8"
#define PROV_NAMES_AES_256_WRAP_INV "AES-256-WRAP-INV:AES256-WRAP-INV"
#define PROV_NAMES_AES_192_WRAP_INV "AES-192-WRAP-INV:AES192-WRAP-INV"
#define PROV_NAMES_AES_128_WRAP_INV "AES-128-WRAP-INV:AES128-WRAP-INV"
#define PROV_NAMES_AES_256_WRAP_PAD_INV "AES-256-WRAP-PAD-INV:AES256-WRAP-PAD-INV"
#define PROV_NAMES_AES_192_WRAP_PAD_INV "AES-192-WRAP-PAD-INV:AES192-WRAP-PAD-INV"
#define PROV_NAMES_AES_128_WRAP_PAD_INV "AES-128-WRAP-PAD-INV:AES128-WRAP-PAD-INV"
#define PROV_NAMES_AES_128_CBC_HMAC_SHA1 "AES-128-CBC-HMAC-SHA1"
#define PROV_NAMES_AES_256_CBC_HMAC_SHA1 "AES-256-CBC-HMAC-SHA1"
#define PROV_NAMES_AES_128_CBC_HMAC_SHA256 "AES-128-CBC-HMAC-SHA256"
#define PROV_NAMES_AES_256_CBC_HMAC_SHA256 "AES-256-CBC-HMAC-SHA256"
#define PROV_NAMES_DES_EDE3_ECB "DES-EDE3-ECB:DES-EDE3"
#define PROV_NAMES_DES_EDE3_CBC "DES-EDE3-CBC:DES3:1.2.840.113549.3.7"
#define PROV_NAMES_NULL "NULL"
#define PROV_NAMES_AES_256_OCB "AES-256-OCB"
#define PROV_NAMES_AES_192_OCB "AES-192-OCB"
#define PROV_NAMES_AES_128_OCB "AES-128-OCB"
#define PROV_NAMES_AES_128_SIV "AES-128-SIV"
#define PROV_NAMES_AES_192_SIV "AES-192-SIV"
#define PROV_NAMES_AES_256_SIV "AES-256-SIV"
#define PROV_NAMES_AES_128_GCM_SIV "AES-128-GCM-SIV"
#define PROV_NAMES_AES_192_GCM_SIV "AES-192-GCM-SIV"
#define PROV_NAMES_AES_256_GCM_SIV "AES-256-GCM-SIV"
#define PROV_NAMES_ARIA_256_GCM "ARIA-256-GCM:1.2.410.200046.1.1.36"
#define PROV_NAMES_ARIA_192_GCM "ARIA-192-GCM:1.2.410.200046.1.1.35"
#define PROV_NAMES_ARIA_128_GCM "ARIA-128-GCM:1.2.410.200046.1.1.34"
#define PROV_NAMES_ARIA_256_CCM "ARIA-256-CCM:1.2.410.200046.1.1.39"
#define PROV_NAMES_ARIA_192_CCM "ARIA-192-CCM:1.2.410.200046.1.1.38"
#define PROV_NAMES_ARIA_128_CCM "ARIA-128-CCM:1.2.410.200046.1.1.37"
#define PROV_NAMES_ARIA_256_ECB "ARIA-256-ECB:1.2.410.200046.1.1.11"
#define PROV_NAMES_ARIA_192_ECB "ARIA-192-ECB:1.2.410.200046.1.1.6"
#define PROV_NAMES_ARIA_128_ECB "ARIA-128-ECB:1.2.410.200046.1.1.1"
#define PROV_NAMES_ARIA_256_CBC "ARIA-256-CBC:ARIA256:1.2.410.200046.1.1.12"
#define PROV_NAMES_ARIA_192_CBC "ARIA-192-CBC:ARIA192:1.2.410.200046.1.1.7"
#define PROV_NAMES_ARIA_128_CBC "ARIA-128-CBC:ARIA128:1.2.410.200046.1.1.2"
#define PROV_NAMES_ARIA_256_OFB "ARIA-256-OFB:1.2.410.200046.1.1.14"
#define PROV_NAMES_ARIA_192_OFB "ARIA-192-OFB:1.2.410.200046.1.1.9"
#define PROV_NAMES_ARIA_128_OFB "ARIA-128-OFB:1.2.410.200046.1.1.4"
#define PROV_NAMES_ARIA_256_CFB "ARIA-256-CFB:1.2.410.200046.1.1.13"
#define PROV_NAMES_ARIA_192_CFB "ARIA-192-CFB:1.2.410.200046.1.1.8"
#define PROV_NAMES_ARIA_128_CFB "ARIA-128-CFB:1.2.410.200046.1.1.3"
#define PROV_NAMES_ARIA_256_CFB1 "ARIA-256-CFB1"
#define PROV_NAMES_ARIA_192_CFB1 "ARIA-192-CFB1"
#define PROV_NAMES_ARIA_128_CFB1 "ARIA-128-CFB1"
#define PROV_NAMES_ARIA_256_CFB8 "ARIA-256-CFB8"
#define PROV_NAMES_ARIA_192_CFB8 "ARIA-192-CFB8"
#define PROV_NAMES_ARIA_128_CFB8 "ARIA-128-CFB8"
#define PROV_NAMES_ARIA_256_CTR "ARIA-256-CTR:1.2.410.200046.1.1.15"
#define PROV_NAMES_ARIA_192_CTR "ARIA-192-CTR:1.2.410.200046.1.1.10"
#define PROV_NAMES_ARIA_128_CTR "ARIA-128-CTR:1.2.410.200046.1.1.5"
#define PROV_NAMES_CAMELLIA_256_ECB "CAMELLIA-256-ECB:0.3.4401.5.3.1.9.41"
#define PROV_NAMES_CAMELLIA_192_ECB "CAMELLIA-192-ECB:0.3.4401.5.3.1.9.21"
#define PROV_NAMES_CAMELLIA_128_ECB "CAMELLIA-128-ECB:0.3.4401.5.3.1.9.1"
#define PROV_NAMES_CAMELLIA_256_CBC "CAMELLIA-256-CBC:CAMELLIA256:1.2.392.200011.61.1.1.1.4"
#define PROV_NAMES_CAMELLIA_192_CBC "CAMELLIA-192-CBC:CAMELLIA192:1.2.392.200011.61.1.1.1.3"
#define PROV_NAMES_CAMELLIA_128_CBC "CAMELLIA-128-CBC:CAMELLIA128:1.2.392.200011.61.1.1.1.2"
#define PROV_NAMES_CAMELLIA_256_CBC_CTS "CAMELLIA-256-CBC-CTS"
#define PROV_NAMES_CAMELLIA_192_CBC_CTS "CAMELLIA-192-CBC-CTS"
#define PROV_NAMES_CAMELLIA_128_CBC_CTS "CAMELLIA-128-CBC-CTS"
#define PROV_NAMES_CAMELLIA_256_OFB "CAMELLIA-256-OFB:0.3.4401.5.3.1.9.43"
#define PROV_NAMES_CAMELLIA_192_OFB "CAMELLIA-192-OFB:0.3.4401.5.3.1.9.23"
#define PROV_NAMES_CAMELLIA_128_OFB "CAMELLIA-128-OFB:0.3.4401.5.3.1.9.3"
#define PROV_NAMES_CAMELLIA_256_CFB "CAMELLIA-256-CFB:0.3.4401.5.3.1.9.44"
#define PROV_NAMES_CAMELLIA_192_CFB "CAMELLIA-192-CFB:0.3.4401.5.3.1.9.24"
#define PROV_NAMES_CAMELLIA_128_CFB "CAMELLIA-128-CFB:0.3.4401.5.3.1.9.4"
#define PROV_NAMES_CAMELLIA_256_CFB1 "CAMELLIA-256-CFB1"
#define PROV_NAMES_CAMELLIA_192_CFB1 "CAMELLIA-192-CFB1"
#define PROV_NAMES_CAMELLIA_128_CFB1 "CAMELLIA-128-CFB1"
#define PROV_NAMES_CAMELLIA_256_CFB8 "CAMELLIA-256-CFB8"
#define PROV_NAMES_CAMELLIA_192_CFB8 "CAMELLIA-192-CFB8"
#define PROV_NAMES_CAMELLIA_128_CFB8 "CAMELLIA-128-CFB8"
#define PROV_NAMES_CAMELLIA_256_CTR "CAMELLIA-256-CTR:0.3.4401.5.3.1.9.49"
#define PROV_NAMES_CAMELLIA_192_CTR "CAMELLIA-192-CTR:0.3.4401.5.3.1.9.29"
#define PROV_NAMES_CAMELLIA_128_CTR "CAMELLIA-128-CTR:0.3.4401.5.3.1.9.9"
#define PROV_NAMES_DES_EDE3_OFB "DES-EDE3-OFB"
#define PROV_NAMES_DES_EDE3_CFB "DES-EDE3-CFB"
#define PROV_NAMES_DES_EDE3_CFB8 "DES-EDE3-CFB8"
#define PROV_NAMES_DES_EDE3_CFB1 "DES-EDE3-CFB1"
#define PROV_NAMES_DES3_WRAP "DES3-WRAP:id-smime-alg-CMS3DESwrap:1.2.840.113549.1.9.16.3.6"
#define PROV_NAMES_DES_EDE_ECB "DES-EDE-ECB:DES-EDE:1.3.14.3.2.17"
#define PROV_NAMES_DES_EDE_CBC "DES-EDE-CBC"
#define PROV_NAMES_DES_EDE_OFB "DES-EDE-OFB"
#define PROV_NAMES_DES_EDE_CFB "DES-EDE-CFB"
#define PROV_NAMES_SM4_ECB "SM4-ECB:1.2.156.10197.1.104.1"
#define PROV_NAMES_SM4_CBC "SM4-CBC:SM4:1.2.156.10197.1.104.2"
#define PROV_NAMES_SM4_CTR "SM4-CTR:1.2.156.10197.1.104.7"
#define PROV_NAMES_SM4_OFB "SM4-OFB:SM4-OFB128:1.2.156.10197.1.104.3"
#define PROV_NAMES_SM4_CFB "SM4-CFB:SM4-CFB128:1.2.156.10197.1.104.4"
#define PROV_NAMES_SM4_GCM "SM4-GCM:1.2.156.10197.1.104.8"
#define PROV_NAMES_SM4_CCM "SM4-CCM:1.2.156.10197.1.104.9"
#define PROV_NAMES_SM4_XTS "SM4-XTS:1.2.156.10197.1.104.10"
#define PROV_NAMES_ChaCha20 "ChaCha20"
#define PROV_NAMES_ChaCha20_Poly1305 "ChaCha20-Poly1305"
#define PROV_NAMES_CAST5_ECB "CAST5-ECB"
#define PROV_NAMES_CAST5_CBC "CAST5-CBC:CAST-CBC:CAST:1.2.840.113533.7.66.10"
#define PROV_NAMES_CAST5_OFB "CAST5-OFB"
#define PROV_NAMES_CAST5_CFB "CAST5-CFB"
#define PROV_NAMES_BF_ECB "BF-ECB"
#define PROV_NAMES_BF_CBC "BF-CBC:BF:BLOWFISH:1.3.6.1.4.1.3029.1.2"
#define PROV_NAMES_BF_OFB "BF-OFB"
#define PROV_NAMES_BF_CFB "BF-CFB"
#define PROV_NAMES_IDEA_ECB "IDEA-ECB"
#define PROV_NAMES_IDEA_CBC "IDEA-CBC:IDEA:1.3.6.1.4.1.188.7.1.1.2"
#define PROV_NAMES_IDEA_OFB "IDEA-OFB:IDEA-OFB64"
#define PROV_NAMES_IDEA_CFB "IDEA-CFB:IDEA-CFB64"
#define PROV_NAMES_SEED_ECB "SEED-ECB:1.2.410.200004.1.3"
#define PROV_NAMES_SEED_CBC "SEED-CBC:SEED:1.2.410.200004.1.4"
#define PROV_NAMES_SEED_OFB "SEED-OFB:SEED-OFB128:1.2.410.200004.1.6"
#define PROV_NAMES_SEED_CFB "SEED-CFB:SEED-CFB128:1.2.410.200004.1.5"
#define PROV_NAMES_RC2_ECB "RC2-ECB"
#define PROV_NAMES_RC2_CBC "RC2-CBC:RC2:RC2-128:1.2.840.113549.3.2"
#define PROV_NAMES_RC2_40_CBC "RC2-40-CBC:RC2-40"
#define PROV_NAMES_RC2_64_CBC "RC2-64-CBC:RC2-64"
#define PROV_NAMES_RC2_CFB "RC2-CFB"
#define PROV_NAMES_RC2_OFB "RC2-OFB"
#define PROV_NAMES_RC4 "RC4:1.2.840.113549.3.4"
#define PROV_NAMES_RC4_40 "RC4-40"
#define PROV_NAMES_RC4_HMAC_MD5 "RC4-HMAC-MD5"
#define PROV_NAMES_RC5_ECB "RC5-ECB"
#define PROV_NAMES_RC5_CBC "RC5-CBC:RC5:1.2.840.113549.3.8"
#define PROV_NAMES_RC5_OFB "RC5-OFB"
#define PROV_NAMES_RC5_CFB "RC5-CFB"
#define PROV_NAMES_DESX_CBC "DESX-CBC:DESX"
#define PROV_NAMES_DES_ECB "DES-ECB:1.3.14.3.2.6"
#define PROV_NAMES_DES_CBC "DES-CBC:DES:1.3.14.3.2.7"
#define PROV_NAMES_DES_OFB "DES-OFB:1.3.14.3.2.8"
#define PROV_NAMES_DES_CFB "DES-CFB:1.3.14.3.2.9"
#define PROV_NAMES_DES_CFB1 "DES-CFB1"
#define PROV_NAMES_DES_CFB8 "DES-CFB8"
/*-
* Digests
* -------
*/
#define PROV_NAMES_SHA1 "SHA1:SHA-1:SSL3-SHA1:1.3.14.3.2.26"
#define PROV_NAMES_SHA2_224 "SHA2-224:SHA-224:SHA224:2.16.840.1.101.3.4.2.4"
#define PROV_NAMES_SHA2_256 "SHA2-256:SHA-256:SHA256:2.16.840.1.101.3.4.2.1"
#define PROV_NAMES_SHA2_256_192 "SHA2-256/192:SHA-256/192:SHA256-192"
#define PROV_NAMES_SHA2_384 "SHA2-384:SHA-384:SHA384:2.16.840.1.101.3.4.2.2"
#define PROV_NAMES_SHA2_512 "SHA2-512:SHA-512:SHA512:2.16.840.1.101.3.4.2.3"
#define PROV_NAMES_SHA2_512_224 "SHA2-512/224:SHA-512/224:SHA512-224:2.16.840.1.101.3.4.2.5"
#define PROV_NAMES_SHA2_512_256 "SHA2-512/256:SHA-512/256:SHA512-256:2.16.840.1.101.3.4.2.6"
/* We agree with NIST here, so one name only */
#define PROV_NAMES_SHA3_224 "SHA3-224:2.16.840.1.101.3.4.2.7"
#define PROV_NAMES_SHA3_256 "SHA3-256:2.16.840.1.101.3.4.2.8"
#define PROV_NAMES_SHA3_384 "SHA3-384:2.16.840.1.101.3.4.2.9"
#define PROV_NAMES_SHA3_512 "SHA3-512:2.16.840.1.101.3.4.2.10"
#define PROV_NAMES_KECCAK_224 "KECCAK-224"
#define PROV_NAMES_KECCAK_256 "KECCAK-256"
#define PROV_NAMES_KECCAK_384 "KECCAK-384"
#define PROV_NAMES_KECCAK_512 "KECCAK-512"
#define PROV_NAMES_SHAKE_128 "SHAKE-128:SHAKE128:2.16.840.1.101.3.4.2.11"
#define PROV_NAMES_SHAKE_256 "SHAKE-256:SHAKE256:2.16.840.1.101.3.4.2.12"
/*
* KECCAK-KMAC-128 and KECCAK-KMAC-256 as hashes are mostly useful for
* KMAC128 and KMAC256.
*/
#define PROV_NAMES_KECCAK_KMAC_128 "KECCAK-KMAC-128:KECCAK-KMAC128"
#define PROV_NAMES_KECCAK_KMAC_256 "KECCAK-KMAC-256:KECCAK-KMAC256"
/*
* https://blake2.net/ doesn't specify size variants, but mentions that
* Bouncy Castle uses the names BLAKE2b-160, BLAKE2b-256, BLAKE2b-384, and
* BLAKE2b-512
* If we assume that "2b" and "2s" are versions, that pattern fits with ours.
* We also add our historical names.
*/
#define PROV_NAMES_BLAKE2S_256 "BLAKE2S-256:BLAKE2s256:1.3.6.1.4.1.1722.12.2.2.8"
#define PROV_NAMES_BLAKE2B_512 "BLAKE2B-512:BLAKE2b512:1.3.6.1.4.1.1722.12.2.1.16"
#define PROV_NAMES_SM3 "SM3:1.2.156.10197.1.401"
#define PROV_NAMES_MD5 "MD5:SSL3-MD5:1.2.840.113549.2.5"
#define PROV_NAMES_MD5_SHA1 "MD5-SHA1"
#define PROV_NAMES_MD2 "MD2:1.2.840.113549.2.2"
#define PROV_NAMES_MD4 "MD4:1.2.840.113549.2.4"
#define PROV_NAMES_MDC2 "MDC2:2.5.8.3.101"
#define PROV_NAMES_WHIRLPOOL "WHIRLPOOL:1.0.10118.3.0.55"
#define PROV_NAMES_RIPEMD_160 "RIPEMD-160:RIPEMD160:RIPEMD:RMD160:1.3.36.3.2.1"
/*-
* KDFs / PRFs
* -----------
*/
#define PROV_NAMES_HKDF "HKDF"
#define PROV_DESCS_HKDF_SIGN "OpenSSL HKDF via EVP_PKEY implementation"
#define PROV_NAMES_TLS1_3_KDF "TLS13-KDF"
#define PROV_NAMES_SSKDF "SSKDF"
#define PROV_NAMES_PBKDF1 "PBKDF1"
#define PROV_NAMES_PBKDF2 "PBKDF2:1.2.840.113549.1.5.12"
#define PROV_NAMES_PVKKDF "PVKKDF"
#define PROV_NAMES_SSHKDF "SSHKDF"
#define PROV_NAMES_X963KDF "X963KDF:X942KDF-CONCAT"
#define PROV_NAMES_X942KDF_ASN1 "X942KDF-ASN1:X942KDF"
#define PROV_NAMES_TLS1_PRF "TLS1-PRF"
#define PROV_DESCS_TLS1_PRF_SIGN "OpenSSL TLS1_PRF via EVP_PKEY implementation"
#define PROV_NAMES_KBKDF "KBKDF"
#define PROV_NAMES_PKCS12KDF "PKCS12KDF"
#define PROV_NAMES_SCRYPT "SCRYPT:id-scrypt:1.3.6.1.4.1.11591.4.11"
#define PROV_DESCS_SCRYPT_SIGN "OpenSSL SCRYPT via EVP_PKEY implementation"
#define PROV_NAMES_KRB5KDF "KRB5KDF"
#define PROV_NAMES_HMAC_DRBG_KDF "HMAC-DRBG-KDF"
#define PROV_NAMES_ARGON2I "ARGON2I"
#define PROV_NAMES_ARGON2D "ARGON2D"
#define PROV_NAMES_ARGON2ID "ARGON2ID"
/*-
* MACs
* ----
*/
#define PROV_NAMES_HMAC "HMAC"
#define PROV_DESCS_HMAC_SIGN "OpenSSL HMAC via EVP_PKEY implementation"
#define PROV_NAMES_CMAC "CMAC"
#define PROV_DESCS_CMAC_SIGN "OpenSSL CMAC via EVP_PKEY implementation"
#define PROV_NAMES_SIPHASH "SIPHASH"
#define PROV_DESCS_SIPHASH_SIGN "OpenSSL SIPHASH via EVP_PKEY implementation"
#define PROV_NAMES_POLY1305 "POLY1305"
#define PROV_DESCS_POLY1305_SIGN "OpenSSL POLY1305 via EVP_PKEY implementation"
#define PROV_NAMES_GMAC "GMAC:1.0.9797.3.4"
#define PROV_NAMES_KMAC_128 "KMAC-128:KMAC128:2.16.840.1.101.3.4.2.19"
#define PROV_NAMES_KMAC_256 "KMAC-256:KMAC256:2.16.840.1.101.3.4.2.20"
#define PROV_NAMES_BLAKE2BMAC "BLAKE2BMAC:1.3.6.1.4.1.1722.12.2.1"
#define PROV_NAMES_BLAKE2SMAC "BLAKE2SMAC:1.3.6.1.4.1.1722.12.2.2"
/*-
* RANDs
* -----
*/
#define PROV_NAMES_CTR_DRBG "CTR-DRBG"
#define PROV_NAMES_HASH_DRBG "HASH-DRBG"
#define PROV_NAMES_HMAC_DRBG "HMAC-DRBG"
#define PROV_NAMES_TEST_RAND "TEST-RAND"
#define PROV_NAMES_SEED_SRC "SEED-SRC"
/*-
* Asymmetric algos
* ----------------
*/
#define PROV_NAMES_EC "EC:id-ecPublicKey:1.2.840.10045.2.1"
#define PROV_DESCS_EC "OpenSSL EC implementation"
#define PROV_NAMES_ECDH "ECDH"
#define PROV_DESCS_ECDH "OpenSSL ECDH implementation"
#define PROV_NAMES_ECDSA "ECDSA"
#define PROV_DESCS_ECDSA "OpenSSL ECDSA implementation"
#define PROV_NAMES_X25519 "X25519:1.3.101.110"
#define PROV_DESCS_X25519 "OpenSSL X25519 implementation"
#define PROV_NAMES_X448 "X448:1.3.101.111"
#define PROV_DESCS_X448 "OpenSSL X448 implementation"
#define PROV_NAMES_ED25519 "ED25519:1.3.101.112"
#define PROV_DESCS_ED25519 "OpenSSL ED25519 implementation"
#define PROV_NAMES_ED448 "ED448:1.3.101.113"
#define PROV_DESCS_ED448 "OpenSSL ED448 implementation"
#define PROV_NAMES_DH "DH:dhKeyAgreement:1.2.840.113549.1.3.1"
#define PROV_DESCS_DH "OpenSSL PKCS#3 DH implementation"
#define PROV_NAMES_DHX "DHX:X9.42 DH:dhpublicnumber:1.2.840.10046.2.1"
#define PROV_DESCS_DHX "OpenSSL X9.42 DH implementation"
#define PROV_NAMES_DSA "DSA:dsaEncryption:1.2.840.10040.4.1"
#define PROV_DESCS_DSA "OpenSSL DSA implementation"
#define PROV_NAMES_RSA "RSA:rsaEncryption:1.2.840.113549.1.1.1"
#define PROV_DESCS_RSA "OpenSSL RSA implementation"
#define PROV_NAMES_RSA_PSS "RSA-PSS:RSASSA-PSS:1.2.840.113549.1.1.10"
#define PROV_DESCS_RSA_PSS "OpenSSL RSA-PSS implementation"
#define PROV_NAMES_SM2 "SM2:1.2.156.10197.1.301"
#define PROV_DESCS_SM2 "OpenSSL SM2 implementation"
| 17,584 | 49.971014 | 113 | h |
openssl | openssl-master/providers/implementations/include/prov/seeding.h | /*
* Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "prov/provider_ctx.h"
#include "crypto/rand_pool.h"
/* Hardware-based seeding functions. */
size_t ossl_prov_acquire_entropy_from_tsc(RAND_POOL *pool);
size_t ossl_prov_acquire_entropy_from_cpu(RAND_POOL *pool);
/*
* External seeding functions from the core dispatch table.
*/
int ossl_prov_seeding_from_dispatch(const OSSL_DISPATCH *fns);
size_t ossl_prov_get_entropy(PROV_CTX *prov_ctx, unsigned char **pout,
int entropy, size_t min_len, size_t max_len);
void ossl_prov_cleanup_entropy(PROV_CTX *prov_ctx, unsigned char *buf,
size_t len);
size_t ossl_prov_get_nonce(PROV_CTX *prov_ctx, unsigned char **pout,
size_t min_len, size_t max_len,
const void *salt, size_t salt_len);
void ossl_prov_cleanup_nonce(PROV_CTX *prov_ctx, unsigned char *buf,
size_t len);
| 1,254 | 39.483871 | 74 | h |
openssl | openssl-master/providers/implementations/kdfs/hmacdrbg_kdf.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdlib.h>
#include <string.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/kdf.h>
#include <openssl/proverr.h>
#include <openssl/core_names.h>
#include "prov/providercommon.h"
#include "prov/implementations.h"
#include "prov/hmac_drbg.h"
#include "prov/provider_ctx.h"
static OSSL_FUNC_kdf_newctx_fn hmac_drbg_kdf_new;
static OSSL_FUNC_kdf_dupctx_fn hmac_drbg_kdf_dup;
static OSSL_FUNC_kdf_freectx_fn hmac_drbg_kdf_free;
static OSSL_FUNC_kdf_reset_fn hmac_drbg_kdf_reset;
static OSSL_FUNC_kdf_derive_fn hmac_drbg_kdf_derive;
static OSSL_FUNC_kdf_settable_ctx_params_fn hmac_drbg_kdf_settable_ctx_params;
static OSSL_FUNC_kdf_set_ctx_params_fn hmac_drbg_kdf_set_ctx_params;
static OSSL_FUNC_kdf_gettable_ctx_params_fn hmac_drbg_kdf_gettable_ctx_params;
static OSSL_FUNC_kdf_get_ctx_params_fn hmac_drbg_kdf_get_ctx_params;
typedef struct {
PROV_DRBG_HMAC base;
void *provctx;
unsigned char *entropy, *nonce;
size_t entropylen, noncelen;
int init;
} KDF_HMAC_DRBG;
static void *hmac_drbg_kdf_new(void *provctx)
{
KDF_HMAC_DRBG *ctx;
if (!ossl_prov_is_running())
return NULL;
ctx = OPENSSL_zalloc(sizeof(*ctx));
if (ctx == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
return NULL;
}
ctx->provctx = provctx;
return ctx;
}
static void hmac_drbg_kdf_reset(void *vctx)
{
KDF_HMAC_DRBG *ctx = (KDF_HMAC_DRBG *)vctx;
PROV_DRBG_HMAC *drbg = &ctx->base;
void *provctx = ctx->provctx;
EVP_MAC_CTX_free(drbg->ctx);
ossl_prov_digest_reset(&drbg->digest);
OPENSSL_clear_free(ctx->entropy, ctx->entropylen);
OPENSSL_clear_free(ctx->nonce, ctx->noncelen);
OPENSSL_cleanse(ctx, sizeof(*ctx));
ctx->provctx = provctx;
}
static void hmac_drbg_kdf_free(void *vctx)
{
KDF_HMAC_DRBG *ctx = (KDF_HMAC_DRBG *)vctx;
if (ctx != NULL) {
hmac_drbg_kdf_reset(ctx);
OPENSSL_free(ctx);
}
}
static int ossl_drbg_hmac_dup(PROV_DRBG_HMAC *dst, const PROV_DRBG_HMAC *src) {
if (src->ctx != NULL) {
dst->ctx = EVP_MAC_CTX_dup(src->ctx);
if (dst->ctx == NULL)
return 0;
}
if (!ossl_prov_digest_copy(&dst->digest, &src->digest))
return 0;
memcpy(dst->K, src->K, sizeof(dst->K));
memcpy(dst->V, src->V, sizeof(dst->V));
dst->blocklen = src->blocklen;
return 1;
}
static void *hmac_drbg_kdf_dup(void *vctx)
{
const KDF_HMAC_DRBG *src = (const KDF_HMAC_DRBG *)vctx;
KDF_HMAC_DRBG *dst;
dst = hmac_drbg_kdf_new(src->provctx);
if (dst != NULL) {
if (!ossl_drbg_hmac_dup(&dst->base, &src->base)
|| !ossl_prov_memdup(src->entropy, src->entropylen,
&dst->entropy , &dst->entropylen)
|| !ossl_prov_memdup(src->nonce, src->noncelen,
&dst->nonce, &dst->noncelen))
goto err;
dst->init = src->init;
}
return dst;
err:
hmac_drbg_kdf_free(dst);
return NULL;
}
static int hmac_drbg_kdf_derive(void *vctx, unsigned char *out, size_t outlen,
const OSSL_PARAM params[])
{
KDF_HMAC_DRBG *ctx = (KDF_HMAC_DRBG *)vctx;
PROV_DRBG_HMAC *drbg = &ctx->base;
if (!ossl_prov_is_running()
|| !hmac_drbg_kdf_set_ctx_params(vctx, params))
return 0;
if (!ctx->init) {
if (ctx->entropy == NULL
|| ctx->entropylen == 0
|| ctx->nonce == NULL
|| ctx->noncelen == 0
|| !ossl_drbg_hmac_init(drbg, ctx->entropy, ctx->entropylen,
ctx->nonce, ctx->noncelen, NULL, 0))
return 0;
ctx->init = 1;
}
return ossl_drbg_hmac_generate(drbg, out, outlen, NULL, 0);
}
static int hmac_drbg_kdf_get_ctx_params(void *vctx, OSSL_PARAM params[])
{
KDF_HMAC_DRBG *hmac = (KDF_HMAC_DRBG *)vctx;
PROV_DRBG_HMAC *drbg = &hmac->base;
const char *name;
const EVP_MD *md;
OSSL_PARAM *p;
p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_MAC);
if (p != NULL) {
if (drbg->ctx == NULL)
return 0;
name = EVP_MAC_get0_name(EVP_MAC_CTX_get0_mac(drbg->ctx));
if (!OSSL_PARAM_set_utf8_string(p, name))
return 0;
}
p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_DIGEST);
if (p != NULL) {
md = ossl_prov_digest_md(&drbg->digest);
if (md == NULL || !OSSL_PARAM_set_utf8_string(p, EVP_MD_get0_name(md)))
return 0;
}
return 1;
}
static const OSSL_PARAM *hmac_drbg_kdf_gettable_ctx_params(
ossl_unused void *vctx, ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_MAC, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
static int hmac_drbg_kdf_set_ctx_params(void *vctx,
const OSSL_PARAM params[])
{
KDF_HMAC_DRBG *hmac = (KDF_HMAC_DRBG *)vctx;
PROV_DRBG_HMAC *drbg = &hmac->base;
OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(hmac->provctx);
const EVP_MD *md;
const OSSL_PARAM *p;
void *ptr = NULL;
size_t size = 0;
if (params == NULL)
return 1;
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_HMACDRBG_ENTROPY);
if (p != NULL) {
if (!OSSL_PARAM_get_octet_string(p, &ptr, 0, &size))
return 0;
OPENSSL_free(hmac->entropy);
hmac->entropy = ptr;
hmac->entropylen = size;
hmac->init = 0;
ptr = NULL;
}
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_HMACDRBG_NONCE);
if (p != NULL) {
if (!OSSL_PARAM_get_octet_string(p, &ptr, 0, &size))
return 0;
OPENSSL_free(hmac->nonce);
hmac->nonce = ptr;
hmac->noncelen = size;
hmac->init = 0;
}
p = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_DIGEST);
if (p != NULL) {
if (!ossl_prov_digest_load_from_params(&drbg->digest, params, libctx))
return 0;
/* Confirm digest is allowed. Allow all digests that are not XOF */
md = ossl_prov_digest_md(&drbg->digest);
if (md != NULL) {
if ((EVP_MD_get_flags(md) & EVP_MD_FLAG_XOF) != 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_XOF_DIGESTS_NOT_ALLOWED);
return 0;
}
drbg->blocklen = EVP_MD_get_size(md);
}
return ossl_prov_macctx_load_from_params(&drbg->ctx, params,
"HMAC", NULL, NULL, libctx);
}
return 1;
}
static const OSSL_PARAM *hmac_drbg_kdf_settable_ctx_params(
ossl_unused void *vctx, ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_HMACDRBG_ENTROPY, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_HMACDRBG_NONCE, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
const OSSL_DISPATCH ossl_kdf_hmac_drbg_functions[] = {
{ OSSL_FUNC_KDF_NEWCTX, (void(*)(void))hmac_drbg_kdf_new },
{ OSSL_FUNC_KDF_FREECTX, (void(*)(void))hmac_drbg_kdf_free },
{ OSSL_FUNC_KDF_DUPCTX, (void(*)(void))hmac_drbg_kdf_dup },
{ OSSL_FUNC_KDF_RESET, (void(*)(void))hmac_drbg_kdf_reset },
{ OSSL_FUNC_KDF_DERIVE, (void(*)(void))hmac_drbg_kdf_derive },
{ OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
(void(*)(void))hmac_drbg_kdf_settable_ctx_params },
{ OSSL_FUNC_KDF_SET_CTX_PARAMS,
(void(*)(void))hmac_drbg_kdf_set_ctx_params },
{ OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
(void(*)(void))hmac_drbg_kdf_gettable_ctx_params },
{ OSSL_FUNC_KDF_GET_CTX_PARAMS,
(void(*)(void))hmac_drbg_kdf_get_ctx_params },
OSSL_DISPATCH_END
};
| 8,357 | 31.146154 | 79 | c |
openssl | openssl-master/providers/implementations/kdfs/kbkdf.c | /*
* Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright 2019 Red Hat, Inc.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* This implements https://csrc.nist.gov/publications/detail/sp/800-108/final
* section 5.1 ("counter mode") and section 5.2 ("feedback mode") in both HMAC
* and CMAC. That document does not name the KDFs it defines; the name is
* derived from
* https://csrc.nist.gov/Projects/Cryptographic-Algorithm-Validation-Program/Key-Derivation
*
* Note that section 5.3 ("double-pipeline mode") is not implemented, though
* it would be possible to do so in the future.
*
* These versions all assume the counter is used. It would be relatively
* straightforward to expose a configuration handle should the need arise.
*
* Variable names attempt to match those of SP800-108.
*/
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/core_names.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/kdf.h>
#include <openssl/params.h>
#include <openssl/proverr.h>
#include "internal/cryptlib.h"
#include "crypto/evp.h"
#include "internal/numbers.h"
#include "internal/endian.h"
#include "prov/implementations.h"
#include "prov/provider_ctx.h"
#include "prov/provider_util.h"
#include "prov/providercommon.h"
#include "internal/e_os.h"
#include "internal/params.h"
#define ossl_min(a, b) ((a) < (b)) ? (a) : (b)
typedef enum {
COUNTER = 0,
FEEDBACK
} kbkdf_mode;
/* Our context structure. */
typedef struct {
void *provctx;
kbkdf_mode mode;
EVP_MAC_CTX *ctx_init;
/* Names are lowercased versions of those found in SP800-108. */
int r;
unsigned char *ki;
size_t ki_len;
unsigned char *label;
size_t label_len;
unsigned char *context;
size_t context_len;
unsigned char *iv;
size_t iv_len;
int use_l;
int is_kmac;
int use_separator;
} KBKDF;
/* Definitions needed for typechecking. */
static OSSL_FUNC_kdf_newctx_fn kbkdf_new;
static OSSL_FUNC_kdf_dupctx_fn kbkdf_dup;
static OSSL_FUNC_kdf_freectx_fn kbkdf_free;
static OSSL_FUNC_kdf_reset_fn kbkdf_reset;
static OSSL_FUNC_kdf_derive_fn kbkdf_derive;
static OSSL_FUNC_kdf_settable_ctx_params_fn kbkdf_settable_ctx_params;
static OSSL_FUNC_kdf_set_ctx_params_fn kbkdf_set_ctx_params;
static OSSL_FUNC_kdf_gettable_ctx_params_fn kbkdf_gettable_ctx_params;
static OSSL_FUNC_kdf_get_ctx_params_fn kbkdf_get_ctx_params;
/* Not all platforms have htobe32(). */
static uint32_t be32(uint32_t host)
{
uint32_t big = 0;
DECLARE_IS_ENDIAN;
if (!IS_LITTLE_ENDIAN)
return host;
big |= (host & 0xff000000) >> 24;
big |= (host & 0x00ff0000) >> 8;
big |= (host & 0x0000ff00) << 8;
big |= (host & 0x000000ff) << 24;
return big;
}
static void init(KBKDF *ctx)
{
ctx->r = 32;
ctx->use_l = 1;
ctx->use_separator = 1;
ctx->is_kmac = 0;
}
static void *kbkdf_new(void *provctx)
{
KBKDF *ctx;
if (!ossl_prov_is_running())
return NULL;
ctx = OPENSSL_zalloc(sizeof(*ctx));
if (ctx == NULL)
return NULL;
ctx->provctx = provctx;
init(ctx);
return ctx;
}
static void kbkdf_free(void *vctx)
{
KBKDF *ctx = (KBKDF *)vctx;
if (ctx != NULL) {
kbkdf_reset(ctx);
OPENSSL_free(ctx);
}
}
static void kbkdf_reset(void *vctx)
{
KBKDF *ctx = (KBKDF *)vctx;
void *provctx = ctx->provctx;
EVP_MAC_CTX_free(ctx->ctx_init);
OPENSSL_clear_free(ctx->context, ctx->context_len);
OPENSSL_clear_free(ctx->label, ctx->label_len);
OPENSSL_clear_free(ctx->ki, ctx->ki_len);
OPENSSL_clear_free(ctx->iv, ctx->iv_len);
memset(ctx, 0, sizeof(*ctx));
ctx->provctx = provctx;
init(ctx);
}
static void *kbkdf_dup(void *vctx)
{
const KBKDF *src = (const KBKDF *)vctx;
KBKDF *dest;
dest = kbkdf_new(src->provctx);
if (dest != NULL) {
dest->ctx_init = EVP_MAC_CTX_dup(src->ctx_init);
if (dest->ctx_init == NULL
|| !ossl_prov_memdup(src->ki, src->ki_len,
&dest->ki, &dest->ki_len)
|| !ossl_prov_memdup(src->label, src->label_len,
&dest->label, &dest->label_len)
|| !ossl_prov_memdup(src->context, src->context_len,
&dest->context, &dest->context_len)
|| !ossl_prov_memdup(src->iv, src->iv_len,
&dest->iv, &dest->iv_len))
goto err;
dest->mode = src->mode;
dest->r = src->r;
dest->use_l = src->use_l;
dest->use_separator = src->use_separator;
dest->is_kmac = src->is_kmac;
}
return dest;
err:
kbkdf_free(dest);
return NULL;
}
/* SP800-108 section 5.1 or section 5.2 depending on mode. */
static int derive(EVP_MAC_CTX *ctx_init, kbkdf_mode mode, unsigned char *iv,
size_t iv_len, unsigned char *label, size_t label_len,
unsigned char *context, size_t context_len,
unsigned char *k_i, size_t h, uint32_t l, int has_separator,
unsigned char *ko, size_t ko_len, int r)
{
int ret = 0;
EVP_MAC_CTX *ctx = NULL;
size_t written = 0, to_write, k_i_len = iv_len;
const unsigned char zero = 0;
uint32_t counter, i;
/*
* From SP800-108:
* The fixed input data is a concatenation of a Label,
* a separation indicator 0x00, the Context, and L.
* One or more of these fixed input data fields may be omitted.
*
* has_separator == 0 means that the separator is omitted.
* Passing a value of l == 0 means that L is omitted.
* The Context and L are omitted automatically if a NULL buffer is passed.
*/
int has_l = (l != 0);
/* Setup K(0) for feedback mode. */
if (iv_len > 0)
memcpy(k_i, iv, iv_len);
for (counter = 1; written < ko_len; counter++) {
i = be32(counter);
ctx = EVP_MAC_CTX_dup(ctx_init);
if (ctx == NULL)
goto done;
/* Perform feedback, if appropriate. */
if (mode == FEEDBACK && !EVP_MAC_update(ctx, k_i, k_i_len))
goto done;
if (!EVP_MAC_update(ctx, 4 - (r / 8) + (unsigned char *)&i, r / 8)
|| !EVP_MAC_update(ctx, label, label_len)
|| (has_separator && !EVP_MAC_update(ctx, &zero, 1))
|| !EVP_MAC_update(ctx, context, context_len)
|| (has_l && !EVP_MAC_update(ctx, (unsigned char *)&l, 4))
|| !EVP_MAC_final(ctx, k_i, NULL, h))
goto done;
to_write = ko_len - written;
memcpy(ko + written, k_i, ossl_min(to_write, h));
written += h;
k_i_len = h;
EVP_MAC_CTX_free(ctx);
ctx = NULL;
}
ret = 1;
done:
EVP_MAC_CTX_free(ctx);
return ret;
}
/* This must be run before the key is set */
static int kmac_init(EVP_MAC_CTX *ctx, const unsigned char *custom, size_t customlen)
{
OSSL_PARAM params[2];
if (custom == NULL || customlen == 0)
return 1;
params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_CUSTOM,
(void *)custom, customlen);
params[1] = OSSL_PARAM_construct_end();
return EVP_MAC_CTX_set_params(ctx, params) > 0;
}
static int kmac_derive(EVP_MAC_CTX *ctx, unsigned char *out, size_t outlen,
const unsigned char *context, size_t contextlen)
{
OSSL_PARAM params[2];
params[0] = OSSL_PARAM_construct_size_t(OSSL_MAC_PARAM_SIZE, &outlen);
params[1] = OSSL_PARAM_construct_end();
return EVP_MAC_CTX_set_params(ctx, params) > 0
&& EVP_MAC_update(ctx, context, contextlen)
&& EVP_MAC_final(ctx, out, NULL, outlen);
}
static int kbkdf_derive(void *vctx, unsigned char *key, size_t keylen,
const OSSL_PARAM params[])
{
KBKDF *ctx = (KBKDF *)vctx;
int ret = 0;
unsigned char *k_i = NULL;
uint32_t l = 0;
size_t h = 0;
uint64_t counter_max;
if (!ossl_prov_is_running() || !kbkdf_set_ctx_params(ctx, params))
return 0;
/* label, context, and iv are permitted to be empty. Check everything
* else. */
if (ctx->ctx_init == NULL) {
if (ctx->ki_len == 0 || ctx->ki == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_NO_KEY_SET);
return 0;
}
/* Could either be missing MAC or missing message digest or missing
* cipher - arbitrarily, I pick this one. */
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MAC);
return 0;
}
/* Fail if the output length is zero */
if (keylen == 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
return 0;
}
if (ctx->is_kmac) {
ret = kmac_derive(ctx->ctx_init, key, keylen,
ctx->context, ctx->context_len);
goto done;
}
h = EVP_MAC_CTX_get_mac_size(ctx->ctx_init);
if (h == 0)
goto done;
if (ctx->iv_len != 0 && ctx->iv_len != h) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_SEED_LENGTH);
goto done;
}
if (ctx->mode == COUNTER) {
/* Fail if keylen is too large for r */
counter_max = (uint64_t)1 << (uint64_t)ctx->r;
if ((uint64_t)(keylen / h) >= counter_max) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
goto done;
}
}
if (ctx->use_l != 0)
l = be32(keylen * 8);
k_i = OPENSSL_zalloc(h);
if (k_i == NULL)
goto done;
ret = derive(ctx->ctx_init, ctx->mode, ctx->iv, ctx->iv_len, ctx->label,
ctx->label_len, ctx->context, ctx->context_len, k_i, h, l,
ctx->use_separator, key, keylen, ctx->r);
done:
if (ret != 1)
OPENSSL_cleanse(key, keylen);
OPENSSL_clear_free(k_i, h);
return ret;
}
static int kbkdf_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
KBKDF *ctx = (KBKDF *)vctx;
OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
const OSSL_PARAM *p;
if (params == NULL)
return 1;
if (!ossl_prov_macctx_load_from_params(&ctx->ctx_init, params, NULL,
NULL, NULL, libctx))
return 0;
else if (ctx->ctx_init != NULL) {
if (EVP_MAC_is_a(EVP_MAC_CTX_get0_mac(ctx->ctx_init),
OSSL_MAC_NAME_KMAC128)
|| EVP_MAC_is_a(EVP_MAC_CTX_get0_mac(ctx->ctx_init),
OSSL_MAC_NAME_KMAC256)) {
ctx->is_kmac = 1;
} else if (!EVP_MAC_is_a(EVP_MAC_CTX_get0_mac(ctx->ctx_init),
OSSL_MAC_NAME_HMAC)
&& !EVP_MAC_is_a(EVP_MAC_CTX_get0_mac(ctx->ctx_init),
OSSL_MAC_NAME_CMAC)) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MAC);
return 0;
}
}
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_MODE);
if (p != NULL
&& OPENSSL_strncasecmp("counter", p->data, p->data_size) == 0) {
ctx->mode = COUNTER;
} else if (p != NULL
&& OPENSSL_strncasecmp("feedback", p->data, p->data_size) == 0) {
ctx->mode = FEEDBACK;
} else if (p != NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
return 0;
}
if (ossl_param_get1_octet_string(params, OSSL_KDF_PARAM_KEY,
&ctx->ki, &ctx->ki_len) == 0)
return 0;
if (ossl_param_get1_octet_string(params, OSSL_KDF_PARAM_SALT,
&ctx->label, &ctx->label_len) == 0)
return 0;
if (ossl_param_get1_concat_octet_string(params, OSSL_KDF_PARAM_INFO,
&ctx->context, &ctx->context_len,
0) == 0)
return 0;
if (ossl_param_get1_octet_string(params, OSSL_KDF_PARAM_SEED,
&ctx->iv, &ctx->iv_len) == 0)
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KBKDF_USE_L);
if (p != NULL && !OSSL_PARAM_get_int(p, &ctx->use_l))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KBKDF_R);
if (p != NULL) {
int new_r = 0;
if (!OSSL_PARAM_get_int(p, &new_r))
return 0;
if (new_r != 8 && new_r != 16 && new_r != 24 && new_r != 32)
return 0;
ctx->r = new_r;
}
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KBKDF_USE_SEPARATOR);
if (p != NULL && !OSSL_PARAM_get_int(p, &ctx->use_separator))
return 0;
/* Set up digest context, if we can. */
if (ctx->ctx_init != NULL && ctx->ki_len != 0) {
if ((ctx->is_kmac && !kmac_init(ctx->ctx_init, ctx->label, ctx->label_len))
|| !EVP_MAC_init(ctx->ctx_init, ctx->ki, ctx->ki_len, NULL))
return 0;
}
return 1;
}
static const OSSL_PARAM *kbkdf_settable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_INFO, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SEED, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_CIPHER, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_MAC, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_MODE, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_int(OSSL_KDF_PARAM_KBKDF_USE_L, NULL),
OSSL_PARAM_int(OSSL_KDF_PARAM_KBKDF_USE_SEPARATOR, NULL),
OSSL_PARAM_int(OSSL_KDF_PARAM_KBKDF_R, NULL),
OSSL_PARAM_END,
};
return known_settable_ctx_params;
}
static int kbkdf_get_ctx_params(void *vctx, OSSL_PARAM params[])
{
OSSL_PARAM *p;
p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE);
if (p == NULL)
return -2;
/* KBKDF can produce results as large as you like. */
return OSSL_PARAM_set_size_t(p, SIZE_MAX);
}
static const OSSL_PARAM *kbkdf_gettable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] =
{ OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL), OSSL_PARAM_END };
return known_gettable_ctx_params;
}
const OSSL_DISPATCH ossl_kdf_kbkdf_functions[] = {
{ OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kbkdf_new },
{ OSSL_FUNC_KDF_DUPCTX, (void(*)(void))kbkdf_dup },
{ OSSL_FUNC_KDF_FREECTX, (void(*)(void))kbkdf_free },
{ OSSL_FUNC_KDF_RESET, (void(*)(void))kbkdf_reset },
{ OSSL_FUNC_KDF_DERIVE, (void(*)(void))kbkdf_derive },
{ OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
(void(*)(void))kbkdf_settable_ctx_params },
{ OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kbkdf_set_ctx_params },
{ OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
(void(*)(void))kbkdf_gettable_ctx_params },
{ OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kbkdf_get_ctx_params },
OSSL_DISPATCH_END,
};
| 15,533 | 31.095041 | 91 | c |
openssl | openssl-master/providers/implementations/kdfs/krb5kdf.c | /*
* Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* DES low level APIs are deprecated for public use, but still ok for internal
* use. We access the DES_set_odd_parity(3) function here.
*/
#include "internal/deprecated.h"
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <openssl/core_names.h>
#include <openssl/des.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/proverr.h>
#include "internal/cryptlib.h"
#include "crypto/evp.h"
#include "internal/numbers.h"
#include "prov/implementations.h"
#include "prov/provider_ctx.h"
#include "prov/provider_util.h"
#include "prov/providercommon.h"
/* KRB5 KDF defined in RFC 3961, Section 5.1 */
static OSSL_FUNC_kdf_newctx_fn krb5kdf_new;
static OSSL_FUNC_kdf_dupctx_fn krb5kdf_dup;
static OSSL_FUNC_kdf_freectx_fn krb5kdf_free;
static OSSL_FUNC_kdf_reset_fn krb5kdf_reset;
static OSSL_FUNC_kdf_derive_fn krb5kdf_derive;
static OSSL_FUNC_kdf_settable_ctx_params_fn krb5kdf_settable_ctx_params;
static OSSL_FUNC_kdf_set_ctx_params_fn krb5kdf_set_ctx_params;
static OSSL_FUNC_kdf_gettable_ctx_params_fn krb5kdf_gettable_ctx_params;
static OSSL_FUNC_kdf_get_ctx_params_fn krb5kdf_get_ctx_params;
static int KRB5KDF(const EVP_CIPHER *cipher, ENGINE *engine,
const unsigned char *key, size_t key_len,
const unsigned char *constant, size_t constant_len,
unsigned char *okey, size_t okey_len);
typedef struct {
void *provctx;
PROV_CIPHER cipher;
unsigned char *key;
size_t key_len;
unsigned char *constant;
size_t constant_len;
} KRB5KDF_CTX;
static void *krb5kdf_new(void *provctx)
{
KRB5KDF_CTX *ctx;
if (!ossl_prov_is_running())
return NULL;
if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL)
return NULL;
ctx->provctx = provctx;
return ctx;
}
static void krb5kdf_free(void *vctx)
{
KRB5KDF_CTX *ctx = (KRB5KDF_CTX *)vctx;
if (ctx != NULL) {
krb5kdf_reset(ctx);
OPENSSL_free(ctx);
}
}
static void krb5kdf_reset(void *vctx)
{
KRB5KDF_CTX *ctx = (KRB5KDF_CTX *)vctx;
void *provctx = ctx->provctx;
ossl_prov_cipher_reset(&ctx->cipher);
OPENSSL_clear_free(ctx->key, ctx->key_len);
OPENSSL_clear_free(ctx->constant, ctx->constant_len);
memset(ctx, 0, sizeof(*ctx));
ctx->provctx = provctx;
}
static int krb5kdf_set_membuf(unsigned char **dst, size_t *dst_len,
const OSSL_PARAM *p)
{
OPENSSL_clear_free(*dst, *dst_len);
*dst = NULL;
*dst_len = 0;
return OSSL_PARAM_get_octet_string(p, (void **)dst, 0, dst_len);
}
static void *krb5kdf_dup(void *vctx)
{
const KRB5KDF_CTX *src = (const KRB5KDF_CTX *)vctx;
KRB5KDF_CTX *dest;
dest = krb5kdf_new(src->provctx);
if (dest != NULL) {
if (!ossl_prov_memdup(src->key, src->key_len,
&dest->key, &dest->key_len)
|| !ossl_prov_memdup(src->constant, src->constant_len,
&dest->constant , &dest->constant_len)
|| !ossl_prov_cipher_copy(&dest->cipher, &src->cipher))
goto err;
}
return dest;
err:
krb5kdf_free(dest);
return NULL;
}
static int krb5kdf_derive(void *vctx, unsigned char *key, size_t keylen,
const OSSL_PARAM params[])
{
KRB5KDF_CTX *ctx = (KRB5KDF_CTX *)vctx;
const EVP_CIPHER *cipher;
ENGINE *engine;
if (!ossl_prov_is_running() || !krb5kdf_set_ctx_params(ctx, params))
return 0;
cipher = ossl_prov_cipher_cipher(&ctx->cipher);
if (cipher == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_CIPHER);
return 0;
}
if (ctx->key == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_KEY);
return 0;
}
if (ctx->constant == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_CONSTANT);
return 0;
}
engine = ossl_prov_cipher_engine(&ctx->cipher);
return KRB5KDF(cipher, engine, ctx->key, ctx->key_len,
ctx->constant, ctx->constant_len,
key, keylen);
}
static int krb5kdf_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
const OSSL_PARAM *p;
KRB5KDF_CTX *ctx = vctx;
OSSL_LIB_CTX *provctx = PROV_LIBCTX_OF(ctx->provctx);
if (params == NULL)
return 1;
if (!ossl_prov_cipher_load_from_params(&ctx->cipher, params, provctx))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KEY)) != NULL)
if (!krb5kdf_set_membuf(&ctx->key, &ctx->key_len, p))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_CONSTANT))
!= NULL)
if (!krb5kdf_set_membuf(&ctx->constant, &ctx->constant_len, p))
return 0;
return 1;
}
static const OSSL_PARAM *krb5kdf_settable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_CIPHER, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_CONSTANT, NULL, 0),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
static int krb5kdf_get_ctx_params(void *vctx, OSSL_PARAM params[])
{
KRB5KDF_CTX *ctx = (KRB5KDF_CTX *)vctx;
const EVP_CIPHER *cipher;
size_t len;
OSSL_PARAM *p;
cipher = ossl_prov_cipher_cipher(&ctx->cipher);
if (cipher)
len = EVP_CIPHER_get_key_length(cipher);
else
len = EVP_MAX_KEY_LENGTH;
if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
return OSSL_PARAM_set_size_t(p, len);
return -2;
}
static const OSSL_PARAM *krb5kdf_gettable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
const OSSL_DISPATCH ossl_kdf_krb5kdf_functions[] = {
{ OSSL_FUNC_KDF_NEWCTX, (void(*)(void))krb5kdf_new },
{ OSSL_FUNC_KDF_DUPCTX, (void(*)(void))krb5kdf_dup },
{ OSSL_FUNC_KDF_FREECTX, (void(*)(void))krb5kdf_free },
{ OSSL_FUNC_KDF_RESET, (void(*)(void))krb5kdf_reset },
{ OSSL_FUNC_KDF_DERIVE, (void(*)(void))krb5kdf_derive },
{ OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
(void(*)(void))krb5kdf_settable_ctx_params },
{ OSSL_FUNC_KDF_SET_CTX_PARAMS,
(void(*)(void))krb5kdf_set_ctx_params },
{ OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
(void(*)(void))krb5kdf_gettable_ctx_params },
{ OSSL_FUNC_KDF_GET_CTX_PARAMS,
(void(*)(void))krb5kdf_get_ctx_params },
OSSL_DISPATCH_END
};
#ifndef OPENSSL_NO_DES
/*
* DES3 is a special case, it requires a random-to-key function and its
* input truncated to 21 bytes of the 24 produced by the cipher.
* See RFC3961 6.3.1
*/
static int fixup_des3_key(unsigned char *key)
{
unsigned char *cblock;
int i, j;
for (i = 2; i >= 0; i--) {
cblock = &key[i * 8];
memmove(cblock, &key[i * 7], 7);
cblock[7] = 0;
for (j = 0; j < 7; j++)
cblock[7] |= (cblock[j] & 1) << (j + 1);
DES_set_odd_parity((DES_cblock *)cblock);
}
/* fail if keys are such that triple des degrades to single des */
if (CRYPTO_memcmp(&key[0], &key[8], 8) == 0 ||
CRYPTO_memcmp(&key[8], &key[16], 8) == 0) {
return 0;
}
return 1;
}
#endif
/*
* N-fold(K) where blocksize is N, and constant_len is K
* Note: Here |= denotes concatenation
*
* L = lcm(N,K)
* R = L/K
*
* for r: 1 -> R
* s |= constant rot 13*(r-1))
*
* block = 0
* for k: 1 -> K
* block += s[N(k-1)..(N-1)k] (one's complement addition)
*
* Optimizing for space we compute:
* for each l in L-1 -> 0:
* s[l] = (constant rot 13*(l/K))[l%k]
* block[l % N] += s[l] (with carry)
* finally add carry if any
*/
static void n_fold(unsigned char *block, unsigned int blocksize,
const unsigned char *constant, size_t constant_len)
{
unsigned int tmp, gcd, remainder, lcm, carry;
int b, l;
if (constant_len == blocksize) {
memcpy(block, constant, constant_len);
return;
}
/* Least Common Multiple of lengths: LCM(a,b)*/
gcd = blocksize;
remainder = constant_len;
/* Calculate Great Common Divisor first GCD(a,b) */
while (remainder != 0) {
tmp = gcd % remainder;
gcd = remainder;
remainder = tmp;
}
/* resulting a is the GCD, LCM(a,b) = |a*b|/GCD(a,b) */
lcm = blocksize * constant_len / gcd;
/* now spread out the bits */
memset(block, 0, blocksize);
/* last to first to be able to bring carry forward */
carry = 0;
for (l = lcm - 1; l >= 0; l--) {
unsigned int rotbits, rshift, rbyte;
/* destination byte in block is l % N */
b = l % blocksize;
/* Our virtual s buffer is R = L/K long (K = constant_len) */
/* So we rotate backwards from R-1 to 0 (none) rotations */
rotbits = 13 * (l / constant_len);
/* find the byte on s where rotbits falls onto */
rbyte = l - (rotbits / 8);
/* calculate how much shift on that byte */
rshift = rotbits & 0x07;
/* rbyte % constant_len gives us the unrotated byte in the
* constant buffer, get also the previous byte then
* appropriately shift them to get the rotated byte we need */
tmp = (constant[(rbyte-1) % constant_len] << (8 - rshift)
| constant[rbyte % constant_len] >> rshift)
& 0xff;
/* add with carry to any value placed by previous passes */
tmp += carry + block[b];
block[b] = tmp & 0xff;
/* save any carry that may be left */
carry = tmp >> 8;
}
/* if any carry is left at the end, add it through the number */
for (b = blocksize - 1; b >= 0 && carry != 0; b--) {
carry += block[b];
block[b] = carry & 0xff;
carry >>= 8;
}
}
static int cipher_init(EVP_CIPHER_CTX *ctx,
const EVP_CIPHER *cipher, ENGINE *engine,
const unsigned char *key, size_t key_len)
{
int klen, ret;
ret = EVP_EncryptInit_ex(ctx, cipher, engine, key, NULL);
if (!ret)
goto out;
/* set the key len for the odd variable key len cipher */
klen = EVP_CIPHER_CTX_get_key_length(ctx);
if (key_len != (size_t)klen) {
ret = EVP_CIPHER_CTX_set_key_length(ctx, key_len);
if (ret <= 0) {
ret = 0;
goto out;
}
}
/* we never want padding, either the length requested is a multiple of
* the cipher block size or we are passed a cipher that can cope with
* partial blocks via techniques like cipher text stealing */
ret = EVP_CIPHER_CTX_set_padding(ctx, 0);
if (!ret)
goto out;
out:
return ret;
}
static int KRB5KDF(const EVP_CIPHER *cipher, ENGINE *engine,
const unsigned char *key, size_t key_len,
const unsigned char *constant, size_t constant_len,
unsigned char *okey, size_t okey_len)
{
EVP_CIPHER_CTX *ctx = NULL;
unsigned char block[EVP_MAX_BLOCK_LENGTH * 2];
unsigned char *plainblock, *cipherblock;
size_t blocksize;
size_t cipherlen;
size_t osize;
#ifndef OPENSSL_NO_DES
int des3_no_fixup = 0;
#endif
int ret;
if (key_len != okey_len) {
#ifndef OPENSSL_NO_DES
/* special case for 3des, where the caller may be requesting
* the random raw key, instead of the fixed up key */
if (EVP_CIPHER_get_nid(cipher) == NID_des_ede3_cbc &&
key_len == 24 && okey_len == 21) {
des3_no_fixup = 1;
} else {
#endif
ERR_raise(ERR_LIB_PROV, PROV_R_WRONG_OUTPUT_BUFFER_SIZE);
return 0;
#ifndef OPENSSL_NO_DES
}
#endif
}
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
return 0;
ret = cipher_init(ctx, cipher, engine, key, key_len);
if (!ret)
goto out;
/* Initialize input block */
blocksize = EVP_CIPHER_CTX_get_block_size(ctx);
if (constant_len > blocksize) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CONSTANT_LENGTH);
ret = 0;
goto out;
}
n_fold(block, blocksize, constant, constant_len);
plainblock = block;
cipherblock = block + EVP_MAX_BLOCK_LENGTH;
for (osize = 0; osize < okey_len; osize += cipherlen) {
int olen;
ret = EVP_EncryptUpdate(ctx, cipherblock, &olen,
plainblock, blocksize);
if (!ret)
goto out;
cipherlen = olen;
ret = EVP_EncryptFinal_ex(ctx, cipherblock, &olen);
if (!ret)
goto out;
if (olen != 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_WRONG_FINAL_BLOCK_LENGTH);
ret = 0;
goto out;
}
/* write cipherblock out */
if (cipherlen > okey_len - osize)
cipherlen = okey_len - osize;
memcpy(okey + osize, cipherblock, cipherlen);
if (okey_len > osize + cipherlen) {
/* we need to reinitialize cipher context per spec */
ret = EVP_CIPHER_CTX_reset(ctx);
if (!ret)
goto out;
ret = cipher_init(ctx, cipher, engine, key, key_len);
if (!ret)
goto out;
/* also swap block offsets so last ciphertext becomes new
* plaintext */
plainblock = cipherblock;
if (cipherblock == block) {
cipherblock += EVP_MAX_BLOCK_LENGTH;
} else {
cipherblock = block;
}
}
}
#ifndef OPENSSL_NO_DES
if (EVP_CIPHER_get_nid(cipher) == NID_des_ede3_cbc && !des3_no_fixup) {
ret = fixup_des3_key(okey);
if (!ret) {
ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_GENERATE_KEY);
goto out;
}
}
#endif
ret = 1;
out:
EVP_CIPHER_CTX_free(ctx);
OPENSSL_cleanse(block, EVP_MAX_BLOCK_LENGTH * 2);
return ret;
}
| 14,666 | 28.993865 | 79 | c |
openssl | openssl-master/providers/implementations/kdfs/pbkdf1.c | /*
* Copyright 1999-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/trace.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/core_names.h>
#include <openssl/proverr.h>
#include "internal/cryptlib.h"
#include "internal/numbers.h"
#include "crypto/evp.h"
#include "prov/provider_ctx.h"
#include "prov/providercommon.h"
#include "prov/implementations.h"
#include "prov/provider_util.h"
static OSSL_FUNC_kdf_newctx_fn kdf_pbkdf1_new;
static OSSL_FUNC_kdf_dupctx_fn kdf_pbkdf1_dup;
static OSSL_FUNC_kdf_freectx_fn kdf_pbkdf1_free;
static OSSL_FUNC_kdf_reset_fn kdf_pbkdf1_reset;
static OSSL_FUNC_kdf_derive_fn kdf_pbkdf1_derive;
static OSSL_FUNC_kdf_settable_ctx_params_fn kdf_pbkdf1_settable_ctx_params;
static OSSL_FUNC_kdf_set_ctx_params_fn kdf_pbkdf1_set_ctx_params;
static OSSL_FUNC_kdf_gettable_ctx_params_fn kdf_pbkdf1_gettable_ctx_params;
static OSSL_FUNC_kdf_get_ctx_params_fn kdf_pbkdf1_get_ctx_params;
typedef struct {
void *provctx;
PROV_DIGEST digest;
unsigned char *pass;
size_t pass_len;
unsigned char *salt;
size_t salt_len;
uint64_t iter;
} KDF_PBKDF1;
/*
* PKCS5 PBKDF1 compatible key/IV generation as specified in:
* https://tools.ietf.org/html/rfc8018#page-10
*/
static int kdf_pbkdf1_do_derive(const unsigned char *pass, size_t passlen,
const unsigned char *salt, size_t saltlen,
uint64_t iter, const EVP_MD *md_type,
unsigned char *out, size_t n)
{
uint64_t i;
int mdsize, ret = 0;
unsigned char md_tmp[EVP_MAX_MD_SIZE];
EVP_MD_CTX *ctx = NULL;
ctx = EVP_MD_CTX_new();
if (ctx == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_EVP_LIB);
goto err;
}
if (!EVP_DigestInit_ex(ctx, md_type, NULL)
|| !EVP_DigestUpdate(ctx, pass, passlen)
|| !EVP_DigestUpdate(ctx, salt, saltlen)
|| !EVP_DigestFinal_ex(ctx, md_tmp, NULL))
goto err;
mdsize = EVP_MD_size(md_type);
if (mdsize < 0)
goto err;
for (i = 1; i < iter; i++) {
if (!EVP_DigestInit_ex(ctx, md_type, NULL))
goto err;
if (!EVP_DigestUpdate(ctx, md_tmp, mdsize))
goto err;
if (!EVP_DigestFinal_ex(ctx, md_tmp, NULL))
goto err;
}
memcpy(out, md_tmp, n);
ret = 1;
err:
EVP_MD_CTX_free(ctx);
return ret;
}
static void *kdf_pbkdf1_new(void *provctx)
{
KDF_PBKDF1 *ctx;
if (!ossl_prov_is_running())
return NULL;
ctx = OPENSSL_zalloc(sizeof(*ctx));
if (ctx == NULL)
return NULL;
ctx->provctx = provctx;
return ctx;
}
static void kdf_pbkdf1_cleanup(KDF_PBKDF1 *ctx)
{
ossl_prov_digest_reset(&ctx->digest);
OPENSSL_free(ctx->salt);
OPENSSL_clear_free(ctx->pass, ctx->pass_len);
memset(ctx, 0, sizeof(*ctx));
}
static void kdf_pbkdf1_free(void *vctx)
{
KDF_PBKDF1 *ctx = (KDF_PBKDF1 *)vctx;
if (ctx != NULL) {
kdf_pbkdf1_cleanup(ctx);
OPENSSL_free(ctx);
}
}
static void kdf_pbkdf1_reset(void *vctx)
{
KDF_PBKDF1 *ctx = (KDF_PBKDF1 *)vctx;
void *provctx = ctx->provctx;
kdf_pbkdf1_cleanup(ctx);
ctx->provctx = provctx;
}
static void *kdf_pbkdf1_dup(void *vctx)
{
const KDF_PBKDF1 *src = (const KDF_PBKDF1 *)vctx;
KDF_PBKDF1 *dest;
dest = kdf_pbkdf1_new(src->provctx);
if (dest != NULL) {
if (!ossl_prov_memdup(src->salt, src->salt_len,
&dest->salt, &dest->salt_len)
|| !ossl_prov_memdup(src->pass, src->pass_len,
&dest->pass , &dest->pass_len)
|| !ossl_prov_digest_copy(&dest->digest, &src->digest))
goto err;
dest->iter = src->iter;
}
return dest;
err:
kdf_pbkdf1_free(dest);
return NULL;
}
static int kdf_pbkdf1_set_membuf(unsigned char **buffer, size_t *buflen,
const OSSL_PARAM *p)
{
OPENSSL_clear_free(*buffer, *buflen);
*buffer = NULL;
*buflen = 0;
if (p->data_size == 0) {
if ((*buffer = OPENSSL_malloc(1)) == NULL)
return 0;
} else if (p->data != NULL) {
if (!OSSL_PARAM_get_octet_string(p, (void **)buffer, 0, buflen))
return 0;
}
return 1;
}
static int kdf_pbkdf1_derive(void *vctx, unsigned char *key, size_t keylen,
const OSSL_PARAM params[])
{
KDF_PBKDF1 *ctx = (KDF_PBKDF1 *)vctx;
const EVP_MD *md;
if (!ossl_prov_is_running() || !kdf_pbkdf1_set_ctx_params(ctx, params))
return 0;
if (ctx->pass == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_PASS);
return 0;
}
if (ctx->salt == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SALT);
return 0;
}
md = ossl_prov_digest_md(&ctx->digest);
return kdf_pbkdf1_do_derive(ctx->pass, ctx->pass_len, ctx->salt, ctx->salt_len,
ctx->iter, md, key, keylen);
}
static int kdf_pbkdf1_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
const OSSL_PARAM *p;
KDF_PBKDF1 *ctx = vctx;
OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
if (!ossl_prov_digest_load_from_params(&ctx->digest, params, libctx))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_PASSWORD)) != NULL)
if (!kdf_pbkdf1_set_membuf(&ctx->pass, &ctx->pass_len, p))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SALT)) != NULL)
if (!kdf_pbkdf1_set_membuf(&ctx->salt, &ctx->salt_len, p))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_ITER)) != NULL)
if (!OSSL_PARAM_get_uint64(p, &ctx->iter))
return 0;
return 1;
}
static const OSSL_PARAM *kdf_pbkdf1_settable_ctx_params(ossl_unused void *ctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_PASSWORD, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, NULL, 0),
OSSL_PARAM_uint64(OSSL_KDF_PARAM_ITER, NULL),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
static int kdf_pbkdf1_get_ctx_params(void *vctx, OSSL_PARAM params[])
{
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
return OSSL_PARAM_set_size_t(p, SIZE_MAX);
return -2;
}
static const OSSL_PARAM *kdf_pbkdf1_gettable_ctx_params(ossl_unused void *ctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
const OSSL_DISPATCH ossl_kdf_pbkdf1_functions[] = {
{ OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_pbkdf1_new },
{ OSSL_FUNC_KDF_DUPCTX, (void(*)(void))kdf_pbkdf1_dup },
{ OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_pbkdf1_free },
{ OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_pbkdf1_reset },
{ OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_pbkdf1_derive },
{ OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
(void(*)(void))kdf_pbkdf1_settable_ctx_params },
{ OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_pbkdf1_set_ctx_params },
{ OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
(void(*)(void))kdf_pbkdf1_gettable_ctx_params },
{ OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_pbkdf1_get_ctx_params },
OSSL_DISPATCH_END
};
| 8,063 | 29.430189 | 83 | c |
openssl | openssl-master/providers/implementations/kdfs/pbkdf2.c | /*
* Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* HMAC low level APIs are deprecated for public use, but still ok for internal
* use.
*/
#include "internal/deprecated.h"
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/core_names.h>
#include <openssl/proverr.h>
#include "internal/cryptlib.h"
#include "internal/numbers.h"
#include "crypto/evp.h"
#include "prov/provider_ctx.h"
#include "prov/providercommon.h"
#include "prov/implementations.h"
#include "prov/provider_util.h"
#include "pbkdf2.h"
/* Constants specified in SP800-132 */
#define KDF_PBKDF2_MIN_KEY_LEN_BITS 112
#define KDF_PBKDF2_MAX_KEY_LEN_DIGEST_RATIO 0xFFFFFFFF
#define KDF_PBKDF2_MIN_ITERATIONS 1000
#define KDF_PBKDF2_MIN_SALT_LEN (128 / 8)
static OSSL_FUNC_kdf_newctx_fn kdf_pbkdf2_new;
static OSSL_FUNC_kdf_dupctx_fn kdf_pbkdf2_dup;
static OSSL_FUNC_kdf_freectx_fn kdf_pbkdf2_free;
static OSSL_FUNC_kdf_reset_fn kdf_pbkdf2_reset;
static OSSL_FUNC_kdf_derive_fn kdf_pbkdf2_derive;
static OSSL_FUNC_kdf_settable_ctx_params_fn kdf_pbkdf2_settable_ctx_params;
static OSSL_FUNC_kdf_set_ctx_params_fn kdf_pbkdf2_set_ctx_params;
static OSSL_FUNC_kdf_gettable_ctx_params_fn kdf_pbkdf2_gettable_ctx_params;
static OSSL_FUNC_kdf_get_ctx_params_fn kdf_pbkdf2_get_ctx_params;
static int pbkdf2_derive(const char *pass, size_t passlen,
const unsigned char *salt, int saltlen, uint64_t iter,
const EVP_MD *digest, unsigned char *key,
size_t keylen, int extra_checks);
typedef struct {
void *provctx;
unsigned char *pass;
size_t pass_len;
unsigned char *salt;
size_t salt_len;
uint64_t iter;
PROV_DIGEST digest;
int lower_bound_checks;
} KDF_PBKDF2;
static void kdf_pbkdf2_init(KDF_PBKDF2 *ctx);
static void *kdf_pbkdf2_new_no_init(void *provctx)
{
KDF_PBKDF2 *ctx;
if (!ossl_prov_is_running())
return NULL;
ctx = OPENSSL_zalloc(sizeof(*ctx));
if (ctx == NULL)
return NULL;
ctx->provctx = provctx;
return ctx;
}
static void *kdf_pbkdf2_new(void *provctx)
{
KDF_PBKDF2 *ctx = kdf_pbkdf2_new_no_init(provctx);
if (ctx != NULL)
kdf_pbkdf2_init(ctx);
return ctx;
}
static void kdf_pbkdf2_cleanup(KDF_PBKDF2 *ctx)
{
ossl_prov_digest_reset(&ctx->digest);
OPENSSL_free(ctx->salt);
OPENSSL_clear_free(ctx->pass, ctx->pass_len);
memset(ctx, 0, sizeof(*ctx));
}
static void kdf_pbkdf2_free(void *vctx)
{
KDF_PBKDF2 *ctx = (KDF_PBKDF2 *)vctx;
if (ctx != NULL) {
kdf_pbkdf2_cleanup(ctx);
OPENSSL_free(ctx);
}
}
static void kdf_pbkdf2_reset(void *vctx)
{
KDF_PBKDF2 *ctx = (KDF_PBKDF2 *)vctx;
void *provctx = ctx->provctx;
kdf_pbkdf2_cleanup(ctx);
ctx->provctx = provctx;
kdf_pbkdf2_init(ctx);
}
static void *kdf_pbkdf2_dup(void *vctx)
{
const KDF_PBKDF2 *src = (const KDF_PBKDF2 *)vctx;
KDF_PBKDF2 *dest;
/* We need a new PBKDF2 object but uninitialised since we're filling it */
dest = kdf_pbkdf2_new_no_init(src->provctx);
if (dest != NULL) {
if (!ossl_prov_memdup(src->salt, src->salt_len,
&dest->salt, &dest->salt_len)
|| !ossl_prov_memdup(src->pass, src->pass_len,
&dest->pass, &dest->pass_len)
|| !ossl_prov_digest_copy(&dest->digest, &src->digest))
goto err;
dest->iter = src->iter;
dest->lower_bound_checks = src->lower_bound_checks;
}
return dest;
err:
kdf_pbkdf2_free(dest);
return NULL;
}
static void kdf_pbkdf2_init(KDF_PBKDF2 *ctx)
{
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
OSSL_LIB_CTX *provctx = PROV_LIBCTX_OF(ctx->provctx);
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
SN_sha1, 0);
if (!ossl_prov_digest_load_from_params(&ctx->digest, params, provctx))
/* This is an error, but there is no way to indicate such directly */
ossl_prov_digest_reset(&ctx->digest);
ctx->iter = PKCS5_DEFAULT_ITER;
ctx->lower_bound_checks = ossl_kdf_pbkdf2_default_checks;
}
static int pbkdf2_set_membuf(unsigned char **buffer, size_t *buflen,
const OSSL_PARAM *p)
{
OPENSSL_clear_free(*buffer, *buflen);
*buffer = NULL;
*buflen = 0;
if (p->data_size == 0) {
if ((*buffer = OPENSSL_malloc(1)) == NULL)
return 0;
} else if (p->data != NULL) {
if (!OSSL_PARAM_get_octet_string(p, (void **)buffer, 0, buflen))
return 0;
}
return 1;
}
static int kdf_pbkdf2_derive(void *vctx, unsigned char *key, size_t keylen,
const OSSL_PARAM params[])
{
KDF_PBKDF2 *ctx = (KDF_PBKDF2 *)vctx;
const EVP_MD *md;
if (!ossl_prov_is_running() || !kdf_pbkdf2_set_ctx_params(ctx, params))
return 0;
if (ctx->pass == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_PASS);
return 0;
}
if (ctx->salt == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SALT);
return 0;
}
md = ossl_prov_digest_md(&ctx->digest);
return pbkdf2_derive((char *)ctx->pass, ctx->pass_len,
ctx->salt, ctx->salt_len, ctx->iter,
md, key, keylen, ctx->lower_bound_checks);
}
static int kdf_pbkdf2_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
const OSSL_PARAM *p;
KDF_PBKDF2 *ctx = vctx;
OSSL_LIB_CTX *provctx = PROV_LIBCTX_OF(ctx->provctx);
int pkcs5;
uint64_t iter, min_iter;
if (params == NULL)
return 1;
if (!ossl_prov_digest_load_from_params(&ctx->digest, params, provctx))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_PKCS5)) != NULL) {
if (!OSSL_PARAM_get_int(p, &pkcs5))
return 0;
ctx->lower_bound_checks = pkcs5 == 0;
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_PASSWORD)) != NULL)
if (!pbkdf2_set_membuf(&ctx->pass, &ctx->pass_len, p))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SALT)) != NULL) {
if (ctx->lower_bound_checks != 0
&& p->data_size < KDF_PBKDF2_MIN_SALT_LEN) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_SALT_LENGTH);
return 0;
}
if (!pbkdf2_set_membuf(&ctx->salt, &ctx->salt_len, p))
return 0;
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_ITER)) != NULL) {
if (!OSSL_PARAM_get_uint64(p, &iter))
return 0;
min_iter = ctx->lower_bound_checks != 0 ? KDF_PBKDF2_MIN_ITERATIONS : 1;
if (iter < min_iter) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_ITERATION_COUNT);
return 0;
}
ctx->iter = iter;
}
return 1;
}
static const OSSL_PARAM *kdf_pbkdf2_settable_ctx_params(ossl_unused void *ctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_PASSWORD, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, NULL, 0),
OSSL_PARAM_uint64(OSSL_KDF_PARAM_ITER, NULL),
OSSL_PARAM_int(OSSL_KDF_PARAM_PKCS5, NULL),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
static int kdf_pbkdf2_get_ctx_params(void *vctx, OSSL_PARAM params[])
{
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
return OSSL_PARAM_set_size_t(p, SIZE_MAX);
return -2;
}
static const OSSL_PARAM *kdf_pbkdf2_gettable_ctx_params(ossl_unused void *ctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
const OSSL_DISPATCH ossl_kdf_pbkdf2_functions[] = {
{ OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_pbkdf2_new },
{ OSSL_FUNC_KDF_DUPCTX, (void(*)(void))kdf_pbkdf2_dup },
{ OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_pbkdf2_free },
{ OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_pbkdf2_reset },
{ OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_pbkdf2_derive },
{ OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
(void(*)(void))kdf_pbkdf2_settable_ctx_params },
{ OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_pbkdf2_set_ctx_params },
{ OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
(void(*)(void))kdf_pbkdf2_gettable_ctx_params },
{ OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_pbkdf2_get_ctx_params },
OSSL_DISPATCH_END
};
/*
* This is an implementation of PKCS#5 v2.0 password based encryption key
* derivation function PBKDF2. SHA1 version verified against test vectors
* posted by Peter Gutmann to the PKCS-TNG mailing list.
*
* The constraints specified by SP800-132 have been added i.e.
* - Check the range of the key length.
* - Minimum iteration count of 1000.
* - Randomly-generated portion of the salt shall be at least 128 bits.
*/
static int pbkdf2_derive(const char *pass, size_t passlen,
const unsigned char *salt, int saltlen, uint64_t iter,
const EVP_MD *digest, unsigned char *key,
size_t keylen, int lower_bound_checks)
{
int ret = 0;
unsigned char digtmp[EVP_MAX_MD_SIZE], *p, itmp[4];
int cplen, k, tkeylen, mdlen;
uint64_t j;
unsigned long i = 1;
HMAC_CTX *hctx_tpl = NULL, *hctx = NULL;
mdlen = EVP_MD_get_size(digest);
if (mdlen <= 0)
return 0;
/*
* This check should always be done because keylen / mdlen >= (2^32 - 1)
* results in an overflow of the loop counter 'i'.
*/
if ((keylen / mdlen) >= KDF_PBKDF2_MAX_KEY_LEN_DIGEST_RATIO) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
return 0;
}
if (lower_bound_checks) {
if ((keylen * 8) < KDF_PBKDF2_MIN_KEY_LEN_BITS) {
ERR_raise(ERR_LIB_PROV, PROV_R_KEY_SIZE_TOO_SMALL);
return 0;
}
if (saltlen < KDF_PBKDF2_MIN_SALT_LEN) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_SALT_LENGTH);
return 0;
}
if (iter < KDF_PBKDF2_MIN_ITERATIONS) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_ITERATION_COUNT);
return 0;
}
}
hctx_tpl = HMAC_CTX_new();
if (hctx_tpl == NULL)
return 0;
p = key;
tkeylen = keylen;
if (!HMAC_Init_ex(hctx_tpl, pass, passlen, digest, NULL))
goto err;
hctx = HMAC_CTX_new();
if (hctx == NULL)
goto err;
while (tkeylen) {
if (tkeylen > mdlen)
cplen = mdlen;
else
cplen = tkeylen;
/*
* We are unlikely to ever use more than 256 blocks (5120 bits!) but
* just in case...
*/
itmp[0] = (unsigned char)((i >> 24) & 0xff);
itmp[1] = (unsigned char)((i >> 16) & 0xff);
itmp[2] = (unsigned char)((i >> 8) & 0xff);
itmp[3] = (unsigned char)(i & 0xff);
if (!HMAC_CTX_copy(hctx, hctx_tpl))
goto err;
if (!HMAC_Update(hctx, salt, saltlen)
|| !HMAC_Update(hctx, itmp, 4)
|| !HMAC_Final(hctx, digtmp, NULL))
goto err;
memcpy(p, digtmp, cplen);
for (j = 1; j < iter; j++) {
if (!HMAC_CTX_copy(hctx, hctx_tpl))
goto err;
if (!HMAC_Update(hctx, digtmp, mdlen)
|| !HMAC_Final(hctx, digtmp, NULL))
goto err;
for (k = 0; k < cplen; k++)
p[k] ^= digtmp[k];
}
tkeylen -= cplen;
i++;
p += cplen;
}
ret = 1;
err:
HMAC_CTX_free(hctx);
HMAC_CTX_free(hctx_tpl);
return ret;
}
| 12,480 | 30.677665 | 80 | c |
openssl | openssl-master/providers/implementations/kdfs/pbkdf2.h | /*
* Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Available in pbkdfe_fips.c, and compiled with different values depending
* on we're in the FIPS module or not.
*/
extern const int ossl_kdf_pbkdf2_default_checks;
| 508 | 32.933333 | 75 | h |
openssl | openssl-master/providers/implementations/kdfs/pbkdf2_fips.c | /*
* Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "pbkdf2.h"
/*
* For backwards compatibility reasons,
* Extra checks are done by default in fips mode only.
*/
#ifdef FIPS_MODULE
const int ossl_kdf_pbkdf2_default_checks = 1;
#else
const int ossl_kdf_pbkdf2_default_checks = 0;
#endif /* FIPS_MODULE */
| 602 | 27.714286 | 74 | c |
openssl | openssl-master/providers/implementations/kdfs/pkcs12kdf.c | /*
* Copyright 1999-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/trace.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/core_names.h>
#include <openssl/proverr.h>
#include "internal/cryptlib.h"
#include "internal/numbers.h"
#include "crypto/evp.h"
#include "prov/provider_ctx.h"
#include "prov/providercommon.h"
#include "prov/implementations.h"
#include "prov/provider_util.h"
static OSSL_FUNC_kdf_newctx_fn kdf_pkcs12_new;
static OSSL_FUNC_kdf_dupctx_fn kdf_pkcs12_dup;
static OSSL_FUNC_kdf_freectx_fn kdf_pkcs12_free;
static OSSL_FUNC_kdf_reset_fn kdf_pkcs12_reset;
static OSSL_FUNC_kdf_derive_fn kdf_pkcs12_derive;
static OSSL_FUNC_kdf_settable_ctx_params_fn kdf_pkcs12_settable_ctx_params;
static OSSL_FUNC_kdf_set_ctx_params_fn kdf_pkcs12_set_ctx_params;
static OSSL_FUNC_kdf_gettable_ctx_params_fn kdf_pkcs12_gettable_ctx_params;
static OSSL_FUNC_kdf_get_ctx_params_fn kdf_pkcs12_get_ctx_params;
typedef struct {
void *provctx;
PROV_DIGEST digest;
unsigned char *pass;
size_t pass_len;
unsigned char *salt;
size_t salt_len;
uint64_t iter;
int id;
} KDF_PKCS12;
/* PKCS12 compatible key/IV generation */
static int pkcs12kdf_derive(const unsigned char *pass, size_t passlen,
const unsigned char *salt, size_t saltlen,
int id, uint64_t iter, const EVP_MD *md_type,
unsigned char *out, size_t n)
{
unsigned char *B = NULL, *D = NULL, *I = NULL, *p = NULL, *Ai = NULL;
size_t Slen, Plen, Ilen;
size_t i, j, k, u, v;
uint64_t iter_cnt;
int ret = 0, ui, vi;
EVP_MD_CTX *ctx = NULL;
ctx = EVP_MD_CTX_new();
if (ctx == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_EVP_LIB);
goto end;
}
vi = EVP_MD_get_block_size(md_type);
ui = EVP_MD_get_size(md_type);
if (ui <= 0 || vi <= 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_DIGEST_SIZE);
goto end;
}
u = (size_t)ui;
v = (size_t)vi;
D = OPENSSL_malloc(v);
Ai = OPENSSL_malloc(u);
B = OPENSSL_malloc(v + 1);
Slen = v * ((saltlen + v - 1) / v);
if (passlen != 0)
Plen = v * ((passlen + v - 1) / v);
else
Plen = 0;
Ilen = Slen + Plen;
I = OPENSSL_malloc(Ilen);
if (D == NULL || Ai == NULL || B == NULL || I == NULL)
goto end;
for (i = 0; i < v; i++)
D[i] = id;
p = I;
for (i = 0; i < Slen; i++)
*p++ = salt[i % saltlen];
for (i = 0; i < Plen; i++)
*p++ = pass[i % passlen];
for (;;) {
if (!EVP_DigestInit_ex(ctx, md_type, NULL)
|| !EVP_DigestUpdate(ctx, D, v)
|| !EVP_DigestUpdate(ctx, I, Ilen)
|| !EVP_DigestFinal_ex(ctx, Ai, NULL))
goto end;
for (iter_cnt = 1; iter_cnt < iter; iter_cnt++) {
if (!EVP_DigestInit_ex(ctx, md_type, NULL)
|| !EVP_DigestUpdate(ctx, Ai, u)
|| !EVP_DigestFinal_ex(ctx, Ai, NULL))
goto end;
}
memcpy(out, Ai, n < u ? n : u);
if (u >= n) {
ret = 1;
break;
}
n -= u;
out += u;
for (j = 0; j < v; j++)
B[j] = Ai[j % u];
for (j = 0; j < Ilen; j += v) {
unsigned char *Ij = I + j;
uint16_t c = 1;
/* Work out Ij = Ij + B + 1 */
for (k = v; k > 0;) {
k--;
c += Ij[k] + B[k];
Ij[k] = (unsigned char)c;
c >>= 8;
}
}
}
end:
OPENSSL_free(Ai);
OPENSSL_free(B);
OPENSSL_free(D);
OPENSSL_free(I);
EVP_MD_CTX_free(ctx);
return ret;
}
static void *kdf_pkcs12_new(void *provctx)
{
KDF_PKCS12 *ctx;
if (!ossl_prov_is_running())
return NULL;
ctx = OPENSSL_zalloc(sizeof(*ctx));
if (ctx == NULL)
return NULL;
ctx->provctx = provctx;
return ctx;
}
static void kdf_pkcs12_cleanup(KDF_PKCS12 *ctx)
{
ossl_prov_digest_reset(&ctx->digest);
OPENSSL_free(ctx->salt);
OPENSSL_clear_free(ctx->pass, ctx->pass_len);
memset(ctx, 0, sizeof(*ctx));
}
static void kdf_pkcs12_free(void *vctx)
{
KDF_PKCS12 *ctx = (KDF_PKCS12 *)vctx;
if (ctx != NULL) {
kdf_pkcs12_cleanup(ctx);
OPENSSL_free(ctx);
}
}
static void kdf_pkcs12_reset(void *vctx)
{
KDF_PKCS12 *ctx = (KDF_PKCS12 *)vctx;
void *provctx = ctx->provctx;
kdf_pkcs12_cleanup(ctx);
ctx->provctx = provctx;
}
static void *kdf_pkcs12_dup(void *vctx)
{
const KDF_PKCS12 *src = (const KDF_PKCS12 *)vctx;
KDF_PKCS12 *dest;
dest = kdf_pkcs12_new(src->provctx);
if (dest != NULL) {
if (!ossl_prov_memdup(src->salt, src->salt_len,
&dest->salt, &dest->salt_len)
|| !ossl_prov_memdup(src->pass, src->pass_len,
&dest->pass , &dest->pass_len)
|| !ossl_prov_digest_copy(&dest->digest, &src->digest))
goto err;
dest->iter = src->iter;
dest->id = src->id;
}
return dest;
err:
kdf_pkcs12_free(dest);
return NULL;
}
static int pkcs12kdf_set_membuf(unsigned char **buffer, size_t *buflen,
const OSSL_PARAM *p)
{
OPENSSL_clear_free(*buffer, *buflen);
*buffer = NULL;
*buflen = 0;
if (p->data_size == 0) {
if ((*buffer = OPENSSL_malloc(1)) == NULL)
return 0;
} else if (p->data != NULL) {
if (!OSSL_PARAM_get_octet_string(p, (void **)buffer, 0, buflen))
return 0;
}
return 1;
}
static int kdf_pkcs12_derive(void *vctx, unsigned char *key, size_t keylen,
const OSSL_PARAM params[])
{
KDF_PKCS12 *ctx = (KDF_PKCS12 *)vctx;
const EVP_MD *md;
if (!ossl_prov_is_running() || !kdf_pkcs12_set_ctx_params(ctx, params))
return 0;
if (ctx->pass == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_PASS);
return 0;
}
if (ctx->salt == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SALT);
return 0;
}
md = ossl_prov_digest_md(&ctx->digest);
return pkcs12kdf_derive(ctx->pass, ctx->pass_len, ctx->salt, ctx->salt_len,
ctx->id, ctx->iter, md, key, keylen);
}
static int kdf_pkcs12_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
const OSSL_PARAM *p;
KDF_PKCS12 *ctx = vctx;
OSSL_LIB_CTX *provctx = PROV_LIBCTX_OF(ctx->provctx);
if (params == NULL)
return 1;
if (!ossl_prov_digest_load_from_params(&ctx->digest, params, provctx))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_PASSWORD)) != NULL)
if (!pkcs12kdf_set_membuf(&ctx->pass, &ctx->pass_len, p))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SALT)) != NULL)
if (!pkcs12kdf_set_membuf(&ctx->salt, &ctx->salt_len, p))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_PKCS12_ID)) != NULL)
if (!OSSL_PARAM_get_int(p, &ctx->id))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_ITER)) != NULL)
if (!OSSL_PARAM_get_uint64(p, &ctx->iter))
return 0;
return 1;
}
static const OSSL_PARAM *kdf_pkcs12_settable_ctx_params(
ossl_unused void *ctx, ossl_unused void *provctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_PASSWORD, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, NULL, 0),
OSSL_PARAM_uint64(OSSL_KDF_PARAM_ITER, NULL),
OSSL_PARAM_int(OSSL_KDF_PARAM_PKCS12_ID, NULL),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
static int kdf_pkcs12_get_ctx_params(void *vctx, OSSL_PARAM params[])
{
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
return OSSL_PARAM_set_size_t(p, SIZE_MAX);
return -2;
}
static const OSSL_PARAM *kdf_pkcs12_gettable_ctx_params(
ossl_unused void *ctx, ossl_unused void *provctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
const OSSL_DISPATCH ossl_kdf_pkcs12_functions[] = {
{ OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_pkcs12_new },
{ OSSL_FUNC_KDF_DUPCTX, (void(*)(void))kdf_pkcs12_dup },
{ OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_pkcs12_free },
{ OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_pkcs12_reset },
{ OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_pkcs12_derive },
{ OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
(void(*)(void))kdf_pkcs12_settable_ctx_params },
{ OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_pkcs12_set_ctx_params },
{ OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
(void(*)(void))kdf_pkcs12_gettable_ctx_params },
{ OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_pkcs12_get_ctx_params },
OSSL_DISPATCH_END
};
| 9,567 | 28.9 | 80 | c |
openssl | openssl-master/providers/implementations/kdfs/pvkkdf.c | /*
* Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/evp.h>
#include <openssl/core_names.h>
#include <openssl/proverr.h>
#include <openssl/err.h>
#include "internal/numbers.h" /* SIZE_MAX */
#include "prov/provider_ctx.h"
#include "prov/providercommon.h"
#include "prov/implementations.h"
#include "prov/provider_util.h"
static OSSL_FUNC_kdf_newctx_fn kdf_pvk_new;
static OSSL_FUNC_kdf_dupctx_fn kdf_pvk_dup;
static OSSL_FUNC_kdf_freectx_fn kdf_pvk_free;
static OSSL_FUNC_kdf_reset_fn kdf_pvk_reset;
static OSSL_FUNC_kdf_derive_fn kdf_pvk_derive;
static OSSL_FUNC_kdf_settable_ctx_params_fn kdf_pvk_settable_ctx_params;
static OSSL_FUNC_kdf_set_ctx_params_fn kdf_pvk_set_ctx_params;
static OSSL_FUNC_kdf_gettable_ctx_params_fn kdf_pvk_gettable_ctx_params;
static OSSL_FUNC_kdf_get_ctx_params_fn kdf_pvk_get_ctx_params;
typedef struct {
void *provctx;
unsigned char *pass;
size_t pass_len;
unsigned char *salt;
size_t salt_len;
PROV_DIGEST digest;
} KDF_PVK;
static void kdf_pvk_init(KDF_PVK *ctx);
static void *kdf_pvk_new(void *provctx)
{
KDF_PVK *ctx;
if (!ossl_prov_is_running())
return NULL;
ctx = OPENSSL_zalloc(sizeof(*ctx));
if (ctx == NULL)
return NULL;
ctx->provctx = provctx;
kdf_pvk_init(ctx);
return ctx;
}
static void kdf_pvk_cleanup(KDF_PVK *ctx)
{
ossl_prov_digest_reset(&ctx->digest);
OPENSSL_free(ctx->salt);
OPENSSL_clear_free(ctx->pass, ctx->pass_len);
OPENSSL_cleanse(ctx, sizeof(*ctx));
}
static void kdf_pvk_free(void *vctx)
{
KDF_PVK *ctx = (KDF_PVK *)vctx;
if (ctx != NULL) {
kdf_pvk_cleanup(ctx);
OPENSSL_free(ctx);
}
}
static void *kdf_pvk_dup(void *vctx)
{
const KDF_PVK *src = (const KDF_PVK *)vctx;
KDF_PVK *dest;
dest = kdf_pvk_new(src->provctx);
if (dest != NULL)
if (!ossl_prov_memdup(src->salt, src->salt_len,
&dest->salt, &dest->salt_len)
|| !ossl_prov_memdup(src->pass, src->pass_len,
&dest->pass , &dest->pass_len)
|| !ossl_prov_digest_copy(&dest->digest, &src->digest))
goto err;
return dest;
err:
kdf_pvk_free(dest);
return NULL;
}
static void kdf_pvk_reset(void *vctx)
{
KDF_PVK *ctx = (KDF_PVK *)vctx;
void *provctx = ctx->provctx;
kdf_pvk_cleanup(ctx);
ctx->provctx = provctx;
kdf_pvk_init(ctx);
}
static void kdf_pvk_init(KDF_PVK *ctx)
{
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
OSSL_LIB_CTX *provctx = PROV_LIBCTX_OF(ctx->provctx);
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
SN_sha1, 0);
if (!ossl_prov_digest_load_from_params(&ctx->digest, params, provctx))
/* This is an error, but there is no way to indicate such directly */
ossl_prov_digest_reset(&ctx->digest);
}
static int pvk_set_membuf(unsigned char **buffer, size_t *buflen,
const OSSL_PARAM *p)
{
OPENSSL_clear_free(*buffer, *buflen);
*buffer = NULL;
*buflen = 0;
if (p->data_size == 0) {
if ((*buffer = OPENSSL_malloc(1)) == NULL)
return 0;
} else if (p->data != NULL) {
if (!OSSL_PARAM_get_octet_string(p, (void **)buffer, 0, buflen))
return 0;
}
return 1;
}
static int kdf_pvk_derive(void *vctx, unsigned char *key, size_t keylen,
const OSSL_PARAM params[])
{
KDF_PVK *ctx = (KDF_PVK *)vctx;
const EVP_MD *md;
EVP_MD_CTX *mctx;
int res;
if (!ossl_prov_is_running() || !kdf_pvk_set_ctx_params(ctx, params))
return 0;
if (ctx->pass == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_PASS);
return 0;
}
if (ctx->salt == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SALT);
return 0;
}
md = ossl_prov_digest_md(&ctx->digest);
if (md == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_DIGEST);
return 0;
}
res = EVP_MD_get_size(md);
if (res <= 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_BAD_LENGTH);
return 0;
}
if ((size_t)res > keylen) {
ERR_raise(ERR_LIB_PROV, PROV_R_LENGTH_TOO_LARGE);
return 0;
}
mctx = EVP_MD_CTX_new();
res = mctx != NULL
&& EVP_DigestInit_ex(mctx, md, NULL)
&& EVP_DigestUpdate(mctx, ctx->salt, ctx->salt_len)
&& EVP_DigestUpdate(mctx, ctx->pass, ctx->pass_len)
&& EVP_DigestFinal_ex(mctx, key, NULL);
EVP_MD_CTX_free(mctx);
return res;
}
static int kdf_pvk_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
const OSSL_PARAM *p;
KDF_PVK *ctx = vctx;
OSSL_LIB_CTX *provctx = PROV_LIBCTX_OF(ctx->provctx);
if (params == NULL)
return 1;
if (!ossl_prov_digest_load_from_params(&ctx->digest, params, provctx))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_PASSWORD)) != NULL)
if (!pvk_set_membuf(&ctx->pass, &ctx->pass_len, p))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SALT)) != NULL) {
if (!pvk_set_membuf(&ctx->salt, &ctx->salt_len, p))
return 0;
}
return 1;
}
static const OSSL_PARAM *kdf_pvk_settable_ctx_params(ossl_unused void *ctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_PASSWORD, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, NULL, 0),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
static int kdf_pvk_get_ctx_params(void *vctx, OSSL_PARAM params[])
{
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
return OSSL_PARAM_set_size_t(p, SIZE_MAX);
return -2;
}
static const OSSL_PARAM *kdf_pvk_gettable_ctx_params(ossl_unused void *ctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
const OSSL_DISPATCH ossl_kdf_pvk_functions[] = {
{ OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_pvk_new },
{ OSSL_FUNC_KDF_DUPCTX, (void(*)(void))kdf_pvk_dup },
{ OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_pvk_free },
{ OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_pvk_reset },
{ OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_pvk_derive },
{ OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
(void(*)(void))kdf_pvk_settable_ctx_params },
{ OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_pvk_set_ctx_params },
{ OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
(void(*)(void))kdf_pvk_gettable_ctx_params },
{ OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_pvk_get_ctx_params },
OSSL_DISPATCH_END
};
| 7,432 | 28.851406 | 80 | c |
openssl | openssl-master/providers/implementations/kdfs/scrypt.c | /*
* Copyright 2017-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/err.h>
#include <openssl/core_names.h>
#include <openssl/proverr.h>
#include "crypto/evp.h"
#include "internal/numbers.h"
#include "prov/implementations.h"
#include "prov/provider_ctx.h"
#include "prov/providercommon.h"
#include "prov/provider_util.h"
#ifndef OPENSSL_NO_SCRYPT
static OSSL_FUNC_kdf_newctx_fn kdf_scrypt_new;
static OSSL_FUNC_kdf_dupctx_fn kdf_scrypt_dup;
static OSSL_FUNC_kdf_freectx_fn kdf_scrypt_free;
static OSSL_FUNC_kdf_reset_fn kdf_scrypt_reset;
static OSSL_FUNC_kdf_derive_fn kdf_scrypt_derive;
static OSSL_FUNC_kdf_settable_ctx_params_fn kdf_scrypt_settable_ctx_params;
static OSSL_FUNC_kdf_set_ctx_params_fn kdf_scrypt_set_ctx_params;
static OSSL_FUNC_kdf_gettable_ctx_params_fn kdf_scrypt_gettable_ctx_params;
static OSSL_FUNC_kdf_get_ctx_params_fn kdf_scrypt_get_ctx_params;
static int scrypt_alg(const char *pass, size_t passlen,
const unsigned char *salt, size_t saltlen,
uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem,
unsigned char *key, size_t keylen, EVP_MD *sha256,
OSSL_LIB_CTX *libctx, const char *propq);
typedef struct {
OSSL_LIB_CTX *libctx;
char *propq;
unsigned char *pass;
size_t pass_len;
unsigned char *salt;
size_t salt_len;
uint64_t N;
uint64_t r, p;
uint64_t maxmem_bytes;
EVP_MD *sha256;
} KDF_SCRYPT;
static void kdf_scrypt_init(KDF_SCRYPT *ctx);
static void *kdf_scrypt_new_inner(OSSL_LIB_CTX *libctx)
{
KDF_SCRYPT *ctx;
if (!ossl_prov_is_running())
return NULL;
ctx = OPENSSL_zalloc(sizeof(*ctx));
if (ctx == NULL)
return NULL;
ctx->libctx = libctx;
kdf_scrypt_init(ctx);
return ctx;
}
static void *kdf_scrypt_new(void *provctx)
{
return kdf_scrypt_new_inner(PROV_LIBCTX_OF(provctx));
}
static void kdf_scrypt_free(void *vctx)
{
KDF_SCRYPT *ctx = (KDF_SCRYPT *)vctx;
if (ctx != NULL) {
OPENSSL_free(ctx->propq);
EVP_MD_free(ctx->sha256);
kdf_scrypt_reset(ctx);
OPENSSL_free(ctx);
}
}
static void kdf_scrypt_reset(void *vctx)
{
KDF_SCRYPT *ctx = (KDF_SCRYPT *)vctx;
OPENSSL_free(ctx->salt);
OPENSSL_clear_free(ctx->pass, ctx->pass_len);
kdf_scrypt_init(ctx);
}
static void *kdf_scrypt_dup(void *vctx)
{
const KDF_SCRYPT *src = (const KDF_SCRYPT *)vctx;
KDF_SCRYPT *dest;
dest = kdf_scrypt_new_inner(src->libctx);
if (dest != NULL) {
if (src->sha256 != NULL && !EVP_MD_up_ref(src->sha256))
goto err;
if (src->propq != NULL) {
dest->propq = OPENSSL_strdup(src->propq);
if (dest->propq == NULL)
goto err;
}
if (!ossl_prov_memdup(src->salt, src->salt_len,
&dest->salt, &dest->salt_len)
|| !ossl_prov_memdup(src->pass, src->pass_len,
&dest->pass , &dest->pass_len))
goto err;
dest->N = src->N;
dest->r = src->r;
dest->p = src->p;
dest->maxmem_bytes = src->maxmem_bytes;
dest->sha256 = src->sha256;
}
return dest;
err:
kdf_scrypt_free(dest);
return NULL;
}
static void kdf_scrypt_init(KDF_SCRYPT *ctx)
{
/* Default values are the most conservative recommendation given in the
* original paper of C. Percival. Derivation uses roughly 1 GiB of memory
* for this parameter choice (approx. 128 * r * N * p bytes).
*/
ctx->N = 1 << 20;
ctx->r = 8;
ctx->p = 1;
ctx->maxmem_bytes = 1025 * 1024 * 1024;
}
static int scrypt_set_membuf(unsigned char **buffer, size_t *buflen,
const OSSL_PARAM *p)
{
OPENSSL_clear_free(*buffer, *buflen);
*buffer = NULL;
*buflen = 0;
if (p->data_size == 0) {
if ((*buffer = OPENSSL_malloc(1)) == NULL)
return 0;
} else if (p->data != NULL) {
if (!OSSL_PARAM_get_octet_string(p, (void **)buffer, 0, buflen))
return 0;
}
return 1;
}
static int set_digest(KDF_SCRYPT *ctx)
{
EVP_MD_free(ctx->sha256);
ctx->sha256 = EVP_MD_fetch(ctx->libctx, "sha256", ctx->propq);
if (ctx->sha256 == NULL) {
OPENSSL_free(ctx);
ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_LOAD_SHA256);
return 0;
}
return 1;
}
static int set_property_query(KDF_SCRYPT *ctx, const char *propq)
{
OPENSSL_free(ctx->propq);
ctx->propq = NULL;
if (propq != NULL) {
ctx->propq = OPENSSL_strdup(propq);
if (ctx->propq == NULL)
return 0;
}
return 1;
}
static int kdf_scrypt_derive(void *vctx, unsigned char *key, size_t keylen,
const OSSL_PARAM params[])
{
KDF_SCRYPT *ctx = (KDF_SCRYPT *)vctx;
if (!ossl_prov_is_running() || !kdf_scrypt_set_ctx_params(ctx, params))
return 0;
if (ctx->pass == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_PASS);
return 0;
}
if (ctx->salt == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SALT);
return 0;
}
if (ctx->sha256 == NULL && !set_digest(ctx))
return 0;
return scrypt_alg((char *)ctx->pass, ctx->pass_len, ctx->salt,
ctx->salt_len, ctx->N, ctx->r, ctx->p,
ctx->maxmem_bytes, key, keylen, ctx->sha256,
ctx->libctx, ctx->propq);
}
static int is_power_of_two(uint64_t value)
{
return (value != 0) && ((value & (value - 1)) == 0);
}
static int kdf_scrypt_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
const OSSL_PARAM *p;
KDF_SCRYPT *ctx = vctx;
uint64_t u64_value;
if (params == NULL)
return 1;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_PASSWORD)) != NULL)
if (!scrypt_set_membuf(&ctx->pass, &ctx->pass_len, p))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SALT)) != NULL)
if (!scrypt_set_membuf(&ctx->salt, &ctx->salt_len, p))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SCRYPT_N))
!= NULL) {
if (!OSSL_PARAM_get_uint64(p, &u64_value)
|| u64_value <= 1
|| !is_power_of_two(u64_value))
return 0;
ctx->N = u64_value;
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SCRYPT_R))
!= NULL) {
if (!OSSL_PARAM_get_uint64(p, &u64_value) || u64_value < 1)
return 0;
ctx->r = u64_value;
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SCRYPT_P))
!= NULL) {
if (!OSSL_PARAM_get_uint64(p, &u64_value) || u64_value < 1)
return 0;
ctx->p = u64_value;
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SCRYPT_MAXMEM))
!= NULL) {
if (!OSSL_PARAM_get_uint64(p, &u64_value) || u64_value < 1)
return 0;
ctx->maxmem_bytes = u64_value;
}
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_PROPERTIES);
if (p != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING
|| !set_property_query(ctx, p->data)
|| !set_digest(ctx))
return 0;
}
return 1;
}
static const OSSL_PARAM *kdf_scrypt_settable_ctx_params(ossl_unused void *ctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_PASSWORD, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, NULL, 0),
OSSL_PARAM_uint64(OSSL_KDF_PARAM_SCRYPT_N, NULL),
OSSL_PARAM_uint32(OSSL_KDF_PARAM_SCRYPT_R, NULL),
OSSL_PARAM_uint32(OSSL_KDF_PARAM_SCRYPT_P, NULL),
OSSL_PARAM_uint64(OSSL_KDF_PARAM_SCRYPT_MAXMEM, NULL),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
static int kdf_scrypt_get_ctx_params(void *vctx, OSSL_PARAM params[])
{
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
return OSSL_PARAM_set_size_t(p, SIZE_MAX);
return -2;
}
static const OSSL_PARAM *kdf_scrypt_gettable_ctx_params(ossl_unused void *ctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
const OSSL_DISPATCH ossl_kdf_scrypt_functions[] = {
{ OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_scrypt_new },
{ OSSL_FUNC_KDF_DUPCTX, (void(*)(void))kdf_scrypt_dup },
{ OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_scrypt_free },
{ OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_scrypt_reset },
{ OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_scrypt_derive },
{ OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
(void(*)(void))kdf_scrypt_settable_ctx_params },
{ OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_scrypt_set_ctx_params },
{ OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
(void(*)(void))kdf_scrypt_gettable_ctx_params },
{ OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_scrypt_get_ctx_params },
OSSL_DISPATCH_END
};
#define R(a,b) (((a) << (b)) | ((a) >> (32 - (b))))
static void salsa208_word_specification(uint32_t inout[16])
{
int i;
uint32_t x[16];
memcpy(x, inout, sizeof(x));
for (i = 8; i > 0; i -= 2) {
x[4] ^= R(x[0] + x[12], 7);
x[8] ^= R(x[4] + x[0], 9);
x[12] ^= R(x[8] + x[4], 13);
x[0] ^= R(x[12] + x[8], 18);
x[9] ^= R(x[5] + x[1], 7);
x[13] ^= R(x[9] + x[5], 9);
x[1] ^= R(x[13] + x[9], 13);
x[5] ^= R(x[1] + x[13], 18);
x[14] ^= R(x[10] + x[6], 7);
x[2] ^= R(x[14] + x[10], 9);
x[6] ^= R(x[2] + x[14], 13);
x[10] ^= R(x[6] + x[2], 18);
x[3] ^= R(x[15] + x[11], 7);
x[7] ^= R(x[3] + x[15], 9);
x[11] ^= R(x[7] + x[3], 13);
x[15] ^= R(x[11] + x[7], 18);
x[1] ^= R(x[0] + x[3], 7);
x[2] ^= R(x[1] + x[0], 9);
x[3] ^= R(x[2] + x[1], 13);
x[0] ^= R(x[3] + x[2], 18);
x[6] ^= R(x[5] + x[4], 7);
x[7] ^= R(x[6] + x[5], 9);
x[4] ^= R(x[7] + x[6], 13);
x[5] ^= R(x[4] + x[7], 18);
x[11] ^= R(x[10] + x[9], 7);
x[8] ^= R(x[11] + x[10], 9);
x[9] ^= R(x[8] + x[11], 13);
x[10] ^= R(x[9] + x[8], 18);
x[12] ^= R(x[15] + x[14], 7);
x[13] ^= R(x[12] + x[15], 9);
x[14] ^= R(x[13] + x[12], 13);
x[15] ^= R(x[14] + x[13], 18);
}
for (i = 0; i < 16; ++i)
inout[i] += x[i];
OPENSSL_cleanse(x, sizeof(x));
}
static void scryptBlockMix(uint32_t *B_, uint32_t *B, uint64_t r)
{
uint64_t i, j;
uint32_t X[16], *pB;
memcpy(X, B + (r * 2 - 1) * 16, sizeof(X));
pB = B;
for (i = 0; i < r * 2; i++) {
for (j = 0; j < 16; j++)
X[j] ^= *pB++;
salsa208_word_specification(X);
memcpy(B_ + (i / 2 + (i & 1) * r) * 16, X, sizeof(X));
}
OPENSSL_cleanse(X, sizeof(X));
}
static void scryptROMix(unsigned char *B, uint64_t r, uint64_t N,
uint32_t *X, uint32_t *T, uint32_t *V)
{
unsigned char *pB;
uint32_t *pV;
uint64_t i, k;
/* Convert from little endian input */
for (pV = V, i = 0, pB = B; i < 32 * r; i++, pV++) {
*pV = *pB++;
*pV |= *pB++ << 8;
*pV |= *pB++ << 16;
*pV |= (uint32_t)*pB++ << 24;
}
for (i = 1; i < N; i++, pV += 32 * r)
scryptBlockMix(pV, pV - 32 * r, r);
scryptBlockMix(X, V + (N - 1) * 32 * r, r);
for (i = 0; i < N; i++) {
uint32_t j;
j = X[16 * (2 * r - 1)] % N;
pV = V + 32 * r * j;
for (k = 0; k < 32 * r; k++)
T[k] = X[k] ^ *pV++;
scryptBlockMix(X, T, r);
}
/* Convert output to little endian */
for (i = 0, pB = B; i < 32 * r; i++) {
uint32_t xtmp = X[i];
*pB++ = xtmp & 0xff;
*pB++ = (xtmp >> 8) & 0xff;
*pB++ = (xtmp >> 16) & 0xff;
*pB++ = (xtmp >> 24) & 0xff;
}
}
#ifndef SIZE_MAX
# define SIZE_MAX ((size_t)-1)
#endif
/*
* Maximum power of two that will fit in uint64_t: this should work on
* most (all?) platforms.
*/
#define LOG2_UINT64_MAX (sizeof(uint64_t) * 8 - 1)
/*
* Maximum value of p * r:
* p <= ((2^32-1) * hLen) / MFLen =>
* p <= ((2^32-1) * 32) / (128 * r) =>
* p * r <= (2^30-1)
*/
#define SCRYPT_PR_MAX ((1 << 30) - 1)
static int scrypt_alg(const char *pass, size_t passlen,
const unsigned char *salt, size_t saltlen,
uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem,
unsigned char *key, size_t keylen, EVP_MD *sha256,
OSSL_LIB_CTX *libctx, const char *propq)
{
int rv = 0;
unsigned char *B;
uint32_t *X, *V, *T;
uint64_t i, Blen, Vlen;
/* Sanity check parameters */
/* initial check, r,p must be non zero, N >= 2 and a power of 2 */
if (r == 0 || p == 0 || N < 2 || (N & (N - 1)))
return 0;
/* Check p * r < SCRYPT_PR_MAX avoiding overflow */
if (p > SCRYPT_PR_MAX / r) {
ERR_raise(ERR_LIB_EVP, EVP_R_MEMORY_LIMIT_EXCEEDED);
return 0;
}
/*
* Need to check N: if 2^(128 * r / 8) overflows limit this is
* automatically satisfied since N <= UINT64_MAX.
*/
if (16 * r <= LOG2_UINT64_MAX) {
if (N >= (((uint64_t)1) << (16 * r))) {
ERR_raise(ERR_LIB_EVP, EVP_R_MEMORY_LIMIT_EXCEEDED);
return 0;
}
}
/* Memory checks: check total allocated buffer size fits in uint64_t */
/*
* B size in section 5 step 1.S
* Note: we know p * 128 * r < UINT64_MAX because we already checked
* p * r < SCRYPT_PR_MAX
*/
Blen = p * 128 * r;
/*
* Yet we pass it as integer to PKCS5_PBKDF2_HMAC... [This would
* have to be revised when/if PKCS5_PBKDF2_HMAC accepts size_t.]
*/
if (Blen > INT_MAX) {
ERR_raise(ERR_LIB_EVP, EVP_R_MEMORY_LIMIT_EXCEEDED);
return 0;
}
/*
* Check 32 * r * (N + 2) * sizeof(uint32_t) fits in uint64_t
* This is combined size V, X and T (section 4)
*/
i = UINT64_MAX / (32 * sizeof(uint32_t));
if (N + 2 > i / r) {
ERR_raise(ERR_LIB_EVP, EVP_R_MEMORY_LIMIT_EXCEEDED);
return 0;
}
Vlen = 32 * r * (N + 2) * sizeof(uint32_t);
/* check total allocated size fits in uint64_t */
if (Blen > UINT64_MAX - Vlen) {
ERR_raise(ERR_LIB_EVP, EVP_R_MEMORY_LIMIT_EXCEEDED);
return 0;
}
/* Check that the maximum memory doesn't exceed a size_t limits */
if (maxmem > SIZE_MAX)
maxmem = SIZE_MAX;
if (Blen + Vlen > maxmem) {
ERR_raise(ERR_LIB_EVP, EVP_R_MEMORY_LIMIT_EXCEEDED);
return 0;
}
/* If no key return to indicate parameters are OK */
if (key == NULL)
return 1;
B = OPENSSL_malloc((size_t)(Blen + Vlen));
if (B == NULL)
return 0;
X = (uint32_t *)(B + Blen);
T = X + 32 * r;
V = T + 32 * r;
if (ossl_pkcs5_pbkdf2_hmac_ex(pass, passlen, salt, saltlen, 1, sha256,
(int)Blen, B, libctx, propq) == 0)
goto err;
for (i = 0; i < p; i++)
scryptROMix(B + 128 * r * i, r, N, X, T, V);
if (ossl_pkcs5_pbkdf2_hmac_ex(pass, passlen, B, (int)Blen, 1, sha256,
keylen, key, libctx, propq) == 0)
goto err;
rv = 1;
err:
if (rv == 0)
ERR_raise(ERR_LIB_EVP, EVP_R_PBKDF2_ERROR);
OPENSSL_clear_free(B, (size_t)(Blen + Vlen));
return rv;
}
#endif
| 16,286 | 28.666667 | 80 | c |
openssl | openssl-master/providers/implementations/kdfs/sshkdf.c | /*
* Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/core_names.h>
#include <openssl/proverr.h>
#include "internal/cryptlib.h"
#include "internal/numbers.h"
#include "crypto/evp.h"
#include "prov/provider_ctx.h"
#include "prov/providercommon.h"
#include "prov/implementations.h"
#include "prov/provider_util.h"
/* See RFC 4253, Section 7.2 */
static OSSL_FUNC_kdf_newctx_fn kdf_sshkdf_new;
static OSSL_FUNC_kdf_dupctx_fn kdf_sshkdf_dup;
static OSSL_FUNC_kdf_freectx_fn kdf_sshkdf_free;
static OSSL_FUNC_kdf_reset_fn kdf_sshkdf_reset;
static OSSL_FUNC_kdf_derive_fn kdf_sshkdf_derive;
static OSSL_FUNC_kdf_settable_ctx_params_fn kdf_sshkdf_settable_ctx_params;
static OSSL_FUNC_kdf_set_ctx_params_fn kdf_sshkdf_set_ctx_params;
static OSSL_FUNC_kdf_gettable_ctx_params_fn kdf_sshkdf_gettable_ctx_params;
static OSSL_FUNC_kdf_get_ctx_params_fn kdf_sshkdf_get_ctx_params;
static int SSHKDF(const EVP_MD *evp_md,
const unsigned char *key, size_t key_len,
const unsigned char *xcghash, size_t xcghash_len,
const unsigned char *session_id, size_t session_id_len,
char type, unsigned char *okey, size_t okey_len);
typedef struct {
void *provctx;
PROV_DIGEST digest;
unsigned char *key; /* K */
size_t key_len;
unsigned char *xcghash; /* H */
size_t xcghash_len;
char type; /* X */
unsigned char *session_id;
size_t session_id_len;
} KDF_SSHKDF;
static void *kdf_sshkdf_new(void *provctx)
{
KDF_SSHKDF *ctx;
if (!ossl_prov_is_running())
return NULL;
if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) != NULL)
ctx->provctx = provctx;
return ctx;
}
static void kdf_sshkdf_free(void *vctx)
{
KDF_SSHKDF *ctx = (KDF_SSHKDF *)vctx;
if (ctx != NULL) {
kdf_sshkdf_reset(ctx);
OPENSSL_free(ctx);
}
}
static void kdf_sshkdf_reset(void *vctx)
{
KDF_SSHKDF *ctx = (KDF_SSHKDF *)vctx;
void *provctx = ctx->provctx;
ossl_prov_digest_reset(&ctx->digest);
OPENSSL_clear_free(ctx->key, ctx->key_len);
OPENSSL_clear_free(ctx->xcghash, ctx->xcghash_len);
OPENSSL_clear_free(ctx->session_id, ctx->session_id_len);
memset(ctx, 0, sizeof(*ctx));
ctx->provctx = provctx;
}
static void *kdf_sshkdf_dup(void *vctx)
{
const KDF_SSHKDF *src = (const KDF_SSHKDF *)vctx;
KDF_SSHKDF *dest;
dest = kdf_sshkdf_new(src->provctx);
if (dest != NULL) {
if (!ossl_prov_memdup(src->key, src->key_len,
&dest->key, &dest->key_len)
|| !ossl_prov_memdup(src->xcghash, src->xcghash_len,
&dest->xcghash , &dest->xcghash_len)
|| !ossl_prov_memdup(src->session_id, src->session_id_len,
&dest->session_id , &dest->session_id_len)
|| !ossl_prov_digest_copy(&dest->digest, &src->digest))
goto err;
dest->type = src->type;
}
return dest;
err:
kdf_sshkdf_free(dest);
return NULL;
}
static int sshkdf_set_membuf(unsigned char **dst, size_t *dst_len,
const OSSL_PARAM *p)
{
OPENSSL_clear_free(*dst, *dst_len);
*dst = NULL;
*dst_len = 0;
return OSSL_PARAM_get_octet_string(p, (void **)dst, 0, dst_len);
}
static int kdf_sshkdf_derive(void *vctx, unsigned char *key, size_t keylen,
const OSSL_PARAM params[])
{
KDF_SSHKDF *ctx = (KDF_SSHKDF *)vctx;
const EVP_MD *md;
if (!ossl_prov_is_running() || !kdf_sshkdf_set_ctx_params(ctx, params))
return 0;
md = ossl_prov_digest_md(&ctx->digest);
if (md == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
return 0;
}
if (ctx->key == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_KEY);
return 0;
}
if (ctx->xcghash == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_XCGHASH);
return 0;
}
if (ctx->session_id == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SESSION_ID);
return 0;
}
if (ctx->type == 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_TYPE);
return 0;
}
return SSHKDF(md, ctx->key, ctx->key_len,
ctx->xcghash, ctx->xcghash_len,
ctx->session_id, ctx->session_id_len,
ctx->type, key, keylen);
}
static int kdf_sshkdf_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
const OSSL_PARAM *p;
KDF_SSHKDF *ctx = vctx;
OSSL_LIB_CTX *provctx = PROV_LIBCTX_OF(ctx->provctx);
if (params == NULL)
return 1;
if (!ossl_prov_digest_load_from_params(&ctx->digest, params, provctx))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KEY)) != NULL)
if (!sshkdf_set_membuf(&ctx->key, &ctx->key_len, p))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SSHKDF_XCGHASH))
!= NULL)
if (!sshkdf_set_membuf(&ctx->xcghash, &ctx->xcghash_len, p))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SSHKDF_SESSION_ID))
!= NULL)
if (!sshkdf_set_membuf(&ctx->session_id, &ctx->session_id_len, p))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SSHKDF_TYPE))
!= NULL) {
const char *kdftype;
if (!OSSL_PARAM_get_utf8_string_ptr(p, &kdftype))
return 0;
/* Expect one character (byte in this case) */
if (kdftype == NULL || p->data_size != 1)
return 0;
if (kdftype[0] < 65 || kdftype[0] > 70) {
ERR_raise(ERR_LIB_PROV, PROV_R_VALUE_ERROR);
return 0;
}
ctx->type = kdftype[0];
}
return 1;
}
static const OSSL_PARAM *kdf_sshkdf_settable_ctx_params(ossl_unused void *ctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SSHKDF_XCGHASH, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SSHKDF_SESSION_ID, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_SSHKDF_TYPE, NULL, 0),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
static int kdf_sshkdf_get_ctx_params(void *vctx, OSSL_PARAM params[])
{
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
return OSSL_PARAM_set_size_t(p, SIZE_MAX);
return -2;
}
static const OSSL_PARAM *kdf_sshkdf_gettable_ctx_params(ossl_unused void *ctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
const OSSL_DISPATCH ossl_kdf_sshkdf_functions[] = {
{ OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_sshkdf_new },
{ OSSL_FUNC_KDF_DUPCTX, (void(*)(void))kdf_sshkdf_dup },
{ OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_sshkdf_free },
{ OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_sshkdf_reset },
{ OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_sshkdf_derive },
{ OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
(void(*)(void))kdf_sshkdf_settable_ctx_params },
{ OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_sshkdf_set_ctx_params },
{ OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
(void(*)(void))kdf_sshkdf_gettable_ctx_params },
{ OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_sshkdf_get_ctx_params },
OSSL_DISPATCH_END
};
static int SSHKDF(const EVP_MD *evp_md,
const unsigned char *key, size_t key_len,
const unsigned char *xcghash, size_t xcghash_len,
const unsigned char *session_id, size_t session_id_len,
char type, unsigned char *okey, size_t okey_len)
{
EVP_MD_CTX *md = NULL;
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int dsize = 0;
size_t cursize = 0;
int ret = 0;
md = EVP_MD_CTX_new();
if (md == NULL)
return 0;
if (!EVP_DigestInit_ex(md, evp_md, NULL))
goto out;
if (!EVP_DigestUpdate(md, key, key_len))
goto out;
if (!EVP_DigestUpdate(md, xcghash, xcghash_len))
goto out;
if (!EVP_DigestUpdate(md, &type, 1))
goto out;
if (!EVP_DigestUpdate(md, session_id, session_id_len))
goto out;
if (!EVP_DigestFinal_ex(md, digest, &dsize))
goto out;
if (okey_len < dsize) {
memcpy(okey, digest, okey_len);
ret = 1;
goto out;
}
memcpy(okey, digest, dsize);
for (cursize = dsize; cursize < okey_len; cursize += dsize) {
if (!EVP_DigestInit_ex(md, evp_md, NULL))
goto out;
if (!EVP_DigestUpdate(md, key, key_len))
goto out;
if (!EVP_DigestUpdate(md, xcghash, xcghash_len))
goto out;
if (!EVP_DigestUpdate(md, okey, cursize))
goto out;
if (!EVP_DigestFinal_ex(md, digest, &dsize))
goto out;
if (okey_len < cursize + dsize) {
memcpy(okey + cursize, digest, okey_len - cursize);
ret = 1;
goto out;
}
memcpy(okey + cursize, digest, dsize);
}
ret = 1;
out:
EVP_MD_CTX_free(md);
OPENSSL_cleanse(digest, EVP_MAX_MD_SIZE);
return ret;
}
| 10,053 | 29.746177 | 80 | c |
openssl | openssl-master/providers/implementations/kdfs/sskdf.c | /*
* Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Refer to https://csrc.nist.gov/publications/detail/sp/800-56c/rev-1/final
* Section 4.1.
*
* The Single Step KDF algorithm is given by:
*
* Result(0) = empty bit string (i.e., the null string).
* For i = 1 to reps, do the following:
* Increment counter by 1.
* Result(i) = Result(i - 1) || H(counter || Z || FixedInfo).
* DKM = LeftmostBits(Result(reps), L))
*
* NOTES:
* Z is a shared secret required to produce the derived key material.
* counter is a 4 byte buffer.
* FixedInfo is a bit string containing context specific data.
* DKM is the output derived key material.
* L is the required size of the DKM.
* reps = [L / H_outputBits]
* H(x) is the auxiliary function that can be either a hash, HMAC or KMAC.
* H_outputBits is the length of the output of the auxiliary function H(x).
*
* Currently there is not a comprehensive list of test vectors for this
* algorithm, especially for H(x) = HMAC and H(x) = KMAC.
* Test vectors for H(x) = Hash are indirectly used by CAVS KAS tests.
*/
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/proverr.h>
#include "internal/cryptlib.h"
#include "internal/numbers.h"
#include "crypto/evp.h"
#include "prov/provider_ctx.h"
#include "prov/providercommon.h"
#include "prov/implementations.h"
#include "prov/provider_util.h"
#include "internal/params.h"
typedef struct {
void *provctx;
EVP_MAC_CTX *macctx; /* H(x) = HMAC_hash OR H(x) = KMAC */
PROV_DIGEST digest; /* H(x) = hash(x) */
unsigned char *secret;
size_t secret_len;
unsigned char *info;
size_t info_len;
unsigned char *salt;
size_t salt_len;
size_t out_len; /* optional KMAC parameter */
int is_kmac;
} KDF_SSKDF;
#define SSKDF_MAX_INLEN (1<<30)
#define SSKDF_KMAC128_DEFAULT_SALT_SIZE (168 - 4)
#define SSKDF_KMAC256_DEFAULT_SALT_SIZE (136 - 4)
/* KMAC uses a Customisation string of 'KDF' */
static const unsigned char kmac_custom_str[] = { 0x4B, 0x44, 0x46 };
static OSSL_FUNC_kdf_newctx_fn sskdf_new;
static OSSL_FUNC_kdf_dupctx_fn sskdf_dup;
static OSSL_FUNC_kdf_freectx_fn sskdf_free;
static OSSL_FUNC_kdf_reset_fn sskdf_reset;
static OSSL_FUNC_kdf_derive_fn sskdf_derive;
static OSSL_FUNC_kdf_derive_fn x963kdf_derive;
static OSSL_FUNC_kdf_settable_ctx_params_fn sskdf_settable_ctx_params;
static OSSL_FUNC_kdf_set_ctx_params_fn sskdf_set_ctx_params;
static OSSL_FUNC_kdf_gettable_ctx_params_fn sskdf_gettable_ctx_params;
static OSSL_FUNC_kdf_get_ctx_params_fn sskdf_get_ctx_params;
/*
* Refer to https://csrc.nist.gov/publications/detail/sp/800-56c/rev-1/final
* Section 4. One-Step Key Derivation using H(x) = hash(x)
* Note: X9.63 also uses this code with the only difference being that the
* counter is appended to the secret 'z'.
* i.e.
* result[i] = Hash(counter || z || info) for One Step OR
* result[i] = Hash(z || counter || info) for X9.63.
*/
static int SSKDF_hash_kdm(const EVP_MD *kdf_md,
const unsigned char *z, size_t z_len,
const unsigned char *info, size_t info_len,
unsigned int append_ctr,
unsigned char *derived_key, size_t derived_key_len)
{
int ret = 0, hlen;
size_t counter, out_len, len = derived_key_len;
unsigned char c[4];
unsigned char mac[EVP_MAX_MD_SIZE];
unsigned char *out = derived_key;
EVP_MD_CTX *ctx = NULL, *ctx_init = NULL;
if (z_len > SSKDF_MAX_INLEN || info_len > SSKDF_MAX_INLEN
|| derived_key_len > SSKDF_MAX_INLEN
|| derived_key_len == 0)
return 0;
hlen = EVP_MD_get_size(kdf_md);
if (hlen <= 0)
return 0;
out_len = (size_t)hlen;
ctx = EVP_MD_CTX_create();
ctx_init = EVP_MD_CTX_create();
if (ctx == NULL || ctx_init == NULL)
goto end;
if (!EVP_DigestInit(ctx_init, kdf_md))
goto end;
for (counter = 1;; counter++) {
c[0] = (unsigned char)((counter >> 24) & 0xff);
c[1] = (unsigned char)((counter >> 16) & 0xff);
c[2] = (unsigned char)((counter >> 8) & 0xff);
c[3] = (unsigned char)(counter & 0xff);
if (!(EVP_MD_CTX_copy_ex(ctx, ctx_init)
&& (append_ctr || EVP_DigestUpdate(ctx, c, sizeof(c)))
&& EVP_DigestUpdate(ctx, z, z_len)
&& (!append_ctr || EVP_DigestUpdate(ctx, c, sizeof(c)))
&& EVP_DigestUpdate(ctx, info, info_len)))
goto end;
if (len >= out_len) {
if (!EVP_DigestFinal_ex(ctx, out, NULL))
goto end;
out += out_len;
len -= out_len;
if (len == 0)
break;
} else {
if (!EVP_DigestFinal_ex(ctx, mac, NULL))
goto end;
memcpy(out, mac, len);
break;
}
}
ret = 1;
end:
EVP_MD_CTX_destroy(ctx);
EVP_MD_CTX_destroy(ctx_init);
OPENSSL_cleanse(mac, sizeof(mac));
return ret;
}
static int kmac_init(EVP_MAC_CTX *ctx, const unsigned char *custom,
size_t custom_len, size_t kmac_out_len,
size_t derived_key_len, unsigned char **out)
{
OSSL_PARAM params[2];
/* Only KMAC has custom data - so return if not KMAC */
if (custom == NULL)
return 1;
params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_CUSTOM,
(void *)custom, custom_len);
params[1] = OSSL_PARAM_construct_end();
if (!EVP_MAC_CTX_set_params(ctx, params))
return 0;
/* By default only do one iteration if kmac_out_len is not specified */
if (kmac_out_len == 0)
kmac_out_len = derived_key_len;
/* otherwise check the size is valid */
else if (!(kmac_out_len == derived_key_len
|| kmac_out_len == 20
|| kmac_out_len == 28
|| kmac_out_len == 32
|| kmac_out_len == 48
|| kmac_out_len == 64))
return 0;
params[0] = OSSL_PARAM_construct_size_t(OSSL_MAC_PARAM_SIZE,
&kmac_out_len);
if (EVP_MAC_CTX_set_params(ctx, params) <= 0)
return 0;
/*
* For kmac the output buffer can be larger than EVP_MAX_MD_SIZE: so
* alloc a buffer for this case.
*/
if (kmac_out_len > EVP_MAX_MD_SIZE) {
*out = OPENSSL_zalloc(kmac_out_len);
if (*out == NULL)
return 0;
}
return 1;
}
/*
* Refer to https://csrc.nist.gov/publications/detail/sp/800-56c/rev-1/final
* Section 4. One-Step Key Derivation using MAC: i.e either
* H(x) = HMAC-hash(salt, x) OR
* H(x) = KMAC#(salt, x, outbits, CustomString='KDF')
*/
static int SSKDF_mac_kdm(EVP_MAC_CTX *ctx_init,
const unsigned char *kmac_custom,
size_t kmac_custom_len, size_t kmac_out_len,
const unsigned char *salt, size_t salt_len,
const unsigned char *z, size_t z_len,
const unsigned char *info, size_t info_len,
unsigned char *derived_key, size_t derived_key_len)
{
int ret = 0;
size_t counter, out_len, len;
unsigned char c[4];
unsigned char mac_buf[EVP_MAX_MD_SIZE];
unsigned char *out = derived_key;
EVP_MAC_CTX *ctx = NULL;
unsigned char *mac = mac_buf, *kmac_buffer = NULL;
if (z_len > SSKDF_MAX_INLEN || info_len > SSKDF_MAX_INLEN
|| derived_key_len > SSKDF_MAX_INLEN
|| derived_key_len == 0)
return 0;
if (!kmac_init(ctx_init, kmac_custom, kmac_custom_len, kmac_out_len,
derived_key_len, &kmac_buffer))
goto end;
if (kmac_buffer != NULL)
mac = kmac_buffer;
if (!EVP_MAC_init(ctx_init, salt, salt_len, NULL))
goto end;
out_len = EVP_MAC_CTX_get_mac_size(ctx_init); /* output size */
if (out_len <= 0 || (mac == mac_buf && out_len > sizeof(mac_buf)))
goto end;
len = derived_key_len;
for (counter = 1;; counter++) {
c[0] = (unsigned char)((counter >> 24) & 0xff);
c[1] = (unsigned char)((counter >> 16) & 0xff);
c[2] = (unsigned char)((counter >> 8) & 0xff);
c[3] = (unsigned char)(counter & 0xff);
ctx = EVP_MAC_CTX_dup(ctx_init);
if (!(ctx != NULL
&& EVP_MAC_update(ctx, c, sizeof(c))
&& EVP_MAC_update(ctx, z, z_len)
&& EVP_MAC_update(ctx, info, info_len)))
goto end;
if (len >= out_len) {
if (!EVP_MAC_final(ctx, out, NULL, len))
goto end;
out += out_len;
len -= out_len;
if (len == 0)
break;
} else {
if (!EVP_MAC_final(ctx, mac, NULL, out_len))
goto end;
memcpy(out, mac, len);
break;
}
EVP_MAC_CTX_free(ctx);
ctx = NULL;
}
ret = 1;
end:
if (kmac_buffer != NULL)
OPENSSL_clear_free(kmac_buffer, kmac_out_len);
else
OPENSSL_cleanse(mac_buf, sizeof(mac_buf));
EVP_MAC_CTX_free(ctx);
return ret;
}
static void *sskdf_new(void *provctx)
{
KDF_SSKDF *ctx;
if (!ossl_prov_is_running())
return NULL;
if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) != NULL)
ctx->provctx = provctx;
return ctx;
}
static void sskdf_reset(void *vctx)
{
KDF_SSKDF *ctx = (KDF_SSKDF *)vctx;
void *provctx = ctx->provctx;
EVP_MAC_CTX_free(ctx->macctx);
ossl_prov_digest_reset(&ctx->digest);
OPENSSL_clear_free(ctx->secret, ctx->secret_len);
OPENSSL_clear_free(ctx->info, ctx->info_len);
OPENSSL_clear_free(ctx->salt, ctx->salt_len);
memset(ctx, 0, sizeof(*ctx));
ctx->provctx = provctx;
}
static void sskdf_free(void *vctx)
{
KDF_SSKDF *ctx = (KDF_SSKDF *)vctx;
if (ctx != NULL) {
sskdf_reset(ctx);
OPENSSL_free(ctx);
}
}
static void *sskdf_dup(void *vctx)
{
const KDF_SSKDF *src = (const KDF_SSKDF *)vctx;
KDF_SSKDF *dest;
dest = sskdf_new(src->provctx);
if (dest != NULL) {
if (src->macctx != NULL) {
dest->macctx = EVP_MAC_CTX_dup(src->macctx);
if (dest->macctx == NULL)
goto err;
}
if (!ossl_prov_memdup(src->info, src->info_len,
&dest->info, &dest->info_len)
|| !ossl_prov_memdup(src->salt, src->salt_len,
&dest->salt , &dest->salt_len)
|| !ossl_prov_memdup(src->secret, src->secret_len,
&dest->secret, &dest->secret_len)
|| !ossl_prov_digest_copy(&dest->digest, &src->digest))
goto err;
dest->out_len = src->out_len;
dest->is_kmac = src->is_kmac;
}
return dest;
err:
sskdf_free(dest);
return NULL;
}
static size_t sskdf_size(KDF_SSKDF *ctx)
{
int len;
const EVP_MD *md = NULL;
if (ctx->is_kmac)
return SIZE_MAX;
md = ossl_prov_digest_md(&ctx->digest);
if (md == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
return 0;
}
len = EVP_MD_get_size(md);
return (len <= 0) ? 0 : (size_t)len;
}
static int sskdf_derive(void *vctx, unsigned char *key, size_t keylen,
const OSSL_PARAM params[])
{
KDF_SSKDF *ctx = (KDF_SSKDF *)vctx;
const EVP_MD *md;
if (!ossl_prov_is_running() || !sskdf_set_ctx_params(ctx, params))
return 0;
if (ctx->secret == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SECRET);
return 0;
}
md = ossl_prov_digest_md(&ctx->digest);
if (ctx->macctx != NULL) {
/* H(x) = KMAC or H(x) = HMAC */
int ret;
const unsigned char *custom = NULL;
size_t custom_len = 0;
int default_salt_len;
EVP_MAC *mac = EVP_MAC_CTX_get0_mac(ctx->macctx);
if (EVP_MAC_is_a(mac, OSSL_MAC_NAME_HMAC)) {
/* H(x) = HMAC(x, salt, hash) */
if (md == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
return 0;
}
default_salt_len = EVP_MD_get_size(md);
if (default_salt_len <= 0)
return 0;
} else if (ctx->is_kmac) {
/* H(x) = KMACzzz(x, salt, custom) */
custom = kmac_custom_str;
custom_len = sizeof(kmac_custom_str);
if (EVP_MAC_is_a(mac, OSSL_MAC_NAME_KMAC128))
default_salt_len = SSKDF_KMAC128_DEFAULT_SALT_SIZE;
else
default_salt_len = SSKDF_KMAC256_DEFAULT_SALT_SIZE;
} else {
ERR_raise(ERR_LIB_PROV, PROV_R_UNSUPPORTED_MAC_TYPE);
return 0;
}
/* If no salt is set then use a default_salt of zeros */
if (ctx->salt == NULL || ctx->salt_len <= 0) {
ctx->salt = OPENSSL_zalloc(default_salt_len);
if (ctx->salt == NULL)
return 0;
ctx->salt_len = default_salt_len;
}
ret = SSKDF_mac_kdm(ctx->macctx,
custom, custom_len, ctx->out_len,
ctx->salt, ctx->salt_len,
ctx->secret, ctx->secret_len,
ctx->info, ctx->info_len, key, keylen);
return ret;
} else {
/* H(x) = hash */
if (md == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
return 0;
}
return SSKDF_hash_kdm(md, ctx->secret, ctx->secret_len,
ctx->info, ctx->info_len, 0, key, keylen);
}
}
static int x963kdf_derive(void *vctx, unsigned char *key, size_t keylen,
const OSSL_PARAM params[])
{
KDF_SSKDF *ctx = (KDF_SSKDF *)vctx;
const EVP_MD *md;
if (!ossl_prov_is_running() || !sskdf_set_ctx_params(ctx, params))
return 0;
if (ctx->secret == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SECRET);
return 0;
}
if (ctx->macctx != NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_NOT_SUPPORTED);
return 0;
}
/* H(x) = hash */
md = ossl_prov_digest_md(&ctx->digest);
if (md == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
return 0;
}
return SSKDF_hash_kdm(md, ctx->secret, ctx->secret_len,
ctx->info, ctx->info_len, 1, key, keylen);
}
static int sskdf_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
const OSSL_PARAM *p;
KDF_SSKDF *ctx = vctx;
OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
size_t sz;
int r;
if (params == NULL)
return 1;
if (!ossl_prov_macctx_load_from_params(&ctx->macctx, params,
NULL, NULL, NULL, libctx))
return 0;
if (ctx->macctx != NULL) {
if (EVP_MAC_is_a(EVP_MAC_CTX_get0_mac(ctx->macctx),
OSSL_MAC_NAME_KMAC128)
|| EVP_MAC_is_a(EVP_MAC_CTX_get0_mac(ctx->macctx),
OSSL_MAC_NAME_KMAC256)) {
ctx->is_kmac = 1;
}
}
if (!ossl_prov_digest_load_from_params(&ctx->digest, params, libctx))
return 0;
r = ossl_param_get1_octet_string(params, OSSL_KDF_PARAM_SECRET,
&ctx->secret, &ctx->secret_len);
if (r == -1)
r = ossl_param_get1_octet_string(params, OSSL_KDF_PARAM_KEY,
&ctx->secret, &ctx->secret_len);
if (r == 0)
return 0;
if (ossl_param_get1_concat_octet_string(params, OSSL_KDF_PARAM_INFO,
&ctx->info, &ctx->info_len, 0) == 0)
return 0;
if (ossl_param_get1_octet_string(params, OSSL_KDF_PARAM_SALT,
&ctx->salt, &ctx->salt_len) == 0)
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_MAC_SIZE))
!= NULL) {
if (!OSSL_PARAM_get_size_t(p, &sz) || sz == 0)
return 0;
ctx->out_len = sz;
}
return 1;
}
static const OSSL_PARAM *sskdf_settable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SECRET, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_INFO, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_MAC, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, NULL, 0),
OSSL_PARAM_size_t(OSSL_KDF_PARAM_MAC_SIZE, NULL),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
static int sskdf_get_ctx_params(void *vctx, OSSL_PARAM params[])
{
KDF_SSKDF *ctx = (KDF_SSKDF *)vctx;
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
return OSSL_PARAM_set_size_t(p, sskdf_size(ctx));
return -2;
}
static const OSSL_PARAM *sskdf_gettable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
const OSSL_DISPATCH ossl_kdf_sskdf_functions[] = {
{ OSSL_FUNC_KDF_NEWCTX, (void(*)(void))sskdf_new },
{ OSSL_FUNC_KDF_DUPCTX, (void(*)(void))sskdf_dup },
{ OSSL_FUNC_KDF_FREECTX, (void(*)(void))sskdf_free },
{ OSSL_FUNC_KDF_RESET, (void(*)(void))sskdf_reset },
{ OSSL_FUNC_KDF_DERIVE, (void(*)(void))sskdf_derive },
{ OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
(void(*)(void))sskdf_settable_ctx_params },
{ OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))sskdf_set_ctx_params },
{ OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
(void(*)(void))sskdf_gettable_ctx_params },
{ OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))sskdf_get_ctx_params },
OSSL_DISPATCH_END
};
const OSSL_DISPATCH ossl_kdf_x963_kdf_functions[] = {
{ OSSL_FUNC_KDF_NEWCTX, (void(*)(void))sskdf_new },
{ OSSL_FUNC_KDF_DUPCTX, (void(*)(void))sskdf_dup },
{ OSSL_FUNC_KDF_FREECTX, (void(*)(void))sskdf_free },
{ OSSL_FUNC_KDF_RESET, (void(*)(void))sskdf_reset },
{ OSSL_FUNC_KDF_DERIVE, (void(*)(void))x963kdf_derive },
{ OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
(void(*)(void))sskdf_settable_ctx_params },
{ OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))sskdf_set_ctx_params },
{ OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
(void(*)(void))sskdf_gettable_ctx_params },
{ OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))sskdf_get_ctx_params },
OSSL_DISPATCH_END
};
| 19,623 | 32.545299 | 80 | c |
openssl | openssl-master/providers/implementations/kdfs/tls1_prf.c | /*
* Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Refer to "The TLS Protocol Version 1.0" Section 5
* (https://tools.ietf.org/html/rfc2246#section-5) and
* "The Transport Layer Security (TLS) Protocol Version 1.2" Section 5
* (https://tools.ietf.org/html/rfc5246#section-5).
*
* For TLS v1.0 and TLS v1.1 the TLS PRF algorithm is given by:
*
* PRF(secret, label, seed) = P_MD5(S1, label + seed) XOR
* P_SHA-1(S2, label + seed)
*
* where P_MD5 and P_SHA-1 are defined by P_<hash>, below, and S1 and S2 are
* two halves of the secret (with the possibility of one shared byte, in the
* case where the length of the original secret is odd). S1 is taken from the
* first half of the secret, S2 from the second half.
*
* For TLS v1.2 the TLS PRF algorithm is given by:
*
* PRF(secret, label, seed) = P_<hash>(secret, label + seed)
*
* where hash is SHA-256 for all cipher suites defined in RFC 5246 as well as
* those published prior to TLS v1.2 while the TLS v1.2 protocol is in effect,
* unless defined otherwise by the cipher suite.
*
* P_<hash> is an expansion function that uses a single hash function to expand
* a secret and seed into an arbitrary quantity of output:
*
* P_<hash>(secret, seed) = HMAC_<hash>(secret, A(1) + seed) +
* HMAC_<hash>(secret, A(2) + seed) +
* HMAC_<hash>(secret, A(3) + seed) + ...
*
* where + indicates concatenation. P_<hash> can be iterated as many times as
* is necessary to produce the required quantity of data.
*
* A(i) is defined as:
* A(0) = seed
* A(i) = HMAC_<hash>(secret, A(i-1))
*/
/*
* Low level APIs (such as DH) are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/proverr.h>
#include "internal/cryptlib.h"
#include "internal/numbers.h"
#include "crypto/evp.h"
#include "prov/provider_ctx.h"
#include "prov/providercommon.h"
#include "prov/implementations.h"
#include "prov/provider_util.h"
#include "prov/securitycheck.h"
#include "internal/e_os.h"
static OSSL_FUNC_kdf_newctx_fn kdf_tls1_prf_new;
static OSSL_FUNC_kdf_dupctx_fn kdf_tls1_prf_dup;
static OSSL_FUNC_kdf_freectx_fn kdf_tls1_prf_free;
static OSSL_FUNC_kdf_reset_fn kdf_tls1_prf_reset;
static OSSL_FUNC_kdf_derive_fn kdf_tls1_prf_derive;
static OSSL_FUNC_kdf_settable_ctx_params_fn kdf_tls1_prf_settable_ctx_params;
static OSSL_FUNC_kdf_set_ctx_params_fn kdf_tls1_prf_set_ctx_params;
static OSSL_FUNC_kdf_gettable_ctx_params_fn kdf_tls1_prf_gettable_ctx_params;
static OSSL_FUNC_kdf_get_ctx_params_fn kdf_tls1_prf_get_ctx_params;
static int tls1_prf_alg(EVP_MAC_CTX *mdctx, EVP_MAC_CTX *sha1ctx,
const unsigned char *sec, size_t slen,
const unsigned char *seed, size_t seed_len,
unsigned char *out, size_t olen);
#define TLS1_PRF_MAXBUF 1024
#define TLS_MD_MASTER_SECRET_CONST "\x6d\x61\x73\x74\x65\x72\x20\x73\x65\x63\x72\x65\x74"
#define TLS_MD_MASTER_SECRET_CONST_SIZE 13
/* TLS KDF kdf context structure */
typedef struct {
void *provctx;
/* MAC context for the main digest */
EVP_MAC_CTX *P_hash;
/* MAC context for SHA1 for the MD5/SHA-1 combined PRF */
EVP_MAC_CTX *P_sha1;
/* Secret value to use for PRF */
unsigned char *sec;
size_t seclen;
/* Buffer of concatenated seed data */
unsigned char seed[TLS1_PRF_MAXBUF];
size_t seedlen;
} TLS1_PRF;
static void *kdf_tls1_prf_new(void *provctx)
{
TLS1_PRF *ctx;
if (!ossl_prov_is_running())
return NULL;
if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) != NULL)
ctx->provctx = provctx;
return ctx;
}
static void kdf_tls1_prf_free(void *vctx)
{
TLS1_PRF *ctx = (TLS1_PRF *)vctx;
if (ctx != NULL) {
kdf_tls1_prf_reset(ctx);
OPENSSL_free(ctx);
}
}
static void kdf_tls1_prf_reset(void *vctx)
{
TLS1_PRF *ctx = (TLS1_PRF *)vctx;
void *provctx = ctx->provctx;
EVP_MAC_CTX_free(ctx->P_hash);
EVP_MAC_CTX_free(ctx->P_sha1);
OPENSSL_clear_free(ctx->sec, ctx->seclen);
OPENSSL_cleanse(ctx->seed, ctx->seedlen);
memset(ctx, 0, sizeof(*ctx));
ctx->provctx = provctx;
}
static void *kdf_tls1_prf_dup(void *vctx)
{
const TLS1_PRF *src = (const TLS1_PRF *)vctx;
TLS1_PRF *dest;
dest = kdf_tls1_prf_new(src->provctx);
if (dest != NULL) {
if (src->P_hash != NULL
&& (dest->P_hash = EVP_MAC_CTX_dup(src->P_hash)) == NULL)
goto err;
if (src->P_sha1 != NULL
&& (dest->P_sha1 = EVP_MAC_CTX_dup(src->P_sha1)) == NULL)
goto err;
if (!ossl_prov_memdup(src->sec, src->seclen, &dest->sec, &dest->seclen))
goto err;
memcpy(dest->seed, src->seed, src->seedlen);
dest->seedlen = src->seedlen;
}
return dest;
err:
kdf_tls1_prf_free(dest);
return NULL;
}
static int kdf_tls1_prf_derive(void *vctx, unsigned char *key, size_t keylen,
const OSSL_PARAM params[])
{
TLS1_PRF *ctx = (TLS1_PRF *)vctx;
OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
if (!ossl_prov_is_running() || !kdf_tls1_prf_set_ctx_params(ctx, params))
return 0;
if (ctx->P_hash == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
return 0;
}
if (ctx->sec == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SECRET);
return 0;
}
if (ctx->seedlen == 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SEED);
return 0;
}
if (keylen == 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
return 0;
}
/*
* The seed buffer is prepended with a label.
* If EMS mode is enforced then the label "master secret" is not allowed,
* We do the check this way since the PRF is used for other purposes, as well
* as "extended master secret".
*/
if (ossl_tls1_prf_ems_check_enabled(libctx)) {
if (ctx->seedlen >= TLS_MD_MASTER_SECRET_CONST_SIZE
&& memcmp(ctx->seed, TLS_MD_MASTER_SECRET_CONST,
TLS_MD_MASTER_SECRET_CONST_SIZE) == 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_EMS_NOT_ENABLED);
return 0;
}
}
return tls1_prf_alg(ctx->P_hash, ctx->P_sha1,
ctx->sec, ctx->seclen,
ctx->seed, ctx->seedlen,
key, keylen);
}
static int kdf_tls1_prf_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
const OSSL_PARAM *p;
TLS1_PRF *ctx = vctx;
OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
if (params == NULL)
return 1;
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_DIGEST)) != NULL) {
if (OPENSSL_strcasecmp(p->data, SN_md5_sha1) == 0) {
if (!ossl_prov_macctx_load_from_params(&ctx->P_hash, params,
OSSL_MAC_NAME_HMAC,
NULL, SN_md5, libctx)
|| !ossl_prov_macctx_load_from_params(&ctx->P_sha1, params,
OSSL_MAC_NAME_HMAC,
NULL, SN_sha1, libctx))
return 0;
} else {
EVP_MAC_CTX_free(ctx->P_sha1);
if (!ossl_prov_macctx_load_from_params(&ctx->P_hash, params,
OSSL_MAC_NAME_HMAC,
NULL, NULL, libctx))
return 0;
}
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SECRET)) != NULL) {
OPENSSL_clear_free(ctx->sec, ctx->seclen);
ctx->sec = NULL;
if (!OSSL_PARAM_get_octet_string(p, (void **)&ctx->sec, 0, &ctx->seclen))
return 0;
}
/* The seed fields concatenate, so process them all */
if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SEED)) != NULL) {
for (; p != NULL; p = OSSL_PARAM_locate_const(p + 1,
OSSL_KDF_PARAM_SEED)) {
const void *q = ctx->seed + ctx->seedlen;
size_t sz = 0;
if (p->data_size != 0
&& p->data != NULL
&& !OSSL_PARAM_get_octet_string(p, (void **)&q,
TLS1_PRF_MAXBUF - ctx->seedlen,
&sz))
return 0;
ctx->seedlen += sz;
}
}
return 1;
}
static const OSSL_PARAM *kdf_tls1_prf_settable_ctx_params(
ossl_unused void *ctx, ossl_unused void *provctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SECRET, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SEED, NULL, 0),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
static int kdf_tls1_prf_get_ctx_params(void *vctx, OSSL_PARAM params[])
{
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
return OSSL_PARAM_set_size_t(p, SIZE_MAX);
return -2;
}
static const OSSL_PARAM *kdf_tls1_prf_gettable_ctx_params(
ossl_unused void *ctx, ossl_unused void *provctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
const OSSL_DISPATCH ossl_kdf_tls1_prf_functions[] = {
{ OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_tls1_prf_new },
{ OSSL_FUNC_KDF_DUPCTX, (void(*)(void))kdf_tls1_prf_dup },
{ OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_tls1_prf_free },
{ OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_tls1_prf_reset },
{ OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_tls1_prf_derive },
{ OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
(void(*)(void))kdf_tls1_prf_settable_ctx_params },
{ OSSL_FUNC_KDF_SET_CTX_PARAMS,
(void(*)(void))kdf_tls1_prf_set_ctx_params },
{ OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
(void(*)(void))kdf_tls1_prf_gettable_ctx_params },
{ OSSL_FUNC_KDF_GET_CTX_PARAMS,
(void(*)(void))kdf_tls1_prf_get_ctx_params },
OSSL_DISPATCH_END
};
/*
* Refer to "The TLS Protocol Version 1.0" Section 5
* (https://tools.ietf.org/html/rfc2246#section-5) and
* "The Transport Layer Security (TLS) Protocol Version 1.2" Section 5
* (https://tools.ietf.org/html/rfc5246#section-5).
*
* P_<hash> is an expansion function that uses a single hash function to expand
* a secret and seed into an arbitrary quantity of output:
*
* P_<hash>(secret, seed) = HMAC_<hash>(secret, A(1) + seed) +
* HMAC_<hash>(secret, A(2) + seed) +
* HMAC_<hash>(secret, A(3) + seed) + ...
*
* where + indicates concatenation. P_<hash> can be iterated as many times as
* is necessary to produce the required quantity of data.
*
* A(i) is defined as:
* A(0) = seed
* A(i) = HMAC_<hash>(secret, A(i-1))
*/
static int tls1_prf_P_hash(EVP_MAC_CTX *ctx_init,
const unsigned char *sec, size_t sec_len,
const unsigned char *seed, size_t seed_len,
unsigned char *out, size_t olen)
{
size_t chunk;
EVP_MAC_CTX *ctx = NULL, *ctx_Ai = NULL;
unsigned char Ai[EVP_MAX_MD_SIZE];
size_t Ai_len;
int ret = 0;
if (!EVP_MAC_init(ctx_init, sec, sec_len, NULL))
goto err;
chunk = EVP_MAC_CTX_get_mac_size(ctx_init);
if (chunk == 0)
goto err;
/* A(0) = seed */
ctx_Ai = EVP_MAC_CTX_dup(ctx_init);
if (ctx_Ai == NULL)
goto err;
if (seed != NULL && !EVP_MAC_update(ctx_Ai, seed, seed_len))
goto err;
for (;;) {
/* calc: A(i) = HMAC_<hash>(secret, A(i-1)) */
if (!EVP_MAC_final(ctx_Ai, Ai, &Ai_len, sizeof(Ai)))
goto err;
EVP_MAC_CTX_free(ctx_Ai);
ctx_Ai = NULL;
/* calc next chunk: HMAC_<hash>(secret, A(i) + seed) */
ctx = EVP_MAC_CTX_dup(ctx_init);
if (ctx == NULL)
goto err;
if (!EVP_MAC_update(ctx, Ai, Ai_len))
goto err;
/* save state for calculating next A(i) value */
if (olen > chunk) {
ctx_Ai = EVP_MAC_CTX_dup(ctx);
if (ctx_Ai == NULL)
goto err;
}
if (seed != NULL && !EVP_MAC_update(ctx, seed, seed_len))
goto err;
if (olen <= chunk) {
/* last chunk - use Ai as temp bounce buffer */
if (!EVP_MAC_final(ctx, Ai, &Ai_len, sizeof(Ai)))
goto err;
memcpy(out, Ai, olen);
break;
}
if (!EVP_MAC_final(ctx, out, NULL, olen))
goto err;
EVP_MAC_CTX_free(ctx);
ctx = NULL;
out += chunk;
olen -= chunk;
}
ret = 1;
err:
EVP_MAC_CTX_free(ctx);
EVP_MAC_CTX_free(ctx_Ai);
OPENSSL_cleanse(Ai, sizeof(Ai));
return ret;
}
/*
* Refer to "The TLS Protocol Version 1.0" Section 5
* (https://tools.ietf.org/html/rfc2246#section-5) and
* "The Transport Layer Security (TLS) Protocol Version 1.2" Section 5
* (https://tools.ietf.org/html/rfc5246#section-5).
*
* For TLS v1.0 and TLS v1.1:
*
* PRF(secret, label, seed) = P_MD5(S1, label + seed) XOR
* P_SHA-1(S2, label + seed)
*
* S1 is taken from the first half of the secret, S2 from the second half.
*
* L_S = length in bytes of secret;
* L_S1 = L_S2 = ceil(L_S / 2);
*
* For TLS v1.2:
*
* PRF(secret, label, seed) = P_<hash>(secret, label + seed)
*/
static int tls1_prf_alg(EVP_MAC_CTX *mdctx, EVP_MAC_CTX *sha1ctx,
const unsigned char *sec, size_t slen,
const unsigned char *seed, size_t seed_len,
unsigned char *out, size_t olen)
{
if (sha1ctx != NULL) {
/* TLS v1.0 and TLS v1.1 */
size_t i;
unsigned char *tmp;
/* calc: L_S1 = L_S2 = ceil(L_S / 2) */
size_t L_S1 = (slen + 1) / 2;
size_t L_S2 = L_S1;
if (!tls1_prf_P_hash(mdctx, sec, L_S1,
seed, seed_len, out, olen))
return 0;
if ((tmp = OPENSSL_malloc(olen)) == NULL)
return 0;
if (!tls1_prf_P_hash(sha1ctx, sec + slen - L_S2, L_S2,
seed, seed_len, tmp, olen)) {
OPENSSL_clear_free(tmp, olen);
return 0;
}
for (i = 0; i < olen; i++)
out[i] ^= tmp[i];
OPENSSL_clear_free(tmp, olen);
return 1;
}
/* TLS v1.2 */
if (!tls1_prf_P_hash(mdctx, sec, slen, seed, seed_len, out, olen))
return 0;
return 1;
}
| 15,527 | 32.756522 | 96 | c |
openssl | openssl-master/providers/implementations/kdfs/x942kdf.c | /*
* Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/e_os.h"
#include <openssl/core_names.h>
#include <openssl/core_dispatch.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/params.h>
#include <openssl/proverr.h>
#include "internal/packet.h"
#include "internal/der.h"
#include "internal/nelem.h"
#include "prov/provider_ctx.h"
#include "prov/providercommon.h"
#include "prov/implementations.h"
#include "prov/provider_util.h"
#include "prov/der_wrap.h"
#define X942KDF_MAX_INLEN (1 << 30)
static OSSL_FUNC_kdf_newctx_fn x942kdf_new;
static OSSL_FUNC_kdf_dupctx_fn x942kdf_dup;
static OSSL_FUNC_kdf_freectx_fn x942kdf_free;
static OSSL_FUNC_kdf_reset_fn x942kdf_reset;
static OSSL_FUNC_kdf_derive_fn x942kdf_derive;
static OSSL_FUNC_kdf_settable_ctx_params_fn x942kdf_settable_ctx_params;
static OSSL_FUNC_kdf_set_ctx_params_fn x942kdf_set_ctx_params;
static OSSL_FUNC_kdf_gettable_ctx_params_fn x942kdf_gettable_ctx_params;
static OSSL_FUNC_kdf_get_ctx_params_fn x942kdf_get_ctx_params;
typedef struct {
void *provctx;
PROV_DIGEST digest;
unsigned char *secret;
size_t secret_len;
unsigned char *acvpinfo;
size_t acvpinfo_len;
unsigned char *partyuinfo, *partyvinfo, *supp_pubinfo, *supp_privinfo;
size_t partyuinfo_len, partyvinfo_len, supp_pubinfo_len, supp_privinfo_len;
size_t dkm_len;
const unsigned char *cek_oid;
size_t cek_oid_len;
int use_keybits;
} KDF_X942;
/*
* A table of allowed wrapping algorithms, oids and the associated output
* lengths.
* NOTE: RC2wrap and camellia128_wrap have been removed as there are no
* corresponding ciphers for these operations.
*/
static const struct {
const char *name;
const unsigned char *oid;
size_t oid_len;
size_t keklen; /* size in bytes */
} kek_algs[] = {
{ "AES-128-WRAP", ossl_der_oid_id_aes128_wrap, DER_OID_SZ_id_aes128_wrap,
16 },
{ "AES-192-WRAP", ossl_der_oid_id_aes192_wrap, DER_OID_SZ_id_aes192_wrap,
24 },
{ "AES-256-WRAP", ossl_der_oid_id_aes256_wrap, DER_OID_SZ_id_aes256_wrap,
32 },
#ifndef FIPS_MODULE
{ "DES3-WRAP", ossl_der_oid_id_alg_CMS3DESwrap,
DER_OID_SZ_id_alg_CMS3DESwrap, 24 },
#endif
};
static int find_alg_id(OSSL_LIB_CTX *libctx, const char *algname,
const char *propq, size_t *id)
{
int ret = 1;
size_t i;
EVP_CIPHER *cipher;
cipher = EVP_CIPHER_fetch(libctx, algname, propq);
if (cipher != NULL) {
for (i = 0; i < OSSL_NELEM(kek_algs); i++) {
if (EVP_CIPHER_is_a(cipher, kek_algs[i].name)) {
*id = i;
goto end;
}
}
}
ret = 0;
ERR_raise(ERR_LIB_PROV, PROV_R_UNSUPPORTED_CEK_ALG);
end:
EVP_CIPHER_free(cipher);
return ret;
}
static int DER_w_keyinfo(WPACKET *pkt,
const unsigned char *der_oid, size_t der_oidlen,
unsigned char **pcounter)
{
return ossl_DER_w_begin_sequence(pkt, -1)
/* Store the initial value of 1 into the counter */
&& ossl_DER_w_octet_string_uint32(pkt, -1, 1)
/* Remember where we stored the counter in the buffer */
&& (pcounter == NULL
|| (*pcounter = WPACKET_get_curr(pkt)) != NULL)
&& ossl_DER_w_precompiled(pkt, -1, der_oid, der_oidlen)
&& ossl_DER_w_end_sequence(pkt, -1);
}
static int der_encode_sharedinfo(WPACKET *pkt, unsigned char *buf, size_t buflen,
const unsigned char *der_oid, size_t der_oidlen,
const unsigned char *acvp, size_t acvplen,
const unsigned char *partyu, size_t partyulen,
const unsigned char *partyv, size_t partyvlen,
const unsigned char *supp_pub, size_t supp_publen,
const unsigned char *supp_priv, size_t supp_privlen,
uint32_t keylen_bits, unsigned char **pcounter)
{
return (buf != NULL ? WPACKET_init_der(pkt, buf, buflen) :
WPACKET_init_null_der(pkt))
&& ossl_DER_w_begin_sequence(pkt, -1)
&& (supp_priv == NULL
|| ossl_DER_w_octet_string(pkt, 3, supp_priv, supp_privlen))
&& (supp_pub == NULL
|| ossl_DER_w_octet_string(pkt, 2, supp_pub, supp_publen))
&& (keylen_bits == 0
|| ossl_DER_w_octet_string_uint32(pkt, 2, keylen_bits))
&& (partyv == NULL || ossl_DER_w_octet_string(pkt, 1, partyv, partyvlen))
&& (partyu == NULL || ossl_DER_w_octet_string(pkt, 0, partyu, partyulen))
&& (acvp == NULL || ossl_DER_w_precompiled(pkt, -1, acvp, acvplen))
&& DER_w_keyinfo(pkt, der_oid, der_oidlen, pcounter)
&& ossl_DER_w_end_sequence(pkt, -1)
&& WPACKET_finish(pkt);
}
/*
* Encode the other info structure.
*
* The ANS X9.42-2003 standard uses OtherInfo:
*
* OtherInfo ::= SEQUENCE {
* keyInfo KeySpecificInfo,
* partyUInfo [0] OCTET STRING OPTIONAL,
* partyVInfo [1] OCTET STRING OPTIONAL,
* suppPubInfo [2] OCTET STRING OPTIONAL,
* suppPrivInfo [3] OCTET STRING OPTIONAL
* }
*
* KeySpecificInfo ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* counter OCTET STRING SIZE (4..4)
* }
*
* RFC2631 Section 2.1.2 Contains the following definition for OtherInfo
*
* OtherInfo ::= SEQUENCE {
* keyInfo KeySpecificInfo,
* partyAInfo [0] OCTET STRING OPTIONAL,
* suppPubInfo [2] OCTET STRING
* }
* Where suppPubInfo is the key length (in bits) (stored into 4 bytes)
*
* |keylen| is the length (in bytes) of the generated KEK. It is stored into
* suppPubInfo (in bits). It is ignored if the value is 0.
* |cek_oid| The oid of the key wrapping algorithm.
* |cek_oidlen| The length (in bytes) of the key wrapping algorithm oid,
* |acvp| is the optional blob of DER data representing one or more of the
* OtherInfo fields related to |partyu|, |partyv|, |supp_pub| and |supp_priv|.
* This field should normally be NULL. If |acvp| is non NULL then |partyu|,
* |partyv|, |supp_pub| and |supp_priv| should all be NULL.
* |acvp_len| is the |acvp| length (in bytes).
* |partyu| is the optional public info contributed by the initiator.
* It can be NULL. (It is also used as the ukm by CMS).
* |partyu_len| is the |partyu| length (in bytes).
* |partyv| is the optional public info contributed by the responder.
* It can be NULL.
* |partyv_len| is the |partyv| length (in bytes).
* |supp_pub| is the optional additional, mutually-known public information.
* It can be NULL. |keylen| should be 0 if this is not NULL.
* |supp_pub_len| is the |supp_pub| length (in bytes).
* |supp_priv| is the optional additional, mutually-known private information.
* It can be NULL.
* |supp_priv_len| is the |supp_priv| length (in bytes).
* |der| is the returned encoded data. It must be freed by the caller.
* |der_len| is the returned size of the encoded data.
* |out_ctr| returns a pointer to the counter data which is embedded inside the
* encoded data. This allows the counter bytes to be updated without
* re-encoding.
*
* Returns: 1 if successfully encoded, or 0 otherwise.
* Assumptions: |der|, |der_len| & |out_ctr| are not NULL.
*/
static int
x942_encode_otherinfo(size_t keylen,
const unsigned char *cek_oid, size_t cek_oid_len,
const unsigned char *acvp, size_t acvp_len,
const unsigned char *partyu, size_t partyu_len,
const unsigned char *partyv, size_t partyv_len,
const unsigned char *supp_pub, size_t supp_pub_len,
const unsigned char *supp_priv, size_t supp_priv_len,
unsigned char **der, size_t *der_len,
unsigned char **out_ctr)
{
int ret = 0;
unsigned char *pcounter = NULL, *der_buf = NULL;
size_t der_buflen = 0;
WPACKET pkt;
uint32_t keylen_bits;
/* keylenbits must fit into 4 bytes */
if (keylen > 0xFFFFFF)
return 0;
keylen_bits = 8 * keylen;
/* Calculate the size of the buffer */
if (!der_encode_sharedinfo(&pkt, NULL, 0, cek_oid, cek_oid_len,
acvp, acvp_len,
partyu, partyu_len, partyv, partyv_len,
supp_pub, supp_pub_len, supp_priv, supp_priv_len,
keylen_bits, NULL)
|| !WPACKET_get_total_written(&pkt, &der_buflen))
goto err;
WPACKET_cleanup(&pkt);
/* Alloc the buffer */
der_buf = OPENSSL_zalloc(der_buflen);
if (der_buf == NULL)
goto err;
/* Encode into the buffer */
if (!der_encode_sharedinfo(&pkt, der_buf, der_buflen, cek_oid, cek_oid_len,
acvp, acvp_len,
partyu, partyu_len, partyv, partyv_len,
supp_pub, supp_pub_len, supp_priv, supp_priv_len,
keylen_bits, &pcounter))
goto err;
/*
* Since we allocated the exact size required, the buffer should point to the
* start of the allocated buffer at this point.
*/
if (WPACKET_get_curr(&pkt) != der_buf)
goto err;
/*
* The data for the DER encoded octet string of a 32 bit counter = 1
* should be 04 04 00 00 00 01
* So just check the header is correct and skip over it.
* This counter will be incremented in the kdf update loop.
*/
if (pcounter == NULL
|| pcounter[0] != 0x04
|| pcounter[1] != 0x04)
goto err;
*out_ctr = (pcounter + 2);
*der = der_buf;
*der_len = der_buflen;
ret = 1;
err:
WPACKET_cleanup(&pkt);
return ret;
}
static int x942kdf_hash_kdm(const EVP_MD *kdf_md,
const unsigned char *z, size_t z_len,
const unsigned char *other, size_t other_len,
unsigned char *ctr,
unsigned char *derived_key, size_t derived_key_len)
{
int ret = 0, hlen;
size_t counter, out_len, len = derived_key_len;
unsigned char mac[EVP_MAX_MD_SIZE];
unsigned char *out = derived_key;
EVP_MD_CTX *ctx = NULL, *ctx_init = NULL;
if (z_len > X942KDF_MAX_INLEN
|| other_len > X942KDF_MAX_INLEN
|| derived_key_len > X942KDF_MAX_INLEN
|| derived_key_len == 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_BAD_LENGTH);
return 0;
}
hlen = EVP_MD_get_size(kdf_md);
if (hlen <= 0)
return 0;
out_len = (size_t)hlen;
ctx = EVP_MD_CTX_create();
ctx_init = EVP_MD_CTX_create();
if (ctx == NULL || ctx_init == NULL)
goto end;
if (!EVP_DigestInit(ctx_init, kdf_md))
goto end;
for (counter = 1;; counter++) {
/* updating the ctr modifies 4 bytes in the 'other' buffer */
ctr[0] = (unsigned char)((counter >> 24) & 0xff);
ctr[1] = (unsigned char)((counter >> 16) & 0xff);
ctr[2] = (unsigned char)((counter >> 8) & 0xff);
ctr[3] = (unsigned char)(counter & 0xff);
if (!EVP_MD_CTX_copy_ex(ctx, ctx_init)
|| !EVP_DigestUpdate(ctx, z, z_len)
|| !EVP_DigestUpdate(ctx, other, other_len))
goto end;
if (len >= out_len) {
if (!EVP_DigestFinal_ex(ctx, out, NULL))
goto end;
out += out_len;
len -= out_len;
if (len == 0)
break;
} else {
if (!EVP_DigestFinal_ex(ctx, mac, NULL))
goto end;
memcpy(out, mac, len);
break;
}
}
ret = 1;
end:
EVP_MD_CTX_free(ctx);
EVP_MD_CTX_free(ctx_init);
OPENSSL_cleanse(mac, sizeof(mac));
return ret;
}
static void *x942kdf_new(void *provctx)
{
KDF_X942 *ctx;
if (!ossl_prov_is_running())
return NULL;
if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL)
return NULL;
ctx->provctx = provctx;
ctx->use_keybits = 1;
return ctx;
}
static void x942kdf_reset(void *vctx)
{
KDF_X942 *ctx = (KDF_X942 *)vctx;
void *provctx = ctx->provctx;
ossl_prov_digest_reset(&ctx->digest);
OPENSSL_clear_free(ctx->secret, ctx->secret_len);
OPENSSL_clear_free(ctx->acvpinfo, ctx->acvpinfo_len);
OPENSSL_clear_free(ctx->partyuinfo, ctx->partyuinfo_len);
OPENSSL_clear_free(ctx->partyvinfo, ctx->partyvinfo_len);
OPENSSL_clear_free(ctx->supp_pubinfo, ctx->supp_pubinfo_len);
OPENSSL_clear_free(ctx->supp_privinfo, ctx->supp_privinfo_len);
memset(ctx, 0, sizeof(*ctx));
ctx->provctx = provctx;
ctx->use_keybits = 1;
}
static void x942kdf_free(void *vctx)
{
KDF_X942 *ctx = (KDF_X942 *)vctx;
if (ctx != NULL) {
x942kdf_reset(ctx);
OPENSSL_free(ctx);
}
}
static void *x942kdf_dup(void *vctx)
{
const KDF_X942 *src = (const KDF_X942 *)vctx;
KDF_X942 *dest;
dest = x942kdf_new(src->provctx);
if (dest != NULL) {
if (!ossl_prov_memdup(src->secret, src->secret_len,
&dest->secret , &dest->secret_len)
|| !ossl_prov_memdup(src->acvpinfo, src->acvpinfo_len,
&dest->acvpinfo , &dest->acvpinfo_len)
|| !ossl_prov_memdup(src->partyuinfo, src->partyuinfo_len,
&dest->partyuinfo , &dest->partyuinfo_len)
|| !ossl_prov_memdup(src->partyvinfo, src->partyvinfo_len,
&dest->partyvinfo , &dest->partyvinfo_len)
|| !ossl_prov_memdup(src->supp_pubinfo, src->supp_pubinfo_len,
&dest->supp_pubinfo,
&dest->supp_pubinfo_len)
|| !ossl_prov_memdup(src->supp_privinfo, src->supp_privinfo_len,
&dest->supp_privinfo,
&dest->supp_privinfo_len)
|| !ossl_prov_digest_copy(&dest->digest, &src->digest))
goto err;
dest->cek_oid = src->cek_oid;
dest->cek_oid_len = src->cek_oid_len;
dest->dkm_len = src->dkm_len;
dest->use_keybits = src->use_keybits;
}
return dest;
err:
x942kdf_free(dest);
return NULL;
}
static int x942kdf_set_buffer(unsigned char **out, size_t *out_len,
const OSSL_PARAM *p)
{
if (p->data_size == 0 || p->data == NULL)
return 1;
OPENSSL_free(*out);
*out = NULL;
return OSSL_PARAM_get_octet_string(p, (void **)out, 0, out_len);
}
static size_t x942kdf_size(KDF_X942 *ctx)
{
int len;
const EVP_MD *md = ossl_prov_digest_md(&ctx->digest);
if (md == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
return 0;
}
len = EVP_MD_get_size(md);
return (len <= 0) ? 0 : (size_t)len;
}
static int x942kdf_derive(void *vctx, unsigned char *key, size_t keylen,
const OSSL_PARAM params[])
{
KDF_X942 *ctx = (KDF_X942 *)vctx;
const EVP_MD *md;
int ret = 0;
unsigned char *ctr;
unsigned char *der = NULL;
size_t der_len = 0;
if (!ossl_prov_is_running() || !x942kdf_set_ctx_params(ctx, params))
return 0;
/*
* These 2 options encode to the same field so only one of them should be
* active at once.
*/
if (ctx->use_keybits && ctx->supp_pubinfo != NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_PUBINFO);
return 0;
}
/*
* If the blob of acvp data is used then the individual info fields that it
* replaces should not also be defined.
*/
if (ctx->acvpinfo != NULL
&& (ctx->partyuinfo != NULL
|| ctx->partyvinfo != NULL
|| ctx->supp_pubinfo != NULL
|| ctx->supp_privinfo != NULL)) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_DATA);
return 0;
}
if (ctx->secret == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SECRET);
return 0;
}
md = ossl_prov_digest_md(&ctx->digest);
if (md == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
return 0;
}
if (ctx->cek_oid == NULL || ctx->cek_oid_len == 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_CEK_ALG);
return 0;
}
if (ctx->partyuinfo != NULL && ctx->partyuinfo_len >= X942KDF_MAX_INLEN) {
/*
* Note the ukm length MUST be 512 bits if it is used.
* For backwards compatibility the old check is being done.
*/
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_UKM_LENGTH);
return 0;
}
/* generate the otherinfo der */
if (!x942_encode_otherinfo(ctx->use_keybits ? ctx->dkm_len : 0,
ctx->cek_oid, ctx->cek_oid_len,
ctx->acvpinfo, ctx->acvpinfo_len,
ctx->partyuinfo, ctx->partyuinfo_len,
ctx->partyvinfo, ctx->partyvinfo_len,
ctx->supp_pubinfo, ctx->supp_pubinfo_len,
ctx->supp_privinfo, ctx->supp_privinfo_len,
&der, &der_len, &ctr)) {
ERR_raise(ERR_LIB_PROV, PROV_R_BAD_ENCODING);
return 0;
}
ret = x942kdf_hash_kdm(md, ctx->secret, ctx->secret_len,
der, der_len, ctr, key, keylen);
OPENSSL_free(der);
return ret;
}
static int x942kdf_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
const OSSL_PARAM *p, *pq;
KDF_X942 *ctx = vctx;
OSSL_LIB_CTX *provctx = PROV_LIBCTX_OF(ctx->provctx);
const char *propq = NULL;
size_t id;
if (params == NULL)
return 1;
if (!ossl_prov_digest_load_from_params(&ctx->digest, params, provctx))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SECRET);
if (p == NULL)
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KEY);
if (p != NULL && !x942kdf_set_buffer(&ctx->secret, &ctx->secret_len, p))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_X942_ACVPINFO);
if (p != NULL
&& !x942kdf_set_buffer(&ctx->acvpinfo, &ctx->acvpinfo_len, p))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_X942_PARTYUINFO);
if (p == NULL)
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_UKM);
if (p != NULL
&& !x942kdf_set_buffer(&ctx->partyuinfo, &ctx->partyuinfo_len, p))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_X942_PARTYVINFO);
if (p != NULL
&& !x942kdf_set_buffer(&ctx->partyvinfo, &ctx->partyvinfo_len, p))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_X942_USE_KEYBITS);
if (p != NULL && !OSSL_PARAM_get_int(p, &ctx->use_keybits))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_X942_SUPP_PUBINFO);
if (p != NULL) {
if (!x942kdf_set_buffer(&ctx->supp_pubinfo, &ctx->supp_pubinfo_len, p))
return 0;
ctx->use_keybits = 0;
}
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_X942_SUPP_PRIVINFO);
if (p != NULL
&& !x942kdf_set_buffer(&ctx->supp_privinfo, &ctx->supp_privinfo_len, p))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_CEK_ALG);
if (p != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
pq = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_PROPERTIES);
/*
* We already grab the properties during ossl_prov_digest_load_from_params()
* so there is no need to check the validity again..
*/
if (pq != NULL)
propq = p->data;
if (find_alg_id(provctx, p->data, propq, &id) == 0)
return 0;
ctx->cek_oid = kek_algs[id].oid;
ctx->cek_oid_len = kek_algs[id].oid_len;
ctx->dkm_len = kek_algs[id].keklen;
}
return 1;
}
static const OSSL_PARAM *x942kdf_settable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SECRET, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_UKM, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_X942_ACVPINFO, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_X942_PARTYUINFO, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_X942_PARTYVINFO, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_X942_SUPP_PUBINFO, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KDF_PARAM_X942_SUPP_PRIVINFO, NULL, 0),
OSSL_PARAM_int(OSSL_KDF_PARAM_X942_USE_KEYBITS, NULL),
OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_CEK_ALG, NULL, 0),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
static int x942kdf_get_ctx_params(void *vctx, OSSL_PARAM params[])
{
KDF_X942 *ctx = (KDF_X942 *)vctx;
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
return OSSL_PARAM_set_size_t(p, x942kdf_size(ctx));
return -2;
}
static const OSSL_PARAM *x942kdf_gettable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
const OSSL_DISPATCH ossl_kdf_x942_kdf_functions[] = {
{ OSSL_FUNC_KDF_NEWCTX, (void(*)(void))x942kdf_new },
{ OSSL_FUNC_KDF_DUPCTX, (void(*)(void))x942kdf_dup },
{ OSSL_FUNC_KDF_FREECTX, (void(*)(void))x942kdf_free },
{ OSSL_FUNC_KDF_RESET, (void(*)(void))x942kdf_reset },
{ OSSL_FUNC_KDF_DERIVE, (void(*)(void))x942kdf_derive },
{ OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
(void(*)(void))x942kdf_settable_ctx_params },
{ OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))x942kdf_set_ctx_params },
{ OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
(void(*)(void))x942kdf_gettable_ctx_params },
{ OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))x942kdf_get_ctx_params },
OSSL_DISPATCH_END
};
| 23,034 | 35.505547 | 85 | c |
openssl | openssl-master/providers/implementations/kem/ecx_kem.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* The following implementation is part of RFC 9180 related to DHKEM using
* ECX keys (i.e. X25519 and X448)
* References to Sections in the comments below refer to RFC 9180.
*/
#include "internal/deprecated.h"
#include <string.h>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/kdf.h>
#include <openssl/err.h>
#include <openssl/sha.h>
#include <openssl/rand.h>
#include <openssl/proverr.h>
#include "prov/provider_ctx.h"
#include "prov/implementations.h"
#include "prov/securitycheck.h"
#include "prov/providercommon.h"
#include "prov/ecx.h"
#include "crypto/ecx.h"
#include <openssl/hpke.h>
#include "internal/hpke_util.h"
#include "eckem.h"
#define MAX_ECX_KEYLEN X448_KEYLEN
/* KEM identifiers from Section 7.1 "Table 2 KEM IDs" */
#define KEMID_X25519_HKDF_SHA256 0x20
#define KEMID_X448_HKDF_SHA512 0x21
/* ASCII: "KEM", in hex for EBCDIC compatibility */
static const char LABEL_KEM[] = "\x4b\x45\x4d";
typedef struct {
ECX_KEY *recipient_key;
ECX_KEY *sender_authkey;
OSSL_LIB_CTX *libctx;
char *propq;
unsigned int mode;
unsigned int op;
unsigned char *ikm;
size_t ikmlen;
const char *kdfname;
const OSSL_HPKE_KEM_INFO *info;
} PROV_ECX_CTX;
static OSSL_FUNC_kem_newctx_fn ecxkem_newctx;
static OSSL_FUNC_kem_encapsulate_init_fn ecxkem_encapsulate_init;
static OSSL_FUNC_kem_encapsulate_fn ecxkem_encapsulate;
static OSSL_FUNC_kem_decapsulate_init_fn ecxkem_decapsulate_init;
static OSSL_FUNC_kem_decapsulate_fn ecxkem_decapsulate;
static OSSL_FUNC_kem_freectx_fn ecxkem_freectx;
static OSSL_FUNC_kem_set_ctx_params_fn ecxkem_set_ctx_params;
static OSSL_FUNC_kem_auth_encapsulate_init_fn ecxkem_auth_encapsulate_init;
static OSSL_FUNC_kem_auth_decapsulate_init_fn ecxkem_auth_decapsulate_init;
/*
* Set KEM values as specified in Section 7.1 "Table 2 KEM IDs"
* There is only one set of values for X25519 and X448.
* Additional values could be set via set_params if required.
*/
static const OSSL_HPKE_KEM_INFO *get_kem_info(ECX_KEY *ecx)
{
const char *name = NULL;
if (ecx->type == ECX_KEY_TYPE_X25519)
name = SN_X25519;
else
name = SN_X448;
return ossl_HPKE_KEM_INFO_find_curve(name);
}
/*
* Set the recipient key, and free any existing key.
* ecx can be NULL. The ecx key may have only a private or public component.
*/
static int recipient_key_set(PROV_ECX_CTX *ctx, ECX_KEY *ecx)
{
ossl_ecx_key_free(ctx->recipient_key);
ctx->recipient_key = NULL;
if (ecx != NULL) {
ctx->info = get_kem_info(ecx);
if (ctx->info == NULL)
return -2;
ctx->kdfname = "HKDF";
if (!ossl_ecx_key_up_ref(ecx))
return 0;
ctx->recipient_key = ecx;
}
return 1;
}
/*
* Set the senders auth key, and free any existing auth key.
* ecx can be NULL.
*/
static int sender_authkey_set(PROV_ECX_CTX *ctx, ECX_KEY *ecx)
{
ossl_ecx_key_free(ctx->sender_authkey);
ctx->sender_authkey = NULL;
if (ecx != NULL) {
if (!ossl_ecx_key_up_ref(ecx))
return 0;
ctx->sender_authkey = ecx;
}
return 1;
}
/*
* Serialize a public key from byte array's for the encoded public keys.
* ctx is used to access the key type.
* Returns: The created ECX_KEY or NULL on error.
*/
static ECX_KEY *ecxkey_pubfromdata(PROV_ECX_CTX *ctx,
const unsigned char *pubbuf, size_t pubbuflen)
{
ECX_KEY *ecx = NULL;
OSSL_PARAM params[2], *p = params;
*p++ = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_PUB_KEY,
(char *)pubbuf, pubbuflen);
*p = OSSL_PARAM_construct_end();
ecx = ossl_ecx_key_new(ctx->libctx, ctx->recipient_key->type, 1, ctx->propq);
if (ecx == NULL)
return NULL;
if (ossl_ecx_key_fromdata(ecx, params, 0) <= 0) {
ossl_ecx_key_free(ecx);
ecx = NULL;
}
return ecx;
}
static unsigned char *ecx_pubkey(ECX_KEY *ecx)
{
if (ecx == NULL || !ecx->haspubkey) {
ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PUBLIC_KEY);
return 0;
}
return ecx->pubkey;
}
static void *ecxkem_newctx(void *provctx)
{
PROV_ECX_CTX *ctx = OPENSSL_zalloc(sizeof(PROV_ECX_CTX));
if (ctx == NULL)
return NULL;
ctx->libctx = PROV_LIBCTX_OF(provctx);
return ctx;
}
static void ecxkem_freectx(void *vectx)
{
PROV_ECX_CTX *ctx = (PROV_ECX_CTX *)vectx;
OPENSSL_clear_free(ctx->ikm, ctx->ikmlen);
recipient_key_set(ctx, NULL);
sender_authkey_set(ctx, NULL);
OPENSSL_free(ctx);
}
static int ecx_match_params(const ECX_KEY *key1, const ECX_KEY *key2)
{
return (key1->type == key2->type && key1->keylen == key2->keylen);
}
static int ecx_key_check(const ECX_KEY *ecx, int requires_privatekey)
{
if (ecx->privkey == NULL)
return (requires_privatekey == 0);
return 1;
}
static int ecxkem_init(void *vecxctx, int operation, void *vecx, void *vauth,
ossl_unused const OSSL_PARAM params[])
{
int rv;
PROV_ECX_CTX *ctx = (PROV_ECX_CTX *)vecxctx;
ECX_KEY *ecx = vecx;
ECX_KEY *auth = vauth;
if (!ossl_prov_is_running())
return 0;
if (!ecx_key_check(ecx, operation == EVP_PKEY_OP_DECAPSULATE))
return 0;
rv = recipient_key_set(ctx, ecx);
if (rv <= 0)
return rv;
if (auth != NULL) {
if (!ecx_match_params(auth, ctx->recipient_key)
|| !ecx_key_check(auth, operation == EVP_PKEY_OP_ENCAPSULATE)
|| !sender_authkey_set(ctx, auth))
return 0;
}
ctx->op = operation;
return ecxkem_set_ctx_params(vecxctx, params);
}
static int ecxkem_encapsulate_init(void *vecxctx, void *vecx,
const OSSL_PARAM params[])
{
return ecxkem_init(vecxctx, EVP_PKEY_OP_ENCAPSULATE, vecx, NULL, params);
}
static int ecxkem_decapsulate_init(void *vecxctx, void *vecx,
const OSSL_PARAM params[])
{
return ecxkem_init(vecxctx, EVP_PKEY_OP_DECAPSULATE, vecx, NULL, params);
}
static int ecxkem_auth_encapsulate_init(void *vctx, void *vecx, void *vauthpriv,
const OSSL_PARAM params[])
{
return ecxkem_init(vctx, EVP_PKEY_OP_ENCAPSULATE, vecx, vauthpriv, params);
}
static int ecxkem_auth_decapsulate_init(void *vctx, void *vecx, void *vauthpub,
const OSSL_PARAM params[])
{
return ecxkem_init(vctx, EVP_PKEY_OP_DECAPSULATE, vecx, vauthpub, params);
}
static int ecxkem_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
PROV_ECX_CTX *ctx = (PROV_ECX_CTX *)vctx;
const OSSL_PARAM *p;
int mode;
if (ctx == NULL)
return 0;
if (params == NULL)
return 1;
p = OSSL_PARAM_locate_const(params, OSSL_KEM_PARAM_IKME);
if (p != NULL) {
void *tmp = NULL;
size_t tmplen = 0;
if (p->data != NULL && p->data_size != 0) {
if (!OSSL_PARAM_get_octet_string(p, &tmp, 0, &tmplen))
return 0;
}
OPENSSL_clear_free(ctx->ikm, ctx->ikmlen);
ctx->ikm = tmp;
ctx->ikmlen = tmplen;
}
p = OSSL_PARAM_locate_const(params, OSSL_KEM_PARAM_OPERATION);
if (p != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
mode = ossl_eckem_modename2id(p->data);
if (mode == KEM_MODE_UNDEFINED)
return 0;
ctx->mode = mode;
}
return 1;
}
static const OSSL_PARAM known_settable_ecxkem_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_KEM_PARAM_OPERATION, NULL, 0),
OSSL_PARAM_octet_string(OSSL_KEM_PARAM_IKME, NULL, 0),
OSSL_PARAM_END
};
static const OSSL_PARAM *ecxkem_settable_ctx_params(ossl_unused void *vctx,
ossl_unused void *provctx)
{
return known_settable_ecxkem_ctx_params;
}
/*
* See Section 4.1 DH-Based KEM (DHKEM) ExtractAndExpand
*/
static int dhkem_extract_and_expand(EVP_KDF_CTX *kctx,
unsigned char *okm, size_t okmlen,
uint16_t kemid,
const unsigned char *dhkm, size_t dhkmlen,
const unsigned char *kemctx,
size_t kemctxlen)
{
uint8_t suiteid[2];
uint8_t prk[EVP_MAX_MD_SIZE];
size_t prklen = okmlen; /* Nh */
int ret;
if (prklen > sizeof(prk))
return 0;
suiteid[0] = (kemid >> 8) &0xff;
suiteid[1] = kemid & 0xff;
ret = ossl_hpke_labeled_extract(kctx, prk, prklen,
NULL, 0, LABEL_KEM, suiteid, sizeof(suiteid),
OSSL_DHKEM_LABEL_EAE_PRK, dhkm, dhkmlen)
&& ossl_hpke_labeled_expand(kctx, okm, okmlen, prk, prklen,
LABEL_KEM, suiteid, sizeof(suiteid),
OSSL_DHKEM_LABEL_SHARED_SECRET,
kemctx, kemctxlen);
OPENSSL_cleanse(prk, prklen);
return ret;
}
/*
* See Section 7.1.3 DeriveKeyPair.
*
* This function is used by ecx keygen.
* (For this reason it does not use any of the state stored in PROV_ECX_CTX).
*
* Params:
* ecx An initialized ecx key.
* privout The buffer to store the generated private key into (it is assumed
* this is of length ecx->keylen).
* ikm buffer containing the input key material (seed). This must be non NULL.
* ikmlen size of the ikm buffer in bytes
* Returns:
* 1 if successful or 0 otherwise.
*/
int ossl_ecx_dhkem_derive_private(ECX_KEY *ecx, unsigned char *privout,
const unsigned char *ikm, size_t ikmlen)
{
int ret = 0;
EVP_KDF_CTX *kdfctx = NULL;
unsigned char prk[EVP_MAX_MD_SIZE];
uint8_t suiteid[2];
const OSSL_HPKE_KEM_INFO *info = get_kem_info(ecx);
/* ikmlen should have a length of at least Nsk */
if (ikmlen < info->Nsk) {
ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_INPUT_LENGTH,
"ikm length is :%zu, should be at least %zu",
ikmlen, info->Nsk);
goto err;
}
kdfctx = ossl_kdf_ctx_create("HKDF", info->mdname, ecx->libctx, ecx->propq);
if (kdfctx == NULL)
return 0;
suiteid[0] = info->kem_id / 256;
suiteid[1] = info->kem_id % 256;
if (!ossl_hpke_labeled_extract(kdfctx, prk, info->Nsecret,
NULL, 0, LABEL_KEM, suiteid, sizeof(suiteid),
OSSL_DHKEM_LABEL_DKP_PRK, ikm, ikmlen))
goto err;
if (!ossl_hpke_labeled_expand(kdfctx, privout, info->Nsk, prk, info->Nsecret,
LABEL_KEM, suiteid, sizeof(suiteid),
OSSL_DHKEM_LABEL_SK, NULL, 0))
goto err;
ret = 1;
err:
OPENSSL_cleanse(prk, sizeof(prk));
EVP_KDF_CTX_free(kdfctx);
return ret;
}
/*
* Do a keygen operation without having to use EVP_PKEY.
* Params:
* ctx Context object
* ikm The seed material - if this is NULL, then a random seed is used.
* Returns:
* The generated ECX key, or NULL on failure.
*/
static ECX_KEY *derivekey(PROV_ECX_CTX *ctx,
const unsigned char *ikm, size_t ikmlen)
{
int ok = 0;
ECX_KEY *key;
unsigned char *privkey;
unsigned char *seed = (unsigned char *)ikm;
size_t seedlen = ikmlen;
unsigned char tmpbuf[OSSL_HPKE_MAX_PRIVATE];
const OSSL_HPKE_KEM_INFO *info = ctx->info;
key = ossl_ecx_key_new(ctx->libctx, ctx->recipient_key->type, 0, ctx->propq);
if (key == NULL)
return NULL;
privkey = ossl_ecx_key_allocate_privkey(key);
if (privkey == NULL)
goto err;
/* Generate a random seed if there is no input ikm */
if (seed == NULL || seedlen == 0) {
if (info->Nsk > sizeof(tmpbuf))
goto err;
if (RAND_priv_bytes_ex(ctx->libctx, tmpbuf, info->Nsk, 0) <= 0)
goto err;
seed = tmpbuf;
seedlen = info->Nsk;
}
if (!ossl_ecx_dhkem_derive_private(key, privkey, seed, seedlen))
goto err;
if (!ossl_ecx_public_from_private(key))
goto err;
key->haspubkey = 1;
ok = 1;
err:
if (!ok) {
ossl_ecx_key_free(key);
key = NULL;
}
if (seed != ikm)
OPENSSL_cleanse(seed, seedlen);
return key;
}
/*
* Do an ecxdh key exchange.
* dhkm = DH(sender, peer)
*
* NOTE: Instead of using EVP_PKEY_derive() API's, we use ECX_KEY operations
* to avoid messy conversions back to EVP_PKEY.
*
* Returns the size of the secret if successful, or 0 otherwise,
*/
static int generate_ecxdhkm(const ECX_KEY *sender, const ECX_KEY *peer,
unsigned char *out, size_t maxout,
unsigned int secretsz)
{
size_t len = 0;
/* NOTE: ossl_ecx_compute_key checks for shared secret being all zeros */
return ossl_ecx_compute_key((ECX_KEY *)peer, (ECX_KEY *)sender,
sender->keylen, out, &len, maxout);
}
/*
* Derive a secret using ECXDH (code is shared by the encap and decap)
*
* dhkm = Concat(ecxdh(privkey1, peerkey1), ecdh(privkey2, peerkey2)
* kemctx = Concat(sender_pub, recipient_pub, ctx->sender_authkey)
* secret = dhkem_extract_and_expand(kemid, dhkm, kemctx);
*
* Params:
* ctx Object that contains algorithm state and constants.
* secret The returned secret (with a length ctx->alg->secretlen bytes).
* privkey1 A private key used for ECXDH key derivation.
* peerkey1 A public key used for ECXDH key derivation with privkey1
* privkey2 A optional private key used for a second ECXDH key derivation.
* It can be NULL.
* peerkey2 A optional public key used for a second ECXDH key derivation
* with privkey2,. It can be NULL.
* sender_pub The senders public key in encoded form.
* recipient_pub The recipients public key in encoded form.
* Notes:
* The second ecdh() is only used for the HPKE auth modes when both privkey2
* and peerkey2 are non NULL (i.e. ctx->sender_authkey is not NULL).
*/
static int derive_secret(PROV_ECX_CTX *ctx, unsigned char *secret,
const ECX_KEY *privkey1, const ECX_KEY *peerkey1,
const ECX_KEY *privkey2, const ECX_KEY *peerkey2,
const unsigned char *sender_pub,
const unsigned char *recipient_pub)
{
int ret = 0;
EVP_KDF_CTX *kdfctx = NULL;
unsigned char *sender_authpub = NULL;
unsigned char dhkm[MAX_ECX_KEYLEN * 2];
unsigned char kemctx[MAX_ECX_KEYLEN * 3];
size_t kemctxlen = 0, dhkmlen = 0;
const OSSL_HPKE_KEM_INFO *info = ctx->info;
int auth = ctx->sender_authkey != NULL;
size_t encodedkeylen = info->Npk;
if (!generate_ecxdhkm(privkey1, peerkey1, dhkm, sizeof(dhkm), encodedkeylen))
goto err;
dhkmlen = encodedkeylen;
/* Concat the optional second ECXDH (used for Auth) */
if (auth) {
if (!generate_ecxdhkm(privkey2, peerkey2,
dhkm + dhkmlen, sizeof(dhkm) - dhkmlen,
encodedkeylen))
goto err;
/* Get the public key of the auth sender in encoded form */
sender_authpub = ecx_pubkey(ctx->sender_authkey);
if (sender_authpub == NULL)
goto err;
dhkmlen += encodedkeylen;
}
kemctxlen = encodedkeylen + dhkmlen;
if (kemctxlen > sizeof(kemctx))
goto err;
/* kemctx is the concat of both sides encoded public key */
memcpy(kemctx, sender_pub, encodedkeylen);
memcpy(kemctx + encodedkeylen, recipient_pub, encodedkeylen);
if (auth)
memcpy(kemctx + 2 * encodedkeylen, sender_authpub, encodedkeylen);
kdfctx = ossl_kdf_ctx_create(ctx->kdfname, info->mdname,
ctx->libctx, ctx->propq);
if (kdfctx == NULL)
goto err;
if (!dhkem_extract_and_expand(kdfctx, secret, info->Nsecret,
info->kem_id, dhkm, dhkmlen,
kemctx, kemctxlen))
goto err;
ret = 1;
err:
OPENSSL_cleanse(dhkm, dhkmlen);
EVP_KDF_CTX_free(kdfctx);
return ret;
}
/*
* Do a DHKEM encapsulate operation.
*
* See Section 4.1 Encap() and AuthEncap()
*
* Params:
* ctx A context object holding the recipients public key and the
* optional senders auth private key.
* enc A buffer to return the senders ephemeral public key.
* Setting this to NULL allows the enclen and secretlen to return
* values, without calculating the secret.
* enclen Passes in the max size of the enc buffer and returns the
* encoded public key length.
* secret A buffer to return the calculated shared secret.
* secretlen Passes in the max size of the secret buffer and returns the
* secret length.
* Returns: 1 on success or 0 otherwise.
*/
static int dhkem_encap(PROV_ECX_CTX *ctx,
unsigned char *enc, size_t *enclen,
unsigned char *secret, size_t *secretlen)
{
int ret = 0;
ECX_KEY *sender_ephemkey = NULL;
unsigned char *sender_ephempub, *recipient_pub;
const OSSL_HPKE_KEM_INFO *info = ctx->info;
if (enc == NULL) {
if (enclen == NULL && secretlen == NULL)
return 0;
if (enclen != NULL)
*enclen = info->Nenc;
if (secretlen != NULL)
*secretlen = info->Nsecret;
return 1;
}
if (*secretlen < info->Nsecret) {
ERR_raise_data(ERR_LIB_PROV, PROV_R_BAD_LENGTH, "*secretlen too small");
return 0;
}
if (*enclen < info->Nenc) {
ERR_raise_data(ERR_LIB_PROV, PROV_R_BAD_LENGTH, "*enclen too small");
return 0;
}
/* Create an ephemeral key */
sender_ephemkey = derivekey(ctx, ctx->ikm, ctx->ikmlen);
sender_ephempub = ecx_pubkey(sender_ephemkey);
recipient_pub = ecx_pubkey(ctx->recipient_key);
if (sender_ephempub == NULL || recipient_pub == NULL)
goto err;
if (!derive_secret(ctx, secret,
sender_ephemkey, ctx->recipient_key,
ctx->sender_authkey, ctx->recipient_key,
sender_ephempub, recipient_pub))
goto err;
/* Return the public part of the ephemeral key */
memcpy(enc, sender_ephempub, info->Nenc);
*enclen = info->Nenc;
*secretlen = info->Nsecret;
ret = 1;
err:
ossl_ecx_key_free(sender_ephemkey);
return ret;
}
/*
* Do a DHKEM decapsulate operation.
* See Section 4.1 Decap() and Auth Decap()
*
* Params:
* ctx A context object holding the recipients private key and the
* optional senders auth public key.
* secret A buffer to return the calculated shared secret. Setting this to
* NULL can be used to return the secretlen.
* secretlen Passes in the max size of the secret buffer and returns the
* secret length.
* enc A buffer containing the senders ephemeral public key that was returned
* from dhkem_encap().
* enclen The length in bytes of enc.
* Returns: 1 If the shared secret is returned or 0 on error.
*/
static int dhkem_decap(PROV_ECX_CTX *ctx,
unsigned char *secret, size_t *secretlen,
const unsigned char *enc, size_t enclen)
{
int ret = 0;
ECX_KEY *recipient_privkey = ctx->recipient_key;
ECX_KEY *sender_ephempubkey = NULL;
const OSSL_HPKE_KEM_INFO *info = ctx->info;
unsigned char *recipient_pub;
if (secret == NULL) {
*secretlen = info->Nsecret;
return 1;
}
if (*secretlen < info->Nsecret) {
ERR_raise_data(ERR_LIB_PROV, PROV_R_BAD_LENGTH, "*secretlen too small");
return 0;
}
if (enclen != info->Nenc) {
ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_KEY, "Invalid enc public key");
return 0;
}
/* Get the public part of the ephemeral key created by encap */
sender_ephempubkey = ecxkey_pubfromdata(ctx, enc, enclen);
if (sender_ephempubkey == NULL)
goto err;
recipient_pub = ecx_pubkey(recipient_privkey);
if (recipient_pub == NULL)
goto err;
if (!derive_secret(ctx, secret,
ctx->recipient_key, sender_ephempubkey,
ctx->recipient_key, ctx->sender_authkey,
enc, recipient_pub))
goto err;
*secretlen = info->Nsecret;
ret = 1;
err:
ossl_ecx_key_free(sender_ephempubkey);
return ret;
}
static int ecxkem_encapsulate(void *vctx, unsigned char *out, size_t *outlen,
unsigned char *secret, size_t *secretlen)
{
PROV_ECX_CTX *ctx = (PROV_ECX_CTX *)vctx;
switch (ctx->mode) {
case KEM_MODE_DHKEM:
return dhkem_encap(ctx, out, outlen, secret, secretlen);
default:
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
return -2;
}
}
static int ecxkem_decapsulate(void *vctx, unsigned char *out, size_t *outlen,
const unsigned char *in, size_t inlen)
{
PROV_ECX_CTX *ctx = (PROV_ECX_CTX *)vctx;
switch (ctx->mode) {
case KEM_MODE_DHKEM:
return dhkem_decap(vctx, out, outlen, in, inlen);
default:
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
return -2;
}
}
const OSSL_DISPATCH ossl_ecx_asym_kem_functions[] = {
{ OSSL_FUNC_KEM_NEWCTX, (void (*)(void))ecxkem_newctx },
{ OSSL_FUNC_KEM_ENCAPSULATE_INIT,
(void (*)(void))ecxkem_encapsulate_init },
{ OSSL_FUNC_KEM_ENCAPSULATE, (void (*)(void))ecxkem_encapsulate },
{ OSSL_FUNC_KEM_DECAPSULATE_INIT,
(void (*)(void))ecxkem_decapsulate_init },
{ OSSL_FUNC_KEM_DECAPSULATE, (void (*)(void))ecxkem_decapsulate },
{ OSSL_FUNC_KEM_FREECTX, (void (*)(void))ecxkem_freectx },
{ OSSL_FUNC_KEM_SET_CTX_PARAMS,
(void (*)(void))ecxkem_set_ctx_params },
{ OSSL_FUNC_KEM_SETTABLE_CTX_PARAMS,
(void (*)(void))ecxkem_settable_ctx_params },
{ OSSL_FUNC_KEM_AUTH_ENCAPSULATE_INIT,
(void (*)(void))ecxkem_auth_encapsulate_init },
{ OSSL_FUNC_KEM_AUTH_DECAPSULATE_INIT,
(void (*)(void))ecxkem_auth_decapsulate_init },
OSSL_DISPATCH_END
};
| 22,953 | 31.558865 | 83 | c |
openssl | openssl-master/providers/implementations/kem/kem_util.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h> /* for memcpy() */
#include <openssl/core_names.h>
#include <openssl/crypto.h>
#include "eckem.h"
typedef struct {
unsigned int id;
const char *mode;
} KEM_MODE;
static const KEM_MODE eckem_modename_id_map[] = {
{ KEM_MODE_DHKEM, OSSL_KEM_PARAM_OPERATION_DHKEM },
{ 0, NULL }
};
int ossl_eckem_modename2id(const char *name)
{
size_t i;
if (name == NULL)
return KEM_MODE_UNDEFINED;
for (i = 0; eckem_modename_id_map[i].mode != NULL; ++i) {
if (OPENSSL_strcasecmp(name, eckem_modename_id_map[i].mode) == 0)
return eckem_modename_id_map[i].id;
}
return KEM_MODE_UNDEFINED;
}
| 993 | 25.157895 | 74 | c |
openssl | openssl-master/providers/implementations/kem/rsa_kem.c | /*
* Copyright 2020-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* RSA low level APIs are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include "internal/nelem.h"
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/rsa.h>
#include <openssl/params.h>
#include <openssl/err.h>
#include "crypto/rsa.h"
#include <openssl/proverr.h>
#include "internal/nelem.h"
#include "prov/provider_ctx.h"
#include "prov/implementations.h"
#include "prov/securitycheck.h"
static OSSL_FUNC_kem_newctx_fn rsakem_newctx;
static OSSL_FUNC_kem_encapsulate_init_fn rsakem_encapsulate_init;
static OSSL_FUNC_kem_encapsulate_fn rsakem_generate;
static OSSL_FUNC_kem_decapsulate_init_fn rsakem_decapsulate_init;
static OSSL_FUNC_kem_decapsulate_fn rsakem_recover;
static OSSL_FUNC_kem_freectx_fn rsakem_freectx;
static OSSL_FUNC_kem_dupctx_fn rsakem_dupctx;
static OSSL_FUNC_kem_get_ctx_params_fn rsakem_get_ctx_params;
static OSSL_FUNC_kem_gettable_ctx_params_fn rsakem_gettable_ctx_params;
static OSSL_FUNC_kem_set_ctx_params_fn rsakem_set_ctx_params;
static OSSL_FUNC_kem_settable_ctx_params_fn rsakem_settable_ctx_params;
/*
* Only the KEM for RSASVE as defined in SP800-56b r2 is implemented
* currently.
*/
#define KEM_OP_UNDEFINED -1
#define KEM_OP_RSASVE 0
/*
* What's passed as an actual key is defined by the KEYMGMT interface.
* We happen to know that our KEYMGMT simply passes RSA structures, so
* we use that here too.
*/
typedef struct {
OSSL_LIB_CTX *libctx;
RSA *rsa;
int op;
} PROV_RSA_CTX;
static const OSSL_ITEM rsakem_opname_id_map[] = {
{ KEM_OP_RSASVE, OSSL_KEM_PARAM_OPERATION_RSASVE },
};
static int name2id(const char *name, const OSSL_ITEM *map, size_t sz)
{
size_t i;
if (name == NULL)
return -1;
for (i = 0; i < sz; ++i) {
if (OPENSSL_strcasecmp(map[i].ptr, name) == 0)
return map[i].id;
}
return -1;
}
static int rsakem_opname2id(const char *name)
{
return name2id(name, rsakem_opname_id_map, OSSL_NELEM(rsakem_opname_id_map));
}
static void *rsakem_newctx(void *provctx)
{
PROV_RSA_CTX *prsactx = OPENSSL_zalloc(sizeof(PROV_RSA_CTX));
if (prsactx == NULL)
return NULL;
prsactx->libctx = PROV_LIBCTX_OF(provctx);
prsactx->op = KEM_OP_UNDEFINED;
return prsactx;
}
static void rsakem_freectx(void *vprsactx)
{
PROV_RSA_CTX *prsactx = (PROV_RSA_CTX *)vprsactx;
RSA_free(prsactx->rsa);
OPENSSL_free(prsactx);
}
static void *rsakem_dupctx(void *vprsactx)
{
PROV_RSA_CTX *srcctx = (PROV_RSA_CTX *)vprsactx;
PROV_RSA_CTX *dstctx;
dstctx = OPENSSL_zalloc(sizeof(*srcctx));
if (dstctx == NULL)
return NULL;
*dstctx = *srcctx;
if (dstctx->rsa != NULL && !RSA_up_ref(dstctx->rsa)) {
OPENSSL_free(dstctx);
return NULL;
}
return dstctx;
}
static int rsakem_init(void *vprsactx, void *vrsa,
const OSSL_PARAM params[], int operation)
{
PROV_RSA_CTX *prsactx = (PROV_RSA_CTX *)vprsactx;
if (prsactx == NULL || vrsa == NULL)
return 0;
if (!ossl_rsa_check_key(prsactx->libctx, vrsa, operation))
return 0;
if (!RSA_up_ref(vrsa))
return 0;
RSA_free(prsactx->rsa);
prsactx->rsa = vrsa;
return rsakem_set_ctx_params(prsactx, params);
}
static int rsakem_encapsulate_init(void *vprsactx, void *vrsa,
const OSSL_PARAM params[])
{
return rsakem_init(vprsactx, vrsa, params, EVP_PKEY_OP_ENCAPSULATE);
}
static int rsakem_decapsulate_init(void *vprsactx, void *vrsa,
const OSSL_PARAM params[])
{
return rsakem_init(vprsactx, vrsa, params, EVP_PKEY_OP_DECAPSULATE);
}
static int rsakem_get_ctx_params(void *vprsactx, OSSL_PARAM *params)
{
PROV_RSA_CTX *ctx = (PROV_RSA_CTX *)vprsactx;
return ctx != NULL;
}
static const OSSL_PARAM known_gettable_rsakem_ctx_params[] = {
OSSL_PARAM_END
};
static const OSSL_PARAM *rsakem_gettable_ctx_params(ossl_unused void *vprsactx,
ossl_unused void *provctx)
{
return known_gettable_rsakem_ctx_params;
}
static int rsakem_set_ctx_params(void *vprsactx, const OSSL_PARAM params[])
{
PROV_RSA_CTX *prsactx = (PROV_RSA_CTX *)vprsactx;
const OSSL_PARAM *p;
int op;
if (prsactx == NULL)
return 0;
if (params == NULL)
return 1;
p = OSSL_PARAM_locate_const(params, OSSL_KEM_PARAM_OPERATION);
if (p != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
op = rsakem_opname2id(p->data);
if (op < 0)
return 0;
prsactx->op = op;
}
return 1;
}
static const OSSL_PARAM known_settable_rsakem_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_KEM_PARAM_OPERATION, NULL, 0),
OSSL_PARAM_END
};
static const OSSL_PARAM *rsakem_settable_ctx_params(ossl_unused void *vprsactx,
ossl_unused void *provctx)
{
return known_settable_rsakem_ctx_params;
}
/*
* NIST.SP.800-56Br2
* 7.2.1.2 RSASVE Generate Operation (RSASVE.GENERATE).
*
* Generate a random in the range 1 < z < (n – 1)
*/
static int rsasve_gen_rand_bytes(RSA *rsa_pub,
unsigned char *out, int outlen)
{
int ret = 0;
BN_CTX *bnctx;
BIGNUM *z, *nminus3;
bnctx = BN_CTX_secure_new_ex(ossl_rsa_get0_libctx(rsa_pub));
if (bnctx == NULL)
return 0;
/*
* Generate a random in the range 1 < z < (n – 1).
* Since BN_priv_rand_range_ex() returns a value in range 0 <= r < max
* We can achieve this by adding 2.. but then we need to subtract 3 from
* the upper bound i.e: 2 + (0 <= r < (n - 3))
*/
BN_CTX_start(bnctx);
nminus3 = BN_CTX_get(bnctx);
z = BN_CTX_get(bnctx);
ret = (z != NULL
&& (BN_copy(nminus3, RSA_get0_n(rsa_pub)) != NULL)
&& BN_sub_word(nminus3, 3)
&& BN_priv_rand_range_ex(z, nminus3, 0, bnctx)
&& BN_add_word(z, 2)
&& (BN_bn2binpad(z, out, outlen) == outlen));
BN_CTX_end(bnctx);
BN_CTX_free(bnctx);
return ret;
}
/*
* NIST.SP.800-56Br2
* 7.2.1.2 RSASVE Generate Operation (RSASVE.GENERATE).
*/
static int rsasve_generate(PROV_RSA_CTX *prsactx,
unsigned char *out, size_t *outlen,
unsigned char *secret, size_t *secretlen)
{
int ret;
size_t nlen;
/* Step (1): nlen = Ceil(len(n)/8) */
nlen = RSA_size(prsactx->rsa);
if (out == NULL) {
if (nlen == 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY);
return 0;
}
if (outlen == NULL && secretlen == NULL)
return 0;
if (outlen != NULL)
*outlen = nlen;
if (secretlen != NULL)
*secretlen = nlen;
return 1;
}
/*
* Step (2): Generate a random byte string z of nlen bytes where
* 1 < z < n - 1
*/
if (!rsasve_gen_rand_bytes(prsactx->rsa, secret, nlen))
return 0;
/* Step(3): out = RSAEP((n,e), z) */
ret = RSA_public_encrypt(nlen, secret, out, prsactx->rsa, RSA_NO_PADDING);
if (ret) {
ret = 1;
if (outlen != NULL)
*outlen = nlen;
if (secretlen != NULL)
*secretlen = nlen;
} else {
OPENSSL_cleanse(secret, nlen);
}
return ret;
}
/*
* NIST.SP.800-56Br2
* 7.2.1.3 RSASVE Recovery Operation (RSASVE.RECOVER).
*/
static int rsasve_recover(PROV_RSA_CTX *prsactx,
unsigned char *out, size_t *outlen,
const unsigned char *in, size_t inlen)
{
size_t nlen;
/* Step (1): get the byte length of n */
nlen = RSA_size(prsactx->rsa);
if (out == NULL) {
if (nlen == 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY);
return 0;
}
*outlen = nlen;
return 1;
}
/* Step (2): check the input ciphertext 'inlen' matches the nlen */
if (inlen != nlen) {
ERR_raise(ERR_LIB_PROV, PROV_R_BAD_LENGTH);
return 0;
}
/* Step (3): out = RSADP((n,d), in) */
return (RSA_private_decrypt(inlen, in, out, prsactx->rsa, RSA_NO_PADDING) > 0);
}
static int rsakem_generate(void *vprsactx, unsigned char *out, size_t *outlen,
unsigned char *secret, size_t *secretlen)
{
PROV_RSA_CTX *prsactx = (PROV_RSA_CTX *)vprsactx;
switch (prsactx->op) {
case KEM_OP_RSASVE:
return rsasve_generate(prsactx, out, outlen, secret, secretlen);
default:
return -2;
}
}
static int rsakem_recover(void *vprsactx, unsigned char *out, size_t *outlen,
const unsigned char *in, size_t inlen)
{
PROV_RSA_CTX *prsactx = (PROV_RSA_CTX *)vprsactx;
switch (prsactx->op) {
case KEM_OP_RSASVE:
return rsasve_recover(prsactx, out, outlen, in, inlen);
default:
return -2;
}
}
const OSSL_DISPATCH ossl_rsa_asym_kem_functions[] = {
{ OSSL_FUNC_KEM_NEWCTX, (void (*)(void))rsakem_newctx },
{ OSSL_FUNC_KEM_ENCAPSULATE_INIT,
(void (*)(void))rsakem_encapsulate_init },
{ OSSL_FUNC_KEM_ENCAPSULATE, (void (*)(void))rsakem_generate },
{ OSSL_FUNC_KEM_DECAPSULATE_INIT,
(void (*)(void))rsakem_decapsulate_init },
{ OSSL_FUNC_KEM_DECAPSULATE, (void (*)(void))rsakem_recover },
{ OSSL_FUNC_KEM_FREECTX, (void (*)(void))rsakem_freectx },
{ OSSL_FUNC_KEM_DUPCTX, (void (*)(void))rsakem_dupctx },
{ OSSL_FUNC_KEM_GET_CTX_PARAMS,
(void (*)(void))rsakem_get_ctx_params },
{ OSSL_FUNC_KEM_GETTABLE_CTX_PARAMS,
(void (*)(void))rsakem_gettable_ctx_params },
{ OSSL_FUNC_KEM_SET_CTX_PARAMS,
(void (*)(void))rsakem_set_ctx_params },
{ OSSL_FUNC_KEM_SETTABLE_CTX_PARAMS,
(void (*)(void))rsakem_settable_ctx_params },
OSSL_DISPATCH_END
};
| 10,379 | 27.360656 | 83 | c |
openssl | openssl-master/providers/implementations/keymgmt/dsa_kmgmt.c | /*
* Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* DSA low level APIs are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/bn.h>
#include <openssl/err.h>
#include "prov/providercommon.h"
#include "prov/implementations.h"
#include "prov/provider_ctx.h"
#include "crypto/dsa.h"
#include "internal/sizes.h"
#include "internal/nelem.h"
#include "internal/param_build_set.h"
static OSSL_FUNC_keymgmt_new_fn dsa_newdata;
static OSSL_FUNC_keymgmt_free_fn dsa_freedata;
static OSSL_FUNC_keymgmt_gen_init_fn dsa_gen_init;
static OSSL_FUNC_keymgmt_gen_set_template_fn dsa_gen_set_template;
static OSSL_FUNC_keymgmt_gen_set_params_fn dsa_gen_set_params;
static OSSL_FUNC_keymgmt_gen_settable_params_fn dsa_gen_settable_params;
static OSSL_FUNC_keymgmt_gen_fn dsa_gen;
static OSSL_FUNC_keymgmt_gen_cleanup_fn dsa_gen_cleanup;
static OSSL_FUNC_keymgmt_load_fn dsa_load;
static OSSL_FUNC_keymgmt_get_params_fn dsa_get_params;
static OSSL_FUNC_keymgmt_gettable_params_fn dsa_gettable_params;
static OSSL_FUNC_keymgmt_has_fn dsa_has;
static OSSL_FUNC_keymgmt_match_fn dsa_match;
static OSSL_FUNC_keymgmt_validate_fn dsa_validate;
static OSSL_FUNC_keymgmt_import_fn dsa_import;
static OSSL_FUNC_keymgmt_import_types_fn dsa_import_types;
static OSSL_FUNC_keymgmt_export_fn dsa_export;
static OSSL_FUNC_keymgmt_export_types_fn dsa_export_types;
static OSSL_FUNC_keymgmt_dup_fn dsa_dup;
#define DSA_DEFAULT_MD "SHA256"
#define DSA_POSSIBLE_SELECTIONS \
(OSSL_KEYMGMT_SELECT_KEYPAIR | OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS)
struct dsa_gen_ctx {
OSSL_LIB_CTX *libctx;
FFC_PARAMS *ffc_params;
int selection;
/* All these parameters are used for parameter generation only */
size_t pbits;
size_t qbits;
unsigned char *seed; /* optional FIPS186-4 param for testing */
size_t seedlen;
int gindex; /* optional FIPS186-4 generator index (ignored if -1) */
int gen_type; /* DSA_PARAMGEN_TYPE_FIPS_186_2 or DSA_PARAMGEN_TYPE_FIPS_186_4 */
int pcounter;
int hindex;
char *mdname;
char *mdprops;
OSSL_CALLBACK *cb;
void *cbarg;
};
typedef struct dh_name2id_st{
const char *name;
int id;
} DSA_GENTYPE_NAME2ID;
static const DSA_GENTYPE_NAME2ID dsatype2id[]=
{
#ifdef FIPS_MODULE
{ "default", DSA_PARAMGEN_TYPE_FIPS_186_4 },
#else
{ "default", DSA_PARAMGEN_TYPE_FIPS_DEFAULT },
#endif
{ "fips186_4", DSA_PARAMGEN_TYPE_FIPS_186_4 },
{ "fips186_2", DSA_PARAMGEN_TYPE_FIPS_186_2 },
};
static int dsa_gen_type_name2id(const char *name)
{
size_t i;
for (i = 0; i < OSSL_NELEM(dsatype2id); ++i) {
if (OPENSSL_strcasecmp(dsatype2id[i].name, name) == 0)
return dsatype2id[i].id;
}
return -1;
}
static int dsa_key_todata(DSA *dsa, OSSL_PARAM_BLD *bld, OSSL_PARAM params[],
int include_private)
{
const BIGNUM *priv = NULL, *pub = NULL;
if (dsa == NULL)
return 0;
DSA_get0_key(dsa, &pub, &priv);
if (include_private
&& priv != NULL
&& !ossl_param_build_set_bn(bld, params, OSSL_PKEY_PARAM_PRIV_KEY, priv))
return 0;
if (pub != NULL
&& !ossl_param_build_set_bn(bld, params, OSSL_PKEY_PARAM_PUB_KEY, pub))
return 0;
return 1;
}
static void *dsa_newdata(void *provctx)
{
if (!ossl_prov_is_running())
return NULL;
return ossl_dsa_new(PROV_LIBCTX_OF(provctx));
}
static void dsa_freedata(void *keydata)
{
DSA_free(keydata);
}
static int dsa_has(const void *keydata, int selection)
{
const DSA *dsa = keydata;
int ok = 1;
if (!ossl_prov_is_running() || dsa == NULL)
return 0;
if ((selection & DSA_POSSIBLE_SELECTIONS) == 0)
return 1; /* the selection is not missing */
if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)
ok = ok && (DSA_get0_pub_key(dsa) != NULL);
if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
ok = ok && (DSA_get0_priv_key(dsa) != NULL);
if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
ok = ok && (DSA_get0_p(dsa) != NULL && DSA_get0_g(dsa) != NULL);
return ok;
}
static int dsa_match(const void *keydata1, const void *keydata2, int selection)
{
const DSA *dsa1 = keydata1;
const DSA *dsa2 = keydata2;
int ok = 1;
if (!ossl_prov_is_running())
return 0;
if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) {
int key_checked = 0;
if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
const BIGNUM *pa = DSA_get0_pub_key(dsa1);
const BIGNUM *pb = DSA_get0_pub_key(dsa2);
if (pa != NULL && pb != NULL) {
ok = ok && BN_cmp(pa, pb) == 0;
key_checked = 1;
}
}
if (!key_checked
&& (selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
const BIGNUM *pa = DSA_get0_priv_key(dsa1);
const BIGNUM *pb = DSA_get0_priv_key(dsa2);
if (pa != NULL && pb != NULL) {
ok = ok && BN_cmp(pa, pb) == 0;
key_checked = 1;
}
}
ok = ok && key_checked;
}
if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0) {
FFC_PARAMS *dsaparams1 = ossl_dsa_get0_params((DSA *)dsa1);
FFC_PARAMS *dsaparams2 = ossl_dsa_get0_params((DSA *)dsa2);
ok = ok && ossl_ffc_params_cmp(dsaparams1, dsaparams2, 1);
}
return ok;
}
static int dsa_import(void *keydata, int selection, const OSSL_PARAM params[])
{
DSA *dsa = keydata;
int ok = 1;
if (!ossl_prov_is_running() || dsa == NULL)
return 0;
if ((selection & DSA_POSSIBLE_SELECTIONS) == 0)
return 0;
/* a key without parameters is meaningless */
ok = ok && ossl_dsa_ffc_params_fromdata(dsa, params);
if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) {
int include_private =
selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY ? 1 : 0;
ok = ok && ossl_dsa_key_fromdata(dsa, params, include_private);
}
return ok;
}
static int dsa_export(void *keydata, int selection, OSSL_CALLBACK *param_cb,
void *cbarg)
{
DSA *dsa = keydata;
OSSL_PARAM_BLD *tmpl;
OSSL_PARAM *params = NULL;
int ok = 1;
if (!ossl_prov_is_running() || dsa == NULL)
return 0;
tmpl = OSSL_PARAM_BLD_new();
if (tmpl == NULL)
return 0;
if ((selection & OSSL_KEYMGMT_SELECT_ALL_PARAMETERS) != 0)
ok = ok && ossl_ffc_params_todata(ossl_dsa_get0_params(dsa), tmpl, NULL);
if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) {
int include_private =
selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY ? 1 : 0;
ok = ok && dsa_key_todata(dsa, tmpl, NULL, include_private);
}
if (!ok || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
ok = 0;
goto err;
}
ok = param_cb(params, cbarg);
OSSL_PARAM_free(params);
err:
OSSL_PARAM_BLD_free(tmpl);
return ok;
}
/* IMEXPORT = IMPORT + EXPORT */
# define DSA_IMEXPORTABLE_PARAMETERS \
OSSL_PARAM_BN(OSSL_PKEY_PARAM_FFC_P, NULL, 0), \
OSSL_PARAM_BN(OSSL_PKEY_PARAM_FFC_Q, NULL, 0), \
OSSL_PARAM_BN(OSSL_PKEY_PARAM_FFC_G, NULL, 0), \
OSSL_PARAM_BN(OSSL_PKEY_PARAM_FFC_COFACTOR, NULL, 0), \
OSSL_PARAM_int(OSSL_PKEY_PARAM_FFC_GINDEX, NULL), \
OSSL_PARAM_int(OSSL_PKEY_PARAM_FFC_PCOUNTER, NULL), \
OSSL_PARAM_int(OSSL_PKEY_PARAM_FFC_H, NULL), \
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_FFC_SEED, NULL, 0)
# define DSA_IMEXPORTABLE_PUBLIC_KEY \
OSSL_PARAM_BN(OSSL_PKEY_PARAM_PUB_KEY, NULL, 0)
# define DSA_IMEXPORTABLE_PRIVATE_KEY \
OSSL_PARAM_BN(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0)
static const OSSL_PARAM dsa_all_types[] = {
DSA_IMEXPORTABLE_PARAMETERS,
DSA_IMEXPORTABLE_PUBLIC_KEY,
DSA_IMEXPORTABLE_PRIVATE_KEY,
OSSL_PARAM_END
};
static const OSSL_PARAM dsa_parameter_types[] = {
DSA_IMEXPORTABLE_PARAMETERS,
OSSL_PARAM_END
};
static const OSSL_PARAM dsa_key_types[] = {
DSA_IMEXPORTABLE_PUBLIC_KEY,
DSA_IMEXPORTABLE_PRIVATE_KEY,
OSSL_PARAM_END
};
static const OSSL_PARAM *dsa_types[] = {
NULL, /* Index 0 = none of them */
dsa_parameter_types, /* Index 1 = parameter types */
dsa_key_types, /* Index 2 = key types */
dsa_all_types /* Index 3 = 1 + 2 */
};
static const OSSL_PARAM *dsa_imexport_types(int selection)
{
int type_select = 0;
if ((selection & OSSL_KEYMGMT_SELECT_ALL_PARAMETERS) != 0)
type_select += 1;
if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0)
type_select += 2;
return dsa_types[type_select];
}
static const OSSL_PARAM *dsa_import_types(int selection)
{
return dsa_imexport_types(selection);
}
static const OSSL_PARAM *dsa_export_types(int selection)
{
return dsa_imexport_types(selection);
}
static ossl_inline int dsa_get_params(void *key, OSSL_PARAM params[])
{
DSA *dsa = key;
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_BITS)) != NULL
&& !OSSL_PARAM_set_int(p, DSA_bits(dsa)))
return 0;
if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_SECURITY_BITS)) != NULL
&& !OSSL_PARAM_set_int(p, DSA_security_bits(dsa)))
return 0;
if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_MAX_SIZE)) != NULL
&& !OSSL_PARAM_set_int(p, DSA_size(dsa)))
return 0;
if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_DEFAULT_DIGEST)) != NULL
&& !OSSL_PARAM_set_utf8_string(p, DSA_DEFAULT_MD))
return 0;
return ossl_ffc_params_todata(ossl_dsa_get0_params(dsa), NULL, params)
&& dsa_key_todata(dsa, NULL, params, 1);
}
static const OSSL_PARAM dsa_params[] = {
OSSL_PARAM_int(OSSL_PKEY_PARAM_BITS, NULL),
OSSL_PARAM_int(OSSL_PKEY_PARAM_SECURITY_BITS, NULL),
OSSL_PARAM_int(OSSL_PKEY_PARAM_MAX_SIZE, NULL),
OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_DEFAULT_DIGEST, NULL, 0),
DSA_IMEXPORTABLE_PARAMETERS,
DSA_IMEXPORTABLE_PUBLIC_KEY,
DSA_IMEXPORTABLE_PRIVATE_KEY,
OSSL_PARAM_END
};
static const OSSL_PARAM *dsa_gettable_params(void *provctx)
{
return dsa_params;
}
static int dsa_validate_domparams(const DSA *dsa, int checktype)
{
int status = 0;
return ossl_dsa_check_params(dsa, checktype, &status);
}
static int dsa_validate_public(const DSA *dsa)
{
int status = 0;
const BIGNUM *pub_key = NULL;
DSA_get0_key(dsa, &pub_key, NULL);
if (pub_key == NULL)
return 0;
return ossl_dsa_check_pub_key(dsa, pub_key, &status);
}
static int dsa_validate_private(const DSA *dsa)
{
int status = 0;
const BIGNUM *priv_key = NULL;
DSA_get0_key(dsa, NULL, &priv_key);
if (priv_key == NULL)
return 0;
return ossl_dsa_check_priv_key(dsa, priv_key, &status);
}
static int dsa_validate(const void *keydata, int selection, int checktype)
{
const DSA *dsa = keydata;
int ok = 1;
if (!ossl_prov_is_running())
return 0;
if ((selection & DSA_POSSIBLE_SELECTIONS) == 0)
return 1; /* nothing to validate */
if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
ok = ok && dsa_validate_domparams(dsa, checktype);
if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)
ok = ok && dsa_validate_public(dsa);
if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
ok = ok && dsa_validate_private(dsa);
/* If the whole key is selected, we do a pairwise validation */
if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR)
== OSSL_KEYMGMT_SELECT_KEYPAIR)
ok = ok && ossl_dsa_check_pairwise(dsa);
return ok;
}
static void *dsa_gen_init(void *provctx, int selection,
const OSSL_PARAM params[])
{
OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(provctx);
struct dsa_gen_ctx *gctx = NULL;
if (!ossl_prov_is_running() || (selection & DSA_POSSIBLE_SELECTIONS) == 0)
return NULL;
if ((gctx = OPENSSL_zalloc(sizeof(*gctx))) != NULL) {
gctx->selection = selection;
gctx->libctx = libctx;
gctx->pbits = 2048;
gctx->qbits = 224;
#ifdef FIPS_MODULE
gctx->gen_type = DSA_PARAMGEN_TYPE_FIPS_186_4;
#else
gctx->gen_type = DSA_PARAMGEN_TYPE_FIPS_DEFAULT;
#endif
gctx->gindex = -1;
gctx->pcounter = -1;
gctx->hindex = 0;
}
if (!dsa_gen_set_params(gctx, params)) {
OPENSSL_free(gctx);
gctx = NULL;
}
return gctx;
}
static int dsa_gen_set_template(void *genctx, void *templ)
{
struct dsa_gen_ctx *gctx = genctx;
DSA *dsa = templ;
if (!ossl_prov_is_running() || gctx == NULL || dsa == NULL)
return 0;
gctx->ffc_params = ossl_dsa_get0_params(dsa);
return 1;
}
static int dsa_set_gen_seed(struct dsa_gen_ctx *gctx, unsigned char *seed,
size_t seedlen)
{
OPENSSL_clear_free(gctx->seed, gctx->seedlen);
gctx->seed = NULL;
gctx->seedlen = 0;
if (seed != NULL && seedlen > 0) {
gctx->seed = OPENSSL_memdup(seed, seedlen);
if (gctx->seed == NULL)
return 0;
gctx->seedlen = seedlen;
}
return 1;
}
static int dsa_gen_set_params(void *genctx, const OSSL_PARAM params[])
{
struct dsa_gen_ctx *gctx = genctx;
const OSSL_PARAM *p;
if (gctx == NULL)
return 0;
if (params == NULL)
return 1;
p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_FFC_TYPE);
if (p != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING
|| ((gctx->gen_type = dsa_gen_type_name2id(p->data)) == -1)) {
ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT);
return 0;
}
}
p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_FFC_GINDEX);
if (p != NULL
&& !OSSL_PARAM_get_int(p, &gctx->gindex))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_FFC_PCOUNTER);
if (p != NULL
&& !OSSL_PARAM_get_int(p, &gctx->pcounter))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_FFC_H);
if (p != NULL
&& !OSSL_PARAM_get_int(p, &gctx->hindex))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_FFC_SEED);
if (p != NULL
&& (p->data_type != OSSL_PARAM_OCTET_STRING
|| !dsa_set_gen_seed(gctx, p->data, p->data_size)))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_FFC_PBITS)) != NULL
&& !OSSL_PARAM_get_size_t(p, &gctx->pbits))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_FFC_QBITS)) != NULL
&& !OSSL_PARAM_get_size_t(p, &gctx->qbits))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_FFC_DIGEST);
if (p != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
OPENSSL_free(gctx->mdname);
gctx->mdname = OPENSSL_strdup(p->data);
if (gctx->mdname == NULL)
return 0;
}
p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_FFC_DIGEST_PROPS);
if (p != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
OPENSSL_free(gctx->mdprops);
gctx->mdprops = OPENSSL_strdup(p->data);
if (gctx->mdprops == NULL)
return 0;
}
return 1;
}
static const OSSL_PARAM *dsa_gen_settable_params(ossl_unused void *genctx,
ossl_unused void *provctx)
{
static OSSL_PARAM settable[] = {
OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_FFC_TYPE, NULL, 0),
OSSL_PARAM_size_t(OSSL_PKEY_PARAM_FFC_PBITS, NULL),
OSSL_PARAM_size_t(OSSL_PKEY_PARAM_FFC_QBITS, NULL),
OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_FFC_DIGEST, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_FFC_DIGEST_PROPS, NULL, 0),
OSSL_PARAM_int(OSSL_PKEY_PARAM_FFC_GINDEX, NULL),
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_FFC_SEED, NULL, 0),
OSSL_PARAM_int(OSSL_PKEY_PARAM_FFC_PCOUNTER, NULL),
OSSL_PARAM_int(OSSL_PKEY_PARAM_FFC_H, NULL),
OSSL_PARAM_END
};
return settable;
}
static int dsa_gencb(int p, int n, BN_GENCB *cb)
{
struct dsa_gen_ctx *gctx = BN_GENCB_get_arg(cb);
OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END };
params[0] = OSSL_PARAM_construct_int(OSSL_GEN_PARAM_POTENTIAL, &p);
params[1] = OSSL_PARAM_construct_int(OSSL_GEN_PARAM_ITERATION, &n);
return gctx->cb(params, gctx->cbarg);
}
static void *dsa_gen(void *genctx, OSSL_CALLBACK *osslcb, void *cbarg)
{
struct dsa_gen_ctx *gctx = genctx;
DSA *dsa = NULL;
BN_GENCB *gencb = NULL;
int ret = 0;
FFC_PARAMS *ffc;
if (!ossl_prov_is_running() || gctx == NULL)
return NULL;
dsa = ossl_dsa_new(gctx->libctx);
if (dsa == NULL)
return NULL;
if (gctx->gen_type == DSA_PARAMGEN_TYPE_FIPS_DEFAULT)
gctx->gen_type = (gctx->pbits >= 2048 ? DSA_PARAMGEN_TYPE_FIPS_186_4 :
DSA_PARAMGEN_TYPE_FIPS_186_2);
gctx->cb = osslcb;
gctx->cbarg = cbarg;
gencb = BN_GENCB_new();
if (gencb != NULL)
BN_GENCB_set(gencb, dsa_gencb, genctx);
ffc = ossl_dsa_get0_params(dsa);
/* Copy the template value if one was passed */
if (gctx->ffc_params != NULL
&& !ossl_ffc_params_copy(ffc, gctx->ffc_params))
goto end;
if (gctx->seed != NULL
&& !ossl_ffc_params_set_seed(ffc, gctx->seed, gctx->seedlen))
goto end;
if (gctx->gindex != -1) {
ossl_ffc_params_set_gindex(ffc, gctx->gindex);
if (gctx->pcounter != -1)
ossl_ffc_params_set_pcounter(ffc, gctx->pcounter);
} else if (gctx->hindex != 0) {
ossl_ffc_params_set_h(ffc, gctx->hindex);
}
if (gctx->mdname != NULL)
ossl_ffc_set_digest(ffc, gctx->mdname, gctx->mdprops);
if ((gctx->selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0) {
if (ossl_dsa_generate_ffc_parameters(dsa, gctx->gen_type,
gctx->pbits, gctx->qbits,
gencb) <= 0)
goto end;
}
ossl_ffc_params_enable_flags(ffc, FFC_PARAM_FLAG_VALIDATE_LEGACY,
gctx->gen_type == DSA_PARAMGEN_TYPE_FIPS_186_2);
if ((gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) {
if (ffc->p == NULL
|| ffc->q == NULL
|| ffc->g == NULL)
goto end;
if (DSA_generate_key(dsa) <= 0)
goto end;
}
ret = 1;
end:
if (ret <= 0) {
DSA_free(dsa);
dsa = NULL;
}
BN_GENCB_free(gencb);
return dsa;
}
static void dsa_gen_cleanup(void *genctx)
{
struct dsa_gen_ctx *gctx = genctx;
if (gctx == NULL)
return;
OPENSSL_free(gctx->mdname);
OPENSSL_free(gctx->mdprops);
OPENSSL_clear_free(gctx->seed, gctx->seedlen);
OPENSSL_free(gctx);
}
static void *dsa_load(const void *reference, size_t reference_sz)
{
DSA *dsa = NULL;
if (ossl_prov_is_running() && reference_sz == sizeof(dsa)) {
/* The contents of the reference is the address to our object */
dsa = *(DSA **)reference;
/* We grabbed, so we detach it */
*(DSA **)reference = NULL;
return dsa;
}
return NULL;
}
static void *dsa_dup(const void *keydata_from, int selection)
{
if (ossl_prov_is_running())
return ossl_dsa_dup(keydata_from, selection);
return NULL;
}
const OSSL_DISPATCH ossl_dsa_keymgmt_functions[] = {
{ OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))dsa_newdata },
{ OSSL_FUNC_KEYMGMT_GEN_INIT, (void (*)(void))dsa_gen_init },
{ OSSL_FUNC_KEYMGMT_GEN_SET_TEMPLATE, (void (*)(void))dsa_gen_set_template },
{ OSSL_FUNC_KEYMGMT_GEN_SET_PARAMS, (void (*)(void))dsa_gen_set_params },
{ OSSL_FUNC_KEYMGMT_GEN_SETTABLE_PARAMS,
(void (*)(void))dsa_gen_settable_params },
{ OSSL_FUNC_KEYMGMT_GEN, (void (*)(void))dsa_gen },
{ OSSL_FUNC_KEYMGMT_GEN_CLEANUP, (void (*)(void))dsa_gen_cleanup },
{ OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))dsa_load },
{ OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))dsa_freedata },
{ OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*) (void))dsa_get_params },
{ OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*) (void))dsa_gettable_params },
{ OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))dsa_has },
{ OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))dsa_match },
{ OSSL_FUNC_KEYMGMT_VALIDATE, (void (*)(void))dsa_validate },
{ OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))dsa_import },
{ OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))dsa_import_types },
{ OSSL_FUNC_KEYMGMT_EXPORT, (void (*)(void))dsa_export },
{ OSSL_FUNC_KEYMGMT_EXPORT_TYPES, (void (*)(void))dsa_export_types },
{ OSSL_FUNC_KEYMGMT_DUP, (void (*)(void))dsa_dup },
OSSL_DISPATCH_END
};
| 21,726 | 31.093058 | 84 | c |
openssl | openssl-master/providers/implementations/keymgmt/kdf_legacy_kmgmt.c | /*
* Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* This implemments a dummy key manager for legacy KDFs that still support the
* old way of performing a KDF via EVP_PKEY_derive(). New KDFs should not be
* implemented this way. In reality there is no key data for such KDFs, so this
* key manager does very little.
*/
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/err.h>
#include "prov/implementations.h"
#include "prov/providercommon.h"
#include "prov/provider_ctx.h"
#include "prov/kdfexchange.h"
static OSSL_FUNC_keymgmt_new_fn kdf_newdata;
static OSSL_FUNC_keymgmt_free_fn kdf_freedata;
static OSSL_FUNC_keymgmt_has_fn kdf_has;
KDF_DATA *ossl_kdf_data_new(void *provctx)
{
KDF_DATA *kdfdata;
if (!ossl_prov_is_running())
return NULL;
kdfdata = OPENSSL_zalloc(sizeof(*kdfdata));
if (kdfdata == NULL)
return NULL;
if (!CRYPTO_NEW_REF(&kdfdata->refcnt, 1)) {
OPENSSL_free(kdfdata);
return NULL;
}
kdfdata->libctx = PROV_LIBCTX_OF(provctx);
return kdfdata;
}
void ossl_kdf_data_free(KDF_DATA *kdfdata)
{
int ref = 0;
if (kdfdata == NULL)
return;
CRYPTO_DOWN_REF(&kdfdata->refcnt, &ref);
if (ref > 0)
return;
CRYPTO_FREE_REF(&kdfdata->refcnt);
OPENSSL_free(kdfdata);
}
int ossl_kdf_data_up_ref(KDF_DATA *kdfdata)
{
int ref = 0;
/* This is effectively doing a new operation on the KDF_DATA and should be
* adequately guarded again modules' error states. However, both current
* calls here are guarded properly in exchange/kdf_exch.c. Thus, it
* could be removed here. The concern is that something in the future
* might call this function without adequate guards. It's a cheap call,
* it seems best to leave it even though it is currently redundant.
*/
if (!ossl_prov_is_running())
return 0;
CRYPTO_UP_REF(&kdfdata->refcnt, &ref);
return 1;
}
static void *kdf_newdata(void *provctx)
{
return ossl_kdf_data_new(provctx);
}
static void kdf_freedata(void *kdfdata)
{
ossl_kdf_data_free(kdfdata);
}
static int kdf_has(const void *keydata, int selection)
{
return 1; /* nothing is missing */
}
const OSSL_DISPATCH ossl_kdf_keymgmt_functions[] = {
{ OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))kdf_newdata },
{ OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))kdf_freedata },
{ OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))kdf_has },
OSSL_DISPATCH_END
};
| 2,773 | 25.932039 | 79 | c |
openssl | openssl-master/providers/implementations/keymgmt/mac_legacy_kmgmt.c | /*
* Copyright 2020-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* We need to use some engine deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <string.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/proverr.h>
#include <openssl/param_build.h>
#ifndef FIPS_MODULE
# include <openssl/engine.h>
#endif
#include "internal/param_build_set.h"
#include "prov/implementations.h"
#include "prov/providercommon.h"
#include "prov/provider_ctx.h"
#include "prov/macsignature.h"
static OSSL_FUNC_keymgmt_new_fn mac_new;
static OSSL_FUNC_keymgmt_free_fn mac_free;
static OSSL_FUNC_keymgmt_gen_init_fn mac_gen_init;
static OSSL_FUNC_keymgmt_gen_fn mac_gen;
static OSSL_FUNC_keymgmt_gen_cleanup_fn mac_gen_cleanup;
static OSSL_FUNC_keymgmt_gen_set_params_fn mac_gen_set_params;
static OSSL_FUNC_keymgmt_gen_settable_params_fn mac_gen_settable_params;
static OSSL_FUNC_keymgmt_get_params_fn mac_get_params;
static OSSL_FUNC_keymgmt_gettable_params_fn mac_gettable_params;
static OSSL_FUNC_keymgmt_set_params_fn mac_set_params;
static OSSL_FUNC_keymgmt_settable_params_fn mac_settable_params;
static OSSL_FUNC_keymgmt_has_fn mac_has;
static OSSL_FUNC_keymgmt_match_fn mac_match;
static OSSL_FUNC_keymgmt_import_fn mac_import;
static OSSL_FUNC_keymgmt_import_types_fn mac_imexport_types;
static OSSL_FUNC_keymgmt_export_fn mac_export;
static OSSL_FUNC_keymgmt_export_types_fn mac_imexport_types;
static OSSL_FUNC_keymgmt_new_fn mac_new_cmac;
static OSSL_FUNC_keymgmt_gettable_params_fn cmac_gettable_params;
static OSSL_FUNC_keymgmt_import_types_fn cmac_imexport_types;
static OSSL_FUNC_keymgmt_export_types_fn cmac_imexport_types;
static OSSL_FUNC_keymgmt_gen_init_fn cmac_gen_init;
static OSSL_FUNC_keymgmt_gen_set_params_fn cmac_gen_set_params;
static OSSL_FUNC_keymgmt_gen_settable_params_fn cmac_gen_settable_params;
struct mac_gen_ctx {
OSSL_LIB_CTX *libctx;
int selection;
unsigned char *priv_key;
size_t priv_key_len;
PROV_CIPHER cipher;
};
MAC_KEY *ossl_mac_key_new(OSSL_LIB_CTX *libctx, int cmac)
{
MAC_KEY *mackey;
if (!ossl_prov_is_running())
return NULL;
mackey = OPENSSL_zalloc(sizeof(*mackey));
if (mackey == NULL)
return NULL;
if (!CRYPTO_NEW_REF(&mackey->refcnt, 1)) {
OPENSSL_free(mackey);
return NULL;
}
mackey->libctx = libctx;
mackey->cmac = cmac;
return mackey;
}
void ossl_mac_key_free(MAC_KEY *mackey)
{
int ref = 0;
if (mackey == NULL)
return;
CRYPTO_DOWN_REF(&mackey->refcnt, &ref);
if (ref > 0)
return;
OPENSSL_secure_clear_free(mackey->priv_key, mackey->priv_key_len);
OPENSSL_free(mackey->properties);
ossl_prov_cipher_reset(&mackey->cipher);
CRYPTO_FREE_REF(&mackey->refcnt);
OPENSSL_free(mackey);
}
int ossl_mac_key_up_ref(MAC_KEY *mackey)
{
int ref = 0;
/* This is effectively doing a new operation on the MAC_KEY and should be
* adequately guarded again modules' error states. However, both current
* calls here are guarded properly in signature/mac_legacy.c. Thus, it
* could be removed here. The concern is that something in the future
* might call this function without adequate guards. It's a cheap call,
* it seems best to leave it even though it is currently redundant.
*/
if (!ossl_prov_is_running())
return 0;
CRYPTO_UP_REF(&mackey->refcnt, &ref);
return 1;
}
static void *mac_new(void *provctx)
{
return ossl_mac_key_new(PROV_LIBCTX_OF(provctx), 0);
}
static void *mac_new_cmac(void *provctx)
{
return ossl_mac_key_new(PROV_LIBCTX_OF(provctx), 1);
}
static void mac_free(void *mackey)
{
ossl_mac_key_free(mackey);
}
static int mac_has(const void *keydata, int selection)
{
const MAC_KEY *key = keydata;
int ok = 0;
if (ossl_prov_is_running() && key != NULL) {
/*
* MAC keys always have all the parameters they need (i.e. none).
* Therefore we always return with 1, if asked about parameters.
* Similarly for public keys.
*/
ok = 1;
if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
ok = key->priv_key != NULL;
}
return ok;
}
static int mac_match(const void *keydata1, const void *keydata2, int selection)
{
const MAC_KEY *key1 = keydata1;
const MAC_KEY *key2 = keydata2;
int ok = 1;
if (!ossl_prov_is_running())
return 0;
if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
if ((key1->priv_key == NULL && key2->priv_key != NULL)
|| (key1->priv_key != NULL && key2->priv_key == NULL)
|| key1->priv_key_len != key2->priv_key_len
|| (key1->cipher.cipher == NULL && key2->cipher.cipher != NULL)
|| (key1->cipher.cipher != NULL && key2->cipher.cipher == NULL))
ok = 0;
else
ok = ok && (key1->priv_key == NULL /* implies key2->privkey == NULL */
|| CRYPTO_memcmp(key1->priv_key, key2->priv_key,
key1->priv_key_len) == 0);
if (key1->cipher.cipher != NULL)
ok = ok && EVP_CIPHER_is_a(key1->cipher.cipher,
EVP_CIPHER_get0_name(key2->cipher.cipher));
}
return ok;
}
static int mac_key_fromdata(MAC_KEY *key, const OSSL_PARAM params[])
{
const OSSL_PARAM *p;
p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PRIV_KEY);
if (p != NULL) {
if (p->data_type != OSSL_PARAM_OCTET_STRING) {
ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT);
return 0;
}
OPENSSL_secure_clear_free(key->priv_key, key->priv_key_len);
/* allocate at least one byte to distinguish empty key from no key set */
key->priv_key = OPENSSL_secure_malloc(p->data_size > 0 ? p->data_size : 1);
if (key->priv_key == NULL)
return 0;
memcpy(key->priv_key, p->data, p->data_size);
key->priv_key_len = p->data_size;
}
p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PROPERTIES);
if (p != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING) {
ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT);
return 0;
}
OPENSSL_free(key->properties);
key->properties = OPENSSL_strdup(p->data);
if (key->properties == NULL)
return 0;
}
if (key->cmac && !ossl_prov_cipher_load_from_params(&key->cipher, params,
key->libctx)) {
ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT);
return 0;
}
if (key->priv_key != NULL)
return 1;
return 0;
}
static int mac_import(void *keydata, int selection, const OSSL_PARAM params[])
{
MAC_KEY *key = keydata;
if (!ossl_prov_is_running() || key == NULL)
return 0;
if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) == 0)
return 0;
return mac_key_fromdata(key, params);
}
static int key_to_params(MAC_KEY *key, OSSL_PARAM_BLD *tmpl,
OSSL_PARAM params[])
{
if (key == NULL)
return 0;
if (key->priv_key != NULL
&& !ossl_param_build_set_octet_string(tmpl, params,
OSSL_PKEY_PARAM_PRIV_KEY,
key->priv_key, key->priv_key_len))
return 0;
if (key->cipher.cipher != NULL
&& !ossl_param_build_set_utf8_string(tmpl, params,
OSSL_PKEY_PARAM_CIPHER,
EVP_CIPHER_get0_name(key->cipher.cipher)))
return 0;
#if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
if (key->cipher.engine != NULL
&& !ossl_param_build_set_utf8_string(tmpl, params,
OSSL_PKEY_PARAM_ENGINE,
ENGINE_get_id(key->cipher.engine)))
return 0;
#endif
return 1;
}
static int mac_export(void *keydata, int selection, OSSL_CALLBACK *param_cb,
void *cbarg)
{
MAC_KEY *key = keydata;
OSSL_PARAM_BLD *tmpl;
OSSL_PARAM *params = NULL;
int ret = 0;
if (!ossl_prov_is_running() || key == NULL)
return 0;
tmpl = OSSL_PARAM_BLD_new();
if (tmpl == NULL)
return 0;
if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0
&& !key_to_params(key, tmpl, NULL))
goto err;
params = OSSL_PARAM_BLD_to_param(tmpl);
if (params == NULL)
goto err;
ret = param_cb(params, cbarg);
OSSL_PARAM_free(params);
err:
OSSL_PARAM_BLD_free(tmpl);
return ret;
}
static const OSSL_PARAM mac_key_types[] = {
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_END
};
static const OSSL_PARAM *mac_imexport_types(int selection)
{
if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
return mac_key_types;
return NULL;
}
static const OSSL_PARAM cmac_key_types[] = {
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_CIPHER, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_ENGINE, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_END
};
static const OSSL_PARAM *cmac_imexport_types(int selection)
{
if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
return cmac_key_types;
return NULL;
}
static int mac_get_params(void *key, OSSL_PARAM params[])
{
return key_to_params(key, NULL, params);
}
static const OSSL_PARAM *mac_gettable_params(void *provctx)
{
static const OSSL_PARAM gettable_params[] = {
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0),
OSSL_PARAM_END
};
return gettable_params;
}
static const OSSL_PARAM *cmac_gettable_params(void *provctx)
{
static const OSSL_PARAM gettable_params[] = {
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_CIPHER, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_ENGINE, NULL, 0),
OSSL_PARAM_END
};
return gettable_params;
}
static int mac_set_params(void *keydata, const OSSL_PARAM params[])
{
MAC_KEY *key = keydata;
const OSSL_PARAM *p;
if (key == NULL)
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PRIV_KEY);
if (p != NULL)
return mac_key_fromdata(key, params);
return 1;
}
static const OSSL_PARAM *mac_settable_params(void *provctx)
{
static const OSSL_PARAM settable_params[] = {
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0),
OSSL_PARAM_END
};
return settable_params;
}
static void *mac_gen_init_common(void *provctx, int selection)
{
OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(provctx);
struct mac_gen_ctx *gctx = NULL;
if (!ossl_prov_is_running())
return NULL;
if ((gctx = OPENSSL_zalloc(sizeof(*gctx))) != NULL) {
gctx->libctx = libctx;
gctx->selection = selection;
}
return gctx;
}
static void *mac_gen_init(void *provctx, int selection,
const OSSL_PARAM params[])
{
struct mac_gen_ctx *gctx = mac_gen_init_common(provctx, selection);
if (gctx != NULL && !mac_gen_set_params(gctx, params)) {
OPENSSL_free(gctx);
gctx = NULL;
}
return gctx;
}
static void *cmac_gen_init(void *provctx, int selection,
const OSSL_PARAM params[])
{
struct mac_gen_ctx *gctx = mac_gen_init_common(provctx, selection);
if (gctx != NULL && !cmac_gen_set_params(gctx, params)) {
OPENSSL_free(gctx);
gctx = NULL;
}
return gctx;
}
static int mac_gen_set_params(void *genctx, const OSSL_PARAM params[])
{
struct mac_gen_ctx *gctx = genctx;
const OSSL_PARAM *p;
if (gctx == NULL)
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PRIV_KEY);
if (p != NULL) {
if (p->data_type != OSSL_PARAM_OCTET_STRING) {
ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT);
return 0;
}
gctx->priv_key = OPENSSL_secure_malloc(p->data_size);
if (gctx->priv_key == NULL)
return 0;
memcpy(gctx->priv_key, p->data, p->data_size);
gctx->priv_key_len = p->data_size;
}
return 1;
}
static int cmac_gen_set_params(void *genctx, const OSSL_PARAM params[])
{
struct mac_gen_ctx *gctx = genctx;
if (!mac_gen_set_params(genctx, params))
return 0;
if (!ossl_prov_cipher_load_from_params(&gctx->cipher, params,
gctx->libctx)) {
ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT);
return 0;
}
return 1;
}
static const OSSL_PARAM *mac_gen_settable_params(ossl_unused void *genctx,
ossl_unused void *provctx)
{
static OSSL_PARAM settable[] = {
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0),
OSSL_PARAM_END
};
return settable;
}
static const OSSL_PARAM *cmac_gen_settable_params(ossl_unused void *genctx,
ossl_unused void *provctx)
{
static OSSL_PARAM settable[] = {
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_CIPHER, NULL, 0),
OSSL_PARAM_END
};
return settable;
}
static void *mac_gen(void *genctx, OSSL_CALLBACK *cb, void *cbarg)
{
struct mac_gen_ctx *gctx = genctx;
MAC_KEY *key;
if (!ossl_prov_is_running() || gctx == NULL)
return NULL;
if ((key = ossl_mac_key_new(gctx->libctx, 0)) == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_PROV_LIB);
return NULL;
}
/* If we're doing parameter generation then we just return a blank key */
if ((gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)
return key;
if (gctx->priv_key == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY);
ossl_mac_key_free(key);
return NULL;
}
/*
* This is horrible but required for backwards compatibility. We don't
* actually do real key generation at all. We simply copy the key that was
* previously set in the gctx. Hopefully at some point in the future all
* of this can be removed and we will only support the EVP_KDF APIs.
*/
if (!ossl_prov_cipher_copy(&key->cipher, &gctx->cipher)) {
ossl_mac_key_free(key);
ERR_raise(ERR_LIB_PROV, ERR_R_INTERNAL_ERROR);
return NULL;
}
ossl_prov_cipher_reset(&gctx->cipher);
key->priv_key = gctx->priv_key;
key->priv_key_len = gctx->priv_key_len;
gctx->priv_key_len = 0;
gctx->priv_key = NULL;
return key;
}
static void mac_gen_cleanup(void *genctx)
{
struct mac_gen_ctx *gctx = genctx;
OPENSSL_secure_clear_free(gctx->priv_key, gctx->priv_key_len);
ossl_prov_cipher_reset(&gctx->cipher);
OPENSSL_free(gctx);
}
const OSSL_DISPATCH ossl_mac_legacy_keymgmt_functions[] = {
{ OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))mac_new },
{ OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))mac_free },
{ OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*) (void))mac_get_params },
{ OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*) (void))mac_gettable_params },
{ OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*) (void))mac_set_params },
{ OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (void (*) (void))mac_settable_params },
{ OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))mac_has },
{ OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))mac_match },
{ OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))mac_import },
{ OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))mac_imexport_types },
{ OSSL_FUNC_KEYMGMT_EXPORT, (void (*)(void))mac_export },
{ OSSL_FUNC_KEYMGMT_EXPORT_TYPES, (void (*)(void))mac_imexport_types },
{ OSSL_FUNC_KEYMGMT_GEN_INIT, (void (*)(void))mac_gen_init },
{ OSSL_FUNC_KEYMGMT_GEN_SET_PARAMS, (void (*)(void))mac_gen_set_params },
{ OSSL_FUNC_KEYMGMT_GEN_SETTABLE_PARAMS,
(void (*)(void))mac_gen_settable_params },
{ OSSL_FUNC_KEYMGMT_GEN, (void (*)(void))mac_gen },
{ OSSL_FUNC_KEYMGMT_GEN_CLEANUP, (void (*)(void))mac_gen_cleanup },
OSSL_DISPATCH_END
};
const OSSL_DISPATCH ossl_cmac_legacy_keymgmt_functions[] = {
{ OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))mac_new_cmac },
{ OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))mac_free },
{ OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*) (void))mac_get_params },
{ OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*) (void))cmac_gettable_params },
{ OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*) (void))mac_set_params },
{ OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (void (*) (void))mac_settable_params },
{ OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))mac_has },
{ OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))mac_match },
{ OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))mac_import },
{ OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))cmac_imexport_types },
{ OSSL_FUNC_KEYMGMT_EXPORT, (void (*)(void))mac_export },
{ OSSL_FUNC_KEYMGMT_EXPORT_TYPES, (void (*)(void))cmac_imexport_types },
{ OSSL_FUNC_KEYMGMT_GEN_INIT, (void (*)(void))cmac_gen_init },
{ OSSL_FUNC_KEYMGMT_GEN_SET_PARAMS, (void (*)(void))cmac_gen_set_params },
{ OSSL_FUNC_KEYMGMT_GEN_SETTABLE_PARAMS,
(void (*)(void))cmac_gen_settable_params },
{ OSSL_FUNC_KEYMGMT_GEN, (void (*)(void))mac_gen },
{ OSSL_FUNC_KEYMGMT_GEN_CLEANUP, (void (*)(void))mac_gen_cleanup },
OSSL_DISPATCH_END
};
| 18,149 | 30.954225 | 87 | c |
openssl | openssl-master/providers/implementations/macs/blake2_mac_impl.c | /*
* Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/proverr.h>
#include "prov/blake2.h"
#include "internal/cryptlib.h"
#include "prov/implementations.h"
#include "prov/providercommon.h"
/*
* Forward declaration of everything implemented here. This is not strictly
* necessary for the compiler, but provides an assurance that the signatures
* of the functions in the dispatch table are correct.
*/
static OSSL_FUNC_mac_newctx_fn blake2_mac_new;
static OSSL_FUNC_mac_dupctx_fn blake2_mac_dup;
static OSSL_FUNC_mac_freectx_fn blake2_mac_free;
static OSSL_FUNC_mac_gettable_ctx_params_fn blake2_gettable_ctx_params;
static OSSL_FUNC_mac_get_ctx_params_fn blake2_get_ctx_params;
static OSSL_FUNC_mac_settable_ctx_params_fn blake2_mac_settable_ctx_params;
static OSSL_FUNC_mac_set_ctx_params_fn blake2_mac_set_ctx_params;
static OSSL_FUNC_mac_init_fn blake2_mac_init;
static OSSL_FUNC_mac_update_fn blake2_mac_update;
static OSSL_FUNC_mac_final_fn blake2_mac_final;
struct blake2_mac_data_st {
BLAKE2_CTX ctx;
BLAKE2_PARAM params;
unsigned char key[BLAKE2_KEYBYTES];
};
static void *blake2_mac_new(void *unused_provctx)
{
struct blake2_mac_data_st *macctx;
if (!ossl_prov_is_running())
return NULL;
macctx = OPENSSL_zalloc(sizeof(*macctx));
if (macctx != NULL) {
BLAKE2_PARAM_INIT(&macctx->params);
/* ctx initialization is deferred to BLAKE2b_Init() */
}
return macctx;
}
static void *blake2_mac_dup(void *vsrc)
{
struct blake2_mac_data_st *dst;
struct blake2_mac_data_st *src = vsrc;
if (!ossl_prov_is_running())
return NULL;
dst = OPENSSL_zalloc(sizeof(*dst));
if (dst == NULL)
return NULL;
*dst = *src;
return dst;
}
static void blake2_mac_free(void *vmacctx)
{
struct blake2_mac_data_st *macctx = vmacctx;
if (macctx != NULL) {
OPENSSL_cleanse(macctx->key, sizeof(macctx->key));
OPENSSL_free(macctx);
}
}
static size_t blake2_mac_size(void *vmacctx)
{
struct blake2_mac_data_st *macctx = vmacctx;
return macctx->params.digest_length;
}
static int blake2_setkey(struct blake2_mac_data_st *macctx,
const unsigned char *key, size_t keylen)
{
if (keylen > BLAKE2_KEYBYTES || keylen == 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
return 0;
}
memcpy(macctx->key, key, keylen);
/* Pad with zeroes at the end if required */
if (keylen < BLAKE2_KEYBYTES)
memset(macctx->key + keylen, 0, BLAKE2_KEYBYTES - keylen);
BLAKE2_PARAM_SET_KEY_LENGTH(&macctx->params, (uint8_t)keylen);
return 1;
}
static int blake2_mac_init(void *vmacctx, const unsigned char *key,
size_t keylen, const OSSL_PARAM params[])
{
struct blake2_mac_data_st *macctx = vmacctx;
if (!ossl_prov_is_running() || !blake2_mac_set_ctx_params(macctx, params))
return 0;
if (key != NULL) {
if (!blake2_setkey(macctx, key, keylen))
return 0;
} else if (macctx->params.key_length == 0) {
/* Check key has been set */
ERR_raise(ERR_LIB_PROV, PROV_R_NO_KEY_SET);
return 0;
}
return BLAKE2_INIT_KEY(&macctx->ctx, &macctx->params, macctx->key);
}
static int blake2_mac_update(void *vmacctx,
const unsigned char *data, size_t datalen)
{
struct blake2_mac_data_st *macctx = vmacctx;
if (datalen == 0)
return 1;
return BLAKE2_UPDATE(&macctx->ctx, data, datalen);
}
static int blake2_mac_final(void *vmacctx,
unsigned char *out, size_t *outl,
size_t outsize)
{
struct blake2_mac_data_st *macctx = vmacctx;
if (!ossl_prov_is_running())
return 0;
*outl = blake2_mac_size(macctx);
return BLAKE2_FINAL(out, &macctx->ctx);
}
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_MAC_PARAM_SIZE, NULL),
OSSL_PARAM_size_t(OSSL_MAC_PARAM_BLOCK_SIZE, NULL),
OSSL_PARAM_END
};
static const OSSL_PARAM *blake2_gettable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
return known_gettable_ctx_params;
}
static int blake2_get_ctx_params(void *vmacctx, OSSL_PARAM params[])
{
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_MAC_PARAM_SIZE)) != NULL
&& !OSSL_PARAM_set_size_t(p, blake2_mac_size(vmacctx)))
return 0;
if ((p = OSSL_PARAM_locate(params, OSSL_MAC_PARAM_BLOCK_SIZE)) != NULL
&& !OSSL_PARAM_set_size_t(p, BLAKE2_BLOCKBYTES))
return 0;
return 1;
}
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_MAC_PARAM_SIZE, NULL),
OSSL_PARAM_octet_string(OSSL_MAC_PARAM_KEY, NULL, 0),
OSSL_PARAM_octet_string(OSSL_MAC_PARAM_CUSTOM, NULL, 0),
OSSL_PARAM_octet_string(OSSL_MAC_PARAM_SALT, NULL, 0),
OSSL_PARAM_END
};
static const OSSL_PARAM *blake2_mac_settable_ctx_params(
ossl_unused void *ctx, ossl_unused void *p_ctx)
{
return known_settable_ctx_params;
}
/*
* ALL parameters should be set before init().
*/
static int blake2_mac_set_ctx_params(void *vmacctx, const OSSL_PARAM params[])
{
struct blake2_mac_data_st *macctx = vmacctx;
const OSSL_PARAM *p;
if (params == NULL)
return 1;
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_SIZE)) != NULL) {
size_t size;
if (!OSSL_PARAM_get_size_t(p, &size)
|| size < 1
|| size > BLAKE2_OUTBYTES) {
ERR_raise(ERR_LIB_PROV, PROV_R_NOT_XOF_OR_INVALID_LENGTH);
return 0;
}
BLAKE2_PARAM_SET_DIGEST_LENGTH(&macctx->params, (uint8_t)size);
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_KEY)) != NULL
&& !blake2_setkey(macctx, p->data, p->data_size))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_CUSTOM))
!= NULL) {
/*
* The OSSL_PARAM API doesn't provide direct pointer use, so we
* must handle the OSSL_PARAM structure ourselves here
*/
if (p->data_size > BLAKE2_PERSONALBYTES) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CUSTOM_LENGTH);
return 0;
}
BLAKE2_PARAM_SET_PERSONAL(&macctx->params, p->data, p->data_size);
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_SALT)) != NULL) {
/*
* The OSSL_PARAM API doesn't provide direct pointer use, so we
* must handle the OSSL_PARAM structure ourselves here as well
*/
if (p->data_size > BLAKE2_SALTBYTES) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_SALT_LENGTH);
return 0;
}
BLAKE2_PARAM_SET_SALT(&macctx->params, p->data, p->data_size);
}
return 1;
}
const OSSL_DISPATCH BLAKE2_FUNCTIONS[] = {
{ OSSL_FUNC_MAC_NEWCTX, (void (*)(void))blake2_mac_new },
{ OSSL_FUNC_MAC_DUPCTX, (void (*)(void))blake2_mac_dup },
{ OSSL_FUNC_MAC_FREECTX, (void (*)(void))blake2_mac_free },
{ OSSL_FUNC_MAC_INIT, (void (*)(void))blake2_mac_init },
{ OSSL_FUNC_MAC_UPDATE, (void (*)(void))blake2_mac_update },
{ OSSL_FUNC_MAC_FINAL, (void (*)(void))blake2_mac_final },
{ OSSL_FUNC_MAC_GETTABLE_CTX_PARAMS,
(void (*)(void))blake2_gettable_ctx_params },
{ OSSL_FUNC_MAC_GET_CTX_PARAMS, (void (*)(void))blake2_get_ctx_params },
{ OSSL_FUNC_MAC_SETTABLE_CTX_PARAMS,
(void (*)(void))blake2_mac_settable_ctx_params },
{ OSSL_FUNC_MAC_SET_CTX_PARAMS, (void (*)(void))blake2_mac_set_ctx_params },
OSSL_DISPATCH_END
};
| 8,068 | 30.643137 | 80 | c |
openssl | openssl-master/providers/implementations/macs/blake2b_mac.c | /*
* Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* Constants */
#define BLAKE2_CTX BLAKE2B_CTX
#define BLAKE2_PARAM BLAKE2B_PARAM
#define BLAKE2_KEYBYTES BLAKE2B_KEYBYTES
#define BLAKE2_OUTBYTES BLAKE2B_OUTBYTES
#define BLAKE2_PERSONALBYTES BLAKE2B_PERSONALBYTES
#define BLAKE2_SALTBYTES BLAKE2B_SALTBYTES
#define BLAKE2_BLOCKBYTES BLAKE2B_BLOCKBYTES
/* Function names */
#define BLAKE2_PARAM_INIT ossl_blake2b_param_init
#define BLAKE2_INIT_KEY ossl_blake2b_init_key
#define BLAKE2_UPDATE ossl_blake2b_update
#define BLAKE2_FINAL ossl_blake2b_final
#define BLAKE2_PARAM_SET_DIGEST_LENGTH ossl_blake2b_param_set_digest_length
#define BLAKE2_PARAM_SET_KEY_LENGTH ossl_blake2b_param_set_key_length
#define BLAKE2_PARAM_SET_PERSONAL ossl_blake2b_param_set_personal
#define BLAKE2_PARAM_SET_SALT ossl_blake2b_param_set_salt
/* OSSL_DISPATCH symbol */
#define BLAKE2_FUNCTIONS ossl_blake2bmac_functions
#include "blake2_mac_impl.c"
| 1,220 | 34.911765 | 75 | c |
openssl | openssl-master/providers/implementations/macs/blake2s_mac.c | /*
* Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* Constants */
#define BLAKE2_CTX BLAKE2S_CTX
#define BLAKE2_PARAM BLAKE2S_PARAM
#define BLAKE2_KEYBYTES BLAKE2S_KEYBYTES
#define BLAKE2_OUTBYTES BLAKE2S_OUTBYTES
#define BLAKE2_PERSONALBYTES BLAKE2S_PERSONALBYTES
#define BLAKE2_SALTBYTES BLAKE2S_SALTBYTES
#define BLAKE2_BLOCKBYTES BLAKE2S_BLOCKBYTES
/* Function names */
#define BLAKE2_PARAM_INIT ossl_blake2s_param_init
#define BLAKE2_INIT_KEY ossl_blake2s_init_key
#define BLAKE2_UPDATE ossl_blake2s_update
#define BLAKE2_FINAL ossl_blake2s_final
#define BLAKE2_PARAM_SET_DIGEST_LENGTH ossl_blake2s_param_set_digest_length
#define BLAKE2_PARAM_SET_KEY_LENGTH ossl_blake2s_param_set_key_length
#define BLAKE2_PARAM_SET_PERSONAL ossl_blake2s_param_set_personal
#define BLAKE2_PARAM_SET_SALT ossl_blake2s_param_set_salt
/* OSSL_DISPATCH symbol */
#define BLAKE2_FUNCTIONS ossl_blake2smac_functions
#include "blake2_mac_impl.c"
| 1,219 | 35.969697 | 75 | c |
openssl | openssl-master/providers/implementations/macs/cmac_prov.c | /*
* Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* CMAC low level APIs are deprecated for public use, but still ok for internal
* use.
*/
#include "internal/deprecated.h"
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/evp.h>
#include <openssl/cmac.h>
#include <openssl/err.h>
#include <openssl/proverr.h>
#include "prov/implementations.h"
#include "prov/provider_ctx.h"
#include "prov/provider_util.h"
#include "prov/providercommon.h"
/*
* Forward declaration of everything implemented here. This is not strictly
* necessary for the compiler, but provides an assurance that the signatures
* of the functions in the dispatch table are correct.
*/
static OSSL_FUNC_mac_newctx_fn cmac_new;
static OSSL_FUNC_mac_dupctx_fn cmac_dup;
static OSSL_FUNC_mac_freectx_fn cmac_free;
static OSSL_FUNC_mac_gettable_ctx_params_fn cmac_gettable_ctx_params;
static OSSL_FUNC_mac_get_ctx_params_fn cmac_get_ctx_params;
static OSSL_FUNC_mac_settable_ctx_params_fn cmac_settable_ctx_params;
static OSSL_FUNC_mac_set_ctx_params_fn cmac_set_ctx_params;
static OSSL_FUNC_mac_init_fn cmac_init;
static OSSL_FUNC_mac_update_fn cmac_update;
static OSSL_FUNC_mac_final_fn cmac_final;
/* local CMAC data */
struct cmac_data_st {
void *provctx;
CMAC_CTX *ctx;
PROV_CIPHER cipher;
};
static void *cmac_new(void *provctx)
{
struct cmac_data_st *macctx;
if (!ossl_prov_is_running())
return NULL;
if ((macctx = OPENSSL_zalloc(sizeof(*macctx))) == NULL
|| (macctx->ctx = CMAC_CTX_new()) == NULL) {
OPENSSL_free(macctx);
macctx = NULL;
} else {
macctx->provctx = provctx;
}
return macctx;
}
static void cmac_free(void *vmacctx)
{
struct cmac_data_st *macctx = vmacctx;
if (macctx != NULL) {
CMAC_CTX_free(macctx->ctx);
ossl_prov_cipher_reset(&macctx->cipher);
OPENSSL_free(macctx);
}
}
static void *cmac_dup(void *vsrc)
{
struct cmac_data_st *src = vsrc;
struct cmac_data_st *dst;
if (!ossl_prov_is_running())
return NULL;
dst = cmac_new(src->provctx);
if (dst == NULL)
return NULL;
if (!CMAC_CTX_copy(dst->ctx, src->ctx)
|| !ossl_prov_cipher_copy(&dst->cipher, &src->cipher)) {
cmac_free(dst);
return NULL;
}
return dst;
}
static size_t cmac_size(void *vmacctx)
{
struct cmac_data_st *macctx = vmacctx;
return EVP_CIPHER_CTX_get_block_size(CMAC_CTX_get0_cipher_ctx(macctx->ctx));
}
static int cmac_setkey(struct cmac_data_st *macctx,
const unsigned char *key, size_t keylen)
{
int rv = CMAC_Init(macctx->ctx, key, keylen,
ossl_prov_cipher_cipher(&macctx->cipher),
ossl_prov_cipher_engine(&macctx->cipher));
ossl_prov_cipher_reset(&macctx->cipher);
return rv;
}
static int cmac_init(void *vmacctx, const unsigned char *key,
size_t keylen, const OSSL_PARAM params[])
{
struct cmac_data_st *macctx = vmacctx;
if (!ossl_prov_is_running() || !cmac_set_ctx_params(macctx, params))
return 0;
if (key != NULL)
return cmac_setkey(macctx, key, keylen);
/* Reinitialize the CMAC context */
return CMAC_Init(macctx->ctx, NULL, 0, NULL, NULL);
}
static int cmac_update(void *vmacctx, const unsigned char *data,
size_t datalen)
{
struct cmac_data_st *macctx = vmacctx;
return CMAC_Update(macctx->ctx, data, datalen);
}
static int cmac_final(void *vmacctx, unsigned char *out, size_t *outl,
size_t outsize)
{
struct cmac_data_st *macctx = vmacctx;
if (!ossl_prov_is_running())
return 0;
return CMAC_Final(macctx->ctx, out, outl);
}
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_MAC_PARAM_SIZE, NULL),
OSSL_PARAM_size_t(OSSL_MAC_PARAM_BLOCK_SIZE, NULL),
OSSL_PARAM_END
};
static const OSSL_PARAM *cmac_gettable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
return known_gettable_ctx_params;
}
static int cmac_get_ctx_params(void *vmacctx, OSSL_PARAM params[])
{
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_MAC_PARAM_SIZE)) != NULL
&& !OSSL_PARAM_set_size_t(p, cmac_size(vmacctx)))
return 0;
if ((p = OSSL_PARAM_locate(params, OSSL_MAC_PARAM_BLOCK_SIZE)) != NULL
&& !OSSL_PARAM_set_size_t(p, cmac_size(vmacctx)))
return 0;
return 1;
}
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_MAC_PARAM_CIPHER, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_MAC_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_octet_string(OSSL_MAC_PARAM_KEY, NULL, 0),
OSSL_PARAM_END
};
static const OSSL_PARAM *cmac_settable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
return known_settable_ctx_params;
}
/*
* ALL parameters should be set before init().
*/
static int cmac_set_ctx_params(void *vmacctx, const OSSL_PARAM params[])
{
struct cmac_data_st *macctx = vmacctx;
OSSL_LIB_CTX *ctx = PROV_LIBCTX_OF(macctx->provctx);
const OSSL_PARAM *p;
if (params == NULL)
return 1;
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_CIPHER)) != NULL) {
if (!ossl_prov_cipher_load_from_params(&macctx->cipher, params, ctx))
return 0;
if (EVP_CIPHER_get_mode(ossl_prov_cipher_cipher(&macctx->cipher))
!= EVP_CIPH_CBC_MODE) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
return 0;
}
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_KEY)) != NULL) {
if (p->data_type != OSSL_PARAM_OCTET_STRING)
return 0;
return cmac_setkey(macctx, p->data, p->data_size);
}
return 1;
}
const OSSL_DISPATCH ossl_cmac_functions[] = {
{ OSSL_FUNC_MAC_NEWCTX, (void (*)(void))cmac_new },
{ OSSL_FUNC_MAC_DUPCTX, (void (*)(void))cmac_dup },
{ OSSL_FUNC_MAC_FREECTX, (void (*)(void))cmac_free },
{ OSSL_FUNC_MAC_INIT, (void (*)(void))cmac_init },
{ OSSL_FUNC_MAC_UPDATE, (void (*)(void))cmac_update },
{ OSSL_FUNC_MAC_FINAL, (void (*)(void))cmac_final },
{ OSSL_FUNC_MAC_GETTABLE_CTX_PARAMS,
(void (*)(void))cmac_gettable_ctx_params },
{ OSSL_FUNC_MAC_GET_CTX_PARAMS, (void (*)(void))cmac_get_ctx_params },
{ OSSL_FUNC_MAC_SETTABLE_CTX_PARAMS,
(void (*)(void))cmac_settable_ctx_params },
{ OSSL_FUNC_MAC_SET_CTX_PARAMS, (void (*)(void))cmac_set_ctx_params },
OSSL_DISPATCH_END
};
| 6,982 | 28.84188 | 80 | c |
openssl | openssl-master/providers/implementations/macs/gmac_prov.c | /*
* Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdlib.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/proverr.h>
#include "prov/implementations.h"
#include "prov/provider_ctx.h"
#include "prov/provider_util.h"
#include "prov/providercommon.h"
/*
* Forward declaration of everything implemented here. This is not strictly
* necessary for the compiler, but provides an assurance that the signatures
* of the functions in the dispatch table are correct.
*/
static OSSL_FUNC_mac_newctx_fn gmac_new;
static OSSL_FUNC_mac_dupctx_fn gmac_dup;
static OSSL_FUNC_mac_freectx_fn gmac_free;
static OSSL_FUNC_mac_gettable_params_fn gmac_gettable_params;
static OSSL_FUNC_mac_get_params_fn gmac_get_params;
static OSSL_FUNC_mac_settable_ctx_params_fn gmac_settable_ctx_params;
static OSSL_FUNC_mac_set_ctx_params_fn gmac_set_ctx_params;
static OSSL_FUNC_mac_init_fn gmac_init;
static OSSL_FUNC_mac_update_fn gmac_update;
static OSSL_FUNC_mac_final_fn gmac_final;
/* local GMAC pkey structure */
struct gmac_data_st {
void *provctx;
EVP_CIPHER_CTX *ctx; /* Cipher context */
PROV_CIPHER cipher;
};
static void gmac_free(void *vmacctx)
{
struct gmac_data_st *macctx = vmacctx;
if (macctx != NULL) {
EVP_CIPHER_CTX_free(macctx->ctx);
ossl_prov_cipher_reset(&macctx->cipher);
OPENSSL_free(macctx);
}
}
static void *gmac_new(void *provctx)
{
struct gmac_data_st *macctx;
if (!ossl_prov_is_running())
return NULL;
if ((macctx = OPENSSL_zalloc(sizeof(*macctx))) == NULL
|| (macctx->ctx = EVP_CIPHER_CTX_new()) == NULL) {
gmac_free(macctx);
return NULL;
}
macctx->provctx = provctx;
return macctx;
}
static void *gmac_dup(void *vsrc)
{
struct gmac_data_st *src = vsrc;
struct gmac_data_st *dst;
if (!ossl_prov_is_running())
return NULL;
dst = gmac_new(src->provctx);
if (dst == NULL)
return NULL;
if (!EVP_CIPHER_CTX_copy(dst->ctx, src->ctx)
|| !ossl_prov_cipher_copy(&dst->cipher, &src->cipher)) {
gmac_free(dst);
return NULL;
}
return dst;
}
static size_t gmac_size(void)
{
return EVP_GCM_TLS_TAG_LEN;
}
static int gmac_setkey(struct gmac_data_st *macctx,
const unsigned char *key, size_t keylen)
{
EVP_CIPHER_CTX *ctx = macctx->ctx;
if (keylen != (size_t)EVP_CIPHER_CTX_get_key_length(ctx)) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
return 0;
}
if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, NULL))
return 0;
return 1;
}
static int gmac_init(void *vmacctx, const unsigned char *key,
size_t keylen, const OSSL_PARAM params[])
{
struct gmac_data_st *macctx = vmacctx;
if (!ossl_prov_is_running() || !gmac_set_ctx_params(macctx, params))
return 0;
if (key != NULL)
return gmac_setkey(macctx, key, keylen);
return EVP_EncryptInit_ex(macctx->ctx, NULL, NULL, NULL, NULL);
}
static int gmac_update(void *vmacctx, const unsigned char *data,
size_t datalen)
{
struct gmac_data_st *macctx = vmacctx;
EVP_CIPHER_CTX *ctx = macctx->ctx;
int outlen;
if (datalen == 0)
return 1;
while (datalen > INT_MAX) {
if (!EVP_EncryptUpdate(ctx, NULL, &outlen, data, INT_MAX))
return 0;
data += INT_MAX;
datalen -= INT_MAX;
}
return EVP_EncryptUpdate(ctx, NULL, &outlen, data, datalen);
}
static int gmac_final(void *vmacctx, unsigned char *out, size_t *outl,
size_t outsize)
{
OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
struct gmac_data_st *macctx = vmacctx;
int hlen = 0;
if (!ossl_prov_is_running())
return 0;
if (!EVP_EncryptFinal_ex(macctx->ctx, out, &hlen))
return 0;
hlen = gmac_size();
params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TAG,
out, (size_t)hlen);
if (!EVP_CIPHER_CTX_get_params(macctx->ctx, params))
return 0;
*outl = hlen;
return 1;
}
static const OSSL_PARAM known_gettable_params[] = {
OSSL_PARAM_size_t(OSSL_MAC_PARAM_SIZE, NULL),
OSSL_PARAM_END
};
static const OSSL_PARAM *gmac_gettable_params(void *provctx)
{
return known_gettable_params;
}
static int gmac_get_params(OSSL_PARAM params[])
{
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_MAC_PARAM_SIZE)) != NULL)
return OSSL_PARAM_set_size_t(p, gmac_size());
return 1;
}
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_MAC_PARAM_CIPHER, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_MAC_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_octet_string(OSSL_MAC_PARAM_KEY, NULL, 0),
OSSL_PARAM_octet_string(OSSL_MAC_PARAM_IV, NULL, 0),
OSSL_PARAM_END
};
static const OSSL_PARAM *gmac_settable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
return known_settable_ctx_params;
}
/*
* ALL parameters should be set before init().
*/
static int gmac_set_ctx_params(void *vmacctx, const OSSL_PARAM params[])
{
struct gmac_data_st *macctx = vmacctx;
EVP_CIPHER_CTX *ctx = macctx->ctx;
OSSL_LIB_CTX *provctx = PROV_LIBCTX_OF(macctx->provctx);
const OSSL_PARAM *p;
if (params == NULL)
return 1;
if (ctx == NULL)
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_CIPHER)) != NULL) {
if (!ossl_prov_cipher_load_from_params(&macctx->cipher, params, provctx))
return 0;
if (EVP_CIPHER_get_mode(ossl_prov_cipher_cipher(&macctx->cipher))
!= EVP_CIPH_GCM_MODE) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
return 0;
}
if (!EVP_EncryptInit_ex(ctx, ossl_prov_cipher_cipher(&macctx->cipher),
ossl_prov_cipher_engine(&macctx->cipher), NULL,
NULL))
return 0;
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_KEY)) != NULL)
if (p->data_type != OSSL_PARAM_OCTET_STRING
|| !gmac_setkey(macctx, p->data, p->data_size))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_IV)) != NULL) {
if (p->data_type != OSSL_PARAM_OCTET_STRING)
return 0;
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN,
p->data_size, NULL) <= 0
|| !EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, p->data))
return 0;
}
return 1;
}
const OSSL_DISPATCH ossl_gmac_functions[] = {
{ OSSL_FUNC_MAC_NEWCTX, (void (*)(void))gmac_new },
{ OSSL_FUNC_MAC_DUPCTX, (void (*)(void))gmac_dup },
{ OSSL_FUNC_MAC_FREECTX, (void (*)(void))gmac_free },
{ OSSL_FUNC_MAC_INIT, (void (*)(void))gmac_init },
{ OSSL_FUNC_MAC_UPDATE, (void (*)(void))gmac_update },
{ OSSL_FUNC_MAC_FINAL, (void (*)(void))gmac_final },
{ OSSL_FUNC_MAC_GETTABLE_PARAMS, (void (*)(void))gmac_gettable_params },
{ OSSL_FUNC_MAC_GET_PARAMS, (void (*)(void))gmac_get_params },
{ OSSL_FUNC_MAC_SETTABLE_CTX_PARAMS,
(void (*)(void))gmac_settable_ctx_params },
{ OSSL_FUNC_MAC_SET_CTX_PARAMS, (void (*)(void))gmac_set_ctx_params },
OSSL_DISPATCH_END
};
| 7,809 | 29.038462 | 81 | c |
openssl | openssl-master/providers/implementations/macs/hmac_prov.c | /*
* Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* HMAC low level APIs are deprecated for public use, but still ok for internal
* use.
*/
#include "internal/deprecated.h"
#include <string.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include "internal/ssl3_cbc.h"
#include "prov/implementations.h"
#include "prov/provider_ctx.h"
#include "prov/provider_util.h"
#include "prov/providercommon.h"
/*
* Forward declaration of everything implemented here. This is not strictly
* necessary for the compiler, but provides an assurance that the signatures
* of the functions in the dispatch table are correct.
*/
static OSSL_FUNC_mac_newctx_fn hmac_new;
static OSSL_FUNC_mac_dupctx_fn hmac_dup;
static OSSL_FUNC_mac_freectx_fn hmac_free;
static OSSL_FUNC_mac_gettable_ctx_params_fn hmac_gettable_ctx_params;
static OSSL_FUNC_mac_get_ctx_params_fn hmac_get_ctx_params;
static OSSL_FUNC_mac_settable_ctx_params_fn hmac_settable_ctx_params;
static OSSL_FUNC_mac_set_ctx_params_fn hmac_set_ctx_params;
static OSSL_FUNC_mac_init_fn hmac_init;
static OSSL_FUNC_mac_update_fn hmac_update;
static OSSL_FUNC_mac_final_fn hmac_final;
/* local HMAC context structure */
/* typedef EVP_MAC_IMPL */
struct hmac_data_st {
void *provctx;
HMAC_CTX *ctx; /* HMAC context */
PROV_DIGEST digest;
unsigned char *key;
size_t keylen;
/* Length of full TLS record including the MAC and any padding */
size_t tls_data_size;
unsigned char tls_header[13];
int tls_header_set;
unsigned char tls_mac_out[EVP_MAX_MD_SIZE];
size_t tls_mac_out_size;
};
static void *hmac_new(void *provctx)
{
struct hmac_data_st *macctx;
if (!ossl_prov_is_running())
return NULL;
if ((macctx = OPENSSL_zalloc(sizeof(*macctx))) == NULL
|| (macctx->ctx = HMAC_CTX_new()) == NULL) {
OPENSSL_free(macctx);
return NULL;
}
macctx->provctx = provctx;
return macctx;
}
static void hmac_free(void *vmacctx)
{
struct hmac_data_st *macctx = vmacctx;
if (macctx != NULL) {
HMAC_CTX_free(macctx->ctx);
ossl_prov_digest_reset(&macctx->digest);
OPENSSL_secure_clear_free(macctx->key, macctx->keylen);
OPENSSL_free(macctx);
}
}
static void *hmac_dup(void *vsrc)
{
struct hmac_data_st *src = vsrc;
struct hmac_data_st *dst;
HMAC_CTX *ctx;
if (!ossl_prov_is_running())
return NULL;
dst = hmac_new(src->provctx);
if (dst == NULL)
return NULL;
ctx = dst->ctx;
*dst = *src;
dst->ctx = ctx;
dst->key = NULL;
memset(&dst->digest, 0, sizeof(dst->digest));
if (!HMAC_CTX_copy(dst->ctx, src->ctx)
|| !ossl_prov_digest_copy(&dst->digest, &src->digest)) {
hmac_free(dst);
return NULL;
}
if (src->key != NULL) {
/* There is no "secure" OPENSSL_memdup */
dst->key = OPENSSL_secure_malloc(src->keylen > 0 ? src->keylen : 1);
if (dst->key == NULL) {
hmac_free(dst);
return 0;
}
memcpy(dst->key, src->key, src->keylen);
}
return dst;
}
static size_t hmac_size(struct hmac_data_st *macctx)
{
return HMAC_size(macctx->ctx);
}
static int hmac_block_size(struct hmac_data_st *macctx)
{
const EVP_MD *md = ossl_prov_digest_md(&macctx->digest);
if (md == NULL)
return 0;
return EVP_MD_block_size(md);
}
static int hmac_setkey(struct hmac_data_st *macctx,
const unsigned char *key, size_t keylen)
{
const EVP_MD *digest;
if (macctx->key != NULL)
OPENSSL_secure_clear_free(macctx->key, macctx->keylen);
/* Keep a copy of the key in case we need it for TLS HMAC */
macctx->key = OPENSSL_secure_malloc(keylen > 0 ? keylen : 1);
if (macctx->key == NULL)
return 0;
memcpy(macctx->key, key, keylen);
macctx->keylen = keylen;
digest = ossl_prov_digest_md(&macctx->digest);
/* HMAC_Init_ex doesn't tolerate all zero params, so we must be careful */
if (key != NULL || (macctx->tls_data_size == 0 && digest != NULL))
return HMAC_Init_ex(macctx->ctx, key, keylen, digest,
ossl_prov_digest_engine(&macctx->digest));
return 1;
}
static int hmac_init(void *vmacctx, const unsigned char *key,
size_t keylen, const OSSL_PARAM params[])
{
struct hmac_data_st *macctx = vmacctx;
if (!ossl_prov_is_running() || !hmac_set_ctx_params(macctx, params))
return 0;
if (key != NULL)
return hmac_setkey(macctx, key, keylen);
/* Just reinit the HMAC context */
return HMAC_Init_ex(macctx->ctx, NULL, 0, NULL, NULL);
}
static int hmac_update(void *vmacctx, const unsigned char *data,
size_t datalen)
{
struct hmac_data_st *macctx = vmacctx;
if (macctx->tls_data_size > 0) {
/* We're doing a TLS HMAC */
if (!macctx->tls_header_set) {
/* We expect the first update call to contain the TLS header */
if (datalen != sizeof(macctx->tls_header))
return 0;
memcpy(macctx->tls_header, data, datalen);
macctx->tls_header_set = 1;
return 1;
}
/* macctx->tls_data_size is datalen plus the padding length */
if (macctx->tls_data_size < datalen)
return 0;
return ssl3_cbc_digest_record(ossl_prov_digest_md(&macctx->digest),
macctx->tls_mac_out,
&macctx->tls_mac_out_size,
macctx->tls_header,
data,
datalen,
macctx->tls_data_size,
macctx->key,
macctx->keylen,
0);
}
return HMAC_Update(macctx->ctx, data, datalen);
}
static int hmac_final(void *vmacctx, unsigned char *out, size_t *outl,
size_t outsize)
{
unsigned int hlen;
struct hmac_data_st *macctx = vmacctx;
if (!ossl_prov_is_running())
return 0;
if (macctx->tls_data_size > 0) {
if (macctx->tls_mac_out_size == 0)
return 0;
if (outl != NULL)
*outl = macctx->tls_mac_out_size;
memcpy(out, macctx->tls_mac_out, macctx->tls_mac_out_size);
return 1;
}
if (!HMAC_Final(macctx->ctx, out, &hlen))
return 0;
*outl = hlen;
return 1;
}
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_MAC_PARAM_SIZE, NULL),
OSSL_PARAM_size_t(OSSL_MAC_PARAM_BLOCK_SIZE, NULL),
OSSL_PARAM_END
};
static const OSSL_PARAM *hmac_gettable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
return known_gettable_ctx_params;
}
static int hmac_get_ctx_params(void *vmacctx, OSSL_PARAM params[])
{
struct hmac_data_st *macctx = vmacctx;
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_MAC_PARAM_SIZE)) != NULL
&& !OSSL_PARAM_set_size_t(p, hmac_size(macctx)))
return 0;
if ((p = OSSL_PARAM_locate(params, OSSL_MAC_PARAM_BLOCK_SIZE)) != NULL
&& !OSSL_PARAM_set_int(p, hmac_block_size(macctx)))
return 0;
return 1;
}
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_MAC_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_MAC_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_octet_string(OSSL_MAC_PARAM_KEY, NULL, 0),
OSSL_PARAM_int(OSSL_MAC_PARAM_DIGEST_NOINIT, NULL),
OSSL_PARAM_int(OSSL_MAC_PARAM_DIGEST_ONESHOT, NULL),
OSSL_PARAM_size_t(OSSL_MAC_PARAM_TLS_DATA_SIZE, NULL),
OSSL_PARAM_END
};
static const OSSL_PARAM *hmac_settable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
return known_settable_ctx_params;
}
static int set_flag(const OSSL_PARAM params[], const char *key, int mask,
int *flags)
{
const OSSL_PARAM *p = OSSL_PARAM_locate_const(params, key);
int flag = 0;
if (p != NULL) {
if (!OSSL_PARAM_get_int(p, &flag))
return 0;
if (flag == 0)
*flags &= ~mask;
else
*flags |= mask;
}
return 1;
}
/*
* ALL parameters should be set before init().
*/
static int hmac_set_ctx_params(void *vmacctx, const OSSL_PARAM params[])
{
struct hmac_data_st *macctx = vmacctx;
OSSL_LIB_CTX *ctx = PROV_LIBCTX_OF(macctx->provctx);
const OSSL_PARAM *p;
int flags = 0;
if (params == NULL)
return 1;
if (!ossl_prov_digest_load_from_params(&macctx->digest, params, ctx))
return 0;
if (!set_flag(params, OSSL_MAC_PARAM_DIGEST_NOINIT, EVP_MD_CTX_FLAG_NO_INIT,
&flags))
return 0;
if (!set_flag(params, OSSL_MAC_PARAM_DIGEST_ONESHOT, EVP_MD_CTX_FLAG_ONESHOT,
&flags))
return 0;
if (flags)
HMAC_CTX_set_flags(macctx->ctx, flags);
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_KEY)) != NULL) {
if (p->data_type != OSSL_PARAM_OCTET_STRING)
return 0;
if (!hmac_setkey(macctx, p->data, p->data_size))
return 0;
}
if ((p = OSSL_PARAM_locate_const(params,
OSSL_MAC_PARAM_TLS_DATA_SIZE)) != NULL) {
if (!OSSL_PARAM_get_size_t(p, &macctx->tls_data_size))
return 0;
}
return 1;
}
const OSSL_DISPATCH ossl_hmac_functions[] = {
{ OSSL_FUNC_MAC_NEWCTX, (void (*)(void))hmac_new },
{ OSSL_FUNC_MAC_DUPCTX, (void (*)(void))hmac_dup },
{ OSSL_FUNC_MAC_FREECTX, (void (*)(void))hmac_free },
{ OSSL_FUNC_MAC_INIT, (void (*)(void))hmac_init },
{ OSSL_FUNC_MAC_UPDATE, (void (*)(void))hmac_update },
{ OSSL_FUNC_MAC_FINAL, (void (*)(void))hmac_final },
{ OSSL_FUNC_MAC_GETTABLE_CTX_PARAMS,
(void (*)(void))hmac_gettable_ctx_params },
{ OSSL_FUNC_MAC_GET_CTX_PARAMS, (void (*)(void))hmac_get_ctx_params },
{ OSSL_FUNC_MAC_SETTABLE_CTX_PARAMS,
(void (*)(void))hmac_settable_ctx_params },
{ OSSL_FUNC_MAC_SET_CTX_PARAMS, (void (*)(void))hmac_set_ctx_params },
OSSL_DISPATCH_END
};
| 10,743 | 29.7851 | 81 | c |
openssl | openssl-master/providers/implementations/macs/kmac_prov.c | /*
* Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* See SP800-185 "Appendix A - KMAC, .... in Terms of Keccak[c]"
*
* Inputs are:
* K = Key (len(K) < 2^2040 bits)
* X = Input
* L = Output length (0 <= L < 2^2040 bits)
* S = Customization String Default="" (len(S) < 2^2040 bits)
*
* KMAC128(K, X, L, S)
* {
* newX = bytepad(encode_string(K), 168) || X || right_encode(L).
* T = bytepad(encode_string("KMAC") || encode_string(S), 168).
* return KECCAK[256](T || newX || 00, L).
* }
*
* KMAC256(K, X, L, S)
* {
* newX = bytepad(encode_string(K), 136) || X || right_encode(L).
* T = bytepad(encode_string("KMAC") || encode_string(S), 136).
* return KECCAK[512](T || newX || 00, L).
* }
*
* KMAC128XOF(K, X, L, S)
* {
* newX = bytepad(encode_string(K), 168) || X || right_encode(0).
* T = bytepad(encode_string("KMAC") || encode_string(S), 168).
* return KECCAK[256](T || newX || 00, L).
* }
*
* KMAC256XOF(K, X, L, S)
* {
* newX = bytepad(encode_string(K), 136) || X || right_encode(0).
* T = bytepad(encode_string("KMAC") || encode_string(S), 136).
* return KECCAK[512](T || newX || 00, L).
* }
*
*/
#include <stdlib.h>
#include <string.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/proverr.h>
#include "prov/implementations.h"
#include "prov/provider_ctx.h"
#include "prov/provider_util.h"
#include "prov/providercommon.h"
#include "internal/cryptlib.h" /* ossl_assert */
/*
* Forward declaration of everything implemented here. This is not strictly
* necessary for the compiler, but provides an assurance that the signatures
* of the functions in the dispatch table are correct.
*/
static OSSL_FUNC_mac_newctx_fn kmac128_new;
static OSSL_FUNC_mac_newctx_fn kmac256_new;
static OSSL_FUNC_mac_dupctx_fn kmac_dup;
static OSSL_FUNC_mac_freectx_fn kmac_free;
static OSSL_FUNC_mac_gettable_ctx_params_fn kmac_gettable_ctx_params;
static OSSL_FUNC_mac_get_ctx_params_fn kmac_get_ctx_params;
static OSSL_FUNC_mac_settable_ctx_params_fn kmac_settable_ctx_params;
static OSSL_FUNC_mac_set_ctx_params_fn kmac_set_ctx_params;
static OSSL_FUNC_mac_init_fn kmac_init;
static OSSL_FUNC_mac_update_fn kmac_update;
static OSSL_FUNC_mac_final_fn kmac_final;
#define KMAC_MAX_BLOCKSIZE ((1600 - 128 * 2) / 8) /* 168 */
/*
* Length encoding will be a 1 byte size + length in bits (3 bytes max)
* This gives a range of 0..0XFFFFFF bits = 2097151 bytes).
*/
#define KMAC_MAX_OUTPUT_LEN (0xFFFFFF / 8)
#define KMAC_MAX_ENCODED_HEADER_LEN (1 + 3)
/*
* Restrict the maximum length of the customisation string. This must not
* exceed 64 bits = 8k bytes.
*/
#define KMAC_MAX_CUSTOM 512
/* Maximum size of encoded custom string */
#define KMAC_MAX_CUSTOM_ENCODED (KMAC_MAX_CUSTOM + KMAC_MAX_ENCODED_HEADER_LEN)
/* Maximum key size in bytes = 512 (4096 bits) */
#define KMAC_MAX_KEY 512
#define KMAC_MIN_KEY 4
/*
* Maximum Encoded Key size will be padded to a multiple of the blocksize
* i.e KMAC_MAX_KEY + KMAC_MAX_ENCODED_HEADER_LEN = 512 + 4
* Padded to a multiple of KMAC_MAX_BLOCKSIZE
*/
#define KMAC_MAX_KEY_ENCODED (KMAC_MAX_BLOCKSIZE * 4)
/* Fixed value of encode_string("KMAC") */
static const unsigned char kmac_string[] = {
0x01, 0x20, 0x4B, 0x4D, 0x41, 0x43
};
#define KMAC_FLAG_XOF_MODE 1
struct kmac_data_st {
void *provctx;
EVP_MD_CTX *ctx;
PROV_DIGEST digest;
size_t out_len;
size_t key_len;
size_t custom_len;
/* If xof_mode = 1 then we use right_encode(0) */
int xof_mode;
/* key and custom are stored in encoded form */
unsigned char key[KMAC_MAX_KEY_ENCODED];
unsigned char custom[KMAC_MAX_CUSTOM_ENCODED];
};
static int encode_string(unsigned char *out, size_t out_max_len, size_t *out_len,
const unsigned char *in, size_t in_len);
static int right_encode(unsigned char *out, size_t out_max_len, size_t *out_len,
size_t bits);
static int bytepad(unsigned char *out, size_t *out_len,
const unsigned char *in1, size_t in1_len,
const unsigned char *in2, size_t in2_len,
size_t w);
static int kmac_bytepad_encode_key(unsigned char *out, size_t out_max_len,
size_t *out_len,
const unsigned char *in, size_t in_len,
size_t w);
static void kmac_free(void *vmacctx)
{
struct kmac_data_st *kctx = vmacctx;
if (kctx != NULL) {
EVP_MD_CTX_free(kctx->ctx);
ossl_prov_digest_reset(&kctx->digest);
OPENSSL_cleanse(kctx->key, kctx->key_len);
OPENSSL_cleanse(kctx->custom, kctx->custom_len);
OPENSSL_free(kctx);
}
}
/*
* We have KMAC implemented as a hash, which we can use instead of
* reimplementing the EVP functionality with direct use of
* keccak_mac_init() and friends.
*/
static struct kmac_data_st *kmac_new(void *provctx)
{
struct kmac_data_st *kctx;
if (!ossl_prov_is_running())
return NULL;
if ((kctx = OPENSSL_zalloc(sizeof(*kctx))) == NULL
|| (kctx->ctx = EVP_MD_CTX_new()) == NULL) {
kmac_free(kctx);
return NULL;
}
kctx->provctx = provctx;
return kctx;
}
static void *kmac_fetch_new(void *provctx, const OSSL_PARAM *params)
{
struct kmac_data_st *kctx = kmac_new(provctx);
if (kctx == NULL)
return 0;
if (!ossl_prov_digest_load_from_params(&kctx->digest, params,
PROV_LIBCTX_OF(provctx))) {
kmac_free(kctx);
return 0;
}
kctx->out_len = EVP_MD_get_size(ossl_prov_digest_md(&kctx->digest));
return kctx;
}
static void *kmac128_new(void *provctx)
{
static const OSSL_PARAM kmac128_params[] = {
OSSL_PARAM_utf8_string("digest", OSSL_DIGEST_NAME_KECCAK_KMAC128,
sizeof(OSSL_DIGEST_NAME_KECCAK_KMAC128)),
OSSL_PARAM_END
};
return kmac_fetch_new(provctx, kmac128_params);
}
static void *kmac256_new(void *provctx)
{
static const OSSL_PARAM kmac256_params[] = {
OSSL_PARAM_utf8_string("digest", OSSL_DIGEST_NAME_KECCAK_KMAC256,
sizeof(OSSL_DIGEST_NAME_KECCAK_KMAC256)),
OSSL_PARAM_END
};
return kmac_fetch_new(provctx, kmac256_params);
}
static void *kmac_dup(void *vsrc)
{
struct kmac_data_st *src = vsrc;
struct kmac_data_st *dst;
if (!ossl_prov_is_running())
return NULL;
dst = kmac_new(src->provctx);
if (dst == NULL)
return NULL;
if (!EVP_MD_CTX_copy(dst->ctx, src->ctx)
|| !ossl_prov_digest_copy(&dst->digest, &src->digest)) {
kmac_free(dst);
return NULL;
}
dst->out_len = src->out_len;
dst->key_len = src->key_len;
dst->custom_len = src->custom_len;
dst->xof_mode = src->xof_mode;
memcpy(dst->key, src->key, src->key_len);
memcpy(dst->custom, src->custom, dst->custom_len);
return dst;
}
static int kmac_setkey(struct kmac_data_st *kctx, const unsigned char *key,
size_t keylen)
{
const EVP_MD *digest = ossl_prov_digest_md(&kctx->digest);
int w = EVP_MD_get_block_size(digest);
if (keylen < KMAC_MIN_KEY || keylen > KMAC_MAX_KEY) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
return 0;
}
if (w < 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_DIGEST_LENGTH);
return 0;
}
if (!kmac_bytepad_encode_key(kctx->key, sizeof(kctx->key), &kctx->key_len,
key, keylen, (size_t)w))
return 0;
return 1;
}
/*
* The init() assumes that any ctrl methods are set beforehand for
* md, key and custom. Setting the fields afterwards will have no
* effect on the output mac.
*/
static int kmac_init(void *vmacctx, const unsigned char *key,
size_t keylen, const OSSL_PARAM params[])
{
struct kmac_data_st *kctx = vmacctx;
EVP_MD_CTX *ctx = kctx->ctx;
unsigned char *out;
size_t out_len, block_len;
int res, t;
if (!ossl_prov_is_running() || !kmac_set_ctx_params(kctx, params))
return 0;
if (key != NULL) {
if (!kmac_setkey(kctx, key, keylen))
return 0;
} else if (kctx->key_len == 0) {
/* Check key has been set */
ERR_raise(ERR_LIB_PROV, PROV_R_NO_KEY_SET);
return 0;
}
if (!EVP_DigestInit_ex(kctx->ctx, ossl_prov_digest_md(&kctx->digest),
NULL))
return 0;
t = EVP_MD_get_block_size(ossl_prov_digest_md(&kctx->digest));
if (t < 0) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_DIGEST_LENGTH);
return 0;
}
block_len = t;
/* Set default custom string if it is not already set */
if (kctx->custom_len == 0) {
const OSSL_PARAM cparams[] = {
OSSL_PARAM_octet_string(OSSL_MAC_PARAM_CUSTOM, "", 0),
OSSL_PARAM_END
};
(void)kmac_set_ctx_params(kctx, cparams);
}
if (!bytepad(NULL, &out_len, kmac_string, sizeof(kmac_string),
kctx->custom, kctx->custom_len, block_len)) {
ERR_raise(ERR_LIB_PROV, ERR_R_INTERNAL_ERROR);
return 0;
}
out = OPENSSL_malloc(out_len);
if (out == NULL)
return 0;
res = bytepad(out, NULL, kmac_string, sizeof(kmac_string),
kctx->custom, kctx->custom_len, block_len)
&& EVP_DigestUpdate(ctx, out, out_len)
&& EVP_DigestUpdate(ctx, kctx->key, kctx->key_len);
OPENSSL_free(out);
return res;
}
static int kmac_update(void *vmacctx, const unsigned char *data,
size_t datalen)
{
struct kmac_data_st *kctx = vmacctx;
return EVP_DigestUpdate(kctx->ctx, data, datalen);
}
static int kmac_final(void *vmacctx, unsigned char *out, size_t *outl,
size_t outsize)
{
struct kmac_data_st *kctx = vmacctx;
EVP_MD_CTX *ctx = kctx->ctx;
size_t lbits, len;
unsigned char encoded_outlen[KMAC_MAX_ENCODED_HEADER_LEN];
int ok;
if (!ossl_prov_is_running())
return 0;
/* KMAC XOF mode sets the encoded length to 0 */
lbits = (kctx->xof_mode ? 0 : (kctx->out_len * 8));
ok = right_encode(encoded_outlen, sizeof(encoded_outlen), &len, lbits)
&& EVP_DigestUpdate(ctx, encoded_outlen, len)
&& EVP_DigestFinalXOF(ctx, out, kctx->out_len);
*outl = kctx->out_len;
return ok;
}
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_MAC_PARAM_SIZE, NULL),
OSSL_PARAM_size_t(OSSL_MAC_PARAM_BLOCK_SIZE, NULL),
OSSL_PARAM_END
};
static const OSSL_PARAM *kmac_gettable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
return known_gettable_ctx_params;
}
static int kmac_get_ctx_params(void *vmacctx, OSSL_PARAM params[])
{
struct kmac_data_st *kctx = vmacctx;
OSSL_PARAM *p;
int sz;
if ((p = OSSL_PARAM_locate(params, OSSL_MAC_PARAM_SIZE)) != NULL
&& !OSSL_PARAM_set_size_t(p, kctx->out_len))
return 0;
if ((p = OSSL_PARAM_locate(params, OSSL_MAC_PARAM_BLOCK_SIZE)) != NULL) {
sz = EVP_MD_block_size(ossl_prov_digest_md(&kctx->digest));
if (!OSSL_PARAM_set_int(p, sz))
return 0;
}
return 1;
}
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_int(OSSL_MAC_PARAM_XOF, NULL),
OSSL_PARAM_size_t(OSSL_MAC_PARAM_SIZE, NULL),
OSSL_PARAM_octet_string(OSSL_MAC_PARAM_KEY, NULL, 0),
OSSL_PARAM_octet_string(OSSL_MAC_PARAM_CUSTOM, NULL, 0),
OSSL_PARAM_END
};
static const OSSL_PARAM *kmac_settable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
return known_settable_ctx_params;
}
/*
* The following params can be set any time before final():
* - "outlen" or "size": The requested output length.
* - "xof": If set, this indicates that right_encoded(0)
* is part of the digested data, otherwise it
* uses right_encoded(requested output length).
*
* All other params should be set before init().
*/
static int kmac_set_ctx_params(void *vmacctx, const OSSL_PARAM *params)
{
struct kmac_data_st *kctx = vmacctx;
const OSSL_PARAM *p;
if (params == NULL)
return 1;
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_XOF)) != NULL
&& !OSSL_PARAM_get_int(p, &kctx->xof_mode))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_SIZE)) != NULL) {
size_t sz = 0;
if (!OSSL_PARAM_get_size_t(p, &sz))
return 0;
if (sz > KMAC_MAX_OUTPUT_LEN) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_OUTPUT_LENGTH);
return 0;
}
kctx->out_len = sz;
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_KEY)) != NULL
&& !kmac_setkey(kctx, p->data, p->data_size))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_CUSTOM))
!= NULL) {
if (p->data_size > KMAC_MAX_CUSTOM) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CUSTOM_LENGTH);
return 0;
}
if (!encode_string(kctx->custom, sizeof(kctx->custom), &kctx->custom_len,
p->data, p->data_size))
return 0;
}
return 1;
}
/* Encoding/Padding Methods. */
/* Returns the number of bytes required to store 'bits' into a byte array */
static unsigned int get_encode_size(size_t bits)
{
unsigned int cnt = 0, sz = sizeof(size_t);
while (bits && (cnt < sz)) {
++cnt;
bits >>= 8;
}
/* If bits is zero 1 byte is required */
if (cnt == 0)
cnt = 1;
return cnt;
}
/*
* Convert an integer into bytes . The number of bytes is appended
* to the end of the buffer. Returns an array of bytes 'out' of size
* *out_len.
*
* e.g if bits = 32, out[2] = { 0x20, 0x01 }
*/
static int right_encode(unsigned char *out, size_t out_max_len, size_t *out_len,
size_t bits)
{
unsigned int len = get_encode_size(bits);
int i;
if (len >= out_max_len) {
ERR_raise(ERR_LIB_PROV, PROV_R_LENGTH_TOO_LARGE);
return 0;
}
/* MSB's are at the start of the bytes array */
for (i = len - 1; i >= 0; --i) {
out[i] = (unsigned char)(bits & 0xFF);
bits >>= 8;
}
/* Tack the length onto the end */
out[len] = (unsigned char)len;
/* The Returned length includes the tacked on byte */
*out_len = len + 1;
return 1;
}
/*
* Encodes a string with a left encoded length added. Note that the
* in_len is converted to bits (*8).
*
* e.g- in="KMAC" gives out[6] = { 0x01, 0x20, 0x4B, 0x4D, 0x41, 0x43 }
* len bits K M A C
*/
static int encode_string(unsigned char *out, size_t out_max_len, size_t *out_len,
const unsigned char *in, size_t in_len)
{
if (in == NULL) {
*out_len = 0;
} else {
size_t i, bits, len, sz;
bits = 8 * in_len;
len = get_encode_size(bits);
sz = 1 + len + in_len;
if (sz > out_max_len) {
ERR_raise(ERR_LIB_PROV, PROV_R_LENGTH_TOO_LARGE);
return 0;
}
out[0] = (unsigned char)len;
for (i = len; i > 0; --i) {
out[i] = (bits & 0xFF);
bits >>= 8;
}
memcpy(out + len + 1, in, in_len);
*out_len = sz;
}
return 1;
}
/*
* Returns a zero padded encoding of the inputs in1 and an optional
* in2 (can be NULL). The padded output must be a multiple of the blocksize 'w'.
* The value of w is in bytes (< 256).
*
* The returned output is:
* zero_padded(multiple of w, (left_encode(w) || in1 [|| in2])
*/
static int bytepad(unsigned char *out, size_t *out_len,
const unsigned char *in1, size_t in1_len,
const unsigned char *in2, size_t in2_len, size_t w)
{
int len;
unsigned char *p = out;
int sz = w;
if (out == NULL) {
if (out_len == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
sz = 2 + in1_len + (in2 != NULL ? in2_len : 0);
*out_len = (sz + w - 1) / w * w;
return 1;
}
if (!ossl_assert(w <= 255))
return 0;
/* Left encoded w */
*p++ = 1;
*p++ = (unsigned char)w;
/* || in1 */
memcpy(p, in1, in1_len);
p += in1_len;
/* [ || in2 ] */
if (in2 != NULL && in2_len > 0) {
memcpy(p, in2, in2_len);
p += in2_len;
}
/* Figure out the pad size (divisible by w) */
len = p - out;
sz = (len + w - 1) / w * w;
/* zero pad the end of the buffer */
if (sz != len)
memset(p, 0, sz - len);
if (out_len != NULL)
*out_len = sz;
return 1;
}
/* Returns out = bytepad(encode_string(in), w) */
static int kmac_bytepad_encode_key(unsigned char *out, size_t out_max_len,
size_t *out_len,
const unsigned char *in, size_t in_len,
size_t w)
{
unsigned char tmp[KMAC_MAX_KEY + KMAC_MAX_ENCODED_HEADER_LEN];
size_t tmp_len;
if (!encode_string(tmp, sizeof(tmp), &tmp_len, in, in_len))
return 0;
if (!bytepad(NULL, out_len, tmp, tmp_len, NULL, 0, w))
return 0;
if (!ossl_assert(*out_len <= out_max_len))
return 0;
return bytepad(out, NULL, tmp, tmp_len, NULL, 0, w);
}
const OSSL_DISPATCH ossl_kmac128_functions[] = {
{ OSSL_FUNC_MAC_NEWCTX, (void (*)(void))kmac128_new },
{ OSSL_FUNC_MAC_DUPCTX, (void (*)(void))kmac_dup },
{ OSSL_FUNC_MAC_FREECTX, (void (*)(void))kmac_free },
{ OSSL_FUNC_MAC_INIT, (void (*)(void))kmac_init },
{ OSSL_FUNC_MAC_UPDATE, (void (*)(void))kmac_update },
{ OSSL_FUNC_MAC_FINAL, (void (*)(void))kmac_final },
{ OSSL_FUNC_MAC_GETTABLE_CTX_PARAMS,
(void (*)(void))kmac_gettable_ctx_params },
{ OSSL_FUNC_MAC_GET_CTX_PARAMS, (void (*)(void))kmac_get_ctx_params },
{ OSSL_FUNC_MAC_SETTABLE_CTX_PARAMS,
(void (*)(void))kmac_settable_ctx_params },
{ OSSL_FUNC_MAC_SET_CTX_PARAMS, (void (*)(void))kmac_set_ctx_params },
OSSL_DISPATCH_END
};
const OSSL_DISPATCH ossl_kmac256_functions[] = {
{ OSSL_FUNC_MAC_NEWCTX, (void (*)(void))kmac256_new },
{ OSSL_FUNC_MAC_DUPCTX, (void (*)(void))kmac_dup },
{ OSSL_FUNC_MAC_FREECTX, (void (*)(void))kmac_free },
{ OSSL_FUNC_MAC_INIT, (void (*)(void))kmac_init },
{ OSSL_FUNC_MAC_UPDATE, (void (*)(void))kmac_update },
{ OSSL_FUNC_MAC_FINAL, (void (*)(void))kmac_final },
{ OSSL_FUNC_MAC_GETTABLE_CTX_PARAMS,
(void (*)(void))kmac_gettable_ctx_params },
{ OSSL_FUNC_MAC_GET_CTX_PARAMS, (void (*)(void))kmac_get_ctx_params },
{ OSSL_FUNC_MAC_SETTABLE_CTX_PARAMS,
(void (*)(void))kmac_settable_ctx_params },
{ OSSL_FUNC_MAC_SET_CTX_PARAMS, (void (*)(void))kmac_set_ctx_params },
OSSL_DISPATCH_END
};
| 19,645 | 30.383387 | 81 | c |
openssl | openssl-master/providers/implementations/macs/poly1305_prov.c | /*
* Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/proverr.h>
#include "crypto/poly1305.h"
#include "prov/implementations.h"
#include "prov/providercommon.h"
/*
* Forward declaration of everything implemented here. This is not strictly
* necessary for the compiler, but provides an assurance that the signatures
* of the functions in the dispatch table are correct.
*/
static OSSL_FUNC_mac_newctx_fn poly1305_new;
static OSSL_FUNC_mac_dupctx_fn poly1305_dup;
static OSSL_FUNC_mac_freectx_fn poly1305_free;
static OSSL_FUNC_mac_gettable_params_fn poly1305_gettable_params;
static OSSL_FUNC_mac_get_params_fn poly1305_get_params;
static OSSL_FUNC_mac_settable_ctx_params_fn poly1305_settable_ctx_params;
static OSSL_FUNC_mac_set_ctx_params_fn poly1305_set_ctx_params;
static OSSL_FUNC_mac_init_fn poly1305_init;
static OSSL_FUNC_mac_update_fn poly1305_update;
static OSSL_FUNC_mac_final_fn poly1305_final;
struct poly1305_data_st {
void *provctx;
int updated;
POLY1305 poly1305; /* Poly1305 data */
};
static void *poly1305_new(void *provctx)
{
struct poly1305_data_st *ctx;
if (!ossl_prov_is_running())
return NULL;
ctx = OPENSSL_zalloc(sizeof(*ctx));
if (ctx != NULL)
ctx->provctx = provctx;
return ctx;
}
static void poly1305_free(void *vmacctx)
{
OPENSSL_free(vmacctx);
}
static void *poly1305_dup(void *vsrc)
{
struct poly1305_data_st *src = vsrc;
struct poly1305_data_st *dst;
if (!ossl_prov_is_running())
return NULL;
dst = OPENSSL_malloc(sizeof(*dst));
if (dst == NULL)
return NULL;
*dst = *src;
return dst;
}
static size_t poly1305_size(void)
{
return POLY1305_DIGEST_SIZE;
}
static int poly1305_setkey(struct poly1305_data_st *ctx,
const unsigned char *key, size_t keylen)
{
if (keylen != POLY1305_KEY_SIZE) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
return 0;
}
Poly1305_Init(&ctx->poly1305, key);
ctx->updated = 0;
return 1;
}
static int poly1305_init(void *vmacctx, const unsigned char *key,
size_t keylen, const OSSL_PARAM params[])
{
struct poly1305_data_st *ctx = vmacctx;
/* initialize the context in MAC_ctrl function */
if (!ossl_prov_is_running() || !poly1305_set_ctx_params(ctx, params))
return 0;
if (key != NULL)
return poly1305_setkey(ctx, key, keylen);
/* no reinitialization of context with the same key is allowed */
return ctx->updated == 0;
}
static int poly1305_update(void *vmacctx, const unsigned char *data,
size_t datalen)
{
struct poly1305_data_st *ctx = vmacctx;
ctx->updated = 1;
if (datalen == 0)
return 1;
/* poly1305 has nothing to return in its update function */
Poly1305_Update(&ctx->poly1305, data, datalen);
return 1;
}
static int poly1305_final(void *vmacctx, unsigned char *out, size_t *outl,
size_t outsize)
{
struct poly1305_data_st *ctx = vmacctx;
if (!ossl_prov_is_running())
return 0;
ctx->updated = 1;
Poly1305_Final(&ctx->poly1305, out);
*outl = poly1305_size();
return 1;
}
static const OSSL_PARAM known_gettable_params[] = {
OSSL_PARAM_size_t(OSSL_MAC_PARAM_SIZE, NULL),
OSSL_PARAM_END
};
static const OSSL_PARAM *poly1305_gettable_params(void *provctx)
{
return known_gettable_params;
}
static int poly1305_get_params(OSSL_PARAM params[])
{
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_MAC_PARAM_SIZE)) != NULL)
return OSSL_PARAM_set_size_t(p, poly1305_size());
return 1;
}
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_octet_string(OSSL_MAC_PARAM_KEY, NULL, 0),
OSSL_PARAM_END
};
static const OSSL_PARAM *poly1305_settable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
return known_settable_ctx_params;
}
static int poly1305_set_ctx_params(void *vmacctx, const OSSL_PARAM *params)
{
struct poly1305_data_st *ctx = vmacctx;
const OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_KEY)) != NULL
&& !poly1305_setkey(ctx, p->data, p->data_size))
return 0;
return 1;
}
const OSSL_DISPATCH ossl_poly1305_functions[] = {
{ OSSL_FUNC_MAC_NEWCTX, (void (*)(void))poly1305_new },
{ OSSL_FUNC_MAC_DUPCTX, (void (*)(void))poly1305_dup },
{ OSSL_FUNC_MAC_FREECTX, (void (*)(void))poly1305_free },
{ OSSL_FUNC_MAC_INIT, (void (*)(void))poly1305_init },
{ OSSL_FUNC_MAC_UPDATE, (void (*)(void))poly1305_update },
{ OSSL_FUNC_MAC_FINAL, (void (*)(void))poly1305_final },
{ OSSL_FUNC_MAC_GETTABLE_PARAMS, (void (*)(void))poly1305_gettable_params },
{ OSSL_FUNC_MAC_GET_PARAMS, (void (*)(void))poly1305_get_params },
{ OSSL_FUNC_MAC_SETTABLE_CTX_PARAMS,
(void (*)(void))poly1305_settable_ctx_params },
{ OSSL_FUNC_MAC_SET_CTX_PARAMS, (void (*)(void))poly1305_set_ctx_params },
OSSL_DISPATCH_END
};
| 5,532 | 28.430851 | 80 | c |
openssl | openssl-master/providers/implementations/macs/siphash_prov.c | /*
* Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/proverr.h>
#include "crypto/siphash.h"
#include "prov/implementations.h"
#include "prov/providercommon.h"
/*
* Forward declaration of everything implemented here. This is not strictly
* necessary for the compiler, but provides an assurance that the signatures
* of the functions in the dispatch table are correct.
*/
static OSSL_FUNC_mac_newctx_fn siphash_new;
static OSSL_FUNC_mac_dupctx_fn siphash_dup;
static OSSL_FUNC_mac_freectx_fn siphash_free;
static OSSL_FUNC_mac_gettable_ctx_params_fn siphash_gettable_ctx_params;
static OSSL_FUNC_mac_get_ctx_params_fn siphash_get_ctx_params;
static OSSL_FUNC_mac_settable_ctx_params_fn siphash_settable_ctx_params;
static OSSL_FUNC_mac_set_ctx_params_fn siphash_set_params;
static OSSL_FUNC_mac_init_fn siphash_init;
static OSSL_FUNC_mac_update_fn siphash_update;
static OSSL_FUNC_mac_final_fn siphash_final;
struct siphash_data_st {
void *provctx;
SIPHASH siphash; /* Siphash data */
SIPHASH sipcopy; /* Siphash data copy for reinitialization */
unsigned int crounds, drounds;
};
static unsigned int crounds(struct siphash_data_st *ctx)
{
return ctx->crounds != 0 ? ctx->crounds : SIPHASH_C_ROUNDS;
}
static unsigned int drounds(struct siphash_data_st *ctx)
{
return ctx->drounds != 0 ? ctx->drounds : SIPHASH_D_ROUNDS;
}
static void *siphash_new(void *provctx)
{
struct siphash_data_st *ctx;
if (!ossl_prov_is_running())
return NULL;
ctx = OPENSSL_zalloc(sizeof(*ctx));
if (ctx != NULL)
ctx->provctx = provctx;
return ctx;
}
static void siphash_free(void *vmacctx)
{
OPENSSL_free(vmacctx);
}
static void *siphash_dup(void *vsrc)
{
struct siphash_data_st *ssrc = vsrc;
struct siphash_data_st *sdst;
if (!ossl_prov_is_running())
return NULL;
sdst = OPENSSL_malloc(sizeof(*sdst));
if (sdst == NULL)
return NULL;
*sdst = *ssrc;
return sdst;
}
static size_t siphash_size(void *vmacctx)
{
struct siphash_data_st *ctx = vmacctx;
return SipHash_hash_size(&ctx->siphash);
}
static int siphash_setkey(struct siphash_data_st *ctx,
const unsigned char *key, size_t keylen)
{
int ret;
if (keylen != SIPHASH_KEY_SIZE)
return 0;
ret = SipHash_Init(&ctx->siphash, key, crounds(ctx), drounds(ctx));
if (ret)
ctx->sipcopy = ctx->siphash;
return ret;
}
static int siphash_init(void *vmacctx, const unsigned char *key, size_t keylen,
const OSSL_PARAM params[])
{
struct siphash_data_st *ctx = vmacctx;
if (!ossl_prov_is_running() || !siphash_set_params(ctx, params))
return 0;
/*
* Without a key, there is not much to do here,
* The actual initialization happens through controls.
*/
if (key == NULL) {
ctx->siphash = ctx->sipcopy;
return 1;
}
return siphash_setkey(ctx, key, keylen);
}
static int siphash_update(void *vmacctx, const unsigned char *data,
size_t datalen)
{
struct siphash_data_st *ctx = vmacctx;
if (datalen == 0)
return 1;
SipHash_Update(&ctx->siphash, data, datalen);
return 1;
}
static int siphash_final(void *vmacctx, unsigned char *out, size_t *outl,
size_t outsize)
{
struct siphash_data_st *ctx = vmacctx;
size_t hlen = siphash_size(ctx);
if (!ossl_prov_is_running() || outsize < hlen)
return 0;
*outl = hlen;
return SipHash_Final(&ctx->siphash, out, hlen);
}
static const OSSL_PARAM *siphash_gettable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_MAC_PARAM_SIZE, NULL),
OSSL_PARAM_uint(OSSL_MAC_PARAM_C_ROUNDS, NULL),
OSSL_PARAM_uint(OSSL_MAC_PARAM_D_ROUNDS, NULL),
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
static int siphash_get_ctx_params(void *vmacctx, OSSL_PARAM params[])
{
struct siphash_data_st *ctx = vmacctx;
OSSL_PARAM *p;
if ((p = OSSL_PARAM_locate(params, OSSL_MAC_PARAM_SIZE)) != NULL
&& !OSSL_PARAM_set_size_t(p, siphash_size(vmacctx)))
return 0;
if ((p = OSSL_PARAM_locate(params, OSSL_MAC_PARAM_C_ROUNDS)) != NULL
&& !OSSL_PARAM_set_uint(p, crounds(ctx)))
return 0;
if ((p = OSSL_PARAM_locate(params, OSSL_MAC_PARAM_D_ROUNDS)) != NULL
&& !OSSL_PARAM_set_uint(p, drounds(ctx)))
return 0;
return 1;
}
static const OSSL_PARAM *siphash_settable_ctx_params(ossl_unused void *ctx,
void *provctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_MAC_PARAM_SIZE, NULL),
OSSL_PARAM_octet_string(OSSL_MAC_PARAM_KEY, NULL, 0),
OSSL_PARAM_uint(OSSL_MAC_PARAM_C_ROUNDS, NULL),
OSSL_PARAM_uint(OSSL_MAC_PARAM_D_ROUNDS, NULL),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
static int siphash_set_params(void *vmacctx, const OSSL_PARAM *params)
{
struct siphash_data_st *ctx = vmacctx;
const OSSL_PARAM *p = NULL;
size_t size;
if (params == NULL)
return 1;
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_SIZE)) != NULL) {
if (!OSSL_PARAM_get_size_t(p, &size)
|| !SipHash_set_hash_size(&ctx->siphash, size)
|| !SipHash_set_hash_size(&ctx->sipcopy, size))
return 0;
}
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_C_ROUNDS)) != NULL
&& !OSSL_PARAM_get_uint(p, &ctx->crounds))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_D_ROUNDS)) != NULL
&& !OSSL_PARAM_get_uint(p, &ctx->drounds))
return 0;
if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_KEY)) != NULL)
if (p->data_type != OSSL_PARAM_OCTET_STRING
|| !siphash_setkey(ctx, p->data, p->data_size))
return 0;
return 1;
}
const OSSL_DISPATCH ossl_siphash_functions[] = {
{ OSSL_FUNC_MAC_NEWCTX, (void (*)(void))siphash_new },
{ OSSL_FUNC_MAC_DUPCTX, (void (*)(void))siphash_dup },
{ OSSL_FUNC_MAC_FREECTX, (void (*)(void))siphash_free },
{ OSSL_FUNC_MAC_INIT, (void (*)(void))siphash_init },
{ OSSL_FUNC_MAC_UPDATE, (void (*)(void))siphash_update },
{ OSSL_FUNC_MAC_FINAL, (void (*)(void))siphash_final },
{ OSSL_FUNC_MAC_GETTABLE_CTX_PARAMS,
(void (*)(void))siphash_gettable_ctx_params },
{ OSSL_FUNC_MAC_GET_CTX_PARAMS, (void (*)(void))siphash_get_ctx_params },
{ OSSL_FUNC_MAC_SETTABLE_CTX_PARAMS,
(void (*)(void))siphash_settable_ctx_params },
{ OSSL_FUNC_MAC_SET_CTX_PARAMS, (void (*)(void))siphash_set_params },
OSSL_DISPATCH_END
};
| 7,378 | 30.004202 | 79 | c |
openssl | openssl-master/providers/implementations/rands/crngt.c | /*
* Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Implementation of the FIPS 140-2 section 4.9.2 Conditional Tests.
*/
#include <string.h>
#include <openssl/evp.h>
#include <openssl/core_dispatch.h>
#include <openssl/params.h>
#include <openssl/self_test.h>
#include "prov/providercommon.h"
#include "prov/provider_ctx.h"
#include "internal/cryptlib.h"
#include "crypto/rand_pool.h"
#include "drbg_local.h"
#include "prov/seeding.h"
#include "crypto/context.h"
typedef struct crng_test_global_st {
unsigned char crngt_prev[EVP_MAX_MD_SIZE];
EVP_MD *md;
int preloaded;
CRYPTO_RWLOCK *lock;
} CRNG_TEST_GLOBAL;
static int crngt_get_entropy(PROV_CTX *provctx, const EVP_MD *digest,
unsigned char *buf, unsigned char *md,
unsigned int *md_size)
{
int r;
size_t n;
unsigned char *p;
n = ossl_prov_get_entropy(provctx, &p, 0, CRNGT_BUFSIZ, CRNGT_BUFSIZ);
if (n == CRNGT_BUFSIZ) {
r = EVP_Digest(p, CRNGT_BUFSIZ, md, md_size, digest, NULL);
if (r != 0)
memcpy(buf, p, CRNGT_BUFSIZ);
ossl_prov_cleanup_entropy(provctx, p, n);
return r != 0;
}
if (n != 0)
ossl_prov_cleanup_entropy(provctx, p, n);
return 0;
}
void ossl_rand_crng_ctx_free(void *vcrngt_glob)
{
CRNG_TEST_GLOBAL *crngt_glob = vcrngt_glob;
CRYPTO_THREAD_lock_free(crngt_glob->lock);
EVP_MD_free(crngt_glob->md);
OPENSSL_free(crngt_glob);
}
void *ossl_rand_crng_ctx_new(OSSL_LIB_CTX *ctx)
{
CRNG_TEST_GLOBAL *crngt_glob = OPENSSL_zalloc(sizeof(*crngt_glob));
if (crngt_glob == NULL)
return NULL;
if ((crngt_glob->md = EVP_MD_fetch(ctx, "SHA256", "")) == NULL) {
OPENSSL_free(crngt_glob);
return NULL;
}
if ((crngt_glob->lock = CRYPTO_THREAD_lock_new()) == NULL) {
EVP_MD_free(crngt_glob->md);
OPENSSL_free(crngt_glob);
return NULL;
}
return crngt_glob;
}
static int prov_crngt_compare_previous(const unsigned char *prev,
const unsigned char *cur,
size_t sz)
{
const int res = memcmp(prev, cur, sz) != 0;
if (!res)
ossl_set_error_state(OSSL_SELF_TEST_TYPE_CRNG);
return res;
}
size_t ossl_crngt_get_entropy(PROV_DRBG *drbg,
unsigned char **pout,
int entropy, size_t min_len, size_t max_len,
int prediction_resistance)
{
unsigned char md[EVP_MAX_MD_SIZE];
unsigned char buf[CRNGT_BUFSIZ];
unsigned char *ent, *entp, *entbuf;
unsigned int sz;
size_t bytes_needed;
size_t r = 0, s, t;
int crng_test_pass = 1;
OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(drbg->provctx);
CRNG_TEST_GLOBAL *crngt_glob
= ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_RAND_CRNGT_INDEX);
OSSL_CALLBACK *stcb = NULL;
void *stcbarg = NULL;
OSSL_SELF_TEST *st = NULL;
if (crngt_glob == NULL)
return 0;
if (!CRYPTO_THREAD_write_lock(crngt_glob->lock))
return 0;
if (!crngt_glob->preloaded) {
if (!crngt_get_entropy(drbg->provctx, crngt_glob->md, buf,
crngt_glob->crngt_prev, NULL)) {
OPENSSL_cleanse(buf, sizeof(buf));
goto unlock_return;
}
crngt_glob->preloaded = 1;
}
/*
* Calculate how many bytes of seed material we require, rounded up
* to the nearest byte. If the entropy is of less than full quality,
* the amount required should be scaled up appropriately here.
*/
bytes_needed = (entropy + 7) / 8;
if (bytes_needed < min_len)
bytes_needed = min_len;
if (bytes_needed > max_len)
goto unlock_return;
entp = ent = OPENSSL_secure_malloc(bytes_needed);
if (ent == NULL)
goto unlock_return;
OSSL_SELF_TEST_get_callback(libctx, &stcb, &stcbarg);
if (stcb != NULL) {
st = OSSL_SELF_TEST_new(stcb, stcbarg);
if (st == NULL)
goto err;
OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_CRNG,
OSSL_SELF_TEST_DESC_RNG);
}
for (t = bytes_needed; t > 0;) {
/* Care needs to be taken to avoid overrunning the buffer */
s = t >= CRNGT_BUFSIZ ? CRNGT_BUFSIZ : t;
entbuf = t >= CRNGT_BUFSIZ ? entp : buf;
if (!crngt_get_entropy(drbg->provctx, crngt_glob->md, entbuf, md, &sz))
goto err;
if (t < CRNGT_BUFSIZ)
memcpy(entp, buf, t);
/* Force a failure here if the callback returns 1 */
if (OSSL_SELF_TEST_oncorrupt_byte(st, md))
memcpy(md, crngt_glob->crngt_prev, sz);
if (!prov_crngt_compare_previous(crngt_glob->crngt_prev, md, sz)) {
crng_test_pass = 0;
goto err;
}
/* Update for next block */
memcpy(crngt_glob->crngt_prev, md, sz);
entp += s;
t -= s;
}
r = bytes_needed;
*pout = ent;
ent = NULL;
err:
OSSL_SELF_TEST_onend(st, crng_test_pass);
OSSL_SELF_TEST_free(st);
OPENSSL_secure_clear_free(ent, bytes_needed);
unlock_return:
CRYPTO_THREAD_unlock(crngt_glob->lock);
return r;
}
void ossl_crngt_cleanup_entropy(ossl_unused PROV_DRBG *drbg,
unsigned char *out, size_t outlen)
{
OPENSSL_secure_clear_free(out, outlen);
}
| 5,823 | 29.176166 | 79 | c |
openssl | openssl-master/providers/implementations/rands/drbg_hash.c | /*
* Copyright 2011-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/sha.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/core_dispatch.h>
#include <openssl/proverr.h>
#include "internal/thread_once.h"
#include "prov/providercommon.h"
#include "prov/provider_ctx.h"
#include "prov/provider_util.h"
#include "prov/implementations.h"
#include "drbg_local.h"
static OSSL_FUNC_rand_newctx_fn drbg_hash_new_wrapper;
static OSSL_FUNC_rand_freectx_fn drbg_hash_free;
static OSSL_FUNC_rand_instantiate_fn drbg_hash_instantiate_wrapper;
static OSSL_FUNC_rand_uninstantiate_fn drbg_hash_uninstantiate_wrapper;
static OSSL_FUNC_rand_generate_fn drbg_hash_generate_wrapper;
static OSSL_FUNC_rand_reseed_fn drbg_hash_reseed_wrapper;
static OSSL_FUNC_rand_settable_ctx_params_fn drbg_hash_settable_ctx_params;
static OSSL_FUNC_rand_set_ctx_params_fn drbg_hash_set_ctx_params;
static OSSL_FUNC_rand_gettable_ctx_params_fn drbg_hash_gettable_ctx_params;
static OSSL_FUNC_rand_get_ctx_params_fn drbg_hash_get_ctx_params;
static OSSL_FUNC_rand_verify_zeroization_fn drbg_hash_verify_zeroization;
static int drbg_hash_set_ctx_params_locked(void *vctx, const OSSL_PARAM params[]);
/* 888 bits from SP800-90Ar1 10.1 table 2 */
#define HASH_PRNG_MAX_SEEDLEN (888/8)
/* 440 bits from SP800-90Ar1 10.1 table 2 */
#define HASH_PRNG_SMALL_SEEDLEN (440/8)
/* Determine what seedlen to use based on the block length */
#define MAX_BLOCKLEN_USING_SMALL_SEEDLEN (256/8)
#define INBYTE_IGNORE ((unsigned char)0xFF)
typedef struct rand_drbg_hash_st {
PROV_DIGEST digest;
EVP_MD_CTX *ctx;
size_t blocklen;
unsigned char V[HASH_PRNG_MAX_SEEDLEN];
unsigned char C[HASH_PRNG_MAX_SEEDLEN];
/* Temporary value storage: should always exceed max digest length */
unsigned char vtmp[HASH_PRNG_MAX_SEEDLEN];
} PROV_DRBG_HASH;
/*
* SP800-90Ar1 10.3.1 Derivation function using a Hash Function (Hash_df).
* The input string used is composed of:
* inbyte - An optional leading byte (ignore if equal to INBYTE_IGNORE)
* in - input string 1 (A Non NULL value).
* in2 - optional input string (Can be NULL).
* in3 - optional input string (Can be NULL).
* These are concatenated as part of the DigestUpdate process.
*/
static int hash_df(PROV_DRBG *drbg, unsigned char *out,
const unsigned char inbyte,
const unsigned char *in, size_t inlen,
const unsigned char *in2, size_t in2len,
const unsigned char *in3, size_t in3len)
{
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
EVP_MD_CTX *ctx = hash->ctx;
unsigned char *vtmp = hash->vtmp;
/* tmp = counter || num_bits_returned || [inbyte] */
unsigned char tmp[1 + 4 + 1];
int tmp_sz = 0;
size_t outlen = drbg->seedlen;
size_t num_bits_returned = outlen * 8;
/*
* No need to check outlen size here, as the standard only ever needs
* seedlen bytes which is always less than the maximum permitted.
*/
/* (Step 3) counter = 1 (tmp[0] is the 8 bit counter) */
tmp[tmp_sz++] = 1;
/* tmp[1..4] is the fixed 32 bit no_of_bits_to_return */
tmp[tmp_sz++] = (unsigned char)((num_bits_returned >> 24) & 0xff);
tmp[tmp_sz++] = (unsigned char)((num_bits_returned >> 16) & 0xff);
tmp[tmp_sz++] = (unsigned char)((num_bits_returned >> 8) & 0xff);
tmp[tmp_sz++] = (unsigned char)(num_bits_returned & 0xff);
/* Tack the additional input byte onto the end of tmp if it exists */
if (inbyte != INBYTE_IGNORE)
tmp[tmp_sz++] = inbyte;
/* (Step 4) */
for (;;) {
/*
* (Step 4.1) out = out || Hash(tmp || in || [in2] || [in3])
* (where tmp = counter || num_bits_returned || [inbyte])
*/
if (!(EVP_DigestInit_ex(ctx, ossl_prov_digest_md(&hash->digest), NULL)
&& EVP_DigestUpdate(ctx, tmp, tmp_sz)
&& EVP_DigestUpdate(ctx, in, inlen)
&& (in2 == NULL || EVP_DigestUpdate(ctx, in2, in2len))
&& (in3 == NULL || EVP_DigestUpdate(ctx, in3, in3len))))
return 0;
if (outlen < hash->blocklen) {
if (!EVP_DigestFinal(ctx, vtmp, NULL))
return 0;
memcpy(out, vtmp, outlen);
OPENSSL_cleanse(vtmp, hash->blocklen);
break;
} else if (!EVP_DigestFinal(ctx, out, NULL)) {
return 0;
}
outlen -= hash->blocklen;
if (outlen == 0)
break;
/* (Step 4.2) counter++ */
tmp[0]++;
out += hash->blocklen;
}
return 1;
}
/* Helper function that just passes 2 input parameters to hash_df() */
static int hash_df1(PROV_DRBG *drbg, unsigned char *out,
const unsigned char in_byte,
const unsigned char *in1, size_t in1len)
{
return hash_df(drbg, out, in_byte, in1, in1len, NULL, 0, NULL, 0);
}
/*
* Add 2 byte buffers together. The first elements in each buffer are the top
* most bytes. The result is stored in the dst buffer.
* The final carry is ignored i.e: dst = (dst + in) mod (2^seedlen_bits).
* where dst size is drbg->seedlen, and inlen <= drbg->seedlen.
*/
static int add_bytes(PROV_DRBG *drbg, unsigned char *dst,
unsigned char *in, size_t inlen)
{
size_t i;
int result;
const unsigned char *add;
unsigned char carry = 0, *d;
assert(drbg->seedlen >= 1 && inlen >= 1 && inlen <= drbg->seedlen);
d = &dst[drbg->seedlen - 1];
add = &in[inlen - 1];
for (i = inlen; i > 0; i--, d--, add--) {
result = *d + *add + carry;
carry = (unsigned char)(result >> 8);
*d = (unsigned char)(result & 0xff);
}
if (carry != 0) {
/* Add the carry to the top of the dst if inlen is not the same size */
for (i = drbg->seedlen - inlen; i > 0; --i, d--) {
*d += 1; /* Carry can only be 1 */
if (*d != 0) /* exit if carry doesn't propagate to the next byte */
break;
}
}
return 1;
}
/* V = (V + Hash(inbyte || V || [additional_input]) mod (2^seedlen) */
static int add_hash_to_v(PROV_DRBG *drbg, unsigned char inbyte,
const unsigned char *adin, size_t adinlen)
{
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
EVP_MD_CTX *ctx = hash->ctx;
return EVP_DigestInit_ex(ctx, ossl_prov_digest_md(&hash->digest), NULL)
&& EVP_DigestUpdate(ctx, &inbyte, 1)
&& EVP_DigestUpdate(ctx, hash->V, drbg->seedlen)
&& (adin == NULL || EVP_DigestUpdate(ctx, adin, adinlen))
&& EVP_DigestFinal(ctx, hash->vtmp, NULL)
&& add_bytes(drbg, hash->V, hash->vtmp, hash->blocklen);
}
/*
* The Hashgen() as listed in SP800-90Ar1 10.1.1.4 Hash_DRBG_Generate_Process.
*
* drbg contains the current value of V.
* outlen is the requested number of bytes.
* out is a buffer to return the generated bits.
*
* The algorithm to generate the bits is:
* data = V
* w = NULL
* for (i = 1 to m) {
* W = W || Hash(data)
* data = (data + 1) mod (2^seedlen)
* }
* out = Leftmost(W, outlen)
*
* Returns zero if an error occurs otherwise it returns 1.
*/
static int hash_gen(PROV_DRBG *drbg, unsigned char *out, size_t outlen)
{
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
unsigned char one = 1;
if (outlen == 0)
return 1;
memcpy(hash->vtmp, hash->V, drbg->seedlen);
for (;;) {
if (!EVP_DigestInit_ex(hash->ctx, ossl_prov_digest_md(&hash->digest),
NULL)
|| !EVP_DigestUpdate(hash->ctx, hash->vtmp, drbg->seedlen))
return 0;
if (outlen < hash->blocklen) {
if (!EVP_DigestFinal(hash->ctx, hash->vtmp, NULL))
return 0;
memcpy(out, hash->vtmp, outlen);
return 1;
} else {
if (!EVP_DigestFinal(hash->ctx, out, NULL))
return 0;
outlen -= hash->blocklen;
if (outlen == 0)
break;
out += hash->blocklen;
}
add_bytes(drbg, hash->vtmp, &one, 1);
}
return 1;
}
/*
* SP800-90Ar1 10.1.1.2 Hash_DRBG_Instantiate_Process:
*
* ent is entropy input obtained from a randomness source of length ent_len.
* nonce is a string of bytes of length nonce_len.
* pstr is a personalization string received from an application. May be NULL.
*
* Returns zero if an error occurs otherwise it returns 1.
*/
static int drbg_hash_instantiate(PROV_DRBG *drbg,
const unsigned char *ent, size_t ent_len,
const unsigned char *nonce, size_t nonce_len,
const unsigned char *pstr, size_t pstr_len)
{
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
EVP_MD_CTX_free(hash->ctx);
hash->ctx = EVP_MD_CTX_new();
/* (Step 1-3) V = Hash_df(entropy||nonce||pers, seedlen) */
return hash->ctx != NULL
&& hash_df(drbg, hash->V, INBYTE_IGNORE,
ent, ent_len, nonce, nonce_len, pstr, pstr_len)
/* (Step 4) C = Hash_df(0x00||V, seedlen) */
&& hash_df1(drbg, hash->C, 0x00, hash->V, drbg->seedlen);
}
static int drbg_hash_instantiate_wrapper(void *vdrbg, unsigned int strength,
int prediction_resistance,
const unsigned char *pstr,
size_t pstr_len,
const OSSL_PARAM params[])
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
int ret = 0;
if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
return 0;
if (!ossl_prov_is_running()
|| !drbg_hash_set_ctx_params_locked(drbg, params))
goto err;
ret = ossl_prov_drbg_instantiate(drbg, strength, prediction_resistance,
pstr, pstr_len);
err:
if (drbg->lock != NULL)
CRYPTO_THREAD_unlock(drbg->lock);
return ret;
}
/*
* SP800-90Ar1 10.1.1.3 Hash_DRBG_Reseed_Process:
*
* ent is entropy input bytes obtained from a randomness source.
* addin is additional input received from an application. May be NULL.
*
* Returns zero if an error occurs otherwise it returns 1.
*/
static int drbg_hash_reseed(PROV_DRBG *drbg,
const unsigned char *ent, size_t ent_len,
const unsigned char *adin, size_t adin_len)
{
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
/* (Step 1-2) V = Hash_df(0x01 || V || entropy_input || additional_input) */
/* V about to be updated so use C as output instead */
if (!hash_df(drbg, hash->C, 0x01, hash->V, drbg->seedlen, ent, ent_len,
adin, adin_len))
return 0;
memcpy(hash->V, hash->C, drbg->seedlen);
/* (Step 4) C = Hash_df(0x00||V, seedlen) */
return hash_df1(drbg, hash->C, 0x00, hash->V, drbg->seedlen);
}
static int drbg_hash_reseed_wrapper(void *vdrbg, int prediction_resistance,
const unsigned char *ent, size_t ent_len,
const unsigned char *adin, size_t adin_len)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
return ossl_prov_drbg_reseed(drbg, prediction_resistance, ent, ent_len,
adin, adin_len);
}
/*
* SP800-90Ar1 10.1.1.4 Hash_DRBG_Generate_Process:
*
* Generates pseudo random bytes using the drbg.
* out is a buffer to fill with outlen bytes of pseudo random data.
* addin is additional input received from an application. May be NULL.
*
* Returns zero if an error occurs otherwise it returns 1.
*/
static int drbg_hash_generate(PROV_DRBG *drbg,
unsigned char *out, size_t outlen,
const unsigned char *adin, size_t adin_len)
{
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
unsigned char counter[4];
int reseed_counter = drbg->generate_counter;
counter[0] = (unsigned char)((reseed_counter >> 24) & 0xff);
counter[1] = (unsigned char)((reseed_counter >> 16) & 0xff);
counter[2] = (unsigned char)((reseed_counter >> 8) & 0xff);
counter[3] = (unsigned char)(reseed_counter & 0xff);
return hash->ctx != NULL
&& (adin == NULL
/* (Step 2) if adin != NULL then V = V + Hash(0x02||V||adin) */
|| adin_len == 0
|| add_hash_to_v(drbg, 0x02, adin, adin_len))
/* (Step 3) Hashgen(outlen, V) */
&& hash_gen(drbg, out, outlen)
/* (Step 4/5) H = V = (V + Hash(0x03||V) mod (2^seedlen_bits) */
&& add_hash_to_v(drbg, 0x03, NULL, 0)
/* (Step 5) V = (V + H + C + reseed_counter) mod (2^seedlen_bits) */
/* V = (V + C) mod (2^seedlen_bits) */
&& add_bytes(drbg, hash->V, hash->C, drbg->seedlen)
/* V = (V + reseed_counter) mod (2^seedlen_bits) */
&& add_bytes(drbg, hash->V, counter, 4);
}
static int drbg_hash_generate_wrapper
(void *vdrbg, unsigned char *out, size_t outlen, unsigned int strength,
int prediction_resistance, const unsigned char *adin, size_t adin_len)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
return ossl_prov_drbg_generate(drbg, out, outlen, strength,
prediction_resistance, adin, adin_len);
}
static int drbg_hash_uninstantiate(PROV_DRBG *drbg)
{
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
OPENSSL_cleanse(hash->V, sizeof(hash->V));
OPENSSL_cleanse(hash->C, sizeof(hash->C));
OPENSSL_cleanse(hash->vtmp, sizeof(hash->vtmp));
return ossl_prov_drbg_uninstantiate(drbg);
}
static int drbg_hash_uninstantiate_wrapper(void *vdrbg)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
int ret;
if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
return 0;
ret = drbg_hash_uninstantiate(drbg);
if (drbg->lock != NULL)
CRYPTO_THREAD_unlock(drbg->lock);
return ret;
}
static int drbg_hash_verify_zeroization(void *vdrbg)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
int ret = 0;
if (drbg->lock != NULL && !CRYPTO_THREAD_read_lock(drbg->lock))
return 0;
PROV_DRBG_VERYIFY_ZEROIZATION(hash->V);
PROV_DRBG_VERYIFY_ZEROIZATION(hash->C);
PROV_DRBG_VERYIFY_ZEROIZATION(hash->vtmp);
ret = 1;
err:
if (drbg->lock != NULL)
CRYPTO_THREAD_unlock(drbg->lock);
return ret;
}
static int drbg_hash_new(PROV_DRBG *ctx)
{
PROV_DRBG_HASH *hash;
hash = OPENSSL_secure_zalloc(sizeof(*hash));
if (hash == NULL)
return 0;
ctx->data = hash;
ctx->seedlen = HASH_PRNG_MAX_SEEDLEN;
ctx->max_entropylen = DRBG_MAX_LENGTH;
ctx->max_noncelen = DRBG_MAX_LENGTH;
ctx->max_perslen = DRBG_MAX_LENGTH;
ctx->max_adinlen = DRBG_MAX_LENGTH;
/* Maximum number of bits per request = 2^19 = 2^16 bytes */
ctx->max_request = 1 << 16;
return 1;
}
static void *drbg_hash_new_wrapper(void *provctx, void *parent,
const OSSL_DISPATCH *parent_dispatch)
{
return ossl_rand_drbg_new(provctx, parent, parent_dispatch, &drbg_hash_new,
&drbg_hash_instantiate, &drbg_hash_uninstantiate,
&drbg_hash_reseed, &drbg_hash_generate);
}
static void drbg_hash_free(void *vdrbg)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
PROV_DRBG_HASH *hash;
if (drbg != NULL && (hash = (PROV_DRBG_HASH *)drbg->data) != NULL) {
EVP_MD_CTX_free(hash->ctx);
ossl_prov_digest_reset(&hash->digest);
OPENSSL_secure_clear_free(hash, sizeof(*hash));
}
ossl_rand_drbg_free(drbg);
}
static int drbg_hash_get_ctx_params(void *vdrbg, OSSL_PARAM params[])
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)drbg->data;
const EVP_MD *md;
OSSL_PARAM *p;
int ret = 0, complete = 0;
if (!ossl_drbg_get_ctx_params_no_lock(drbg, params, &complete))
return 0;
if (complete)
return 1;
if (drbg->lock != NULL && !CRYPTO_THREAD_read_lock(drbg->lock))
return 0;
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_DIGEST);
if (p != NULL) {
md = ossl_prov_digest_md(&hash->digest);
if (md == NULL || !OSSL_PARAM_set_utf8_string(p, EVP_MD_get0_name(md)))
goto err;
}
ret = ossl_drbg_get_ctx_params(drbg, params);
err:
if (drbg->lock != NULL)
CRYPTO_THREAD_unlock(drbg->lock);
return ret;
}
static const OSSL_PARAM *drbg_hash_gettable_ctx_params(ossl_unused void *vctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_DRBG_GETTABLE_CTX_COMMON,
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
static int drbg_hash_set_ctx_params_locked(void *vctx, const OSSL_PARAM params[])
{
PROV_DRBG *ctx = (PROV_DRBG *)vctx;
PROV_DRBG_HASH *hash = (PROV_DRBG_HASH *)ctx->data;
OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
const EVP_MD *md;
if (!ossl_prov_digest_load_from_params(&hash->digest, params, libctx))
return 0;
md = ossl_prov_digest_md(&hash->digest);
if (md != NULL) {
if (!ossl_drbg_verify_digest(libctx, md))
return 0; /* Error already raised for us */
/* These are taken from SP 800-90 10.1 Table 2 */
hash->blocklen = EVP_MD_get_size(md);
/* See SP800-57 Part1 Rev4 5.6.1 Table 3 */
ctx->strength = 64 * (hash->blocklen >> 3);
if (ctx->strength > 256)
ctx->strength = 256;
if (hash->blocklen > MAX_BLOCKLEN_USING_SMALL_SEEDLEN)
ctx->seedlen = HASH_PRNG_MAX_SEEDLEN;
else
ctx->seedlen = HASH_PRNG_SMALL_SEEDLEN;
ctx->min_entropylen = ctx->strength / 8;
ctx->min_noncelen = ctx->min_entropylen / 2;
}
return ossl_drbg_set_ctx_params(ctx, params);
}
static int drbg_hash_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
PROV_DRBG *drbg = (PROV_DRBG *)vctx;
int ret;
if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
return 0;
ret = drbg_hash_set_ctx_params_locked(vctx, params);
if (drbg->lock != NULL)
CRYPTO_THREAD_unlock(drbg->lock);
return ret;
}
static const OSSL_PARAM *drbg_hash_settable_ctx_params(ossl_unused void *vctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_DRBG_SETTABLE_CTX_COMMON,
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
const OSSL_DISPATCH ossl_drbg_hash_functions[] = {
{ OSSL_FUNC_RAND_NEWCTX, (void(*)(void))drbg_hash_new_wrapper },
{ OSSL_FUNC_RAND_FREECTX, (void(*)(void))drbg_hash_free },
{ OSSL_FUNC_RAND_INSTANTIATE,
(void(*)(void))drbg_hash_instantiate_wrapper },
{ OSSL_FUNC_RAND_UNINSTANTIATE,
(void(*)(void))drbg_hash_uninstantiate_wrapper },
{ OSSL_FUNC_RAND_GENERATE, (void(*)(void))drbg_hash_generate_wrapper },
{ OSSL_FUNC_RAND_RESEED, (void(*)(void))drbg_hash_reseed_wrapper },
{ OSSL_FUNC_RAND_ENABLE_LOCKING, (void(*)(void))ossl_drbg_enable_locking },
{ OSSL_FUNC_RAND_LOCK, (void(*)(void))ossl_drbg_lock },
{ OSSL_FUNC_RAND_UNLOCK, (void(*)(void))ossl_drbg_unlock },
{ OSSL_FUNC_RAND_SETTABLE_CTX_PARAMS,
(void(*)(void))drbg_hash_settable_ctx_params },
{ OSSL_FUNC_RAND_SET_CTX_PARAMS, (void(*)(void))drbg_hash_set_ctx_params },
{ OSSL_FUNC_RAND_GETTABLE_CTX_PARAMS,
(void(*)(void))drbg_hash_gettable_ctx_params },
{ OSSL_FUNC_RAND_GET_CTX_PARAMS, (void(*)(void))drbg_hash_get_ctx_params },
{ OSSL_FUNC_RAND_VERIFY_ZEROIZATION,
(void(*)(void))drbg_hash_verify_zeroization },
{ OSSL_FUNC_RAND_GET_SEED, (void(*)(void))ossl_drbg_get_seed },
{ OSSL_FUNC_RAND_CLEAR_SEED, (void(*)(void))ossl_drbg_clear_seed },
OSSL_DISPATCH_END
};
| 20,824 | 34.416667 | 82 | c |
openssl | openssl-master/providers/implementations/rands/drbg_hmac.c | /*
* Copyright 2011-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdlib.h>
#include <string.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/proverr.h>
#include "internal/thread_once.h"
#include "prov/providercommon.h"
#include "prov/implementations.h"
#include "prov/provider_ctx.h"
#include "prov/hmac_drbg.h"
#include "drbg_local.h"
static OSSL_FUNC_rand_newctx_fn drbg_hmac_new_wrapper;
static OSSL_FUNC_rand_freectx_fn drbg_hmac_free;
static OSSL_FUNC_rand_instantiate_fn drbg_hmac_instantiate_wrapper;
static OSSL_FUNC_rand_uninstantiate_fn drbg_hmac_uninstantiate_wrapper;
static OSSL_FUNC_rand_generate_fn drbg_hmac_generate_wrapper;
static OSSL_FUNC_rand_reseed_fn drbg_hmac_reseed_wrapper;
static OSSL_FUNC_rand_settable_ctx_params_fn drbg_hmac_settable_ctx_params;
static OSSL_FUNC_rand_set_ctx_params_fn drbg_hmac_set_ctx_params;
static OSSL_FUNC_rand_gettable_ctx_params_fn drbg_hmac_gettable_ctx_params;
static OSSL_FUNC_rand_get_ctx_params_fn drbg_hmac_get_ctx_params;
static OSSL_FUNC_rand_verify_zeroization_fn drbg_hmac_verify_zeroization;
static int drbg_hmac_set_ctx_params_locked(void *vctx, const OSSL_PARAM params[]);
/*
* Called twice by SP800-90Ar1 10.1.2.2 HMAC_DRBG_Update_Process.
*
* hmac is an object that holds the input/output Key and Value (K and V).
* inbyte is 0x00 on the first call and 0x01 on the second call.
* in1, in2, in3 are optional inputs that can be NULL.
* in1len, in2len, in3len are the lengths of the input buffers.
*
* The returned K,V is:
* hmac->K = HMAC(hmac->K, hmac->V || inbyte || [in1] || [in2] || [in3])
* hmac->V = HMAC(hmac->K, hmac->V)
*
* Returns zero if an error occurs otherwise it returns 1.
*/
static int do_hmac(PROV_DRBG_HMAC *hmac, unsigned char inbyte,
const unsigned char *in1, size_t in1len,
const unsigned char *in2, size_t in2len,
const unsigned char *in3, size_t in3len)
{
EVP_MAC_CTX *ctx = hmac->ctx;
if (!EVP_MAC_init(ctx, hmac->K, hmac->blocklen, NULL)
/* K = HMAC(K, V || inbyte || [in1] || [in2] || [in3]) */
|| !EVP_MAC_update(ctx, hmac->V, hmac->blocklen)
|| !EVP_MAC_update(ctx, &inbyte, 1)
|| !(in1 == NULL || in1len == 0 || EVP_MAC_update(ctx, in1, in1len))
|| !(in2 == NULL || in2len == 0 || EVP_MAC_update(ctx, in2, in2len))
|| !(in3 == NULL || in3len == 0 || EVP_MAC_update(ctx, in3, in3len))
|| !EVP_MAC_final(ctx, hmac->K, NULL, sizeof(hmac->K)))
return 0;
/* V = HMAC(K, V) */
return EVP_MAC_init(ctx, hmac->K, hmac->blocklen, NULL)
&& EVP_MAC_update(ctx, hmac->V, hmac->blocklen)
&& EVP_MAC_final(ctx, hmac->V, NULL, sizeof(hmac->V));
}
/*
* SP800-90Ar1 10.1.2.2 HMAC_DRBG_Update_Process
*
*
* Updates the drbg objects Key(K) and Value(V) using the following algorithm:
* K,V = do_hmac(hmac, 0, in1, in2, in3)
* if (any input is not NULL)
* K,V = do_hmac(hmac, 1, in1, in2, in3)
*
* where in1, in2, in3 are optional input buffers that can be NULL.
* in1len, in2len, in3len are the lengths of the input buffers.
*
* Returns zero if an error occurs otherwise it returns 1.
*/
static int drbg_hmac_update(PROV_DRBG_HMAC *hmac,
const unsigned char *in1, size_t in1len,
const unsigned char *in2, size_t in2len,
const unsigned char *in3, size_t in3len)
{
/* (Steps 1-2) K = HMAC(K, V||0x00||provided_data). V = HMAC(K,V) */
if (!do_hmac(hmac, 0x00, in1, in1len, in2, in2len, in3, in3len))
return 0;
/* (Step 3) If provided_data == NULL then return (K,V) */
if (in1len == 0 && in2len == 0 && in3len == 0)
return 1;
/* (Steps 4-5) K = HMAC(K, V||0x01||provided_data). V = HMAC(K,V) */
return do_hmac(hmac, 0x01, in1, in1len, in2, in2len, in3, in3len);
}
/*
* SP800-90Ar1 10.1.2.3 HMAC_DRBG_Instantiate_Process:
*
* This sets the drbg Key (K) to all zeros, and Value (V) to all 1's.
* and then calls (K,V) = drbg_hmac_update() with input parameters:
* ent = entropy data (Can be NULL) of length ent_len.
* nonce = nonce data (Can be NULL) of length nonce_len.
* pstr = personalization data (Can be NULL) of length pstr_len.
*
* Returns zero if an error occurs otherwise it returns 1.
*/
int ossl_drbg_hmac_init(PROV_DRBG_HMAC *hmac,
const unsigned char *ent, size_t ent_len,
const unsigned char *nonce, size_t nonce_len,
const unsigned char *pstr, size_t pstr_len)
{
if (hmac->ctx == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MAC);
return 0;
}
/* (Step 2) Key = 0x00 00...00 */
memset(hmac->K, 0x00, hmac->blocklen);
/* (Step 3) V = 0x01 01...01 */
memset(hmac->V, 0x01, hmac->blocklen);
/* (Step 4) (K,V) = HMAC_DRBG_Update(entropy||nonce||pers string, K, V) */
return drbg_hmac_update(hmac, ent, ent_len, nonce, nonce_len, pstr,
pstr_len);
}
static int drbg_hmac_instantiate(PROV_DRBG *drbg,
const unsigned char *ent, size_t ent_len,
const unsigned char *nonce, size_t nonce_len,
const unsigned char *pstr, size_t pstr_len)
{
return ossl_drbg_hmac_init((PROV_DRBG_HMAC *)drbg->data, ent, ent_len,
nonce, nonce_len, pstr, pstr_len);
}
static int drbg_hmac_instantiate_wrapper(void *vdrbg, unsigned int strength,
int prediction_resistance,
const unsigned char *pstr,
size_t pstr_len,
const OSSL_PARAM params[])
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
int ret = 0;
if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
return 0;
if (!ossl_prov_is_running()
|| !drbg_hmac_set_ctx_params_locked(drbg, params))
goto err;
ret = ossl_prov_drbg_instantiate(drbg, strength, prediction_resistance,
pstr, pstr_len);
err:
if (drbg->lock != NULL)
CRYPTO_THREAD_unlock(drbg->lock);
return ret;
}
/*
* SP800-90Ar1 10.1.2.4 HMAC_DRBG_Reseed_Process:
*
* Reseeds the drbg's Key (K) and Value (V) by calling
* (K,V) = drbg_hmac_update() with the following input parameters:
* ent = entropy input data (Can be NULL) of length ent_len.
* adin = additional input data (Can be NULL) of length adin_len.
*
* Returns zero if an error occurs otherwise it returns 1.
*/
static int drbg_hmac_reseed(PROV_DRBG *drbg,
const unsigned char *ent, size_t ent_len,
const unsigned char *adin, size_t adin_len)
{
PROV_DRBG_HMAC *hmac = (PROV_DRBG_HMAC *)drbg->data;
/* (Step 2) (K,V) = HMAC_DRBG_Update(entropy||additional_input, K, V) */
return drbg_hmac_update(hmac, ent, ent_len, adin, adin_len, NULL, 0);
}
static int drbg_hmac_reseed_wrapper(void *vdrbg, int prediction_resistance,
const unsigned char *ent, size_t ent_len,
const unsigned char *adin, size_t adin_len)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
return ossl_prov_drbg_reseed(drbg, prediction_resistance, ent, ent_len,
adin, adin_len);
}
/*
* SP800-90Ar1 10.1.2.5 HMAC_DRBG_Generate_Process:
*
* Generates pseudo random bytes and updates the internal K,V for the drbg.
* out is a buffer to fill with outlen bytes of pseudo random data.
* adin is an additional_input string of size adin_len that may be NULL.
*
* Returns zero if an error occurs otherwise it returns 1.
*/
int ossl_drbg_hmac_generate(PROV_DRBG_HMAC *hmac,
unsigned char *out, size_t outlen,
const unsigned char *adin, size_t adin_len)
{
EVP_MAC_CTX *ctx = hmac->ctx;
const unsigned char *temp = hmac->V;
/* (Step 2) if adin != NULL then (K,V) = HMAC_DRBG_Update(adin, K, V) */
if (adin != NULL
&& adin_len > 0
&& !drbg_hmac_update(hmac, adin, adin_len, NULL, 0, NULL, 0))
return 0;
/*
* (Steps 3-5) temp = NULL
* while (len(temp) < outlen) {
* V = HMAC(K, V)
* temp = temp || V
* }
*/
for (;;) {
if (!EVP_MAC_init(ctx, hmac->K, hmac->blocklen, NULL)
|| !EVP_MAC_update(ctx, temp, hmac->blocklen))
return 0;
if (outlen > hmac->blocklen) {
if (!EVP_MAC_final(ctx, out, NULL, outlen))
return 0;
temp = out;
} else {
if (!EVP_MAC_final(ctx, hmac->V, NULL, sizeof(hmac->V)))
return 0;
memcpy(out, hmac->V, outlen);
break;
}
out += hmac->blocklen;
outlen -= hmac->blocklen;
}
/* (Step 6) (K,V) = HMAC_DRBG_Update(adin, K, V) */
if (!drbg_hmac_update(hmac, adin, adin_len, NULL, 0, NULL, 0))
return 0;
return 1;
}
static int drbg_hmac_generate(PROV_DRBG *drbg,
unsigned char *out, size_t outlen,
const unsigned char *adin, size_t adin_len)
{
return ossl_drbg_hmac_generate((PROV_DRBG_HMAC *)drbg->data, out, outlen,
adin, adin_len);
}
static int drbg_hmac_generate_wrapper(void *vdrbg,
unsigned char *out, size_t outlen, unsigned int strength,
int prediction_resistance, const unsigned char *adin, size_t adin_len)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
return ossl_prov_drbg_generate(drbg, out, outlen, strength,
prediction_resistance, adin, adin_len);
}
static int drbg_hmac_uninstantiate(PROV_DRBG *drbg)
{
PROV_DRBG_HMAC *hmac = (PROV_DRBG_HMAC *)drbg->data;
OPENSSL_cleanse(hmac->K, sizeof(hmac->K));
OPENSSL_cleanse(hmac->V, sizeof(hmac->V));
return ossl_prov_drbg_uninstantiate(drbg);
}
static int drbg_hmac_uninstantiate_wrapper(void *vdrbg)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
int ret;
if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
return 0;
ret = drbg_hmac_uninstantiate(drbg);
if (drbg->lock != NULL)
CRYPTO_THREAD_unlock(drbg->lock);
return ret;
}
static int drbg_hmac_verify_zeroization(void *vdrbg)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
PROV_DRBG_HMAC *hmac = (PROV_DRBG_HMAC *)drbg->data;
int ret = 0;
if (drbg->lock != NULL && !CRYPTO_THREAD_read_lock(drbg->lock))
return 0;
PROV_DRBG_VERYIFY_ZEROIZATION(hmac->K);
PROV_DRBG_VERYIFY_ZEROIZATION(hmac->V);
ret = 1;
err:
if (drbg->lock != NULL)
CRYPTO_THREAD_unlock(drbg->lock);
return ret;
}
static int drbg_hmac_new(PROV_DRBG *drbg)
{
PROV_DRBG_HMAC *hmac;
hmac = OPENSSL_secure_zalloc(sizeof(*hmac));
if (hmac == NULL)
return 0;
drbg->data = hmac;
/* See SP800-57 Part1 Rev4 5.6.1 Table 3 */
drbg->max_entropylen = DRBG_MAX_LENGTH;
drbg->max_noncelen = DRBG_MAX_LENGTH;
drbg->max_perslen = DRBG_MAX_LENGTH;
drbg->max_adinlen = DRBG_MAX_LENGTH;
/* Maximum number of bits per request = 2^19 = 2^16 bytes */
drbg->max_request = 1 << 16;
return 1;
}
static void *drbg_hmac_new_wrapper(void *provctx, void *parent,
const OSSL_DISPATCH *parent_dispatch)
{
return ossl_rand_drbg_new(provctx, parent, parent_dispatch, &drbg_hmac_new,
&drbg_hmac_instantiate, &drbg_hmac_uninstantiate,
&drbg_hmac_reseed, &drbg_hmac_generate);
}
static void drbg_hmac_free(void *vdrbg)
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
PROV_DRBG_HMAC *hmac;
if (drbg != NULL && (hmac = (PROV_DRBG_HMAC *)drbg->data) != NULL) {
EVP_MAC_CTX_free(hmac->ctx);
ossl_prov_digest_reset(&hmac->digest);
OPENSSL_secure_clear_free(hmac, sizeof(*hmac));
}
ossl_rand_drbg_free(drbg);
}
static int drbg_hmac_get_ctx_params(void *vdrbg, OSSL_PARAM params[])
{
PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
PROV_DRBG_HMAC *hmac = (PROV_DRBG_HMAC *)drbg->data;
const char *name;
const EVP_MD *md;
OSSL_PARAM *p;
int ret = 0, complete = 0;
if (!ossl_drbg_get_ctx_params_no_lock(drbg, params, &complete))
return 0;
if (complete)
return 1;
if (drbg->lock != NULL && !CRYPTO_THREAD_read_lock(drbg->lock))
return 0;
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAC);
if (p != NULL) {
if (hmac->ctx == NULL)
goto err;
name = EVP_MAC_get0_name(EVP_MAC_CTX_get0_mac(hmac->ctx));
if (!OSSL_PARAM_set_utf8_string(p, name))
goto err;
}
p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_DIGEST);
if (p != NULL) {
md = ossl_prov_digest_md(&hmac->digest);
if (md == NULL || !OSSL_PARAM_set_utf8_string(p, EVP_MD_get0_name(md)))
goto err;
}
ret = ossl_drbg_get_ctx_params(drbg, params);
err:
if (drbg->lock != NULL)
CRYPTO_THREAD_unlock(drbg->lock);
return ret;
}
static const OSSL_PARAM *drbg_hmac_gettable_ctx_params(ossl_unused void *vctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_MAC, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_DRBG_GETTABLE_CTX_COMMON,
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
static int drbg_hmac_set_ctx_params_locked(void *vctx, const OSSL_PARAM params[])
{
PROV_DRBG *ctx = (PROV_DRBG *)vctx;
PROV_DRBG_HMAC *hmac = (PROV_DRBG_HMAC *)ctx->data;
OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
const EVP_MD *md;
if (!ossl_prov_digest_load_from_params(&hmac->digest, params, libctx))
return 0;
md = ossl_prov_digest_md(&hmac->digest);
if (md != NULL && !ossl_drbg_verify_digest(libctx, md))
return 0; /* Error already raised for us */
if (!ossl_prov_macctx_load_from_params(&hmac->ctx, params,
NULL, NULL, NULL, libctx))
return 0;
if (md != NULL && hmac->ctx != NULL) {
/* These are taken from SP 800-90 10.1 Table 2 */
hmac->blocklen = EVP_MD_get_size(md);
/* See SP800-57 Part1 Rev4 5.6.1 Table 3 */
ctx->strength = 64 * (int)(hmac->blocklen >> 3);
if (ctx->strength > 256)
ctx->strength = 256;
ctx->seedlen = hmac->blocklen;
ctx->min_entropylen = ctx->strength / 8;
ctx->min_noncelen = ctx->min_entropylen / 2;
}
return ossl_drbg_set_ctx_params(ctx, params);
}
static int drbg_hmac_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
PROV_DRBG *drbg = (PROV_DRBG *)vctx;
int ret;
if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
return 0;
ret = drbg_hmac_set_ctx_params_locked(vctx, params);
if (drbg->lock != NULL)
CRYPTO_THREAD_unlock(drbg->lock);
return ret;
}
static const OSSL_PARAM *drbg_hmac_settable_ctx_params(ossl_unused void *vctx,
ossl_unused void *p_ctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_DRBG_PARAM_MAC, NULL, 0),
OSSL_PARAM_DRBG_SETTABLE_CTX_COMMON,
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
const OSSL_DISPATCH ossl_drbg_ossl_hmac_functions[] = {
{ OSSL_FUNC_RAND_NEWCTX, (void(*)(void))drbg_hmac_new_wrapper },
{ OSSL_FUNC_RAND_FREECTX, (void(*)(void))drbg_hmac_free },
{ OSSL_FUNC_RAND_INSTANTIATE,
(void(*)(void))drbg_hmac_instantiate_wrapper },
{ OSSL_FUNC_RAND_UNINSTANTIATE,
(void(*)(void))drbg_hmac_uninstantiate_wrapper },
{ OSSL_FUNC_RAND_GENERATE, (void(*)(void))drbg_hmac_generate_wrapper },
{ OSSL_FUNC_RAND_RESEED, (void(*)(void))drbg_hmac_reseed_wrapper },
{ OSSL_FUNC_RAND_ENABLE_LOCKING, (void(*)(void))ossl_drbg_enable_locking },
{ OSSL_FUNC_RAND_LOCK, (void(*)(void))ossl_drbg_lock },
{ OSSL_FUNC_RAND_UNLOCK, (void(*)(void))ossl_drbg_unlock },
{ OSSL_FUNC_RAND_SETTABLE_CTX_PARAMS,
(void(*)(void))drbg_hmac_settable_ctx_params },
{ OSSL_FUNC_RAND_SET_CTX_PARAMS, (void(*)(void))drbg_hmac_set_ctx_params },
{ OSSL_FUNC_RAND_GETTABLE_CTX_PARAMS,
(void(*)(void))drbg_hmac_gettable_ctx_params },
{ OSSL_FUNC_RAND_GET_CTX_PARAMS, (void(*)(void))drbg_hmac_get_ctx_params },
{ OSSL_FUNC_RAND_VERIFY_ZEROIZATION,
(void(*)(void))drbg_hmac_verify_zeroization },
{ OSSL_FUNC_RAND_GET_SEED, (void(*)(void))ossl_drbg_get_seed },
{ OSSL_FUNC_RAND_CLEAR_SEED, (void(*)(void))ossl_drbg_clear_seed },
OSSL_DISPATCH_END
};
| 17,585 | 34.743902 | 82 | c |
openssl | openssl-master/providers/implementations/rands/seed_src.c | /*
* Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include <openssl/rand.h>
#include <openssl/core_dispatch.h>
#include <openssl/e_os2.h>
#include <openssl/params.h>
#include <openssl/core_names.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/randerr.h>
#include <openssl/proverr.h>
#include "prov/implementations.h"
#include "prov/provider_ctx.h"
#include "crypto/rand.h"
#include "crypto/rand_pool.h"
static OSSL_FUNC_rand_newctx_fn seed_src_new;
static OSSL_FUNC_rand_freectx_fn seed_src_free;
static OSSL_FUNC_rand_instantiate_fn seed_src_instantiate;
static OSSL_FUNC_rand_uninstantiate_fn seed_src_uninstantiate;
static OSSL_FUNC_rand_generate_fn seed_src_generate;
static OSSL_FUNC_rand_reseed_fn seed_src_reseed;
static OSSL_FUNC_rand_gettable_ctx_params_fn seed_src_gettable_ctx_params;
static OSSL_FUNC_rand_get_ctx_params_fn seed_src_get_ctx_params;
static OSSL_FUNC_rand_verify_zeroization_fn seed_src_verify_zeroization;
static OSSL_FUNC_rand_enable_locking_fn seed_src_enable_locking;
static OSSL_FUNC_rand_lock_fn seed_src_lock;
static OSSL_FUNC_rand_unlock_fn seed_src_unlock;
static OSSL_FUNC_rand_get_seed_fn seed_get_seed;
static OSSL_FUNC_rand_clear_seed_fn seed_clear_seed;
typedef struct {
void *provctx;
int state;
} PROV_SEED_SRC;
static void *seed_src_new(void *provctx, void *parent,
const OSSL_DISPATCH *parent_dispatch)
{
PROV_SEED_SRC *s;
if (parent != NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_SEED_SOURCES_MUST_NOT_HAVE_A_PARENT);
return NULL;
}
s = OPENSSL_zalloc(sizeof(*s));
if (s == NULL)
return NULL;
s->provctx = provctx;
s->state = EVP_RAND_STATE_UNINITIALISED;
return s;
}
static void seed_src_free(void *vseed)
{
OPENSSL_free(vseed);
}
static int seed_src_instantiate(void *vseed, unsigned int strength,
int prediction_resistance,
const unsigned char *pstr, size_t pstr_len,
ossl_unused const OSSL_PARAM params[])
{
PROV_SEED_SRC *s = (PROV_SEED_SRC *)vseed;
s->state = EVP_RAND_STATE_READY;
return 1;
}
static int seed_src_uninstantiate(void *vseed)
{
PROV_SEED_SRC *s = (PROV_SEED_SRC *)vseed;
s->state = EVP_RAND_STATE_UNINITIALISED;
return 1;
}
static int seed_src_generate(void *vseed, unsigned char *out, size_t outlen,
unsigned int strength,
ossl_unused int prediction_resistance,
ossl_unused const unsigned char *adin,
ossl_unused size_t adin_len)
{
PROV_SEED_SRC *s = (PROV_SEED_SRC *)vseed;
size_t entropy_available;
RAND_POOL *pool;
if (s->state != EVP_RAND_STATE_READY) {
ERR_raise(ERR_LIB_PROV,
s->state == EVP_RAND_STATE_ERROR ? PROV_R_IN_ERROR_STATE
: PROV_R_NOT_INSTANTIATED);
return 0;
}
pool = ossl_rand_pool_new(strength, 1, outlen, outlen);
if (pool == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_RAND_LIB);
return 0;
}
/* Get entropy by polling system entropy sources. */
entropy_available = ossl_pool_acquire_entropy(pool);
if (entropy_available > 0)
memcpy(out, ossl_rand_pool_buffer(pool), ossl_rand_pool_length(pool));
ossl_rand_pool_free(pool);
return entropy_available > 0;
}
static int seed_src_reseed(void *vseed,
ossl_unused int prediction_resistance,
ossl_unused const unsigned char *ent,
ossl_unused size_t ent_len,
ossl_unused const unsigned char *adin,
ossl_unused size_t adin_len)
{
PROV_SEED_SRC *s = (PROV_SEED_SRC *)vseed;
if (s->state != EVP_RAND_STATE_READY) {
ERR_raise(ERR_LIB_PROV,
s->state == EVP_RAND_STATE_ERROR ? PROV_R_IN_ERROR_STATE
: PROV_R_NOT_INSTANTIATED);
return 0;
}
return 1;
}
static int seed_src_get_ctx_params(void *vseed, OSSL_PARAM params[])
{
PROV_SEED_SRC *s = (PROV_SEED_SRC *)vseed;
OSSL_PARAM *p;
p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STATE);
if (p != NULL && !OSSL_PARAM_set_int(p, s->state))
return 0;
p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STRENGTH);
if (p != NULL && !OSSL_PARAM_set_int(p, 1024))
return 0;
p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_MAX_REQUEST);
if (p != NULL && !OSSL_PARAM_set_size_t(p, 128))
return 0;
return 1;
}
static const OSSL_PARAM *seed_src_gettable_ctx_params(ossl_unused void *vseed,
ossl_unused void *provctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_int(OSSL_RAND_PARAM_STATE, NULL),
OSSL_PARAM_uint(OSSL_RAND_PARAM_STRENGTH, NULL),
OSSL_PARAM_size_t(OSSL_RAND_PARAM_MAX_REQUEST, NULL),
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
static int seed_src_verify_zeroization(ossl_unused void *vseed)
{
return 1;
}
static size_t seed_get_seed(void *vseed, unsigned char **pout,
int entropy, size_t min_len, size_t max_len,
int prediction_resistance,
const unsigned char *adin, size_t adin_len)
{
size_t bytes_needed;
unsigned char *p;
/*
* Figure out how many bytes we need.
* This assumes that the seed sources provide eight bits of entropy
* per byte. For lower quality sources, the formula will need to be
* different.
*/
bytes_needed = entropy >= 0 ? (entropy + 7) / 8 : 0;
if (bytes_needed < min_len)
bytes_needed = min_len;
if (bytes_needed > max_len) {
ERR_raise(ERR_LIB_PROV, PROV_R_ENTROPY_SOURCE_STRENGTH_TOO_WEAK);
return 0;
}
p = OPENSSL_secure_malloc(bytes_needed);
if (p == NULL)
return 0;
if (seed_src_generate(vseed, p, bytes_needed, 0, prediction_resistance,
adin, adin_len) != 0) {
*pout = p;
return bytes_needed;
}
OPENSSL_secure_clear_free(p, bytes_needed);
return 0;
}
static void seed_clear_seed(ossl_unused void *vdrbg,
unsigned char *out, size_t outlen)
{
OPENSSL_secure_clear_free(out, outlen);
}
static int seed_src_enable_locking(ossl_unused void *vseed)
{
return 1;
}
int seed_src_lock(ossl_unused void *vctx)
{
return 1;
}
void seed_src_unlock(ossl_unused void *vctx)
{
}
const OSSL_DISPATCH ossl_seed_src_functions[] = {
{ OSSL_FUNC_RAND_NEWCTX, (void(*)(void))seed_src_new },
{ OSSL_FUNC_RAND_FREECTX, (void(*)(void))seed_src_free },
{ OSSL_FUNC_RAND_INSTANTIATE,
(void(*)(void))seed_src_instantiate },
{ OSSL_FUNC_RAND_UNINSTANTIATE,
(void(*)(void))seed_src_uninstantiate },
{ OSSL_FUNC_RAND_GENERATE, (void(*)(void))seed_src_generate },
{ OSSL_FUNC_RAND_RESEED, (void(*)(void))seed_src_reseed },
{ OSSL_FUNC_RAND_ENABLE_LOCKING, (void(*)(void))seed_src_enable_locking },
{ OSSL_FUNC_RAND_LOCK, (void(*)(void))seed_src_lock },
{ OSSL_FUNC_RAND_UNLOCK, (void(*)(void))seed_src_unlock },
{ OSSL_FUNC_RAND_GETTABLE_CTX_PARAMS,
(void(*)(void))seed_src_gettable_ctx_params },
{ OSSL_FUNC_RAND_GET_CTX_PARAMS, (void(*)(void))seed_src_get_ctx_params },
{ OSSL_FUNC_RAND_VERIFY_ZEROIZATION,
(void(*)(void))seed_src_verify_zeroization },
{ OSSL_FUNC_RAND_GET_SEED, (void(*)(void))seed_get_seed },
{ OSSL_FUNC_RAND_CLEAR_SEED, (void(*)(void))seed_clear_seed },
OSSL_DISPATCH_END
};
| 8,099 | 31.4 | 80 | c |
openssl | openssl-master/providers/implementations/rands/test_rng.c | /*
* Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include <openssl/core_dispatch.h>
#include <openssl/e_os2.h>
#include <openssl/params.h>
#include <openssl/core_names.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/randerr.h>
#include "prov/providercommon.h"
#include "prov/provider_ctx.h"
#include "prov/provider_util.h"
#include "prov/implementations.h"
static OSSL_FUNC_rand_newctx_fn test_rng_new;
static OSSL_FUNC_rand_freectx_fn test_rng_free;
static OSSL_FUNC_rand_instantiate_fn test_rng_instantiate;
static OSSL_FUNC_rand_uninstantiate_fn test_rng_uninstantiate;
static OSSL_FUNC_rand_generate_fn test_rng_generate;
static OSSL_FUNC_rand_reseed_fn test_rng_reseed;
static OSSL_FUNC_rand_nonce_fn test_rng_nonce;
static OSSL_FUNC_rand_settable_ctx_params_fn test_rng_settable_ctx_params;
static OSSL_FUNC_rand_set_ctx_params_fn test_rng_set_ctx_params;
static OSSL_FUNC_rand_gettable_ctx_params_fn test_rng_gettable_ctx_params;
static OSSL_FUNC_rand_get_ctx_params_fn test_rng_get_ctx_params;
static OSSL_FUNC_rand_verify_zeroization_fn test_rng_verify_zeroization;
static OSSL_FUNC_rand_enable_locking_fn test_rng_enable_locking;
static OSSL_FUNC_rand_lock_fn test_rng_lock;
static OSSL_FUNC_rand_unlock_fn test_rng_unlock;
static OSSL_FUNC_rand_get_seed_fn test_rng_get_seed;
typedef struct {
void *provctx;
int state;
unsigned int strength;
size_t max_request;
unsigned char *entropy, *nonce;
size_t entropy_len, entropy_pos, nonce_len;
CRYPTO_RWLOCK *lock;
} PROV_TEST_RNG;
static void *test_rng_new(void *provctx, void *parent,
const OSSL_DISPATCH *parent_dispatch)
{
PROV_TEST_RNG *t;
t = OPENSSL_zalloc(sizeof(*t));
if (t == NULL)
return NULL;
t->max_request = INT_MAX;
t->provctx = provctx;
t->state = EVP_RAND_STATE_UNINITIALISED;
return t;
}
static void test_rng_free(void *vtest)
{
PROV_TEST_RNG *t = (PROV_TEST_RNG *)vtest;
if (t == NULL)
return;
OPENSSL_free(t->entropy);
OPENSSL_free(t->nonce);
CRYPTO_THREAD_lock_free(t->lock);
OPENSSL_free(t);
}
static int test_rng_instantiate(void *vtest, unsigned int strength,
int prediction_resistance,
const unsigned char *pstr, size_t pstr_len,
const OSSL_PARAM params[])
{
PROV_TEST_RNG *t = (PROV_TEST_RNG *)vtest;
if (!test_rng_set_ctx_params(t, params) || strength > t->strength)
return 0;
t->state = EVP_RAND_STATE_READY;
t->entropy_pos = 0;
return 1;
}
static int test_rng_uninstantiate(void *vtest)
{
PROV_TEST_RNG *t = (PROV_TEST_RNG *)vtest;
t->entropy_pos = 0;
t->state = EVP_RAND_STATE_UNINITIALISED;
return 1;
}
static int test_rng_generate(void *vtest, unsigned char *out, size_t outlen,
unsigned int strength, int prediction_resistance,
const unsigned char *adin, size_t adin_len)
{
PROV_TEST_RNG *t = (PROV_TEST_RNG *)vtest;
if (strength > t->strength || t->entropy_len - t->entropy_pos < outlen)
return 0;
memcpy(out, t->entropy + t->entropy_pos, outlen);
t->entropy_pos += outlen;
return 1;
}
static int test_rng_reseed(ossl_unused void *vtest,
ossl_unused int prediction_resistance,
ossl_unused const unsigned char *ent,
ossl_unused size_t ent_len,
ossl_unused const unsigned char *adin,
ossl_unused size_t adin_len)
{
return 1;
}
static size_t test_rng_nonce(void *vtest, unsigned char *out,
unsigned int strength,
ossl_unused size_t min_noncelen,
ossl_unused size_t max_noncelen)
{
PROV_TEST_RNG *t = (PROV_TEST_RNG *)vtest;
if (t->nonce == NULL || strength > t->strength)
return 0;
if (out != NULL)
memcpy(out, t->nonce, t->nonce_len);
return t->nonce_len;
}
static int test_rng_get_ctx_params(void *vtest, OSSL_PARAM params[])
{
PROV_TEST_RNG *t = (PROV_TEST_RNG *)vtest;
OSSL_PARAM *p;
p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STATE);
if (p != NULL && !OSSL_PARAM_set_int(p, t->state))
return 0;
p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STRENGTH);
if (p != NULL && !OSSL_PARAM_set_int(p, t->strength))
return 0;
p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_MAX_REQUEST);
if (p != NULL && !OSSL_PARAM_set_size_t(p, t->max_request))
return 0;
return 1;
}
static const OSSL_PARAM *test_rng_gettable_ctx_params(ossl_unused void *vtest,
ossl_unused void *provctx)
{
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_int(OSSL_RAND_PARAM_STATE, NULL),
OSSL_PARAM_uint(OSSL_RAND_PARAM_STRENGTH, NULL),
OSSL_PARAM_size_t(OSSL_RAND_PARAM_MAX_REQUEST, NULL),
OSSL_PARAM_END
};
return known_gettable_ctx_params;
}
static int test_rng_set_ctx_params(void *vtest, const OSSL_PARAM params[])
{
PROV_TEST_RNG *t = (PROV_TEST_RNG *)vtest;
const OSSL_PARAM *p;
void *ptr = NULL;
size_t size = 0;
if (params == NULL)
return 1;
p = OSSL_PARAM_locate_const(params, OSSL_RAND_PARAM_STRENGTH);
if (p != NULL && !OSSL_PARAM_get_uint(p, &t->strength))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_RAND_PARAM_TEST_ENTROPY);
if (p != NULL) {
if (!OSSL_PARAM_get_octet_string(p, &ptr, 0, &size))
return 0;
OPENSSL_free(t->entropy);
t->entropy = ptr;
t->entropy_len = size;
t->entropy_pos = 0;
ptr = NULL;
}
p = OSSL_PARAM_locate_const(params, OSSL_RAND_PARAM_TEST_NONCE);
if (p != NULL) {
if (!OSSL_PARAM_get_octet_string(p, &ptr, 0, &size))
return 0;
OPENSSL_free(t->nonce);
t->nonce = ptr;
t->nonce_len = size;
}
p = OSSL_PARAM_locate_const(params, OSSL_RAND_PARAM_MAX_REQUEST);
if (p != NULL && !OSSL_PARAM_get_size_t(p, &t->max_request))
return 0;
return 1;
}
static const OSSL_PARAM *test_rng_settable_ctx_params(ossl_unused void *vtest,
ossl_unused void *provctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY, NULL, 0),
OSSL_PARAM_octet_string(OSSL_RAND_PARAM_TEST_NONCE, NULL, 0),
OSSL_PARAM_uint(OSSL_RAND_PARAM_STRENGTH, NULL),
OSSL_PARAM_size_t(OSSL_RAND_PARAM_MAX_REQUEST, NULL),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
static int test_rng_verify_zeroization(ossl_unused void *vtest)
{
return 1;
}
static size_t test_rng_get_seed(void *vtest, unsigned char **pout,
int entropy, size_t min_len, size_t max_len,
ossl_unused int prediction_resistance,
ossl_unused const unsigned char *adin,
ossl_unused size_t adin_len)
{
PROV_TEST_RNG *t = (PROV_TEST_RNG *)vtest;
*pout = t->entropy;
return t->entropy_len > max_len ? max_len : t->entropy_len;
}
static int test_rng_enable_locking(void *vtest)
{
PROV_TEST_RNG *t = (PROV_TEST_RNG *)vtest;
if (t != NULL && t->lock == NULL) {
t->lock = CRYPTO_THREAD_lock_new();
if (t->lock == NULL) {
ERR_raise(ERR_LIB_PROV, RAND_R_FAILED_TO_CREATE_LOCK);
return 0;
}
}
return 1;
}
static int test_rng_lock(void *vtest)
{
PROV_TEST_RNG *t = (PROV_TEST_RNG *)vtest;
if (t == NULL || t->lock == NULL)
return 1;
return CRYPTO_THREAD_write_lock(t->lock);
}
static void test_rng_unlock(void *vtest)
{
PROV_TEST_RNG *t = (PROV_TEST_RNG *)vtest;
if (t != NULL && t->lock != NULL)
CRYPTO_THREAD_unlock(t->lock);
}
const OSSL_DISPATCH ossl_test_rng_functions[] = {
{ OSSL_FUNC_RAND_NEWCTX, (void(*)(void))test_rng_new },
{ OSSL_FUNC_RAND_FREECTX, (void(*)(void))test_rng_free },
{ OSSL_FUNC_RAND_INSTANTIATE,
(void(*)(void))test_rng_instantiate },
{ OSSL_FUNC_RAND_UNINSTANTIATE,
(void(*)(void))test_rng_uninstantiate },
{ OSSL_FUNC_RAND_GENERATE, (void(*)(void))test_rng_generate },
{ OSSL_FUNC_RAND_RESEED, (void(*)(void))test_rng_reseed },
{ OSSL_FUNC_RAND_NONCE, (void(*)(void))test_rng_nonce },
{ OSSL_FUNC_RAND_ENABLE_LOCKING, (void(*)(void))test_rng_enable_locking },
{ OSSL_FUNC_RAND_LOCK, (void(*)(void))test_rng_lock },
{ OSSL_FUNC_RAND_UNLOCK, (void(*)(void))test_rng_unlock },
{ OSSL_FUNC_RAND_SETTABLE_CTX_PARAMS,
(void(*)(void))test_rng_settable_ctx_params },
{ OSSL_FUNC_RAND_SET_CTX_PARAMS, (void(*)(void))test_rng_set_ctx_params },
{ OSSL_FUNC_RAND_GETTABLE_CTX_PARAMS,
(void(*)(void))test_rng_gettable_ctx_params },
{ OSSL_FUNC_RAND_GET_CTX_PARAMS, (void(*)(void))test_rng_get_ctx_params },
{ OSSL_FUNC_RAND_VERIFY_ZEROIZATION,
(void(*)(void))test_rng_verify_zeroization },
{ OSSL_FUNC_RAND_GET_SEED, (void(*)(void))test_rng_get_seed },
OSSL_DISPATCH_END
};
| 9,662 | 31.535354 | 80 | c |
openssl | openssl-master/providers/implementations/rands/seeding/rand_cpu_arm64.c | /*
* Copyright 2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/cryptlib.h"
#include <openssl/opensslconf.h>
#include "crypto/rand_pool.h"
#include "prov/seeding.h"
#ifdef OPENSSL_RAND_SEED_RDCPU
#include "crypto/arm_arch.h"
size_t OPENSSL_rndrrs_bytes(unsigned char *buf, size_t len);
static size_t get_hardware_random_value(unsigned char *buf, size_t len);
/*
* Acquire entropy using Arm-specific cpu instructions
*
* Uses the RNDRRS instruction. RNDR is never needed since
* RNDRRS will always be available if RNDR is an available
* instruction.
*
* Returns the total entropy count, if it exceeds the requested
* entropy count. Otherwise, returns an entropy count of 0.
*/
size_t ossl_prov_acquire_entropy_from_cpu(RAND_POOL *pool)
{
size_t bytes_needed;
unsigned char *buffer;
bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
if (bytes_needed > 0) {
buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
if (buffer != NULL) {
if (get_hardware_random_value(buffer, bytes_needed) == bytes_needed)
ossl_rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
else
ossl_rand_pool_add_end(pool, 0, 0);
}
}
return ossl_rand_pool_entropy_available(pool);
}
static size_t get_hardware_random_value(unsigned char *buf, size_t len)
{
/* Always use RNDRRS or nothing */
if (OPENSSL_armcap_P & ARMV8_RNG) {
if (OPENSSL_rndrrs_bytes(buf, len) != len)
return 0;
} else {
return 0;
}
return len;
}
#else
NON_EMPTY_TRANSLATION_UNIT
#endif /* OPENSSL_RAND_SEED_RDCPU */
| 1,941 | 27.558824 | 80 | c |
openssl | openssl-master/providers/implementations/rands/seeding/rand_cpu_x86.c | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/cryptlib.h"
#include <openssl/opensslconf.h>
#include "crypto/rand_pool.h"
#include "prov/seeding.h"
#ifdef OPENSSL_RAND_SEED_RDCPU
# if defined(OPENSSL_SYS_TANDEM) && defined(_TNS_X_TARGET)
# include <builtin.h> /* _rdrand64 */
# include <string.h> /* memcpy */
# else
size_t OPENSSL_ia32_rdseed_bytes(unsigned char *buf, size_t len);
size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len);
# endif
static size_t get_hardware_random_value(unsigned char *buf, size_t len);
/*
* Acquire entropy using Intel-specific cpu instructions
*
* Uses the RDSEED instruction if available, otherwise uses
* RDRAND if available.
*
* For the differences between RDSEED and RDRAND, and why RDSEED
* is the preferred choice, see https://goo.gl/oK3KcN
*
* Returns the total entropy count, if it exceeds the requested
* entropy count. Otherwise, returns an entropy count of 0.
*/
size_t ossl_prov_acquire_entropy_from_cpu(RAND_POOL *pool)
{
size_t bytes_needed;
unsigned char *buffer;
bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
if (bytes_needed > 0) {
buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
if (buffer != NULL) {
if (get_hardware_random_value(buffer, bytes_needed) == bytes_needed) {
ossl_rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
} else {
ossl_rand_pool_add_end(pool, 0, 0);
}
}
}
return ossl_rand_pool_entropy_available(pool);
}
#if defined(OPENSSL_SYS_TANDEM) && defined(_TNS_X_TARGET)
/* Obtain random bytes from the x86 hardware random function in 64 bit chunks */
static size_t get_hardware_random_value(unsigned char *buf, size_t len)
{
size_t bytes_remaining = len;
while (bytes_remaining > 0) {
/* Always use 64 bit fetch, then use the lower bytes as needed. */
/* The platform is big-endian. */
uint64_t random_value = 0;
if (_rdrand64(&random_value) != 0) {
unsigned char *random_buffer = (unsigned char *)&random_value;
if (bytes_remaining >= sizeof(random_value)) {
memcpy(buf, random_buffer, sizeof(random_value));
bytes_remaining -= sizeof(random_value);
buf += sizeof(random_value);
} else {
memcpy(buf,
random_buffer + (sizeof(random_value) - bytes_remaining),
bytes_remaining);
bytes_remaining = 0; /* This will terminate the loop */
}
} else
break;
}
if (bytes_remaining == 0)
return len;
return 0;
}
#else
static size_t get_hardware_random_value(unsigned char *buf, size_t len) {
/* Whichever comes first, use RDSEED, RDRAND or nothing */
if ((OPENSSL_ia32cap_P[2] & (1 << 18)) != 0) {
if (OPENSSL_ia32_rdseed_bytes(buf, len) != len)
return 0;
} else if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) {
if (OPENSSL_ia32_rdrand_bytes(buf, len) != len)
return 0;
} else
return 0;
return len;
}
#endif
#else
NON_EMPTY_TRANSLATION_UNIT
#endif
| 3,490 | 31.324074 | 82 | c |
openssl | openssl-master/providers/implementations/rands/seeding/rand_tsc.c | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/cryptlib.h"
#include <openssl/opensslconf.h>
#include "crypto/rand_pool.h"
#include "prov/seeding.h"
#ifdef OPENSSL_RAND_SEED_RDTSC
/*
* IMPORTANT NOTE: It is not currently possible to use this code
* because we are not sure about the amount of randomness it provides.
* Some SP800-90B tests have been run, but there is internal skepticism.
* So for now this code is not used.
*/
# error "RDTSC enabled? Should not be possible!"
/*
* Acquire entropy from high-speed clock
*
* Since we get some randomness from the low-order bits of the
* high-speed clock, it can help.
*
* Returns the total entropy count, if it exceeds the requested
* entropy count. Otherwise, returns an entropy count of 0.
*/
size_t ossl_prov_acquire_entropy_from_tsc(RAND_POOL *pool)
{
unsigned char c;
int i;
if ((OPENSSL_ia32cap_P[0] & (1 << 4)) != 0) {
for (i = 0; i < TSC_READ_COUNT; i++) {
c = (unsigned char)(OPENSSL_rdtsc() & 0xFF);
ossl_rand_pool_add(pool, &c, 1, 4);
}
}
return ossl_rand_pool_entropy_available(pool);
}
#else
NON_EMPTY_TRANSLATION_UNIT
#endif
| 1,474 | 29.102041 | 74 | c |
openssl | openssl-master/providers/implementations/rands/seeding/rand_unix.c | /*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include "internal/e_os.h"
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/rand.h>
#include <openssl/crypto.h>
#include "crypto/rand_pool.h"
#include "crypto/rand.h"
#include "internal/dso.h"
#include "internal/nelem.h"
#include "prov/seeding.h"
#ifdef __linux
# include <sys/syscall.h>
# ifdef DEVRANDOM_WAIT
# include <sys/shm.h>
# include <sys/utsname.h>
# endif
#endif
#if (defined(__FreeBSD__) || defined(__NetBSD__)) && !defined(OPENSSL_SYS_UEFI)
# include <sys/types.h>
# include <sys/sysctl.h>
# include <sys/param.h>
#endif
#if defined(__OpenBSD__)
# include <sys/param.h>
#endif
#if defined(__DragonFly__)
# include <sys/param.h>
# include <sys/random.h>
#endif
#if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
|| defined(__DJGPP__)
# include <sys/types.h>
# include <sys/stat.h>
# include <fcntl.h>
# include <unistd.h>
# include <sys/time.h>
static uint64_t get_time_stamp(void);
/* Macro to convert two thirty two bit values into a sixty four bit one */
# define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
/*
* Check for the existence and support of POSIX timers. The standard
* says that the _POSIX_TIMERS macro will have a positive value if they
* are available.
*
* However, we want an additional constraint: that the timer support does
* not require an extra library dependency. Early versions of glibc
* require -lrt to be specified on the link line to access the timers,
* so this needs to be checked for.
*
* It is worse because some libraries define __GLIBC__ but don't
* support the version testing macro (e.g. uClibc). This means
* an extra check is needed.
*
* The final condition is:
* "have posix timers and either not glibc or glibc without -lrt"
*
* The nested #if sequences are required to avoid using a parameterised
* macro that might be undefined.
*/
# undef OSSL_POSIX_TIMER_OKAY
/* On some systems, _POSIX_TIMERS is defined but empty.
* Subtracting by 0 when comparing avoids an error in this case. */
# if defined(_POSIX_TIMERS) && _POSIX_TIMERS -0 > 0
# if defined(__GLIBC__)
# if defined(__GLIBC_PREREQ)
# if __GLIBC_PREREQ(2, 17)
# define OSSL_POSIX_TIMER_OKAY
# endif
# endif
# else
# define OSSL_POSIX_TIMER_OKAY
# endif
# endif
#endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS))
|| defined(__DJGPP__) */
#if defined(OPENSSL_RAND_SEED_NONE)
/* none means none. this simplifies the following logic */
# undef OPENSSL_RAND_SEED_OS
# undef OPENSSL_RAND_SEED_GETRANDOM
# undef OPENSSL_RAND_SEED_LIBRANDOM
# undef OPENSSL_RAND_SEED_DEVRANDOM
# undef OPENSSL_RAND_SEED_RDTSC
# undef OPENSSL_RAND_SEED_RDCPU
# undef OPENSSL_RAND_SEED_EGD
#endif
#if defined(OPENSSL_SYS_UEFI) && !defined(OPENSSL_RAND_SEED_NONE)
# error "UEFI only supports seeding NONE"
#endif
#if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
|| defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
|| defined(OPENSSL_SYS_UEFI))
# if defined(OPENSSL_SYS_VOS)
# ifndef OPENSSL_RAND_SEED_OS
# error "Unsupported seeding method configured; must be os"
# endif
# if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
# error "Unsupported HP-PA and IA32 at the same time."
# endif
# if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
# error "Must have one of HP-PA or IA32"
# endif
/*
* The following algorithm repeatedly samples the real-time clock (RTC) to
* generate a sequence of unpredictable data. The algorithm relies upon the
* uneven execution speed of the code (due to factors such as cache misses,
* interrupts, bus activity, and scheduling) and upon the rather large
* relative difference between the speed of the clock and the rate at which
* it can be read. If it is ported to an environment where execution speed
* is more constant or where the RTC ticks at a much slower rate, or the
* clock can be read with fewer instructions, it is likely that the results
* would be far more predictable. This should only be used for legacy
* platforms.
*
* As a precaution, we assume only 2 bits of entropy per byte.
*/
size_t ossl_pool_acquire_entropy(RAND_POOL *pool)
{
short int code;
int i, k;
size_t bytes_needed;
struct timespec ts;
unsigned char v;
# ifdef OPENSSL_SYS_VOS_HPPA
long duration;
extern void s$sleep(long *_duration, short int *_code);
# else
long long duration;
extern void s$sleep2(long long *_duration, short int *_code);
# endif
bytes_needed = ossl_rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
for (i = 0; i < bytes_needed; i++) {
/*
* burn some cpu; hope for interrupts, cache collisions, bus
* interference, etc.
*/
for (k = 0; k < 99; k++)
ts.tv_nsec = random();
# ifdef OPENSSL_SYS_VOS_HPPA
/* sleep for 1/1024 of a second (976 us). */
duration = 1;
s$sleep(&duration, &code);
# else
/* sleep for 1/65536 of a second (15 us). */
duration = 1;
s$sleep2(&duration, &code);
# endif
/* Get wall clock time, take 8 bits. */
clock_gettime(CLOCK_REALTIME, &ts);
v = (unsigned char)(ts.tv_nsec & 0xFF);
ossl_rand_pool_add(pool, arg, &v, sizeof(v), 2);
}
return ossl_rand_pool_entropy_available(pool);
}
void ossl_rand_pool_cleanup(void)
{
}
void ossl_rand_pool_keep_random_devices_open(int keep)
{
}
# else
# if defined(OPENSSL_RAND_SEED_EGD) && \
(defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
# error "Seeding uses EGD but EGD is turned off or no device given"
# endif
# if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
# error "Seeding uses urandom but DEVRANDOM is not configured"
# endif
# if defined(OPENSSL_RAND_SEED_OS)
# if !defined(DEVRANDOM)
# error "OS seeding requires DEVRANDOM to be configured"
# endif
# define OPENSSL_RAND_SEED_GETRANDOM
# define OPENSSL_RAND_SEED_DEVRANDOM
# endif
# if defined(OPENSSL_RAND_SEED_LIBRANDOM)
# error "librandom not (yet) supported"
# endif
# if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
/*
* sysctl_random(): Use sysctl() to read a random number from the kernel
* Returns the number of bytes returned in buf on success, -1 on failure.
*/
static ssize_t sysctl_random(char *buf, size_t buflen)
{
int mib[2];
size_t done = 0;
size_t len;
/*
* Note: sign conversion between size_t and ssize_t is safe even
* without a range check, see comment in syscall_random()
*/
/*
* On FreeBSD old implementations returned longs, newer versions support
* variable sizes up to 256 byte. The code below would not work properly
* when the sysctl returns long and we want to request something not a
* multiple of longs, which should never be the case.
*/
#if defined(__FreeBSD__)
if (!ossl_assert(buflen % sizeof(long) == 0)) {
errno = EINVAL;
return -1;
}
#endif
/*
* On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
* filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
* it returns a variable number of bytes with the current version supporting
* up to 256 bytes.
* Just return an error on older NetBSD versions.
*/
#if defined(__NetBSD__) && __NetBSD_Version__ < 400000000
errno = ENOSYS;
return -1;
#endif
mib[0] = CTL_KERN;
mib[1] = KERN_ARND;
do {
len = buflen > 256 ? 256 : buflen;
if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
return done > 0 ? done : -1;
done += len;
buf += len;
buflen -= len;
} while (buflen > 0);
return done;
}
# endif
# if defined(OPENSSL_RAND_SEED_GETRANDOM)
# if defined(__linux) && !defined(__NR_getrandom)
# if defined(__arm__)
# define __NR_getrandom (__NR_SYSCALL_BASE+384)
# elif defined(__i386__)
# define __NR_getrandom 355
# elif defined(__x86_64__)
# if defined(__ILP32__)
# define __NR_getrandom (__X32_SYSCALL_BIT + 318)
# else
# define __NR_getrandom 318
# endif
# elif defined(__xtensa__)
# define __NR_getrandom 338
# elif defined(__s390__) || defined(__s390x__)
# define __NR_getrandom 349
# elif defined(__bfin__)
# define __NR_getrandom 389
# elif defined(__powerpc__)
# define __NR_getrandom 359
# elif defined(__mips__) || defined(__mips64)
# if _MIPS_SIM == _MIPS_SIM_ABI32
# define __NR_getrandom (__NR_Linux + 353)
# elif _MIPS_SIM == _MIPS_SIM_ABI64
# define __NR_getrandom (__NR_Linux + 313)
# elif _MIPS_SIM == _MIPS_SIM_NABI32
# define __NR_getrandom (__NR_Linux + 317)
# endif
# elif defined(__hppa__)
# define __NR_getrandom (__NR_Linux + 339)
# elif defined(__sparc__)
# define __NR_getrandom 347
# elif defined(__ia64__)
# define __NR_getrandom 1339
# elif defined(__alpha__)
# define __NR_getrandom 511
# elif defined(__sh__)
# if defined(__SH5__)
# define __NR_getrandom 373
# else
# define __NR_getrandom 384
# endif
# elif defined(__avr32__)
# define __NR_getrandom 317
# elif defined(__microblaze__)
# define __NR_getrandom 385
# elif defined(__m68k__)
# define __NR_getrandom 352
# elif defined(__cris__)
# define __NR_getrandom 356
# else /* generic (f.e. aarch64, loongarch, loongarch64) */
# define __NR_getrandom 278
# endif
# endif
/*
* syscall_random(): Try to get random data using a system call
* returns the number of bytes returned in buf, or < 0 on error.
*/
static ssize_t syscall_random(void *buf, size_t buflen)
{
/*
* Note: 'buflen' equals the size of the buffer which is used by the
* get_entropy() callback of the RAND_DRBG. It is roughly bounded by
*
* 2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
*
* which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
* between size_t and ssize_t is safe even without a range check.
*/
/*
* Do runtime detection to find getentropy().
*
* Known OSs that should support this:
* - Darwin since 16 (OSX 10.12, IOS 10.0).
* - Solaris since 11.3
* - OpenBSD since 5.6
* - Linux since 3.17 with glibc 2.25
* - FreeBSD since 12.0 (1200061)
*
* Note: Sometimes getentropy() can be provided but not implemented
* internally. So we need to check errno for ENOSYS
*/
# if !defined(__DragonFly__) && !defined(__NetBSD__)
# if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
extern int getentropy(void *buffer, size_t length) __attribute__((weak));
if (getentropy != NULL) {
if (getentropy(buf, buflen) == 0)
return (ssize_t)buflen;
if (errno != ENOSYS)
return -1;
}
# elif defined(OPENSSL_APPLE_CRYPTO_RANDOM)
if (CCRandomGenerateBytes(buf, buflen) == kCCSuccess)
return (ssize_t)buflen;
return -1;
# else
union {
void *p;
int (*f)(void *buffer, size_t length);
} p_getentropy;
/*
* We could cache the result of the lookup, but we normally don't
* call this function often.
*/
ERR_set_mark();
p_getentropy.p = DSO_global_lookup("getentropy");
ERR_pop_to_mark();
if (p_getentropy.p != NULL)
return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
# endif
# endif /* !__DragonFly__ */
/* Linux supports this since version 3.17 */
# if defined(__linux) && defined(__NR_getrandom)
return syscall(__NR_getrandom, buf, buflen, 0);
# elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
return sysctl_random(buf, buflen);
# elif (defined(__DragonFly__) && __DragonFly_version >= 500700) \
|| (defined(__NetBSD__) && __NetBSD_Version >= 1000000000)
return getrandom(buf, buflen, 0);
# elif defined(__wasi__)
if (getentropy(buf, buflen) == 0)
return (ssize_t)buflen;
return -1;
# else
errno = ENOSYS;
return -1;
# endif
}
# endif /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
# if defined(OPENSSL_RAND_SEED_DEVRANDOM)
static const char *random_device_paths[] = { DEVRANDOM };
static struct random_device {
int fd;
dev_t dev;
ino_t ino;
mode_t mode;
dev_t rdev;
} random_devices[OSSL_NELEM(random_device_paths)];
static int keep_random_devices_open = 1;
# if defined(__linux) && defined(DEVRANDOM_WAIT) \
&& defined(OPENSSL_RAND_SEED_GETRANDOM)
static void *shm_addr;
static void cleanup_shm(void)
{
shmdt(shm_addr);
}
/*
* Ensure that the system randomness source has been adequately seeded.
* This is done by having the first start of libcrypto, wait until the device
* /dev/random becomes able to supply a byte of entropy. Subsequent starts
* of the library and later reseedings do not need to do this.
*/
static int wait_random_seeded(void)
{
static int seeded = OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID < 0;
static const int kernel_version[] = { DEVRANDOM_SAFE_KERNEL };
int kernel[2];
int shm_id, fd, r;
char c, *p;
struct utsname un;
fd_set fds;
if (!seeded) {
/* See if anything has created the global seeded indication */
if ((shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1, 0)) == -1) {
/*
* Check the kernel's version and fail if it is too recent.
*
* Linux kernels from 4.8 onwards do not guarantee that
* /dev/urandom is properly seeded when /dev/random becomes
* readable. However, such kernels support the getentropy(2)
* system call and this should always succeed which renders
* this alternative but essentially identical source moot.
*/
if (uname(&un) == 0) {
kernel[0] = atoi(un.release);
p = strchr(un.release, '.');
kernel[1] = p == NULL ? 0 : atoi(p + 1);
if (kernel[0] > kernel_version[0]
|| (kernel[0] == kernel_version[0]
&& kernel[1] >= kernel_version[1])) {
return 0;
}
}
/* Open /dev/random and wait for it to be readable */
if ((fd = open(DEVRANDOM_WAIT, O_RDONLY)) != -1) {
if (DEVRANDM_WAIT_USE_SELECT && fd < FD_SETSIZE) {
FD_ZERO(&fds);
FD_SET(fd, &fds);
while ((r = select(fd + 1, &fds, NULL, NULL, NULL)) < 0
&& errno == EINTR);
} else {
while ((r = read(fd, &c, 1)) < 0 && errno == EINTR);
}
close(fd);
if (r == 1) {
seeded = 1;
/* Create the shared memory indicator */
shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1,
IPC_CREAT | S_IRUSR | S_IRGRP | S_IROTH);
}
}
}
if (shm_id != -1) {
seeded = 1;
/*
* Map the shared memory to prevent its premature destruction.
* If this call fails, it isn't a big problem.
*/
shm_addr = shmat(shm_id, NULL, SHM_RDONLY);
if (shm_addr != (void *)-1)
OPENSSL_atexit(&cleanup_shm);
}
}
return seeded;
}
# else /* defined __linux && DEVRANDOM_WAIT && OPENSSL_RAND_SEED_GETRANDOM */
static int wait_random_seeded(void)
{
return 1;
}
# endif
/*
* Verify that the file descriptor associated with the random source is
* still valid. The rationale for doing this is the fact that it is not
* uncommon for daemons to close all open file handles when daemonizing.
* So the handle might have been closed or even reused for opening
* another file.
*/
static int check_random_device(struct random_device * rd)
{
struct stat st;
return rd->fd != -1
&& fstat(rd->fd, &st) != -1
&& rd->dev == st.st_dev
&& rd->ino == st.st_ino
&& ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
&& rd->rdev == st.st_rdev;
}
/*
* Open a random device if required and return its file descriptor or -1 on error
*/
static int get_random_device(size_t n)
{
struct stat st;
struct random_device * rd = &random_devices[n];
/* reuse existing file descriptor if it is (still) valid */
if (check_random_device(rd))
return rd->fd;
/* open the random device ... */
if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
return rd->fd;
/* ... and cache its relevant stat(2) data */
if (fstat(rd->fd, &st) != -1) {
rd->dev = st.st_dev;
rd->ino = st.st_ino;
rd->mode = st.st_mode;
rd->rdev = st.st_rdev;
} else {
close(rd->fd);
rd->fd = -1;
}
return rd->fd;
}
/*
* Close a random device making sure it is a random device
*/
static void close_random_device(size_t n)
{
struct random_device * rd = &random_devices[n];
if (check_random_device(rd))
close(rd->fd);
rd->fd = -1;
}
int ossl_rand_pool_init(void)
{
size_t i;
for (i = 0; i < OSSL_NELEM(random_devices); i++)
random_devices[i].fd = -1;
return 1;
}
void ossl_rand_pool_cleanup(void)
{
size_t i;
for (i = 0; i < OSSL_NELEM(random_devices); i++)
close_random_device(i);
}
void ossl_rand_pool_keep_random_devices_open(int keep)
{
if (!keep)
ossl_rand_pool_cleanup();
keep_random_devices_open = keep;
}
# else /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
int ossl_rand_pool_init(void)
{
return 1;
}
void ossl_rand_pool_cleanup(void)
{
}
void ossl_rand_pool_keep_random_devices_open(int keep)
{
}
# endif /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
/*
* Try the various seeding methods in turn, exit when successful.
*
* If more than one entropy source is available, is it
* preferable to stop as soon as enough entropy has been collected
* (as favored by @rsalz) or should one rather be defensive and add
* more entropy than requested and/or from different sources?
*
* Currently, the user can select multiple entropy sources in the
* configure step, yet in practice only the first available source
* will be used. A more flexible solution has been requested, but
* currently it is not clear how this can be achieved without
* overengineering the problem. There are many parameters which
* could be taken into account when selecting the order and amount
* of input from the different entropy sources (trust, quality,
* possibility of blocking).
*/
size_t ossl_pool_acquire_entropy(RAND_POOL *pool)
{
# if defined(OPENSSL_RAND_SEED_NONE)
return ossl_rand_pool_entropy_available(pool);
# else
size_t entropy_available = 0;
(void)entropy_available; /* avoid compiler warning */
# if defined(OPENSSL_RAND_SEED_GETRANDOM)
{
size_t bytes_needed;
unsigned char *buffer;
ssize_t bytes;
/* Maximum allowed number of consecutive unsuccessful attempts */
int attempts = 3;
bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
while (bytes_needed != 0 && attempts-- > 0) {
buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
bytes = syscall_random(buffer, bytes_needed);
if (bytes > 0) {
ossl_rand_pool_add_end(pool, bytes, 8 * bytes);
bytes_needed -= bytes;
attempts = 3; /* reset counter after successful attempt */
} else if (bytes < 0 && errno != EINTR) {
break;
}
}
}
entropy_available = ossl_rand_pool_entropy_available(pool);
if (entropy_available > 0)
return entropy_available;
# endif
# if defined(OPENSSL_RAND_SEED_LIBRANDOM)
{
/* Not yet implemented. */
}
# endif
# if defined(OPENSSL_RAND_SEED_DEVRANDOM)
if (wait_random_seeded()) {
size_t bytes_needed;
unsigned char *buffer;
size_t i;
bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths);
i++) {
ssize_t bytes = 0;
/* Maximum number of consecutive unsuccessful attempts */
int attempts = 3;
const int fd = get_random_device(i);
if (fd == -1)
continue;
while (bytes_needed != 0 && attempts-- > 0) {
buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
bytes = read(fd, buffer, bytes_needed);
if (bytes > 0) {
ossl_rand_pool_add_end(pool, bytes, 8 * bytes);
bytes_needed -= bytes;
attempts = 3; /* reset counter on successful attempt */
} else if (bytes < 0 && errno != EINTR) {
break;
}
}
if (bytes < 0 || !keep_random_devices_open)
close_random_device(i);
bytes_needed = ossl_rand_pool_bytes_needed(pool, 1);
}
entropy_available = ossl_rand_pool_entropy_available(pool);
if (entropy_available > 0)
return entropy_available;
}
# endif
# if defined(OPENSSL_RAND_SEED_RDTSC)
entropy_available = ossl_prov_acquire_entropy_from_tsc(pool);
if (entropy_available > 0)
return entropy_available;
# endif
# if defined(OPENSSL_RAND_SEED_RDCPU)
entropy_available = ossl_prov_acquire_entropy_from_cpu(pool);
if (entropy_available > 0)
return entropy_available;
# endif
# if defined(OPENSSL_RAND_SEED_EGD)
{
static const char *paths[] = { DEVRANDOM_EGD, NULL };
size_t bytes_needed;
unsigned char *buffer;
int i;
bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
for (i = 0; bytes_needed > 0 && paths[i] != NULL; i++) {
size_t bytes = 0;
int num;
buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
num = RAND_query_egd_bytes(paths[i],
buffer, (int)bytes_needed);
if (num == (int)bytes_needed)
bytes = bytes_needed;
ossl_rand_pool_add_end(pool, bytes, 8 * bytes);
bytes_needed = ossl_rand_pool_bytes_needed(pool, 1);
}
entropy_available = ossl_rand_pool_entropy_available(pool);
if (entropy_available > 0)
return entropy_available;
}
# endif
return ossl_rand_pool_entropy_available(pool);
# endif
}
# endif
#endif
#if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
|| defined(__DJGPP__)
int ossl_pool_add_nonce_data(RAND_POOL *pool)
{
struct {
pid_t pid;
CRYPTO_THREAD_ID tid;
uint64_t time;
} data;
/* Erase the entire structure including any padding */
memset(&data, 0, sizeof(data));
/*
* Add process id, thread id, and a high resolution timestamp to
* ensure that the nonce is unique with high probability for
* different process instances.
*/
data.pid = getpid();
data.tid = CRYPTO_THREAD_get_current_id();
data.time = get_time_stamp();
return ossl_rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
}
/*
* Get the current time with the highest possible resolution
*
* The time stamp is added to the nonce, so it is optimized for not repeating.
* The current time is ideal for this purpose, provided the computer's clock
* is synchronized.
*/
static uint64_t get_time_stamp(void)
{
# if defined(OSSL_POSIX_TIMER_OKAY)
{
struct timespec ts;
if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
return TWO32TO64(ts.tv_sec, ts.tv_nsec);
}
# endif
# if defined(__unix__) \
|| (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
{
struct timeval tv;
if (gettimeofday(&tv, NULL) == 0)
return TWO32TO64(tv.tv_sec, tv.tv_usec);
}
# endif
return time(NULL);
}
#endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS))
|| defined(__DJGPP__) */
| 24,914 | 29.797281 | 81 | c |
openssl | openssl-master/providers/implementations/rands/seeding/rand_vms.c | /*
* Copyright 2001-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/e_os.h"
#define __NEW_STARLET 1 /* New starlet definitions since VMS 7.0 */
#include <unistd.h>
#include "internal/cryptlib.h"
#include "internal/nelem.h"
#include <openssl/rand.h>
#include "crypto/rand.h"
#include "crypto/rand_pool.h"
#include "prov/seeding.h"
#include <descrip.h>
#include <dvidef.h>
#include <jpidef.h>
#include <rmidef.h>
#include <syidef.h>
#include <ssdef.h>
#include <starlet.h>
#include <efndef.h>
#include <gen64def.h>
#include <iosbdef.h>
#include <iledef.h>
#include <lib$routines.h>
#ifdef __DECC
# pragma message disable DOLLARID
#endif
#include <dlfcn.h> /* SYS$GET_ENTROPY presence */
#ifndef OPENSSL_RAND_SEED_OS
# error "Unsupported seeding method configured; must be os"
#endif
/*
* DATA COLLECTION METHOD
* ======================
*
* This is a method to get low quality entropy.
* It works by collecting all kinds of statistical data that
* VMS offers and using them as random seed.
*/
/* We need to make sure we have the right size pointer in some cases */
#if __INITIAL_POINTER_SIZE == 64
# pragma pointer_size save
# pragma pointer_size 32
#endif
typedef uint32_t *uint32_t__ptr32;
#if __INITIAL_POINTER_SIZE == 64
# pragma pointer_size restore
#endif
struct item_st {
short length, code; /* length is number of bytes */
};
static const struct item_st DVI_item_data[] = {
{4, DVI$_ERRCNT},
{4, DVI$_REFCNT},
};
static const struct item_st JPI_item_data[] = {
{4, JPI$_BUFIO},
{4, JPI$_CPUTIM},
{4, JPI$_DIRIO},
{4, JPI$_IMAGECOUNT},
{4, JPI$_PAGEFLTS},
{4, JPI$_PID},
{4, JPI$_PPGCNT},
{4, JPI$_WSPEAK},
/*
* Note: the direct result is just a 32-bit address. However, it points
* to a list of 4 32-bit words, so we make extra space for them so we can
* do in-place replacement of values
*/
{16, JPI$_FINALEXC},
};
static const struct item_st JPI_item_data_64bit[] = {
{8, JPI$_LAST_LOGIN_I},
{8, JPI$_LOGINTIM},
};
static const struct item_st RMI_item_data[] = {
{4, RMI$_COLPG},
{4, RMI$_MWAIT},
{4, RMI$_CEF},
{4, RMI$_PFW},
{4, RMI$_LEF},
{4, RMI$_LEFO},
{4, RMI$_HIB},
{4, RMI$_HIBO},
{4, RMI$_SUSP},
{4, RMI$_SUSPO},
{4, RMI$_FPG},
{4, RMI$_COM},
{4, RMI$_COMO},
{4, RMI$_CUR},
#if defined __alpha
{4, RMI$_FRLIST},
{4, RMI$_MODLIST},
#endif
{4, RMI$_FAULTS},
{4, RMI$_PREADS},
{4, RMI$_PWRITES},
{4, RMI$_PWRITIO},
{4, RMI$_PREADIO},
{4, RMI$_GVALFLTS},
{4, RMI$_WRTINPROG},
{4, RMI$_FREFLTS},
{4, RMI$_DZROFLTS},
{4, RMI$_SYSFAULTS},
{4, RMI$_ISWPCNT},
{4, RMI$_DIRIO},
{4, RMI$_BUFIO},
{4, RMI$_MBREADS},
{4, RMI$_MBWRITES},
{4, RMI$_LOGNAM},
{4, RMI$_FCPCALLS},
{4, RMI$_FCPREAD},
{4, RMI$_FCPWRITE},
{4, RMI$_FCPCACHE},
{4, RMI$_FCPCPU},
{4, RMI$_FCPHIT},
{4, RMI$_FCPSPLIT},
{4, RMI$_FCPFAULT},
{4, RMI$_ENQNEW},
{4, RMI$_ENQCVT},
{4, RMI$_DEQ},
{4, RMI$_BLKAST},
{4, RMI$_ENQWAIT},
{4, RMI$_ENQNOTQD},
{4, RMI$_DLCKSRCH},
{4, RMI$_DLCKFND},
{4, RMI$_NUMLOCKS},
{4, RMI$_NUMRES},
{4, RMI$_ARRLOCPK},
{4, RMI$_DEPLOCPK},
{4, RMI$_ARRTRAPK},
{4, RMI$_TRCNGLOS},
{4, RMI$_RCVBUFFL},
{4, RMI$_ENQNEWLOC},
{4, RMI$_ENQNEWIN},
{4, RMI$_ENQNEWOUT},
{4, RMI$_ENQCVTLOC},
{4, RMI$_ENQCVTIN},
{4, RMI$_ENQCVTOUT},
{4, RMI$_DEQLOC},
{4, RMI$_DEQIN},
{4, RMI$_DEQOUT},
{4, RMI$_BLKLOC},
{4, RMI$_BLKIN},
{4, RMI$_BLKOUT},
{4, RMI$_DIRIN},
{4, RMI$_DIROUT},
/* We currently get a fault when trying these */
#if 0
{140, RMI$_MSCP_EVERYTHING}, /* 35 32-bit words */
{152, RMI$_DDTM_ALL}, /* 38 32-bit words */
{80, RMI$_TMSCP_EVERYTHING} /* 20 32-bit words */
#endif
{4, RMI$_LPZ_PAGCNT},
{4, RMI$_LPZ_HITS},
{4, RMI$_LPZ_MISSES},
{4, RMI$_LPZ_EXPCNT},
{4, RMI$_LPZ_ALLOCF},
{4, RMI$_LPZ_ALLOC2},
{4, RMI$_ACCESS},
{4, RMI$_ALLOC},
{4, RMI$_FCPCREATE},
{4, RMI$_VOLWAIT},
{4, RMI$_FCPTURN},
{4, RMI$_FCPERASE},
{4, RMI$_OPENS},
{4, RMI$_FIDHIT},
{4, RMI$_FIDMISS},
{4, RMI$_FILHDR_HIT},
{4, RMI$_DIRFCB_HIT},
{4, RMI$_DIRFCB_MISS},
{4, RMI$_DIRDATA_HIT},
{4, RMI$_EXTHIT},
{4, RMI$_EXTMISS},
{4, RMI$_QUOHIT},
{4, RMI$_QUOMISS},
{4, RMI$_STORAGMAP_HIT},
{4, RMI$_VOLLCK},
{4, RMI$_SYNCHLCK},
{4, RMI$_SYNCHWAIT},
{4, RMI$_ACCLCK},
{4, RMI$_XQPCACHEWAIT},
{4, RMI$_DIRDATA_MISS},
{4, RMI$_FILHDR_MISS},
{4, RMI$_STORAGMAP_MISS},
{4, RMI$_PROCCNTMAX},
{4, RMI$_PROCBATCNT},
{4, RMI$_PROCINTCNT},
{4, RMI$_PROCNETCNT},
{4, RMI$_PROCSWITCHCNT},
{4, RMI$_PROCBALSETCNT},
{4, RMI$_PROCLOADCNT},
{4, RMI$_BADFLTS},
{4, RMI$_EXEFAULTS},
{4, RMI$_HDRINSWAPS},
{4, RMI$_HDROUTSWAPS},
{4, RMI$_IOPAGCNT},
{4, RMI$_ISWPCNTPG},
{4, RMI$_OSWPCNT},
{4, RMI$_OSWPCNTPG},
{4, RMI$_RDFAULTS},
{4, RMI$_TRANSFLTS},
{4, RMI$_WRTFAULTS},
#if defined __alpha
{4, RMI$_USERPAGES},
#endif
{4, RMI$_VMSPAGES},
{4, RMI$_TTWRITES},
{4, RMI$_BUFOBJPAG},
{4, RMI$_BUFOBJPAGPEAK},
{4, RMI$_BUFOBJPAGS01},
{4, RMI$_BUFOBJPAGS2},
{4, RMI$_BUFOBJPAGMAXS01},
{4, RMI$_BUFOBJPAGMAXS2},
{4, RMI$_BUFOBJPAGPEAKS01},
{4, RMI$_BUFOBJPAGPEAKS2},
{4, RMI$_BUFOBJPGLTMAXS01},
{4, RMI$_BUFOBJPGLTMAXS2},
{4, RMI$_DLCK_INCMPLT},
{4, RMI$_DLCKMSGS_IN},
{4, RMI$_DLCKMSGS_OUT},
{4, RMI$_MCHKERRS},
{4, RMI$_MEMERRS},
};
static const struct item_st RMI_item_data_64bit[] = {
#if defined __ia64
{8, RMI$_FRLIST},
{8, RMI$_MODLIST},
#endif
{8, RMI$_LCKMGR_REQCNT},
{8, RMI$_LCKMGR_REQTIME},
{8, RMI$_LCKMGR_SPINCNT},
{8, RMI$_LCKMGR_SPINTIME},
{8, RMI$_CPUINTSTK},
{8, RMI$_CPUMPSYNCH},
{8, RMI$_CPUKERNEL},
{8, RMI$_CPUEXEC},
{8, RMI$_CPUSUPER},
{8, RMI$_CPUUSER},
#if defined __ia64
{8, RMI$_USERPAGES},
#endif
{8, RMI$_TQETOTAL},
{8, RMI$_TQESYSUB},
{8, RMI$_TQEUSRTIMR},
{8, RMI$_TQEUSRWAKE},
};
static const struct item_st SYI_item_data[] = {
{4, SYI$_PAGEFILE_FREE},
};
/*
* Input:
* items_data - an array of lengths and codes
* items_data_num - number of elements in that array
*
* Output:
* items - pre-allocated ILE3 array to be filled.
* It's assumed to have items_data_num elements plus
* one extra for the terminating NULL element
* databuffer - pre-allocated 32-bit word array.
*
* Returns the number of elements used in databuffer
*/
static size_t prepare_item_list(const struct item_st *items_input,
size_t items_input_num,
ILE3 *items,
uint32_t__ptr32 databuffer)
{
size_t data_sz = 0;
for (; items_input_num-- > 0; items_input++, items++) {
items->ile3$w_code = items_input->code;
/* Special treatment of JPI$_FINALEXC */
if (items->ile3$w_code == JPI$_FINALEXC)
items->ile3$w_length = 4;
else
items->ile3$w_length = items_input->length;
items->ile3$ps_bufaddr = databuffer;
items->ile3$ps_retlen_addr = 0;
databuffer += items_input->length / sizeof(databuffer[0]);
data_sz += items_input->length;
}
/* Terminating NULL entry */
items->ile3$w_length = items->ile3$w_code = 0;
items->ile3$ps_bufaddr = items->ile3$ps_retlen_addr = NULL;
return data_sz / sizeof(databuffer[0]);
}
static void massage_JPI(ILE3 *items)
{
/*
* Special treatment of JPI$_FINALEXC
* The result of that item's data buffer is a 32-bit address to a list of
* 4 32-bit words.
*/
for (; items->ile3$w_length != 0; items++) {
if (items->ile3$w_code == JPI$_FINALEXC) {
uint32_t *data = items->ile3$ps_bufaddr;
uint32_t *ptr = (uint32_t *)*data;
size_t j;
/*
* We know we made space for 4 32-bit words, so we can do in-place
* replacement.
*/
for (j = 0; j < 4; j++)
data[j] = ptr[j];
break;
}
}
}
/*
* This number expresses how many bits of data contain 1 bit of entropy.
*
* For the moment, we assume about 0.05 entropy bits per data bit, or 1
* bit of entropy per 20 data bits.
*/
#define ENTROPY_FACTOR 20
size_t data_collect_method(RAND_POOL *pool)
{
ILE3 JPI_items_64bit[OSSL_NELEM(JPI_item_data_64bit) + 1];
ILE3 RMI_items_64bit[OSSL_NELEM(RMI_item_data_64bit) + 1];
ILE3 DVI_items[OSSL_NELEM(DVI_item_data) + 1];
ILE3 JPI_items[OSSL_NELEM(JPI_item_data) + 1];
ILE3 RMI_items[OSSL_NELEM(RMI_item_data) + 1];
ILE3 SYI_items[OSSL_NELEM(SYI_item_data) + 1];
union {
/* This ensures buffer starts at 64 bit boundary */
uint64_t dummy;
uint32_t buffer[OSSL_NELEM(JPI_item_data_64bit) * 2
+ OSSL_NELEM(RMI_item_data_64bit) * 2
+ OSSL_NELEM(DVI_item_data)
+ OSSL_NELEM(JPI_item_data)
+ OSSL_NELEM(RMI_item_data)
+ OSSL_NELEM(SYI_item_data)
+ 4 /* For JPI$_FINALEXC */];
} data;
size_t total_elems = 0;
size_t total_length = 0;
size_t bytes_needed = ossl_rand_pool_bytes_needed(pool, ENTROPY_FACTOR);
size_t bytes_remaining = ossl_rand_pool_bytes_remaining(pool);
/* Take all the 64-bit items first, to ensure proper alignment of data */
total_elems +=
prepare_item_list(JPI_item_data_64bit, OSSL_NELEM(JPI_item_data_64bit),
JPI_items_64bit, &data.buffer[total_elems]);
total_elems +=
prepare_item_list(RMI_item_data_64bit, OSSL_NELEM(RMI_item_data_64bit),
RMI_items_64bit, &data.buffer[total_elems]);
/* Now the 32-bit items */
total_elems += prepare_item_list(DVI_item_data, OSSL_NELEM(DVI_item_data),
DVI_items, &data.buffer[total_elems]);
total_elems += prepare_item_list(JPI_item_data, OSSL_NELEM(JPI_item_data),
JPI_items, &data.buffer[total_elems]);
total_elems += prepare_item_list(RMI_item_data, OSSL_NELEM(RMI_item_data),
RMI_items, &data.buffer[total_elems]);
total_elems += prepare_item_list(SYI_item_data, OSSL_NELEM(SYI_item_data),
SYI_items, &data.buffer[total_elems]);
total_length = total_elems * sizeof(data.buffer[0]);
/* Fill data.buffer with various info bits from this process */
{
uint32_t status;
uint32_t efn;
IOSB iosb;
$DESCRIPTOR(SYSDEVICE, "SYS$SYSDEVICE:");
if ((status = sys$getdviw(EFN$C_ENF, 0, &SYSDEVICE, DVI_items,
0, 0, 0, 0, 0)) != SS$_NORMAL) {
lib$signal(status);
return 0;
}
if ((status = sys$getjpiw(EFN$C_ENF, 0, 0, JPI_items_64bit, 0, 0, 0))
!= SS$_NORMAL) {
lib$signal(status);
return 0;
}
if ((status = sys$getjpiw(EFN$C_ENF, 0, 0, JPI_items, 0, 0, 0))
!= SS$_NORMAL) {
lib$signal(status);
return 0;
}
if ((status = sys$getsyiw(EFN$C_ENF, 0, 0, SYI_items, 0, 0, 0))
!= SS$_NORMAL) {
lib$signal(status);
return 0;
}
/*
* The RMI service is a bit special, as there is no synchronous
* variant, so we MUST create an event flag to synchronise on.
*/
if ((status = lib$get_ef(&efn)) != SS$_NORMAL) {
lib$signal(status);
return 0;
}
if ((status = sys$getrmi(efn, 0, 0, RMI_items_64bit, &iosb, 0, 0))
!= SS$_NORMAL) {
lib$signal(status);
return 0;
}
if ((status = sys$synch(efn, &iosb)) != SS$_NORMAL) {
lib$signal(status);
return 0;
}
if (iosb.iosb$l_getxxi_status != SS$_NORMAL) {
lib$signal(iosb.iosb$l_getxxi_status);
return 0;
}
if ((status = sys$getrmi(efn, 0, 0, RMI_items, &iosb, 0, 0))
!= SS$_NORMAL) {
lib$signal(status);
return 0;
}
if ((status = sys$synch(efn, &iosb)) != SS$_NORMAL) {
lib$signal(status);
return 0;
}
if (iosb.iosb$l_getxxi_status != SS$_NORMAL) {
lib$signal(iosb.iosb$l_getxxi_status);
return 0;
}
if ((status = lib$free_ef(&efn)) != SS$_NORMAL) {
lib$signal(status);
return 0;
}
}
massage_JPI(JPI_items);
/*
* If we can't feed the requirements from the caller, we're in deep trouble.
*/
if (!ossl_assert(total_length >= bytes_needed)) {
ERR_raise_data(ERR_LIB_RAND, RAND_R_RANDOM_POOL_UNDERFLOW,
"Needed: %zu, Available: %zu",
bytes_needed, total_length);
return 0;
}
/*
* Try not to overfeed the pool
*/
if (total_length > bytes_remaining)
total_length = bytes_remaining;
/* We give the pessimistic value for the amount of entropy */
ossl_rand_pool_add(pool, (unsigned char *)data.buffer, total_length,
8 * total_length / ENTROPY_FACTOR);
return ossl_rand_pool_entropy_available(pool);
}
/*
* SYS$GET_ENTROPY METHOD
* ======================
*
* This is a high entropy method based on a new system service that is
* based on getentropy() from FreeBSD 12. It's only used if available,
* and its availability is detected at run-time.
*
* We assume that this function provides full entropy random output.
*/
#define PUBLIC_VECTORS "SYS$LIBRARY:SYS$PUBLIC_VECTORS.EXE"
#define GET_ENTROPY "SYS$GET_ENTROPY"
static int get_entropy_address_flag = 0;
static int (*get_entropy_address)(void *buffer, size_t buffer_size) = NULL;
static int init_get_entropy_address(void)
{
if (get_entropy_address_flag == 0)
get_entropy_address = dlsym(dlopen(PUBLIC_VECTORS, 0), GET_ENTROPY);
get_entropy_address_flag = 1;
return get_entropy_address != NULL;
}
size_t get_entropy_method(RAND_POOL *pool)
{
/*
* The documentation says that SYS$GET_ENTROPY will give a maximum of
* 256 bytes of data.
*/
unsigned char buffer[256];
size_t bytes_needed;
size_t bytes_to_get = 0;
uint32_t status;
for (bytes_needed = ossl_rand_pool_bytes_needed(pool, 1);
bytes_needed > 0;
bytes_needed -= bytes_to_get) {
bytes_to_get =
bytes_needed > sizeof(buffer) ? sizeof(buffer) : bytes_needed;
status = get_entropy_address(buffer, bytes_to_get);
if (status == SS$_RETRY) {
/* Set to zero so the loop doesn't diminish |bytes_needed| */
bytes_to_get = 0;
/* Should sleep some amount of time */
continue;
}
if (status != SS$_NORMAL) {
lib$signal(status);
return 0;
}
ossl_rand_pool_add(pool, buffer, bytes_to_get, 8 * bytes_to_get);
}
return ossl_rand_pool_entropy_available(pool);
}
/*
* MAIN ENTROPY ACQUISITION FUNCTIONS
* ==================================
*
* These functions are called by the RAND / DRBG functions
*/
size_t ossl_pool_acquire_entropy(RAND_POOL *pool)
{
if (init_get_entropy_address())
return get_entropy_method(pool);
return data_collect_method(pool);
}
int ossl_pool_add_nonce_data(RAND_POOL *pool)
{
/*
* Two variables to ensure that two nonces won't ever be the same
*/
static unsigned __int64 last_time = 0;
static unsigned __int32 last_seq = 0;
struct {
pid_t pid;
CRYPTO_THREAD_ID tid;
unsigned __int64 time;
unsigned __int32 seq;
} data;
/* Erase the entire structure including any padding */
memset(&data, 0, sizeof(data));
/*
* Add process id, thread id, a timestamp, and a sequence number in case
* the same time stamp is repeated, to ensure that the nonce is unique
* with high probability for different process instances.
*
* The normal OpenVMS time is specified to be high granularity (100ns),
* but the time update granularity given by sys$gettim() may be lower.
*
* OpenVMS version 8.4 (which is the latest for Alpha and Itanium) and
* on have sys$gettim_prec() as well, which is supposedly having a better
* time update granularity, but tests on Itanium (and even Alpha) have
* shown that compared with sys$gettim(), the difference is marginal,
* so of very little significance in terms of entropy.
* Given that, and that it's a high ask to expect everyone to have
* upgraded to OpenVMS version 8.4, only sys$gettim() is used, and a
* sequence number is added as well, in case sys$gettim() returns the
* same time value more than once.
*
* This function is assumed to be called under thread lock, and does
* therefore not take concurrency into account.
*/
data.pid = getpid();
data.tid = CRYPTO_THREAD_get_current_id();
data.seq = 0;
sys$gettim((void*)&data.time);
if (data.time == last_time) {
data.seq = ++last_seq;
} else {
last_time = data.time;
last_seq = 0;
}
return ossl_rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
}
int ossl_rand_pool_init(void)
{
return 1;
}
void ossl_rand_pool_cleanup(void)
{
}
void ossl_rand_pool_keep_random_devices_open(int keep)
{
}
| 18,578 | 29.111831 | 80 | c |
openssl | openssl-master/providers/implementations/rands/seeding/rand_vxworks.c | /*
* Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/opensslconf.h>
#include <openssl/rand.h>
#include "crypto/rand_pool.h"
#include "crypto/rand.h"
#include "internal/cryptlib.h"
#include "prov/seeding.h"
#include <version.h>
#include <taskLib.h>
#if defined(OPENSSL_RAND_SEED_NONE)
/* none means none */
# undef OPENSSL_RAND_SEED_OS
#endif
#if defined(OPENSSL_RAND_SEED_OS)
# if _WRS_VXWORKS_MAJOR >= 7
# define RAND_SEED_VXRANDLIB
# else
# error "VxWorks <7 only support RAND_SEED_NONE"
# endif
#endif
#if defined(RAND_SEED_VXRANDLIB)
# include <randomNumGen.h>
#endif
/* Macro to convert two thirty two bit values into a sixty four bit one */
#define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
static uint64_t get_time_stamp(void)
{
struct timespec ts;
if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
return TWO32TO64(ts.tv_sec, ts.tv_nsec);
return time(NULL);
}
static uint64_t get_timer_bits(void)
{
uint64_t res = OPENSSL_rdtsc();
struct timespec ts;
if (res != 0)
return res;
if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
return TWO32TO64(ts.tv_sec, ts.tv_nsec);
return time(NULL);
}
/*
* empty implementation
* vxworks does not need to init/cleanup or keep open the random lib
*/
int ossl_rand_pool_init(void)
{
return 1;
}
void ossl_rand_pool_cleanup(void)
{
}
void ossl_rand_pool_keep_random_devices_open(int keep)
{
}
int ossl_pool_add_nonce_data(RAND_POOL *pool)
{
struct {
pid_t pid;
CRYPTO_THREAD_ID tid;
uint64_t time;
} data;
memset(&data, 0, sizeof(data));
/*
* Add process id, thread id, and a high resolution timestamp to
* ensure that the nonce is unique with high probability for
* different process instances.
*/
data.pid = getpid();
data.tid = CRYPTO_THREAD_get_current_id();
data.time = get_time_stamp();
return ossl_rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
}
size_t ossl_pool_acquire_entropy(RAND_POOL *pool)
{
#if defined(RAND_SEED_VXRANDLIB)
/* vxRandLib based entropy method */
size_t bytes_needed;
bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
if (bytes_needed > 0)
{
int retryCount = 0;
STATUS result = ERROR;
unsigned char *buffer;
buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
while ((result != OK) && (retryCount < 10)) {
RANDOM_NUM_GEN_STATUS status = randStatus();
if ((status == RANDOM_NUM_GEN_ENOUGH_ENTROPY)
|| (status == RANDOM_NUM_GEN_MAX_ENTROPY)) {
result = randBytes(buffer, bytes_needed);
if (result == OK)
ossl_rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
/*
* no else here: randStatus said ok, if randBytes failed
* it will result in another loop or no entropy
*/
} else {
/*
* give a minimum delay here to allow OS to collect more
* entropy. taskDelay duration will depend on the system tick,
* this is by design as the sw-random lib uses interrupts
* which will at least happen during ticks
*/
taskDelay(5);
}
retryCount++;
}
}
return ossl_rand_pool_entropy_available(pool);
#else
/*
* SEED_NONE means none, without randlib we dont have entropy and
* rely on it being added externally
*/
return ossl_rand_pool_entropy_available(pool);
#endif /* defined(RAND_SEED_VXRANDLIB) */
}
| 3,979 | 25.891892 | 81 | c |
openssl | openssl-master/providers/implementations/rands/seeding/rand_win.c | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/cryptlib.h"
#include <openssl/rand.h>
#include "crypto/rand_pool.h"
#include "crypto/rand.h"
#include "prov/seeding.h"
#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32)
# ifndef OPENSSL_RAND_SEED_OS
# error "Unsupported seeding method configured; must be os"
# endif
# include <windows.h>
/* On Windows Vista or higher use BCrypt instead of the legacy CryptoAPI */
# if defined(_MSC_VER) && _MSC_VER > 1500 /* 1500 = Visual Studio 2008 */ \
&& defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0600
# define USE_BCRYPTGENRANDOM
# endif
# ifdef USE_BCRYPTGENRANDOM
# include <bcrypt.h>
# ifdef _MSC_VER
# pragma comment(lib, "bcrypt.lib")
# endif
# ifndef STATUS_SUCCESS
# define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
# endif
# else
# include <wincrypt.h>
/*
* Intel hardware RNG CSP -- available from
* http://developer.intel.com/design/security/rng/redist_license.htm
*/
# define PROV_INTEL_SEC 22
# define INTEL_DEF_PROV L"Intel Hardware Cryptographic Service Provider"
# endif
size_t ossl_pool_acquire_entropy(RAND_POOL *pool)
{
# ifndef USE_BCRYPTGENRANDOM
HCRYPTPROV hProvider;
# endif
unsigned char *buffer;
size_t bytes_needed;
size_t entropy_available = 0;
# ifdef OPENSSL_RAND_SEED_RDTSC
entropy_available = ossl_prov_acquire_entropy_from_tsc(pool);
if (entropy_available > 0)
return entropy_available;
# endif
# ifdef OPENSSL_RAND_SEED_RDCPU
entropy_available = ossl_prov_acquire_entropy_from_cpu(pool);
if (entropy_available > 0)
return entropy_available;
# endif
# ifdef USE_BCRYPTGENRANDOM
bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
if (buffer != NULL) {
size_t bytes = 0;
if (BCryptGenRandom(NULL, buffer, bytes_needed,
BCRYPT_USE_SYSTEM_PREFERRED_RNG) == STATUS_SUCCESS)
bytes = bytes_needed;
ossl_rand_pool_add_end(pool, bytes, 8 * bytes);
entropy_available = ossl_rand_pool_entropy_available(pool);
}
if (entropy_available > 0)
return entropy_available;
# else
bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
if (buffer != NULL) {
size_t bytes = 0;
/* poll the CryptoAPI PRNG */
if (CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT | CRYPT_SILENT) != 0) {
if (CryptGenRandom(hProvider, bytes_needed, buffer) != 0)
bytes = bytes_needed;
CryptReleaseContext(hProvider, 0);
}
ossl_rand_pool_add_end(pool, bytes, 8 * bytes);
entropy_available = ossl_rand_pool_entropy_available(pool);
}
if (entropy_available > 0)
return entropy_available;
bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
if (buffer != NULL) {
size_t bytes = 0;
/* poll the Pentium PRG with CryptoAPI */
if (CryptAcquireContextW(&hProvider, NULL,
INTEL_DEF_PROV, PROV_INTEL_SEC,
CRYPT_VERIFYCONTEXT | CRYPT_SILENT) != 0) {
if (CryptGenRandom(hProvider, bytes_needed, buffer) != 0)
bytes = bytes_needed;
CryptReleaseContext(hProvider, 0);
}
ossl_rand_pool_add_end(pool, bytes, 8 * bytes);
entropy_available = ossl_rand_pool_entropy_available(pool);
}
if (entropy_available > 0)
return entropy_available;
# endif
return ossl_rand_pool_entropy_available(pool);
}
int ossl_pool_add_nonce_data(RAND_POOL *pool)
{
struct {
DWORD pid;
DWORD tid;
FILETIME time;
} data;
/* Erase the entire structure including any padding */
memset(&data, 0, sizeof(data));
/*
* Add process id, thread id, and a high resolution timestamp to
* ensure that the nonce is unique with high probability for
* different process instances.
*/
data.pid = GetCurrentProcessId();
data.tid = GetCurrentThreadId();
GetSystemTimeAsFileTime(&data.time);
return ossl_rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
}
int ossl_rand_pool_init(void)
{
return 1;
}
void ossl_rand_pool_cleanup(void)
{
}
void ossl_rand_pool_keep_random_devices_open(int keep)
{
}
#endif
| 4,866 | 28.676829 | 79 | c |
openssl | openssl-master/providers/implementations/signature/dsa_sig.c | /*
* Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* DSA low level APIs are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include <string.h>
#include <openssl/crypto.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/err.h>
#include <openssl/dsa.h>
#include <openssl/params.h>
#include <openssl/evp.h>
#include <openssl/proverr.h>
#include "internal/nelem.h"
#include "internal/sizes.h"
#include "internal/cryptlib.h"
#include "prov/providercommon.h"
#include "prov/implementations.h"
#include "prov/provider_ctx.h"
#include "prov/securitycheck.h"
#include "crypto/dsa.h"
#include "prov/der_dsa.h"
static OSSL_FUNC_signature_newctx_fn dsa_newctx;
static OSSL_FUNC_signature_sign_init_fn dsa_sign_init;
static OSSL_FUNC_signature_verify_init_fn dsa_verify_init;
static OSSL_FUNC_signature_sign_fn dsa_sign;
static OSSL_FUNC_signature_verify_fn dsa_verify;
static OSSL_FUNC_signature_digest_sign_init_fn dsa_digest_sign_init;
static OSSL_FUNC_signature_digest_sign_update_fn dsa_digest_signverify_update;
static OSSL_FUNC_signature_digest_sign_final_fn dsa_digest_sign_final;
static OSSL_FUNC_signature_digest_verify_init_fn dsa_digest_verify_init;
static OSSL_FUNC_signature_digest_verify_update_fn dsa_digest_signverify_update;
static OSSL_FUNC_signature_digest_verify_final_fn dsa_digest_verify_final;
static OSSL_FUNC_signature_freectx_fn dsa_freectx;
static OSSL_FUNC_signature_dupctx_fn dsa_dupctx;
static OSSL_FUNC_signature_get_ctx_params_fn dsa_get_ctx_params;
static OSSL_FUNC_signature_gettable_ctx_params_fn dsa_gettable_ctx_params;
static OSSL_FUNC_signature_set_ctx_params_fn dsa_set_ctx_params;
static OSSL_FUNC_signature_settable_ctx_params_fn dsa_settable_ctx_params;
static OSSL_FUNC_signature_get_ctx_md_params_fn dsa_get_ctx_md_params;
static OSSL_FUNC_signature_gettable_ctx_md_params_fn dsa_gettable_ctx_md_params;
static OSSL_FUNC_signature_set_ctx_md_params_fn dsa_set_ctx_md_params;
static OSSL_FUNC_signature_settable_ctx_md_params_fn dsa_settable_ctx_md_params;
/*
* What's passed as an actual key is defined by the KEYMGMT interface.
* We happen to know that our KEYMGMT simply passes DSA structures, so
* we use that here too.
*/
typedef struct {
OSSL_LIB_CTX *libctx;
char *propq;
DSA *dsa;
/*
* Flag to determine if the hash function can be changed (1) or not (0)
* Because it's dangerous to change during a DigestSign or DigestVerify
* operation, this flag is cleared by their Init function, and set again
* by their Final function.
*/
unsigned int flag_allow_md : 1;
/* If this is set to 1 then the generated k is not random */
unsigned int nonce_type;
char mdname[OSSL_MAX_NAME_SIZE];
/* The Algorithm Identifier of the combined signature algorithm */
unsigned char aid_buf[OSSL_MAX_ALGORITHM_ID_SIZE];
unsigned char *aid;
size_t aid_len;
/* main digest */
EVP_MD *md;
EVP_MD_CTX *mdctx;
int operation;
} PROV_DSA_CTX;
static size_t dsa_get_md_size(const PROV_DSA_CTX *pdsactx)
{
if (pdsactx->md != NULL)
return EVP_MD_get_size(pdsactx->md);
return 0;
}
static void *dsa_newctx(void *provctx, const char *propq)
{
PROV_DSA_CTX *pdsactx;
if (!ossl_prov_is_running())
return NULL;
pdsactx = OPENSSL_zalloc(sizeof(PROV_DSA_CTX));
if (pdsactx == NULL)
return NULL;
pdsactx->libctx = PROV_LIBCTX_OF(provctx);
pdsactx->flag_allow_md = 1;
if (propq != NULL && (pdsactx->propq = OPENSSL_strdup(propq)) == NULL) {
OPENSSL_free(pdsactx);
pdsactx = NULL;
}
return pdsactx;
}
static int dsa_setup_md(PROV_DSA_CTX *ctx,
const char *mdname, const char *mdprops)
{
if (mdprops == NULL)
mdprops = ctx->propq;
if (mdname != NULL) {
int sha1_allowed = (ctx->operation != EVP_PKEY_OP_SIGN);
WPACKET pkt;
EVP_MD *md = EVP_MD_fetch(ctx->libctx, mdname, mdprops);
int md_nid = ossl_digest_get_approved_nid_with_sha1(ctx->libctx, md,
sha1_allowed);
size_t mdname_len = strlen(mdname);
if (md == NULL || md_nid < 0) {
if (md == NULL)
ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_DIGEST,
"%s could not be fetched", mdname);
if (md_nid < 0)
ERR_raise_data(ERR_LIB_PROV, PROV_R_DIGEST_NOT_ALLOWED,
"digest=%s", mdname);
if (mdname_len >= sizeof(ctx->mdname))
ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_DIGEST,
"%s exceeds name buffer length", mdname);
EVP_MD_free(md);
return 0;
}
if (!ctx->flag_allow_md) {
if (ctx->mdname[0] != '\0' && !EVP_MD_is_a(md, ctx->mdname)) {
ERR_raise_data(ERR_LIB_PROV, PROV_R_DIGEST_NOT_ALLOWED,
"digest %s != %s", mdname, ctx->mdname);
EVP_MD_free(md);
return 0;
}
EVP_MD_free(md);
return 1;
}
EVP_MD_CTX_free(ctx->mdctx);
EVP_MD_free(ctx->md);
/*
* We do not care about DER writing errors.
* All it really means is that for some reason, there's no
* AlgorithmIdentifier to be had, but the operation itself is
* still valid, just as long as it's not used to construct
* anything that needs an AlgorithmIdentifier.
*/
ctx->aid_len = 0;
if (WPACKET_init_der(&pkt, ctx->aid_buf, sizeof(ctx->aid_buf))
&& ossl_DER_w_algorithmIdentifier_DSA_with_MD(&pkt, -1, ctx->dsa,
md_nid)
&& WPACKET_finish(&pkt)) {
WPACKET_get_total_written(&pkt, &ctx->aid_len);
ctx->aid = WPACKET_get_curr(&pkt);
}
WPACKET_cleanup(&pkt);
ctx->mdctx = NULL;
ctx->md = md;
OPENSSL_strlcpy(ctx->mdname, mdname, sizeof(ctx->mdname));
}
return 1;
}
static int dsa_signverify_init(void *vpdsactx, void *vdsa,
const OSSL_PARAM params[], int operation)
{
PROV_DSA_CTX *pdsactx = (PROV_DSA_CTX *)vpdsactx;
if (!ossl_prov_is_running()
|| pdsactx == NULL)
return 0;
if (vdsa == NULL && pdsactx->dsa == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_NO_KEY_SET);
return 0;
}
if (vdsa != NULL) {
if (!ossl_dsa_check_key(pdsactx->libctx, vdsa,
operation == EVP_PKEY_OP_SIGN)) {
ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
return 0;
}
if (!DSA_up_ref(vdsa))
return 0;
DSA_free(pdsactx->dsa);
pdsactx->dsa = vdsa;
}
pdsactx->operation = operation;
if (!dsa_set_ctx_params(pdsactx, params))
return 0;
return 1;
}
static int dsa_sign_init(void *vpdsactx, void *vdsa, const OSSL_PARAM params[])
{
return dsa_signverify_init(vpdsactx, vdsa, params, EVP_PKEY_OP_SIGN);
}
static int dsa_verify_init(void *vpdsactx, void *vdsa,
const OSSL_PARAM params[])
{
return dsa_signverify_init(vpdsactx, vdsa, params, EVP_PKEY_OP_VERIFY);
}
static int dsa_sign(void *vpdsactx, unsigned char *sig, size_t *siglen,
size_t sigsize, const unsigned char *tbs, size_t tbslen)
{
PROV_DSA_CTX *pdsactx = (PROV_DSA_CTX *)vpdsactx;
int ret;
unsigned int sltmp;
size_t dsasize = DSA_size(pdsactx->dsa);
size_t mdsize = dsa_get_md_size(pdsactx);
if (!ossl_prov_is_running())
return 0;
if (sig == NULL) {
*siglen = dsasize;
return 1;
}
if (sigsize < (size_t)dsasize)
return 0;
if (mdsize != 0 && tbslen != mdsize)
return 0;
ret = ossl_dsa_sign_int(0, tbs, tbslen, sig, &sltmp, pdsactx->dsa,
pdsactx->nonce_type, pdsactx->mdname,
pdsactx->libctx, pdsactx->propq);
if (ret <= 0)
return 0;
*siglen = sltmp;
return 1;
}
static int dsa_verify(void *vpdsactx, const unsigned char *sig, size_t siglen,
const unsigned char *tbs, size_t tbslen)
{
PROV_DSA_CTX *pdsactx = (PROV_DSA_CTX *)vpdsactx;
size_t mdsize = dsa_get_md_size(pdsactx);
if (!ossl_prov_is_running() || (mdsize != 0 && tbslen != mdsize))
return 0;
return DSA_verify(0, tbs, tbslen, sig, siglen, pdsactx->dsa);
}
static int dsa_digest_signverify_init(void *vpdsactx, const char *mdname,
void *vdsa, const OSSL_PARAM params[],
int operation)
{
PROV_DSA_CTX *pdsactx = (PROV_DSA_CTX *)vpdsactx;
if (!ossl_prov_is_running())
return 0;
if (!dsa_signverify_init(vpdsactx, vdsa, params, operation))
return 0;
if (!dsa_setup_md(pdsactx, mdname, NULL))
return 0;
pdsactx->flag_allow_md = 0;
if (pdsactx->mdctx == NULL) {
pdsactx->mdctx = EVP_MD_CTX_new();
if (pdsactx->mdctx == NULL)
goto error;
}
if (!EVP_DigestInit_ex2(pdsactx->mdctx, pdsactx->md, params))
goto error;
return 1;
error:
EVP_MD_CTX_free(pdsactx->mdctx);
pdsactx->mdctx = NULL;
return 0;
}
static int dsa_digest_sign_init(void *vpdsactx, const char *mdname,
void *vdsa, const OSSL_PARAM params[])
{
return dsa_digest_signverify_init(vpdsactx, mdname, vdsa, params,
EVP_PKEY_OP_SIGN);
}
static int dsa_digest_verify_init(void *vpdsactx, const char *mdname,
void *vdsa, const OSSL_PARAM params[])
{
return dsa_digest_signverify_init(vpdsactx, mdname, vdsa, params,
EVP_PKEY_OP_VERIFY);
}
int dsa_digest_signverify_update(void *vpdsactx, const unsigned char *data,
size_t datalen)
{
PROV_DSA_CTX *pdsactx = (PROV_DSA_CTX *)vpdsactx;
if (pdsactx == NULL || pdsactx->mdctx == NULL)
return 0;
return EVP_DigestUpdate(pdsactx->mdctx, data, datalen);
}
int dsa_digest_sign_final(void *vpdsactx, unsigned char *sig, size_t *siglen,
size_t sigsize)
{
PROV_DSA_CTX *pdsactx = (PROV_DSA_CTX *)vpdsactx;
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int dlen = 0;
if (!ossl_prov_is_running() || pdsactx == NULL || pdsactx->mdctx == NULL)
return 0;
/*
* If sig is NULL then we're just finding out the sig size. Other fields
* are ignored. Defer to dsa_sign.
*/
if (sig != NULL) {
/*
* There is the possibility that some externally provided
* digests exceed EVP_MAX_MD_SIZE. We should probably handle that somehow -
* but that problem is much larger than just in DSA.
*/
if (!EVP_DigestFinal_ex(pdsactx->mdctx, digest, &dlen))
return 0;
}
pdsactx->flag_allow_md = 1;
return dsa_sign(vpdsactx, sig, siglen, sigsize, digest, (size_t)dlen);
}
int dsa_digest_verify_final(void *vpdsactx, const unsigned char *sig,
size_t siglen)
{
PROV_DSA_CTX *pdsactx = (PROV_DSA_CTX *)vpdsactx;
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int dlen = 0;
if (!ossl_prov_is_running() || pdsactx == NULL || pdsactx->mdctx == NULL)
return 0;
/*
* There is the possibility that some externally provided
* digests exceed EVP_MAX_MD_SIZE. We should probably handle that somehow -
* but that problem is much larger than just in DSA.
*/
if (!EVP_DigestFinal_ex(pdsactx->mdctx, digest, &dlen))
return 0;
pdsactx->flag_allow_md = 1;
return dsa_verify(vpdsactx, sig, siglen, digest, (size_t)dlen);
}
static void dsa_freectx(void *vpdsactx)
{
PROV_DSA_CTX *ctx = (PROV_DSA_CTX *)vpdsactx;
OPENSSL_free(ctx->propq);
EVP_MD_CTX_free(ctx->mdctx);
EVP_MD_free(ctx->md);
ctx->propq = NULL;
ctx->mdctx = NULL;
ctx->md = NULL;
DSA_free(ctx->dsa);
OPENSSL_free(ctx);
}
static void *dsa_dupctx(void *vpdsactx)
{
PROV_DSA_CTX *srcctx = (PROV_DSA_CTX *)vpdsactx;
PROV_DSA_CTX *dstctx;
if (!ossl_prov_is_running())
return NULL;
dstctx = OPENSSL_zalloc(sizeof(*srcctx));
if (dstctx == NULL)
return NULL;
*dstctx = *srcctx;
dstctx->dsa = NULL;
dstctx->md = NULL;
dstctx->mdctx = NULL;
dstctx->propq = NULL;
if (srcctx->dsa != NULL && !DSA_up_ref(srcctx->dsa))
goto err;
dstctx->dsa = srcctx->dsa;
if (srcctx->md != NULL && !EVP_MD_up_ref(srcctx->md))
goto err;
dstctx->md = srcctx->md;
if (srcctx->mdctx != NULL) {
dstctx->mdctx = EVP_MD_CTX_new();
if (dstctx->mdctx == NULL
|| !EVP_MD_CTX_copy_ex(dstctx->mdctx, srcctx->mdctx))
goto err;
}
if (srcctx->propq != NULL) {
dstctx->propq = OPENSSL_strdup(srcctx->propq);
if (dstctx->propq == NULL)
goto err;
}
return dstctx;
err:
dsa_freectx(dstctx);
return NULL;
}
static int dsa_get_ctx_params(void *vpdsactx, OSSL_PARAM *params)
{
PROV_DSA_CTX *pdsactx = (PROV_DSA_CTX *)vpdsactx;
OSSL_PARAM *p;
if (pdsactx == NULL)
return 0;
p = OSSL_PARAM_locate(params, OSSL_SIGNATURE_PARAM_ALGORITHM_ID);
if (p != NULL
&& !OSSL_PARAM_set_octet_string(p, pdsactx->aid, pdsactx->aid_len))
return 0;
p = OSSL_PARAM_locate(params, OSSL_SIGNATURE_PARAM_DIGEST);
if (p != NULL && !OSSL_PARAM_set_utf8_string(p, pdsactx->mdname))
return 0;
p = OSSL_PARAM_locate(params, OSSL_SIGNATURE_PARAM_NONCE_TYPE);
if (p != NULL && !OSSL_PARAM_set_uint(p, pdsactx->nonce_type))
return 0;
return 1;
}
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_octet_string(OSSL_SIGNATURE_PARAM_ALGORITHM_ID, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_uint(OSSL_SIGNATURE_PARAM_NONCE_TYPE, NULL),
OSSL_PARAM_END
};
static const OSSL_PARAM *dsa_gettable_ctx_params(ossl_unused void *ctx,
ossl_unused void *provctx)
{
return known_gettable_ctx_params;
}
static int dsa_set_ctx_params(void *vpdsactx, const OSSL_PARAM params[])
{
PROV_DSA_CTX *pdsactx = (PROV_DSA_CTX *)vpdsactx;
const OSSL_PARAM *p;
if (pdsactx == NULL)
return 0;
if (params == NULL)
return 1;
p = OSSL_PARAM_locate_const(params, OSSL_SIGNATURE_PARAM_DIGEST);
if (p != NULL) {
char mdname[OSSL_MAX_NAME_SIZE] = "", *pmdname = mdname;
char mdprops[OSSL_MAX_PROPQUERY_SIZE] = "", *pmdprops = mdprops;
const OSSL_PARAM *propsp =
OSSL_PARAM_locate_const(params,
OSSL_SIGNATURE_PARAM_PROPERTIES);
if (!OSSL_PARAM_get_utf8_string(p, &pmdname, sizeof(mdname)))
return 0;
if (propsp != NULL
&& !OSSL_PARAM_get_utf8_string(propsp, &pmdprops, sizeof(mdprops)))
return 0;
if (!dsa_setup_md(pdsactx, mdname, mdprops))
return 0;
}
p = OSSL_PARAM_locate_const(params, OSSL_SIGNATURE_PARAM_NONCE_TYPE);
if (p != NULL
&& !OSSL_PARAM_get_uint(p, &pdsactx->nonce_type))
return 0;
return 1;
}
static const OSSL_PARAM settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_SIGNATURE_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_uint(OSSL_SIGNATURE_PARAM_NONCE_TYPE, NULL),
OSSL_PARAM_END
};
static const OSSL_PARAM settable_ctx_params_no_digest[] = {
OSSL_PARAM_END
};
static const OSSL_PARAM *dsa_settable_ctx_params(void *vpdsactx,
ossl_unused void *provctx)
{
PROV_DSA_CTX *pdsactx = (PROV_DSA_CTX *)vpdsactx;
if (pdsactx != NULL && !pdsactx->flag_allow_md)
return settable_ctx_params_no_digest;
return settable_ctx_params;
}
static int dsa_get_ctx_md_params(void *vpdsactx, OSSL_PARAM *params)
{
PROV_DSA_CTX *pdsactx = (PROV_DSA_CTX *)vpdsactx;
if (pdsactx->mdctx == NULL)
return 0;
return EVP_MD_CTX_get_params(pdsactx->mdctx, params);
}
static const OSSL_PARAM *dsa_gettable_ctx_md_params(void *vpdsactx)
{
PROV_DSA_CTX *pdsactx = (PROV_DSA_CTX *)vpdsactx;
if (pdsactx->md == NULL)
return 0;
return EVP_MD_gettable_ctx_params(pdsactx->md);
}
static int dsa_set_ctx_md_params(void *vpdsactx, const OSSL_PARAM params[])
{
PROV_DSA_CTX *pdsactx = (PROV_DSA_CTX *)vpdsactx;
if (pdsactx->mdctx == NULL)
return 0;
return EVP_MD_CTX_set_params(pdsactx->mdctx, params);
}
static const OSSL_PARAM *dsa_settable_ctx_md_params(void *vpdsactx)
{
PROV_DSA_CTX *pdsactx = (PROV_DSA_CTX *)vpdsactx;
if (pdsactx->md == NULL)
return 0;
return EVP_MD_settable_ctx_params(pdsactx->md);
}
const OSSL_DISPATCH ossl_dsa_signature_functions[] = {
{ OSSL_FUNC_SIGNATURE_NEWCTX, (void (*)(void))dsa_newctx },
{ OSSL_FUNC_SIGNATURE_SIGN_INIT, (void (*)(void))dsa_sign_init },
{ OSSL_FUNC_SIGNATURE_SIGN, (void (*)(void))dsa_sign },
{ OSSL_FUNC_SIGNATURE_VERIFY_INIT, (void (*)(void))dsa_verify_init },
{ OSSL_FUNC_SIGNATURE_VERIFY, (void (*)(void))dsa_verify },
{ OSSL_FUNC_SIGNATURE_DIGEST_SIGN_INIT,
(void (*)(void))dsa_digest_sign_init },
{ OSSL_FUNC_SIGNATURE_DIGEST_SIGN_UPDATE,
(void (*)(void))dsa_digest_signverify_update },
{ OSSL_FUNC_SIGNATURE_DIGEST_SIGN_FINAL,
(void (*)(void))dsa_digest_sign_final },
{ OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_INIT,
(void (*)(void))dsa_digest_verify_init },
{ OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_UPDATE,
(void (*)(void))dsa_digest_signverify_update },
{ OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_FINAL,
(void (*)(void))dsa_digest_verify_final },
{ OSSL_FUNC_SIGNATURE_FREECTX, (void (*)(void))dsa_freectx },
{ OSSL_FUNC_SIGNATURE_DUPCTX, (void (*)(void))dsa_dupctx },
{ OSSL_FUNC_SIGNATURE_GET_CTX_PARAMS, (void (*)(void))dsa_get_ctx_params },
{ OSSL_FUNC_SIGNATURE_GETTABLE_CTX_PARAMS,
(void (*)(void))dsa_gettable_ctx_params },
{ OSSL_FUNC_SIGNATURE_SET_CTX_PARAMS, (void (*)(void))dsa_set_ctx_params },
{ OSSL_FUNC_SIGNATURE_SETTABLE_CTX_PARAMS,
(void (*)(void))dsa_settable_ctx_params },
{ OSSL_FUNC_SIGNATURE_GET_CTX_MD_PARAMS,
(void (*)(void))dsa_get_ctx_md_params },
{ OSSL_FUNC_SIGNATURE_GETTABLE_CTX_MD_PARAMS,
(void (*)(void))dsa_gettable_ctx_md_params },
{ OSSL_FUNC_SIGNATURE_SET_CTX_MD_PARAMS,
(void (*)(void))dsa_set_ctx_md_params },
{ OSSL_FUNC_SIGNATURE_SETTABLE_CTX_MD_PARAMS,
(void (*)(void))dsa_settable_ctx_md_params },
OSSL_DISPATCH_END
};
| 19,403 | 30.55122 | 83 | c |
openssl | openssl-master/providers/implementations/signature/ecdsa_sig.c | /*
* Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* ECDSA low level APIs are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include <string.h> /* memcpy */
#include <openssl/crypto.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/dsa.h>
#include <openssl/params.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/proverr.h>
#include "internal/nelem.h"
#include "internal/sizes.h"
#include "internal/cryptlib.h"
#include "internal/deterministic_nonce.h"
#include "prov/providercommon.h"
#include "prov/implementations.h"
#include "prov/provider_ctx.h"
#include "prov/securitycheck.h"
#include "crypto/ec.h"
#include "prov/der_ec.h"
static OSSL_FUNC_signature_newctx_fn ecdsa_newctx;
static OSSL_FUNC_signature_sign_init_fn ecdsa_sign_init;
static OSSL_FUNC_signature_verify_init_fn ecdsa_verify_init;
static OSSL_FUNC_signature_sign_fn ecdsa_sign;
static OSSL_FUNC_signature_verify_fn ecdsa_verify;
static OSSL_FUNC_signature_digest_sign_init_fn ecdsa_digest_sign_init;
static OSSL_FUNC_signature_digest_sign_update_fn ecdsa_digest_signverify_update;
static OSSL_FUNC_signature_digest_sign_final_fn ecdsa_digest_sign_final;
static OSSL_FUNC_signature_digest_verify_init_fn ecdsa_digest_verify_init;
static OSSL_FUNC_signature_digest_verify_update_fn ecdsa_digest_signverify_update;
static OSSL_FUNC_signature_digest_verify_final_fn ecdsa_digest_verify_final;
static OSSL_FUNC_signature_freectx_fn ecdsa_freectx;
static OSSL_FUNC_signature_dupctx_fn ecdsa_dupctx;
static OSSL_FUNC_signature_get_ctx_params_fn ecdsa_get_ctx_params;
static OSSL_FUNC_signature_gettable_ctx_params_fn ecdsa_gettable_ctx_params;
static OSSL_FUNC_signature_set_ctx_params_fn ecdsa_set_ctx_params;
static OSSL_FUNC_signature_settable_ctx_params_fn ecdsa_settable_ctx_params;
static OSSL_FUNC_signature_get_ctx_md_params_fn ecdsa_get_ctx_md_params;
static OSSL_FUNC_signature_gettable_ctx_md_params_fn ecdsa_gettable_ctx_md_params;
static OSSL_FUNC_signature_set_ctx_md_params_fn ecdsa_set_ctx_md_params;
static OSSL_FUNC_signature_settable_ctx_md_params_fn ecdsa_settable_ctx_md_params;
/*
* What's passed as an actual key is defined by the KEYMGMT interface.
* We happen to know that our KEYMGMT simply passes DSA structures, so
* we use that here too.
*/
typedef struct {
OSSL_LIB_CTX *libctx;
char *propq;
EC_KEY *ec;
char mdname[OSSL_MAX_NAME_SIZE];
/*
* Flag to determine if the hash function can be changed (1) or not (0)
* Because it's dangerous to change during a DigestSign or DigestVerify
* operation, this flag is cleared by their Init function, and set again
* by their Final function.
*/
unsigned int flag_allow_md : 1;
/* The Algorithm Identifier of the combined signature algorithm */
unsigned char aid_buf[OSSL_MAX_ALGORITHM_ID_SIZE];
unsigned char *aid;
size_t aid_len;
size_t mdsize;
int operation;
EVP_MD *md;
EVP_MD_CTX *mdctx;
/*
* Internally used to cache the results of calling the EC group
* sign_setup() methods which are then passed to the sign operation.
* This is used by CAVS failure tests to terminate a loop if the signature
* is not valid.
* This could of also been done with a simple flag.
*/
BIGNUM *kinv;
BIGNUM *r;
#if !defined(OPENSSL_NO_ACVP_TESTS)
/*
* This indicates that KAT (CAVS) test is running. Externally an app will
* override the random callback such that the generated private key and k
* are known.
* Normal operation will loop to choose a new k if the signature is not
* valid - but for this mode of operation it forces a failure instead.
*/
unsigned int kattest;
#endif
/* If this is set then the generated k is not random */
unsigned int nonce_type;
} PROV_ECDSA_CTX;
static void *ecdsa_newctx(void *provctx, const char *propq)
{
PROV_ECDSA_CTX *ctx;
if (!ossl_prov_is_running())
return NULL;
ctx = OPENSSL_zalloc(sizeof(PROV_ECDSA_CTX));
if (ctx == NULL)
return NULL;
ctx->flag_allow_md = 1;
ctx->libctx = PROV_LIBCTX_OF(provctx);
if (propq != NULL && (ctx->propq = OPENSSL_strdup(propq)) == NULL) {
OPENSSL_free(ctx);
ctx = NULL;
}
return ctx;
}
static int ecdsa_signverify_init(void *vctx, void *ec,
const OSSL_PARAM params[], int operation)
{
PROV_ECDSA_CTX *ctx = (PROV_ECDSA_CTX *)vctx;
if (!ossl_prov_is_running()
|| ctx == NULL)
return 0;
if (ec == NULL && ctx->ec == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_NO_KEY_SET);
return 0;
}
if (ec != NULL) {
if (!ossl_ec_check_key(ctx->libctx, ec, operation == EVP_PKEY_OP_SIGN))
return 0;
if (!EC_KEY_up_ref(ec))
return 0;
EC_KEY_free(ctx->ec);
ctx->ec = ec;
}
ctx->operation = operation;
if (!ecdsa_set_ctx_params(ctx, params))
return 0;
return 1;
}
static int ecdsa_sign_init(void *vctx, void *ec, const OSSL_PARAM params[])
{
return ecdsa_signverify_init(vctx, ec, params, EVP_PKEY_OP_SIGN);
}
static int ecdsa_verify_init(void *vctx, void *ec, const OSSL_PARAM params[])
{
return ecdsa_signverify_init(vctx, ec, params, EVP_PKEY_OP_VERIFY);
}
static int ecdsa_sign(void *vctx, unsigned char *sig, size_t *siglen,
size_t sigsize, const unsigned char *tbs, size_t tbslen)
{
PROV_ECDSA_CTX *ctx = (PROV_ECDSA_CTX *)vctx;
int ret;
unsigned int sltmp;
size_t ecsize = ECDSA_size(ctx->ec);
if (!ossl_prov_is_running())
return 0;
if (sig == NULL) {
*siglen = ecsize;
return 1;
}
#if !defined(OPENSSL_NO_ACVP_TESTS)
if (ctx->kattest && !ECDSA_sign_setup(ctx->ec, NULL, &ctx->kinv, &ctx->r))
return 0;
#endif
if (sigsize < (size_t)ecsize)
return 0;
if (ctx->mdsize != 0 && tbslen != ctx->mdsize)
return 0;
if (ctx->nonce_type != 0) {
ret = ossl_ecdsa_deterministic_sign(tbs, tbslen, sig, &sltmp,
ctx->ec, ctx->nonce_type,
ctx->mdname,
ctx->libctx, ctx->propq);
} else {
ret = ECDSA_sign_ex(0, tbs, tbslen, sig, &sltmp, ctx->kinv, ctx->r,
ctx->ec);
}
if (ret <= 0)
return 0;
*siglen = sltmp;
return 1;
}
static int ecdsa_verify(void *vctx, const unsigned char *sig, size_t siglen,
const unsigned char *tbs, size_t tbslen)
{
PROV_ECDSA_CTX *ctx = (PROV_ECDSA_CTX *)vctx;
if (!ossl_prov_is_running() || (ctx->mdsize != 0 && tbslen != ctx->mdsize))
return 0;
return ECDSA_verify(0, tbs, tbslen, sig, siglen, ctx->ec);
}
static int ecdsa_setup_md(PROV_ECDSA_CTX *ctx, const char *mdname,
const char *mdprops)
{
EVP_MD *md = NULL;
size_t mdname_len;
int md_nid, sha1_allowed;
WPACKET pkt;
if (mdname == NULL)
return 1;
mdname_len = strlen(mdname);
if (mdname_len >= sizeof(ctx->mdname)) {
ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_DIGEST,
"%s exceeds name buffer length", mdname);
return 0;
}
if (mdprops == NULL)
mdprops = ctx->propq;
md = EVP_MD_fetch(ctx->libctx, mdname, mdprops);
if (md == NULL) {
ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_DIGEST,
"%s could not be fetched", mdname);
return 0;
}
sha1_allowed = (ctx->operation != EVP_PKEY_OP_SIGN);
md_nid = ossl_digest_get_approved_nid_with_sha1(ctx->libctx, md,
sha1_allowed);
if (md_nid < 0) {
ERR_raise_data(ERR_LIB_PROV, PROV_R_DIGEST_NOT_ALLOWED,
"digest=%s", mdname);
EVP_MD_free(md);
return 0;
}
if (!ctx->flag_allow_md) {
if (ctx->mdname[0] != '\0' && !EVP_MD_is_a(md, ctx->mdname)) {
ERR_raise_data(ERR_LIB_PROV, PROV_R_DIGEST_NOT_ALLOWED,
"digest %s != %s", mdname, ctx->mdname);
EVP_MD_free(md);
return 0;
}
EVP_MD_free(md);
return 1;
}
EVP_MD_CTX_free(ctx->mdctx);
EVP_MD_free(ctx->md);
ctx->aid_len = 0;
if (WPACKET_init_der(&pkt, ctx->aid_buf, sizeof(ctx->aid_buf))
&& ossl_DER_w_algorithmIdentifier_ECDSA_with_MD(&pkt, -1, ctx->ec,
md_nid)
&& WPACKET_finish(&pkt)) {
WPACKET_get_total_written(&pkt, &ctx->aid_len);
ctx->aid = WPACKET_get_curr(&pkt);
}
WPACKET_cleanup(&pkt);
ctx->mdctx = NULL;
ctx->md = md;
ctx->mdsize = EVP_MD_get_size(ctx->md);
OPENSSL_strlcpy(ctx->mdname, mdname, sizeof(ctx->mdname));
return 1;
}
static int ecdsa_digest_signverify_init(void *vctx, const char *mdname,
void *ec, const OSSL_PARAM params[],
int operation)
{
PROV_ECDSA_CTX *ctx = (PROV_ECDSA_CTX *)vctx;
if (!ossl_prov_is_running())
return 0;
if (!ecdsa_signverify_init(vctx, ec, params, operation)
|| !ecdsa_setup_md(ctx, mdname, NULL))
return 0;
ctx->flag_allow_md = 0;
if (ctx->mdctx == NULL) {
ctx->mdctx = EVP_MD_CTX_new();
if (ctx->mdctx == NULL)
goto error;
}
if (!EVP_DigestInit_ex2(ctx->mdctx, ctx->md, params))
goto error;
return 1;
error:
EVP_MD_CTX_free(ctx->mdctx);
ctx->mdctx = NULL;
return 0;
}
static int ecdsa_digest_sign_init(void *vctx, const char *mdname, void *ec,
const OSSL_PARAM params[])
{
return ecdsa_digest_signverify_init(vctx, mdname, ec, params,
EVP_PKEY_OP_SIGN);
}
static int ecdsa_digest_verify_init(void *vctx, const char *mdname, void *ec,
const OSSL_PARAM params[])
{
return ecdsa_digest_signverify_init(vctx, mdname, ec, params,
EVP_PKEY_OP_VERIFY);
}
int ecdsa_digest_signverify_update(void *vctx, const unsigned char *data,
size_t datalen)
{
PROV_ECDSA_CTX *ctx = (PROV_ECDSA_CTX *)vctx;
if (ctx == NULL || ctx->mdctx == NULL)
return 0;
return EVP_DigestUpdate(ctx->mdctx, data, datalen);
}
int ecdsa_digest_sign_final(void *vctx, unsigned char *sig, size_t *siglen,
size_t sigsize)
{
PROV_ECDSA_CTX *ctx = (PROV_ECDSA_CTX *)vctx;
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int dlen = 0;
if (!ossl_prov_is_running() || ctx == NULL || ctx->mdctx == NULL)
return 0;
/*
* If sig is NULL then we're just finding out the sig size. Other fields
* are ignored. Defer to ecdsa_sign.
*/
if (sig != NULL
&& !EVP_DigestFinal_ex(ctx->mdctx, digest, &dlen))
return 0;
ctx->flag_allow_md = 1;
return ecdsa_sign(vctx, sig, siglen, sigsize, digest, (size_t)dlen);
}
int ecdsa_digest_verify_final(void *vctx, const unsigned char *sig,
size_t siglen)
{
PROV_ECDSA_CTX *ctx = (PROV_ECDSA_CTX *)vctx;
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int dlen = 0;
if (!ossl_prov_is_running() || ctx == NULL || ctx->mdctx == NULL)
return 0;
if (!EVP_DigestFinal_ex(ctx->mdctx, digest, &dlen))
return 0;
ctx->flag_allow_md = 1;
return ecdsa_verify(ctx, sig, siglen, digest, (size_t)dlen);
}
static void ecdsa_freectx(void *vctx)
{
PROV_ECDSA_CTX *ctx = (PROV_ECDSA_CTX *)vctx;
OPENSSL_free(ctx->propq);
EVP_MD_CTX_free(ctx->mdctx);
EVP_MD_free(ctx->md);
ctx->propq = NULL;
ctx->mdctx = NULL;
ctx->md = NULL;
ctx->mdsize = 0;
EC_KEY_free(ctx->ec);
BN_clear_free(ctx->kinv);
BN_clear_free(ctx->r);
OPENSSL_free(ctx);
}
static void *ecdsa_dupctx(void *vctx)
{
PROV_ECDSA_CTX *srcctx = (PROV_ECDSA_CTX *)vctx;
PROV_ECDSA_CTX *dstctx;
if (!ossl_prov_is_running())
return NULL;
dstctx = OPENSSL_zalloc(sizeof(*srcctx));
if (dstctx == NULL)
return NULL;
*dstctx = *srcctx;
dstctx->ec = NULL;
dstctx->md = NULL;
dstctx->mdctx = NULL;
dstctx->propq = NULL;
if (srcctx->ec != NULL && !EC_KEY_up_ref(srcctx->ec))
goto err;
/* Test KATS should not need to be supported */
if (srcctx->kinv != NULL || srcctx->r != NULL)
goto err;
dstctx->ec = srcctx->ec;
if (srcctx->md != NULL && !EVP_MD_up_ref(srcctx->md))
goto err;
dstctx->md = srcctx->md;
if (srcctx->mdctx != NULL) {
dstctx->mdctx = EVP_MD_CTX_new();
if (dstctx->mdctx == NULL
|| !EVP_MD_CTX_copy_ex(dstctx->mdctx, srcctx->mdctx))
goto err;
}
if (srcctx->propq != NULL) {
dstctx->propq = OPENSSL_strdup(srcctx->propq);
if (dstctx->propq == NULL)
goto err;
}
return dstctx;
err:
ecdsa_freectx(dstctx);
return NULL;
}
static int ecdsa_get_ctx_params(void *vctx, OSSL_PARAM *params)
{
PROV_ECDSA_CTX *ctx = (PROV_ECDSA_CTX *)vctx;
OSSL_PARAM *p;
if (ctx == NULL)
return 0;
p = OSSL_PARAM_locate(params, OSSL_SIGNATURE_PARAM_ALGORITHM_ID);
if (p != NULL && !OSSL_PARAM_set_octet_string(p, ctx->aid, ctx->aid_len))
return 0;
p = OSSL_PARAM_locate(params, OSSL_SIGNATURE_PARAM_DIGEST_SIZE);
if (p != NULL && !OSSL_PARAM_set_size_t(p, ctx->mdsize))
return 0;
p = OSSL_PARAM_locate(params, OSSL_SIGNATURE_PARAM_DIGEST);
if (p != NULL && !OSSL_PARAM_set_utf8_string(p, ctx->md == NULL
? ctx->mdname
: EVP_MD_get0_name(ctx->md)))
return 0;
p = OSSL_PARAM_locate(params, OSSL_SIGNATURE_PARAM_NONCE_TYPE);
if (p != NULL && !OSSL_PARAM_set_uint(p, ctx->nonce_type))
return 0;
return 1;
}
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_octet_string(OSSL_SIGNATURE_PARAM_ALGORITHM_ID, NULL, 0),
OSSL_PARAM_size_t(OSSL_SIGNATURE_PARAM_DIGEST_SIZE, NULL),
OSSL_PARAM_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_uint(OSSL_SIGNATURE_PARAM_NONCE_TYPE, NULL),
OSSL_PARAM_END
};
static const OSSL_PARAM *ecdsa_gettable_ctx_params(ossl_unused void *vctx,
ossl_unused void *provctx)
{
return known_gettable_ctx_params;
}
static int ecdsa_set_ctx_params(void *vctx, const OSSL_PARAM params[])
{
PROV_ECDSA_CTX *ctx = (PROV_ECDSA_CTX *)vctx;
const OSSL_PARAM *p;
size_t mdsize = 0;
if (ctx == NULL)
return 0;
if (params == NULL)
return 1;
#if !defined(OPENSSL_NO_ACVP_TESTS)
p = OSSL_PARAM_locate_const(params, OSSL_SIGNATURE_PARAM_KAT);
if (p != NULL && !OSSL_PARAM_get_uint(p, &ctx->kattest))
return 0;
#endif
p = OSSL_PARAM_locate_const(params, OSSL_SIGNATURE_PARAM_DIGEST);
if (p != NULL) {
char mdname[OSSL_MAX_NAME_SIZE] = "", *pmdname = mdname;
char mdprops[OSSL_MAX_PROPQUERY_SIZE] = "", *pmdprops = mdprops;
const OSSL_PARAM *propsp =
OSSL_PARAM_locate_const(params,
OSSL_SIGNATURE_PARAM_PROPERTIES);
if (!OSSL_PARAM_get_utf8_string(p, &pmdname, sizeof(mdname)))
return 0;
if (propsp != NULL
&& !OSSL_PARAM_get_utf8_string(propsp, &pmdprops, sizeof(mdprops)))
return 0;
if (!ecdsa_setup_md(ctx, mdname, mdprops))
return 0;
}
p = OSSL_PARAM_locate_const(params, OSSL_SIGNATURE_PARAM_DIGEST_SIZE);
if (p != NULL) {
if (!OSSL_PARAM_get_size_t(p, &mdsize)
|| (!ctx->flag_allow_md && mdsize != ctx->mdsize))
return 0;
ctx->mdsize = mdsize;
}
p = OSSL_PARAM_locate_const(params, OSSL_SIGNATURE_PARAM_NONCE_TYPE);
if (p != NULL
&& !OSSL_PARAM_get_uint(p, &ctx->nonce_type))
return 0;
return 1;
}
static const OSSL_PARAM settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_size_t(OSSL_SIGNATURE_PARAM_DIGEST_SIZE, NULL),
OSSL_PARAM_utf8_string(OSSL_SIGNATURE_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_uint(OSSL_SIGNATURE_PARAM_KAT, NULL),
OSSL_PARAM_uint(OSSL_SIGNATURE_PARAM_NONCE_TYPE, NULL),
OSSL_PARAM_END
};
static const OSSL_PARAM settable_ctx_params_no_digest[] = {
OSSL_PARAM_uint(OSSL_SIGNATURE_PARAM_KAT, NULL),
OSSL_PARAM_END
};
static const OSSL_PARAM *ecdsa_settable_ctx_params(void *vctx,
ossl_unused void *provctx)
{
PROV_ECDSA_CTX *ctx = (PROV_ECDSA_CTX *)vctx;
if (ctx != NULL && !ctx->flag_allow_md)
return settable_ctx_params_no_digest;
return settable_ctx_params;
}
static int ecdsa_get_ctx_md_params(void *vctx, OSSL_PARAM *params)
{
PROV_ECDSA_CTX *ctx = (PROV_ECDSA_CTX *)vctx;
if (ctx->mdctx == NULL)
return 0;
return EVP_MD_CTX_get_params(ctx->mdctx, params);
}
static const OSSL_PARAM *ecdsa_gettable_ctx_md_params(void *vctx)
{
PROV_ECDSA_CTX *ctx = (PROV_ECDSA_CTX *)vctx;
if (ctx->md == NULL)
return 0;
return EVP_MD_gettable_ctx_params(ctx->md);
}
static int ecdsa_set_ctx_md_params(void *vctx, const OSSL_PARAM params[])
{
PROV_ECDSA_CTX *ctx = (PROV_ECDSA_CTX *)vctx;
if (ctx->mdctx == NULL)
return 0;
return EVP_MD_CTX_set_params(ctx->mdctx, params);
}
static const OSSL_PARAM *ecdsa_settable_ctx_md_params(void *vctx)
{
PROV_ECDSA_CTX *ctx = (PROV_ECDSA_CTX *)vctx;
if (ctx->md == NULL)
return 0;
return EVP_MD_settable_ctx_params(ctx->md);
}
const OSSL_DISPATCH ossl_ecdsa_signature_functions[] = {
{ OSSL_FUNC_SIGNATURE_NEWCTX, (void (*)(void))ecdsa_newctx },
{ OSSL_FUNC_SIGNATURE_SIGN_INIT, (void (*)(void))ecdsa_sign_init },
{ OSSL_FUNC_SIGNATURE_SIGN, (void (*)(void))ecdsa_sign },
{ OSSL_FUNC_SIGNATURE_VERIFY_INIT, (void (*)(void))ecdsa_verify_init },
{ OSSL_FUNC_SIGNATURE_VERIFY, (void (*)(void))ecdsa_verify },
{ OSSL_FUNC_SIGNATURE_DIGEST_SIGN_INIT,
(void (*)(void))ecdsa_digest_sign_init },
{ OSSL_FUNC_SIGNATURE_DIGEST_SIGN_UPDATE,
(void (*)(void))ecdsa_digest_signverify_update },
{ OSSL_FUNC_SIGNATURE_DIGEST_SIGN_FINAL,
(void (*)(void))ecdsa_digest_sign_final },
{ OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_INIT,
(void (*)(void))ecdsa_digest_verify_init },
{ OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_UPDATE,
(void (*)(void))ecdsa_digest_signverify_update },
{ OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_FINAL,
(void (*)(void))ecdsa_digest_verify_final },
{ OSSL_FUNC_SIGNATURE_FREECTX, (void (*)(void))ecdsa_freectx },
{ OSSL_FUNC_SIGNATURE_DUPCTX, (void (*)(void))ecdsa_dupctx },
{ OSSL_FUNC_SIGNATURE_GET_CTX_PARAMS, (void (*)(void))ecdsa_get_ctx_params },
{ OSSL_FUNC_SIGNATURE_GETTABLE_CTX_PARAMS,
(void (*)(void))ecdsa_gettable_ctx_params },
{ OSSL_FUNC_SIGNATURE_SET_CTX_PARAMS, (void (*)(void))ecdsa_set_ctx_params },
{ OSSL_FUNC_SIGNATURE_SETTABLE_CTX_PARAMS,
(void (*)(void))ecdsa_settable_ctx_params },
{ OSSL_FUNC_SIGNATURE_GET_CTX_MD_PARAMS,
(void (*)(void))ecdsa_get_ctx_md_params },
{ OSSL_FUNC_SIGNATURE_GETTABLE_CTX_MD_PARAMS,
(void (*)(void))ecdsa_gettable_ctx_md_params },
{ OSSL_FUNC_SIGNATURE_SET_CTX_MD_PARAMS,
(void (*)(void))ecdsa_set_ctx_md_params },
{ OSSL_FUNC_SIGNATURE_SETTABLE_CTX_MD_PARAMS,
(void (*)(void))ecdsa_settable_ctx_md_params },
OSSL_DISPATCH_END
};
| 20,290 | 30.704688 | 82 | c |
openssl | openssl-master/providers/implementations/signature/mac_legacy_sig.c | /*
* Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* We need to use some engine deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/err.h>
#include <openssl/proverr.h>
#ifndef FIPS_MODULE
# include <openssl/engine.h>
#endif
#include "prov/implementations.h"
#include "prov/provider_ctx.h"
#include "prov/macsignature.h"
#include "prov/providercommon.h"
static OSSL_FUNC_signature_newctx_fn mac_hmac_newctx;
static OSSL_FUNC_signature_newctx_fn mac_siphash_newctx;
static OSSL_FUNC_signature_newctx_fn mac_poly1305_newctx;
static OSSL_FUNC_signature_newctx_fn mac_cmac_newctx;
static OSSL_FUNC_signature_digest_sign_init_fn mac_digest_sign_init;
static OSSL_FUNC_signature_digest_sign_update_fn mac_digest_sign_update;
static OSSL_FUNC_signature_digest_sign_final_fn mac_digest_sign_final;
static OSSL_FUNC_signature_freectx_fn mac_freectx;
static OSSL_FUNC_signature_dupctx_fn mac_dupctx;
static OSSL_FUNC_signature_set_ctx_params_fn mac_set_ctx_params;
static OSSL_FUNC_signature_settable_ctx_params_fn mac_hmac_settable_ctx_params;
static OSSL_FUNC_signature_settable_ctx_params_fn mac_siphash_settable_ctx_params;
static OSSL_FUNC_signature_settable_ctx_params_fn mac_poly1305_settable_ctx_params;
static OSSL_FUNC_signature_settable_ctx_params_fn mac_cmac_settable_ctx_params;
typedef struct {
OSSL_LIB_CTX *libctx;
char *propq;
MAC_KEY *key;
EVP_MAC_CTX *macctx;
} PROV_MAC_CTX;
static void *mac_newctx(void *provctx, const char *propq, const char *macname)
{
PROV_MAC_CTX *pmacctx;
EVP_MAC *mac = NULL;
if (!ossl_prov_is_running())
return NULL;
pmacctx = OPENSSL_zalloc(sizeof(PROV_MAC_CTX));
if (pmacctx == NULL)
return NULL;
pmacctx->libctx = PROV_LIBCTX_OF(provctx);
if (propq != NULL && (pmacctx->propq = OPENSSL_strdup(propq)) == NULL)
goto err;
mac = EVP_MAC_fetch(pmacctx->libctx, macname, propq);
if (mac == NULL)
goto err;
pmacctx->macctx = EVP_MAC_CTX_new(mac);
if (pmacctx->macctx == NULL)
goto err;
EVP_MAC_free(mac);
return pmacctx;
err:
OPENSSL_free(pmacctx->propq);
OPENSSL_free(pmacctx);
EVP_MAC_free(mac);
return NULL;
}
#define MAC_NEWCTX(funcname, macname) \
static void *mac_##funcname##_newctx(void *provctx, const char *propq) \
{ \
return mac_newctx(provctx, propq, macname); \
}
MAC_NEWCTX(hmac, "HMAC")
MAC_NEWCTX(siphash, "SIPHASH")
MAC_NEWCTX(poly1305, "POLY1305")
MAC_NEWCTX(cmac, "CMAC")
static int mac_digest_sign_init(void *vpmacctx, const char *mdname, void *vkey,
const OSSL_PARAM params[])
{
PROV_MAC_CTX *pmacctx = (PROV_MAC_CTX *)vpmacctx;
const char *ciphername = NULL, *engine = NULL;
if (!ossl_prov_is_running()
|| pmacctx == NULL)
return 0;
if (pmacctx->key == NULL && vkey == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_NO_KEY_SET);
return 0;
}
if (vkey != NULL) {
if (!ossl_mac_key_up_ref(vkey))
return 0;
ossl_mac_key_free(pmacctx->key);
pmacctx->key = vkey;
}
if (pmacctx->key->cipher.cipher != NULL)
ciphername = (char *)EVP_CIPHER_get0_name(pmacctx->key->cipher.cipher);
#if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
if (pmacctx->key->cipher.engine != NULL)
engine = (char *)ENGINE_get_id(pmacctx->key->cipher.engine);
#endif
if (!ossl_prov_set_macctx(pmacctx->macctx, NULL,
(char *)ciphername,
(char *)mdname,
(char *)engine,
pmacctx->key->properties,
NULL, 0))
return 0;
if (!EVP_MAC_init(pmacctx->macctx, pmacctx->key->priv_key,
pmacctx->key->priv_key_len, params))
return 0;
return 1;
}
int mac_digest_sign_update(void *vpmacctx, const unsigned char *data,
size_t datalen)
{
PROV_MAC_CTX *pmacctx = (PROV_MAC_CTX *)vpmacctx;
if (pmacctx == NULL || pmacctx->macctx == NULL)
return 0;
return EVP_MAC_update(pmacctx->macctx, data, datalen);
}
int mac_digest_sign_final(void *vpmacctx, unsigned char *mac, size_t *maclen,
size_t macsize)
{
PROV_MAC_CTX *pmacctx = (PROV_MAC_CTX *)vpmacctx;
if (!ossl_prov_is_running() || pmacctx == NULL || pmacctx->macctx == NULL)
return 0;
return EVP_MAC_final(pmacctx->macctx, mac, maclen, macsize);
}
static void mac_freectx(void *vpmacctx)
{
PROV_MAC_CTX *ctx = (PROV_MAC_CTX *)vpmacctx;
OPENSSL_free(ctx->propq);
EVP_MAC_CTX_free(ctx->macctx);
ossl_mac_key_free(ctx->key);
OPENSSL_free(ctx);
}
static void *mac_dupctx(void *vpmacctx)
{
PROV_MAC_CTX *srcctx = (PROV_MAC_CTX *)vpmacctx;
PROV_MAC_CTX *dstctx;
if (!ossl_prov_is_running())
return NULL;
dstctx = OPENSSL_zalloc(sizeof(*srcctx));
if (dstctx == NULL)
return NULL;
*dstctx = *srcctx;
dstctx->propq = NULL;
dstctx->key = NULL;
dstctx->macctx = NULL;
if (srcctx->propq != NULL && (dstctx->propq = OPENSSL_strdup(srcctx->propq)) == NULL)
goto err;
if (srcctx->key != NULL && !ossl_mac_key_up_ref(srcctx->key))
goto err;
dstctx->key = srcctx->key;
if (srcctx->macctx != NULL) {
dstctx->macctx = EVP_MAC_CTX_dup(srcctx->macctx);
if (dstctx->macctx == NULL)
goto err;
}
return dstctx;
err:
mac_freectx(dstctx);
return NULL;
}
static int mac_set_ctx_params(void *vpmacctx, const OSSL_PARAM params[])
{
PROV_MAC_CTX *ctx = (PROV_MAC_CTX *)vpmacctx;
return EVP_MAC_CTX_set_params(ctx->macctx, params);
}
static const OSSL_PARAM *mac_settable_ctx_params(ossl_unused void *ctx,
void *provctx,
const char *macname)
{
EVP_MAC *mac = EVP_MAC_fetch(PROV_LIBCTX_OF(provctx), macname,
NULL);
const OSSL_PARAM *params;
if (mac == NULL)
return NULL;
params = EVP_MAC_settable_ctx_params(mac);
EVP_MAC_free(mac);
return params;
}
#define MAC_SETTABLE_CTX_PARAMS(funcname, macname) \
static const OSSL_PARAM *mac_##funcname##_settable_ctx_params(void *ctx, \
void *provctx) \
{ \
return mac_settable_ctx_params(ctx, provctx, macname); \
}
MAC_SETTABLE_CTX_PARAMS(hmac, "HMAC")
MAC_SETTABLE_CTX_PARAMS(siphash, "SIPHASH")
MAC_SETTABLE_CTX_PARAMS(poly1305, "POLY1305")
MAC_SETTABLE_CTX_PARAMS(cmac, "CMAC")
#define MAC_SIGNATURE_FUNCTIONS(funcname) \
const OSSL_DISPATCH ossl_mac_legacy_##funcname##_signature_functions[] = { \
{ OSSL_FUNC_SIGNATURE_NEWCTX, (void (*)(void))mac_##funcname##_newctx }, \
{ OSSL_FUNC_SIGNATURE_DIGEST_SIGN_INIT, \
(void (*)(void))mac_digest_sign_init }, \
{ OSSL_FUNC_SIGNATURE_DIGEST_SIGN_UPDATE, \
(void (*)(void))mac_digest_sign_update }, \
{ OSSL_FUNC_SIGNATURE_DIGEST_SIGN_FINAL, \
(void (*)(void))mac_digest_sign_final }, \
{ OSSL_FUNC_SIGNATURE_FREECTX, (void (*)(void))mac_freectx }, \
{ OSSL_FUNC_SIGNATURE_DUPCTX, (void (*)(void))mac_dupctx }, \
{ OSSL_FUNC_SIGNATURE_SET_CTX_PARAMS, \
(void (*)(void))mac_set_ctx_params }, \
{ OSSL_FUNC_SIGNATURE_SETTABLE_CTX_PARAMS, \
(void (*)(void))mac_##funcname##_settable_ctx_params }, \
OSSL_DISPATCH_END \
};
MAC_SIGNATURE_FUNCTIONS(hmac)
MAC_SIGNATURE_FUNCTIONS(siphash)
MAC_SIGNATURE_FUNCTIONS(poly1305)
MAC_SIGNATURE_FUNCTIONS(cmac)
| 8,177 | 29.744361 | 89 | c |
openssl | openssl-master/providers/implementations/signature/sm2_sig.c | /*
* Copyright 2020-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* ECDSA low level APIs are deprecated for public use, but still ok for
* internal use - SM2 implementation uses ECDSA_size() function.
*/
#include "internal/deprecated.h"
#include <string.h> /* memcpy */
#include <openssl/crypto.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/dsa.h>
#include <openssl/params.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/proverr.h>
#include "internal/nelem.h"
#include "internal/sizes.h"
#include "internal/cryptlib.h"
#include "internal/sm3.h"
#include "prov/implementations.h"
#include "prov/providercommon.h"
#include "prov/provider_ctx.h"
#include "crypto/ec.h"
#include "crypto/sm2.h"
#include "prov/der_sm2.h"
static OSSL_FUNC_signature_newctx_fn sm2sig_newctx;
static OSSL_FUNC_signature_sign_init_fn sm2sig_signature_init;
static OSSL_FUNC_signature_verify_init_fn sm2sig_signature_init;
static OSSL_FUNC_signature_sign_fn sm2sig_sign;
static OSSL_FUNC_signature_verify_fn sm2sig_verify;
static OSSL_FUNC_signature_digest_sign_init_fn sm2sig_digest_signverify_init;
static OSSL_FUNC_signature_digest_sign_update_fn sm2sig_digest_signverify_update;
static OSSL_FUNC_signature_digest_sign_final_fn sm2sig_digest_sign_final;
static OSSL_FUNC_signature_digest_verify_init_fn sm2sig_digest_signverify_init;
static OSSL_FUNC_signature_digest_verify_update_fn sm2sig_digest_signverify_update;
static OSSL_FUNC_signature_digest_verify_final_fn sm2sig_digest_verify_final;
static OSSL_FUNC_signature_freectx_fn sm2sig_freectx;
static OSSL_FUNC_signature_dupctx_fn sm2sig_dupctx;
static OSSL_FUNC_signature_get_ctx_params_fn sm2sig_get_ctx_params;
static OSSL_FUNC_signature_gettable_ctx_params_fn sm2sig_gettable_ctx_params;
static OSSL_FUNC_signature_set_ctx_params_fn sm2sig_set_ctx_params;
static OSSL_FUNC_signature_settable_ctx_params_fn sm2sig_settable_ctx_params;
static OSSL_FUNC_signature_get_ctx_md_params_fn sm2sig_get_ctx_md_params;
static OSSL_FUNC_signature_gettable_ctx_md_params_fn sm2sig_gettable_ctx_md_params;
static OSSL_FUNC_signature_set_ctx_md_params_fn sm2sig_set_ctx_md_params;
static OSSL_FUNC_signature_settable_ctx_md_params_fn sm2sig_settable_ctx_md_params;
/*
* What's passed as an actual key is defined by the KEYMGMT interface.
* We happen to know that our KEYMGMT simply passes EC structures, so
* we use that here too.
*/
typedef struct {
OSSL_LIB_CTX *libctx;
char *propq;
EC_KEY *ec;
/*
* Flag to determine if the 'z' digest needs to be computed and fed to the
* hash function.
* This flag should be set on initialization and the computation should
* be performed only once, on first update.
*/
unsigned int flag_compute_z_digest : 1;
char mdname[OSSL_MAX_NAME_SIZE];
/* The Algorithm Identifier of the combined signature algorithm */
unsigned char aid_buf[OSSL_MAX_ALGORITHM_ID_SIZE];
unsigned char *aid;
size_t aid_len;
/* main digest */
EVP_MD *md;
EVP_MD_CTX *mdctx;
size_t mdsize;
/* SM2 ID used for calculating the Z value */
unsigned char *id;
size_t id_len;
} PROV_SM2_CTX;
static int sm2sig_set_mdname(PROV_SM2_CTX *psm2ctx, const char *mdname)
{
if (psm2ctx->md == NULL) /* We need an SM3 md to compare with */
psm2ctx->md = EVP_MD_fetch(psm2ctx->libctx, psm2ctx->mdname,
psm2ctx->propq);
if (psm2ctx->md == NULL)
return 0;
if (mdname == NULL)
return 1;
if (strlen(mdname) >= sizeof(psm2ctx->mdname)
|| !EVP_MD_is_a(psm2ctx->md, mdname)) {
ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_DIGEST, "digest=%s",
mdname);
return 0;
}
OPENSSL_strlcpy(psm2ctx->mdname, mdname, sizeof(psm2ctx->mdname));
return 1;
}
static void *sm2sig_newctx(void *provctx, const char *propq)
{
PROV_SM2_CTX *ctx = OPENSSL_zalloc(sizeof(PROV_SM2_CTX));
if (ctx == NULL)
return NULL;
ctx->libctx = PROV_LIBCTX_OF(provctx);
if (propq != NULL && (ctx->propq = OPENSSL_strdup(propq)) == NULL) {
OPENSSL_free(ctx);
return NULL;
}
ctx->mdsize = SM3_DIGEST_LENGTH;
strcpy(ctx->mdname, OSSL_DIGEST_NAME_SM3);
return ctx;
}
static int sm2sig_signature_init(void *vpsm2ctx, void *ec,
const OSSL_PARAM params[])
{
PROV_SM2_CTX *psm2ctx = (PROV_SM2_CTX *)vpsm2ctx;
if (!ossl_prov_is_running()
|| psm2ctx == NULL)
return 0;
if (ec == NULL && psm2ctx->ec == NULL) {
ERR_raise(ERR_LIB_PROV, PROV_R_NO_KEY_SET);
return 0;
}
if (ec != NULL) {
if (!EC_KEY_up_ref(ec))
return 0;
EC_KEY_free(psm2ctx->ec);
psm2ctx->ec = ec;
}
return sm2sig_set_ctx_params(psm2ctx, params);
}
static int sm2sig_sign(void *vpsm2ctx, unsigned char *sig, size_t *siglen,
size_t sigsize, const unsigned char *tbs, size_t tbslen)
{
PROV_SM2_CTX *ctx = (PROV_SM2_CTX *)vpsm2ctx;
int ret;
unsigned int sltmp;
/* SM2 uses ECDSA_size as well */
size_t ecsize = ECDSA_size(ctx->ec);
if (sig == NULL) {
*siglen = ecsize;
return 1;
}
if (sigsize < (size_t)ecsize)
return 0;
if (ctx->mdsize != 0 && tbslen != ctx->mdsize)
return 0;
ret = ossl_sm2_internal_sign(tbs, tbslen, sig, &sltmp, ctx->ec);
if (ret <= 0)
return 0;
*siglen = sltmp;
return 1;
}
static int sm2sig_verify(void *vpsm2ctx, const unsigned char *sig, size_t siglen,
const unsigned char *tbs, size_t tbslen)
{
PROV_SM2_CTX *ctx = (PROV_SM2_CTX *)vpsm2ctx;
if (ctx->mdsize != 0 && tbslen != ctx->mdsize)
return 0;
return ossl_sm2_internal_verify(tbs, tbslen, sig, siglen, ctx->ec);
}
static void free_md(PROV_SM2_CTX *ctx)
{
EVP_MD_CTX_free(ctx->mdctx);
EVP_MD_free(ctx->md);
ctx->mdctx = NULL;
ctx->md = NULL;
}
static int sm2sig_digest_signverify_init(void *vpsm2ctx, const char *mdname,
void *ec, const OSSL_PARAM params[])
{
PROV_SM2_CTX *ctx = (PROV_SM2_CTX *)vpsm2ctx;
int md_nid;
WPACKET pkt;
int ret = 0;
if (!sm2sig_signature_init(vpsm2ctx, ec, params)
|| !sm2sig_set_mdname(ctx, mdname))
return ret;
if (ctx->mdctx == NULL) {
ctx->mdctx = EVP_MD_CTX_new();
if (ctx->mdctx == NULL)
goto error;
}
md_nid = EVP_MD_get_type(ctx->md);
/*
* We do not care about DER writing errors.
* All it really means is that for some reason, there's no
* AlgorithmIdentifier to be had, but the operation itself is
* still valid, just as long as it's not used to construct
* anything that needs an AlgorithmIdentifier.
*/
ctx->aid_len = 0;
if (WPACKET_init_der(&pkt, ctx->aid_buf, sizeof(ctx->aid_buf))
&& ossl_DER_w_algorithmIdentifier_SM2_with_MD(&pkt, -1, ctx->ec, md_nid)
&& WPACKET_finish(&pkt)) {
WPACKET_get_total_written(&pkt, &ctx->aid_len);
ctx->aid = WPACKET_get_curr(&pkt);
}
WPACKET_cleanup(&pkt);
if (!EVP_DigestInit_ex2(ctx->mdctx, ctx->md, params))
goto error;
ctx->flag_compute_z_digest = 1;
ret = 1;
error:
return ret;
}
static int sm2sig_compute_z_digest(PROV_SM2_CTX *ctx)
{
uint8_t *z = NULL;
int ret = 1;
if (ctx->flag_compute_z_digest) {
/* Only do this once */
ctx->flag_compute_z_digest = 0;
if ((z = OPENSSL_zalloc(ctx->mdsize)) == NULL
/* get hashed prefix 'z' of tbs message */
|| !ossl_sm2_compute_z_digest(z, ctx->md, ctx->id, ctx->id_len,
ctx->ec)
|| !EVP_DigestUpdate(ctx->mdctx, z, ctx->mdsize))
ret = 0;
OPENSSL_free(z);
}
return ret;
}
int sm2sig_digest_signverify_update(void *vpsm2ctx, const unsigned char *data,
size_t datalen)
{
PROV_SM2_CTX *psm2ctx = (PROV_SM2_CTX *)vpsm2ctx;
if (psm2ctx == NULL || psm2ctx->mdctx == NULL)
return 0;
return sm2sig_compute_z_digest(psm2ctx)
&& EVP_DigestUpdate(psm2ctx->mdctx, data, datalen);
}
int sm2sig_digest_sign_final(void *vpsm2ctx, unsigned char *sig, size_t *siglen,
size_t sigsize)
{
PROV_SM2_CTX *psm2ctx = (PROV_SM2_CTX *)vpsm2ctx;
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int dlen = 0;
if (psm2ctx == NULL || psm2ctx->mdctx == NULL)
return 0;
/*
* If sig is NULL then we're just finding out the sig size. Other fields
* are ignored. Defer to sm2sig_sign.
*/
if (sig != NULL) {
if (!(sm2sig_compute_z_digest(psm2ctx)
&& EVP_DigestFinal_ex(psm2ctx->mdctx, digest, &dlen)))
return 0;
}
return sm2sig_sign(vpsm2ctx, sig, siglen, sigsize, digest, (size_t)dlen);
}
int sm2sig_digest_verify_final(void *vpsm2ctx, const unsigned char *sig,
size_t siglen)
{
PROV_SM2_CTX *psm2ctx = (PROV_SM2_CTX *)vpsm2ctx;
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int dlen = 0;
if (psm2ctx == NULL
|| psm2ctx->mdctx == NULL
|| EVP_MD_get_size(psm2ctx->md) > (int)sizeof(digest))
return 0;
if (!(sm2sig_compute_z_digest(psm2ctx)
&& EVP_DigestFinal_ex(psm2ctx->mdctx, digest, &dlen)))
return 0;
return sm2sig_verify(vpsm2ctx, sig, siglen, digest, (size_t)dlen);
}
static void sm2sig_freectx(void *vpsm2ctx)
{
PROV_SM2_CTX *ctx = (PROV_SM2_CTX *)vpsm2ctx;
free_md(ctx);
EC_KEY_free(ctx->ec);
OPENSSL_free(ctx->id);
OPENSSL_free(ctx);
}
static void *sm2sig_dupctx(void *vpsm2ctx)
{
PROV_SM2_CTX *srcctx = (PROV_SM2_CTX *)vpsm2ctx;
PROV_SM2_CTX *dstctx;
dstctx = OPENSSL_zalloc(sizeof(*srcctx));
if (dstctx == NULL)
return NULL;
*dstctx = *srcctx;
dstctx->ec = NULL;
dstctx->md = NULL;
dstctx->mdctx = NULL;
if (srcctx->ec != NULL && !EC_KEY_up_ref(srcctx->ec))
goto err;
dstctx->ec = srcctx->ec;
if (srcctx->md != NULL && !EVP_MD_up_ref(srcctx->md))
goto err;
dstctx->md = srcctx->md;
if (srcctx->mdctx != NULL) {
dstctx->mdctx = EVP_MD_CTX_new();
if (dstctx->mdctx == NULL
|| !EVP_MD_CTX_copy_ex(dstctx->mdctx, srcctx->mdctx))
goto err;
}
if (srcctx->id != NULL) {
dstctx->id = OPENSSL_malloc(srcctx->id_len);
if (dstctx->id == NULL)
goto err;
dstctx->id_len = srcctx->id_len;
memcpy(dstctx->id, srcctx->id, srcctx->id_len);
}
return dstctx;
err:
sm2sig_freectx(dstctx);
return NULL;
}
static int sm2sig_get_ctx_params(void *vpsm2ctx, OSSL_PARAM *params)
{
PROV_SM2_CTX *psm2ctx = (PROV_SM2_CTX *)vpsm2ctx;
OSSL_PARAM *p;
if (psm2ctx == NULL)
return 0;
p = OSSL_PARAM_locate(params, OSSL_SIGNATURE_PARAM_ALGORITHM_ID);
if (p != NULL
&& !OSSL_PARAM_set_octet_string(p, psm2ctx->aid, psm2ctx->aid_len))
return 0;
p = OSSL_PARAM_locate(params, OSSL_SIGNATURE_PARAM_DIGEST_SIZE);
if (p != NULL && !OSSL_PARAM_set_size_t(p, psm2ctx->mdsize))
return 0;
p = OSSL_PARAM_locate(params, OSSL_SIGNATURE_PARAM_DIGEST);
if (p != NULL && !OSSL_PARAM_set_utf8_string(p, psm2ctx->md == NULL
? psm2ctx->mdname
: EVP_MD_get0_name(psm2ctx->md)))
return 0;
return 1;
}
static const OSSL_PARAM known_gettable_ctx_params[] = {
OSSL_PARAM_octet_string(OSSL_SIGNATURE_PARAM_ALGORITHM_ID, NULL, 0),
OSSL_PARAM_size_t(OSSL_SIGNATURE_PARAM_DIGEST_SIZE, NULL),
OSSL_PARAM_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_END
};
static const OSSL_PARAM *sm2sig_gettable_ctx_params(ossl_unused void *vpsm2ctx,
ossl_unused void *provctx)
{
return known_gettable_ctx_params;
}
static int sm2sig_set_ctx_params(void *vpsm2ctx, const OSSL_PARAM params[])
{
PROV_SM2_CTX *psm2ctx = (PROV_SM2_CTX *)vpsm2ctx;
const OSSL_PARAM *p;
size_t mdsize;
if (psm2ctx == NULL)
return 0;
if (params == NULL)
return 1;
p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_DIST_ID);
if (p != NULL) {
void *tmp_id = NULL;
size_t tmp_idlen = 0;
/*
* If the 'z' digest has already been computed, the ID is set too late
*/
if (!psm2ctx->flag_compute_z_digest)
return 0;
if (p->data_size != 0
&& !OSSL_PARAM_get_octet_string(p, &tmp_id, 0, &tmp_idlen))
return 0;
OPENSSL_free(psm2ctx->id);
psm2ctx->id = tmp_id;
psm2ctx->id_len = tmp_idlen;
}
/*
* The following code checks that the size is the same as the SM3 digest
* size returning an error otherwise.
* If there is ever any different digest algorithm allowed with SM2
* this needs to be adjusted accordingly.
*/
p = OSSL_PARAM_locate_const(params, OSSL_SIGNATURE_PARAM_DIGEST_SIZE);
if (p != NULL && (!OSSL_PARAM_get_size_t(p, &mdsize)
|| mdsize != psm2ctx->mdsize))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_SIGNATURE_PARAM_DIGEST);
if (p != NULL) {
char *mdname = NULL;
if (!OSSL_PARAM_get_utf8_string(p, &mdname, 0))
return 0;
if (!sm2sig_set_mdname(psm2ctx, mdname)) {
OPENSSL_free(mdname);
return 0;
}
OPENSSL_free(mdname);
}
return 1;
}
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_size_t(OSSL_SIGNATURE_PARAM_DIGEST_SIZE, NULL),
OSSL_PARAM_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST, NULL, 0),
OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_DIST_ID, NULL, 0),
OSSL_PARAM_END
};
static const OSSL_PARAM *sm2sig_settable_ctx_params(ossl_unused void *vpsm2ctx,
ossl_unused void *provctx)
{
return known_settable_ctx_params;
}
static int sm2sig_get_ctx_md_params(void *vpsm2ctx, OSSL_PARAM *params)
{
PROV_SM2_CTX *psm2ctx = (PROV_SM2_CTX *)vpsm2ctx;
if (psm2ctx->mdctx == NULL)
return 0;
return EVP_MD_CTX_get_params(psm2ctx->mdctx, params);
}
static const OSSL_PARAM *sm2sig_gettable_ctx_md_params(void *vpsm2ctx)
{
PROV_SM2_CTX *psm2ctx = (PROV_SM2_CTX *)vpsm2ctx;
if (psm2ctx->md == NULL)
return 0;
return EVP_MD_gettable_ctx_params(psm2ctx->md);
}
static int sm2sig_set_ctx_md_params(void *vpsm2ctx, const OSSL_PARAM params[])
{
PROV_SM2_CTX *psm2ctx = (PROV_SM2_CTX *)vpsm2ctx;
if (psm2ctx->mdctx == NULL)
return 0;
return EVP_MD_CTX_set_params(psm2ctx->mdctx, params);
}
static const OSSL_PARAM *sm2sig_settable_ctx_md_params(void *vpsm2ctx)
{
PROV_SM2_CTX *psm2ctx = (PROV_SM2_CTX *)vpsm2ctx;
if (psm2ctx->md == NULL)
return 0;
return EVP_MD_settable_ctx_params(psm2ctx->md);
}
const OSSL_DISPATCH ossl_sm2_signature_functions[] = {
{ OSSL_FUNC_SIGNATURE_NEWCTX, (void (*)(void))sm2sig_newctx },
{ OSSL_FUNC_SIGNATURE_SIGN_INIT, (void (*)(void))sm2sig_signature_init },
{ OSSL_FUNC_SIGNATURE_SIGN, (void (*)(void))sm2sig_sign },
{ OSSL_FUNC_SIGNATURE_VERIFY_INIT, (void (*)(void))sm2sig_signature_init },
{ OSSL_FUNC_SIGNATURE_VERIFY, (void (*)(void))sm2sig_verify },
{ OSSL_FUNC_SIGNATURE_DIGEST_SIGN_INIT,
(void (*)(void))sm2sig_digest_signverify_init },
{ OSSL_FUNC_SIGNATURE_DIGEST_SIGN_UPDATE,
(void (*)(void))sm2sig_digest_signverify_update },
{ OSSL_FUNC_SIGNATURE_DIGEST_SIGN_FINAL,
(void (*)(void))sm2sig_digest_sign_final },
{ OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_INIT,
(void (*)(void))sm2sig_digest_signverify_init },
{ OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_UPDATE,
(void (*)(void))sm2sig_digest_signverify_update },
{ OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_FINAL,
(void (*)(void))sm2sig_digest_verify_final },
{ OSSL_FUNC_SIGNATURE_FREECTX, (void (*)(void))sm2sig_freectx },
{ OSSL_FUNC_SIGNATURE_DUPCTX, (void (*)(void))sm2sig_dupctx },
{ OSSL_FUNC_SIGNATURE_GET_CTX_PARAMS, (void (*)(void))sm2sig_get_ctx_params },
{ OSSL_FUNC_SIGNATURE_GETTABLE_CTX_PARAMS,
(void (*)(void))sm2sig_gettable_ctx_params },
{ OSSL_FUNC_SIGNATURE_SET_CTX_PARAMS, (void (*)(void))sm2sig_set_ctx_params },
{ OSSL_FUNC_SIGNATURE_SETTABLE_CTX_PARAMS,
(void (*)(void))sm2sig_settable_ctx_params },
{ OSSL_FUNC_SIGNATURE_GET_CTX_MD_PARAMS,
(void (*)(void))sm2sig_get_ctx_md_params },
{ OSSL_FUNC_SIGNATURE_GETTABLE_CTX_MD_PARAMS,
(void (*)(void))sm2sig_gettable_ctx_md_params },
{ OSSL_FUNC_SIGNATURE_SET_CTX_MD_PARAMS,
(void (*)(void))sm2sig_set_ctx_md_params },
{ OSSL_FUNC_SIGNATURE_SETTABLE_CTX_MD_PARAMS,
(void (*)(void))sm2sig_settable_ctx_md_params },
OSSL_DISPATCH_END
};
| 17,476 | 29.987589 | 85 | c |
openssl | openssl-master/providers/implementations/storemgmt/file_store.c | /*
* Copyright 2020-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* This file has quite some overlap with engines/e_loader_attic.c */
#include <string.h>
#include <sys/stat.h>
#include <ctype.h> /* isdigit */
#include <assert.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/core_object.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/params.h>
#include <openssl/decoder.h>
#include <openssl/proverr.h>
#include <openssl/store.h> /* The OSSL_STORE_INFO type numbers */
#include "internal/cryptlib.h"
#include "internal/o_dir.h"
#include "crypto/decoder.h"
#include "crypto/ctype.h" /* ossl_isdigit() */
#include "prov/implementations.h"
#include "prov/bio.h"
#include "file_store_local.h"
DEFINE_STACK_OF(OSSL_STORE_INFO)
#ifdef _WIN32
# define stat _stat
#endif
#ifndef S_ISDIR
# define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
#endif
static OSSL_FUNC_store_open_fn file_open;
static OSSL_FUNC_store_attach_fn file_attach;
static OSSL_FUNC_store_settable_ctx_params_fn file_settable_ctx_params;
static OSSL_FUNC_store_set_ctx_params_fn file_set_ctx_params;
static OSSL_FUNC_store_load_fn file_load;
static OSSL_FUNC_store_eof_fn file_eof;
static OSSL_FUNC_store_close_fn file_close;
/*
* This implementation makes full use of OSSL_DECODER, and then some.
* It uses its own internal decoder implementation that reads DER and
* passes that on to the data callback; this decoder is created with
* internal OpenSSL functions, thereby bypassing the need for a surrounding
* provider. This is ok, since this is a local decoder, not meant for
* public consumption.
* Finally, it sets up its own construct and cleanup functions.
*
* Essentially, that makes this implementation a kind of glorified decoder.
*/
struct file_ctx_st {
void *provctx;
char *uri; /* The URI we currently try to load */
enum {
IS_FILE = 0, /* Read file and pass results */
IS_DIR /* Pass directory entry names */
} type;
union {
/* Used with |IS_FILE| */
struct {
BIO *file;
OSSL_DECODER_CTX *decoderctx;
char *input_type;
char *propq; /* The properties we got as a parameter */
} file;
/* Used with |IS_DIR| */
struct {
OPENSSL_DIR_CTX *ctx;
int end_reached;
/*
* When a search expression is given, these are filled in.
* |search_name| contains the file basename to look for.
* The string is exactly 8 characters long.
*/
char search_name[9];
/*
* The directory reading utility we have combines opening with
* reading the first name. To make sure we can detect the end
* at the right time, we read early and cache the name.
*/
const char *last_entry;
int last_errno;
} dir;
} _;
/* Expected object type. May be unspecified */
int expected_type;
};
static void free_file_ctx(struct file_ctx_st *ctx)
{
if (ctx == NULL)
return;
OPENSSL_free(ctx->uri);
if (ctx->type != IS_DIR) {
OSSL_DECODER_CTX_free(ctx->_.file.decoderctx);
OPENSSL_free(ctx->_.file.propq);
OPENSSL_free(ctx->_.file.input_type);
}
OPENSSL_free(ctx);
}
static struct file_ctx_st *new_file_ctx(int type, const char *uri,
void *provctx)
{
struct file_ctx_st *ctx = NULL;
if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) != NULL
&& (uri == NULL || (ctx->uri = OPENSSL_strdup(uri)) != NULL)) {
ctx->type = type;
ctx->provctx = provctx;
return ctx;
}
free_file_ctx(ctx);
return NULL;
}
static OSSL_DECODER_CONSTRUCT file_load_construct;
static OSSL_DECODER_CLEANUP file_load_cleanup;
/*-
* Opening / attaching streams and directories
* -------------------------------------------
*/
/*
* Function to service both file_open() and file_attach()
*
*
*/
static struct file_ctx_st *file_open_stream(BIO *source, const char *uri,
void *provctx)
{
struct file_ctx_st *ctx;
if ((ctx = new_file_ctx(IS_FILE, uri, provctx)) == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_PROV_LIB);
goto err;
}
ctx->_.file.file = source;
return ctx;
err:
free_file_ctx(ctx);
return NULL;
}
static void *file_open_dir(const char *path, const char *uri, void *provctx)
{
struct file_ctx_st *ctx;
if ((ctx = new_file_ctx(IS_DIR, uri, provctx)) == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_PROV_LIB);
return NULL;
}
ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
ctx->_.dir.last_errno = errno;
if (ctx->_.dir.last_entry == NULL) {
if (ctx->_.dir.last_errno != 0) {
ERR_raise_data(ERR_LIB_SYS, ctx->_.dir.last_errno,
"Calling OPENSSL_DIR_read(\"%s\")", path);
goto err;
}
ctx->_.dir.end_reached = 1;
}
return ctx;
err:
file_close(ctx);
return NULL;
}
static void *file_open(void *provctx, const char *uri)
{
struct file_ctx_st *ctx = NULL;
struct stat st;
struct {
const char *path;
unsigned int check_absolute:1;
} path_data[2];
size_t path_data_n = 0, i;
const char *path, *p = uri, *q;
BIO *bio;
ERR_set_mark();
/*
* First step, just take the URI as is.
*/
path_data[path_data_n].check_absolute = 0;
path_data[path_data_n++].path = uri;
/*
* Second step, if the URI appears to start with the "file" scheme,
* extract the path and make that the second path to check.
* There's a special case if the URI also contains an authority, then
* the full URI shouldn't be used as a path anywhere.
*/
if (CHECK_AND_SKIP_CASE_PREFIX(p, "file:")) {
q = p;
if (CHECK_AND_SKIP_CASE_PREFIX(q, "//")) {
path_data_n--; /* Invalidate using the full URI */
if (CHECK_AND_SKIP_CASE_PREFIX(q, "localhost/")
|| CHECK_AND_SKIP_CASE_PREFIX(q, "/")) {
p = q - 1;
} else {
ERR_clear_last_mark();
ERR_raise(ERR_LIB_PROV, PROV_R_URI_AUTHORITY_UNSUPPORTED);
return NULL;
}
}
path_data[path_data_n].check_absolute = 1;
#ifdef _WIN32
/* Windows "file:" URIs with a drive letter start with a '/' */
if (p[0] == '/' && p[2] == ':' && p[3] == '/') {
char c = tolower(p[1]);
if (c >= 'a' && c <= 'z') {
p++;
/* We know it's absolute, so no need to check */
path_data[path_data_n].check_absolute = 0;
}
}
#endif
path_data[path_data_n++].path = p;
}
for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) {
/*
* If the scheme "file" was an explicit part of the URI, the path must
* be absolute. So says RFC 8089
*/
if (path_data[i].check_absolute && path_data[i].path[0] != '/') {
ERR_clear_last_mark();
ERR_raise_data(ERR_LIB_PROV, PROV_R_PATH_MUST_BE_ABSOLUTE,
"Given path=%s", path_data[i].path);
return NULL;
}
if (stat(path_data[i].path, &st) < 0) {
ERR_raise_data(ERR_LIB_SYS, errno,
"calling stat(%s)",
path_data[i].path);
} else {
path = path_data[i].path;
}
}
if (path == NULL) {
ERR_clear_last_mark();
return NULL;
}
/* Successfully found a working path, clear possible collected errors */
ERR_pop_to_mark();
if (S_ISDIR(st.st_mode))
ctx = file_open_dir(path, uri, provctx);
else if ((bio = BIO_new_file(path, "rb")) == NULL
|| (ctx = file_open_stream(bio, uri, provctx)) == NULL)
BIO_free_all(bio);
return ctx;
}
void *file_attach(void *provctx, OSSL_CORE_BIO *cin)
{
struct file_ctx_st *ctx;
BIO *new_bio = ossl_bio_new_from_core_bio(provctx, cin);
if (new_bio == NULL)
return NULL;
ctx = file_open_stream(new_bio, NULL, provctx);
if (ctx == NULL)
BIO_free(new_bio);
return ctx;
}
/*-
* Setting parameters
* ------------------
*/
static const OSSL_PARAM *file_settable_ctx_params(void *provctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_utf8_string(OSSL_STORE_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_int(OSSL_STORE_PARAM_EXPECT, NULL),
OSSL_PARAM_octet_string(OSSL_STORE_PARAM_SUBJECT, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_STORE_PARAM_INPUT_TYPE, NULL, 0),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
static int file_set_ctx_params(void *loaderctx, const OSSL_PARAM params[])
{
struct file_ctx_st *ctx = loaderctx;
const OSSL_PARAM *p;
if (params == NULL)
return 1;
if (ctx->type != IS_DIR) {
/* these parameters are ignored for directories */
p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_PROPERTIES);
if (p != NULL) {
OPENSSL_free(ctx->_.file.propq);
ctx->_.file.propq = NULL;
if (!OSSL_PARAM_get_utf8_string(p, &ctx->_.file.propq, 0))
return 0;
}
p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_INPUT_TYPE);
if (p != NULL) {
OPENSSL_free(ctx->_.file.input_type);
ctx->_.file.input_type = NULL;
if (!OSSL_PARAM_get_utf8_string(p, &ctx->_.file.input_type, 0))
return 0;
}
}
p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_EXPECT);
if (p != NULL && !OSSL_PARAM_get_int(p, &ctx->expected_type))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_SUBJECT);
if (p != NULL) {
const unsigned char *der = NULL;
size_t der_len = 0;
X509_NAME *x509_name;
unsigned long hash;
int ok;
if (ctx->type != IS_DIR) {
ERR_raise(ERR_LIB_PROV,
PROV_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES);
return 0;
}
if (!OSSL_PARAM_get_octet_string_ptr(p, (const void **)&der, &der_len)
|| (x509_name = d2i_X509_NAME(NULL, &der, der_len)) == NULL)
return 0;
hash = X509_NAME_hash_ex(x509_name,
ossl_prov_ctx_get0_libctx(ctx->provctx), NULL,
&ok);
BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
"%08lx", hash);
X509_NAME_free(x509_name);
if (ok == 0)
return 0;
}
return 1;
}
/*-
* Loading an object from a stream
* -------------------------------
*/
struct file_load_data_st {
OSSL_CALLBACK *object_cb;
void *object_cbarg;
};
static int file_load_construct(OSSL_DECODER_INSTANCE *decoder_inst,
const OSSL_PARAM *params, void *construct_data)
{
struct file_load_data_st *data = construct_data;
/*
* At some point, we may find it justifiable to recognise PKCS#12 and
* handle it specially here, making |file_load()| return pass its
* contents one piece at ta time, like |e_loader_attic.c| does.
*
* However, that currently means parsing them out, which converts the
* DER encoded PKCS#12 into a bunch of EVP_PKEYs and X509s, just to
* have to re-encode them into DER to create an object abstraction for
* each of them.
* It's much simpler (less churn) to pass on the object abstraction we
* get to the load_result callback and leave it to that one to do the
* work. If that's libcrypto code, we know that it has much better
* possibilities to handle the EVP_PKEYs and X509s without the extra
* churn.
*/
return data->object_cb(params, data->object_cbarg);
}
void file_load_cleanup(void *construct_data)
{
/* Nothing to do */
}
static int file_setup_decoders(struct file_ctx_st *ctx)
{
OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(ctx->provctx);
const OSSL_ALGORITHM *to_algo = NULL;
int ok = 0;
/* Setup for this session, so only if not already done */
if (ctx->_.file.decoderctx == NULL) {
if ((ctx->_.file.decoderctx = OSSL_DECODER_CTX_new()) == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
goto err;
}
/* Make sure the input type is set */
if (!OSSL_DECODER_CTX_set_input_type(ctx->_.file.decoderctx,
ctx->_.file.input_type)) {
ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
goto err;
}
/*
* Where applicable, set the outermost structure name.
* The goal is to avoid the STORE object types that are
* potentially password protected but aren't interesting
* for this load.
*/
switch (ctx->expected_type) {
case OSSL_STORE_INFO_CERT:
if (!OSSL_DECODER_CTX_set_input_structure(ctx->_.file.decoderctx,
"Certificate")) {
ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
goto err;
}
break;
case OSSL_STORE_INFO_CRL:
if (!OSSL_DECODER_CTX_set_input_structure(ctx->_.file.decoderctx,
"CertificateList")) {
ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
goto err;
}
break;
default:
break;
}
for (to_algo = ossl_any_to_obj_algorithm;
to_algo->algorithm_names != NULL;
to_algo++) {
OSSL_DECODER *to_obj = NULL;
OSSL_DECODER_INSTANCE *to_obj_inst = NULL;
/*
* Create the internal last resort decoder implementation
* together with a "decoder instance".
* The decoder doesn't need any identification or to be
* attached to any provider, since it's only used locally.
*/
to_obj = ossl_decoder_from_algorithm(0, to_algo, NULL);
if (to_obj != NULL)
to_obj_inst = ossl_decoder_instance_new(to_obj, ctx->provctx);
OSSL_DECODER_free(to_obj);
if (to_obj_inst == NULL)
goto err;
if (!ossl_decoder_ctx_add_decoder_inst(ctx->_.file.decoderctx,
to_obj_inst)) {
ossl_decoder_instance_free(to_obj_inst);
ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
goto err;
}
}
/* Add on the usual extra decoders */
if (!OSSL_DECODER_CTX_add_extra(ctx->_.file.decoderctx,
libctx, ctx->_.file.propq)) {
ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
goto err;
}
/*
* Then install our constructor hooks, which just passes decoded
* data to the load callback
*/
if (!OSSL_DECODER_CTX_set_construct(ctx->_.file.decoderctx,
file_load_construct)
|| !OSSL_DECODER_CTX_set_cleanup(ctx->_.file.decoderctx,
file_load_cleanup)) {
ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
goto err;
}
}
ok = 1;
err:
return ok;
}
static int file_load_file(struct file_ctx_st *ctx,
OSSL_CALLBACK *object_cb, void *object_cbarg,
OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
{
struct file_load_data_st data;
int ret, err;
/* Setup the decoders (one time shot per session */
if (!file_setup_decoders(ctx))
return 0;
/* Setup for this object */
data.object_cb = object_cb;
data.object_cbarg = object_cbarg;
OSSL_DECODER_CTX_set_construct_data(ctx->_.file.decoderctx, &data);
OSSL_DECODER_CTX_set_passphrase_cb(ctx->_.file.decoderctx, pw_cb, pw_cbarg);
/* Launch */
ERR_set_mark();
ret = OSSL_DECODER_from_bio(ctx->_.file.decoderctx, ctx->_.file.file);
if (BIO_eof(ctx->_.file.file)
&& ((err = ERR_peek_last_error()) != 0)
&& ERR_GET_LIB(err) == ERR_LIB_OSSL_DECODER
&& ERR_GET_REASON(err) == ERR_R_UNSUPPORTED)
ERR_pop_to_mark();
else
ERR_clear_last_mark();
return ret;
}
/*-
* Loading a name object from a directory
* --------------------------------------
*/
static char *file_name_to_uri(struct file_ctx_st *ctx, const char *name)
{
char *data = NULL;
assert(name != NULL);
{
const char *pathsep = ossl_ends_with_dirsep(ctx->uri) ? "" : "/";
long calculated_length = strlen(ctx->uri) + strlen(pathsep)
+ strlen(name) + 1 /* \0 */;
data = OPENSSL_zalloc(calculated_length);
if (data == NULL)
return NULL;
OPENSSL_strlcat(data, ctx->uri, calculated_length);
OPENSSL_strlcat(data, pathsep, calculated_length);
OPENSSL_strlcat(data, name, calculated_length);
}
return data;
}
static int file_name_check(struct file_ctx_st *ctx, const char *name)
{
const char *p = NULL;
size_t len = strlen(ctx->_.dir.search_name);
/* If there are no search criteria, all names are accepted */
if (ctx->_.dir.search_name[0] == '\0')
return 1;
/* If the expected type isn't supported, no name is accepted */
if (ctx->expected_type != 0
&& ctx->expected_type != OSSL_STORE_INFO_CERT
&& ctx->expected_type != OSSL_STORE_INFO_CRL)
return 0;
/*
* First, check the basename
*/
if (OPENSSL_strncasecmp(name, ctx->_.dir.search_name, len) != 0
|| name[len] != '.')
return 0;
p = &name[len + 1];
/*
* Then, if the expected type is a CRL, check that the extension starts
* with 'r'
*/
if (*p == 'r') {
p++;
if (ctx->expected_type != 0
&& ctx->expected_type != OSSL_STORE_INFO_CRL)
return 0;
} else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
return 0;
}
/*
* Last, check that the rest of the extension is a decimal number, at
* least one digit long.
*/
if (!isdigit((unsigned char)*p))
return 0;
while (isdigit((unsigned char)*p))
p++;
#ifdef __VMS
/*
* One extra step here, check for a possible generation number.
*/
if (*p == ';')
for (p++; *p != '\0'; p++)
if (!ossl_isdigit((unsigned char)*p))
break;
#endif
/*
* If we've reached the end of the string at this point, we've successfully
* found a fitting file name.
*/
return *p == '\0';
}
static int file_load_dir_entry(struct file_ctx_st *ctx,
OSSL_CALLBACK *object_cb, void *object_cbarg,
OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
{
/* Prepare as much as possible in advance */
static const int object_type = OSSL_OBJECT_NAME;
OSSL_PARAM object[] = {
OSSL_PARAM_int(OSSL_OBJECT_PARAM_TYPE, (int *)&object_type),
OSSL_PARAM_utf8_string(OSSL_OBJECT_PARAM_DATA, NULL, 0),
OSSL_PARAM_END
};
char *newname = NULL;
int ok;
/* Loop until we get an error or until we have a suitable name */
do {
if (ctx->_.dir.last_entry == NULL) {
if (!ctx->_.dir.end_reached) {
assert(ctx->_.dir.last_errno != 0);
ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
}
/* file_eof() will tell if EOF was reached */
return 0;
}
/* flag acceptable names */
if (ctx->_.dir.last_entry[0] != '.'
&& file_name_check(ctx, ctx->_.dir.last_entry)) {
/* If we can't allocate the new name, we fail */
if ((newname =
file_name_to_uri(ctx, ctx->_.dir.last_entry)) == NULL)
return 0;
}
/*
* On the first call (with a NULL context), OPENSSL_DIR_read()
* cares about the second argument. On the following calls, it
* only cares that it isn't NULL. Therefore, we can safely give
* it our URI here.
*/
ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, ctx->uri);
ctx->_.dir.last_errno = errno;
if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
ctx->_.dir.end_reached = 1;
} while (newname == NULL);
object[1].data = newname;
object[1].data_size = strlen(newname);
ok = object_cb(object, object_cbarg);
OPENSSL_free(newname);
return ok;
}
/*-
* Loading, local dispatcher
* -------------------------
*/
static int file_load(void *loaderctx,
OSSL_CALLBACK *object_cb, void *object_cbarg,
OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
{
struct file_ctx_st *ctx = loaderctx;
switch (ctx->type) {
case IS_FILE:
return file_load_file(ctx, object_cb, object_cbarg, pw_cb, pw_cbarg);
case IS_DIR:
return
file_load_dir_entry(ctx, object_cb, object_cbarg, pw_cb, pw_cbarg);
default:
break;
}
/* ctx->type has an unexpected value */
assert(0);
return 0;
}
/*-
* Eof detection and closing
* -------------------------
*/
static int file_eof(void *loaderctx)
{
struct file_ctx_st *ctx = loaderctx;
switch (ctx->type) {
case IS_DIR:
return ctx->_.dir.end_reached;
case IS_FILE:
/*
* BIO_pending() checks any filter BIO.
* BIO_eof() checks the source BIO.
*/
return !BIO_pending(ctx->_.file.file)
&& BIO_eof(ctx->_.file.file);
}
/* ctx->type has an unexpected value */
assert(0);
return 1;
}
static int file_close_dir(struct file_ctx_st *ctx)
{
if (ctx->_.dir.ctx != NULL)
OPENSSL_DIR_end(&ctx->_.dir.ctx);
free_file_ctx(ctx);
return 1;
}
static int file_close_stream(struct file_ctx_st *ctx)
{
/*
* This frees either the provider BIO filter (for file_attach()) OR
* the allocated file BIO (for file_open()).
*/
BIO_free(ctx->_.file.file);
ctx->_.file.file = NULL;
free_file_ctx(ctx);
return 1;
}
static int file_close(void *loaderctx)
{
struct file_ctx_st *ctx = loaderctx;
switch (ctx->type) {
case IS_DIR:
return file_close_dir(ctx);
case IS_FILE:
return file_close_stream(ctx);
}
/* ctx->type has an unexpected value */
assert(0);
return 1;
}
const OSSL_DISPATCH ossl_file_store_functions[] = {
{ OSSL_FUNC_STORE_OPEN, (void (*)(void))file_open },
{ OSSL_FUNC_STORE_ATTACH, (void (*)(void))file_attach },
{ OSSL_FUNC_STORE_SETTABLE_CTX_PARAMS,
(void (*)(void))file_settable_ctx_params },
{ OSSL_FUNC_STORE_SET_CTX_PARAMS, (void (*)(void))file_set_ctx_params },
{ OSSL_FUNC_STORE_LOAD, (void (*)(void))file_load },
{ OSSL_FUNC_STORE_EOF, (void (*)(void))file_eof },
{ OSSL_FUNC_STORE_CLOSE, (void (*)(void))file_close },
OSSL_DISPATCH_END,
};
| 23,944 | 29.503185 | 80 | c |
openssl | openssl-master/providers/implementations/storemgmt/file_store_any2obj.c | /*
* Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* This is a decoder that's completely internal to the 'file:' store
* implementation. Only code in file_store.c know about this one. Because
* of this close relationship, we can cut certain corners, such as making
* assumptions about the "provider context", which is currently simply the
* provider context that the file_store.c code operates within.
*
* All this does is to read known binary encodings (currently: DER, MSBLOB,
* PVK) from the input if it can, and passes it on to the data callback as
* an object abstraction, leaving it to the callback to figure out what it
* actually is.
*
* This MUST be made the last decoder in a chain, leaving it to other more
* specialized decoders to recognise and process their stuff first.
*/
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/core_object.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <openssl/err.h>
#include <openssl/asn1err.h>
#include <openssl/params.h>
#include "internal/asn1.h"
#include "crypto/pem.h" /* For internal PVK and "blob" headers */
#include "prov/bio.h"
#include "file_store_local.h"
/*
* newctx and freectx are not strictly necessary. However, the method creator,
* ossl_decoder_from_algorithm(), demands that they exist, so we make sure to
* oblige.
*/
static OSSL_FUNC_decoder_newctx_fn any2obj_newctx;
static OSSL_FUNC_decoder_freectx_fn any2obj_freectx;
static void *any2obj_newctx(void *provctx)
{
return provctx;
}
static void any2obj_freectx(void *vctx)
{
}
static int any2obj_decode_final(void *provctx, int objtype, BUF_MEM *mem,
OSSL_CALLBACK *data_cb, void *data_cbarg)
{
/*
* 1 indicates that we successfully decoded something, or not at all.
* Ending up "empty handed" is not an error.
*/
int ok = 1;
if (mem != NULL) {
OSSL_PARAM params[3];
params[0] =
OSSL_PARAM_construct_int(OSSL_OBJECT_PARAM_TYPE, &objtype);
params[1] =
OSSL_PARAM_construct_octet_string(OSSL_OBJECT_PARAM_DATA,
mem->data, mem->length);
params[2] = OSSL_PARAM_construct_end();
ok = data_cb(params, data_cbarg);
BUF_MEM_free(mem);
}
return ok;
}
static OSSL_FUNC_decoder_decode_fn der2obj_decode;
static int der2obj_decode(void *provctx, OSSL_CORE_BIO *cin, int selection,
OSSL_CALLBACK *data_cb, void *data_cbarg,
OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
{
BIO *in = ossl_bio_new_from_core_bio(provctx, cin);
BUF_MEM *mem = NULL;
int ok;
if (in == NULL)
return 0;
ERR_set_mark();
ok = (asn1_d2i_read_bio(in, &mem) >= 0);
ERR_pop_to_mark();
if (!ok && mem != NULL) {
BUF_MEM_free(mem);
mem = NULL;
}
BIO_free(in);
/* any2obj_decode_final() frees |mem| for us */
return any2obj_decode_final(provctx, OSSL_OBJECT_UNKNOWN, mem,
data_cb, data_cbarg);
}
static OSSL_FUNC_decoder_decode_fn msblob2obj_decode;
static int msblob2obj_decode(void *provctx, OSSL_CORE_BIO *cin, int selection,
OSSL_CALLBACK *data_cb, void *data_cbarg,
OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
{
BIO *in = ossl_bio_new_from_core_bio(provctx, cin);
BUF_MEM *mem = NULL;
size_t mem_len = 0, mem_want;
const unsigned char *p;
unsigned int bitlen, magic;
int isdss = -1;
int ispub = -1;
int ok = 0;
if (in == NULL)
goto err;
mem_want = 16; /* The size of the MSBLOB header */
if ((mem = BUF_MEM_new()) == NULL
|| !BUF_MEM_grow(mem, mem_want)) {
ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
goto err;
}
ERR_set_mark();
ok = BIO_read(in, &mem->data[0], mem_want) == (int)mem_want;
mem_len += mem_want;
ERR_pop_to_mark();
if (!ok)
goto next;
ERR_set_mark();
p = (unsigned char *)&mem->data[0];
ok = ossl_do_blob_header(&p, 16, &magic, &bitlen, &isdss, &ispub) > 0;
ERR_pop_to_mark();
if (!ok)
goto next;
ok = 0;
mem_want = ossl_blob_length(bitlen, isdss, ispub);
if (!BUF_MEM_grow(mem, mem_len + mem_want)) {
ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
goto err;
}
ERR_set_mark();
ok = BIO_read(in, &mem->data[mem_len], mem_want) == (int)mem_want;
mem_len += mem_want;
ERR_pop_to_mark();
next:
/* Free resources we no longer need. */
BIO_free(in);
if (!ok && mem != NULL) {
BUF_MEM_free(mem);
mem = NULL;
}
/* any2obj_decode_final() frees |mem| for us */
return any2obj_decode_final(provctx, OSSL_OBJECT_PKEY, mem,
data_cb, data_cbarg);
err:
BIO_free(in);
BUF_MEM_free(mem);
return 0;
}
static OSSL_FUNC_decoder_decode_fn pvk2obj_decode;
static int pvk2obj_decode(void *provctx, OSSL_CORE_BIO *cin, int selection,
OSSL_CALLBACK *data_cb, void *data_cbarg,
OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
{
BIO *in = ossl_bio_new_from_core_bio(provctx, cin);
BUF_MEM *mem = NULL;
size_t mem_len = 0, mem_want;
const unsigned char *p;
unsigned int saltlen, keylen;
int ok = 0;
if (in == NULL)
goto err;
mem_want = 24; /* The size of the PVK header */
if ((mem = BUF_MEM_new()) == NULL
|| !BUF_MEM_grow(mem, mem_want)) {
ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
goto err;
}
ERR_set_mark();
ok = BIO_read(in, &mem->data[0], mem_want) == (int)mem_want;
mem_len += mem_want;
ERR_pop_to_mark();
if (!ok)
goto next;
ERR_set_mark();
p = (unsigned char *)&mem->data[0];
ok = ossl_do_PVK_header(&p, 24, 0, &saltlen, &keylen) > 0;
ERR_pop_to_mark();
if (!ok)
goto next;
ok = 0;
mem_want = saltlen + keylen;
if (!BUF_MEM_grow(mem, mem_len + mem_want)) {
ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
goto err;
}
ERR_set_mark();
ok = BIO_read(in, &mem->data[mem_len], mem_want) == (int)mem_want;
mem_len += mem_want;
ERR_pop_to_mark();
next:
/* Free resources we no longer need. */
BIO_free(in);
if (!ok && mem != NULL) {
BUF_MEM_free(mem);
mem = NULL;
}
/* any2obj_decode_final() frees |mem| for us */
return any2obj_decode_final(provctx, OSSL_OBJECT_PKEY, mem,
data_cb, data_cbarg);
err:
BIO_free(in);
BUF_MEM_free(mem);
return 0;
}
#define MAKE_DECODER(fromtype, objtype) \
static const OSSL_DISPATCH fromtype##_to_obj_decoder_functions[] = { \
{ OSSL_FUNC_DECODER_NEWCTX, (void (*)(void))any2obj_newctx }, \
{ OSSL_FUNC_DECODER_FREECTX, (void (*)(void))any2obj_freectx }, \
{ OSSL_FUNC_DECODER_DECODE, (void (*)(void))fromtype##2obj_decode }, \
OSSL_DISPATCH_END \
}
MAKE_DECODER(der, OSSL_OBJECT_UNKNOWN);
MAKE_DECODER(msblob, OSSL_OBJECT_PKEY);
MAKE_DECODER(pvk, OSSL_OBJECT_PKEY);
const OSSL_ALGORITHM ossl_any_to_obj_algorithm[] = {
{ "obj", "input=DER", der_to_obj_decoder_functions },
{ "obj", "input=MSBLOB", msblob_to_obj_decoder_functions },
{ "obj", "input=PVK", pvk_to_obj_decoder_functions },
{ NULL, }
};
| 7,876 | 29.064885 | 79 | c |
openssl | openssl-master/providers/implementations/storemgmt/winstore_store.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/store.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/core_object.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/params.h>
#include <openssl/decoder.h>
#include <openssl/proverr.h>
#include <openssl/store.h> /* The OSSL_STORE_INFO type numbers */
#include "internal/cryptlib.h"
#include "internal/o_dir.h"
#include "crypto/decoder.h"
#include "crypto/ctype.h" /* ossl_isdigit() */
#include "prov/implementations.h"
#include "prov/bio.h"
#include "file_store_local.h"
#ifdef __CYGWIN__
# include <windows.h>
#endif
#include <wincrypt.h>
enum {
STATE_IDLE,
STATE_READ,
STATE_EOF,
};
struct winstore_ctx_st {
void *provctx;
char *propq;
unsigned char *subject;
size_t subject_len;
HCERTSTORE win_store;
const CERT_CONTEXT *win_ctx;
int state;
OSSL_DECODER_CTX *dctx;
};
static void winstore_win_reset(struct winstore_ctx_st *ctx)
{
if (ctx->win_ctx != NULL) {
CertFreeCertificateContext(ctx->win_ctx);
ctx->win_ctx = NULL;
}
ctx->state = STATE_IDLE;
}
static void winstore_win_advance(struct winstore_ctx_st *ctx)
{
CERT_NAME_BLOB name = {0};
if (ctx->state == STATE_EOF)
return;
name.cbData = ctx->subject_len;
name.pbData = ctx->subject;
ctx->win_ctx = (name.cbData == 0 ? NULL :
CertFindCertificateInStore(ctx->win_store,
X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
0, CERT_FIND_SUBJECT_NAME,
&name, ctx->win_ctx));
ctx->state = (ctx->win_ctx == NULL) ? STATE_EOF : STATE_READ;
}
static void *winstore_open(void *provctx, const char *uri)
{
struct winstore_ctx_st *ctx = NULL;
if (!HAS_CASE_PREFIX(uri, "org.openssl.winstore:"))
return NULL;
ctx = OPENSSL_zalloc(sizeof(*ctx));
if (ctx == NULL)
return NULL;
ctx->provctx = provctx;
ctx->win_store = CertOpenSystemStoreW(0, L"ROOT");
if (ctx->win_store == NULL) {
OPENSSL_free(ctx);
return NULL;
}
winstore_win_reset(ctx);
return ctx;
}
static void *winstore_attach(void *provctx, OSSL_CORE_BIO *cin)
{
return NULL; /* not supported */
}
static const OSSL_PARAM *winstore_settable_ctx_params(void *loaderctx, const OSSL_PARAM params[])
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_octet_string(OSSL_STORE_PARAM_SUBJECT, NULL, 0),
OSSL_PARAM_utf8_string(OSSL_STORE_PARAM_PROPERTIES, NULL, 0),
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
static int winstore_set_ctx_params(void *loaderctx, const OSSL_PARAM params[])
{
struct winstore_ctx_st *ctx = loaderctx;
const OSSL_PARAM *p;
int do_reset = 0;
if (params == NULL)
return 1;
p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_PROPERTIES);
if (p != NULL) {
do_reset = 1;
OPENSSL_free(ctx->propq);
ctx->propq = NULL;
if (!OSSL_PARAM_get_utf8_string(p, &ctx->propq, 0))
return 0;
}
p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_SUBJECT);
if (p != NULL) {
const unsigned char *der = NULL;
size_t der_len = 0;
if (!OSSL_PARAM_get_octet_string_ptr(p, (const void **)&der, &der_len))
return 0;
do_reset = 1;
OPENSSL_free(ctx->subject);
ctx->subject = OPENSSL_malloc(der_len);
if (ctx->subject == NULL) {
ctx->subject_len = 0;
return 0;
}
ctx->subject_len = der_len;
memcpy(ctx->subject, der, der_len);
}
if (do_reset) {
winstore_win_reset(ctx);
winstore_win_advance(ctx);
}
return 1;
}
struct load_data_st {
OSSL_CALLBACK *object_cb;
void *object_cbarg;
};
static int load_construct(OSSL_DECODER_INSTANCE *decoder_inst,
const OSSL_PARAM *params, void *construct_data)
{
struct load_data_st *data = construct_data;
return data->object_cb(params, data->object_cbarg);
}
static void load_cleanup(void *construct_data)
{
/* No-op. */
}
static int setup_decoder(struct winstore_ctx_st *ctx)
{
OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(ctx->provctx);
const OSSL_ALGORITHM *to_algo = NULL;
if (ctx->dctx != NULL)
return 1;
ctx->dctx = OSSL_DECODER_CTX_new();
if (ctx->dctx == NULL) {
ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
return 0;
}
if (!OSSL_DECODER_CTX_set_input_type(ctx->dctx, "DER")) {
ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
goto err;
}
if (!OSSL_DECODER_CTX_set_input_structure(ctx->dctx, "Certificate")) {
ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
goto err;
}
for (to_algo = ossl_any_to_obj_algorithm;
to_algo->algorithm_names != NULL;
to_algo++) {
OSSL_DECODER *to_obj = NULL;
OSSL_DECODER_INSTANCE *to_obj_inst = NULL;
/*
* Create the internal last resort decoder implementation
* together with a "decoder instance".
* The decoder doesn't need any identification or to be
* attached to any provider, since it's only used locally.
*/
to_obj = ossl_decoder_from_algorithm(0, to_algo, NULL);
if (to_obj != NULL)
to_obj_inst = ossl_decoder_instance_new(to_obj, ctx->provctx);
OSSL_DECODER_free(to_obj);
if (to_obj_inst == NULL)
goto err;
if (!ossl_decoder_ctx_add_decoder_inst(ctx->dctx,
to_obj_inst)) {
ossl_decoder_instance_free(to_obj_inst);
ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
goto err;
}
}
if (!OSSL_DECODER_CTX_add_extra(ctx->dctx, libctx, ctx->propq)) {
ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
goto err;
}
if (!OSSL_DECODER_CTX_set_construct(ctx->dctx, load_construct)) {
ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
goto err;
}
if (!OSSL_DECODER_CTX_set_cleanup(ctx->dctx, load_cleanup)) {
ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
goto err;
}
return 1;
err:
OSSL_DECODER_CTX_free(ctx->dctx);
ctx->dctx = NULL;
return 0;
}
static int winstore_load_using(struct winstore_ctx_st *ctx,
OSSL_CALLBACK *object_cb, void *object_cbarg,
OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg,
const void *der, size_t der_len)
{
struct load_data_st data;
const unsigned char *der_ = der;
size_t der_len_ = der_len;
if (setup_decoder(ctx) == 0)
return 0;
data.object_cb = object_cb;
data.object_cbarg = object_cbarg;
OSSL_DECODER_CTX_set_construct_data(ctx->dctx, &data);
OSSL_DECODER_CTX_set_passphrase_cb(ctx->dctx, pw_cb, pw_cbarg);
if (OSSL_DECODER_from_data(ctx->dctx, &der_, &der_len_) == 0)
return 0;
return 1;
}
static int winstore_load(void *loaderctx,
OSSL_CALLBACK *object_cb, void *object_cbarg,
OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
{
int ret = 0;
struct winstore_ctx_st *ctx = loaderctx;
if (ctx->state != STATE_READ)
return 0;
ret = winstore_load_using(ctx, object_cb, object_cbarg, pw_cb, pw_cbarg,
ctx->win_ctx->pbCertEncoded,
ctx->win_ctx->cbCertEncoded);
if (ret == 1)
winstore_win_advance(ctx);
return ret;
}
static int winstore_eof(void *loaderctx)
{
struct winstore_ctx_st *ctx = loaderctx;
return ctx->state != STATE_READ;
}
static int winstore_close(void *loaderctx)
{
struct winstore_ctx_st *ctx = loaderctx;
winstore_win_reset(ctx);
CertCloseStore(ctx->win_store, 0);
OSSL_DECODER_CTX_free(ctx->dctx);
OPENSSL_free(ctx->propq);
OPENSSL_free(ctx->subject);
OPENSSL_free(ctx);
return 1;
}
const OSSL_DISPATCH ossl_winstore_store_functions[] = {
{ OSSL_FUNC_STORE_OPEN, (void (*)(void))winstore_open },
{ OSSL_FUNC_STORE_ATTACH, (void (*)(void))winstore_attach },
{ OSSL_FUNC_STORE_SETTABLE_CTX_PARAMS, (void (*)(void))winstore_settable_ctx_params },
{ OSSL_FUNC_STORE_SET_CTX_PARAMS, (void (*)(void))winstore_set_ctx_params },
{ OSSL_FUNC_STORE_LOAD, (void (*)(void))winstore_load },
{ OSSL_FUNC_STORE_EOF, (void (*)(void))winstore_eof },
{ OSSL_FUNC_STORE_CLOSE, (void (*)(void))winstore_close },
OSSL_DISPATCH_END,
};
| 9,179 | 26.818182 | 97 | c |
openssl | openssl-master/ssl/bio_ssl.c | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <openssl/crypto.h>
#include "internal/bio.h"
#include <openssl/err.h>
#include "ssl_local.h"
static int ssl_write(BIO *h, const char *buf, size_t size, size_t *written);
static int ssl_read(BIO *b, char *buf, size_t size, size_t *readbytes);
static int ssl_puts(BIO *h, const char *str);
static long ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2);
static int ssl_new(BIO *h);
static int ssl_free(BIO *data);
static long ssl_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp);
typedef struct bio_ssl_st {
SSL *ssl; /* The ssl handle :-) */
/* re-negotiate every time the total number of bytes is this size */
int num_renegotiates;
unsigned long renegotiate_count;
size_t byte_count;
unsigned long renegotiate_timeout;
unsigned long last_time;
} BIO_SSL;
static const BIO_METHOD methods_sslp = {
BIO_TYPE_SSL,
"ssl",
ssl_write,
NULL, /* ssl_write_old, */
ssl_read,
NULL, /* ssl_read_old, */
ssl_puts,
NULL, /* ssl_gets, */
ssl_ctrl,
ssl_new,
ssl_free,
ssl_callback_ctrl,
};
const BIO_METHOD *BIO_f_ssl(void)
{
return &methods_sslp;
}
static int ssl_new(BIO *bi)
{
BIO_SSL *bs = OPENSSL_zalloc(sizeof(*bs));
if (bs == NULL)
return 0;
BIO_set_init(bi, 0);
BIO_set_data(bi, bs);
/* Clear all flags */
BIO_clear_flags(bi, ~0);
return 1;
}
static int ssl_free(BIO *a)
{
BIO_SSL *bs;
if (a == NULL)
return 0;
bs = BIO_get_data(a);
if (BIO_get_shutdown(a)) {
if (bs->ssl != NULL)
SSL_shutdown(bs->ssl);
if (BIO_get_init(a))
SSL_free(bs->ssl);
BIO_clear_flags(a, ~0); /* Clear all flags */
BIO_set_init(a, 0);
}
OPENSSL_free(bs);
return 1;
}
static int ssl_read(BIO *b, char *buf, size_t size, size_t *readbytes)
{
int ret = 1;
BIO_SSL *sb;
SSL *ssl;
int retry_reason = 0;
int r = 0;
if (buf == NULL)
return 0;
sb = BIO_get_data(b);
ssl = sb->ssl;
BIO_clear_retry_flags(b);
ret = ssl_read_internal(ssl, buf, size, readbytes);
switch (SSL_get_error(ssl, ret)) {
case SSL_ERROR_NONE:
if (sb->renegotiate_count > 0) {
sb->byte_count += *readbytes;
if (sb->byte_count > sb->renegotiate_count) {
sb->byte_count = 0;
sb->num_renegotiates++;
SSL_renegotiate(ssl);
r = 1;
}
}
if ((sb->renegotiate_timeout > 0) && (!r)) {
unsigned long tm;
tm = (unsigned long)time(NULL);
if (tm > sb->last_time + sb->renegotiate_timeout) {
sb->last_time = tm;
sb->num_renegotiates++;
SSL_renegotiate(ssl);
}
}
break;
case SSL_ERROR_WANT_READ:
BIO_set_retry_read(b);
break;
case SSL_ERROR_WANT_WRITE:
BIO_set_retry_write(b);
break;
case SSL_ERROR_WANT_X509_LOOKUP:
BIO_set_retry_special(b);
retry_reason = BIO_RR_SSL_X509_LOOKUP;
break;
case SSL_ERROR_WANT_ACCEPT:
BIO_set_retry_special(b);
retry_reason = BIO_RR_ACCEPT;
break;
case SSL_ERROR_WANT_CONNECT:
BIO_set_retry_special(b);
retry_reason = BIO_RR_CONNECT;
break;
case SSL_ERROR_SYSCALL:
case SSL_ERROR_SSL:
case SSL_ERROR_ZERO_RETURN:
default:
break;
}
BIO_set_retry_reason(b, retry_reason);
return ret;
}
static int ssl_write(BIO *b, const char *buf, size_t size, size_t *written)
{
int ret, r = 0;
int retry_reason = 0;
SSL *ssl;
BIO_SSL *bs;
if (buf == NULL)
return 0;
bs = BIO_get_data(b);
ssl = bs->ssl;
BIO_clear_retry_flags(b);
ret = ssl_write_internal(ssl, buf, size, written);
switch (SSL_get_error(ssl, ret)) {
case SSL_ERROR_NONE:
if (bs->renegotiate_count > 0) {
bs->byte_count += *written;
if (bs->byte_count > bs->renegotiate_count) {
bs->byte_count = 0;
bs->num_renegotiates++;
SSL_renegotiate(ssl);
r = 1;
}
}
if ((bs->renegotiate_timeout > 0) && (!r)) {
unsigned long tm;
tm = (unsigned long)time(NULL);
if (tm > bs->last_time + bs->renegotiate_timeout) {
bs->last_time = tm;
bs->num_renegotiates++;
SSL_renegotiate(ssl);
}
}
break;
case SSL_ERROR_WANT_WRITE:
BIO_set_retry_write(b);
break;
case SSL_ERROR_WANT_READ:
BIO_set_retry_read(b);
break;
case SSL_ERROR_WANT_X509_LOOKUP:
BIO_set_retry_special(b);
retry_reason = BIO_RR_SSL_X509_LOOKUP;
break;
case SSL_ERROR_WANT_CONNECT:
BIO_set_retry_special(b);
retry_reason = BIO_RR_CONNECT;
case SSL_ERROR_SYSCALL:
case SSL_ERROR_SSL:
default:
break;
}
BIO_set_retry_reason(b, retry_reason);
return ret;
}
static long ssl_ctrl(BIO *b, int cmd, long num, void *ptr)
{
SSL **sslp, *ssl;
BIO_SSL *bs, *dbs;
BIO *dbio, *bio;
long ret = 1;
BIO *next;
SSL_CONNECTION *sc = NULL;
bs = BIO_get_data(b);
next = BIO_next(b);
ssl = bs->ssl;
if ((ssl == NULL
|| (sc = SSL_CONNECTION_FROM_SSL(ssl)) == NULL)
&& cmd != BIO_C_SET_SSL)
return 0;
/* TODO(QUIC): The rbio/wbio might be from QUIC_CONNECTION instead */
switch (cmd) {
case BIO_CTRL_RESET:
SSL_shutdown(ssl);
if (sc->handshake_func == ssl->method->ssl_connect)
SSL_set_connect_state(ssl);
else if (sc->handshake_func == ssl->method->ssl_accept)
SSL_set_accept_state(ssl);
if (!SSL_clear(ssl)) {
ret = 0;
break;
}
if (next != NULL)
ret = BIO_ctrl(next, cmd, num, ptr);
else if (sc->rbio != NULL)
ret = BIO_ctrl(sc->rbio, cmd, num, ptr);
else
ret = 1;
break;
case BIO_CTRL_INFO:
ret = 0;
break;
case BIO_C_SSL_MODE:
if (num) /* client mode */
SSL_set_connect_state(ssl);
else
SSL_set_accept_state(ssl);
break;
case BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT:
ret = bs->renegotiate_timeout;
if (num < 60)
num = 5;
bs->renegotiate_timeout = (unsigned long)num;
bs->last_time = (unsigned long)time(NULL);
break;
case BIO_C_SET_SSL_RENEGOTIATE_BYTES:
ret = bs->renegotiate_count;
if ((long)num >= 512)
bs->renegotiate_count = (unsigned long)num;
break;
case BIO_C_GET_SSL_NUM_RENEGOTIATES:
ret = bs->num_renegotiates;
break;
case BIO_C_SET_SSL:
if (ssl != NULL) {
ssl_free(b);
if (!ssl_new(b))
return 0;
bs = BIO_get_data(b);
}
BIO_set_shutdown(b, num);
ssl = (SSL *)ptr;
bs->ssl = ssl;
bio = SSL_get_rbio(ssl);
if (bio != NULL) {
if (next != NULL)
BIO_push(bio, next);
BIO_set_next(b, bio);
BIO_up_ref(bio);
}
BIO_set_init(b, 1);
break;
case BIO_C_GET_SSL:
if (ptr != NULL) {
sslp = (SSL **)ptr;
*sslp = ssl;
} else
ret = 0;
break;
case BIO_CTRL_GET_CLOSE:
ret = BIO_get_shutdown(b);
break;
case BIO_CTRL_SET_CLOSE:
BIO_set_shutdown(b, (int)num);
break;
case BIO_CTRL_WPENDING:
ret = BIO_ctrl(sc->wbio, cmd, num, ptr);
break;
case BIO_CTRL_PENDING:
ret = SSL_pending(ssl);
if (ret == 0)
ret = BIO_pending(sc->rbio);
break;
case BIO_CTRL_FLUSH:
BIO_clear_retry_flags(b);
ret = BIO_ctrl(sc->wbio, cmd, num, ptr);
BIO_copy_next_retry(b);
break;
case BIO_CTRL_PUSH:
if ((next != NULL) && (next != sc->rbio)) {
/*
* We are going to pass ownership of next to the SSL object...but
* we don't own a reference to pass yet - so up ref
*/
BIO_up_ref(next);
SSL_set_bio(ssl, next, next);
}
break;
case BIO_CTRL_POP:
/* Only detach if we are the BIO explicitly being popped */
if (b == ptr) {
/* This will clear the reference we obtained during push */
SSL_set_bio(ssl, NULL, NULL);
}
break;
case BIO_C_DO_STATE_MACHINE:
BIO_clear_retry_flags(b);
BIO_set_retry_reason(b, 0);
ret = (int)SSL_do_handshake(ssl);
switch (SSL_get_error(ssl, (int)ret)) {
case SSL_ERROR_WANT_READ:
BIO_set_flags(b, BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY);
break;
case SSL_ERROR_WANT_WRITE:
BIO_set_flags(b, BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY);
break;
case SSL_ERROR_WANT_CONNECT:
BIO_set_flags(b, BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY);
BIO_set_retry_reason(b, BIO_get_retry_reason(next));
break;
case SSL_ERROR_WANT_X509_LOOKUP:
BIO_set_retry_special(b);
BIO_set_retry_reason(b, BIO_RR_SSL_X509_LOOKUP);
break;
default:
break;
}
break;
case BIO_CTRL_DUP:
dbio = (BIO *)ptr;
dbs = BIO_get_data(dbio);
SSL_free(dbs->ssl);
dbs->ssl = SSL_dup(ssl);
dbs->num_renegotiates = bs->num_renegotiates;
dbs->renegotiate_count = bs->renegotiate_count;
dbs->byte_count = bs->byte_count;
dbs->renegotiate_timeout = bs->renegotiate_timeout;
dbs->last_time = bs->last_time;
ret = (dbs->ssl != NULL);
break;
case BIO_C_GET_FD:
ret = BIO_ctrl(sc->rbio, cmd, num, ptr);
break;
case BIO_CTRL_SET_CALLBACK:
ret = 0; /* use callback ctrl */
break;
case BIO_CTRL_GET_RPOLL_DESCRIPTOR:
if (!SSL_get_rpoll_descriptor(ssl, (BIO_POLL_DESCRIPTOR *)ptr))
ret = 0;
break;
case BIO_CTRL_GET_WPOLL_DESCRIPTOR:
if (!SSL_get_wpoll_descriptor(ssl, (BIO_POLL_DESCRIPTOR *)ptr))
ret = 0;
break;
default:
ret = BIO_ctrl(sc->rbio, cmd, num, ptr);
break;
}
return ret;
}
static long ssl_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp)
{
SSL *ssl;
BIO_SSL *bs;
long ret = 1;
bs = BIO_get_data(b);
ssl = bs->ssl;
switch (cmd) {
case BIO_CTRL_SET_CALLBACK:
ret = BIO_callback_ctrl(SSL_get_rbio(ssl), cmd, fp);
break;
default:
ret = 0;
break;
}
return ret;
}
static int ssl_puts(BIO *bp, const char *str)
{
int n, ret;
n = strlen(str);
ret = BIO_write(bp, str, n);
return ret;
}
BIO *BIO_new_buffer_ssl_connect(SSL_CTX *ctx)
{
#ifndef OPENSSL_NO_SOCK
BIO *ret = NULL, *buf = NULL, *ssl = NULL;
if ((buf = BIO_new(BIO_f_buffer())) == NULL)
return NULL;
if ((ssl = BIO_new_ssl_connect(ctx)) == NULL)
goto err;
if ((ret = BIO_push(buf, ssl)) == NULL)
goto err;
return ret;
err:
BIO_free(buf);
BIO_free(ssl);
#endif
return NULL;
}
BIO *BIO_new_ssl_connect(SSL_CTX *ctx)
{
#ifndef OPENSSL_NO_SOCK
BIO *ret = NULL, *con = NULL, *ssl = NULL;
if ((con = BIO_new(BIO_s_connect())) == NULL)
return NULL;
if ((ssl = BIO_new_ssl(ctx, 1)) == NULL)
goto err;
if ((ret = BIO_push(ssl, con)) == NULL)
goto err;
return ret;
err:
BIO_free(ssl);
BIO_free(con);
#endif
return NULL;
}
BIO *BIO_new_ssl(SSL_CTX *ctx, int client)
{
BIO *ret;
SSL *ssl;
if ((ret = BIO_new(BIO_f_ssl())) == NULL)
return NULL;
if ((ssl = SSL_new(ctx)) == NULL) {
BIO_free(ret);
return NULL;
}
if (client)
SSL_set_connect_state(ssl);
else
SSL_set_accept_state(ssl);
BIO_set_ssl(ret, ssl, BIO_CLOSE);
return ret;
}
int BIO_ssl_copy_session_id(BIO *t, BIO *f)
{
BIO_SSL *tdata, *fdata;
t = BIO_find_type(t, BIO_TYPE_SSL);
f = BIO_find_type(f, BIO_TYPE_SSL);
if ((t == NULL) || (f == NULL))
return 0;
tdata = BIO_get_data(t);
fdata = BIO_get_data(f);
if ((tdata->ssl == NULL) || (fdata->ssl == NULL))
return 0;
if (!SSL_copy_session_id(tdata->ssl, (fdata->ssl)))
return 0;
return 1;
}
void BIO_ssl_shutdown(BIO *b)
{
BIO_SSL *bdata;
for (; b != NULL; b = BIO_next(b)) {
if (BIO_method_type(b) != BIO_TYPE_SSL)
continue;
bdata = BIO_get_data(b);
if (bdata != NULL && bdata->ssl != NULL)
SSL_shutdown(bdata->ssl);
}
}
| 13,482 | 25.079304 | 77 | c |
openssl | openssl-master/ssl/d1_msg.c | /*
* Copyright 2005-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "ssl_local.h"
int dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, size_t len,
size_t *written)
{
int i;
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
if (sc == NULL)
return -1;
if (SSL_in_init(s) && !ossl_statem_get_in_handshake(sc)) {
i = sc->handshake_func(s);
if (i < 0)
return i;
if (i == 0) {
ERR_raise(ERR_LIB_SSL, SSL_R_SSL_HANDSHAKE_FAILURE);
return -1;
}
}
if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
ERR_raise(ERR_LIB_SSL, SSL_R_DTLS_MESSAGE_TOO_BIG);
return -1;
}
return dtls1_write_bytes(sc, type, buf_, len, written);
}
int dtls1_dispatch_alert(SSL *ssl)
{
int i, j;
void (*cb) (const SSL *ssl, int type, int val) = NULL;
unsigned char buf[DTLS1_AL_HEADER_LENGTH];
unsigned char *ptr = &buf[0];
size_t written;
SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
if (s == NULL)
return 0;
s->s3.alert_dispatch = SSL_ALERT_DISPATCH_NONE;
memset(buf, 0, sizeof(buf));
*ptr++ = s->s3.send_alert[0];
*ptr++ = s->s3.send_alert[1];
i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), &written);
if (i <= 0) {
s->s3.alert_dispatch = 1;
/* fprintf(stderr, "not done with alert\n"); */
} else {
(void)BIO_flush(s->wbio);
if (s->msg_callback)
s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3.send_alert,
2, ssl, s->msg_callback_arg);
if (s->info_callback != NULL)
cb = s->info_callback;
else if (ssl->ctx->info_callback != NULL)
cb = ssl->ctx->info_callback;
if (cb != NULL) {
j = (s->s3.send_alert[0] << 8) | s->s3.send_alert[1];
cb(ssl, SSL_CB_WRITE_ALERT, j);
}
}
return i;
}
| 2,249 | 27.125 | 78 | c |
openssl | openssl-master/ssl/d1_srtp.c | /*
* Copyright 2011-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* DTLS code by Eric Rescorla <[email protected]>
*
* Copyright (C) 2006, Network Resonance, Inc. Copyright (C) 2011, RTFM, Inc.
*/
#include <stdio.h>
#include <openssl/objects.h>
#include "ssl_local.h"
#include "quic/quic_local.h"
#ifndef OPENSSL_NO_SRTP
static SRTP_PROTECTION_PROFILE srtp_known_profiles[] = {
{
"SRTP_AES128_CM_SHA1_80",
SRTP_AES128_CM_SHA1_80,
},
{
"SRTP_AES128_CM_SHA1_32",
SRTP_AES128_CM_SHA1_32,
},
{
"SRTP_AEAD_AES_128_GCM",
SRTP_AEAD_AES_128_GCM,
},
{
"SRTP_AEAD_AES_256_GCM",
SRTP_AEAD_AES_256_GCM,
},
{
"SRTP_DOUBLE_AEAD_AES_128_GCM_AEAD_AES_128_GCM",
SRTP_DOUBLE_AEAD_AES_128_GCM_AEAD_AES_128_GCM,
},
{
"SRTP_DOUBLE_AEAD_AES_256_GCM_AEAD_AES_256_GCM",
SRTP_DOUBLE_AEAD_AES_256_GCM_AEAD_AES_256_GCM,
},
{
"SRTP_ARIA_128_CTR_HMAC_SHA1_80",
SRTP_ARIA_128_CTR_HMAC_SHA1_80,
},
{
"SRTP_ARIA_128_CTR_HMAC_SHA1_32",
SRTP_ARIA_128_CTR_HMAC_SHA1_32,
},
{
"SRTP_ARIA_256_CTR_HMAC_SHA1_80",
SRTP_ARIA_256_CTR_HMAC_SHA1_80,
},
{
"SRTP_ARIA_256_CTR_HMAC_SHA1_32",
SRTP_ARIA_256_CTR_HMAC_SHA1_32,
},
{
"SRTP_AEAD_ARIA_128_GCM",
SRTP_AEAD_ARIA_128_GCM,
},
{
"SRTP_AEAD_ARIA_256_GCM",
SRTP_AEAD_ARIA_256_GCM,
},
{0}
};
static int find_profile_by_name(char *profile_name,
SRTP_PROTECTION_PROFILE **pptr, size_t len)
{
SRTP_PROTECTION_PROFILE *p;
p = srtp_known_profiles;
while (p->name) {
if ((len == strlen(p->name))
&& strncmp(p->name, profile_name, len) == 0) {
*pptr = p;
return 0;
}
p++;
}
return 1;
}
static int ssl_ctx_make_profiles(const char *profiles_string,
STACK_OF(SRTP_PROTECTION_PROFILE) **out)
{
STACK_OF(SRTP_PROTECTION_PROFILE) *profiles;
char *col;
char *ptr = (char *)profiles_string;
SRTP_PROTECTION_PROFILE *p;
if ((profiles = sk_SRTP_PROTECTION_PROFILE_new_null()) == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_SRTP_COULD_NOT_ALLOCATE_PROFILES);
return 1;
}
do {
col = strchr(ptr, ':');
if (!find_profile_by_name(ptr, &p, col ? (size_t)(col - ptr)
: strlen(ptr))) {
if (sk_SRTP_PROTECTION_PROFILE_find(profiles, p) >= 0) {
ERR_raise(ERR_LIB_SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
goto err;
}
if (!sk_SRTP_PROTECTION_PROFILE_push(profiles, p)) {
ERR_raise(ERR_LIB_SSL, SSL_R_SRTP_COULD_NOT_ALLOCATE_PROFILES);
goto err;
}
} else {
ERR_raise(ERR_LIB_SSL, SSL_R_SRTP_UNKNOWN_PROTECTION_PROFILE);
goto err;
}
if (col)
ptr = col + 1;
} while (col);
sk_SRTP_PROTECTION_PROFILE_free(*out);
*out = profiles;
return 0;
err:
sk_SRTP_PROTECTION_PROFILE_free(profiles);
return 1;
}
int SSL_CTX_set_tlsext_use_srtp(SSL_CTX *ctx, const char *profiles)
{
if (IS_QUIC_METHOD(ctx->method))
return 1;
return ssl_ctx_make_profiles(profiles, &ctx->srtp_profiles);
}
int SSL_set_tlsext_use_srtp(SSL *s, const char *profiles)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
if (sc == NULL)
return 1;
return ssl_ctx_make_profiles(profiles, &sc->srtp_profiles);
}
STACK_OF(SRTP_PROTECTION_PROFILE) *SSL_get_srtp_profiles(SSL *s)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
if (sc != NULL) {
if (sc->srtp_profiles != NULL) {
return sc->srtp_profiles;
} else if ((s->ctx != NULL) && (s->ctx->srtp_profiles != NULL)) {
return s->ctx->srtp_profiles;
}
}
return NULL;
}
SRTP_PROTECTION_PROFILE *SSL_get_selected_srtp_profile(SSL *s)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
if (sc == NULL)
return 0;
return sc->srtp_profile;
}
#endif
| 4,443 | 23.152174 | 79 | c |
openssl | openssl-master/ssl/event_queue.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdlib.h>
#include "internal/event_queue.h"
#include "crypto/sparse_array.h"
#include "ssl_local.h"
struct ossl_event_queue_st {
PRIORITY_QUEUE_OF(OSSL_EVENT) *timed_events;
PRIORITY_QUEUE_OF(OSSL_EVENT) *now_events;
};
static int event_compare_times(const OSSL_EVENT *a, const OSSL_EVENT *b)
{
return ossl_time_compare(a->when, b->when);
}
static int event_compare_priority(const OSSL_EVENT *a, const OSSL_EVENT *b)
{
if (a->priority > b->priority)
return -1;
if (a->priority < b->priority)
return 1;
return 0;
}
OSSL_EVENT_QUEUE *ossl_event_queue_new(void)
{
OSSL_EVENT_QUEUE *r = OPENSSL_malloc(sizeof(*r));
if (r != NULL) {
r->timed_events = ossl_pqueue_OSSL_EVENT_new(&event_compare_times);
r->now_events = ossl_pqueue_OSSL_EVENT_new(&event_compare_priority);
if (r->timed_events == NULL || r->now_events == NULL) {
ossl_event_queue_free(r);
return NULL;
}
}
return r;
}
void ossl_event_free(OSSL_EVENT *event)
{
if (event != NULL) {
if (event->flag_dynamic)
OPENSSL_free(event);
else
event->queue = NULL;
}
}
static void event_queue_free(PRIORITY_QUEUE_OF(OSSL_EVENT) *queue)
{
OSSL_EVENT *e;
if (queue != NULL) {
while ((e = ossl_pqueue_OSSL_EVENT_pop(queue)) != NULL)
ossl_event_free(e);
ossl_pqueue_OSSL_EVENT_free(queue);
}
}
void ossl_event_queue_free(OSSL_EVENT_QUEUE *queue)
{
if (queue != NULL) {
event_queue_free(queue->now_events);
event_queue_free(queue->timed_events);
OPENSSL_free(queue);
}
}
static ossl_inline
int event_queue_add(OSSL_EVENT_QUEUE *queue, OSSL_EVENT *event)
{
PRIORITY_QUEUE_OF(OSSL_EVENT) *pq =
ossl_time_compare(event->when, ossl_time_now()) <= 0
? queue->now_events
: queue->timed_events;
if (ossl_pqueue_OSSL_EVENT_push(pq, event, &event->ref)) {
event->queue = pq;
return 1;
}
return 0;
}
static ossl_inline
void ossl_event_set(OSSL_EVENT *event, uint32_t type, uint32_t priority,
OSSL_TIME when, void *ctx,
void *payload, size_t payload_size)
{
event->type = type;
event->priority = priority;
event->when = when;
event->ctx = ctx;
event->payload = payload;
event->payload_size = payload_size;
}
OSSL_EVENT *ossl_event_queue_add_new(OSSL_EVENT_QUEUE *queue,
uint32_t type, uint32_t priority,
OSSL_TIME when, void *ctx,
void *payload, size_t payload_size)
{
OSSL_EVENT *e = OPENSSL_malloc(sizeof(*e));
if (e == NULL || queue == NULL)
return NULL;
ossl_event_set(e, type, priority, when, ctx, payload, payload_size);
e->flag_dynamic = 1;
if (event_queue_add(queue, e))
return e;
OPENSSL_free(e);
return NULL;
}
int ossl_event_queue_add(OSSL_EVENT_QUEUE *queue, OSSL_EVENT *event,
uint32_t type, uint32_t priority,
OSSL_TIME when, void *ctx,
void *payload, size_t payload_size)
{
if (event == NULL || queue == NULL)
return 0;
ossl_event_set(event, type, priority, when, ctx, payload, payload_size);
event->flag_dynamic = 0;
return event_queue_add(queue, event);
}
int ossl_event_queue_remove(OSSL_EVENT_QUEUE *queue, OSSL_EVENT *event)
{
if (event != NULL && event->queue != NULL) {
ossl_pqueue_OSSL_EVENT_remove(event->queue, event->ref);
event->queue = NULL;
}
return 1;
}
OSSL_TIME ossl_event_time_until(const OSSL_EVENT *event)
{
if (event == NULL)
return ossl_time_infinite();
return ossl_time_subtract(event->when, ossl_time_now());
}
OSSL_TIME ossl_event_queue_time_until_next(const OSSL_EVENT_QUEUE *queue)
{
if (queue == NULL)
return ossl_time_infinite();
if (ossl_pqueue_OSSL_EVENT_num(queue->now_events) > 0)
return ossl_time_zero();
return ossl_event_time_until(ossl_pqueue_OSSL_EVENT_peek(queue->timed_events));
}
int ossl_event_queue_postpone_until(OSSL_EVENT_QUEUE *queue,
OSSL_EVENT *event,
OSSL_TIME when)
{
if (ossl_event_queue_remove(queue, event)) {
event->when = when;
return event_queue_add(queue, event);
}
return 0;
}
int ossl_event_queue_get1_next_event(OSSL_EVENT_QUEUE *queue,
OSSL_EVENT **event)
{
OSSL_TIME now = ossl_time_now();
OSSL_EVENT *e;
/* Check for expired timer based events and convert them to now events */
while ((e = ossl_pqueue_OSSL_EVENT_peek(queue->timed_events)) != NULL
&& ossl_time_compare(e->when, now) <= 0) {
e = ossl_pqueue_OSSL_EVENT_pop(queue->timed_events);
if (!ossl_pqueue_OSSL_EVENT_push(queue->now_events, e, &e->ref)) {
e->queue = NULL;
return 0;
}
}
/*
* Get next event from the now queue.
* The pop returns NULL when there is none.
*/
*event = ossl_pqueue_OSSL_EVENT_pop(queue->now_events);
return 1;
}
| 5,603 | 27.738462 | 83 | c |
openssl | openssl-master/ssl/methods.c | /*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <openssl/macros.h>
#include <openssl/objects.h>
#include "ssl_local.h"
/*-
* TLS/SSLv3 methods
*/
IMPLEMENT_tls_meth_func(TLS_ANY_VERSION, 0, 0,
TLS_method,
ossl_statem_accept,
ossl_statem_connect, TLSv1_2_enc_data)
IMPLEMENT_tls_meth_func(TLS1_3_VERSION, 0, SSL_OP_NO_TLSv1_3,
tlsv1_3_method,
ossl_statem_accept,
ossl_statem_connect, TLSv1_3_enc_data)
#ifndef OPENSSL_NO_TLS1_2_METHOD
IMPLEMENT_tls_meth_func(TLS1_2_VERSION, 0, SSL_OP_NO_TLSv1_2,
tlsv1_2_method,
ossl_statem_accept,
ossl_statem_connect, TLSv1_2_enc_data)
#endif
#ifndef OPENSSL_NO_TLS1_1_METHOD
IMPLEMENT_tls_meth_func(TLS1_1_VERSION, SSL_METHOD_NO_SUITEB, SSL_OP_NO_TLSv1_1,
tlsv1_1_method,
ossl_statem_accept,
ossl_statem_connect, TLSv1_1_enc_data)
#endif
#ifndef OPENSSL_NO_TLS1_METHOD
IMPLEMENT_tls_meth_func(TLS1_VERSION, SSL_METHOD_NO_SUITEB, SSL_OP_NO_TLSv1,
tlsv1_method,
ossl_statem_accept, ossl_statem_connect, TLSv1_enc_data)
#endif
#ifndef OPENSSL_NO_SSL3_METHOD
IMPLEMENT_ssl3_meth_func(sslv3_method, ossl_statem_accept, ossl_statem_connect)
#endif
/*-
* TLS/SSLv3 server methods
*/
IMPLEMENT_tls_meth_func(TLS_ANY_VERSION, 0, 0,
TLS_server_method,
ossl_statem_accept,
ssl_undefined_function, TLSv1_2_enc_data)
IMPLEMENT_tls_meth_func(TLS1_3_VERSION, 0, SSL_OP_NO_TLSv1_3,
tlsv1_3_server_method,
ossl_statem_accept,
ssl_undefined_function, TLSv1_3_enc_data)
#ifndef OPENSSL_NO_TLS1_2_METHOD
IMPLEMENT_tls_meth_func(TLS1_2_VERSION, 0, SSL_OP_NO_TLSv1_2,
tlsv1_2_server_method,
ossl_statem_accept,
ssl_undefined_function, TLSv1_2_enc_data)
#endif
#ifndef OPENSSL_NO_TLS1_1_METHOD
IMPLEMENT_tls_meth_func(TLS1_1_VERSION, SSL_METHOD_NO_SUITEB, SSL_OP_NO_TLSv1_1,
tlsv1_1_server_method,
ossl_statem_accept,
ssl_undefined_function, TLSv1_1_enc_data)
#endif
#ifndef OPENSSL_NO_TLS1_METHOD
IMPLEMENT_tls_meth_func(TLS1_VERSION, SSL_METHOD_NO_SUITEB, SSL_OP_NO_TLSv1,
tlsv1_server_method,
ossl_statem_accept,
ssl_undefined_function, TLSv1_enc_data)
#endif
#ifndef OPENSSL_NO_SSL3_METHOD
IMPLEMENT_ssl3_meth_func(sslv3_server_method,
ossl_statem_accept, ssl_undefined_function)
#endif
/*-
* TLS/SSLv3 client methods
*/
IMPLEMENT_tls_meth_func(TLS_ANY_VERSION, 0, 0,
TLS_client_method,
ssl_undefined_function,
ossl_statem_connect, TLSv1_2_enc_data)
IMPLEMENT_tls_meth_func(TLS1_3_VERSION, 0, SSL_OP_NO_TLSv1_3,
tlsv1_3_client_method,
ssl_undefined_function,
ossl_statem_connect, TLSv1_3_enc_data)
#ifndef OPENSSL_NO_TLS1_2_METHOD
IMPLEMENT_tls_meth_func(TLS1_2_VERSION, 0, SSL_OP_NO_TLSv1_2,
tlsv1_2_client_method,
ssl_undefined_function,
ossl_statem_connect, TLSv1_2_enc_data)
#endif
#ifndef OPENSSL_NO_TLS1_1_METHOD
IMPLEMENT_tls_meth_func(TLS1_1_VERSION, SSL_METHOD_NO_SUITEB, SSL_OP_NO_TLSv1_1,
tlsv1_1_client_method,
ssl_undefined_function,
ossl_statem_connect, TLSv1_1_enc_data)
#endif
#ifndef OPENSSL_NO_TLS1_METHOD
IMPLEMENT_tls_meth_func(TLS1_VERSION, SSL_METHOD_NO_SUITEB, SSL_OP_NO_TLSv1,
tlsv1_client_method,
ssl_undefined_function,
ossl_statem_connect, TLSv1_enc_data)
#endif
#ifndef OPENSSL_NO_SSL3_METHOD
IMPLEMENT_ssl3_meth_func(sslv3_client_method,
ssl_undefined_function, ossl_statem_connect)
#endif
/*-
* DTLS methods
*/
#ifndef OPENSSL_NO_DTLS1_METHOD
IMPLEMENT_dtls1_meth_func(DTLS1_VERSION, SSL_METHOD_NO_SUITEB, SSL_OP_NO_DTLSv1,
dtlsv1_method,
ossl_statem_accept,
ossl_statem_connect, DTLSv1_enc_data)
#endif
#ifndef OPENSSL_NO_DTLS1_2_METHOD
IMPLEMENT_dtls1_meth_func(DTLS1_2_VERSION, 0, SSL_OP_NO_DTLSv1_2,
dtlsv1_2_method,
ossl_statem_accept,
ossl_statem_connect, DTLSv1_2_enc_data)
#endif
IMPLEMENT_dtls1_meth_func(DTLS_ANY_VERSION, 0, 0,
DTLS_method,
ossl_statem_accept,
ossl_statem_connect, DTLSv1_2_enc_data)
/*-
* DTLS server methods
*/
#ifndef OPENSSL_NO_DTLS1_METHOD
IMPLEMENT_dtls1_meth_func(DTLS1_VERSION, SSL_METHOD_NO_SUITEB, SSL_OP_NO_DTLSv1,
dtlsv1_server_method,
ossl_statem_accept,
ssl_undefined_function, DTLSv1_enc_data)
#endif
#ifndef OPENSSL_NO_DTLS1_2_METHOD
IMPLEMENT_dtls1_meth_func(DTLS1_2_VERSION, 0, SSL_OP_NO_DTLSv1_2,
dtlsv1_2_server_method,
ossl_statem_accept,
ssl_undefined_function, DTLSv1_2_enc_data)
#endif
IMPLEMENT_dtls1_meth_func(DTLS_ANY_VERSION, 0, 0,
DTLS_server_method,
ossl_statem_accept,
ssl_undefined_function, DTLSv1_2_enc_data)
/*-
* DTLS client methods
*/
#ifndef OPENSSL_NO_DTLS1_METHOD
IMPLEMENT_dtls1_meth_func(DTLS1_VERSION, SSL_METHOD_NO_SUITEB, SSL_OP_NO_DTLSv1,
dtlsv1_client_method,
ssl_undefined_function,
ossl_statem_connect, DTLSv1_enc_data)
IMPLEMENT_dtls1_meth_func(DTLS1_BAD_VER, SSL_METHOD_NO_SUITEB, SSL_OP_NO_DTLSv1,
dtls_bad_ver_client_method,
ssl_undefined_function,
ossl_statem_connect, DTLSv1_enc_data)
#endif
#ifndef OPENSSL_NO_DTLS1_2_METHOD
IMPLEMENT_dtls1_meth_func(DTLS1_2_VERSION, 0, SSL_OP_NO_DTLSv1_2,
dtlsv1_2_client_method,
ssl_undefined_function,
ossl_statem_connect, DTLSv1_2_enc_data)
#endif
IMPLEMENT_dtls1_meth_func(DTLS_ANY_VERSION, 0, 0,
DTLS_client_method,
ssl_undefined_function,
ossl_statem_connect, DTLSv1_2_enc_data)
#ifndef OPENSSL_NO_DEPRECATED_1_1_0
# ifndef OPENSSL_NO_TLS1_2_METHOD
const SSL_METHOD *TLSv1_2_method(void)
{
return tlsv1_2_method();
}
const SSL_METHOD *TLSv1_2_server_method(void)
{
return tlsv1_2_server_method();
}
const SSL_METHOD *TLSv1_2_client_method(void)
{
return tlsv1_2_client_method();
}
# endif
# ifndef OPENSSL_NO_TLS1_1_METHOD
const SSL_METHOD *TLSv1_1_method(void)
{
return tlsv1_1_method();
}
const SSL_METHOD *TLSv1_1_server_method(void)
{
return tlsv1_1_server_method();
}
const SSL_METHOD *TLSv1_1_client_method(void)
{
return tlsv1_1_client_method();
}
# endif
# ifndef OPENSSL_NO_TLS1_METHOD
const SSL_METHOD *TLSv1_method(void)
{
return tlsv1_method();
}
const SSL_METHOD *TLSv1_server_method(void)
{
return tlsv1_server_method();
}
const SSL_METHOD *TLSv1_client_method(void)
{
return tlsv1_client_method();
}
# endif
# ifndef OPENSSL_NO_SSL3_METHOD
const SSL_METHOD *SSLv3_method(void)
{
return sslv3_method();
}
const SSL_METHOD *SSLv3_server_method(void)
{
return sslv3_server_method();
}
const SSL_METHOD *SSLv3_client_method(void)
{
return sslv3_client_method();
}
# endif
# ifndef OPENSSL_NO_DTLS1_2_METHOD
const SSL_METHOD *DTLSv1_2_method(void)
{
return dtlsv1_2_method();
}
const SSL_METHOD *DTLSv1_2_server_method(void)
{
return dtlsv1_2_server_method();
}
const SSL_METHOD *DTLSv1_2_client_method(void)
{
return dtlsv1_2_client_method();
}
# endif
# ifndef OPENSSL_NO_DTLS1_METHOD
const SSL_METHOD *DTLSv1_method(void)
{
return dtlsv1_method();
}
const SSL_METHOD *DTLSv1_server_method(void)
{
return dtlsv1_server_method();
}
const SSL_METHOD *DTLSv1_client_method(void)
{
return dtlsv1_client_method();
}
# endif
#endif
| 8,918 | 30.853571 | 80 | c |
openssl | openssl-master/ssl/priority_queue.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <assert.h>
#include "internal/priority_queue.h"
#include "internal/safe_math.h"
OSSL_SAFE_MATH_UNSIGNED(size_t, size_t)
/*
* Fundamental operations:
* Binary Heap Fibonacci Heap
* Get smallest O(1) O(1)
* Delete any O(log n) O(log n) average but worst O(n)
* Insert O(log n) O(1)
*
* Not supported:
* Merge two structures O(log n) O(1)
* Decrease key O(log n) O(1)
* Increase key O(log n) ?
*
* The Fibonacci heap is quite a bit more complicated to implement and has
* larger overhead in practice. We favour the binary heap here. A multi-way
* (ternary or quaternary) heap might elicit a performance advantage via better
* cache access patterns.
*/
struct pq_heap_st {
void *data; /* User supplied data pointer */
size_t index; /* Constant index in elements[] */
};
struct pq_elem_st {
size_t posn; /* Current index in heap[] or link in free list */
#ifndef NDEBUG
int used; /* Debug flag indicating that this is in use */
#endif
};
struct ossl_pqueue_st
{
struct pq_heap_st *heap;
struct pq_elem_st *elements;
int (*compare)(const void *, const void *);
size_t htop; /* Highest used heap element */
size_t hmax; /* Allocated heap & element space */
size_t freelist; /* Index into elements[], start of free element list */
};
/*
* The initial and maximum number of elements in the heap.
*/
static const size_t min_nodes = 8;
static const size_t max_nodes =
SIZE_MAX / (sizeof(struct pq_heap_st) > sizeof(struct pq_elem_st)
? sizeof(struct pq_heap_st) : sizeof(struct pq_elem_st));
#ifndef NDEBUG
/* Some basic sanity checking of the data structure */
# define ASSERT_USED(pq, idx) \
assert(pq->elements[pq->heap[idx].index].used); \
assert(pq->elements[pq->heap[idx].index].posn == idx)
# define ASSERT_ELEM_USED(pq, elem) \
assert(pq->elements[elem].used)
#else
# define ASSERT_USED(pq, idx)
# define ASSERT_ELEM_USED(pq, elem)
#endif
/*
* Calculate the array growth based on the target size.
*
* The growth factor is a rational number and is defined by a numerator
* and a denominator. According to Andrew Koenig in his paper "Why Are
* Vectors Efficient?" from JOOP 11(5) 1998, this factor should be less
* than the golden ratio (1.618...).
*
* We use an expansion factor of 8 / 5 = 1.6
*/
static ossl_inline size_t compute_pqueue_growth(size_t target, size_t current)
{
int err = 0;
while (current < target) {
if (current >= max_nodes)
return 0;
current = safe_muldiv_size_t(current, 8, 5, &err);
if (err)
return 0;
if (current >= max_nodes)
current = max_nodes;
}
return current;
}
static ossl_inline void pqueue_swap_elem(OSSL_PQUEUE *pq, size_t i, size_t j)
{
struct pq_heap_st *h = pq->heap, t_h;
struct pq_elem_st *e = pq->elements;
ASSERT_USED(pq, i);
ASSERT_USED(pq, j);
t_h = h[i];
h[i] = h[j];
h[j] = t_h;
e[h[i].index].posn = i;
e[h[j].index].posn = j;
}
static ossl_inline void pqueue_move_elem(OSSL_PQUEUE *pq, size_t from, size_t to)
{
struct pq_heap_st *h = pq->heap;
struct pq_elem_st *e = pq->elements;
ASSERT_USED(pq, from);
h[to] = h[from];
e[h[to].index].posn = to;
}
/*
* Force the specified element to the front of the heap. This breaks
* the heap partial ordering pre-condition.
*/
static ossl_inline void pqueue_force_bottom(OSSL_PQUEUE *pq, size_t n)
{
ASSERT_USED(pq, n);
while (n > 0) {
const size_t p = (n - 1) / 2;
ASSERT_USED(pq, p);
pqueue_swap_elem(pq, n, p);
n = p;
}
}
/*
* Move an element down to its correct position to restore the partial
* order pre-condition.
*/
static ossl_inline void pqueue_move_down(OSSL_PQUEUE *pq, size_t n)
{
struct pq_heap_st *h = pq->heap;
ASSERT_USED(pq, n);
while (n > 0) {
const size_t p = (n - 1) / 2;
ASSERT_USED(pq, p);
if (pq->compare(h[n].data, h[p].data) >= 0)
break;
pqueue_swap_elem(pq, n, p);
n = p;
}
}
/*
* Move an element up to its correct position to restore the partial
* order pre-condition.
*/
static ossl_inline void pqueue_move_up(OSSL_PQUEUE *pq, size_t n)
{
struct pq_heap_st *h = pq->heap;
size_t p = n * 2 + 1;
ASSERT_USED(pq, n);
if (pq->htop > p + 1) {
ASSERT_USED(pq, p);
ASSERT_USED(pq, p + 1);
if (pq->compare(h[p].data, h[p + 1].data) > 0)
p++;
}
while (pq->htop > p && pq->compare(h[p].data, h[n].data) < 0) {
ASSERT_USED(pq, p);
pqueue_swap_elem(pq, n, p);
n = p;
p = n * 2 + 1;
if (pq->htop > p + 1) {
ASSERT_USED(pq, p + 1);
if (pq->compare(h[p].data, h[p + 1].data) > 0)
p++;
}
}
}
int ossl_pqueue_push(OSSL_PQUEUE *pq, void *data, size_t *elem)
{
size_t n, m;
if (!ossl_pqueue_reserve(pq, 1))
return 0;
n = pq->htop++;
m = pq->freelist;
pq->freelist = pq->elements[m].posn;
pq->heap[n].data = data;
pq->heap[n].index = m;
pq->elements[m].posn = n;
#ifndef NDEBUG
pq->elements[m].used = 1;
#endif
pqueue_move_down(pq, n);
if (elem != NULL)
*elem = m;
return 1;
}
void *ossl_pqueue_peek(const OSSL_PQUEUE *pq)
{
if (pq->htop > 0) {
ASSERT_USED(pq, 0);
return pq->heap->data;
}
return NULL;
}
void *ossl_pqueue_pop(OSSL_PQUEUE *pq)
{
void *res;
size_t elem;
if (pq == NULL || pq->htop == 0)
return NULL;
ASSERT_USED(pq, 0);
res = pq->heap->data;
elem = pq->heap->index;
if (--pq->htop != 0) {
pqueue_move_elem(pq, pq->htop, 0);
pqueue_move_up(pq, 0);
}
pq->elements[elem].posn = pq->freelist;
pq->freelist = elem;
#ifndef NDEBUG
pq->elements[elem].used = 0;
#endif
return res;
}
void *ossl_pqueue_remove(OSSL_PQUEUE *pq, size_t elem)
{
size_t n;
if (pq == NULL || elem >= pq->hmax || pq->htop == 0)
return 0;
ASSERT_ELEM_USED(pq, elem);
n = pq->elements[elem].posn;
ASSERT_USED(pq, n);
if (n == pq->htop - 1)
return pq->heap[--pq->htop].data;
if (n > 0)
pqueue_force_bottom(pq, n);
return ossl_pqueue_pop(pq);
}
static void pqueue_add_freelist(OSSL_PQUEUE *pq, size_t from)
{
struct pq_elem_st *e = pq->elements;
size_t i;
#ifndef NDEBUG
for (i = from; i < pq->hmax; i++)
e[i].used = 0;
#endif
e[from].posn = pq->freelist;
for (i = from + 1; i < pq->hmax; i++)
e[i].posn = i - 1;
pq->freelist = pq->hmax - 1;
}
int ossl_pqueue_reserve(OSSL_PQUEUE *pq, size_t n)
{
size_t new_max, cur_max;
struct pq_heap_st *h;
struct pq_elem_st *e;
if (pq == NULL)
return 0;
cur_max = pq->hmax;
if (pq->htop + n < cur_max)
return 1;
new_max = compute_pqueue_growth(n + cur_max, cur_max);
if (new_max == 0) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return 0;
}
h = OPENSSL_realloc(pq->heap, new_max * sizeof(*pq->heap));
if (h == NULL)
return 0;
pq->heap = h;
e = OPENSSL_realloc(pq->elements, new_max * sizeof(*pq->elements));
if (e == NULL)
return 0;
pq->elements = e;
pq->hmax = new_max;
pqueue_add_freelist(pq, cur_max);
return 1;
}
OSSL_PQUEUE *ossl_pqueue_new(int (*compare)(const void *, const void *))
{
OSSL_PQUEUE *pq;
if (compare == NULL)
return NULL;
pq = OPENSSL_malloc(sizeof(*pq));
if (pq == NULL)
return NULL;
pq->compare = compare;
pq->hmax = min_nodes;
pq->htop = 0;
pq->freelist = 0;
pq->heap = OPENSSL_malloc(sizeof(*pq->heap) * min_nodes);
pq->elements = OPENSSL_malloc(sizeof(*pq->elements) * min_nodes);
if (pq->heap == NULL || pq->elements == NULL) {
ossl_pqueue_free(pq);
return NULL;
}
pqueue_add_freelist(pq, 0);
return pq;
}
void ossl_pqueue_free(OSSL_PQUEUE *pq)
{
if (pq != NULL) {
OPENSSL_free(pq->heap);
OPENSSL_free(pq->elements);
OPENSSL_free(pq);
}
}
void ossl_pqueue_pop_free(OSSL_PQUEUE *pq, void (*freefunc)(void *))
{
size_t i;
if (pq != NULL) {
for (i = 0; i < pq->htop; i++)
(*freefunc)(pq->heap[i].data);
ossl_pqueue_free(pq);
}
}
size_t ossl_pqueue_num(const OSSL_PQUEUE *pq)
{
return pq != NULL ? pq->htop : 0;
}
| 9,138 | 23.7 | 81 | c |
openssl | openssl-master/ssl/s3_enc.c | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright 2005 Nokia. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "ssl_local.h"
#include <openssl/evp.h>
#include <openssl/md5.h>
#include <openssl/core_names.h>
#include "internal/cryptlib.h"
static int ssl3_generate_key_block(SSL_CONNECTION *s, unsigned char *km, int num)
{
const EVP_MD *md5 = NULL, *sha1 = NULL;
EVP_MD_CTX *m5;
EVP_MD_CTX *s1;
unsigned char buf[16], smd[SHA_DIGEST_LENGTH];
unsigned char c = 'A';
unsigned int i, k;
int ret = 0;
SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
#ifdef CHARSET_EBCDIC
c = os_toascii[c]; /* 'A' in ASCII */
#endif
k = 0;
md5 = ssl_evp_md_fetch(sctx->libctx, NID_md5, sctx->propq);
sha1 = ssl_evp_md_fetch(sctx->libctx, NID_sha1, sctx->propq);
m5 = EVP_MD_CTX_new();
s1 = EVP_MD_CTX_new();
if (md5 == NULL || sha1 == NULL || m5 == NULL || s1 == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
goto err;
}
for (i = 0; (int)i < num; i += MD5_DIGEST_LENGTH) {
k++;
if (k > sizeof(buf)) {
/* bug: 'buf' is too small for this ciphersuite */
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
memset(buf, c, k);
c++;
if (!EVP_DigestInit_ex(s1, sha1, NULL)
|| !EVP_DigestUpdate(s1, buf, k)
|| !EVP_DigestUpdate(s1, s->session->master_key,
s->session->master_key_length)
|| !EVP_DigestUpdate(s1, s->s3.server_random, SSL3_RANDOM_SIZE)
|| !EVP_DigestUpdate(s1, s->s3.client_random, SSL3_RANDOM_SIZE)
|| !EVP_DigestFinal_ex(s1, smd, NULL)
|| !EVP_DigestInit_ex(m5, md5, NULL)
|| !EVP_DigestUpdate(m5, s->session->master_key,
s->session->master_key_length)
|| !EVP_DigestUpdate(m5, smd, SHA_DIGEST_LENGTH)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if ((int)(i + MD5_DIGEST_LENGTH) > num) {
if (!EVP_DigestFinal_ex(m5, smd, NULL)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
memcpy(km, smd, (num - i));
} else {
if (!EVP_DigestFinal_ex(m5, km, NULL)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
}
km += MD5_DIGEST_LENGTH;
}
OPENSSL_cleanse(smd, sizeof(smd));
ret = 1;
err:
EVP_MD_CTX_free(m5);
EVP_MD_CTX_free(s1);
ssl_evp_md_free(md5);
ssl_evp_md_free(sha1);
return ret;
}
int ssl3_change_cipher_state(SSL_CONNECTION *s, int which)
{
unsigned char *p, *mac_secret;
size_t md_len;
unsigned char *key, *iv;
const EVP_CIPHER *ciph;
const SSL_COMP *comp = NULL;
const EVP_MD *md;
int mdi;
size_t n, iv_len, key_len;
int direction = (which & SSL3_CC_READ) != 0 ? OSSL_RECORD_DIRECTION_READ
: OSSL_RECORD_DIRECTION_WRITE;
ciph = s->s3.tmp.new_sym_enc;
md = s->s3.tmp.new_hash;
/* m == NULL will lead to a crash later */
if (!ossl_assert(md != NULL)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
#ifndef OPENSSL_NO_COMP
comp = s->s3.tmp.new_compression;
#endif
p = s->s3.tmp.key_block;
mdi = EVP_MD_get_size(md);
if (mdi < 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
md_len = (size_t)mdi;
key_len = EVP_CIPHER_get_key_length(ciph);
iv_len = EVP_CIPHER_get_iv_length(ciph);
if ((which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
(which == SSL3_CHANGE_CIPHER_SERVER_READ)) {
mac_secret = &(p[0]);
n = md_len + md_len;
key = &(p[n]);
n += key_len + key_len;
iv = &(p[n]);
n += iv_len + iv_len;
} else {
n = md_len;
mac_secret = &(p[n]);
n += md_len + key_len;
key = &(p[n]);
n += key_len + iv_len;
iv = &(p[n]);
n += iv_len;
}
if (n > s->s3.tmp.key_block_length) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (!ssl_set_new_record_layer(s, SSL3_VERSION,
direction,
OSSL_RECORD_PROTECTION_LEVEL_APPLICATION,
NULL, 0, key, key_len, iv, iv_len, mac_secret,
md_len, ciph, 0, NID_undef, md, comp, NULL)) {
/* SSLfatal already called */
goto err;
}
return 1;
err:
return 0;
}
int ssl3_setup_key_block(SSL_CONNECTION *s)
{
unsigned char *p;
const EVP_CIPHER *c;
const EVP_MD *hash;
int num;
int ret = 0;
SSL_COMP *comp;
if (s->s3.tmp.key_block_length != 0)
return 1;
if (!ssl_cipher_get_evp(SSL_CONNECTION_GET_CTX(s), s->session, &c, &hash,
NULL, NULL, &comp, 0)) {
/* Error is already recorded */
SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
return 0;
}
ssl_evp_cipher_free(s->s3.tmp.new_sym_enc);
s->s3.tmp.new_sym_enc = c;
ssl_evp_md_free(s->s3.tmp.new_hash);
s->s3.tmp.new_hash = hash;
#ifdef OPENSSL_NO_COMP
s->s3.tmp.new_compression = NULL;
#else
s->s3.tmp.new_compression = comp;
#endif
num = EVP_MD_get_size(hash);
if (num < 0)
return 0;
num = EVP_CIPHER_get_key_length(c) + num + EVP_CIPHER_get_iv_length(c);
num *= 2;
ssl3_cleanup_key_block(s);
if ((p = OPENSSL_malloc(num)) == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
return 0;
}
s->s3.tmp.key_block_length = num;
s->s3.tmp.key_block = p;
/* Calls SSLfatal() as required */
ret = ssl3_generate_key_block(s, p, num);
return ret;
}
void ssl3_cleanup_key_block(SSL_CONNECTION *s)
{
OPENSSL_clear_free(s->s3.tmp.key_block, s->s3.tmp.key_block_length);
s->s3.tmp.key_block = NULL;
s->s3.tmp.key_block_length = 0;
}
int ssl3_init_finished_mac(SSL_CONNECTION *s)
{
BIO *buf = BIO_new(BIO_s_mem());
if (buf == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BIO_LIB);
return 0;
}
ssl3_free_digest_list(s);
s->s3.handshake_buffer = buf;
(void)BIO_set_close(s->s3.handshake_buffer, BIO_CLOSE);
return 1;
}
/*
* Free digest list. Also frees handshake buffer since they are always freed
* together.
*/
void ssl3_free_digest_list(SSL_CONNECTION *s)
{
BIO_free(s->s3.handshake_buffer);
s->s3.handshake_buffer = NULL;
EVP_MD_CTX_free(s->s3.handshake_dgst);
s->s3.handshake_dgst = NULL;
}
int ssl3_finish_mac(SSL_CONNECTION *s, const unsigned char *buf, size_t len)
{
int ret;
if (s->s3.handshake_dgst == NULL) {
/* Note: this writes to a memory BIO so a failure is a fatal error */
if (len > INT_MAX) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_OVERFLOW_ERROR);
return 0;
}
ret = BIO_write(s->s3.handshake_buffer, (void *)buf, (int)len);
if (ret <= 0 || ret != (int)len) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
} else {
ret = EVP_DigestUpdate(s->s3.handshake_dgst, buf, len);
if (!ret) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
return 1;
}
int ssl3_digest_cached_records(SSL_CONNECTION *s, int keep)
{
const EVP_MD *md;
long hdatalen;
void *hdata;
if (s->s3.handshake_dgst == NULL) {
hdatalen = BIO_get_mem_data(s->s3.handshake_buffer, &hdata);
if (hdatalen <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_LENGTH);
return 0;
}
s->s3.handshake_dgst = EVP_MD_CTX_new();
if (s->s3.handshake_dgst == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
return 0;
}
md = ssl_handshake_md(s);
if (md == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR,
SSL_R_NO_SUITABLE_DIGEST_ALGORITHM);
return 0;
}
if (!EVP_DigestInit_ex(s->s3.handshake_dgst, md, NULL)
|| !EVP_DigestUpdate(s->s3.handshake_dgst, hdata, hdatalen)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
if (keep == 0) {
BIO_free(s->s3.handshake_buffer);
s->s3.handshake_buffer = NULL;
}
return 1;
}
void ssl3_digest_master_key_set_params(const SSL_SESSION *session,
OSSL_PARAM params[])
{
int n = 0;
params[n++] = OSSL_PARAM_construct_octet_string(OSSL_DIGEST_PARAM_SSL3_MS,
(void *)session->master_key,
session->master_key_length);
params[n++] = OSSL_PARAM_construct_end();
}
size_t ssl3_final_finish_mac(SSL_CONNECTION *s, const char *sender, size_t len,
unsigned char *p)
{
int ret;
EVP_MD_CTX *ctx = NULL;
if (!ssl3_digest_cached_records(s, 0)) {
/* SSLfatal() already called */
return 0;
}
if (EVP_MD_CTX_get_type(s->s3.handshake_dgst) != NID_md5_sha1) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_REQUIRED_DIGEST);
return 0;
}
ctx = EVP_MD_CTX_new();
if (ctx == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
return 0;
}
if (!EVP_MD_CTX_copy_ex(ctx, s->s3.handshake_dgst)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
ret = 0;
goto err;
}
ret = EVP_MD_CTX_get_size(ctx);
if (ret < 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
ret = 0;
goto err;
}
if (sender != NULL) {
OSSL_PARAM digest_cmd_params[3];
ssl3_digest_master_key_set_params(s->session, digest_cmd_params);
if (EVP_DigestUpdate(ctx, sender, len) <= 0
|| EVP_MD_CTX_set_params(ctx, digest_cmd_params) <= 0
|| EVP_DigestFinal_ex(ctx, p, NULL) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
ret = 0;
}
}
err:
EVP_MD_CTX_free(ctx);
return ret;
}
int ssl3_generate_master_secret(SSL_CONNECTION *s, unsigned char *out,
unsigned char *p,
size_t len, size_t *secret_size)
{
static const unsigned char *salt[3] = {
#ifndef CHARSET_EBCDIC
(const unsigned char *)"A",
(const unsigned char *)"BB",
(const unsigned char *)"CCC",
#else
(const unsigned char *)"\x41",
(const unsigned char *)"\x42\x42",
(const unsigned char *)"\x43\x43\x43",
#endif
};
unsigned char buf[EVP_MAX_MD_SIZE];
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
int i, ret = 1;
unsigned int n;
size_t ret_secret_size = 0;
if (ctx == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
return 0;
}
for (i = 0; i < 3; i++) {
if (EVP_DigestInit_ex(ctx, SSL_CONNECTION_GET_CTX(s)->sha1, NULL) <= 0
|| EVP_DigestUpdate(ctx, salt[i],
strlen((const char *)salt[i])) <= 0
|| EVP_DigestUpdate(ctx, p, len) <= 0
|| EVP_DigestUpdate(ctx, &(s->s3.client_random[0]),
SSL3_RANDOM_SIZE) <= 0
|| EVP_DigestUpdate(ctx, &(s->s3.server_random[0]),
SSL3_RANDOM_SIZE) <= 0
|| EVP_DigestFinal_ex(ctx, buf, &n) <= 0
|| EVP_DigestInit_ex(ctx, SSL_CONNECTION_GET_CTX(s)->md5, NULL) <= 0
|| EVP_DigestUpdate(ctx, p, len) <= 0
|| EVP_DigestUpdate(ctx, buf, n) <= 0
|| EVP_DigestFinal_ex(ctx, out, &n) <= 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
ret = 0;
break;
}
out += n;
ret_secret_size += n;
}
EVP_MD_CTX_free(ctx);
OPENSSL_cleanse(buf, sizeof(buf));
if (ret)
*secret_size = ret_secret_size;
return ret;
}
int ssl3_alert_code(int code)
{
switch (code) {
case SSL_AD_CLOSE_NOTIFY:
return SSL3_AD_CLOSE_NOTIFY;
case SSL_AD_UNEXPECTED_MESSAGE:
return SSL3_AD_UNEXPECTED_MESSAGE;
case SSL_AD_BAD_RECORD_MAC:
return SSL3_AD_BAD_RECORD_MAC;
case SSL_AD_DECRYPTION_FAILED:
return SSL3_AD_BAD_RECORD_MAC;
case SSL_AD_RECORD_OVERFLOW:
return SSL3_AD_BAD_RECORD_MAC;
case SSL_AD_DECOMPRESSION_FAILURE:
return SSL3_AD_DECOMPRESSION_FAILURE;
case SSL_AD_HANDSHAKE_FAILURE:
return SSL3_AD_HANDSHAKE_FAILURE;
case SSL_AD_NO_CERTIFICATE:
return SSL3_AD_NO_CERTIFICATE;
case SSL_AD_BAD_CERTIFICATE:
return SSL3_AD_BAD_CERTIFICATE;
case SSL_AD_UNSUPPORTED_CERTIFICATE:
return SSL3_AD_UNSUPPORTED_CERTIFICATE;
case SSL_AD_CERTIFICATE_REVOKED:
return SSL3_AD_CERTIFICATE_REVOKED;
case SSL_AD_CERTIFICATE_EXPIRED:
return SSL3_AD_CERTIFICATE_EXPIRED;
case SSL_AD_CERTIFICATE_UNKNOWN:
return SSL3_AD_CERTIFICATE_UNKNOWN;
case SSL_AD_ILLEGAL_PARAMETER:
return SSL3_AD_ILLEGAL_PARAMETER;
case SSL_AD_UNKNOWN_CA:
return SSL3_AD_BAD_CERTIFICATE;
case SSL_AD_ACCESS_DENIED:
return SSL3_AD_HANDSHAKE_FAILURE;
case SSL_AD_DECODE_ERROR:
return SSL3_AD_HANDSHAKE_FAILURE;
case SSL_AD_DECRYPT_ERROR:
return SSL3_AD_HANDSHAKE_FAILURE;
case SSL_AD_EXPORT_RESTRICTION:
return SSL3_AD_HANDSHAKE_FAILURE;
case SSL_AD_PROTOCOL_VERSION:
return SSL3_AD_HANDSHAKE_FAILURE;
case SSL_AD_INSUFFICIENT_SECURITY:
return SSL3_AD_HANDSHAKE_FAILURE;
case SSL_AD_INTERNAL_ERROR:
return SSL3_AD_HANDSHAKE_FAILURE;
case SSL_AD_USER_CANCELLED:
return SSL3_AD_HANDSHAKE_FAILURE;
case SSL_AD_NO_RENEGOTIATION:
return -1; /* Don't send it :-) */
case SSL_AD_UNSUPPORTED_EXTENSION:
return SSL3_AD_HANDSHAKE_FAILURE;
case SSL_AD_CERTIFICATE_UNOBTAINABLE:
return SSL3_AD_HANDSHAKE_FAILURE;
case SSL_AD_UNRECOGNIZED_NAME:
return SSL3_AD_HANDSHAKE_FAILURE;
case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
return SSL3_AD_HANDSHAKE_FAILURE;
case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
return SSL3_AD_HANDSHAKE_FAILURE;
case SSL_AD_UNKNOWN_PSK_IDENTITY:
return TLS1_AD_UNKNOWN_PSK_IDENTITY;
case SSL_AD_INAPPROPRIATE_FALLBACK:
return TLS1_AD_INAPPROPRIATE_FALLBACK;
case SSL_AD_NO_APPLICATION_PROTOCOL:
return TLS1_AD_NO_APPLICATION_PROTOCOL;
case SSL_AD_CERTIFICATE_REQUIRED:
return SSL_AD_HANDSHAKE_FAILURE;
case TLS13_AD_MISSING_EXTENSION:
return SSL_AD_HANDSHAKE_FAILURE;
default:
return -1;
}
}
| 15,536 | 29.950199 | 81 | c |
openssl | openssl-master/ssl/s3_msg.c | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "ssl_local.h"
int ssl3_do_change_cipher_spec(SSL_CONNECTION *s)
{
int i;
SSL *ssl = SSL_CONNECTION_GET_SSL(s);
if (s->server)
i = SSL3_CHANGE_CIPHER_SERVER_READ;
else
i = SSL3_CHANGE_CIPHER_CLIENT_READ;
if (s->s3.tmp.key_block == NULL) {
if (s->session == NULL || s->session->master_key_length == 0) {
/* might happen if dtls1_read_bytes() calls this */
ERR_raise(ERR_LIB_SSL, SSL_R_CCS_RECEIVED_EARLY);
return 0;
}
s->session->cipher = s->s3.tmp.new_cipher;
if (!ssl->method->ssl3_enc->setup_key_block(s)) {
/* SSLfatal() already called */
return 0;
}
}
if (!ssl->method->ssl3_enc->change_cipher_state(s, i)) {
/* SSLfatal() already called */
return 0;
}
return 1;
}
int ssl3_send_alert(SSL_CONNECTION *s, int level, int desc)
{
SSL *ssl = SSL_CONNECTION_GET_SSL(s);
/* Map tls/ssl alert value to correct one */
if (SSL_CONNECTION_TREAT_AS_TLS13(s))
desc = tls13_alert_code(desc);
else
desc = ssl->method->ssl3_enc->alert_value(desc);
if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have
* protocol_version alerts */
if (desc < 0)
return -1;
if (s->shutdown & SSL_SENT_SHUTDOWN && desc != SSL_AD_CLOSE_NOTIFY)
return -1;
/* If a fatal one, remove from cache */
if ((level == SSL3_AL_FATAL) && (s->session != NULL))
SSL_CTX_remove_session(s->session_ctx, s->session);
s->s3.alert_dispatch = SSL_ALERT_DISPATCH_PENDING;
s->s3.send_alert[0] = level;
s->s3.send_alert[1] = desc;
if (!RECORD_LAYER_write_pending(&s->rlayer)) {
/* data still being written out? */
return ssl->method->ssl_dispatch_alert(ssl);
}
/*
* else data is still being written out, we will get written some time in
* the future
*/
return -1;
}
int ssl3_dispatch_alert(SSL *s)
{
int i, j;
void (*cb) (const SSL *ssl, int type, int val) = NULL;
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
OSSL_RECORD_TEMPLATE templ;
if (sc == NULL)
return -1;
if (sc->rlayer.wrlmethod == NULL) {
/* No write record layer so we can't sent and alert. We just ignore it */
sc->s3.alert_dispatch = SSL_ALERT_DISPATCH_NONE;
return 1;
}
templ.type = SSL3_RT_ALERT;
templ.version = (sc->version == TLS1_3_VERSION) ? TLS1_2_VERSION
: sc->version;
if (SSL_get_state(s) == TLS_ST_CW_CLNT_HELLO
&& !sc->renegotiate
&& TLS1_get_version(s) > TLS1_VERSION
&& sc->hello_retry_request == SSL_HRR_NONE) {
templ.version = TLS1_VERSION;
}
templ.buf = &sc->s3.send_alert[0];
templ.buflen = 2;
if (RECORD_LAYER_write_pending(&sc->rlayer)) {
if (sc->s3.alert_dispatch != SSL_ALERT_DISPATCH_RETRY) {
/*
* We have a write pending but it wasn't from a previous call to
* this function! Can we ever get here? Maybe via API misuse??
* Give up.
*/
sc->s3.alert_dispatch = SSL_ALERT_DISPATCH_NONE;
return -1;
}
/* Retry what we've already got pending */
i = HANDLE_RLAYER_WRITE_RETURN(sc,
sc->rlayer.wrlmethod->retry_write_records(sc->rlayer.wrl));
if (i <= 0) {
/* Could be NBIO. Keep alert_dispatch as SSL_ALERT_DISPATCH_RETRY */
return -1;
}
sc->rlayer.wpend_tot = 0;
sc->s3.alert_dispatch = SSL_ALERT_DISPATCH_NONE;
return 1;
}
i = HANDLE_RLAYER_WRITE_RETURN(sc,
sc->rlayer.wrlmethod->write_records(sc->rlayer.wrl, &templ, 1));
if (i <= 0) {
sc->s3.alert_dispatch = SSL_ALERT_DISPATCH_RETRY;
sc->rlayer.wpend_tot = templ.buflen;
sc->rlayer.wpend_type = templ.type;
sc->rlayer.wpend_buf = templ.buf;
} else {
/*
* Alert sent to BIO - now flush. If the message does not get sent due
* to non-blocking IO, we will not worry too much.
*/
(void)BIO_flush(sc->wbio);
sc->s3.alert_dispatch = SSL_ALERT_DISPATCH_NONE;
if (sc->msg_callback)
sc->msg_callback(1, sc->version, SSL3_RT_ALERT, sc->s3.send_alert,
2, s, sc->msg_callback_arg);
if (sc->info_callback != NULL)
cb = sc->info_callback;
else if (s->ctx->info_callback != NULL)
cb = s->ctx->info_callback;
if (cb != NULL) {
j = (sc->s3.send_alert[0] << 8) | sc->s3.send_alert[1];
cb(s, SSL_CB_WRITE_ALERT, j);
}
}
return i;
}
| 5,222 | 31.64375 | 81 | c |
openssl | openssl-master/ssl/ssl_asn1.c | /*
* Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
* Copyright 2005 Nokia. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include "ssl_local.h"
#include <openssl/asn1t.h>
#include <openssl/encoder.h>
#include <openssl/x509.h>
typedef struct {
uint32_t version;
int32_t ssl_version;
ASN1_OCTET_STRING *cipher;
ASN1_OCTET_STRING *comp_id;
ASN1_OCTET_STRING *master_key;
ASN1_OCTET_STRING *session_id;
ASN1_OCTET_STRING *key_arg;
int64_t time;
int64_t timeout;
X509 *peer;
ASN1_OCTET_STRING *session_id_context;
int32_t verify_result;
ASN1_OCTET_STRING *tlsext_hostname;
uint64_t tlsext_tick_lifetime_hint;
uint32_t tlsext_tick_age_add;
ASN1_OCTET_STRING *tlsext_tick;
#ifndef OPENSSL_NO_PSK
ASN1_OCTET_STRING *psk_identity_hint;
ASN1_OCTET_STRING *psk_identity;
#endif
#ifndef OPENSSL_NO_SRP
ASN1_OCTET_STRING *srp_username;
#endif
uint64_t flags;
uint32_t max_early_data;
ASN1_OCTET_STRING *alpn_selected;
uint32_t tlsext_max_fragment_len_mode;
ASN1_OCTET_STRING *ticket_appdata;
uint32_t kex_group;
ASN1_OCTET_STRING *peer_rpk;
} SSL_SESSION_ASN1;
ASN1_SEQUENCE(SSL_SESSION_ASN1) = {
ASN1_EMBED(SSL_SESSION_ASN1, version, UINT32),
ASN1_EMBED(SSL_SESSION_ASN1, ssl_version, INT32),
ASN1_SIMPLE(SSL_SESSION_ASN1, cipher, ASN1_OCTET_STRING),
ASN1_SIMPLE(SSL_SESSION_ASN1, session_id, ASN1_OCTET_STRING),
ASN1_SIMPLE(SSL_SESSION_ASN1, master_key, ASN1_OCTET_STRING),
ASN1_IMP_OPT(SSL_SESSION_ASN1, key_arg, ASN1_OCTET_STRING, 0),
ASN1_EXP_OPT_EMBED(SSL_SESSION_ASN1, time, ZINT64, 1),
ASN1_EXP_OPT_EMBED(SSL_SESSION_ASN1, timeout, ZINT64, 2),
ASN1_EXP_OPT(SSL_SESSION_ASN1, peer, X509, 3),
ASN1_EXP_OPT(SSL_SESSION_ASN1, session_id_context, ASN1_OCTET_STRING, 4),
ASN1_EXP_OPT_EMBED(SSL_SESSION_ASN1, verify_result, ZINT32, 5),
ASN1_EXP_OPT(SSL_SESSION_ASN1, tlsext_hostname, ASN1_OCTET_STRING, 6),
#ifndef OPENSSL_NO_PSK
ASN1_EXP_OPT(SSL_SESSION_ASN1, psk_identity_hint, ASN1_OCTET_STRING, 7),
ASN1_EXP_OPT(SSL_SESSION_ASN1, psk_identity, ASN1_OCTET_STRING, 8),
#endif
ASN1_EXP_OPT_EMBED(SSL_SESSION_ASN1, tlsext_tick_lifetime_hint, ZUINT64, 9),
ASN1_EXP_OPT(SSL_SESSION_ASN1, tlsext_tick, ASN1_OCTET_STRING, 10),
ASN1_EXP_OPT(SSL_SESSION_ASN1, comp_id, ASN1_OCTET_STRING, 11),
#ifndef OPENSSL_NO_SRP
ASN1_EXP_OPT(SSL_SESSION_ASN1, srp_username, ASN1_OCTET_STRING, 12),
#endif
ASN1_EXP_OPT_EMBED(SSL_SESSION_ASN1, flags, ZUINT64, 13),
ASN1_EXP_OPT_EMBED(SSL_SESSION_ASN1, tlsext_tick_age_add, ZUINT32, 14),
ASN1_EXP_OPT_EMBED(SSL_SESSION_ASN1, max_early_data, ZUINT32, 15),
ASN1_EXP_OPT(SSL_SESSION_ASN1, alpn_selected, ASN1_OCTET_STRING, 16),
ASN1_EXP_OPT_EMBED(SSL_SESSION_ASN1, tlsext_max_fragment_len_mode, ZUINT32, 17),
ASN1_EXP_OPT(SSL_SESSION_ASN1, ticket_appdata, ASN1_OCTET_STRING, 18),
ASN1_EXP_OPT_EMBED(SSL_SESSION_ASN1, kex_group, UINT32, 19),
ASN1_EXP_OPT(SSL_SESSION_ASN1, peer_rpk, ASN1_OCTET_STRING, 20)
} static_ASN1_SEQUENCE_END(SSL_SESSION_ASN1)
IMPLEMENT_STATIC_ASN1_ENCODE_FUNCTIONS(SSL_SESSION_ASN1)
/* Utility functions for i2d_SSL_SESSION */
/* Initialise OCTET STRING from buffer and length */
static void ssl_session_oinit(ASN1_OCTET_STRING **dest, ASN1_OCTET_STRING *os,
const unsigned char *data, size_t len)
{
os->data = (unsigned char *)data; /* justified cast: data is not modified */
os->length = (int)len;
os->flags = 0;
*dest = os;
}
/* Initialise OCTET STRING from string */
static void ssl_session_sinit(ASN1_OCTET_STRING **dest, ASN1_OCTET_STRING *os,
const char *data)
{
if (data != NULL)
ssl_session_oinit(dest, os, (const unsigned char *)data, strlen(data));
else
*dest = NULL;
}
int i2d_SSL_SESSION(const SSL_SESSION *in, unsigned char **pp)
{
SSL_SESSION_ASN1 as;
ASN1_OCTET_STRING cipher;
unsigned char cipher_data[2];
ASN1_OCTET_STRING master_key, session_id, sid_ctx;
#ifndef OPENSSL_NO_COMP
ASN1_OCTET_STRING comp_id;
unsigned char comp_id_data;
#endif
ASN1_OCTET_STRING tlsext_hostname, tlsext_tick;
#ifndef OPENSSL_NO_SRP
ASN1_OCTET_STRING srp_username;
#endif
#ifndef OPENSSL_NO_PSK
ASN1_OCTET_STRING psk_identity, psk_identity_hint;
#endif
ASN1_OCTET_STRING alpn_selected;
ASN1_OCTET_STRING ticket_appdata;
ASN1_OCTET_STRING peer_rpk;
long l;
int ret;
if ((in == NULL) || ((in->cipher == NULL) && (in->cipher_id == 0)))
return 0;
memset(&as, 0, sizeof(as));
as.version = SSL_SESSION_ASN1_VERSION;
as.ssl_version = in->ssl_version;
as.kex_group = in->kex_group;
if (in->cipher == NULL)
l = in->cipher_id;
else
l = in->cipher->id;
cipher_data[0] = ((unsigned char)(l >> 8L)) & 0xff;
cipher_data[1] = ((unsigned char)(l)) & 0xff;
ssl_session_oinit(&as.cipher, &cipher, cipher_data, 2);
#ifndef OPENSSL_NO_COMP
if (in->compress_meth) {
comp_id_data = (unsigned char)in->compress_meth;
ssl_session_oinit(&as.comp_id, &comp_id, &comp_id_data, 1);
}
#endif
ssl_session_oinit(&as.master_key, &master_key,
in->master_key, in->master_key_length);
ssl_session_oinit(&as.session_id, &session_id,
in->session_id, in->session_id_length);
ssl_session_oinit(&as.session_id_context, &sid_ctx,
in->sid_ctx, in->sid_ctx_length);
as.time = (int64_t)ossl_time_to_time_t(in->time);
as.timeout = (int64_t)ossl_time2seconds(in->timeout);
as.verify_result = in->verify_result;
as.peer = in->peer;
as.peer_rpk = NULL;
peer_rpk.data = NULL;
if (in->peer_rpk != NULL) {
peer_rpk.length = i2d_PUBKEY(in->peer_rpk, &peer_rpk.data);
if (peer_rpk.length > 0 && peer_rpk.data != NULL)
as.peer_rpk = &peer_rpk;
}
ssl_session_sinit(&as.tlsext_hostname, &tlsext_hostname,
in->ext.hostname);
if (in->ext.tick) {
ssl_session_oinit(&as.tlsext_tick, &tlsext_tick,
in->ext.tick, in->ext.ticklen);
}
if (in->ext.tick_lifetime_hint > 0)
as.tlsext_tick_lifetime_hint = in->ext.tick_lifetime_hint;
as.tlsext_tick_age_add = in->ext.tick_age_add;
#ifndef OPENSSL_NO_PSK
ssl_session_sinit(&as.psk_identity_hint, &psk_identity_hint,
in->psk_identity_hint);
ssl_session_sinit(&as.psk_identity, &psk_identity, in->psk_identity);
#endif /* OPENSSL_NO_PSK */
#ifndef OPENSSL_NO_SRP
ssl_session_sinit(&as.srp_username, &srp_username, in->srp_username);
#endif /* OPENSSL_NO_SRP */
as.flags = in->flags;
as.max_early_data = in->ext.max_early_data;
if (in->ext.alpn_selected == NULL)
as.alpn_selected = NULL;
else
ssl_session_oinit(&as.alpn_selected, &alpn_selected,
in->ext.alpn_selected, in->ext.alpn_selected_len);
as.tlsext_max_fragment_len_mode = in->ext.max_fragment_len_mode;
if (in->ticket_appdata == NULL)
as.ticket_appdata = NULL;
else
ssl_session_oinit(&as.ticket_appdata, &ticket_appdata,
in->ticket_appdata, in->ticket_appdata_len);
ret = i2d_SSL_SESSION_ASN1(&as, pp);
OPENSSL_free(peer_rpk.data);
return ret;
}
/* Utility functions for d2i_SSL_SESSION */
/* OPENSSL_strndup an OCTET STRING */
static int ssl_session_strndup(char **pdst, ASN1_OCTET_STRING *src)
{
OPENSSL_free(*pdst);
*pdst = NULL;
if (src == NULL)
return 1;
*pdst = OPENSSL_strndup((char *)src->data, src->length);
if (*pdst == NULL)
return 0;
return 1;
}
/* Copy an OCTET STRING, return error if it exceeds maximum length */
static int ssl_session_memcpy(unsigned char *dst, size_t *pdstlen,
ASN1_OCTET_STRING *src, size_t maxlen)
{
if (src == NULL || src->length == 0) {
*pdstlen = 0;
return 1;
}
if (src->length < 0 || src->length > (int)maxlen)
return 0;
memcpy(dst, src->data, src->length);
*pdstlen = src->length;
return 1;
}
SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a, const unsigned char **pp,
long length)
{
return d2i_SSL_SESSION_ex(a, pp, length, NULL, NULL);
}
SSL_SESSION *d2i_SSL_SESSION_ex(SSL_SESSION **a, const unsigned char **pp,
long length, OSSL_LIB_CTX *libctx,
const char *propq)
{
long id;
size_t tmpl;
const unsigned char *p = *pp;
SSL_SESSION_ASN1 *as = NULL;
SSL_SESSION *ret = NULL;
as = d2i_SSL_SESSION_ASN1(NULL, &p, length);
/* ASN.1 code returns suitable error */
if (as == NULL)
goto err;
if (a == NULL || *a == NULL) {
ret = SSL_SESSION_new();
if (ret == NULL)
goto err;
} else {
ret = *a;
}
if (as->version != SSL_SESSION_ASN1_VERSION) {
ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_SSL_VERSION);
goto err;
}
if ((as->ssl_version >> 8) != SSL3_VERSION_MAJOR
&& (as->ssl_version >> 8) != DTLS1_VERSION_MAJOR
&& as->ssl_version != DTLS1_BAD_VER) {
ERR_raise(ERR_LIB_SSL, SSL_R_UNSUPPORTED_SSL_VERSION);
goto err;
}
ret->ssl_version = (int)as->ssl_version;
ret->kex_group = as->kex_group;
if (as->cipher->length != 2) {
ERR_raise(ERR_LIB_SSL, SSL_R_CIPHER_CODE_WRONG_LENGTH);
goto err;
}
id = 0x03000000L | ((unsigned long)as->cipher->data[0] << 8L)
| (unsigned long)as->cipher->data[1];
ret->cipher_id = id;
ret->cipher = ssl3_get_cipher_by_id(id);
if (ret->cipher == NULL)
goto err;
if (!ssl_session_memcpy(ret->session_id, &ret->session_id_length,
as->session_id, SSL3_MAX_SSL_SESSION_ID_LENGTH))
goto err;
if (!ssl_session_memcpy(ret->master_key, &tmpl,
as->master_key, TLS13_MAX_RESUMPTION_PSK_LENGTH))
goto err;
ret->master_key_length = tmpl;
if (as->time != 0)
ret->time = ossl_time_from_time_t(as->time);
else
ret->time = ossl_time_now();
if (as->timeout != 0)
ret->timeout = ossl_seconds2time(as->timeout);
else
ret->timeout = ossl_seconds2time(3);
ssl_session_calculate_timeout(ret);
X509_free(ret->peer);
ret->peer = as->peer;
as->peer = NULL;
EVP_PKEY_free(ret->peer_rpk);
ret->peer_rpk = NULL;
if (as->peer_rpk != NULL) {
const unsigned char *data = as->peer_rpk->data;
/*
* |data| is incremented; we don't want to lose original ptr
*/
ret->peer_rpk = d2i_PUBKEY_ex(NULL, &data, as->peer_rpk->length, libctx, propq);
if (ret->peer_rpk == NULL)
goto err;
}
if (!ssl_session_memcpy(ret->sid_ctx, &ret->sid_ctx_length,
as->session_id_context, SSL_MAX_SID_CTX_LENGTH))
goto err;
/* NB: this defaults to zero which is X509_V_OK */
ret->verify_result = as->verify_result;
if (!ssl_session_strndup(&ret->ext.hostname, as->tlsext_hostname))
goto err;
#ifndef OPENSSL_NO_PSK
if (!ssl_session_strndup(&ret->psk_identity_hint, as->psk_identity_hint))
goto err;
if (!ssl_session_strndup(&ret->psk_identity, as->psk_identity))
goto err;
#endif
ret->ext.tick_lifetime_hint = (unsigned long)as->tlsext_tick_lifetime_hint;
ret->ext.tick_age_add = as->tlsext_tick_age_add;
OPENSSL_free(ret->ext.tick);
if (as->tlsext_tick != NULL) {
ret->ext.tick = as->tlsext_tick->data;
ret->ext.ticklen = as->tlsext_tick->length;
as->tlsext_tick->data = NULL;
} else {
ret->ext.tick = NULL;
}
#ifndef OPENSSL_NO_COMP
if (as->comp_id) {
if (as->comp_id->length != 1) {
ERR_raise(ERR_LIB_SSL, SSL_R_BAD_LENGTH);
goto err;
}
ret->compress_meth = as->comp_id->data[0];
} else {
ret->compress_meth = 0;
}
#endif
#ifndef OPENSSL_NO_SRP
if (!ssl_session_strndup(&ret->srp_username, as->srp_username))
goto err;
#endif /* OPENSSL_NO_SRP */
/* Flags defaults to zero which is fine */
ret->flags = (int32_t)as->flags;
ret->ext.max_early_data = as->max_early_data;
OPENSSL_free(ret->ext.alpn_selected);
if (as->alpn_selected != NULL) {
ret->ext.alpn_selected = as->alpn_selected->data;
ret->ext.alpn_selected_len = as->alpn_selected->length;
as->alpn_selected->data = NULL;
} else {
ret->ext.alpn_selected = NULL;
ret->ext.alpn_selected_len = 0;
}
ret->ext.max_fragment_len_mode = as->tlsext_max_fragment_len_mode;
OPENSSL_free(ret->ticket_appdata);
if (as->ticket_appdata != NULL) {
ret->ticket_appdata = as->ticket_appdata->data;
ret->ticket_appdata_len = as->ticket_appdata->length;
as->ticket_appdata->data = NULL;
} else {
ret->ticket_appdata = NULL;
ret->ticket_appdata_len = 0;
}
M_ASN1_free_of(as, SSL_SESSION_ASN1);
if ((a != NULL) && (*a == NULL))
*a = ret;
*pp = p;
return ret;
err:
M_ASN1_free_of(as, SSL_SESSION_ASN1);
if ((a == NULL) || (*a != ret))
SSL_SESSION_free(ret);
return NULL;
}
| 13,809 | 30.820276 | 88 | c |
openssl | openssl-master/ssl/ssl_cert_comp.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "ssl_local.h"
#include "internal/e_os.h"
#include "internal/refcount.h"
size_t ossl_calculate_comp_expansion(int alg, size_t length)
{
size_t ret;
/*
* Uncompressibility expansion:
* ZLIB: N + 11 + 5 * (N >> 14)
* Brotli: per RFC7932: N + 5 + 3 * (N >> 16)
* ZSTD: N + 4 + 14 + 3 * (N >> 17) + 4
*/
switch (alg) {
case TLSEXT_comp_cert_zlib:
ret = length + 11 + 5 * (length >> 14);
break;
case TLSEXT_comp_cert_brotli:
ret = length + 5 + 3 * (length >> 16);
break;
case TLSEXT_comp_cert_zstd:
ret = length + 22 + 3 * (length >> 17);
break;
default:
return 0;
}
/* Check for overflow */
if (ret < length)
return 0;
return ret;
}
int ossl_comp_has_alg(int a)
{
#ifndef OPENSSL_NO_COMP_ALG
/* 0 means "any" algorithm */
if ((a == 0 || a == TLSEXT_comp_cert_brotli) && BIO_f_brotli() != NULL)
return 1;
if ((a == 0 || a == TLSEXT_comp_cert_zstd) && BIO_f_zstd() != NULL)
return 1;
if ((a == 0 || a == TLSEXT_comp_cert_zlib) && BIO_f_zlib() != NULL)
return 1;
#endif
return 0;
}
/* New operation Helper routine */
#ifndef OPENSSL_NO_COMP_ALG
static OSSL_COMP_CERT *OSSL_COMP_CERT_new(unsigned char *data, size_t len, size_t orig_len, int alg)
{
OSSL_COMP_CERT *ret = NULL;
if (!ossl_comp_has_alg(alg)
|| data == NULL
|| (ret = OPENSSL_zalloc(sizeof(*ret))) == NULL
|| !CRYPTO_NEW_REF(&ret->references, 1))
goto err;
ret->data = data;
ret->len = len;
ret->orig_len = orig_len;
ret->alg = alg;
return ret;
err:
ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
OPENSSL_free(data);
OPENSSL_free(ret);
return NULL;
}
__owur static OSSL_COMP_CERT *OSSL_COMP_CERT_from_compressed_data(unsigned char *data, size_t len,
size_t orig_len, int alg)
{
return OSSL_COMP_CERT_new(OPENSSL_memdup(data, len), len, orig_len, alg);
}
__owur static OSSL_COMP_CERT *OSSL_COMP_CERT_from_uncompressed_data(unsigned char *data, size_t len,
int alg)
{
OSSL_COMP_CERT *ret = NULL;
size_t max_length;
int comp_length;
COMP_METHOD *method;
unsigned char *comp_data = NULL;
COMP_CTX *comp_ctx = NULL;
switch (alg) {
case TLSEXT_comp_cert_brotli:
method = COMP_brotli_oneshot();
break;
case TLSEXT_comp_cert_zlib:
method = COMP_zlib_oneshot();
break;
case TLSEXT_comp_cert_zstd:
method = COMP_zstd_oneshot();
break;
default:
goto err;
}
if ((max_length = ossl_calculate_comp_expansion(alg, len)) == 0
|| method == NULL
|| (comp_ctx = COMP_CTX_new(method)) == NULL
|| (comp_data = OPENSSL_zalloc(max_length)) == NULL)
goto err;
comp_length = COMP_compress_block(comp_ctx, comp_data, max_length, data, len);
if (comp_length <= 0)
goto err;
ret = OSSL_COMP_CERT_new(comp_data, comp_length, len, alg);
comp_data = NULL;
err:
OPENSSL_free(comp_data);
COMP_CTX_free(comp_ctx);
return ret;
}
void OSSL_COMP_CERT_free(OSSL_COMP_CERT *cc)
{
int i;
if (cc == NULL)
return;
CRYPTO_DOWN_REF(&cc->references, &i);
REF_PRINT_COUNT("OSSL_COMP_CERT", cc);
if (i > 0)
return;
REF_ASSERT_ISNT(i < 0);
OPENSSL_free(cc->data);
CRYPTO_FREE_REF(&cc->references);
OPENSSL_free(cc);
}
int OSSL_COMP_CERT_up_ref(OSSL_COMP_CERT *cc)
{
int i;
if (CRYPTO_UP_REF(&cc->references, &i) <= 0)
return 0;
REF_PRINT_COUNT("OSSL_COMP_CERT", cc);
REF_ASSERT_ISNT(i < 2);
return ((i > 1) ? 1 : 0);
}
static int ssl_set_cert_comp_pref(int *prefs, int *algs, size_t len)
{
size_t j = 0;
size_t i;
int found = 0;
int already_set[TLSEXT_comp_cert_limit];
int tmp_prefs[TLSEXT_comp_cert_limit];
/* Note that |len| is the number of |algs| elements */
/* clear all algorithms */
if (len == 0 || algs == NULL) {
memset(prefs, 0, sizeof(tmp_prefs));
return 1;
}
/* This will 0-terminate the array */
memset(tmp_prefs, 0, sizeof(tmp_prefs));
memset(already_set, 0, sizeof(already_set));
/* Include only those algorithms we support, ignoring duplicates and unknowns */
for (i = 0; i < len; i++) {
if (algs[i] != 0 && ossl_comp_has_alg(algs[i])) {
/* Check for duplicate */
if (already_set[algs[i]])
return 0;
tmp_prefs[j++] = algs[i];
already_set[algs[i]] = 1;
found = 1;
}
}
if (found)
memcpy(prefs, tmp_prefs, sizeof(tmp_prefs));
return found;
}
static size_t ssl_get_cert_to_compress(SSL *ssl, CERT_PKEY *cpk, unsigned char **data)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
WPACKET tmppkt;
BUF_MEM buf = { 0 };
size_t ret = 0;
if (sc == NULL
|| cpk == NULL
|| !sc->server
|| !SSL_in_before(ssl))
return 0;
/* Use the |tmppkt| for the to-be-compressed data */
if (!WPACKET_init(&tmppkt, &buf))
goto out;
/* no context present, add 0-length context */
if (!WPACKET_put_bytes_u8(&tmppkt, 0))
goto out;
/*
* ssl3_output_cert_chain() may generate an SSLfatal() error,
* for this case, we want to ignore it, argument for_comp = 1
*/
if (!ssl3_output_cert_chain(sc, &tmppkt, cpk, 1))
goto out;
WPACKET_get_total_written(&tmppkt, &ret);
out:
WPACKET_cleanup(&tmppkt);
if (ret != 0 && data != NULL)
*data = (unsigned char *)buf.data;
else
OPENSSL_free(buf.data);
return ret;
}
static int ssl_compress_one_cert(SSL *ssl, CERT_PKEY *cpk, int alg)
{
unsigned char *cert_data = NULL;
OSSL_COMP_CERT *comp_cert = NULL;
size_t length;
if (cpk == NULL
|| alg == TLSEXT_comp_cert_none
|| !ossl_comp_has_alg(alg))
return 0;
if ((length = ssl_get_cert_to_compress(ssl, cpk, &cert_data)) == 0)
return 0;
comp_cert = OSSL_COMP_CERT_from_uncompressed_data(cert_data, length, alg);
OPENSSL_free(cert_data);
if (comp_cert == NULL)
return 0;
OSSL_COMP_CERT_free(cpk->comp_cert[alg]);
cpk->comp_cert[alg] = comp_cert;
return 1;
}
/* alg_in can be 0, meaning any/all algorithms */
static int ssl_compress_certs(SSL *ssl, CERT_PKEY *cpks, int alg_in)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
int i;
int j;
int alg;
int count = 0;
if (sc == NULL
|| cpks == NULL
|| !ossl_comp_has_alg(alg_in))
return 0;
/* Look through the preferences to see what we have */
for (i = 0; i < TLSEXT_comp_cert_limit; i++) {
/*
* alg = 0 means compress for everything, but only for algorithms enabled
* alg != 0 means compress for that algorithm if enabled
*/
alg = sc->cert_comp_prefs[i];
if ((alg_in == 0 && alg != TLSEXT_comp_cert_none)
|| (alg_in != 0 && alg == alg_in)) {
for (j = 0; j < SSL_PKEY_NUM; j++) {
/* No cert, move on */
if (cpks[j].x509 == NULL)
continue;
if (!ssl_compress_one_cert(ssl, &cpks[j], alg))
return 0;
/* if the cert expanded, set the value in the CERT_PKEY to NULL */
if (cpks[j].comp_cert[alg]->len >= cpks[j].comp_cert[alg]->orig_len) {
OSSL_COMP_CERT_free(cpks[j].comp_cert[alg]);
cpks[j].comp_cert[alg] = NULL;
} else {
count++;
}
}
}
}
return (count > 0);
}
static size_t ssl_get_compressed_cert(SSL *ssl, CERT_PKEY *cpk, int alg, unsigned char **data,
size_t *orig_len)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
size_t cert_len = 0;
size_t comp_len = 0;
unsigned char *cert_data = NULL;
OSSL_COMP_CERT *comp_cert = NULL;
if (sc == NULL
|| cpk == NULL
|| data == NULL
|| orig_len == NULL
|| !sc->server
|| !SSL_in_before(ssl)
|| !ossl_comp_has_alg(alg))
return 0;
if ((cert_len = ssl_get_cert_to_compress(ssl, cpk, &cert_data)) == 0)
goto err;
comp_cert = OSSL_COMP_CERT_from_uncompressed_data(cert_data, cert_len, alg);
OPENSSL_free(cert_data);
if (comp_cert == NULL)
goto err;
comp_len = comp_cert->len;
*orig_len = comp_cert->orig_len;
*data = comp_cert->data;
comp_cert->data = NULL;
err:
OSSL_COMP_CERT_free(comp_cert);
return comp_len;
}
static int ossl_set1_compressed_cert(CERT *cert, int algorithm,
unsigned char *comp_data, size_t comp_length,
size_t orig_length)
{
OSSL_COMP_CERT *comp_cert;
/* No explicit cert set */
if (cert == NULL || cert->key == NULL)
return 0;
comp_cert = OSSL_COMP_CERT_from_compressed_data(comp_data, comp_length,
orig_length, algorithm);
if (comp_cert == NULL)
return 0;
OSSL_COMP_CERT_free(cert->key->comp_cert[algorithm]);
cert->key->comp_cert[algorithm] = comp_cert;
return 1;
}
#endif
/*-
* Public API
*/
int SSL_CTX_set1_cert_comp_preference(SSL_CTX *ctx, int *algs, size_t len)
{
#ifndef OPENSSL_NO_COMP_ALG
return ssl_set_cert_comp_pref(ctx->cert_comp_prefs, algs, len);
#else
return 0;
#endif
}
int SSL_set1_cert_comp_preference(SSL *ssl, int *algs, size_t len)
{
#ifndef OPENSSL_NO_COMP_ALG
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
if (sc == NULL)
return 0;
return ssl_set_cert_comp_pref(sc->cert_comp_prefs, algs, len);
#else
return 0;
#endif
}
int SSL_compress_certs(SSL *ssl, int alg)
{
#ifndef OPENSSL_NO_COMP_ALG
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
if (sc == NULL || sc->cert == NULL)
return 0;
return ssl_compress_certs(ssl, sc->cert->pkeys, alg);
#endif
return 0;
}
int SSL_CTX_compress_certs(SSL_CTX *ctx, int alg)
{
int ret = 0;
#ifndef OPENSSL_NO_COMP_ALG
SSL *new = SSL_new(ctx);
if (new == NULL)
return 0;
ret = ssl_compress_certs(new, ctx->cert->pkeys, alg);
SSL_free(new);
#endif
return ret;
}
size_t SSL_get1_compressed_cert(SSL *ssl, int alg, unsigned char **data, size_t *orig_len)
{
#ifndef OPENSSL_NO_COMP_ALG
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
CERT_PKEY *cpk = NULL;
if (sc->cert != NULL)
cpk = sc->cert->key;
else
cpk = ssl->ctx->cert->key;
return ssl_get_compressed_cert(ssl, cpk, alg, data, orig_len);
#else
return 0;
#endif
}
size_t SSL_CTX_get1_compressed_cert(SSL_CTX *ctx, int alg, unsigned char **data, size_t *orig_len)
{
#ifndef OPENSSL_NO_COMP_ALG
size_t ret;
SSL *new = SSL_new(ctx);
ret = ssl_get_compressed_cert(new, ctx->cert->key, alg, data, orig_len);
SSL_free(new);
return ret;
#else
return 0;
#endif
}
int SSL_CTX_set1_compressed_cert(SSL_CTX *ctx, int algorithm, unsigned char *comp_data,
size_t comp_length, size_t orig_length)
{
#ifndef OPENSSL_NO_COMP_ALG
return ossl_set1_compressed_cert(ctx->cert, algorithm, comp_data, comp_length, orig_length);
#else
return 0;
#endif
}
int SSL_set1_compressed_cert(SSL *ssl, int algorithm, unsigned char *comp_data,
size_t comp_length, size_t orig_length)
{
#ifndef OPENSSL_NO_COMP_ALG
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl);
/* Cannot set a pre-compressed certificate on a client */
if (sc == NULL || !sc->server)
return 0;
return ossl_set1_compressed_cert(sc->cert, algorithm, comp_data, comp_length, orig_length);
#else
return 0;
#endif
}
| 12,507 | 25.841202 | 100 | c |
openssl | openssl-master/ssl/ssl_cert_table.h | /*
* Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Certificate table information. NB: table entries must match SSL_PKEY indices
*/
static SSL_CERT_LOOKUP ssl_cert_info [] = {
{EVP_PKEY_RSA, SSL_aRSA}, /* SSL_PKEY_RSA */
{EVP_PKEY_RSA_PSS, SSL_aRSA}, /* SSL_PKEY_RSA_PSS_SIGN */
{EVP_PKEY_DSA, SSL_aDSS}, /* SSL_PKEY_DSA_SIGN */
{EVP_PKEY_EC, SSL_aECDSA}, /* SSL_PKEY_ECC */
{NID_id_GostR3410_2001, SSL_aGOST01}, /* SSL_PKEY_GOST01 */
{NID_id_GostR3410_2012_256, SSL_aGOST12}, /* SSL_PKEY_GOST12_256 */
{NID_id_GostR3410_2012_512, SSL_aGOST12}, /* SSL_PKEY_GOST12_512 */
{EVP_PKEY_ED25519, SSL_aECDSA}, /* SSL_PKEY_ED25519 */
{EVP_PKEY_ED448, SSL_aECDSA} /* SSL_PKEY_ED448 */
};
| 1,007 | 41 | 79 | h |
openssl | openssl-master/ssl/ssl_err_legacy.c | /*
* Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* This is the C source file where we include this header directly */
#include <openssl/sslerr_legacy.h>
#include "sslerr.h"
#ifndef OPENSSL_NO_DEPRECATED_3_0
int ERR_load_SSL_strings(void)
{
return ossl_err_load_SSL_strings();
}
#else
NON_EMPTY_TRANSLATION_UNIT
#endif
| 612 | 26.863636 | 74 | c |
openssl | openssl-master/ssl/ssl_init.c | /*
* Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/e_os.h"
#include "internal/err.h"
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/trace.h>
#include "ssl_local.h"
#include "sslerr.h"
#include "internal/thread_once.h"
static int stopped;
static void ssl_library_stop(void);
static CRYPTO_ONCE ssl_base = CRYPTO_ONCE_STATIC_INIT;
static int ssl_base_inited = 0;
DEFINE_RUN_ONCE_STATIC(ossl_init_ssl_base)
{
#ifndef OPENSSL_NO_COMP
OSSL_TRACE(INIT, "ossl_init_ssl_base: "
"SSL_COMP_get_compression_methods()\n");
/*
* This will initialise the built-in compression algorithms. The value
* returned is a STACK_OF(SSL_COMP), but that can be discarded safely
*/
SSL_COMP_get_compression_methods();
#endif
ssl_sort_cipher_list();
OSSL_TRACE(INIT, "ossl_init_ssl_base: SSL_add_ssl_module()\n");
/*
* We ignore an error return here. Not much we can do - but not that bad
* either. We can still safely continue.
*/
OPENSSL_atexit(ssl_library_stop);
ssl_base_inited = 1;
return 1;
}
static CRYPTO_ONCE ssl_strings = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_load_ssl_strings)
{
/*
* OPENSSL_NO_AUTOERRINIT is provided here to prevent at compile time
* pulling in all the error strings during static linking
*/
#if !defined(OPENSSL_NO_ERR) && !defined(OPENSSL_NO_AUTOERRINIT)
OSSL_TRACE(INIT, "ossl_init_load_ssl_strings: ossl_err_load_SSL_strings()\n");
ossl_err_load_SSL_strings();
#endif
return 1;
}
DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_load_ssl_strings,
ossl_init_load_ssl_strings)
{
/* Do nothing in this case */
return 1;
}
static void ssl_library_stop(void)
{
/* Might be explicitly called and also by atexit */
if (stopped)
return;
stopped = 1;
if (ssl_base_inited) {
#ifndef OPENSSL_NO_COMP
OSSL_TRACE(INIT, "ssl_library_stop: "
"ssl_comp_free_compression_methods_int()\n");
ssl_comp_free_compression_methods_int();
#endif
}
}
/*
* If this function is called with a non NULL settings value then it must be
* called prior to any threads making calls to any OpenSSL functions,
* i.e. passing a non-null settings value is assumed to be single-threaded.
*/
int OPENSSL_init_ssl(uint64_t opts, const OPENSSL_INIT_SETTINGS * settings)
{
static int stoperrset = 0;
if (stopped) {
if (!stoperrset) {
/*
* We only ever set this once to avoid getting into an infinite
* loop where the error system keeps trying to init and fails so
* sets an error etc
*/
stoperrset = 1;
ERR_raise(ERR_LIB_SSL, ERR_R_INIT_FAIL);
}
return 0;
}
opts |= OPENSSL_INIT_ADD_ALL_CIPHERS
| OPENSSL_INIT_ADD_ALL_DIGESTS;
#ifndef OPENSSL_NO_AUTOLOAD_CONFIG
if ((opts & OPENSSL_INIT_NO_LOAD_CONFIG) == 0)
opts |= OPENSSL_INIT_LOAD_CONFIG;
#endif
if (!OPENSSL_init_crypto(opts, settings))
return 0;
if (!RUN_ONCE(&ssl_base, ossl_init_ssl_base))
return 0;
if ((opts & OPENSSL_INIT_NO_LOAD_SSL_STRINGS)
&& !RUN_ONCE_ALT(&ssl_strings, ossl_init_no_load_ssl_strings,
ossl_init_load_ssl_strings))
return 0;
if ((opts & OPENSSL_INIT_LOAD_SSL_STRINGS)
&& !RUN_ONCE(&ssl_strings, ossl_init_load_ssl_strings))
return 0;
return 1;
}
| 3,803 | 27.818182 | 82 | c |
openssl | openssl-master/ssl/ssl_mcnf.c | /*
* Copyright 2015-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <openssl/conf.h>
#include <openssl/ssl.h>
#include "ssl_local.h"
#include "internal/sslconf.h"
/* SSL library configuration module. */
void SSL_add_ssl_module(void)
{
/* Do nothing. This will be added automatically by libcrypto */
}
static int ssl_do_config(SSL *s, SSL_CTX *ctx, const char *name, int system)
{
SSL_CONF_CTX *cctx = NULL;
size_t i, idx, cmd_count;
int rv = 0;
unsigned int flags;
const SSL_METHOD *meth;
const SSL_CONF_CMD *cmds;
OSSL_LIB_CTX *prev_libctx = NULL;
OSSL_LIB_CTX *libctx = NULL;
if (s == NULL && ctx == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
goto err;
}
if (name == NULL && system)
name = "system_default";
if (!conf_ssl_name_find(name, &idx)) {
if (!system)
ERR_raise_data(ERR_LIB_SSL, SSL_R_INVALID_CONFIGURATION_NAME,
"name=%s", name);
goto err;
}
cmds = conf_ssl_get(idx, &name, &cmd_count);
cctx = SSL_CONF_CTX_new();
if (cctx == NULL)
goto err;
flags = SSL_CONF_FLAG_FILE;
if (!system)
flags |= SSL_CONF_FLAG_CERTIFICATE | SSL_CONF_FLAG_REQUIRE_PRIVATE;
if (s != NULL) {
meth = s->method;
SSL_CONF_CTX_set_ssl(cctx, s);
libctx = s->ctx->libctx;
} else {
meth = ctx->method;
SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
libctx = ctx->libctx;
}
if (meth->ssl_accept != ssl_undefined_function)
flags |= SSL_CONF_FLAG_SERVER;
if (meth->ssl_connect != ssl_undefined_function)
flags |= SSL_CONF_FLAG_CLIENT;
SSL_CONF_CTX_set_flags(cctx, flags);
prev_libctx = OSSL_LIB_CTX_set0_default(libctx);
for (i = 0; i < cmd_count; i++) {
char *cmdstr, *arg;
conf_ssl_get_cmd(cmds, i, &cmdstr, &arg);
rv = SSL_CONF_cmd(cctx, cmdstr, arg);
if (rv <= 0) {
int errcode = rv == -2 ? SSL_R_UNKNOWN_COMMAND : SSL_R_BAD_VALUE;
ERR_raise_data(ERR_LIB_SSL, errcode,
"section=%s, cmd=%s, arg=%s", name, cmdstr, arg);
goto err;
}
}
rv = SSL_CONF_CTX_finish(cctx);
err:
OSSL_LIB_CTX_set0_default(prev_libctx);
SSL_CONF_CTX_free(cctx);
return rv <= 0 ? 0 : 1;
}
int SSL_config(SSL *s, const char *name)
{
return ssl_do_config(s, NULL, name, 0);
}
int SSL_CTX_config(SSL_CTX *ctx, const char *name)
{
return ssl_do_config(NULL, ctx, name, 0);
}
void ssl_ctx_system_config(SSL_CTX *ctx)
{
ssl_do_config(NULL, ctx, NULL, 1);
}
| 2,923 | 27.38835 | 77 | c |
openssl | openssl-master/ssl/ssl_rsa_legacy.c | /*
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* We need to use the deprecated RSA low level calls */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <openssl/err.h>
#include <openssl/rsa.h>
#include <openssl/ssl.h>
int SSL_use_RSAPrivateKey(SSL *ssl, RSA *rsa)
{
EVP_PKEY *pkey;
int ret;
if (rsa == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if ((pkey = EVP_PKEY_new()) == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_EVP_LIB);
return 0;
}
RSA_up_ref(rsa);
if (EVP_PKEY_assign_RSA(pkey, rsa) <= 0) {
RSA_free(rsa);
EVP_PKEY_free(pkey);
return 0;
}
ret = SSL_use_PrivateKey(ssl, pkey);
EVP_PKEY_free(pkey);
return ret;
}
int SSL_use_RSAPrivateKey_file(SSL *ssl, const char *file, int type)
{
int j, ret = 0;
BIO *in;
RSA *rsa = NULL;
in = BIO_new(BIO_s_file());
if (in == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB);
goto end;
}
if (BIO_read_filename(in, file) <= 0) {
ERR_raise(ERR_LIB_SSL, ERR_R_SYS_LIB);
goto end;
}
if (type == SSL_FILETYPE_ASN1) {
j = ERR_R_ASN1_LIB;
rsa = d2i_RSAPrivateKey_bio(in, NULL);
} else if (type == SSL_FILETYPE_PEM) {
j = ERR_R_PEM_LIB;
rsa = PEM_read_bio_RSAPrivateKey(in, NULL,
SSL_get_default_passwd_cb(ssl),
SSL_get_default_passwd_cb_userdata(ssl));
} else {
ERR_raise(ERR_LIB_SSL, SSL_R_BAD_SSL_FILETYPE);
goto end;
}
if (rsa == NULL) {
ERR_raise(ERR_LIB_SSL, j);
goto end;
}
ret = SSL_use_RSAPrivateKey(ssl, rsa);
RSA_free(rsa);
end:
BIO_free(in);
return ret;
}
int SSL_use_RSAPrivateKey_ASN1(SSL *ssl, const unsigned char *d, long len)
{
int ret;
const unsigned char *p;
RSA *rsa;
p = d;
if ((rsa = d2i_RSAPrivateKey(NULL, &p, (long)len)) == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_ASN1_LIB);
return 0;
}
ret = SSL_use_RSAPrivateKey(ssl, rsa);
RSA_free(rsa);
return ret;
}
int SSL_CTX_use_RSAPrivateKey(SSL_CTX *ctx, RSA *rsa)
{
int ret;
EVP_PKEY *pkey;
if (rsa == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if ((pkey = EVP_PKEY_new()) == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_EVP_LIB);
return 0;
}
RSA_up_ref(rsa);
if (EVP_PKEY_assign_RSA(pkey, rsa) <= 0) {
RSA_free(rsa);
EVP_PKEY_free(pkey);
return 0;
}
ret = SSL_CTX_use_PrivateKey(ctx, pkey);
EVP_PKEY_free(pkey);
return ret;
}
int SSL_CTX_use_RSAPrivateKey_file(SSL_CTX *ctx, const char *file, int type)
{
int j, ret = 0;
BIO *in;
RSA *rsa = NULL;
in = BIO_new(BIO_s_file());
if (in == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB);
goto end;
}
if (BIO_read_filename(in, file) <= 0) {
ERR_raise(ERR_LIB_SSL, ERR_R_SYS_LIB);
goto end;
}
if (type == SSL_FILETYPE_ASN1) {
j = ERR_R_ASN1_LIB;
rsa = d2i_RSAPrivateKey_bio(in, NULL);
} else if (type == SSL_FILETYPE_PEM) {
j = ERR_R_PEM_LIB;
rsa = PEM_read_bio_RSAPrivateKey(in, NULL,
SSL_CTX_get_default_passwd_cb(ctx),
SSL_CTX_get_default_passwd_cb_userdata(ctx));
} else {
ERR_raise(ERR_LIB_SSL, SSL_R_BAD_SSL_FILETYPE);
goto end;
}
if (rsa == NULL) {
ERR_raise(ERR_LIB_SSL, j);
goto end;
}
ret = SSL_CTX_use_RSAPrivateKey(ctx, rsa);
RSA_free(rsa);
end:
BIO_free(in);
return ret;
}
int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d,
long len)
{
int ret;
const unsigned char *p;
RSA *rsa;
p = d;
if ((rsa = d2i_RSAPrivateKey(NULL, &p, (long)len)) == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_ASN1_LIB);
return 0;
}
ret = SSL_CTX_use_RSAPrivateKey(ctx, rsa);
RSA_free(rsa);
return ret;
}
| 4,454 | 23.61326 | 86 | c |
openssl | openssl-master/ssl/ssl_stat.c | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright 2005 Nokia. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "ssl_local.h"
const char *SSL_state_string_long(const SSL *s)
{
const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
if (sc == NULL || ossl_statem_in_error(sc))
return "error";
switch (SSL_get_state(s)) {
case TLS_ST_CR_CERT_STATUS:
return "SSLv3/TLS read certificate status";
case TLS_ST_CW_NEXT_PROTO:
return "SSLv3/TLS write next proto";
case TLS_ST_SR_NEXT_PROTO:
return "SSLv3/TLS read next proto";
case TLS_ST_SW_CERT_STATUS:
return "SSLv3/TLS write certificate status";
case TLS_ST_BEFORE:
return "before SSL initialization";
case TLS_ST_OK:
return "SSL negotiation finished successfully";
case TLS_ST_CW_CLNT_HELLO:
return "SSLv3/TLS write client hello";
case TLS_ST_CR_SRVR_HELLO:
return "SSLv3/TLS read server hello";
case TLS_ST_CR_CERT:
return "SSLv3/TLS read server certificate";
case TLS_ST_CR_COMP_CERT:
return "TLSv1.3 read server compressed certificate";
case TLS_ST_CR_KEY_EXCH:
return "SSLv3/TLS read server key exchange";
case TLS_ST_CR_CERT_REQ:
return "SSLv3/TLS read server certificate request";
case TLS_ST_CR_SESSION_TICKET:
return "SSLv3/TLS read server session ticket";
case TLS_ST_CR_SRVR_DONE:
return "SSLv3/TLS read server done";
case TLS_ST_CW_CERT:
return "SSLv3/TLS write client certificate";
case TLS_ST_CW_COMP_CERT:
return "TLSv1.3 write client compressed certificate";
case TLS_ST_CW_KEY_EXCH:
return "SSLv3/TLS write client key exchange";
case TLS_ST_CW_CERT_VRFY:
return "SSLv3/TLS write certificate verify";
case TLS_ST_CW_CHANGE:
case TLS_ST_SW_CHANGE:
return "SSLv3/TLS write change cipher spec";
case TLS_ST_CW_FINISHED:
case TLS_ST_SW_FINISHED:
return "SSLv3/TLS write finished";
case TLS_ST_CR_CHANGE:
case TLS_ST_SR_CHANGE:
return "SSLv3/TLS read change cipher spec";
case TLS_ST_CR_FINISHED:
case TLS_ST_SR_FINISHED:
return "SSLv3/TLS read finished";
case TLS_ST_SR_CLNT_HELLO:
return "SSLv3/TLS read client hello";
case TLS_ST_SW_HELLO_REQ:
return "SSLv3/TLS write hello request";
case TLS_ST_SW_SRVR_HELLO:
return "SSLv3/TLS write server hello";
case TLS_ST_SW_CERT:
return "SSLv3/TLS write certificate";
case TLS_ST_SW_COMP_CERT:
return "TLSv1.3 write server compressed certificate";
case TLS_ST_SW_KEY_EXCH:
return "SSLv3/TLS write key exchange";
case TLS_ST_SW_CERT_REQ:
return "SSLv3/TLS write certificate request";
case TLS_ST_SW_SESSION_TICKET:
return "SSLv3/TLS write session ticket";
case TLS_ST_SW_SRVR_DONE:
return "SSLv3/TLS write server done";
case TLS_ST_SR_CERT:
return "SSLv3/TLS read client certificate";
case TLS_ST_SR_COMP_CERT:
return "TLSv1.3 read client compressed certificate";
case TLS_ST_SR_KEY_EXCH:
return "SSLv3/TLS read client key exchange";
case TLS_ST_SR_CERT_VRFY:
return "SSLv3/TLS read certificate verify";
case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
return "DTLS1 read hello verify request";
case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
return "DTLS1 write hello verify request";
case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
return "TLSv1.3 write encrypted extensions";
case TLS_ST_CR_ENCRYPTED_EXTENSIONS:
return "TLSv1.3 read encrypted extensions";
case TLS_ST_CR_CERT_VRFY:
return "TLSv1.3 read server certificate verify";
case TLS_ST_SW_CERT_VRFY:
return "TLSv1.3 write server certificate verify";
case TLS_ST_CR_HELLO_REQ:
return "SSLv3/TLS read hello request";
case TLS_ST_SW_KEY_UPDATE:
return "TLSv1.3 write server key update";
case TLS_ST_CW_KEY_UPDATE:
return "TLSv1.3 write client key update";
case TLS_ST_SR_KEY_UPDATE:
return "TLSv1.3 read client key update";
case TLS_ST_CR_KEY_UPDATE:
return "TLSv1.3 read server key update";
case TLS_ST_EARLY_DATA:
return "TLSv1.3 early data";
case TLS_ST_PENDING_EARLY_DATA_END:
return "TLSv1.3 pending early data end";
case TLS_ST_CW_END_OF_EARLY_DATA:
return "TLSv1.3 write end of early data";
case TLS_ST_SR_END_OF_EARLY_DATA:
return "TLSv1.3 read end of early data";
default:
return "unknown state";
}
}
const char *SSL_state_string(const SSL *s)
{
const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
if (sc == NULL || ossl_statem_in_error(sc))
return "SSLERR";
switch (SSL_get_state(s)) {
case TLS_ST_SR_NEXT_PROTO:
return "TRNP";
case TLS_ST_SW_SESSION_TICKET:
return "TWST";
case TLS_ST_SW_CERT_STATUS:
return "TWCS";
case TLS_ST_CR_CERT_STATUS:
return "TRCS";
case TLS_ST_CR_SESSION_TICKET:
return "TRST";
case TLS_ST_CW_NEXT_PROTO:
return "TWNP";
case TLS_ST_BEFORE:
return "PINIT";
case TLS_ST_OK:
return "SSLOK";
case TLS_ST_CW_CLNT_HELLO:
return "TWCH";
case TLS_ST_CR_SRVR_HELLO:
return "TRSH";
case TLS_ST_CR_CERT:
return "TRSC";
case TLS_ST_CR_COMP_CERT:
return "TRSCC";
case TLS_ST_CR_KEY_EXCH:
return "TRSKE";
case TLS_ST_CR_CERT_REQ:
return "TRCR";
case TLS_ST_CR_SRVR_DONE:
return "TRSD";
case TLS_ST_CW_CERT:
return "TWCC";
case TLS_ST_CW_COMP_CERT:
return "TWCCC";
case TLS_ST_CW_KEY_EXCH:
return "TWCKE";
case TLS_ST_CW_CERT_VRFY:
return "TWCV";
case TLS_ST_SW_CHANGE:
case TLS_ST_CW_CHANGE:
return "TWCCS";
case TLS_ST_SW_FINISHED:
case TLS_ST_CW_FINISHED:
return "TWFIN";
case TLS_ST_SR_CHANGE:
case TLS_ST_CR_CHANGE:
return "TRCCS";
case TLS_ST_SR_FINISHED:
case TLS_ST_CR_FINISHED:
return "TRFIN";
case TLS_ST_SW_HELLO_REQ:
return "TWHR";
case TLS_ST_SR_CLNT_HELLO:
return "TRCH";
case TLS_ST_SW_SRVR_HELLO:
return "TWSH";
case TLS_ST_SW_CERT:
return "TWSC";
case TLS_ST_SW_COMP_CERT:
return "TWSCC";
case TLS_ST_SW_KEY_EXCH:
return "TWSKE";
case TLS_ST_SW_CERT_REQ:
return "TWCR";
case TLS_ST_SW_SRVR_DONE:
return "TWSD";
case TLS_ST_SR_CERT:
return "TRCC";
case TLS_ST_SR_COMP_CERT:
return "TRCCC";
case TLS_ST_SR_KEY_EXCH:
return "TRCKE";
case TLS_ST_SR_CERT_VRFY:
return "TRCV";
case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
return "DRCHV";
case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
return "DWCHV";
case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
return "TWEE";
case TLS_ST_CR_ENCRYPTED_EXTENSIONS:
return "TREE";
case TLS_ST_CR_CERT_VRFY:
return "TRSCV";
case TLS_ST_SW_CERT_VRFY:
return "TWSCV";
case TLS_ST_CR_HELLO_REQ:
return "TRHR";
case TLS_ST_SW_KEY_UPDATE:
return "TWSKU";
case TLS_ST_CW_KEY_UPDATE:
return "TWCKU";
case TLS_ST_SR_KEY_UPDATE:
return "TRCKU";
case TLS_ST_CR_KEY_UPDATE:
return "TRSKU";
case TLS_ST_EARLY_DATA:
return "TED";
case TLS_ST_PENDING_EARLY_DATA_END:
return "TPEDE";
case TLS_ST_CW_END_OF_EARLY_DATA:
return "TWEOED";
case TLS_ST_SR_END_OF_EARLY_DATA:
return "TWEOED";
default:
return "UNKWN";
}
}
const char *SSL_alert_type_string_long(int value)
{
switch (value >> 8) {
case SSL3_AL_WARNING:
return "warning";
case SSL3_AL_FATAL:
return "fatal";
default:
return "unknown";
}
}
const char *SSL_alert_type_string(int value)
{
switch (value >> 8) {
case SSL3_AL_WARNING:
return "W";
case SSL3_AL_FATAL:
return "F";
default:
return "U";
}
}
const char *SSL_alert_desc_string(int value)
{
switch (value & 0xff) {
case SSL3_AD_CLOSE_NOTIFY:
return "CN";
case SSL3_AD_UNEXPECTED_MESSAGE:
return "UM";
case SSL3_AD_BAD_RECORD_MAC:
return "BM";
case SSL3_AD_DECOMPRESSION_FAILURE:
return "DF";
case SSL3_AD_HANDSHAKE_FAILURE:
return "HF";
case SSL3_AD_NO_CERTIFICATE:
return "NC";
case SSL3_AD_BAD_CERTIFICATE:
return "BC";
case SSL3_AD_UNSUPPORTED_CERTIFICATE:
return "UC";
case SSL3_AD_CERTIFICATE_REVOKED:
return "CR";
case SSL3_AD_CERTIFICATE_EXPIRED:
return "CE";
case SSL3_AD_CERTIFICATE_UNKNOWN:
return "CU";
case SSL3_AD_ILLEGAL_PARAMETER:
return "IP";
case TLS1_AD_DECRYPTION_FAILED:
return "DC";
case TLS1_AD_RECORD_OVERFLOW:
return "RO";
case TLS1_AD_UNKNOWN_CA:
return "CA";
case TLS1_AD_ACCESS_DENIED:
return "AD";
case TLS1_AD_DECODE_ERROR:
return "DE";
case TLS1_AD_DECRYPT_ERROR:
return "CY";
case TLS1_AD_EXPORT_RESTRICTION:
return "ER";
case TLS1_AD_PROTOCOL_VERSION:
return "PV";
case TLS1_AD_INSUFFICIENT_SECURITY:
return "IS";
case TLS1_AD_INTERNAL_ERROR:
return "IE";
case TLS1_AD_USER_CANCELLED:
return "US";
case TLS1_AD_NO_RENEGOTIATION:
return "NR";
case TLS1_AD_UNSUPPORTED_EXTENSION:
return "UE";
case TLS1_AD_CERTIFICATE_UNOBTAINABLE:
return "CO";
case TLS1_AD_UNRECOGNIZED_NAME:
return "UN";
case TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
return "BR";
case TLS1_AD_BAD_CERTIFICATE_HASH_VALUE:
return "BH";
case TLS1_AD_UNKNOWN_PSK_IDENTITY:
return "UP";
default:
return "UK";
}
}
const char *SSL_alert_desc_string_long(int value)
{
switch (value & 0xff) {
case SSL3_AD_CLOSE_NOTIFY:
return "close notify";
case SSL3_AD_UNEXPECTED_MESSAGE:
return "unexpected_message";
case SSL3_AD_BAD_RECORD_MAC:
return "bad record mac";
case SSL3_AD_DECOMPRESSION_FAILURE:
return "decompression failure";
case SSL3_AD_HANDSHAKE_FAILURE:
return "handshake failure";
case SSL3_AD_NO_CERTIFICATE:
return "no certificate";
case SSL3_AD_BAD_CERTIFICATE:
return "bad certificate";
case SSL3_AD_UNSUPPORTED_CERTIFICATE:
return "unsupported certificate";
case SSL3_AD_CERTIFICATE_REVOKED:
return "certificate revoked";
case SSL3_AD_CERTIFICATE_EXPIRED:
return "certificate expired";
case SSL3_AD_CERTIFICATE_UNKNOWN:
return "certificate unknown";
case SSL3_AD_ILLEGAL_PARAMETER:
return "illegal parameter";
case TLS1_AD_DECRYPTION_FAILED:
return "decryption failed";
case TLS1_AD_RECORD_OVERFLOW:
return "record overflow";
case TLS1_AD_UNKNOWN_CA:
return "unknown CA";
case TLS1_AD_ACCESS_DENIED:
return "access denied";
case TLS1_AD_DECODE_ERROR:
return "decode error";
case TLS1_AD_DECRYPT_ERROR:
return "decrypt error";
case TLS1_AD_EXPORT_RESTRICTION:
return "export restriction";
case TLS1_AD_PROTOCOL_VERSION:
return "protocol version";
case TLS1_AD_INSUFFICIENT_SECURITY:
return "insufficient security";
case TLS1_AD_INTERNAL_ERROR:
return "internal error";
case TLS1_AD_USER_CANCELLED:
return "user canceled";
case TLS1_AD_NO_RENEGOTIATION:
return "no renegotiation";
case TLS1_AD_UNSUPPORTED_EXTENSION:
return "unsupported extension";
case TLS1_AD_CERTIFICATE_UNOBTAINABLE:
return "certificate unobtainable";
case TLS1_AD_UNRECOGNIZED_NAME:
return "unrecognized name";
case TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
return "bad certificate status response";
case TLS1_AD_BAD_CERTIFICATE_HASH_VALUE:
return "bad certificate hash value";
case TLS1_AD_UNKNOWN_PSK_IDENTITY:
return "unknown PSK identity";
case TLS1_AD_NO_APPLICATION_PROTOCOL:
return "no application protocol";
default:
return "unknown";
}
}
| 12,668 | 29.97555 | 74 | c |
openssl | openssl-master/ssl/ssl_txt.c | /*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright 2005 Nokia. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <openssl/buffer.h>
#include "ssl_local.h"
#ifndef OPENSSL_NO_STDIO
int SSL_SESSION_print_fp(FILE *fp, const SSL_SESSION *x)
{
BIO *b;
int ret;
if ((b = BIO_new(BIO_s_file())) == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB);
return 0;
}
BIO_set_fp(b, fp, BIO_NOCLOSE);
ret = SSL_SESSION_print(b, x);
BIO_free(b);
return ret;
}
#endif
int SSL_SESSION_print(BIO *bp, const SSL_SESSION *x)
{
size_t i;
const char *s;
int istls13;
if (x == NULL)
goto err;
istls13 = (x->ssl_version == TLS1_3_VERSION);
if (BIO_puts(bp, "SSL-Session:\n") <= 0)
goto err;
s = ssl_protocol_to_string(x->ssl_version);
if (BIO_printf(bp, " Protocol : %s\n", s) <= 0)
goto err;
if (x->cipher == NULL) {
if (((x->cipher_id) & 0xff000000) == 0x02000000) {
if (BIO_printf(bp, " Cipher : %06lX\n",
x->cipher_id & 0xffffff) <= 0)
goto err;
} else {
if (BIO_printf(bp, " Cipher : %04lX\n",
x->cipher_id & 0xffff) <= 0)
goto err;
}
} else {
if (BIO_printf(bp, " Cipher : %s\n",
((x->cipher->name == NULL) ? "unknown"
: x->cipher->name)) <= 0)
goto err;
}
if (BIO_puts(bp, " Session-ID: ") <= 0)
goto err;
for (i = 0; i < x->session_id_length; i++) {
if (BIO_printf(bp, "%02X", x->session_id[i]) <= 0)
goto err;
}
if (BIO_puts(bp, "\n Session-ID-ctx: ") <= 0)
goto err;
for (i = 0; i < x->sid_ctx_length; i++) {
if (BIO_printf(bp, "%02X", x->sid_ctx[i]) <= 0)
goto err;
}
if (istls13) {
if (BIO_puts(bp, "\n Resumption PSK: ") <= 0)
goto err;
} else if (BIO_puts(bp, "\n Master-Key: ") <= 0)
goto err;
for (i = 0; i < x->master_key_length; i++) {
if (BIO_printf(bp, "%02X", x->master_key[i]) <= 0)
goto err;
}
#ifndef OPENSSL_NO_PSK
if (BIO_puts(bp, "\n PSK identity: ") <= 0)
goto err;
if (BIO_printf(bp, "%s", x->psk_identity ? x->psk_identity : "None") <= 0)
goto err;
if (BIO_puts(bp, "\n PSK identity hint: ") <= 0)
goto err;
if (BIO_printf
(bp, "%s", x->psk_identity_hint ? x->psk_identity_hint : "None") <= 0)
goto err;
#endif
#ifndef OPENSSL_NO_SRP
if (BIO_puts(bp, "\n SRP username: ") <= 0)
goto err;
if (BIO_printf(bp, "%s", x->srp_username ? x->srp_username : "None") <= 0)
goto err;
#endif
if (x->ext.tick_lifetime_hint) {
if (BIO_printf(bp,
"\n TLS session ticket lifetime hint: %ld (seconds)",
x->ext.tick_lifetime_hint) <= 0)
goto err;
}
if (x->ext.tick) {
if (BIO_puts(bp, "\n TLS session ticket:\n") <= 0)
goto err;
if (BIO_dump_indent
(bp, (const char *)x->ext.tick, (int)x->ext.ticklen, 4)
<= 0)
goto err;
}
#ifndef OPENSSL_NO_COMP
if (x->compress_meth != 0) {
SSL_COMP *comp = NULL;
if (!ssl_cipher_get_evp(NULL, x, NULL, NULL, NULL, NULL, &comp, 0))
goto err;
if (comp == NULL) {
if (BIO_printf(bp, "\n Compression: %d", x->compress_meth) <= 0)
goto err;
} else {
if (BIO_printf(bp, "\n Compression: %d (%s)", comp->id,
comp->name) <= 0)
goto err;
}
}
#endif
if (!ossl_time_is_zero(x->time)) {
if (BIO_printf(bp, "\n Start Time: %lld",
(long long)ossl_time_to_time_t(x->time)) <= 0)
goto err;
}
if (!ossl_time_is_zero(x->timeout)) {
if (BIO_printf(bp, "\n Timeout : %lld (sec)",
(long long)ossl_time2seconds(x->timeout)) <= 0)
goto err;
}
if (BIO_puts(bp, "\n") <= 0)
goto err;
if (BIO_puts(bp, " Verify return code: ") <= 0)
goto err;
if (BIO_printf(bp, "%ld (%s)\n", x->verify_result,
X509_verify_cert_error_string(x->verify_result)) <= 0)
goto err;
if (BIO_printf(bp, " Extended master secret: %s\n",
x->flags & SSL_SESS_FLAG_EXTMS ? "yes" : "no") <= 0)
goto err;
if (istls13) {
if (BIO_printf(bp, " Max Early Data: %u\n",
(unsigned int)x->ext.max_early_data) <= 0)
goto err;
}
return 1;
err:
return 0;
}
/*
* print session id and master key in NSS keylog format (RSA
* Session-ID:<session id> Master-Key:<master key>)
*/
int SSL_SESSION_print_keylog(BIO *bp, const SSL_SESSION *x)
{
size_t i;
if (x == NULL)
goto err;
if (x->session_id_length == 0 || x->master_key_length == 0)
goto err;
/*
* the RSA prefix is required by the format's definition although there's
* nothing RSA-specific in the output, therefore, we don't have to check if
* the cipher suite is based on RSA
*/
if (BIO_puts(bp, "RSA ") <= 0)
goto err;
if (BIO_puts(bp, "Session-ID:") <= 0)
goto err;
for (i = 0; i < x->session_id_length; i++) {
if (BIO_printf(bp, "%02X", x->session_id[i]) <= 0)
goto err;
}
if (BIO_puts(bp, " Master-Key:") <= 0)
goto err;
for (i = 0; i < x->master_key_length; i++) {
if (BIO_printf(bp, "%02X", x->master_key[i]) <= 0)
goto err;
}
if (BIO_puts(bp, "\n") <= 0)
goto err;
return 1;
err:
return 0;
}
| 6,158 | 29.043902 | 79 | c |
openssl | openssl-master/ssl/ssl_utst.c | /*
* Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "ssl_local.h"
#ifndef OPENSSL_NO_UNIT_TEST
static const struct openssl_ssl_test_functions ssl_test_functions = {
ssl_init_wbio_buffer,
};
const struct openssl_ssl_test_functions *SSL_test_functions(void)
{
return &ssl_test_functions;
}
#endif
| 601 | 24.083333 | 74 | c |
openssl | openssl-master/ssl/sslerr.h | /*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 2020-2023 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_SSLERR_H
# define OSSL_SSLERR_H
# pragma once
# include <openssl/opensslconf.h>
# include <openssl/symhacks.h>
# ifdef __cplusplus
extern "C" {
# endif
int ossl_err_load_SSL_strings(void);
# ifdef __cplusplus
}
# endif
#endif
| 624 | 21.321429 | 74 | h |
openssl | openssl-master/ssl/t1_enc.c | /*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright 2005 Nokia. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "ssl_local.h"
#include "record/record_local.h"
#include "internal/ktls.h"
#include "internal/cryptlib.h"
#include <openssl/comp.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/rand.h>
#include <openssl/obj_mac.h>
#include <openssl/core_names.h>
#include <openssl/trace.h>
/* seed1 through seed5 are concatenated */
static int tls1_PRF(SSL_CONNECTION *s,
const void *seed1, size_t seed1_len,
const void *seed2, size_t seed2_len,
const void *seed3, size_t seed3_len,
const void *seed4, size_t seed4_len,
const void *seed5, size_t seed5_len,
const unsigned char *sec, size_t slen,
unsigned char *out, size_t olen, int fatal)
{
const EVP_MD *md = ssl_prf_md(s);
EVP_KDF *kdf;
EVP_KDF_CTX *kctx = NULL;
OSSL_PARAM params[8], *p = params;
const char *mdname;
if (md == NULL) {
/* Should never happen */
if (fatal)
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
else
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return 0;
}
kdf = EVP_KDF_fetch(SSL_CONNECTION_GET_CTX(s)->libctx,
OSSL_KDF_NAME_TLS1_PRF,
SSL_CONNECTION_GET_CTX(s)->propq);
if (kdf == NULL)
goto err;
kctx = EVP_KDF_CTX_new(kdf);
EVP_KDF_free(kdf);
if (kctx == NULL)
goto err;
mdname = EVP_MD_get0_name(md);
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
(char *)mdname, 0);
*p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SECRET,
(unsigned char *)sec,
(size_t)slen);
*p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SEED,
(void *)seed1, (size_t)seed1_len);
*p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SEED,
(void *)seed2, (size_t)seed2_len);
*p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SEED,
(void *)seed3, (size_t)seed3_len);
*p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SEED,
(void *)seed4, (size_t)seed4_len);
*p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SEED,
(void *)seed5, (size_t)seed5_len);
*p = OSSL_PARAM_construct_end();
if (EVP_KDF_derive(kctx, out, olen, params)) {
EVP_KDF_CTX_free(kctx);
return 1;
}
err:
if (fatal)
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
else
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
EVP_KDF_CTX_free(kctx);
return 0;
}
static int tls1_generate_key_block(SSL_CONNECTION *s, unsigned char *km,
size_t num)
{
int ret;
/* Calls SSLfatal() as required */
ret = tls1_PRF(s,
TLS_MD_KEY_EXPANSION_CONST,
TLS_MD_KEY_EXPANSION_CONST_SIZE, s->s3.server_random,
SSL3_RANDOM_SIZE, s->s3.client_random, SSL3_RANDOM_SIZE,
NULL, 0, NULL, 0, s->session->master_key,
s->session->master_key_length, km, num, 1);
return ret;
}
int tls_provider_set_tls_params(SSL_CONNECTION *s, EVP_CIPHER_CTX *ctx,
const EVP_CIPHER *ciph,
const EVP_MD *md)
{
/*
* Provided cipher, the TLS padding/MAC removal is performed provider
* side so we need to tell the ctx about our TLS version and mac size
*/
OSSL_PARAM params[3], *pprm = params;
size_t macsize = 0;
int imacsize = -1;
if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
/*
* We look at s->ext.use_etm instead of SSL_READ_ETM() or
* SSL_WRITE_ETM() because this test applies to both reading
* and writing.
*/
&& !s->ext.use_etm)
imacsize = EVP_MD_get_size(md);
if (imacsize >= 0)
macsize = (size_t)imacsize;
*pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
&s->version);
*pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
&macsize);
*pprm = OSSL_PARAM_construct_end();
if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
static int tls_iv_length_within_key_block(const EVP_CIPHER *c)
{
/* If GCM/CCM mode only part of IV comes from PRF */
if (EVP_CIPHER_get_mode(c) == EVP_CIPH_GCM_MODE)
return EVP_GCM_TLS_FIXED_IV_LEN;
else if (EVP_CIPHER_get_mode(c) == EVP_CIPH_CCM_MODE)
return EVP_CCM_TLS_FIXED_IV_LEN;
else
return EVP_CIPHER_get_iv_length(c);
}
int tls1_change_cipher_state(SSL_CONNECTION *s, int which)
{
unsigned char *p, *mac_secret;
unsigned char *key, *iv;
const EVP_CIPHER *c;
const SSL_COMP *comp = NULL;
const EVP_MD *m;
int mac_type;
size_t mac_secret_size;
size_t n, i, j, k, cl;
int iivlen;
/*
* Taglen is only relevant for CCM ciphersuites. Other ciphersuites
* ignore this value so we can default it to 0.
*/
size_t taglen = 0;
int direction;
c = s->s3.tmp.new_sym_enc;
m = s->s3.tmp.new_hash;
mac_type = s->s3.tmp.new_mac_pkey_type;
#ifndef OPENSSL_NO_COMP
comp = s->s3.tmp.new_compression;
#endif
p = s->s3.tmp.key_block;
i = mac_secret_size = s->s3.tmp.new_mac_secret_size;
cl = EVP_CIPHER_get_key_length(c);
j = cl;
iivlen = tls_iv_length_within_key_block(c);
if (iivlen < 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
k = iivlen;
if ((which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
(which == SSL3_CHANGE_CIPHER_SERVER_READ)) {
mac_secret = &(p[0]);
n = i + i;
key = &(p[n]);
n += j + j;
iv = &(p[n]);
n += k + k;
} else {
n = i;
mac_secret = &(p[n]);
n += i + j;
key = &(p[n]);
n += j + k;
iv = &(p[n]);
n += k;
}
if (n > s->s3.tmp.key_block_length) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
switch (EVP_CIPHER_get_mode(c)) {
case EVP_CIPH_GCM_MODE:
taglen = EVP_GCM_TLS_TAG_LEN;
break;
case EVP_CIPH_CCM_MODE:
if ((s->s3.tmp.new_cipher->algorithm_enc
& (SSL_AES128CCM8 | SSL_AES256CCM8)) != 0)
taglen = EVP_CCM8_TLS_TAG_LEN;
else
taglen = EVP_CCM_TLS_TAG_LEN;
break;
default:
if (EVP_CIPHER_is_a(c, "CHACHA20-POLY1305")) {
taglen = EVP_CHACHAPOLY_TLS_TAG_LEN;
} else {
/* MAC secret size corresponds to the MAC output size */
taglen = s->s3.tmp.new_mac_secret_size;
}
break;
}
if (which & SSL3_CC_READ) {
if (s->ext.use_etm)
s->s3.flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC_READ;
else
s->s3.flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC_READ;
if (s->s3.tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
else
s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
if (s->s3.tmp.new_cipher->algorithm2 & TLS1_TLSTREE)
s->mac_flags |= SSL_MAC_FLAG_READ_MAC_TLSTREE;
else
s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_TLSTREE;
direction = OSSL_RECORD_DIRECTION_READ;
} else {
if (s->ext.use_etm)
s->s3.flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC_WRITE;
else
s->s3.flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC_WRITE;
if (s->s3.tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM;
else
s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM;
if (s->s3.tmp.new_cipher->algorithm2 & TLS1_TLSTREE)
s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_TLSTREE;
else
s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_TLSTREE;
direction = OSSL_RECORD_DIRECTION_WRITE;
}
if (!ssl_set_new_record_layer(s, s->version, direction,
OSSL_RECORD_PROTECTION_LEVEL_APPLICATION,
NULL, 0, key, cl, iv, (size_t)k, mac_secret,
mac_secret_size, c, taglen, mac_type,
m, comp, NULL)) {
/* SSLfatal already called */
goto err;
}
OSSL_TRACE_BEGIN(TLS) {
BIO_printf(trc_out, "which = %04X, key:\n", which);
BIO_dump_indent(trc_out, key, EVP_CIPHER_get_key_length(c), 4);
BIO_printf(trc_out, "iv:\n");
BIO_dump_indent(trc_out, iv, k, 4);
} OSSL_TRACE_END(TLS);
return 1;
err:
return 0;
}
int tls1_setup_key_block(SSL_CONNECTION *s)
{
unsigned char *p;
const EVP_CIPHER *c;
const EVP_MD *hash;
SSL_COMP *comp;
int mac_type = NID_undef;
size_t num, mac_secret_size = 0;
int ret = 0;
int ivlen;
if (s->s3.tmp.key_block_length != 0)
return 1;
if (!ssl_cipher_get_evp(SSL_CONNECTION_GET_CTX(s), s->session, &c, &hash,
&mac_type, &mac_secret_size, &comp,
s->ext.use_etm)) {
/* Error is already recorded */
SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
return 0;
}
ssl_evp_cipher_free(s->s3.tmp.new_sym_enc);
s->s3.tmp.new_sym_enc = c;
ssl_evp_md_free(s->s3.tmp.new_hash);
s->s3.tmp.new_hash = hash;
s->s3.tmp.new_mac_pkey_type = mac_type;
s->s3.tmp.new_mac_secret_size = mac_secret_size;
ivlen = tls_iv_length_within_key_block(c);
if (ivlen < 0) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
num = mac_secret_size + EVP_CIPHER_get_key_length(c) + ivlen;
num *= 2;
ssl3_cleanup_key_block(s);
if ((p = OPENSSL_malloc(num)) == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
goto err;
}
s->s3.tmp.key_block_length = num;
s->s3.tmp.key_block = p;
OSSL_TRACE_BEGIN(TLS) {
BIO_printf(trc_out, "key block length: %zu\n", num);
BIO_printf(trc_out, "client random\n");
BIO_dump_indent(trc_out, s->s3.client_random, SSL3_RANDOM_SIZE, 4);
BIO_printf(trc_out, "server random\n");
BIO_dump_indent(trc_out, s->s3.server_random, SSL3_RANDOM_SIZE, 4);
BIO_printf(trc_out, "master key\n");
BIO_dump_indent(trc_out,
s->session->master_key,
s->session->master_key_length, 4);
} OSSL_TRACE_END(TLS);
if (!tls1_generate_key_block(s, p, num)) {
/* SSLfatal() already called */
goto err;
}
OSSL_TRACE_BEGIN(TLS) {
BIO_printf(trc_out, "key block\n");
BIO_dump_indent(trc_out, p, num, 4);
} OSSL_TRACE_END(TLS);
ret = 1;
err:
return ret;
}
size_t tls1_final_finish_mac(SSL_CONNECTION *s, const char *str,
size_t slen, unsigned char *out)
{
size_t hashlen;
unsigned char hash[EVP_MAX_MD_SIZE];
size_t finished_size = TLS1_FINISH_MAC_LENGTH;
if (s->s3.tmp.new_cipher->algorithm_mkey & SSL_kGOST18)
finished_size = 32;
if (!ssl3_digest_cached_records(s, 0)) {
/* SSLfatal() already called */
return 0;
}
if (!ssl_handshake_hash(s, hash, sizeof(hash), &hashlen)) {
/* SSLfatal() already called */
return 0;
}
if (!tls1_PRF(s, str, slen, hash, hashlen, NULL, 0, NULL, 0, NULL, 0,
s->session->master_key, s->session->master_key_length,
out, finished_size, 1)) {
/* SSLfatal() already called */
return 0;
}
OPENSSL_cleanse(hash, hashlen);
return finished_size;
}
int tls1_generate_master_secret(SSL_CONNECTION *s, unsigned char *out,
unsigned char *p, size_t len,
size_t *secret_size)
{
if (s->session->flags & SSL_SESS_FLAG_EXTMS) {
unsigned char hash[EVP_MAX_MD_SIZE * 2];
size_t hashlen;
/*
* Digest cached records keeping record buffer (if present): this won't
* affect client auth because we're freezing the buffer at the same
* point (after client key exchange and before certificate verify)
*/
if (!ssl3_digest_cached_records(s, 1)
|| !ssl_handshake_hash(s, hash, sizeof(hash), &hashlen)) {
/* SSLfatal() already called */
return 0;
}
OSSL_TRACE_BEGIN(TLS) {
BIO_printf(trc_out, "Handshake hashes:\n");
BIO_dump(trc_out, (char *)hash, hashlen);
} OSSL_TRACE_END(TLS);
if (!tls1_PRF(s,
TLS_MD_EXTENDED_MASTER_SECRET_CONST,
TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE,
hash, hashlen,
NULL, 0,
NULL, 0,
NULL, 0, p, len, out,
SSL3_MASTER_SECRET_SIZE, 1)) {
/* SSLfatal() already called */
return 0;
}
OPENSSL_cleanse(hash, hashlen);
} else {
if (!tls1_PRF(s,
TLS_MD_MASTER_SECRET_CONST,
TLS_MD_MASTER_SECRET_CONST_SIZE,
s->s3.client_random, SSL3_RANDOM_SIZE,
NULL, 0,
s->s3.server_random, SSL3_RANDOM_SIZE,
NULL, 0, p, len, out,
SSL3_MASTER_SECRET_SIZE, 1)) {
/* SSLfatal() already called */
return 0;
}
}
OSSL_TRACE_BEGIN(TLS) {
BIO_printf(trc_out, "Premaster Secret:\n");
BIO_dump_indent(trc_out, p, len, 4);
BIO_printf(trc_out, "Client Random:\n");
BIO_dump_indent(trc_out, s->s3.client_random, SSL3_RANDOM_SIZE, 4);
BIO_printf(trc_out, "Server Random:\n");
BIO_dump_indent(trc_out, s->s3.server_random, SSL3_RANDOM_SIZE, 4);
BIO_printf(trc_out, "Master Secret:\n");
BIO_dump_indent(trc_out,
s->session->master_key,
SSL3_MASTER_SECRET_SIZE, 4);
} OSSL_TRACE_END(TLS);
*secret_size = SSL3_MASTER_SECRET_SIZE;
return 1;
}
int tls1_export_keying_material(SSL_CONNECTION *s, unsigned char *out,
size_t olen, const char *label, size_t llen,
const unsigned char *context,
size_t contextlen, int use_context)
{
unsigned char *val = NULL;
size_t vallen = 0, currentvalpos;
int rv = 0;
/*
* construct PRF arguments we construct the PRF argument ourself rather
* than passing separate values into the TLS PRF to ensure that the
* concatenation of values does not create a prohibited label.
*/
vallen = llen + SSL3_RANDOM_SIZE * 2;
if (use_context) {
vallen += 2 + contextlen;
}
val = OPENSSL_malloc(vallen);
if (val == NULL)
goto ret;
currentvalpos = 0;
memcpy(val + currentvalpos, (unsigned char *)label, llen);
currentvalpos += llen;
memcpy(val + currentvalpos, s->s3.client_random, SSL3_RANDOM_SIZE);
currentvalpos += SSL3_RANDOM_SIZE;
memcpy(val + currentvalpos, s->s3.server_random, SSL3_RANDOM_SIZE);
currentvalpos += SSL3_RANDOM_SIZE;
if (use_context) {
val[currentvalpos] = (contextlen >> 8) & 0xff;
currentvalpos++;
val[currentvalpos] = contextlen & 0xff;
currentvalpos++;
if ((contextlen > 0) || (context != NULL)) {
memcpy(val + currentvalpos, context, contextlen);
}
}
/*
* disallow prohibited labels note that SSL3_RANDOM_SIZE > max(prohibited
* label len) = 15, so size of val > max(prohibited label len) = 15 and
* the comparisons won't have buffer overflow
*/
if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0)
goto err1;
if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
TLS_MD_SERVER_FINISH_CONST_SIZE) == 0)
goto err1;
if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
TLS_MD_MASTER_SECRET_CONST_SIZE) == 0)
goto err1;
if (memcmp(val, TLS_MD_EXTENDED_MASTER_SECRET_CONST,
TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE) == 0)
goto err1;
if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0)
goto err1;
rv = tls1_PRF(s,
val, vallen,
NULL, 0,
NULL, 0,
NULL, 0,
NULL, 0,
s->session->master_key, s->session->master_key_length,
out, olen, 0);
goto ret;
err1:
ERR_raise(ERR_LIB_SSL, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
ret:
OPENSSL_clear_free(val, vallen);
return rv;
}
int tls1_alert_code(int code)
{
switch (code) {
case SSL_AD_CLOSE_NOTIFY:
return SSL3_AD_CLOSE_NOTIFY;
case SSL_AD_UNEXPECTED_MESSAGE:
return SSL3_AD_UNEXPECTED_MESSAGE;
case SSL_AD_BAD_RECORD_MAC:
return SSL3_AD_BAD_RECORD_MAC;
case SSL_AD_DECRYPTION_FAILED:
return TLS1_AD_DECRYPTION_FAILED;
case SSL_AD_RECORD_OVERFLOW:
return TLS1_AD_RECORD_OVERFLOW;
case SSL_AD_DECOMPRESSION_FAILURE:
return SSL3_AD_DECOMPRESSION_FAILURE;
case SSL_AD_HANDSHAKE_FAILURE:
return SSL3_AD_HANDSHAKE_FAILURE;
case SSL_AD_NO_CERTIFICATE:
return -1;
case SSL_AD_BAD_CERTIFICATE:
return SSL3_AD_BAD_CERTIFICATE;
case SSL_AD_UNSUPPORTED_CERTIFICATE:
return SSL3_AD_UNSUPPORTED_CERTIFICATE;
case SSL_AD_CERTIFICATE_REVOKED:
return SSL3_AD_CERTIFICATE_REVOKED;
case SSL_AD_CERTIFICATE_EXPIRED:
return SSL3_AD_CERTIFICATE_EXPIRED;
case SSL_AD_CERTIFICATE_UNKNOWN:
return SSL3_AD_CERTIFICATE_UNKNOWN;
case SSL_AD_ILLEGAL_PARAMETER:
return SSL3_AD_ILLEGAL_PARAMETER;
case SSL_AD_UNKNOWN_CA:
return TLS1_AD_UNKNOWN_CA;
case SSL_AD_ACCESS_DENIED:
return TLS1_AD_ACCESS_DENIED;
case SSL_AD_DECODE_ERROR:
return TLS1_AD_DECODE_ERROR;
case SSL_AD_DECRYPT_ERROR:
return TLS1_AD_DECRYPT_ERROR;
case SSL_AD_EXPORT_RESTRICTION:
return TLS1_AD_EXPORT_RESTRICTION;
case SSL_AD_PROTOCOL_VERSION:
return TLS1_AD_PROTOCOL_VERSION;
case SSL_AD_INSUFFICIENT_SECURITY:
return TLS1_AD_INSUFFICIENT_SECURITY;
case SSL_AD_INTERNAL_ERROR:
return TLS1_AD_INTERNAL_ERROR;
case SSL_AD_USER_CANCELLED:
return TLS1_AD_USER_CANCELLED;
case SSL_AD_NO_RENEGOTIATION:
return TLS1_AD_NO_RENEGOTIATION;
case SSL_AD_UNSUPPORTED_EXTENSION:
return TLS1_AD_UNSUPPORTED_EXTENSION;
case SSL_AD_CERTIFICATE_UNOBTAINABLE:
return TLS1_AD_CERTIFICATE_UNOBTAINABLE;
case SSL_AD_UNRECOGNIZED_NAME:
return TLS1_AD_UNRECOGNIZED_NAME;
case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
return TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
return TLS1_AD_BAD_CERTIFICATE_HASH_VALUE;
case SSL_AD_UNKNOWN_PSK_IDENTITY:
return TLS1_AD_UNKNOWN_PSK_IDENTITY;
case SSL_AD_INAPPROPRIATE_FALLBACK:
return TLS1_AD_INAPPROPRIATE_FALLBACK;
case SSL_AD_NO_APPLICATION_PROTOCOL:
return TLS1_AD_NO_APPLICATION_PROTOCOL;
case SSL_AD_CERTIFICATE_REQUIRED:
return SSL_AD_HANDSHAKE_FAILURE;
case TLS13_AD_MISSING_EXTENSION:
return SSL_AD_HANDSHAKE_FAILURE;
default:
return -1;
}
}
| 20,662 | 32.87377 | 80 | c |
openssl | openssl-master/ssl/tls_depr.c | /*
* Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* We need to use some engine and HMAC deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <openssl/engine.h>
#include "ssl_local.h"
/*
* Engine APIs are only used to support applications that still use ENGINEs.
* Once ENGINE is removed completely, all of this code can also be removed.
*/
#ifndef OPENSSL_NO_ENGINE
void tls_engine_finish(ENGINE *e)
{
ENGINE_finish(e);
}
#endif
const EVP_CIPHER *tls_get_cipher_from_engine(int nid)
{
const EVP_CIPHER *ret = NULL;
#ifndef OPENSSL_NO_ENGINE
ENGINE *eng;
/*
* If there is an Engine available for this cipher we use the "implicit"
* form to ensure we use that engine later.
*/
eng = ENGINE_get_cipher_engine(nid);
if (eng != NULL) {
ret = ENGINE_get_cipher(eng, nid);
ENGINE_finish(eng);
}
#endif
return ret;
}
const EVP_MD *tls_get_digest_from_engine(int nid)
{
const EVP_MD *ret = NULL;
#ifndef OPENSSL_NO_ENGINE
ENGINE *eng;
/*
* If there is an Engine available for this digest we use the "implicit"
* form to ensure we use that engine later.
*/
eng = ENGINE_get_digest_engine(nid);
if (eng != NULL) {
ret = ENGINE_get_digest(eng, nid);
ENGINE_finish(eng);
}
#endif
return ret;
}
#ifndef OPENSSL_NO_ENGINE
int tls_engine_load_ssl_client_cert(SSL_CONNECTION *s, X509 **px509,
EVP_PKEY **ppkey)
{
SSL *ssl = SSL_CONNECTION_GET_SSL(s);
return ENGINE_load_ssl_client_cert(SSL_CONNECTION_GET_CTX(s)->client_cert_engine,
ssl,
SSL_get_client_CA_list(ssl),
px509, ppkey, NULL, NULL, NULL);
}
#endif
#ifndef OPENSSL_NO_ENGINE
int SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e)
{
if (!ENGINE_init(e)) {
ERR_raise(ERR_LIB_SSL, ERR_R_ENGINE_LIB);
return 0;
}
if (!ENGINE_get_ssl_client_cert_function(e)) {
ERR_raise(ERR_LIB_SSL, SSL_R_NO_CLIENT_CERT_METHOD);
ENGINE_finish(e);
return 0;
}
ctx->client_cert_engine = e;
return 1;
}
#endif
/*
* The HMAC APIs below are only used to support the deprecated public API
* macro SSL_CTX_set_tlsext_ticket_key_cb(). The application supplied callback
* takes an HMAC_CTX in its argument list. The preferred alternative is
* SSL_CTX_set_tlsext_ticket_key_evp_cb(). Once
* SSL_CTX_set_tlsext_ticket_key_cb() is removed, then all of this code can also
* be removed.
*/
#ifndef OPENSSL_NO_DEPRECATED_3_0
int ssl_hmac_old_new(SSL_HMAC *ret)
{
ret->old_ctx = HMAC_CTX_new();
if (ret->old_ctx == NULL)
return 0;
return 1;
}
void ssl_hmac_old_free(SSL_HMAC *ctx)
{
HMAC_CTX_free(ctx->old_ctx);
}
int ssl_hmac_old_init(SSL_HMAC *ctx, void *key, size_t len, char *md)
{
return HMAC_Init_ex(ctx->old_ctx, key, len, EVP_get_digestbyname(md), NULL);
}
int ssl_hmac_old_update(SSL_HMAC *ctx, const unsigned char *data, size_t len)
{
return HMAC_Update(ctx->old_ctx, data, len);
}
int ssl_hmac_old_final(SSL_HMAC *ctx, unsigned char *md, size_t *len)
{
unsigned int l;
if (HMAC_Final(ctx->old_ctx, md, &l) > 0) {
if (len != NULL)
*len = l;
return 1;
}
return 0;
}
size_t ssl_hmac_old_size(const SSL_HMAC *ctx)
{
return HMAC_size(ctx->old_ctx);
}
HMAC_CTX *ssl_hmac_get0_HMAC_CTX(SSL_HMAC *ctx)
{
return ctx->old_ctx;
}
/* Some deprecated public APIs pass DH objects */
EVP_PKEY *ssl_dh_to_pkey(DH *dh)
{
# ifndef OPENSSL_NO_DH
EVP_PKEY *ret;
if (dh == NULL)
return NULL;
ret = EVP_PKEY_new();
if (EVP_PKEY_set1_DH(ret, dh) <= 0) {
EVP_PKEY_free(ret);
return NULL;
}
return ret;
# else
return NULL;
# endif
}
/* Some deprecated public APIs pass EC_KEY objects */
int ssl_set_tmp_ecdh_groups(uint16_t **pext, size_t *pextlen,
void *key)
{
# ifndef OPENSSL_NO_EC
const EC_GROUP *group = EC_KEY_get0_group((const EC_KEY *)key);
int nid;
if (group == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_MISSING_PARAMETERS);
return 0;
}
nid = EC_GROUP_get_curve_name(group);
if (nid == NID_undef)
return 0;
return tls1_set_groups(pext, pextlen, &nid, 1);
# else
return 0;
# endif
}
/*
* Set the callback for generating temporary DH keys.
* ctx: the SSL context.
* dh: the callback
*/
# if !defined(OPENSSL_NO_DH)
void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
DH *(*dh) (SSL *ssl, int is_export,
int keylength))
{
SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
}
void SSL_set_tmp_dh_callback(SSL *ssl, DH *(*dh) (SSL *ssl, int is_export,
int keylength))
{
SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
}
# endif
#endif /* OPENSSL_NO_DEPRECATED */
| 5,340 | 24.193396 | 85 | c |
openssl | openssl-master/ssl/tls_srp.c | /*
* Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2004, EdelKey Project. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*
* Originally written by Christophe Renou and Peter Sylvester,
* for the EdelKey project.
*/
/*
* We need to use the SRP deprecated APIs in order to implement the SSL SRP
* APIs - which are themselves deprecated.
*/
#define OPENSSL_SUPPRESS_DEPRECATED
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include "ssl_local.h"
#ifndef OPENSSL_NO_SRP
# include <openssl/srp.h>
/*
* The public API SSL_CTX_SRP_CTX_free() is deprecated so we use
* ssl_ctx_srp_ctx_free_intern() internally.
*/
int ssl_ctx_srp_ctx_free_intern(SSL_CTX *ctx)
{
if (ctx == NULL)
return 0;
OPENSSL_free(ctx->srp_ctx.login);
OPENSSL_free(ctx->srp_ctx.info);
BN_free(ctx->srp_ctx.N);
BN_free(ctx->srp_ctx.g);
BN_free(ctx->srp_ctx.s);
BN_free(ctx->srp_ctx.B);
BN_free(ctx->srp_ctx.A);
BN_free(ctx->srp_ctx.a);
BN_free(ctx->srp_ctx.b);
BN_free(ctx->srp_ctx.v);
memset(&ctx->srp_ctx, 0, sizeof(ctx->srp_ctx));
ctx->srp_ctx.strength = SRP_MINIMAL_N;
return 1;
}
int SSL_CTX_SRP_CTX_free(SSL_CTX *ctx)
{
return ssl_ctx_srp_ctx_free_intern(ctx);
}
/*
* The public API SSL_SRP_CTX_free() is deprecated so we use
* ssl_srp_ctx_free_intern() internally.
*/
int ssl_srp_ctx_free_intern(SSL_CONNECTION *s)
{
if (s == NULL)
return 0;
OPENSSL_free(s->srp_ctx.login);
OPENSSL_free(s->srp_ctx.info);
BN_free(s->srp_ctx.N);
BN_free(s->srp_ctx.g);
BN_free(s->srp_ctx.s);
BN_free(s->srp_ctx.B);
BN_free(s->srp_ctx.A);
BN_free(s->srp_ctx.a);
BN_free(s->srp_ctx.b);
BN_free(s->srp_ctx.v);
memset(&s->srp_ctx, 0, sizeof(s->srp_ctx));
s->srp_ctx.strength = SRP_MINIMAL_N;
return 1;
}
int SSL_SRP_CTX_free(SSL *s)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
/* the call works with NULL sc */
return ssl_srp_ctx_free_intern(sc);
}
/*
* The public API SSL_SRP_CTX_init() is deprecated so we use
* ssl_srp_ctx_init_intern() internally.
*/
int ssl_srp_ctx_init_intern(SSL_CONNECTION *s)
{
SSL_CTX *ctx;
if (s == NULL || (ctx = SSL_CONNECTION_GET_CTX(s)) == NULL)
return 0;
memset(&s->srp_ctx, 0, sizeof(s->srp_ctx));
s->srp_ctx.SRP_cb_arg = ctx->srp_ctx.SRP_cb_arg;
/* set client Hello login callback */
s->srp_ctx.TLS_ext_srp_username_callback =
ctx->srp_ctx.TLS_ext_srp_username_callback;
/* set SRP N/g param callback for verification */
s->srp_ctx.SRP_verify_param_callback =
ctx->srp_ctx.SRP_verify_param_callback;
/* set SRP client passwd callback */
s->srp_ctx.SRP_give_srp_client_pwd_callback =
ctx->srp_ctx.SRP_give_srp_client_pwd_callback;
s->srp_ctx.strength = ctx->srp_ctx.strength;
if (((ctx->srp_ctx.N != NULL) &&
((s->srp_ctx.N = BN_dup(ctx->srp_ctx.N)) == NULL)) ||
((ctx->srp_ctx.g != NULL) &&
((s->srp_ctx.g = BN_dup(ctx->srp_ctx.g)) == NULL)) ||
((ctx->srp_ctx.s != NULL) &&
((s->srp_ctx.s = BN_dup(ctx->srp_ctx.s)) == NULL)) ||
((ctx->srp_ctx.B != NULL) &&
((s->srp_ctx.B = BN_dup(ctx->srp_ctx.B)) == NULL)) ||
((ctx->srp_ctx.A != NULL) &&
((s->srp_ctx.A = BN_dup(ctx->srp_ctx.A)) == NULL)) ||
((ctx->srp_ctx.a != NULL) &&
((s->srp_ctx.a = BN_dup(ctx->srp_ctx.a)) == NULL)) ||
((ctx->srp_ctx.v != NULL) &&
((s->srp_ctx.v = BN_dup(ctx->srp_ctx.v)) == NULL)) ||
((ctx->srp_ctx.b != NULL) &&
((s->srp_ctx.b = BN_dup(ctx->srp_ctx.b)) == NULL))) {
ERR_raise(ERR_LIB_SSL, ERR_R_BN_LIB);
goto err;
}
if ((ctx->srp_ctx.login != NULL) &&
((s->srp_ctx.login = OPENSSL_strdup(ctx->srp_ctx.login)) == NULL)) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
goto err;
}
if ((ctx->srp_ctx.info != NULL) &&
((s->srp_ctx.info = OPENSSL_strdup(ctx->srp_ctx.info)) == NULL)) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
goto err;
}
s->srp_ctx.srp_Mask = ctx->srp_ctx.srp_Mask;
return 1;
err:
OPENSSL_free(s->srp_ctx.login);
OPENSSL_free(s->srp_ctx.info);
BN_free(s->srp_ctx.N);
BN_free(s->srp_ctx.g);
BN_free(s->srp_ctx.s);
BN_free(s->srp_ctx.B);
BN_free(s->srp_ctx.A);
BN_free(s->srp_ctx.a);
BN_free(s->srp_ctx.b);
BN_free(s->srp_ctx.v);
memset(&s->srp_ctx, 0, sizeof(s->srp_ctx));
return 0;
}
int SSL_SRP_CTX_init(SSL *s)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
/* the call works with NULL sc */
return ssl_srp_ctx_init_intern(sc);
}
/*
* The public API SSL_CTX_SRP_CTX_init() is deprecated so we use
* ssl_ctx_srp_ctx_init_intern() internally.
*/
int ssl_ctx_srp_ctx_init_intern(SSL_CTX *ctx)
{
if (ctx == NULL)
return 0;
memset(&ctx->srp_ctx, 0, sizeof(ctx->srp_ctx));
ctx->srp_ctx.strength = SRP_MINIMAL_N;
return 1;
}
int SSL_CTX_SRP_CTX_init(SSL_CTX *ctx)
{
return ssl_ctx_srp_ctx_init_intern(ctx);
}
/* server side */
/*
* The public API SSL_srp_server_param_with_username() is deprecated so we use
* ssl_srp_server_param_with_username_intern() internally.
*/
int ssl_srp_server_param_with_username_intern(SSL_CONNECTION *s, int *ad)
{
unsigned char b[SSL_MAX_MASTER_KEY_LENGTH];
int al;
SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
*ad = SSL_AD_UNKNOWN_PSK_IDENTITY;
if ((s->srp_ctx.TLS_ext_srp_username_callback != NULL) &&
((al =
s->srp_ctx.TLS_ext_srp_username_callback(SSL_CONNECTION_GET_SSL(s),
ad,
s->srp_ctx.SRP_cb_arg)) !=
SSL_ERROR_NONE))
return al;
*ad = SSL_AD_INTERNAL_ERROR;
if ((s->srp_ctx.N == NULL) ||
(s->srp_ctx.g == NULL) ||
(s->srp_ctx.s == NULL) || (s->srp_ctx.v == NULL))
return SSL3_AL_FATAL;
if (RAND_priv_bytes_ex(SSL_CONNECTION_GET_CTX(s)->libctx, b, sizeof(b),
0) <= 0)
return SSL3_AL_FATAL;
s->srp_ctx.b = BN_bin2bn(b, sizeof(b), NULL);
OPENSSL_cleanse(b, sizeof(b));
/* Calculate: B = (kv + g^b) % N */
return ((s->srp_ctx.B =
SRP_Calc_B_ex(s->srp_ctx.b, s->srp_ctx.N, s->srp_ctx.g,
s->srp_ctx.v, sctx->libctx, sctx->propq)) !=
NULL) ? SSL_ERROR_NONE : SSL3_AL_FATAL;
}
int SSL_srp_server_param_with_username(SSL *s, int *ad)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
if (sc == NULL)
return SSL3_AL_FATAL;
return ssl_srp_server_param_with_username_intern(sc, ad);
}
/*
* If the server just has the raw password, make up a verifier entry on the
* fly
*/
int SSL_set_srp_server_param_pw(SSL *s, const char *user, const char *pass,
const char *grp)
{
SRP_gN *GN;
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
if (sc == NULL)
return -1;
GN = SRP_get_default_gN(grp);
if (GN == NULL)
return -1;
sc->srp_ctx.N = BN_dup(GN->N);
sc->srp_ctx.g = BN_dup(GN->g);
BN_clear_free(sc->srp_ctx.v);
sc->srp_ctx.v = NULL;
BN_clear_free(sc->srp_ctx.s);
sc->srp_ctx.s = NULL;
if (!SRP_create_verifier_BN_ex(user, pass, &sc->srp_ctx.s, &sc->srp_ctx.v,
sc->srp_ctx.N, sc->srp_ctx.g, s->ctx->libctx,
s->ctx->propq))
return -1;
return 1;
}
int SSL_set_srp_server_param(SSL *s, const BIGNUM *N, const BIGNUM *g,
BIGNUM *sa, BIGNUM *v, char *info)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
if (sc == NULL)
return -1;
if (N != NULL) {
if (sc->srp_ctx.N != NULL) {
if (!BN_copy(sc->srp_ctx.N, N)) {
BN_free(sc->srp_ctx.N);
sc->srp_ctx.N = NULL;
}
} else
sc->srp_ctx.N = BN_dup(N);
}
if (g != NULL) {
if (sc->srp_ctx.g != NULL) {
if (!BN_copy(sc->srp_ctx.g, g)) {
BN_free(sc->srp_ctx.g);
sc->srp_ctx.g = NULL;
}
} else
sc->srp_ctx.g = BN_dup(g);
}
if (sa != NULL) {
if (sc->srp_ctx.s != NULL) {
if (!BN_copy(sc->srp_ctx.s, sa)) {
BN_free(sc->srp_ctx.s);
sc->srp_ctx.s = NULL;
}
} else
sc->srp_ctx.s = BN_dup(sa);
}
if (v != NULL) {
if (sc->srp_ctx.v != NULL) {
if (!BN_copy(sc->srp_ctx.v, v)) {
BN_free(sc->srp_ctx.v);
sc->srp_ctx.v = NULL;
}
} else
sc->srp_ctx.v = BN_dup(v);
}
if (info != NULL) {
if (sc->srp_ctx.info)
OPENSSL_free(sc->srp_ctx.info);
if ((sc->srp_ctx.info = OPENSSL_strdup(info)) == NULL)
return -1;
}
if (!(sc->srp_ctx.N) ||
!(sc->srp_ctx.g) || !(sc->srp_ctx.s) || !(sc->srp_ctx.v))
return -1;
return 1;
}
int srp_generate_server_master_secret(SSL_CONNECTION *s)
{
BIGNUM *K = NULL, *u = NULL;
int ret = 0, tmp_len = 0;
unsigned char *tmp = NULL;
SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
if (!SRP_Verify_A_mod_N(s->srp_ctx.A, s->srp_ctx.N))
goto err;
if ((u = SRP_Calc_u_ex(s->srp_ctx.A, s->srp_ctx.B, s->srp_ctx.N,
sctx->libctx, sctx->propq)) == NULL)
goto err;
if ((K = SRP_Calc_server_key(s->srp_ctx.A, s->srp_ctx.v, u, s->srp_ctx.b,
s->srp_ctx.N)) == NULL)
goto err;
tmp_len = BN_num_bytes(K);
if ((tmp = OPENSSL_malloc(tmp_len)) == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
goto err;
}
BN_bn2bin(K, tmp);
/* Calls SSLfatal() as required */
ret = ssl_generate_master_secret(s, tmp, tmp_len, 1);
err:
BN_clear_free(K);
BN_clear_free(u);
return ret;
}
/* client side */
int srp_generate_client_master_secret(SSL_CONNECTION *s)
{
BIGNUM *x = NULL, *u = NULL, *K = NULL;
int ret = 0, tmp_len = 0;
char *passwd = NULL;
unsigned char *tmp = NULL;
SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
/*
* Checks if b % n == 0
*/
if (SRP_Verify_B_mod_N(s->srp_ctx.B, s->srp_ctx.N) == 0
|| (u = SRP_Calc_u_ex(s->srp_ctx.A, s->srp_ctx.B, s->srp_ctx.N,
sctx->libctx, sctx->propq))
== NULL
|| s->srp_ctx.SRP_give_srp_client_pwd_callback == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if ((passwd = s->srp_ctx.SRP_give_srp_client_pwd_callback(SSL_CONNECTION_GET_SSL(s),
s->srp_ctx.SRP_cb_arg))
== NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CALLBACK_FAILED);
goto err;
}
if ((x = SRP_Calc_x_ex(s->srp_ctx.s, s->srp_ctx.login, passwd,
sctx->libctx, sctx->propq)) == NULL
|| (K = SRP_Calc_client_key_ex(s->srp_ctx.N, s->srp_ctx.B,
s->srp_ctx.g, x,
s->srp_ctx.a, u,
sctx->libctx,
sctx->propq)) == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
tmp_len = BN_num_bytes(K);
if ((tmp = OPENSSL_malloc(tmp_len)) == NULL) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
goto err;
}
BN_bn2bin(K, tmp);
/* Calls SSLfatal() as required */
ret = ssl_generate_master_secret(s, tmp, tmp_len, 1);
err:
BN_clear_free(K);
BN_clear_free(x);
if (passwd != NULL)
OPENSSL_clear_free(passwd, strlen(passwd));
BN_clear_free(u);
return ret;
}
int srp_verify_server_param(SSL_CONNECTION *s)
{
SRP_CTX *srp = &s->srp_ctx;
/*
* Sanity check parameters: we can quickly check B % N == 0 by checking B
* != 0 since B < N
*/
if (BN_ucmp(srp->g, srp->N) >= 0 || BN_ucmp(srp->B, srp->N) >= 0
|| BN_is_zero(srp->B)) {
SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_DATA);
return 0;
}
if (BN_num_bits(srp->N) < srp->strength) {
SSLfatal(s, SSL_AD_INSUFFICIENT_SECURITY, SSL_R_INSUFFICIENT_SECURITY);
return 0;
}
if (srp->SRP_verify_param_callback) {
if (srp->SRP_verify_param_callback(SSL_CONNECTION_GET_SSL(s),
srp->SRP_cb_arg) <= 0) {
SSLfatal(s, SSL_AD_INSUFFICIENT_SECURITY, SSL_R_CALLBACK_FAILED);
return 0;
}
} else if (!SRP_check_known_gN_param(srp->g, srp->N)) {
SSLfatal(s, SSL_AD_INSUFFICIENT_SECURITY,
SSL_R_INSUFFICIENT_SECURITY);
return 0;
}
return 1;
}
/*
* The public API SRP_Calc_A_param() is deprecated so we use
* ssl_srp_calc_a_param_intern() internally.
*/
int ssl_srp_calc_a_param_intern(SSL_CONNECTION *s)
{
unsigned char rnd[SSL_MAX_MASTER_KEY_LENGTH];
if (RAND_priv_bytes_ex(SSL_CONNECTION_GET_CTX(s)->libctx,
rnd, sizeof(rnd), 0) <= 0)
return 0;
s->srp_ctx.a = BN_bin2bn(rnd, sizeof(rnd), s->srp_ctx.a);
OPENSSL_cleanse(rnd, sizeof(rnd));
if (!(s->srp_ctx.A = SRP_Calc_A(s->srp_ctx.a, s->srp_ctx.N, s->srp_ctx.g)))
return 0;
return 1;
}
int SRP_Calc_A_param(SSL *s)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
if (sc == NULL)
return 0;
return ssl_srp_calc_a_param_intern(sc);
}
BIGNUM *SSL_get_srp_g(SSL *s)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
if (sc == NULL)
return NULL;
if (sc->srp_ctx.g != NULL)
return sc->srp_ctx.g;
return s->ctx->srp_ctx.g;
}
BIGNUM *SSL_get_srp_N(SSL *s)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
if (sc == NULL)
return NULL;
if (sc->srp_ctx.N != NULL)
return sc->srp_ctx.N;
return s->ctx->srp_ctx.N;
}
char *SSL_get_srp_username(SSL *s)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
if (sc == NULL)
return NULL;
if (sc->srp_ctx.login != NULL)
return sc->srp_ctx.login;
return s->ctx->srp_ctx.login;
}
char *SSL_get_srp_userinfo(SSL *s)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
if (sc == NULL)
return NULL;
if (sc->srp_ctx.info != NULL)
return sc->srp_ctx.info;
return s->ctx->srp_ctx.info;
}
# define tls1_ctx_ctrl ssl3_ctx_ctrl
# define tls1_ctx_callback_ctrl ssl3_ctx_callback_ctrl
int SSL_CTX_set_srp_username(SSL_CTX *ctx, char *name)
{
return tls1_ctx_ctrl(ctx, SSL_CTRL_SET_TLS_EXT_SRP_USERNAME, 0, name);
}
int SSL_CTX_set_srp_password(SSL_CTX *ctx, char *password)
{
return tls1_ctx_ctrl(ctx, SSL_CTRL_SET_TLS_EXT_SRP_PASSWORD, 0, password);
}
int SSL_CTX_set_srp_strength(SSL_CTX *ctx, int strength)
{
return tls1_ctx_ctrl(ctx, SSL_CTRL_SET_TLS_EXT_SRP_STRENGTH, strength,
NULL);
}
int SSL_CTX_set_srp_verify_param_callback(SSL_CTX *ctx,
int (*cb) (SSL *, void *))
{
return tls1_ctx_callback_ctrl(ctx, SSL_CTRL_SET_SRP_VERIFY_PARAM_CB,
(void (*)(void))cb);
}
int SSL_CTX_set_srp_cb_arg(SSL_CTX *ctx, void *arg)
{
return tls1_ctx_ctrl(ctx, SSL_CTRL_SET_SRP_ARG, 0, arg);
}
int SSL_CTX_set_srp_username_callback(SSL_CTX *ctx,
int (*cb) (SSL *, int *, void *))
{
return tls1_ctx_callback_ctrl(ctx, SSL_CTRL_SET_TLS_EXT_SRP_USERNAME_CB,
(void (*)(void))cb);
}
int SSL_CTX_set_srp_client_pwd_callback(SSL_CTX *ctx,
char *(*cb) (SSL *, void *))
{
return tls1_ctx_callback_ctrl(ctx, SSL_CTRL_SET_SRP_GIVE_CLIENT_PWD_CB,
(void (*)(void))cb);
}
#endif
| 16,451 | 28.015873 | 88 | c |
openssl | openssl-master/ssl/quic/cc_newreno.c | #include "internal/quic_cc.h"
#include "internal/quic_types.h"
#include "internal/safe_math.h"
OSSL_SAFE_MATH_UNSIGNED(u64, uint64_t)
typedef struct ossl_cc_newreno_st {
/* Dependencies. */
OSSL_TIME (*now_cb)(void *arg);
void *now_cb_arg;
/* 'Constants' (which we allow to be configurable). */
uint64_t k_init_wnd, k_min_wnd;
uint32_t k_loss_reduction_factor_num, k_loss_reduction_factor_den;
uint32_t persistent_cong_thresh;
/* State. */
size_t max_dgram_size;
uint64_t bytes_in_flight, cong_wnd, slow_start_thresh, bytes_acked;
OSSL_TIME cong_recovery_start_time;
/* Unflushed state during multiple on-loss calls. */
int processing_loss; /* 1 if not flushed */
OSSL_TIME tx_time_of_last_loss;
/* Diagnostic state. */
int in_congestion_recovery;
/* Diagnostic output locations. */
size_t *p_diag_max_dgram_payload_len;
uint64_t *p_diag_cur_cwnd_size;
uint64_t *p_diag_min_cwnd_size;
uint64_t *p_diag_cur_bytes_in_flight;
uint32_t *p_diag_cur_state;
} OSSL_CC_NEWRENO;
#define MIN_MAX_INIT_WND_SIZE 14720 /* RFC 9002 s. 7.2 */
/* TODO(QUIC): Pacing support. */
static void newreno_set_max_dgram_size(OSSL_CC_NEWRENO *nr,
size_t max_dgram_size);
static void newreno_update_diag(OSSL_CC_NEWRENO *nr);
static void newreno_reset(OSSL_CC_DATA *cc);
static OSSL_CC_DATA *newreno_new(OSSL_TIME (*now_cb)(void *arg),
void *now_cb_arg)
{
OSSL_CC_NEWRENO *nr;
if ((nr = OPENSSL_zalloc(sizeof(*nr))) == NULL)
return NULL;
nr->now_cb = now_cb;
nr->now_cb_arg = now_cb_arg;
newreno_set_max_dgram_size(nr, QUIC_MIN_INITIAL_DGRAM_LEN);
newreno_reset((OSSL_CC_DATA *)nr);
return (OSSL_CC_DATA *)nr;
}
static void newreno_free(OSSL_CC_DATA *cc)
{
OPENSSL_free(cc);
}
static void newreno_set_max_dgram_size(OSSL_CC_NEWRENO *nr,
size_t max_dgram_size)
{
size_t max_init_wnd;
int is_reduced = (max_dgram_size < nr->max_dgram_size);
nr->max_dgram_size = max_dgram_size;
max_init_wnd = 2 * max_dgram_size;
if (max_init_wnd < MIN_MAX_INIT_WND_SIZE)
max_init_wnd = MIN_MAX_INIT_WND_SIZE;
nr->k_init_wnd = 10 * max_dgram_size;
if (nr->k_init_wnd > max_init_wnd)
nr->k_init_wnd = max_init_wnd;
nr->k_min_wnd = 2 * max_dgram_size;
if (is_reduced)
nr->cong_wnd = nr->k_init_wnd;
newreno_update_diag(nr);
}
static void newreno_reset(OSSL_CC_DATA *cc)
{
OSSL_CC_NEWRENO *nr = (OSSL_CC_NEWRENO *)cc;
nr->k_loss_reduction_factor_num = 1;
nr->k_loss_reduction_factor_den = 2;
nr->persistent_cong_thresh = 3;
nr->cong_wnd = nr->k_init_wnd;
nr->bytes_in_flight = 0;
nr->bytes_acked = 0;
nr->slow_start_thresh = UINT64_MAX;
nr->cong_recovery_start_time = ossl_time_zero();
nr->processing_loss = 0;
nr->tx_time_of_last_loss = ossl_time_zero();
nr->in_congestion_recovery = 0;
}
static int newreno_set_input_params(OSSL_CC_DATA *cc, const OSSL_PARAM *params)
{
OSSL_CC_NEWRENO *nr = (OSSL_CC_NEWRENO *)cc;
const OSSL_PARAM *p;
size_t value;
p = OSSL_PARAM_locate_const(params, OSSL_CC_OPTION_MAX_DGRAM_PAYLOAD_LEN);
if (p != NULL) {
if (!OSSL_PARAM_get_size_t(p, &value))
return 0;
if (value < QUIC_MIN_INITIAL_DGRAM_LEN)
return 0;
newreno_set_max_dgram_size(nr, value);
}
return 1;
}
static int bind_diag(OSSL_PARAM *params, const char *param_name, size_t len,
void **pp)
{
const OSSL_PARAM *p = OSSL_PARAM_locate_const(params, param_name);
*pp = NULL;
if (p == NULL)
return 1;
if (p->data_type != OSSL_PARAM_UNSIGNED_INTEGER
|| p->data_size != len)
return 0;
*pp = p->data;
return 1;
}
static int newreno_bind_diagnostic(OSSL_CC_DATA *cc, OSSL_PARAM *params)
{
OSSL_CC_NEWRENO *nr = (OSSL_CC_NEWRENO *)cc;
size_t *new_p_max_dgram_payload_len;
uint64_t *new_p_cur_cwnd_size;
uint64_t *new_p_min_cwnd_size;
uint64_t *new_p_cur_bytes_in_flight;
uint32_t *new_p_cur_state;
if (!bind_diag(params, OSSL_CC_OPTION_MAX_DGRAM_PAYLOAD_LEN,
sizeof(size_t), (void **)&new_p_max_dgram_payload_len)
|| !bind_diag(params, OSSL_CC_OPTION_CUR_CWND_SIZE,
sizeof(uint64_t), (void **)&new_p_cur_cwnd_size)
|| !bind_diag(params, OSSL_CC_OPTION_MIN_CWND_SIZE,
sizeof(uint64_t), (void **)&new_p_min_cwnd_size)
|| !bind_diag(params, OSSL_CC_OPTION_CUR_BYTES_IN_FLIGHT,
sizeof(uint64_t), (void **)&new_p_cur_bytes_in_flight)
|| !bind_diag(params, OSSL_CC_OPTION_CUR_STATE,
sizeof(uint32_t), (void **)&new_p_cur_state))
return 0;
if (new_p_max_dgram_payload_len != NULL)
nr->p_diag_max_dgram_payload_len = new_p_max_dgram_payload_len;
if (new_p_cur_cwnd_size != NULL)
nr->p_diag_cur_cwnd_size = new_p_cur_cwnd_size;
if (new_p_min_cwnd_size != NULL)
nr->p_diag_min_cwnd_size = new_p_min_cwnd_size;
if (new_p_cur_bytes_in_flight != NULL)
nr->p_diag_cur_bytes_in_flight = new_p_cur_bytes_in_flight;
if (new_p_cur_state != NULL)
nr->p_diag_cur_state = new_p_cur_state;
newreno_update_diag(nr);
return 1;
}
static void unbind_diag(OSSL_PARAM *params, const char *param_name,
void **pp)
{
const OSSL_PARAM *p = OSSL_PARAM_locate_const(params, param_name);
if (p != NULL)
*pp = NULL;
}
static int newreno_unbind_diagnostic(OSSL_CC_DATA *cc, OSSL_PARAM *params)
{
OSSL_CC_NEWRENO *nr = (OSSL_CC_NEWRENO *)cc;
unbind_diag(params, OSSL_CC_OPTION_MAX_DGRAM_PAYLOAD_LEN,
(void **)&nr->p_diag_max_dgram_payload_len);
unbind_diag(params, OSSL_CC_OPTION_CUR_CWND_SIZE,
(void **)&nr->p_diag_cur_cwnd_size);
unbind_diag(params, OSSL_CC_OPTION_MIN_CWND_SIZE,
(void **)&nr->p_diag_min_cwnd_size);
unbind_diag(params, OSSL_CC_OPTION_CUR_BYTES_IN_FLIGHT,
(void **)&nr->p_diag_cur_bytes_in_flight);
unbind_diag(params, OSSL_CC_OPTION_CUR_STATE,
(void **)&nr->p_diag_cur_state);
return 1;
}
static void newreno_update_diag(OSSL_CC_NEWRENO *nr)
{
if (nr->p_diag_max_dgram_payload_len != NULL)
*nr->p_diag_max_dgram_payload_len = nr->max_dgram_size;
if (nr->p_diag_cur_cwnd_size != NULL)
*nr->p_diag_cur_cwnd_size = nr->cong_wnd;
if (nr->p_diag_min_cwnd_size != NULL)
*nr->p_diag_min_cwnd_size = nr->k_min_wnd;
if (nr->p_diag_cur_bytes_in_flight != NULL)
*nr->p_diag_cur_bytes_in_flight = nr->bytes_in_flight;
if (nr->p_diag_cur_state != NULL) {
if (nr->in_congestion_recovery)
*nr->p_diag_cur_state = 'R';
else if (nr->cong_wnd < nr->slow_start_thresh)
*nr->p_diag_cur_state = 'S';
else
*nr->p_diag_cur_state = 'A';
}
}
static int newreno_in_cong_recovery(OSSL_CC_NEWRENO *nr, OSSL_TIME tx_time)
{
return ossl_time_compare(tx_time, nr->cong_recovery_start_time) <= 0;
}
static void newreno_cong(OSSL_CC_NEWRENO *nr, OSSL_TIME tx_time)
{
int err = 0;
/* No reaction if already in a recovery period. */
if (newreno_in_cong_recovery(nr, tx_time))
return;
/* Start a new recovery period. */
nr->in_congestion_recovery = 1;
nr->cong_recovery_start_time = nr->now_cb(nr->now_cb_arg);
/* slow_start_thresh = cong_wnd * loss_reduction_factor */
nr->slow_start_thresh
= safe_muldiv_u64(nr->cong_wnd,
nr->k_loss_reduction_factor_num,
nr->k_loss_reduction_factor_den,
&err);
if (err)
nr->slow_start_thresh = UINT64_MAX;
nr->cong_wnd = nr->slow_start_thresh;
if (nr->cong_wnd < nr->k_min_wnd)
nr->cong_wnd = nr->k_min_wnd;
}
static void newreno_flush(OSSL_CC_NEWRENO *nr, uint32_t flags)
{
if (!nr->processing_loss)
return;
newreno_cong(nr, nr->tx_time_of_last_loss);
if ((flags & OSSL_CC_LOST_FLAG_PERSISTENT_CONGESTION) != 0) {
nr->cong_wnd = nr->k_min_wnd;
nr->cong_recovery_start_time = ossl_time_zero();
}
nr->processing_loss = 0;
newreno_update_diag(nr);
}
static uint64_t newreno_get_tx_allowance(OSSL_CC_DATA *cc)
{
OSSL_CC_NEWRENO *nr = (OSSL_CC_NEWRENO *)cc;
if (nr->bytes_in_flight >= nr->cong_wnd)
return 0;
return nr->cong_wnd - nr->bytes_in_flight;
}
static OSSL_TIME newreno_get_wakeup_deadline(OSSL_CC_DATA *cc)
{
if (newreno_get_tx_allowance(cc) > 0) {
/* We have TX allowance now so wakeup immediately */
return ossl_time_zero();
} else {
/*
* The NewReno congestion controller does not vary its state in time,
* only in response to stimulus.
*/
return ossl_time_infinite();
}
}
static int newreno_on_data_sent(OSSL_CC_DATA *cc, uint64_t num_bytes)
{
OSSL_CC_NEWRENO *nr = (OSSL_CC_NEWRENO *)cc;
nr->bytes_in_flight += num_bytes;
newreno_update_diag(nr);
return 1;
}
static int newreno_is_cong_limited(OSSL_CC_NEWRENO *nr)
{
uint64_t wnd_rem;
/* We are congestion-limited if we are already at the congestion window. */
if (nr->bytes_in_flight >= nr->cong_wnd)
return 1;
wnd_rem = nr->cong_wnd - nr->bytes_in_flight;
/*
* Consider ourselves congestion-limited if less than three datagrams' worth
* of congestion window remains to be spent, or if we are in slow start and
* have consumed half of our window.
*/
return (nr->cong_wnd < nr->slow_start_thresh && wnd_rem <= nr->cong_wnd / 2)
|| wnd_rem <= 3 * nr->max_dgram_size;
}
static int newreno_on_data_acked(OSSL_CC_DATA *cc,
const OSSL_CC_ACK_INFO *info)
{
OSSL_CC_NEWRENO *nr = (OSSL_CC_NEWRENO *)cc;
/*
* Packet has been acked. Firstly, remove it from the aggregate count of
* bytes in flight.
*/
nr->bytes_in_flight -= info->tx_size;
/*
* We use acknowledgement of data as a signal that we are not at channel
* capacity and that it may be reasonable to increase the congestion window.
* However, acknowledgement is not a useful signal that there is further
* capacity if we are not actually saturating the congestion window that we
* already have (for example, if the application is not generating much data
* or we are limited by flow control). Therefore, we only expand the
* congestion window if we are consuming a significant fraction of the
* congestion window.
*/
if (!newreno_is_cong_limited(nr))
goto out;
/*
* We can handle acknowledgement of a packet in one of three ways
* depending on our current state:
*
* - Congestion Recovery: Do nothing. We don't start increasing
* the congestion window in response to acknowledgements until
* we are no longer in the Congestion Recovery state.
*
* - Slow Start: Increase the congestion window using the slow
* start scale.
*
* - Congestion Avoidance: Increase the congestion window using
* the congestion avoidance scale.
*/
if (newreno_in_cong_recovery(nr, info->tx_time)) {
/* Congestion recovery, do nothing. */
} else if (nr->cong_wnd < nr->slow_start_thresh) {
/* When this condition is true we are in the Slow Start state. */
nr->cong_wnd += info->tx_size;
nr->in_congestion_recovery = 0;
} else {
/* Otherwise, we are in the Congestion Avoidance state. */
nr->bytes_acked += info->tx_size;
/*
* Avoid integer division as per RFC 9002 s. B.5. / RFC3465 s. 2.1.
*/
if (nr->bytes_acked >= nr->cong_wnd) {
nr->bytes_acked -= nr->cong_wnd;
nr->cong_wnd += nr->max_dgram_size;
}
nr->in_congestion_recovery = 0;
}
out:
newreno_update_diag(nr);
return 1;
}
static int newreno_on_data_lost(OSSL_CC_DATA *cc,
const OSSL_CC_LOSS_INFO *info)
{
OSSL_CC_NEWRENO *nr = (OSSL_CC_NEWRENO *)cc;
if (info->tx_size > nr->bytes_in_flight)
return 0;
nr->bytes_in_flight -= info->tx_size;
if (!nr->processing_loss) {
if (ossl_time_compare(info->tx_time, nr->tx_time_of_last_loss) <= 0)
/*
* After triggering congestion due to a lost packet at time t, don't
* trigger congestion again due to any subsequently detected lost
* packet at a time s < t, as we've effectively already signalled
* congestion on loss of that and subsequent packets.
*/
goto out;
nr->processing_loss = 1;
/*
* Cancel any pending window increase in the Congestion Avoidance state.
*/
nr->bytes_acked = 0;
}
nr->tx_time_of_last_loss
= ossl_time_max(nr->tx_time_of_last_loss, info->tx_time);
out:
newreno_update_diag(nr);
return 1;
}
static int newreno_on_data_lost_finished(OSSL_CC_DATA *cc, uint32_t flags)
{
OSSL_CC_NEWRENO *nr = (OSSL_CC_NEWRENO *)cc;
newreno_flush(nr, flags);
return 1;
}
static int newreno_on_data_invalidated(OSSL_CC_DATA *cc,
uint64_t num_bytes)
{
OSSL_CC_NEWRENO *nr = (OSSL_CC_NEWRENO *)cc;
nr->bytes_in_flight -= num_bytes;
newreno_update_diag(nr);
return 1;
}
static int newreno_on_ecn(OSSL_CC_DATA *cc,
const OSSL_CC_ECN_INFO *info)
{
OSSL_CC_NEWRENO *nr = (OSSL_CC_NEWRENO *)cc;
nr->processing_loss = 1;
nr->bytes_acked = 0;
nr->tx_time_of_last_loss = info->largest_acked_time;
newreno_flush(nr, 0);
return 1;
}
const OSSL_CC_METHOD ossl_cc_newreno_method = {
newreno_new,
newreno_free,
newreno_reset,
newreno_set_input_params,
newreno_bind_diagnostic,
newreno_unbind_diagnostic,
newreno_get_tx_allowance,
newreno_get_wakeup_deadline,
newreno_on_data_sent,
newreno_on_data_acked,
newreno_on_data_lost,
newreno_on_data_lost_finished,
newreno_on_data_invalidated,
newreno_on_ecn,
};
| 14,639 | 29.123457 | 80 | c |
openssl | openssl-master/ssl/quic/quic_cfq.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/quic_cfq.h"
typedef struct quic_cfq_item_ex_st QUIC_CFQ_ITEM_EX;
struct quic_cfq_item_ex_st {
QUIC_CFQ_ITEM public;
QUIC_CFQ_ITEM_EX *prev, *next;
unsigned char *encoded;
cfq_free_cb *free_cb;
void *free_cb_arg;
uint64_t frame_type;
size_t encoded_len;
uint32_t priority, pn_space;
int state;
};
uint64_t ossl_quic_cfq_item_get_frame_type(const QUIC_CFQ_ITEM *item)
{
QUIC_CFQ_ITEM_EX *ex = (QUIC_CFQ_ITEM_EX *)item;
return ex->frame_type;
}
const unsigned char *ossl_quic_cfq_item_get_encoded(const QUIC_CFQ_ITEM *item)
{
QUIC_CFQ_ITEM_EX *ex = (QUIC_CFQ_ITEM_EX *)item;
return ex->encoded;
}
size_t ossl_quic_cfq_item_get_encoded_len(const QUIC_CFQ_ITEM *item)
{
QUIC_CFQ_ITEM_EX *ex = (QUIC_CFQ_ITEM_EX *)item;
return ex->encoded_len;
}
int ossl_quic_cfq_item_get_state(const QUIC_CFQ_ITEM *item)
{
QUIC_CFQ_ITEM_EX *ex = (QUIC_CFQ_ITEM_EX *)item;
return ex->state;
}
uint32_t ossl_quic_cfq_item_get_pn_space(const QUIC_CFQ_ITEM *item)
{
QUIC_CFQ_ITEM_EX *ex = (QUIC_CFQ_ITEM_EX *)item;
return ex->pn_space;
}
typedef struct quic_cfq_item_list_st {
QUIC_CFQ_ITEM_EX *head, *tail;
} QUIC_CFQ_ITEM_LIST;
struct quic_cfq_st {
/*
* Invariant: A CFQ item is always in exactly one of these lists, never more
* or less than one.
*
* Invariant: The list the CFQ item is determined exactly by the state field
* of the item.
*/
QUIC_CFQ_ITEM_LIST new_list, tx_list, free_list;
};
static int compare(const QUIC_CFQ_ITEM_EX *a, const QUIC_CFQ_ITEM_EX *b)
{
if (a->pn_space < b->pn_space)
return -1;
else if (a->pn_space > b->pn_space)
return 1;
if (a->priority > b->priority)
return -1;
else if (a->priority < b->priority)
return 1;
return 0;
}
static void list_remove(QUIC_CFQ_ITEM_LIST *l, QUIC_CFQ_ITEM_EX *n)
{
if (l->head == n)
l->head = n->next;
if (l->tail == n)
l->tail = n->prev;
if (n->prev != NULL)
n->prev->next = n->next;
if (n->next != NULL)
n->next->prev = n->prev;
n->prev = n->next = NULL;
}
static void list_insert_head(QUIC_CFQ_ITEM_LIST *l, QUIC_CFQ_ITEM_EX *n)
{
n->next = l->head;
n->prev = NULL;
l->head = n;
if (n->next != NULL)
n->next->prev = n;
if (l->tail == NULL)
l->tail = n;
}
static void list_insert_tail(QUIC_CFQ_ITEM_LIST *l, QUIC_CFQ_ITEM_EX *n)
{
n->prev = l->tail;
n->next = NULL;
l->tail = n;
if (n->prev != NULL)
n->prev->next = n;
if (l->head == NULL)
l->head = n;
}
static void list_insert_after(QUIC_CFQ_ITEM_LIST *l,
QUIC_CFQ_ITEM_EX *ref,
QUIC_CFQ_ITEM_EX *n)
{
n->prev = ref;
n->next = ref->next;
if (ref->next != NULL)
ref->next->prev = n;
ref->next = n;
if (l->tail == ref)
l->tail = n;
}
static void list_insert_sorted(QUIC_CFQ_ITEM_LIST *l, QUIC_CFQ_ITEM_EX *n,
int (*cmp)(const QUIC_CFQ_ITEM_EX *a,
const QUIC_CFQ_ITEM_EX *b))
{
QUIC_CFQ_ITEM_EX *p = l->head, *pprev = NULL;
if (p == NULL) {
l->head = l->tail = n;
n->prev = n->next = NULL;
return;
}
for (; p != NULL && cmp(p, n) < 0; pprev = p, p = p->next);
if (p == NULL)
list_insert_tail(l, n);
else if (pprev == NULL)
list_insert_head(l, n);
else
list_insert_after(l, pprev, n);
}
QUIC_CFQ *ossl_quic_cfq_new(void)
{
QUIC_CFQ *cfq = OPENSSL_zalloc(sizeof(*cfq));
if (cfq == NULL)
return NULL;
return cfq;
}
static void clear_item(QUIC_CFQ_ITEM_EX *item)
{
if (item->free_cb != NULL) {
item->free_cb(item->encoded, item->encoded_len, item->free_cb_arg);
item->free_cb = NULL;
item->encoded = NULL;
item->encoded_len = 0;
}
item->state = -1;
}
static void free_list_items(QUIC_CFQ_ITEM_LIST *l)
{
QUIC_CFQ_ITEM_EX *p, *pnext;
for (p = l->head; p != NULL; p = pnext) {
pnext = p->next;
clear_item(p);
OPENSSL_free(p);
}
}
void ossl_quic_cfq_free(QUIC_CFQ *cfq)
{
if (cfq == NULL)
return;
free_list_items(&cfq->new_list);
free_list_items(&cfq->tx_list);
free_list_items(&cfq->free_list);
OPENSSL_free(cfq);
}
static QUIC_CFQ_ITEM_EX *cfq_get_free(QUIC_CFQ *cfq)
{
QUIC_CFQ_ITEM_EX *item = cfq->free_list.head;
if (item != NULL)
return item;
item = OPENSSL_zalloc(sizeof(*item));
if (item == NULL)
return NULL;
item->state = -1;
list_insert_tail(&cfq->free_list, item);
return item;
}
QUIC_CFQ_ITEM *ossl_quic_cfq_add_frame(QUIC_CFQ *cfq,
uint32_t priority,
uint32_t pn_space,
uint64_t frame_type,
const unsigned char *encoded,
size_t encoded_len,
cfq_free_cb *free_cb,
void *free_cb_arg)
{
QUIC_CFQ_ITEM_EX *item = cfq_get_free(cfq);
if (item == NULL)
return NULL;
item->priority = priority;
item->frame_type = frame_type;
item->pn_space = pn_space;
item->encoded = (unsigned char *)encoded;
item->encoded_len = encoded_len;
item->free_cb = free_cb;
item->free_cb_arg = free_cb_arg;
item->state = QUIC_CFQ_STATE_NEW;
list_remove(&cfq->free_list, item);
list_insert_sorted(&cfq->new_list, item, compare);
return &item->public;
}
void ossl_quic_cfq_mark_tx(QUIC_CFQ *cfq, QUIC_CFQ_ITEM *item)
{
QUIC_CFQ_ITEM_EX *ex = (QUIC_CFQ_ITEM_EX *)item;
switch (ex->state) {
case QUIC_CFQ_STATE_NEW:
list_remove(&cfq->new_list, ex);
list_insert_tail(&cfq->tx_list, ex);
ex->state = QUIC_CFQ_STATE_TX;
break;
case QUIC_CFQ_STATE_TX:
break; /* nothing to do */
default:
assert(0); /* invalid state (e.g. in free state) */
break;
}
}
void ossl_quic_cfq_mark_lost(QUIC_CFQ *cfq, QUIC_CFQ_ITEM *item,
uint32_t priority)
{
QUIC_CFQ_ITEM_EX *ex = (QUIC_CFQ_ITEM_EX *)item;
switch (ex->state) {
case QUIC_CFQ_STATE_NEW:
if (priority != UINT32_MAX && priority != ex->priority) {
list_remove(&cfq->new_list, ex);
ex->priority = priority;
list_insert_sorted(&cfq->new_list, ex, compare);
}
break; /* nothing to do */
case QUIC_CFQ_STATE_TX:
if (priority != UINT32_MAX)
ex->priority = priority;
list_remove(&cfq->tx_list, ex);
list_insert_sorted(&cfq->new_list, ex, compare);
ex->state = QUIC_CFQ_STATE_NEW;
break;
default:
assert(0); /* invalid state (e.g. in free state) */
break;
}
}
/*
* Releases a CFQ item. The item may be in either state (NEW or TX) prior to the
* call. The QUIC_CFQ_ITEM pointer must not be used following this call.
*/
void ossl_quic_cfq_release(QUIC_CFQ *cfq, QUIC_CFQ_ITEM *item)
{
QUIC_CFQ_ITEM_EX *ex = (QUIC_CFQ_ITEM_EX *)item;
switch (ex->state) {
case QUIC_CFQ_STATE_NEW:
list_remove(&cfq->new_list, ex);
list_insert_tail(&cfq->free_list, ex);
clear_item(ex);
break;
case QUIC_CFQ_STATE_TX:
list_remove(&cfq->tx_list, ex);
list_insert_tail(&cfq->free_list, ex);
clear_item(ex);
break;
default:
assert(0); /* invalid state (e.g. in free state) */
break;
}
}
QUIC_CFQ_ITEM *ossl_quic_cfq_get_priority_head(const QUIC_CFQ *cfq,
uint32_t pn_space)
{
QUIC_CFQ_ITEM_EX *item = cfq->new_list.head;
for (; item != NULL && item->pn_space != pn_space; item = item->next);
if (item == NULL)
return NULL;
return &item->public;
}
QUIC_CFQ_ITEM *ossl_quic_cfq_item_get_priority_next(const QUIC_CFQ_ITEM *item,
uint32_t pn_space)
{
QUIC_CFQ_ITEM_EX *ex = (QUIC_CFQ_ITEM_EX *)item;
if (ex == NULL)
return NULL;
ex = ex->next;
for (; ex != NULL && ex->pn_space != pn_space; ex = ex->next);
if (ex == NULL)
return NULL; /* ubsan */
return &ex->public;
}
| 9,098 | 25.071633 | 80 | c |
openssl | openssl-master/ssl/quic/quic_channel_local.h | #ifndef OSSL_QUIC_CHANNEL_LOCAL_H
# define OSSL_QUIC_CHANNEL_LOCAL_H
# include "internal/quic_channel.h"
# ifndef OPENSSL_NO_QUIC
/*
* QUIC Channel Structure
* ======================
*
* QUIC channel internals. It is intended that only the QUIC_CHANNEL
* implementation and the RX depacketiser be allowed to access this structure
* directly. As the RX depacketiser has no state of its own and computes over a
* QUIC_CHANNEL structure, it can be viewed as an extension of the QUIC_CHANNEL
* implementation. While the RX depacketiser could be provided with adequate
* accessors to do what it needs, this would weaken the abstraction provided by
* the QUIC_CHANNEL to other components; moreover the coupling of the RX
* depacketiser to QUIC_CHANNEL internals is too deep and bespoke to make this
* desirable.
*
* Other components should not include this header.
*/
struct quic_channel_st {
OSSL_LIB_CTX *libctx;
const char *propq;
/*
* Master synchronisation mutex used for thread assisted mode
* synchronisation. We don't own this; the instantiator of the channel
* passes it to us and is responsible for freeing it after channel
* destruction.
*/
CRYPTO_MUTEX *mutex;
/*
* Callback used to get the current time.
*/
OSSL_TIME (*now_cb)(void *arg);
void *now_cb_arg;
/*
* The associated TLS 1.3 connection data. Used to provide the handshake
* layer; its 'network' side is plugged into the crypto stream for each EL
* (other than the 0-RTT EL).
*/
QUIC_TLS *qtls;
SSL *tls;
/*
* The transport parameter block we will send or have sent.
* Freed after sending or when connection is freed.
*/
unsigned char *local_transport_params;
/* Asynchronous I/O reactor. */
QUIC_REACTOR rtor;
/* Our current L4 peer address, if any. */
BIO_ADDR cur_peer_addr;
/* Network-side read and write BIOs. */
BIO *net_rbio, *net_wbio;
/*
* Subcomponents of the connection. All of these components are instantiated
* and owned by us.
*/
OSSL_QUIC_TX_PACKETISER *txp;
QUIC_TXPIM *txpim;
QUIC_CFQ *cfq;
/*
* Connection level FC. The stream_count RXFCs is used to manage
* MAX_STREAMS signalling.
*/
QUIC_TXFC conn_txfc;
QUIC_RXFC conn_rxfc;
QUIC_RXFC max_streams_bidi_rxfc, max_streams_uni_rxfc;
QUIC_STREAM_MAP qsm;
OSSL_STATM statm;
OSSL_CC_DATA *cc_data;
const OSSL_CC_METHOD *cc_method;
OSSL_ACKM *ackm;
/*
* RX demuxer. We register incoming DCIDs with this. Since we currently only
* support client operation and use one L4 port per connection, we own the
* demuxer and register a single zero-length DCID with it.
*/
QUIC_DEMUX *demux;
/* Record layers in the TX and RX directions, plus the RX demuxer. */
OSSL_QTX *qtx;
OSSL_QRX *qrx;
/* Message callback related arguments */
ossl_msg_cb msg_callback;
void *msg_callback_arg;
SSL *msg_callback_ssl;
/*
* Send and receive parts of the crypto streams.
* crypto_send[QUIC_PN_SPACE_APP] is the 1-RTT crypto stream. There is no
* 0-RTT crypto stream.
*/
QUIC_SSTREAM *crypto_send[QUIC_PN_SPACE_NUM];
QUIC_RSTREAM *crypto_recv[QUIC_PN_SPACE_NUM];
/* Internal state. */
/*
* Client: The DCID used in the first Initial packet we transmit as a client.
* Server: The DCID used in the first Initial packet the client transmitted.
* Randomly generated and required by RFC to be at least 8 bytes.
*/
QUIC_CONN_ID init_dcid;
/*
* Client: The SCID found in the first Initial packet from the server.
* Not valid for servers.
* Valid if have_received_enc_pkt is set.
*/
QUIC_CONN_ID init_scid;
/*
* Client only: The SCID found in an incoming Retry packet we handled.
* Not valid for servers.
*/
QUIC_CONN_ID retry_scid;
/* The DCID we currently use to talk to the peer and its sequence num. */
QUIC_CONN_ID cur_remote_dcid;
uint64_t cur_remote_seq_num;
uint64_t cur_retire_prior_to;
/* Server only: The DCID we currently expect the peer to use to talk to us. */
QUIC_CONN_ID cur_local_cid;
/* Transport parameter values we send to our peer. */
uint64_t tx_init_max_stream_data_bidi_local;
uint64_t tx_init_max_stream_data_bidi_remote;
uint64_t tx_init_max_stream_data_uni;
/* Transport parameter values received from server. */
uint64_t rx_init_max_stream_data_bidi_local;
uint64_t rx_init_max_stream_data_bidi_remote;
uint64_t rx_init_max_stream_data_uni;
uint64_t rx_max_ack_delay; /* ms */
unsigned char rx_ack_delay_exp;
/*
* Temporary staging area to store information about the incoming packet we
* are currently processing.
*/
OSSL_QRX_PKT *qrx_pkt;
/*
* Current limit on number of streams we may create. Set by transport
* parameters initially and then by MAX_STREAMS frames.
*/
uint64_t max_local_streams_bidi;
uint64_t max_local_streams_uni;
/* The negotiated maximum idle timeout in milliseconds. */
uint64_t max_idle_timeout;
/*
* Maximum payload size in bytes for datagrams sent to our peer, as
* negotiated by transport parameters.
*/
uint64_t rx_max_udp_payload_size;
/* Maximum active CID limit, as negotiated by transport parameters. */
uint64_t rx_active_conn_id_limit;
/*
* Used to allocate stream IDs. This is a stream ordinal, i.e., a stream ID
* without the low two bits designating type and initiator. Shift and or in
* the type bits to convert to a stream ID.
*/
uint64_t next_local_stream_ordinal_bidi;
uint64_t next_local_stream_ordinal_uni;
/*
* Used to track which stream ordinals within a given stream type have been
* used by the remote peer. This is an optimisation used to determine
* which streams should be implicitly created due to usage of a higher
* stream ordinal.
*/
uint64_t next_remote_stream_ordinal_bidi;
uint64_t next_remote_stream_ordinal_uni;
/*
* Application error code to be used for STOP_SENDING/RESET_STREAM frames
* used to autoreject incoming streams.
*/
uint64_t incoming_stream_auto_reject_aec;
/*
* Override packet count threshold at which we do a spontaneous TXKU.
* Usually UINT64_MAX in which case a suitable value is chosen based on AEAD
* limit advice from the QRL utility functions. This is intended for testing
* use only. Usually set to UINT64_MAX.
*/
uint64_t txku_threshold_override;
/* Valid if we are in the TERMINATING or TERMINATED states. */
QUIC_TERMINATE_CAUSE terminate_cause;
/*
* Deadline at which we move to TERMINATING state. Valid if in the
* TERMINATING state.
*/
OSSL_TIME terminate_deadline;
/*
* Deadline at which connection dies due to idle timeout if no further
* events occur.
*/
OSSL_TIME idle_deadline;
/*
* Deadline at which we should send an ACK-eliciting packet to ensure
* idle timeout does not occur.
*/
OSSL_TIME ping_deadline;
/*
* The deadline at which the period in which it is RECOMMENDED that we not
* initiate any spontaneous TXKU ends. This is zero if no such deadline
* applies.
*/
OSSL_TIME txku_cooldown_deadline;
/*
* The deadline at which we take the QRX out of UPDATING and back to NORMAL.
* Valid if rxku_in_progress in 1.
*/
OSSL_TIME rxku_update_end_deadline;
/*
* The first (application space) PN sent with a new key phase. Valid if the
* QTX key epoch is greater than 0. Once a packet we sent with a PN p (p >=
* txku_pn) is ACKed, the TXKU is considered completed and txku_in_progress
* becomes 0. For sanity's sake, such a PN p should also be <= the highest
* PN we have ever sent, of course.
*/
QUIC_PN txku_pn;
/*
* The (application space) PN which triggered RXKU detection. Valid if
* rxku_pending_confirm.
*/
QUIC_PN rxku_trigger_pn;
/*
* State tracking. QUIC connection-level state is best represented based on
* whether various things have happened yet or not, rather than as an
* explicit FSM. We do have a coarse state variable which tracks the basic
* state of the connection's lifecycle, but more fine-grained conditions of
* the Active state are tracked via flags below. For more details, see
* doc/designs/quic-design/connection-state-machine.md. We are in the Open
* state if the state is QUIC_CSM_STATE_ACTIVE and handshake_confirmed is
* set.
*/
unsigned int state : 3;
/*
* Have we received at least one encrypted packet from the peer?
* (If so, Retry and Version Negotiation messages should no longer
* be received and should be ignored if they do occur.)
*/
unsigned int have_received_enc_pkt : 1;
/*
* Have we sent literally any packet yet? If not, there is no point polling
* RX.
*/
unsigned int have_sent_any_pkt : 1;
/*
* Are we currently doing proactive version negotiation?
*/
unsigned int doing_proactive_ver_neg : 1;
/* We have received transport parameters from the peer. */
unsigned int got_remote_transport_params : 1;
/*
* This monotonically transitions to 1 once the TLS state machine is
* 'complete', meaning that it has both sent a Finished and successfully
* verified the peer's Finished (see RFC 9001 s. 4.1.1). Note that it
* does not transition to 1 at both peers simultaneously.
*
* Handshake completion is not the same as handshake confirmation (see
* below).
*/
unsigned int handshake_complete : 1;
/*
* This monotonically transitions to 1 once the handshake is confirmed.
* This happens on the client when we receive a HANDSHAKE_DONE frame.
* At our option, we may also take acknowledgement of any 1-RTT packet
* we sent as a handshake confirmation.
*/
unsigned int handshake_confirmed : 1;
/*
* We are sending Initial packets based on a Retry. This means we definitely
* should not receive another Retry, and if we do it is an error.
*/
unsigned int doing_retry : 1;
/*
* We don't store the current EL here; the TXP asks the QTX which ELs
* are provisioned to determine which ELs to use.
*/
/* Have statm, qsm been initialised? Used to track cleanup. */
unsigned int have_statm : 1;
unsigned int have_qsm : 1;
/*
* Preferred ELs for transmission and reception. This is not strictly needed
* as it can be inferred from what keys we have provisioned, but makes
* determining the current EL simpler and faster. A separate EL for
* transmission and reception is not strictly necessary but makes things
* easier for interoperation with the handshake layer, which likes to invoke
* the yield secret callback at different times for TX and RX.
*/
unsigned int tx_enc_level : 3;
unsigned int rx_enc_level : 3;
/* If bit n is set, EL n has been discarded. */
unsigned int el_discarded : 4;
/*
* While in TERMINATING - CLOSING, set when we should generate a connection
* close frame.
*/
unsigned int conn_close_queued : 1;
/* Are we in server mode? Never changes after instantiation. */
unsigned int is_server : 1;
/*
* Set temporarily when the handshake layer has given us a new RX secret.
* Used to determine if we need to check our RX queues again.
*/
unsigned int have_new_rx_secret : 1;
/*
* Have we sent an ack-eliciting packet since the last successful packet
* reception? Used to determine when to bump idle timer (see RFC 9000 s.
* 10.1).
*/
unsigned int have_sent_ack_eliciting_since_rx : 1;
/* Should incoming streams automatically be rejected? */
unsigned int incoming_stream_auto_reject : 1;
/*
* 1 if a key update sequence was locally initiated, meaning we sent the
* TXKU first and the resultant RXKU shouldn't result in our triggering
* another TXKU. 0 if a key update sequence was initiated by the peer,
* meaning we detect a RXKU first and have to generate a TXKU in response.
*/
unsigned int ku_locally_initiated : 1;
/*
* 1 if we have triggered TXKU (whether spontaneous or solicited) but are
* waiting for any PN using that new KP to be ACKed. While this is set, we
* are not allowed to trigger spontaneous TXKU (but solicited TXKU is
* potentially still possible).
*/
unsigned int txku_in_progress : 1;
/*
* We have received an RXKU event and currently are going through
* UPDATING/COOLDOWN on the QRX. COOLDOWN is currently not used. Since RXKU
* cannot be detected in this state, this doesn't cause a protocol error or
* anything similar if a peer tries TXKU in this state. That traffic would
* simply be dropped. It's only used to track that our UPDATING timer is
* active so we know when to take the QRX out of UPDATING and back to
* NORMAL.
*/
unsigned int rxku_in_progress : 1;
/*
* We have received an RXKU but have yet to send an ACK for it, which means
* no further RXKUs are allowed yet. Note that we cannot detect further
* RXKUs anyway while the QRX remains in the UPDATING/COOLDOWN states, so
* this restriction comes into play if we take more than PTO time to send
* an ACK for it (not likely).
*/
unsigned int rxku_pending_confirm : 1;
/* Temporary variable indicating rxku_pending_confirm is to become 0. */
unsigned int rxku_pending_confirm_done : 1;
/*
* If set, RXKU is expected (because we initiated a spontaneous TXKU).
*/
unsigned int rxku_expected : 1;
/* Permanent net error encountered */
unsigned int net_error : 1;
/* Saved error stack in case permanent error was encountered */
ERR_STATE *err_state;
};
# endif
#endif
| 16,334 | 38.552058 | 82 | h |
openssl | openssl-master/ssl/quic/quic_demux.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/quic_demux.h"
#include "internal/quic_wire_pkt.h"
#include "internal/common.h"
#include <openssl/lhash.h>
#include <openssl/err.h>
#define URXE_DEMUX_STATE_FREE 0 /* on urx_free list */
#define URXE_DEMUX_STATE_PENDING 1 /* on urx_pending list */
#define URXE_DEMUX_STATE_ISSUED 2 /* on neither list */
#define DEMUX_MAX_MSGS_PER_CALL 32
#define DEMUX_DEFAULT_MTU 1500
/* Structure used to track a given connection ID. */
typedef struct quic_demux_conn_st QUIC_DEMUX_CONN;
struct quic_demux_conn_st {
QUIC_DEMUX_CONN *next; /* used when unregistering only */
QUIC_CONN_ID dst_conn_id;
ossl_quic_demux_cb_fn *cb;
void *cb_arg;
};
DEFINE_LHASH_OF_EX(QUIC_DEMUX_CONN);
static unsigned long demux_conn_hash(const QUIC_DEMUX_CONN *conn)
{
size_t i;
unsigned long v = 0;
assert(conn->dst_conn_id.id_len <= QUIC_MAX_CONN_ID_LEN);
for (i = 0; i < conn->dst_conn_id.id_len; ++i)
v ^= ((unsigned long)conn->dst_conn_id.id[i])
<< ((i * 8) % (sizeof(unsigned long) * 8));
return v;
}
static int demux_conn_cmp(const QUIC_DEMUX_CONN *a, const QUIC_DEMUX_CONN *b)
{
return !ossl_quic_conn_id_eq(&a->dst_conn_id, &b->dst_conn_id);
}
struct quic_demux_st {
/* The underlying transport BIO with datagram semantics. */
BIO *net_bio;
/*
* QUIC short packets do not contain the length of the connection ID field,
* therefore it must be known contextually. The demuxer requires connection
* IDs of the same length to be used for all incoming packets.
*/
size_t short_conn_id_len;
/*
* Our current understanding of the upper bound on an incoming datagram size
* in bytes.
*/
size_t mtu;
/* Time retrieval callback. */
OSSL_TIME (*now)(void *arg);
void *now_arg;
/* Hashtable mapping connection IDs to QUIC_DEMUX_CONN structures. */
LHASH_OF(QUIC_DEMUX_CONN) *conns_by_id;
/* The default packet handler, if any. */
ossl_quic_demux_cb_fn *default_cb;
void *default_cb_arg;
/*
* List of URXEs which are not currently in use (i.e., not filled with
* unconsumed data). These are moved to the pending list as they are filled.
*/
QUIC_URXE_LIST urx_free;
/*
* List of URXEs which are filled with received encrypted data. These are
* removed from this list as we invoke the callbacks for each of them. They
* are then not on any list managed by us; we forget about them until our
* user calls ossl_quic_demux_release_urxe to return the URXE to us, at
* which point we add it to the free list.
*/
QUIC_URXE_LIST urx_pending;
/* Whether to use local address support. */
char use_local_addr;
};
QUIC_DEMUX *ossl_quic_demux_new(BIO *net_bio,
size_t short_conn_id_len,
OSSL_TIME (*now)(void *arg),
void *now_arg)
{
QUIC_DEMUX *demux;
demux = OPENSSL_zalloc(sizeof(QUIC_DEMUX));
if (demux == NULL)
return NULL;
demux->net_bio = net_bio;
demux->short_conn_id_len = short_conn_id_len;
/* We update this if possible when we get a BIO. */
demux->mtu = DEMUX_DEFAULT_MTU;
demux->now = now;
demux->now_arg = now_arg;
demux->conns_by_id
= lh_QUIC_DEMUX_CONN_new(demux_conn_hash, demux_conn_cmp);
if (demux->conns_by_id == NULL) {
OPENSSL_free(demux);
return NULL;
}
if (net_bio != NULL
&& BIO_dgram_get_local_addr_cap(net_bio)
&& BIO_dgram_set_local_addr_enable(net_bio, 1))
demux->use_local_addr = 1;
return demux;
}
static void demux_free_conn_it(QUIC_DEMUX_CONN *conn, void *arg)
{
OPENSSL_free(conn);
}
static void demux_free_urxl(QUIC_URXE_LIST *l)
{
QUIC_URXE *e, *enext;
for (e = ossl_list_urxe_head(l); e != NULL; e = enext) {
enext = ossl_list_urxe_next(e);
ossl_list_urxe_remove(l, e);
OPENSSL_free(e);
}
}
void ossl_quic_demux_free(QUIC_DEMUX *demux)
{
if (demux == NULL)
return;
/* Free all connection structures. */
lh_QUIC_DEMUX_CONN_doall_arg(demux->conns_by_id, demux_free_conn_it, NULL);
lh_QUIC_DEMUX_CONN_free(demux->conns_by_id);
/* Free all URXEs we are holding. */
demux_free_urxl(&demux->urx_free);
demux_free_urxl(&demux->urx_pending);
OPENSSL_free(demux);
}
void ossl_quic_demux_set_bio(QUIC_DEMUX *demux, BIO *net_bio)
{
unsigned int mtu;
demux->net_bio = net_bio;
if (net_bio != NULL) {
/*
* Try to determine our MTU if possible. The BIO is not required to
* support this, in which case we remain at the last known MTU, or our
* initial default.
*/
mtu = BIO_dgram_get_mtu(net_bio);
if (mtu >= QUIC_MIN_INITIAL_DGRAM_LEN)
ossl_quic_demux_set_mtu(demux, mtu); /* best effort */
}
}
int ossl_quic_demux_set_mtu(QUIC_DEMUX *demux, unsigned int mtu)
{
if (mtu < QUIC_MIN_INITIAL_DGRAM_LEN)
return 0;
demux->mtu = mtu;
return 1;
}
static QUIC_DEMUX_CONN *demux_get_by_conn_id(QUIC_DEMUX *demux,
const QUIC_CONN_ID *dst_conn_id)
{
QUIC_DEMUX_CONN key;
if (dst_conn_id->id_len > QUIC_MAX_CONN_ID_LEN)
return NULL;
key.dst_conn_id = *dst_conn_id;
return lh_QUIC_DEMUX_CONN_retrieve(demux->conns_by_id, &key);
}
int ossl_quic_demux_register(QUIC_DEMUX *demux,
const QUIC_CONN_ID *dst_conn_id,
ossl_quic_demux_cb_fn *cb, void *cb_arg)
{
QUIC_DEMUX_CONN *conn;
if (dst_conn_id == NULL
|| dst_conn_id->id_len > QUIC_MAX_CONN_ID_LEN
|| cb == NULL)
return 0;
/* Ensure not already registered. */
if (demux_get_by_conn_id(demux, dst_conn_id) != NULL)
/* Handler already registered with this connection ID. */
return 0;
conn = OPENSSL_zalloc(sizeof(QUIC_DEMUX_CONN));
if (conn == NULL)
return 0;
conn->dst_conn_id = *dst_conn_id;
conn->cb = cb;
conn->cb_arg = cb_arg;
lh_QUIC_DEMUX_CONN_insert(demux->conns_by_id, conn);
return 1;
}
static void demux_unregister(QUIC_DEMUX *demux,
QUIC_DEMUX_CONN *conn)
{
lh_QUIC_DEMUX_CONN_delete(demux->conns_by_id, conn);
OPENSSL_free(conn);
}
int ossl_quic_demux_unregister(QUIC_DEMUX *demux,
const QUIC_CONN_ID *dst_conn_id)
{
QUIC_DEMUX_CONN *conn;
if (dst_conn_id == NULL
|| dst_conn_id->id_len > QUIC_MAX_CONN_ID_LEN)
return 0;
conn = demux_get_by_conn_id(demux, dst_conn_id);
if (conn == NULL)
return 0;
demux_unregister(demux, conn);
return 1;
}
struct unreg_arg {
ossl_quic_demux_cb_fn *cb;
void *cb_arg;
QUIC_DEMUX_CONN *head;
};
static void demux_unregister_by_cb(QUIC_DEMUX_CONN *conn, void *arg_)
{
struct unreg_arg *arg = arg_;
if (conn->cb == arg->cb && conn->cb_arg == arg->cb_arg) {
conn->next = arg->head;
arg->head = conn;
}
}
void ossl_quic_demux_unregister_by_cb(QUIC_DEMUX *demux,
ossl_quic_demux_cb_fn *cb,
void *cb_arg)
{
QUIC_DEMUX_CONN *conn, *cnext;
struct unreg_arg arg = {0};
arg.cb = cb;
arg.cb_arg = cb_arg;
lh_QUIC_DEMUX_CONN_doall_arg(demux->conns_by_id,
demux_unregister_by_cb, &arg);
for (conn = arg.head; conn != NULL; conn = cnext) {
cnext = conn->next;
demux_unregister(demux, conn);
}
}
void ossl_quic_demux_set_default_handler(QUIC_DEMUX *demux,
ossl_quic_demux_cb_fn *cb,
void *cb_arg)
{
demux->default_cb = cb;
demux->default_cb_arg = cb_arg;
}
static QUIC_URXE *demux_alloc_urxe(size_t alloc_len)
{
QUIC_URXE *e;
if (alloc_len >= SIZE_MAX - sizeof(QUIC_URXE))
return NULL;
e = OPENSSL_malloc(sizeof(QUIC_URXE) + alloc_len);
if (e == NULL)
return NULL;
ossl_list_urxe_init_elem(e);
e->alloc_len = alloc_len;
e->data_len = 0;
return e;
}
static QUIC_URXE *demux_resize_urxe(QUIC_DEMUX *demux, QUIC_URXE *e,
size_t new_alloc_len)
{
QUIC_URXE *e2, *prev;
if (!ossl_assert(e->demux_state == URXE_DEMUX_STATE_FREE))
/* Never attempt to resize a URXE which is not on the free list. */
return NULL;
prev = ossl_list_urxe_prev(e);
ossl_list_urxe_remove(&demux->urx_free, e);
e2 = OPENSSL_realloc(e, sizeof(QUIC_URXE) + new_alloc_len);
if (e2 == NULL) {
/* Failed to resize, abort. */
if (prev == NULL)
ossl_list_urxe_insert_head(&demux->urx_free, e);
else
ossl_list_urxe_insert_after(&demux->urx_free, prev, e);
return NULL;
}
if (prev == NULL)
ossl_list_urxe_insert_head(&demux->urx_free, e2);
else
ossl_list_urxe_insert_after(&demux->urx_free, prev, e2);
e2->alloc_len = new_alloc_len;
return e2;
}
static QUIC_URXE *demux_reserve_urxe(QUIC_DEMUX *demux, QUIC_URXE *e,
size_t alloc_len)
{
return e->alloc_len < alloc_len ? demux_resize_urxe(demux, e, alloc_len) : e;
}
static int demux_ensure_free_urxe(QUIC_DEMUX *demux, size_t min_num_free)
{
QUIC_URXE *e;
while (ossl_list_urxe_num(&demux->urx_free) < min_num_free) {
e = demux_alloc_urxe(demux->mtu);
if (e == NULL)
return 0;
ossl_list_urxe_insert_tail(&demux->urx_free, e);
e->demux_state = URXE_DEMUX_STATE_FREE;
}
return 1;
}
/*
* Receive datagrams from network, placing them into URXEs.
*
* Returns 1 on success or 0 on failure.
*
* Precondition: at least one URXE is free
* Precondition: there are no pending URXEs
*/
static int demux_recv(QUIC_DEMUX *demux)
{
BIO_MSG msg[DEMUX_MAX_MSGS_PER_CALL];
size_t rd, i;
QUIC_URXE *urxe = ossl_list_urxe_head(&demux->urx_free), *unext;
OSSL_TIME now;
/* This should never be called when we have any pending URXE. */
assert(ossl_list_urxe_head(&demux->urx_pending) == NULL);
assert(urxe->demux_state == URXE_DEMUX_STATE_FREE);
if (demux->net_bio == NULL)
/*
* If no BIO is plugged in, treat this as no datagram being available.
*/
return QUIC_DEMUX_PUMP_RES_TRANSIENT_FAIL;
/*
* Opportunistically receive as many messages as possible in a single
* syscall, determined by how many free URXEs are available.
*/
for (i = 0; i < (ossl_ssize_t)OSSL_NELEM(msg);
++i, urxe = ossl_list_urxe_next(urxe)) {
if (urxe == NULL) {
/* We need at least one URXE to receive into. */
if (!ossl_assert(i > 0))
return QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL;
break;
}
/* Ensure the URXE is big enough. */
urxe = demux_reserve_urxe(demux, urxe, demux->mtu);
if (urxe == NULL)
/* Allocation error, fail. */
return QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL;
/* Ensure we zero any fields added to BIO_MSG at a later date. */
memset(&msg[i], 0, sizeof(BIO_MSG));
msg[i].data = ossl_quic_urxe_data(urxe);
msg[i].data_len = urxe->alloc_len;
msg[i].peer = &urxe->peer;
BIO_ADDR_clear(&urxe->peer);
if (demux->use_local_addr)
msg[i].local = &urxe->local;
else
BIO_ADDR_clear(&urxe->local);
}
ERR_set_mark();
if (!BIO_recvmmsg(demux->net_bio, msg, sizeof(BIO_MSG), i, 0, &rd)) {
if (BIO_err_is_non_fatal(ERR_peek_last_error())) {
/* Transient error, clear the error and stop. */
ERR_pop_to_mark();
return QUIC_DEMUX_PUMP_RES_TRANSIENT_FAIL;
} else {
/* Non-transient error, do not clear the error. */
ERR_clear_last_mark();
return QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL;
}
}
ERR_clear_last_mark();
now = demux->now != NULL ? demux->now(demux->now_arg) : ossl_time_zero();
urxe = ossl_list_urxe_head(&demux->urx_free);
for (i = 0; i < rd; ++i, urxe = unext) {
unext = ossl_list_urxe_next(urxe);
/* Set URXE with actual length of received datagram. */
urxe->data_len = msg[i].data_len;
/* Time we received datagram. */
urxe->time = now;
/* Move from free list to pending list. */
ossl_list_urxe_remove(&demux->urx_free, urxe);
ossl_list_urxe_insert_tail(&demux->urx_pending, urxe);
urxe->demux_state = URXE_DEMUX_STATE_PENDING;
}
return QUIC_DEMUX_PUMP_RES_OK;
}
/* Extract destination connection ID from the first packet in a datagram. */
static int demux_identify_conn_id(QUIC_DEMUX *demux,
QUIC_URXE *e,
QUIC_CONN_ID *dst_conn_id)
{
return ossl_quic_wire_get_pkt_hdr_dst_conn_id(ossl_quic_urxe_data(e),
e->data_len,
demux->short_conn_id_len,
dst_conn_id);
}
/* Identify the connection structure corresponding to a given URXE. */
static QUIC_DEMUX_CONN *demux_identify_conn(QUIC_DEMUX *demux, QUIC_URXE *e)
{
QUIC_CONN_ID dst_conn_id;
if (!demux_identify_conn_id(demux, e, &dst_conn_id))
/*
* Datagram is so badly malformed we can't get the DCID from the first
* packet in it, so just give up.
*/
return NULL;
return demux_get_by_conn_id(demux, &dst_conn_id);
}
/* Process a single pending URXE. */
static int demux_process_pending_urxe(QUIC_DEMUX *demux, QUIC_URXE *e)
{
QUIC_DEMUX_CONN *conn;
/* The next URXE we process should be at the head of the pending list. */
if (!ossl_assert(e == ossl_list_urxe_head(&demux->urx_pending)))
return 0;
assert(e->demux_state == URXE_DEMUX_STATE_PENDING);
conn = demux_identify_conn(demux, e);
if (conn == NULL) {
/*
* We could not identify a connection. If we have a default packet
* handler, pass it to the handler. Otherwise, we will never be able to
* process this datagram, so get rid of it.
*/
ossl_list_urxe_remove(&demux->urx_pending, e);
if (demux->default_cb != NULL) {
/* Pass to default handler. */
e->demux_state = URXE_DEMUX_STATE_ISSUED;
demux->default_cb(e, demux->default_cb_arg);
} else {
/* Discard. */
ossl_list_urxe_insert_tail(&demux->urx_free, e);
e->demux_state = URXE_DEMUX_STATE_FREE;
}
return 1; /* keep processing pending URXEs */
}
/*
* Remove from list and invoke callback. The URXE now belongs to the
* callback. (QUIC_DEMUX_CONN never has non-NULL cb.)
*/
ossl_list_urxe_remove(&demux->urx_pending, e);
e->demux_state = URXE_DEMUX_STATE_ISSUED;
conn->cb(e, conn->cb_arg);
return 1;
}
/* Process pending URXEs to generate callbacks. */
static int demux_process_pending_urxl(QUIC_DEMUX *demux)
{
QUIC_URXE *e;
while ((e = ossl_list_urxe_head(&demux->urx_pending)) != NULL)
if (!demux_process_pending_urxe(demux, e))
return 0;
return 1;
}
/*
* Drain the pending URXE list, processing any pending URXEs by making their
* callbacks. If no URXEs are pending, a network read is attempted first.
*/
int ossl_quic_demux_pump(QUIC_DEMUX *demux)
{
int ret;
if (ossl_list_urxe_head(&demux->urx_pending) == NULL) {
ret = demux_ensure_free_urxe(demux, DEMUX_MAX_MSGS_PER_CALL);
if (ret != 1)
return QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL;
ret = demux_recv(demux);
if (ret != QUIC_DEMUX_PUMP_RES_OK)
return ret;
/*
* If demux_recv returned successfully, we should always have something.
*/
assert(ossl_list_urxe_head(&demux->urx_pending) != NULL);
}
if (!demux_process_pending_urxl(demux))
return QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL;
return QUIC_DEMUX_PUMP_RES_OK;
}
/* Artificially inject a packet into the demuxer for testing purposes. */
int ossl_quic_demux_inject(QUIC_DEMUX *demux,
const unsigned char *buf,
size_t buf_len,
const BIO_ADDR *peer,
const BIO_ADDR *local)
{
int ret;
QUIC_URXE *urxe;
ret = demux_ensure_free_urxe(demux, 1);
if (ret != 1)
return 0;
urxe = ossl_list_urxe_head(&demux->urx_free);
assert(urxe->demux_state == URXE_DEMUX_STATE_FREE);
urxe = demux_reserve_urxe(demux, urxe, buf_len);
if (urxe == NULL)
return 0;
memcpy(ossl_quic_urxe_data(urxe), buf, buf_len);
urxe->data_len = buf_len;
if (peer != NULL)
urxe->peer = *peer;
else
BIO_ADDR_clear(&urxe->peer);
if (local != NULL)
urxe->local = *local;
else
BIO_ADDR_clear(&urxe->local);
urxe->time
= demux->now != NULL ? demux->now(demux->now_arg) : ossl_time_zero();
/* Move from free list to pending list. */
ossl_list_urxe_remove(&demux->urx_free, urxe);
ossl_list_urxe_insert_tail(&demux->urx_pending, urxe);
urxe->demux_state = URXE_DEMUX_STATE_PENDING;
return demux_process_pending_urxl(demux);
}
/* Called by our user to return a URXE to the free list. */
void ossl_quic_demux_release_urxe(QUIC_DEMUX *demux,
QUIC_URXE *e)
{
assert(ossl_list_urxe_prev(e) == NULL && ossl_list_urxe_next(e) == NULL);
assert(e->demux_state == URXE_DEMUX_STATE_ISSUED);
ossl_list_urxe_insert_tail(&demux->urx_free, e);
e->demux_state = URXE_DEMUX_STATE_FREE;
}
void ossl_quic_demux_reinject_urxe(QUIC_DEMUX *demux,
QUIC_URXE *e)
{
assert(ossl_list_urxe_prev(e) == NULL && ossl_list_urxe_next(e) == NULL);
assert(e->demux_state == URXE_DEMUX_STATE_ISSUED);
ossl_list_urxe_insert_head(&demux->urx_pending, e);
e->demux_state = URXE_DEMUX_STATE_PENDING;
}
int ossl_quic_demux_has_pending(const QUIC_DEMUX *demux)
{
return ossl_list_urxe_head(&demux->urx_pending) != NULL;
}
| 19,247 | 29.216641 | 81 | c |
openssl | openssl-master/ssl/quic/quic_fc.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/quic_fc.h"
#include "internal/quic_error.h"
#include "internal/common.h"
#include "internal/safe_math.h"
#include <assert.h>
OSSL_SAFE_MATH_UNSIGNED(uint64_t, uint64_t)
/*
* TX Flow Controller (TXFC)
* =========================
*/
int ossl_quic_txfc_init(QUIC_TXFC *txfc, QUIC_TXFC *conn_txfc)
{
if (conn_txfc != NULL && conn_txfc->parent != NULL)
return 0;
txfc->swm = 0;
txfc->cwm = 0;
txfc->parent = conn_txfc;
txfc->has_become_blocked = 0;
return 1;
}
QUIC_TXFC *ossl_quic_txfc_get_parent(QUIC_TXFC *txfc)
{
return txfc->parent;
}
int ossl_quic_txfc_bump_cwm(QUIC_TXFC *txfc, uint64_t cwm)
{
if (cwm <= txfc->cwm)
return 0;
txfc->cwm = cwm;
return 1;
}
uint64_t ossl_quic_txfc_get_credit_local(QUIC_TXFC *txfc)
{
assert(txfc->swm <= txfc->cwm);
return txfc->cwm - txfc->swm;
}
uint64_t ossl_quic_txfc_get_credit(QUIC_TXFC *txfc)
{
uint64_t r, conn_r;
r = ossl_quic_txfc_get_credit_local(txfc);
if (txfc->parent != NULL) {
assert(txfc->parent->parent == NULL);
conn_r = ossl_quic_txfc_get_credit_local(txfc->parent);
if (conn_r < r)
r = conn_r;
}
return r;
}
int ossl_quic_txfc_consume_credit_local(QUIC_TXFC *txfc, uint64_t num_bytes)
{
int ok = 1;
uint64_t credit = ossl_quic_txfc_get_credit_local(txfc);
if (num_bytes > credit) {
ok = 0;
num_bytes = credit;
}
if (num_bytes > 0 && num_bytes == credit)
txfc->has_become_blocked = 1;
txfc->swm += num_bytes;
return ok;
}
int ossl_quic_txfc_consume_credit(QUIC_TXFC *txfc, uint64_t num_bytes)
{
int ok = ossl_quic_txfc_consume_credit_local(txfc, num_bytes);
if (txfc->parent != NULL) {
assert(txfc->parent->parent == NULL);
if (!ossl_quic_txfc_consume_credit_local(txfc->parent, num_bytes))
return 0;
}
return ok;
}
int ossl_quic_txfc_has_become_blocked(QUIC_TXFC *txfc, int clear)
{
int r = txfc->has_become_blocked;
if (clear)
txfc->has_become_blocked = 0;
return r;
}
uint64_t ossl_quic_txfc_get_cwm(QUIC_TXFC *txfc)
{
return txfc->cwm;
}
uint64_t ossl_quic_txfc_get_swm(QUIC_TXFC *txfc)
{
return txfc->swm;
}
/*
* RX Flow Controller (RXFC)
* =========================
*/
int ossl_quic_rxfc_init(QUIC_RXFC *rxfc, QUIC_RXFC *conn_rxfc,
uint64_t initial_window_size,
uint64_t max_window_size,
OSSL_TIME (*now)(void *now_arg),
void *now_arg)
{
if (conn_rxfc != NULL && conn_rxfc->parent != NULL)
return 0;
rxfc->swm = 0;
rxfc->cwm = initial_window_size;
rxfc->rwm = 0;
rxfc->esrwm = 0;
rxfc->hwm = 0;
rxfc->cur_window_size = initial_window_size;
rxfc->max_window_size = max_window_size;
rxfc->parent = conn_rxfc;
rxfc->error_code = 0;
rxfc->has_cwm_changed = 0;
rxfc->epoch_start = ossl_time_zero();
rxfc->now = now;
rxfc->now_arg = now_arg;
rxfc->is_fin = 0;
rxfc->stream_count_mode = 0;
return 1;
}
int ossl_quic_rxfc_init_for_stream_count(QUIC_RXFC *rxfc,
uint64_t initial_window_size,
OSSL_TIME (*now)(void *arg),
void *now_arg)
{
if (!ossl_quic_rxfc_init(rxfc, NULL,
initial_window_size, initial_window_size,
now, now_arg))
return 0;
rxfc->stream_count_mode = 1;
return 1;
}
QUIC_RXFC *ossl_quic_rxfc_get_parent(QUIC_RXFC *rxfc)
{
return rxfc->parent;
}
void ossl_quic_rxfc_set_max_window_size(QUIC_RXFC *rxfc,
size_t max_window_size)
{
rxfc->max_window_size = max_window_size;
}
static void rxfc_start_epoch(QUIC_RXFC *rxfc)
{
rxfc->epoch_start = rxfc->now(rxfc->now_arg);
rxfc->esrwm = rxfc->rwm;
}
static int on_rx_controlled_bytes(QUIC_RXFC *rxfc, uint64_t num_bytes)
{
int ok = 1;
uint64_t credit = rxfc->cwm - rxfc->swm;
if (num_bytes > credit) {
ok = 0;
num_bytes = credit;
rxfc->error_code = QUIC_ERR_FLOW_CONTROL_ERROR;
}
rxfc->swm += num_bytes;
return ok;
}
int ossl_quic_rxfc_on_rx_stream_frame(QUIC_RXFC *rxfc, uint64_t end, int is_fin)
{
uint64_t delta;
if (!rxfc->stream_count_mode && rxfc->parent == NULL)
return 0;
if (rxfc->is_fin && ((is_fin && rxfc->hwm != end) || end > rxfc->hwm)) {
/* Stream size cannot change after the stream is finished */
rxfc->error_code = QUIC_ERR_FINAL_SIZE_ERROR;
return 1; /* not a caller error */
}
if (is_fin)
rxfc->is_fin = 1;
if (end > rxfc->hwm) {
delta = end - rxfc->hwm;
rxfc->hwm = end;
on_rx_controlled_bytes(rxfc, delta); /* result ignored */
if (rxfc->parent != NULL)
on_rx_controlled_bytes(rxfc->parent, delta); /* result ignored */
} else if (end < rxfc->hwm && is_fin) {
rxfc->error_code = QUIC_ERR_FINAL_SIZE_ERROR;
return 1; /* not a caller error */
}
return 1;
}
/* threshold = 3/4 */
#define WINDOW_THRESHOLD_NUM 3
#define WINDOW_THRESHOLD_DEN 4
static int rxfc_cwm_bump_desired(QUIC_RXFC *rxfc)
{
int err = 0;
uint64_t window_rem = rxfc->cwm - rxfc->rwm;
uint64_t threshold
= safe_mul_uint64_t(rxfc->cur_window_size,
WINDOW_THRESHOLD_NUM, &err) / WINDOW_THRESHOLD_DEN;
if (err)
/*
* Extremely large window should never occur, but if it does, just use
* 1/2 as the threshold.
*/
threshold = rxfc->cur_window_size / 2;
/*
* No point emitting a new MAX_STREAM_DATA frame if the stream has a final
* size.
*/
return !rxfc->is_fin && window_rem <= threshold;
}
static int rxfc_should_bump_window_size(QUIC_RXFC *rxfc, OSSL_TIME rtt)
{
/*
* dt: time since start of epoch
* b: bytes of window consumed since start of epoch
* dw: proportion of window consumed since start of epoch
* T_window: time it will take to use up the entire window, based on dt, dw
* RTT: The current estimated RTT.
*
* b = rwm - esrwm
* dw = b / window_size
* T_window = dt / dw
* T_window = dt / (b / window_size)
* T_window = (dt * window_size) / b
*
* We bump the window size if T_window < 4 * RTT.
*
* We leave the division by b on the LHS to reduce the risk of overflowing
* our 64-bit nanosecond representation, which will afford plenty of
* precision left over after the division anyway.
*/
uint64_t b = rxfc->rwm - rxfc->esrwm;
OSSL_TIME now, dt, t_window;
if (b == 0)
return 0;
now = rxfc->now(rxfc->now_arg);
dt = ossl_time_subtract(now, rxfc->epoch_start);
t_window = ossl_time_muldiv(dt, rxfc->cur_window_size, b);
return ossl_time_compare(t_window, ossl_time_multiply(rtt, 4)) < 0;
}
static void rxfc_adjust_window_size(QUIC_RXFC *rxfc, uint64_t min_window_size,
OSSL_TIME rtt)
{
/* Are we sending updates too often? */
uint64_t new_window_size;
new_window_size = rxfc->cur_window_size;
if (rxfc_should_bump_window_size(rxfc, rtt))
new_window_size *= 2;
if (new_window_size < min_window_size)
new_window_size = min_window_size;
if (new_window_size > rxfc->max_window_size) /* takes precedence over min size */
new_window_size = rxfc->max_window_size;
rxfc->cur_window_size = new_window_size;
rxfc_start_epoch(rxfc);
}
static void rxfc_update_cwm(QUIC_RXFC *rxfc, uint64_t min_window_size,
OSSL_TIME rtt)
{
uint64_t new_cwm;
if (!rxfc_cwm_bump_desired(rxfc))
return;
rxfc_adjust_window_size(rxfc, min_window_size, rtt);
new_cwm = rxfc->rwm + rxfc->cur_window_size;
if (new_cwm > rxfc->cwm) {
rxfc->cwm = new_cwm;
rxfc->has_cwm_changed = 1;
}
}
static int rxfc_on_retire(QUIC_RXFC *rxfc, uint64_t num_bytes,
uint64_t min_window_size,
OSSL_TIME rtt)
{
if (ossl_time_is_zero(rxfc->epoch_start))
/* This happens when we retire our first ever bytes. */
rxfc_start_epoch(rxfc);
rxfc->rwm += num_bytes;
rxfc_update_cwm(rxfc, min_window_size, rtt);
return 1;
}
int ossl_quic_rxfc_on_retire(QUIC_RXFC *rxfc,
uint64_t num_bytes,
OSSL_TIME rtt)
{
if (rxfc->parent == NULL && !rxfc->stream_count_mode)
return 0;
if (num_bytes == 0)
return 1;
if (rxfc->rwm + num_bytes > rxfc->swm)
/* Impossible for us to retire more bytes than we have received. */
return 0;
rxfc_on_retire(rxfc, num_bytes, 0, rtt);
if (!rxfc->stream_count_mode)
rxfc_on_retire(rxfc->parent, num_bytes, rxfc->cur_window_size, rtt);
return 1;
}
uint64_t ossl_quic_rxfc_get_cwm(QUIC_RXFC *rxfc)
{
return rxfc->cwm;
}
uint64_t ossl_quic_rxfc_get_swm(QUIC_RXFC *rxfc)
{
return rxfc->swm;
}
uint64_t ossl_quic_rxfc_get_rwm(QUIC_RXFC *rxfc)
{
return rxfc->rwm;
}
int ossl_quic_rxfc_has_cwm_changed(QUIC_RXFC *rxfc, int clear)
{
int r = rxfc->has_cwm_changed;
if (clear)
rxfc->has_cwm_changed = 0;
return r;
}
int ossl_quic_rxfc_get_error(QUIC_RXFC *rxfc, int clear)
{
int r = rxfc->error_code;
if (clear)
rxfc->error_code = 0;
return r;
}
int ossl_quic_rxfc_get_final_size(const QUIC_RXFC *rxfc, uint64_t *final_size)
{
if (!rxfc->is_fin)
return 0;
if (final_size != NULL)
*final_size = rxfc->hwm;
return 1;
}
| 10,393 | 24.538084 | 85 | c |
openssl | openssl-master/ssl/quic/quic_fifd.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/quic_fifd.h"
#include "internal/quic_wire.h"
DEFINE_LIST_OF(tx_history, OSSL_ACKM_TX_PKT);
int ossl_quic_fifd_init(QUIC_FIFD *fifd,
QUIC_CFQ *cfq,
OSSL_ACKM *ackm,
QUIC_TXPIM *txpim,
/* stream_id is UINT64_MAX for the crypto stream */
QUIC_SSTREAM *(*get_sstream_by_id)(uint64_t stream_id,
uint32_t pn_space,
void *arg),
void *get_sstream_by_id_arg,
/* stream_id is UINT64_MAX if not applicable */
void (*regen_frame)(uint64_t frame_type,
uint64_t stream_id,
QUIC_TXPIM_PKT *pkt,
void *arg),
void *regen_frame_arg,
void (*confirm_frame)(uint64_t frame_type,
uint64_t stream_id,
QUIC_TXPIM_PKT *pkt,
void *arg),
void *confirm_frame_arg,
void (*sstream_updated)(uint64_t stream_id,
void *arg),
void *sstream_updated_arg)
{
if (cfq == NULL || ackm == NULL || txpim == NULL
|| get_sstream_by_id == NULL || regen_frame == NULL)
return 0;
fifd->cfq = cfq;
fifd->ackm = ackm;
fifd->txpim = txpim;
fifd->get_sstream_by_id = get_sstream_by_id;
fifd->get_sstream_by_id_arg = get_sstream_by_id_arg;
fifd->regen_frame = regen_frame;
fifd->regen_frame_arg = regen_frame_arg;
fifd->confirm_frame = confirm_frame;
fifd->confirm_frame_arg = confirm_frame_arg;
fifd->sstream_updated = sstream_updated;
fifd->sstream_updated_arg = sstream_updated_arg;
return 1;
}
void ossl_quic_fifd_cleanup(QUIC_FIFD *fifd)
{
/* No-op. */
}
static void on_acked(void *arg)
{
QUIC_TXPIM_PKT *pkt = arg;
QUIC_FIFD *fifd = pkt->fifd;
const QUIC_TXPIM_CHUNK *chunks = ossl_quic_txpim_pkt_get_chunks(pkt);
size_t i, num_chunks = ossl_quic_txpim_pkt_get_num_chunks(pkt);
QUIC_SSTREAM *sstream;
QUIC_CFQ_ITEM *cfq_item, *cfq_item_next;
/* STREAM and CRYPTO stream chunks, FINs and stream FC frames */
for (i = 0; i < num_chunks; ++i) {
sstream = fifd->get_sstream_by_id(chunks[i].stream_id,
pkt->ackm_pkt.pkt_space,
fifd->get_sstream_by_id_arg);
if (sstream == NULL)
continue;
if (chunks[i].end >= chunks[i].start)
ossl_quic_sstream_mark_acked(sstream,
chunks[i].start, chunks[i].end);
if (chunks[i].has_fin && chunks[i].stream_id != UINT64_MAX)
ossl_quic_sstream_mark_acked_fin(sstream);
if (chunks[i].has_stop_sending && chunks[i].stream_id != UINT64_MAX)
fifd->confirm_frame(OSSL_QUIC_FRAME_TYPE_STOP_SENDING,
chunks[i].stream_id, pkt,
fifd->confirm_frame_arg);
if (chunks[i].has_reset_stream && chunks[i].stream_id != UINT64_MAX)
fifd->confirm_frame(OSSL_QUIC_FRAME_TYPE_RESET_STREAM,
chunks[i].stream_id, pkt,
fifd->confirm_frame_arg);
if (ossl_quic_sstream_is_totally_acked(sstream))
fifd->sstream_updated(chunks[i].stream_id, fifd->sstream_updated_arg);
}
/* GCR */
for (cfq_item = pkt->retx_head; cfq_item != NULL; cfq_item = cfq_item_next) {
cfq_item_next = cfq_item->pkt_next;
ossl_quic_cfq_release(fifd->cfq, cfq_item);
}
ossl_quic_txpim_pkt_release(fifd->txpim, pkt);
}
static void on_lost(void *arg)
{
QUIC_TXPIM_PKT *pkt = arg;
QUIC_FIFD *fifd = pkt->fifd;
const QUIC_TXPIM_CHUNK *chunks = ossl_quic_txpim_pkt_get_chunks(pkt);
size_t i, num_chunks = ossl_quic_txpim_pkt_get_num_chunks(pkt);
QUIC_SSTREAM *sstream;
QUIC_CFQ_ITEM *cfq_item, *cfq_item_next;
int sstream_updated;
/* STREAM and CRYPTO stream chunks, FIN and stream FC frames */
for (i = 0; i < num_chunks; ++i) {
sstream = fifd->get_sstream_by_id(chunks[i].stream_id,
pkt->ackm_pkt.pkt_space,
fifd->get_sstream_by_id_arg);
if (sstream == NULL)
continue;
sstream_updated = 0;
if (chunks[i].end >= chunks[i].start) {
/*
* Note: If the stream is being reset, we do not need to retransmit
* old data as this is pointless. In this case this will be handled
* by (sstream == NULL) above as the QSM will free the QUIC_SSTREAM
* and our call to get_sstream_by_id above will return NULL.
*/
ossl_quic_sstream_mark_lost(sstream,
chunks[i].start, chunks[i].end);
sstream_updated = 1;
}
if (chunks[i].has_fin && chunks[i].stream_id != UINT64_MAX) {
ossl_quic_sstream_mark_lost_fin(sstream);
sstream_updated = 1;
}
if (chunks[i].has_stop_sending && chunks[i].stream_id != UINT64_MAX)
fifd->regen_frame(OSSL_QUIC_FRAME_TYPE_STOP_SENDING,
chunks[i].stream_id, pkt,
fifd->regen_frame_arg);
if (chunks[i].has_reset_stream && chunks[i].stream_id != UINT64_MAX)
fifd->regen_frame(OSSL_QUIC_FRAME_TYPE_RESET_STREAM,
chunks[i].stream_id, pkt,
fifd->regen_frame_arg);
/*
* Inform caller that stream needs an FC frame.
*
* Note: We could track whether an FC frame was sent originally for the
* stream to determine if it really needs to be regenerated or not.
* However, if loss has occurred, it's probably better to ensure the
* peer has up-to-date flow control data for the stream. Given that
* these frames are extremely small, we may as well always send it when
* handling loss.
*/
fifd->regen_frame(OSSL_QUIC_FRAME_TYPE_MAX_STREAM_DATA,
chunks[i].stream_id,
pkt,
fifd->regen_frame_arg);
if (sstream_updated && chunks[i].stream_id != UINT64_MAX)
fifd->sstream_updated(chunks[i].stream_id,
fifd->sstream_updated_arg);
}
/* GCR */
for (cfq_item = pkt->retx_head; cfq_item != NULL; cfq_item = cfq_item_next) {
cfq_item_next = cfq_item->pkt_next;
ossl_quic_cfq_mark_lost(fifd->cfq, cfq_item, UINT32_MAX);
}
/* Regenerate flag frames */
if (pkt->had_handshake_done_frame)
fifd->regen_frame(OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE,
UINT64_MAX, pkt,
fifd->regen_frame_arg);
if (pkt->had_max_data_frame)
fifd->regen_frame(OSSL_QUIC_FRAME_TYPE_MAX_DATA,
UINT64_MAX, pkt,
fifd->regen_frame_arg);
if (pkt->had_max_streams_bidi_frame)
fifd->regen_frame(OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_BIDI,
UINT64_MAX, pkt,
fifd->regen_frame_arg);
if (pkt->had_max_streams_uni_frame)
fifd->regen_frame(OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_UNI,
UINT64_MAX, pkt,
fifd->regen_frame_arg);
if (pkt->had_ack_frame)
/*
* We always use the ACK_WITH_ECN frame type to represent the ACK frame
* type in our callback; we assume it is the caller's job to decide
* whether it wants to send ECN data or not.
*/
fifd->regen_frame(OSSL_QUIC_FRAME_TYPE_ACK_WITH_ECN,
UINT64_MAX, pkt,
fifd->regen_frame_arg);
ossl_quic_txpim_pkt_release(fifd->txpim, pkt);
}
static void on_discarded(void *arg)
{
QUIC_TXPIM_PKT *pkt = arg;
QUIC_FIFD *fifd = pkt->fifd;
QUIC_CFQ_ITEM *cfq_item, *cfq_item_next;
/*
* Don't need to do anything to SSTREAMs for STREAM and CRYPTO streams, as
* we assume caller will clean them up.
*/
/* GCR */
for (cfq_item = pkt->retx_head; cfq_item != NULL; cfq_item = cfq_item_next) {
cfq_item_next = cfq_item->pkt_next;
ossl_quic_cfq_release(fifd->cfq, cfq_item);
}
ossl_quic_txpim_pkt_release(fifd->txpim, pkt);
}
int ossl_quic_fifd_pkt_commit(QUIC_FIFD *fifd, QUIC_TXPIM_PKT *pkt)
{
QUIC_CFQ_ITEM *cfq_item;
const QUIC_TXPIM_CHUNK *chunks;
size_t i, num_chunks;
QUIC_SSTREAM *sstream;
pkt->fifd = fifd;
pkt->ackm_pkt.on_lost = on_lost;
pkt->ackm_pkt.on_acked = on_acked;
pkt->ackm_pkt.on_discarded = on_discarded;
pkt->ackm_pkt.cb_arg = pkt;
ossl_list_tx_history_init_elem(&pkt->ackm_pkt);
pkt->ackm_pkt.anext = pkt->ackm_pkt.lnext = NULL;
/*
* Mark the CFQ items which have been added to this packet as having been
* transmitted.
*/
for (cfq_item = pkt->retx_head;
cfq_item != NULL;
cfq_item = cfq_item->pkt_next)
ossl_quic_cfq_mark_tx(fifd->cfq, cfq_item);
/*
* Mark the send stream chunks which have been added to the packet as having
* been transmitted.
*/
chunks = ossl_quic_txpim_pkt_get_chunks(pkt);
num_chunks = ossl_quic_txpim_pkt_get_num_chunks(pkt);
for (i = 0; i < num_chunks; ++i) {
sstream = fifd->get_sstream_by_id(chunks[i].stream_id,
pkt->ackm_pkt.pkt_space,
fifd->get_sstream_by_id_arg);
if (sstream == NULL)
continue;
if (chunks[i].end >= chunks[i].start
&& !ossl_quic_sstream_mark_transmitted(sstream,
chunks[i].start,
chunks[i].end))
return 0;
if (chunks[i].has_fin
&& !ossl_quic_sstream_mark_transmitted_fin(sstream,
chunks[i].end + 1))
return 0;
}
/* Inform the ACKM. */
return ossl_ackm_on_tx_packet(fifd->ackm, &pkt->ackm_pkt);
}
| 11,208 | 37.651724 | 82 | c |
openssl | openssl-master/ssl/quic/quic_local.h | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_QUIC_LOCAL_H
# define OSSL_QUIC_LOCAL_H
# include <openssl/ssl.h>
# include "internal/quic_ssl.h" /* QUIC_CONNECTION */
# include "internal/quic_txp.h"
# include "internal/quic_statm.h"
# include "internal/quic_demux.h"
# include "internal/quic_record_rx.h"
# include "internal/quic_tls.h"
# include "internal/quic_fc.h"
# include "internal/quic_stream.h"
# include "internal/quic_channel.h"
# include "internal/quic_reactor.h"
# include "internal/quic_thread_assist.h"
# include "../ssl_local.h"
# ifndef OPENSSL_NO_QUIC
/*
* QUIC stream SSL object (QSSO) type. This implements the API personality layer
* for QSSO objects, wrapping the QUIC-native QUIC_STREAM object and tracking
* state required by the libssl API personality.
*/
struct quic_xso_st {
/* SSL object common header. */
struct ssl_st ssl;
/* The connection this stream is associated with. Always non-NULL. */
QUIC_CONNECTION *conn;
/* The stream object. Always non-NULL for as long as the XSO exists. */
QUIC_STREAM *stream;
/* Is this stream in blocking mode? */
unsigned int blocking : 1;
/*
* This state tracks SSL_write all-or-nothing (AON) write semantics
* emulation.
*
* Example chronology:
*
* t=0: aon_write_in_progress=0
* t=1: SSL_write(ssl, b1, l1) called;
* too big to enqueue into sstream at once, SSL_ERROR_WANT_WRITE;
* aon_write_in_progress=1; aon_buf_base=b1; aon_buf_len=l1;
* aon_buf_pos < l1 (depends on how much room was in sstream);
* t=2: SSL_write(ssl, b2, l2);
* b2 must equal b1 (validated unless ACCEPT_MOVING_WRITE_BUFFER)
* l2 must equal l1 (always validated)
* append into sstream from [b2 + aon_buf_pos, b2 + aon_buf_len)
* if done, aon_write_in_progess=0
*
*/
/* Is an AON write in progress? */
unsigned int aon_write_in_progress : 1;
/*
* The base buffer pointer the caller passed us for the initial AON write
* call. We use this for validation purposes unless
* ACCEPT_MOVING_WRITE_BUFFER is enabled.
*
* NOTE: We never dereference this, as the caller might pass a different
* (but identical) buffer if using ACCEPT_MOVING_WRITE_BUFFER. It is for
* validation by pointer comparison only.
*/
const unsigned char *aon_buf_base;
/* The total length of the AON buffer being sent, in bytes. */
size_t aon_buf_len;
/*
* The position in the AON buffer up to which we have successfully sent data
* so far.
*/
size_t aon_buf_pos;
/* SSL_set_mode */
uint32_t ssl_mode;
/* SSL_set_options */
uint64_t ssl_options;
/*
* Last 'normal' error during an app-level I/O operation, used by
* SSL_get_error(); used to track data-path errors like SSL_ERROR_WANT_READ
* and SSL_ERROR_WANT_WRITE.
*/
int last_error;
};
struct quic_conn_st {
/*
* ssl_st is a common header for ordinary SSL objects, QUIC connection
* objects and QUIC stream objects, allowing objects of these different
* types to be disambiguated at runtime and providing some common fields.
*
* Note: This must come first in the QUIC_CONNECTION structure.
*/
struct ssl_st ssl;
SSL *tls;
/*
* The QUIC channel providing the core QUIC connection implementation. Note
* that this is not instantiated until we actually start trying to do the
* handshake. This is to allow us to gather information like whether we are
* going to be in client or server mode before committing to instantiating
* the channel, since we want to determine the channel arguments based on
* that.
*
* The channel remains available after connection termination until the SSL
* object is freed, thus (ch != NULL) iff (started == 1).
*/
QUIC_CHANNEL *ch;
/*
* The mutex used to synchronise access to the QUIC_CHANNEL. We own this but
* provide it to the channel.
*/
CRYPTO_MUTEX *mutex;
/*
* If we have a default stream attached, this is the internal XSO
* object. If there is no default stream, this is NULL.
*/
QUIC_XSO *default_xso;
/* The network read and write BIOs. */
BIO *net_rbio, *net_wbio;
/* Initial peer L4 address. */
BIO_ADDR init_peer_addr;
# ifndef OPENSSL_NO_QUIC_THREAD_ASSIST
/* Manages thread for QUIC thread assisted mode. */
QUIC_THREAD_ASSIST thread_assist;
# endif
/* If non-NULL, used instead of ossl_time_now(). Used for testing. */
OSSL_TIME (*override_now_cb)(void *arg);
void *override_now_cb_arg;
/* Number of XSOs allocated. Includes the default XSO, if any. */
size_t num_xso;
/* Have we started? */
unsigned int started : 1;
/* Can the read and write network BIOs support blocking? */
unsigned int can_poll_net_rbio : 1;
unsigned int can_poll_net_wbio : 1;
/*
* This is 1 if we were instantiated using a QUIC server method
* (for future use).
*/
unsigned int as_server : 1;
/*
* Has the application called SSL_set_accept_state? We require this to be
* congruent with the value of as_server.
*/
unsigned int as_server_state : 1;
/* Are we using thread assisted mode? Never changes after init. */
unsigned int is_thread_assisted : 1;
/* Do connection-level operations (e.g. handshakes) run in blocking mode? */
unsigned int blocking : 1;
/* Do newly created streams start in blocking mode? Inherited by new XSOs. */
unsigned int default_blocking : 1;
/* Have we created a default XSO yet? */
unsigned int default_xso_created : 1;
/* Default stream type. Defaults to SSL_DEFAULT_STREAM_MODE_AUTO_BIDI. */
uint32_t default_stream_mode;
/* SSL_set_mode. This is not used directly but inherited by new XSOs. */
uint32_t default_ssl_mode;
/* SSL_set_options. This is not used directly but inherited by new XSOs. */
uint64_t default_ssl_options;
/* SSL_set_incoming_stream_policy. */
int incoming_stream_policy;
uint64_t incoming_stream_aec;
/*
* Last 'normal' error during an app-level I/O operation, used by
* SSL_get_error(); used to track data-path errors like SSL_ERROR_WANT_READ
* and SSL_ERROR_WANT_WRITE.
*/
int last_error;
};
/* Internal calls to the QUIC CSM which come from various places. */
int ossl_quic_conn_on_handshake_confirmed(QUIC_CONNECTION *qc);
/*
* To be called when a protocol violation occurs. The connection is torn down
* with the given error code, which should be a QUIC_ERR_* value. Reason string
* is optional and copied if provided. frame_type should be 0 if not applicable.
*/
void ossl_quic_conn_raise_protocol_error(QUIC_CONNECTION *qc,
uint64_t error_code,
uint64_t frame_type,
const char *reason);
void ossl_quic_conn_on_remote_conn_close(QUIC_CONNECTION *qc,
OSSL_QUIC_FRAME_CONN_CLOSE *f);
int ossl_quic_trace(int write_p, int version, int content_type,
const void *buf, size_t msglen, SSL *ssl, void *arg);
# define OSSL_QUIC_ANY_VERSION 0xFFFFF
# define IS_QUIC_METHOD(m) \
((m) == OSSL_QUIC_client_method() || \
(m) == OSSL_QUIC_client_thread_method())
# define IS_QUIC_CTX(ctx) IS_QUIC_METHOD((ctx)->method)
# define QUIC_CONNECTION_FROM_SSL_int(ssl, c) \
((ssl) == NULL ? NULL \
: ((ssl)->type == SSL_TYPE_QUIC_CONNECTION \
? (c QUIC_CONNECTION *)(ssl) \
: NULL))
# define QUIC_XSO_FROM_SSL_int(ssl, c) \
((ssl) == NULL \
? NULL \
: (((ssl)->type == SSL_TYPE_QUIC_XSO \
? (c QUIC_XSO *)(ssl) \
: ((ssl)->type == SSL_TYPE_QUIC_CONNECTION \
? (c QUIC_XSO *)((QUIC_CONNECTION *)(ssl))->default_xso \
: NULL))))
# define SSL_CONNECTION_FROM_QUIC_SSL_int(ssl, c) \
((ssl) == NULL ? NULL \
: ((ssl)->type == SSL_TYPE_QUIC_CONNECTION \
? (c SSL_CONNECTION *)((c QUIC_CONNECTION *)(ssl))->tls \
: NULL))
# define IS_QUIC(ssl) ((ssl) != NULL \
&& ((ssl)->type == SSL_TYPE_QUIC_CONNECTION \
|| (ssl)->type == SSL_TYPE_QUIC_XSO))
# else
# define QUIC_CONNECTION_FROM_SSL_int(ssl, c) NULL
# define QUIC_XSO_FROM_SSL_int(ssl, c) NULL
# define SSL_CONNECTION_FROM_QUIC_SSL_int(ssl, c) NULL
# define IS_QUIC(ssl) 0
# define IS_QUIC_CTX(ctx) 0
# define IS_QUIC_METHOD(m) 0
# endif
# define QUIC_CONNECTION_FROM_SSL(ssl) \
QUIC_CONNECTION_FROM_SSL_int(ssl, SSL_CONNECTION_NO_CONST)
# define QUIC_CONNECTION_FROM_CONST_SSL(ssl) \
QUIC_CONNECTION_FROM_SSL_int(ssl, const)
# define QUIC_XSO_FROM_SSL(ssl) \
QUIC_XSO_FROM_SSL_int(ssl, SSL_CONNECTION_NO_CONST)
# define QUIC_XSO_FROM_CONST_SSL(ssl) \
QUIC_XSO_FROM_SSL_int(ssl, const)
# define SSL_CONNECTION_FROM_QUIC_SSL(ssl) \
SSL_CONNECTION_FROM_QUIC_SSL_int(ssl, SSL_CONNECTION_NO_CONST)
# define SSL_CONNECTION_FROM_CONST_QUIC_SSL(ssl) \
SSL_CONNECTION_FROM_CONST_QUIC_SSL_int(ssl, const)
# define IMPLEMENT_quic_meth_func(version, func_name, q_accept, \
q_connect, enc_data) \
const SSL_METHOD *func_name(void) \
{ \
static const SSL_METHOD func_name##_data= { \
version, \
0, \
0, \
ossl_quic_new, \
ossl_quic_free, \
ossl_quic_reset, \
ossl_quic_init, \
ossl_quic_clear, \
ossl_quic_deinit, \
q_accept, \
q_connect, \
ossl_quic_read, \
ossl_quic_peek, \
ossl_quic_write, \
NULL /* shutdown */, \
NULL /* renegotiate */, \
ossl_quic_renegotiate_check, \
NULL /* read_bytes */, \
NULL /* write_bytes */, \
NULL /* dispatch_alert */, \
ossl_quic_ctrl, \
ossl_quic_ctx_ctrl, \
NULL /* get_cipher_by_char */, \
NULL /* put_cipher_by_char */, \
ossl_quic_pending, \
ossl_quic_num_ciphers, \
ossl_quic_get_cipher, \
tls1_default_timeout, \
&enc_data, \
ssl_undefined_void_function, \
ossl_quic_callback_ctrl, \
ossl_quic_ctx_callback_ctrl, \
}; \
return &func_name##_data; \
}
#endif
| 12,306 | 37.579937 | 81 | h |
openssl | openssl-master/ssl/quic/quic_method.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/macros.h>
#include <openssl/objects.h>
#include "quic_local.h"
IMPLEMENT_quic_meth_func(OSSL_QUIC_ANY_VERSION,
OSSL_QUIC_client_method,
ssl_undefined_function,
ossl_quic_connect, ssl3_undef_enc_method)
IMPLEMENT_quic_meth_func(OSSL_QUIC_ANY_VERSION,
OSSL_QUIC_client_thread_method,
ssl_undefined_function,
ossl_quic_connect, ssl3_undef_enc_method)
| 850 | 36 | 74 | c |
openssl | openssl-master/ssl/quic/quic_reactor.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/quic_reactor.h"
#include "internal/common.h"
#include "internal/thread_arch.h"
/*
* Core I/O Reactor Framework
* ==========================
*/
void ossl_quic_reactor_init(QUIC_REACTOR *rtor,
void (*tick_cb)(QUIC_TICK_RESULT *res, void *arg,
uint32_t flags),
void *tick_cb_arg,
OSSL_TIME initial_tick_deadline)
{
rtor->poll_r.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
rtor->poll_w.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
rtor->net_read_desired = 0;
rtor->net_write_desired = 0;
rtor->tick_deadline = initial_tick_deadline;
rtor->tick_cb = tick_cb;
rtor->tick_cb_arg = tick_cb_arg;
}
void ossl_quic_reactor_set_poll_r(QUIC_REACTOR *rtor, const BIO_POLL_DESCRIPTOR *r)
{
rtor->poll_r = *r;
}
void ossl_quic_reactor_set_poll_w(QUIC_REACTOR *rtor, const BIO_POLL_DESCRIPTOR *w)
{
rtor->poll_w = *w;
}
const BIO_POLL_DESCRIPTOR *ossl_quic_reactor_get_poll_r(QUIC_REACTOR *rtor)
{
return &rtor->poll_r;
}
const BIO_POLL_DESCRIPTOR *ossl_quic_reactor_get_poll_w(QUIC_REACTOR *rtor)
{
return &rtor->poll_w;
}
int ossl_quic_reactor_net_read_desired(QUIC_REACTOR *rtor)
{
return rtor->net_read_desired;
}
int ossl_quic_reactor_net_write_desired(QUIC_REACTOR *rtor)
{
return rtor->net_write_desired;
}
OSSL_TIME ossl_quic_reactor_get_tick_deadline(QUIC_REACTOR *rtor)
{
return rtor->tick_deadline;
}
int ossl_quic_reactor_tick(QUIC_REACTOR *rtor, uint32_t flags)
{
QUIC_TICK_RESULT res = {0};
/*
* Note that the tick callback cannot fail; this is intentional. Arguably it
* does not make that much sense for ticking to 'fail' (in the sense of an
* explicit error indicated to the user) because ticking is by its nature
* best effort. If something fatal happens with a connection we can report
* it on the next actual application I/O call.
*/
rtor->tick_cb(&res, rtor->tick_cb_arg, flags);
rtor->net_read_desired = res.net_read_desired;
rtor->net_write_desired = res.net_write_desired;
rtor->tick_deadline = res.tick_deadline;
return 1;
}
/*
* Blocking I/O Adaptation Layer
* =============================
*/
/*
* Utility which can be used to poll on up to two FDs. This is designed to
* support use of split FDs (e.g. with SSL_set_rfd and SSL_set_wfd where
* different FDs are used for read and write).
*
* Generally use of poll(2) is preferred where available. Windows, however,
* hasn't traditionally offered poll(2), only select(2). WSAPoll() was
* introduced in Vista but has seemingly been buggy until relatively recent
* versions of Windows 10. Moreover we support XP so this is not a suitable
* target anyway. However, the traditional issues with select(2) turn out not to
* be an issue on Windows; whereas traditional *NIX select(2) uses a bitmap of
* FDs (and thus is limited in the magnitude of the FDs expressible), Windows
* select(2) is very different. In Windows, socket handles are not allocated
* contiguously from zero and thus this bitmap approach was infeasible. Thus in
* adapting the Berkeley sockets API to Windows a different approach was taken
* whereby the fd_set contains a fixed length array of socket handles and an
* integer indicating how many entries are valid; thus Windows select()
* ironically is actually much more like *NIX poll(2) than *NIX select(2). In
* any case, this means that the relevant limit for Windows select() is the
* number of FDs being polled, not the magnitude of those FDs. Since we only
* poll for two FDs here, this limit does not concern us.
*
* Usage: rfd and wfd may be the same or different. Either or both may also be
* -1. If rfd_want_read is 1, rfd is polled for readability, and if
* wfd_want_write is 1, wfd is polled for writability. Note that since any
* passed FD is always polled for error conditions, setting rfd_want_read=0 and
* wfd_want_write=0 is not the same as passing -1 for both FDs.
*
* deadline is a timestamp to return at. If it is ossl_time_infinite(), the call
* never times out.
*
* Returns 0 on error and 1 on success. Timeout expiry is considered a success
* condition. We don't elaborate our return values here because the way we are
* actually using this doesn't currently care.
*
* If mutex is non-NULL, it is assumed to be held for write and is unlocked for
* the duration of the call.
*
* Precondition: mutex is NULL or is held for write (unchecked)
* Postcondition: mutex is NULL or is held for write (unless
* CRYPTO_THREAD_write_lock fails)
*/
static int poll_two_fds(int rfd, int rfd_want_read,
int wfd, int wfd_want_write,
OSSL_TIME deadline,
CRYPTO_MUTEX *mutex)
{
#if defined(OPENSSL_SYS_WINDOWS) || !defined(POLLIN)
fd_set rfd_set, wfd_set, efd_set;
OSSL_TIME now, timeout;
struct timeval tv, *ptv;
int maxfd, pres;
# ifndef OPENSSL_SYS_WINDOWS
/*
* On Windows there is no relevant limit to the magnitude of a fd value (see
* above). On *NIX the fd_set uses a bitmap and we must check the limit.
*/
if (rfd >= FD_SETSIZE || wfd >= FD_SETSIZE)
return 0;
# endif
FD_ZERO(&rfd_set);
FD_ZERO(&wfd_set);
FD_ZERO(&efd_set);
if (rfd != -1 && rfd_want_read)
openssl_fdset(rfd, &rfd_set);
if (wfd != -1 && wfd_want_write)
openssl_fdset(wfd, &wfd_set);
/* Always check for error conditions. */
if (rfd != -1)
openssl_fdset(rfd, &efd_set);
if (wfd != -1)
openssl_fdset(wfd, &efd_set);
maxfd = rfd;
if (wfd > maxfd)
maxfd = wfd;
if (!ossl_assert(rfd != -1 || wfd != -1
|| !ossl_time_is_infinite(deadline)))
/* Do not block forever; should not happen. */
return 0;
# if defined(OPENSSL_THREADS)
if (mutex != NULL)
ossl_crypto_mutex_unlock(mutex);
# endif
do {
/*
* select expects a timeout, not a deadline, so do the conversion.
* Update for each call to ensure the correct value is used if we repeat
* due to EINTR.
*/
if (ossl_time_is_infinite(deadline)) {
ptv = NULL;
} else {
now = ossl_time_now();
/*
* ossl_time_subtract saturates to zero so we don't need to check if
* now > deadline.
*/
timeout = ossl_time_subtract(deadline, now);
tv = ossl_time_to_timeval(timeout);
ptv = &tv;
}
pres = select(maxfd + 1, &rfd_set, &wfd_set, &efd_set, ptv);
} while (pres == -1 && get_last_socket_error_is_eintr());
# if defined(OPENSSL_THREADS)
if (mutex != NULL)
ossl_crypto_mutex_lock(mutex);
# endif
return pres < 0 ? 0 : 1;
#else
int pres, timeout_ms;
OSSL_TIME now, timeout;
struct pollfd pfds[2] = {0};
size_t npfd = 0;
if (rfd == wfd) {
pfds[npfd].fd = rfd;
pfds[npfd].events = (rfd_want_read ? POLLIN : 0)
| (wfd_want_write ? POLLOUT : 0);
if (rfd >= 0 && pfds[npfd].events != 0)
++npfd;
} else {
pfds[npfd].fd = rfd;
pfds[npfd].events = (rfd_want_read ? POLLIN : 0);
if (rfd >= 0 && pfds[npfd].events != 0)
++npfd;
pfds[npfd].fd = wfd;
pfds[npfd].events = (wfd_want_write ? POLLOUT : 0);
if (wfd >= 0 && pfds[npfd].events != 0)
++npfd;
}
if (!ossl_assert(npfd != 0 || !ossl_time_is_infinite(deadline)))
/* Do not block forever; should not happen. */
return 0;
# if defined(OPENSSL_THREADS)
if (mutex != NULL)
ossl_crypto_mutex_unlock(mutex);
# endif
do {
if (ossl_time_is_infinite(deadline)) {
timeout_ms = -1;
} else {
now = ossl_time_now();
timeout = ossl_time_subtract(deadline, now);
timeout_ms = ossl_time2ms(timeout);
}
pres = poll(pfds, npfd, timeout_ms);
} while (pres == -1 && get_last_socket_error_is_eintr());
# if defined(OPENSSL_THREADS)
if (mutex != NULL)
ossl_crypto_mutex_lock(mutex);
# endif
return pres < 0 ? 0 : 1;
#endif
}
static int poll_descriptor_to_fd(const BIO_POLL_DESCRIPTOR *d, int *fd)
{
if (d == NULL || d->type == BIO_POLL_DESCRIPTOR_TYPE_NONE) {
*fd = INVALID_SOCKET;
return 1;
}
if (d->type != BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD
|| d->value.fd == INVALID_SOCKET)
return 0;
*fd = d->value.fd;
return 1;
}
/*
* Poll up to two abstract poll descriptors. Currently we only support
* poll descriptors which represent FDs.
*
* If mutex is non-NULL, it is assumed be a lock currently held for write and is
* unlocked for the duration of any wait.
*
* Precondition: mutex is NULL or is held for write (unchecked)
* Postcondition: mutex is NULL or is held for write (unless
* CRYPTO_THREAD_write_lock fails)
*/
static int poll_two_descriptors(const BIO_POLL_DESCRIPTOR *r, int r_want_read,
const BIO_POLL_DESCRIPTOR *w, int w_want_write,
OSSL_TIME deadline,
CRYPTO_MUTEX *mutex)
{
int rfd, wfd;
if (!poll_descriptor_to_fd(r, &rfd)
|| !poll_descriptor_to_fd(w, &wfd))
return 0;
return poll_two_fds(rfd, r_want_read, wfd, w_want_write, deadline, mutex);
}
/*
* Block until a predicate function evaluates to true.
*
* If mutex is non-NULL, it is assumed be a lock currently held for write and is
* unlocked for the duration of any wait.
*
* Precondition: Must hold channel write lock (unchecked)
* Precondition: mutex is NULL or is held for write (unchecked)
* Postcondition: mutex is NULL or is held for write (unless
* CRYPTO_THREAD_write_lock fails)
*/
int ossl_quic_reactor_block_until_pred(QUIC_REACTOR *rtor,
int (*pred)(void *arg), void *pred_arg,
uint32_t flags,
CRYPTO_MUTEX *mutex)
{
int res;
for (;;) {
if ((flags & SKIP_FIRST_TICK) != 0)
flags &= ~SKIP_FIRST_TICK;
else
/* best effort */
ossl_quic_reactor_tick(rtor, 0);
if ((res = pred(pred_arg)) != 0)
return res;
if (!poll_two_descriptors(ossl_quic_reactor_get_poll_r(rtor),
ossl_quic_reactor_net_read_desired(rtor),
ossl_quic_reactor_get_poll_w(rtor),
ossl_quic_reactor_net_write_desired(rtor),
ossl_quic_reactor_get_tick_deadline(rtor),
mutex))
/*
* We don't actually care why the call succeeded (timeout, FD
* readiness), we just call reactor_tick and start trying to do I/O
* things again. If poll_two_fds returns 0, this is some other
* non-timeout failure and we should stop here.
*
* TODO(QUIC): In the future we could avoid unnecessary syscalls by
* not retrying network I/O that isn't ready based on the result of
* the poll call. However this might be difficult because it
* requires we do the call to poll(2) or equivalent syscall
* ourselves, whereas in the general case the application does the
* polling and just calls SSL_handle_events(). Implementing this
* optimisation in the future will probably therefore require API
* changes.
*/
return 0;
}
}
| 12,283 | 33.408964 | 83 | c |
openssl | openssl-master/ssl/quic/quic_record_shared.c | #include "quic_record_shared.h"
#include "internal/quic_record_util.h"
#include "internal/common.h"
#include "../ssl_local.h"
/* Constants used for key derivation in QUIC v1. */
static const unsigned char quic_v1_iv_label[] = {
0x71, 0x75, 0x69, 0x63, 0x20, 0x69, 0x76 /* "quic iv" */
};
static const unsigned char quic_v1_key_label[] = {
0x71, 0x75, 0x69, 0x63, 0x20, 0x6b, 0x65, 0x79 /* "quic key" */
};
static const unsigned char quic_v1_hp_label[] = {
0x71, 0x75, 0x69, 0x63, 0x20, 0x68, 0x70 /* "quic hp" */
};
static const unsigned char quic_v1_ku_label[] = {
0x71, 0x75, 0x69, 0x63, 0x20, 0x6b, 0x75 /* "quic ku" */
};
OSSL_QRL_ENC_LEVEL *ossl_qrl_enc_level_set_get(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level,
int require_prov)
{
OSSL_QRL_ENC_LEVEL *el;
if (!ossl_assert(enc_level < QUIC_ENC_LEVEL_NUM))
return NULL;
el = &els->el[enc_level];
if (require_prov)
switch (el->state) {
case QRL_EL_STATE_PROV_NORMAL:
case QRL_EL_STATE_PROV_UPDATING:
case QRL_EL_STATE_PROV_COOLDOWN:
break;
default:
return NULL;
}
return el;
}
int ossl_qrl_enc_level_set_have_el(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level)
{
OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0);
switch (el->state) {
case QRL_EL_STATE_UNPROV:
return 0;
case QRL_EL_STATE_PROV_NORMAL:
case QRL_EL_STATE_PROV_UPDATING:
case QRL_EL_STATE_PROV_COOLDOWN:
return 1;
default:
case QRL_EL_STATE_DISCARDED:
return -1;
}
}
int ossl_qrl_enc_level_set_has_keyslot(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level,
unsigned char tgt_state,
size_t keyslot)
{
OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0);
if (!ossl_assert(el != NULL && keyslot < 2))
return 0;
switch (tgt_state) {
case QRL_EL_STATE_PROV_NORMAL:
case QRL_EL_STATE_PROV_UPDATING:
return enc_level == QUIC_ENC_LEVEL_1RTT || keyslot == 0;
case QRL_EL_STATE_PROV_COOLDOWN:
assert(enc_level == QUIC_ENC_LEVEL_1RTT);
return keyslot == (el->key_epoch & 1);
default:
return 0;
}
}
static void el_teardown_keyslot(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level,
size_t keyslot)
{
OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0);
if (!ossl_qrl_enc_level_set_has_keyslot(els, enc_level, el->state, keyslot))
return;
if (el->cctx[keyslot] != NULL) {
EVP_CIPHER_CTX_free(el->cctx[keyslot]);
el->cctx[keyslot] = NULL;
}
OPENSSL_cleanse(el->iv[keyslot], sizeof(el->iv[keyslot]));
}
static int el_setup_keyslot(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level,
unsigned char tgt_state,
size_t keyslot,
const unsigned char *secret,
size_t secret_len)
{
OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0);
unsigned char key[EVP_MAX_KEY_LENGTH];
size_t key_len = 0, iv_len = 0;
const char *cipher_name = NULL;
EVP_CIPHER *cipher = NULL;
EVP_CIPHER_CTX *cctx = NULL;
if (!ossl_assert(el != NULL
&& ossl_qrl_enc_level_set_has_keyslot(els, enc_level,
tgt_state, keyslot)))
return 0;
cipher_name = ossl_qrl_get_suite_cipher_name(el->suite_id);
iv_len = ossl_qrl_get_suite_cipher_iv_len(el->suite_id);
key_len = ossl_qrl_get_suite_cipher_key_len(el->suite_id);
if (cipher_name == NULL)
return 0;
if (secret_len != ossl_qrl_get_suite_secret_len(el->suite_id)
|| secret_len > EVP_MAX_KEY_LENGTH)
return 0;
assert(el->cctx[keyslot] == NULL);
/* Derive "quic iv" key. */
if (!tls13_hkdf_expand_ex(el->libctx, el->propq,
el->md,
secret,
quic_v1_iv_label,
sizeof(quic_v1_iv_label),
NULL, 0,
el->iv[keyslot], iv_len, 0))
goto err;
/* Derive "quic key" key. */
if (!tls13_hkdf_expand_ex(el->libctx, el->propq,
el->md,
secret,
quic_v1_key_label,
sizeof(quic_v1_key_label),
NULL, 0,
key, key_len, 0))
goto err;
/* Create and initialise cipher context. */
if ((cipher = EVP_CIPHER_fetch(el->libctx, cipher_name, el->propq)) == NULL)
goto err;
if ((cctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
if (!ossl_assert(iv_len == (size_t)EVP_CIPHER_get_iv_length(cipher))
|| !ossl_assert(key_len == (size_t)EVP_CIPHER_get_key_length(cipher)))
goto err;
/* IV will be changed on RX/TX so we don't need to use a real value here. */
if (!EVP_CipherInit_ex(cctx, cipher, NULL, key, el->iv[keyslot], 0))
goto err;
el->cctx[keyslot] = cctx;
/* Zeroize intermediate keys. */
OPENSSL_cleanse(key, sizeof(key));
EVP_CIPHER_free(cipher);
return 1;
err:
EVP_CIPHER_CTX_free(cctx);
EVP_CIPHER_free(cipher);
OPENSSL_cleanse(el->iv[keyslot], sizeof(el->iv[keyslot]));
OPENSSL_cleanse(key, sizeof(key));
return 0;
}
int ossl_qrl_enc_level_set_provide_secret(OSSL_QRL_ENC_LEVEL_SET *els,
OSSL_LIB_CTX *libctx,
const char *propq,
uint32_t enc_level,
uint32_t suite_id,
EVP_MD *md,
const unsigned char *secret,
size_t secret_len,
unsigned char init_key_phase_bit,
int is_tx)
{
OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0);
unsigned char ku_key[EVP_MAX_KEY_LENGTH], hpr_key[EVP_MAX_KEY_LENGTH];
int have_ks0 = 0, have_ks1 = 0, own_md = 0;
const char *md_name = ossl_qrl_get_suite_md_name(suite_id);
size_t hpr_key_len, init_keyslot;
if (el == NULL
|| md_name == NULL
|| init_key_phase_bit > 1 || is_tx < 0 || is_tx > 1
|| (init_key_phase_bit > 0 && enc_level != QUIC_ENC_LEVEL_1RTT))
return 0;
if (enc_level == QUIC_ENC_LEVEL_INITIAL
&& el->state == QRL_EL_STATE_PROV_NORMAL) {
/*
* Sometimes the INITIAL EL needs to be reprovisioned, namely if a
* connection retry occurs. Exceptionally, if the caller wants to
* reprovision the INITIAL EL, tear it down as usual and then override
* the state so it can be provisioned again.
*/
ossl_qrl_enc_level_set_discard(els, enc_level);
el->state = QRL_EL_STATE_UNPROV;
}
if (el->state != QRL_EL_STATE_UNPROV)
return 0;
init_keyslot = is_tx ? 0 : init_key_phase_bit;
hpr_key_len = ossl_qrl_get_suite_hdr_prot_key_len(suite_id);
if (hpr_key_len == 0)
return 0;
if (md == NULL) {
md = EVP_MD_fetch(libctx, md_name, propq);
if (md == NULL)
return 0;
own_md = 1;
}
el->libctx = libctx;
el->propq = propq;
el->md = md;
el->suite_id = suite_id;
el->tag_len = ossl_qrl_get_suite_cipher_tag_len(suite_id);
el->op_count = 0;
el->key_epoch = (uint64_t)init_key_phase_bit;
el->is_tx = (unsigned char)is_tx;
/* Derive "quic hp" key. */
if (!tls13_hkdf_expand_ex(libctx, propq,
md,
secret,
quic_v1_hp_label,
sizeof(quic_v1_hp_label),
NULL, 0,
hpr_key, hpr_key_len, 0))
goto err;
/* Setup KS0 (or KS1 if init_key_phase_bit), our initial keyslot. */
if (!el_setup_keyslot(els, enc_level, QRL_EL_STATE_PROV_NORMAL,
init_keyslot, secret, secret_len))
goto err;
have_ks0 = 1;
if (enc_level == QUIC_ENC_LEVEL_1RTT) {
/* Derive "quic ku" key (the epoch 1 secret). */
if (!tls13_hkdf_expand_ex(libctx, propq,
md,
secret,
quic_v1_ku_label,
sizeof(quic_v1_ku_label),
NULL, 0,
is_tx ? el->ku : ku_key, secret_len, 0))
goto err;
if (!is_tx) {
/* Setup KS1 (or KS0 if init_key_phase_bit), our next keyslot. */
if (!el_setup_keyslot(els, enc_level, QRL_EL_STATE_PROV_NORMAL,
!init_keyslot, ku_key, secret_len))
goto err;
have_ks1 = 1;
/* Derive NEXT "quic ku" key (the epoch 2 secret). */
if (!tls13_hkdf_expand_ex(libctx, propq,
md,
ku_key,
quic_v1_ku_label,
sizeof(quic_v1_ku_label),
NULL, 0,
el->ku, secret_len, 0))
goto err;
}
}
/* Setup header protection context. */
if (!ossl_quic_hdr_protector_init(&el->hpr,
libctx, propq,
ossl_qrl_get_suite_hdr_prot_cipher_id(suite_id),
hpr_key, hpr_key_len))
goto err;
/*
* We are now provisioned: KS0 has our current key (for key epoch 0), KS1
* has our next key (for key epoch 1, in the case of the 1-RTT EL only), and
* el->ku has the secret which will be used to generate keys for key epoch
* 2.
*/
OPENSSL_cleanse(hpr_key, sizeof(hpr_key));
OPENSSL_cleanse(ku_key, sizeof(ku_key));
el->state = QRL_EL_STATE_PROV_NORMAL;
return 1;
err:
el->suite_id = 0;
OPENSSL_cleanse(hpr_key, sizeof(hpr_key));
OPENSSL_cleanse(ku_key, sizeof(ku_key));
OPENSSL_cleanse(el->ku, sizeof(el->ku));
if (have_ks0)
el_teardown_keyslot(els, enc_level, 0);
if (have_ks1)
el_teardown_keyslot(els, enc_level, 1);
if (own_md)
EVP_MD_free(md);
return 0;
}
int ossl_qrl_enc_level_set_key_update(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level)
{
OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0);
size_t secret_len;
unsigned char new_ku[EVP_MAX_KEY_LENGTH];
if (el == NULL || !ossl_assert(enc_level == QUIC_ENC_LEVEL_1RTT))
return 0;
if (el->state != QRL_EL_STATE_PROV_NORMAL)
return 0;
if (!el->is_tx) {
/*
* We already have the key for the next epoch, so just move to using it.
*/
++el->key_epoch;
el->state = QRL_EL_STATE_PROV_UPDATING;
return 1;
}
/*
* TX case. For the TX side we use only keyslot 0; it replaces the old key
* immediately.
*/
secret_len = ossl_qrl_get_suite_secret_len(el->suite_id);
/* Derive NEXT "quic ku" key (the epoch n+1 secret). */
if (!tls13_hkdf_expand_ex(el->libctx, el->propq,
el->md, el->ku,
quic_v1_ku_label,
sizeof(quic_v1_ku_label),
NULL, 0,
new_ku, secret_len, 0))
return 0;
el_teardown_keyslot(els, enc_level, 0);
/* Setup keyslot for CURRENT "quic ku" key. */
if (!el_setup_keyslot(els, enc_level, QRL_EL_STATE_PROV_NORMAL,
0, el->ku, secret_len))
return 0;
++el->key_epoch;
el->op_count = 0;
memcpy(el->ku, new_ku, secret_len);
/* Remain in PROV_NORMAL state */
return 1;
}
/* Transitions from PROV_UPDATING to PROV_COOLDOWN. */
int ossl_qrl_enc_level_set_key_update_done(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level)
{
OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0);
if (el == NULL || !ossl_assert(enc_level == QUIC_ENC_LEVEL_1RTT))
return 0;
/* No new key yet, but erase key material to aid PFS. */
el_teardown_keyslot(els, enc_level, ~el->key_epoch & 1);
el->state = QRL_EL_STATE_PROV_COOLDOWN;
return 1;
}
/*
* Transitions from PROV_COOLDOWN to PROV_NORMAL. (If in PROV_UPDATING,
* auto-transitions to PROV_COOLDOWN first.)
*/
int ossl_qrl_enc_level_set_key_cooldown_done(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level)
{
OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0);
size_t secret_len;
unsigned char new_ku[EVP_MAX_KEY_LENGTH];
if (el == NULL || !ossl_assert(enc_level == QUIC_ENC_LEVEL_1RTT))
return 0;
if (el->state == QRL_EL_STATE_PROV_UPDATING
&& !ossl_qrl_enc_level_set_key_update_done(els, enc_level))
return 0;
if (el->state != QRL_EL_STATE_PROV_COOLDOWN)
return 0;
secret_len = ossl_qrl_get_suite_secret_len(el->suite_id);
if (!el_setup_keyslot(els, enc_level, QRL_EL_STATE_PROV_NORMAL,
~el->key_epoch & 1, el->ku, secret_len))
return 0;
/* Derive NEXT "quic ku" key (the epoch n+1 secret). */
if (!tls13_hkdf_expand_ex(el->libctx, el->propq,
el->md,
el->ku,
quic_v1_ku_label,
sizeof(quic_v1_ku_label),
NULL, 0,
new_ku, secret_len, 0)) {
el_teardown_keyslot(els, enc_level, ~el->key_epoch & 1);
return 0;
}
memcpy(el->ku, new_ku, secret_len);
el->state = QRL_EL_STATE_PROV_NORMAL;
return 1;
}
/*
* Discards keying material for a given encryption level. Transitions from any
* state to DISCARDED.
*/
void ossl_qrl_enc_level_set_discard(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level)
{
OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0);
if (el == NULL || el->state == QRL_EL_STATE_DISCARDED)
return;
if (ossl_qrl_enc_level_set_have_el(els, enc_level) == 1) {
ossl_quic_hdr_protector_cleanup(&el->hpr);
el_teardown_keyslot(els, enc_level, 0);
el_teardown_keyslot(els, enc_level, 1);
}
EVP_MD_free(el->md);
el->md = NULL;
el->state = QRL_EL_STATE_DISCARDED;
}
| 15,478 | 33.01978 | 86 | c |
openssl | openssl-master/ssl/quic/quic_record_shared.h | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_QUIC_RECORD_SHARED_H
# define OSSL_QUIC_RECORD_SHARED_H
# include <openssl/ssl.h>
# include "internal/quic_types.h"
# include "internal/quic_wire_pkt.h"
/*
* QUIC Record Layer EL Management Utilities
* =========================================
*
* This defines a structure for managing the cryptographic state at a given
* encryption level, as this functionality is shared between QRX and QTX. For
* QRL use only.
*/
/*
* States an EL can be in. The Updating and Cooldown states are used by RX only;
* a TX EL in the Provisioned state is always in the Normal substate.
*
* Key material is available if in the Provisioned state.
*/
#define QRL_EL_STATE_UNPROV 0 /* Unprovisioned (initial state) */
#define QRL_EL_STATE_PROV_NORMAL 1 /* Provisioned - Normal */
#define QRL_EL_STATE_PROV_UPDATING 2 /* Provisioned - Updating */
#define QRL_EL_STATE_PROV_COOLDOWN 3 /* Provisioned - Cooldown */
#define QRL_EL_STATE_DISCARDED 4 /* Discarded (terminal state) */
typedef struct ossl_qrl_enc_level_st {
/*
* Cryptographic context used to apply and remove header protection from
* packet headers.
*/
QUIC_HDR_PROTECTOR hpr;
/* Hash function used for key derivation. */
EVP_MD *md;
/* Context used for packet body ciphering. One for each keyslot. */
EVP_CIPHER_CTX *cctx[2];
OSSL_LIB_CTX *libctx;
const char *propq;
/*
* Key epoch, essentially the number of times we have done a key update.
*
* The least significant bit of this is therefore by definition the current
* Key Phase bit value.
*/
uint64_t key_epoch;
/* Usage counter. The caller maintains this. Used by TX side only. */
uint64_t op_count;
/* QRL_SUITE_* value. */
uint32_t suite_id;
/* Length of authentication tag. */
uint32_t tag_len;
/* Current EL state. */
unsigned char state; /* QRL_EL_STATE_* */
/* 1 if for TX, else RX. Initialised when secret provided. */
unsigned char is_tx;
/* IV used to construct nonces used for AEAD packet body ciphering. */
unsigned char iv[2][EVP_MAX_IV_LENGTH];
/*
* Secret for next key epoch.
*/
unsigned char ku[EVP_MAX_KEY_LENGTH];
} OSSL_QRL_ENC_LEVEL;
typedef struct ossl_qrl_enc_level_set_st {
OSSL_QRL_ENC_LEVEL el[QUIC_ENC_LEVEL_NUM];
} OSSL_QRL_ENC_LEVEL_SET;
/*
* Returns 1 if we have key material for a given encryption level (that is, if
* we are in the PROVISIONED state), 0 if we do not yet have material (we are in
* the UNPROVISIONED state) and -1 if the EL is discarded (we are in the
* DISCARDED state).
*/
int ossl_qrl_enc_level_set_have_el(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level);
/*
* Returns EL in a set. If enc_level is not a valid QUIC_ENC_LEVEL_* value,
* returns NULL. If require_prov is 1, returns NULL if the EL is not in
* the PROVISIONED state; otherwise, the returned EL may be in any state.
*/
OSSL_QRL_ENC_LEVEL *ossl_qrl_enc_level_set_get(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level,
int require_prov);
/* Provide secret to an EL. md may be NULL. */
int ossl_qrl_enc_level_set_provide_secret(OSSL_QRL_ENC_LEVEL_SET *els,
OSSL_LIB_CTX *libctx,
const char *propq,
uint32_t enc_level,
uint32_t suite_id,
EVP_MD *md,
const unsigned char *secret,
size_t secret_len,
unsigned char init_key_phase_bit,
int is_tx);
/*
* Returns 1 if the given keyslot index is currently valid for a given EL and EL
* state.
*/
int ossl_qrl_enc_level_set_has_keyslot(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level,
unsigned char tgt_state,
size_t keyslot);
/* Perform a key update. Transitions from PROV_NORMAL to PROV_UPDATING. */
int ossl_qrl_enc_level_set_key_update(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level);
/* Transitions from PROV_UPDATING to PROV_COOLDOWN. */
int ossl_qrl_enc_level_set_key_update_done(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level);
/*
* Transitions from PROV_COOLDOWN to PROV_NORMAL. (If in PROV_UPDATING,
* auto-transitions to PROV_COOLDOWN first.)
*/
int ossl_qrl_enc_level_set_key_cooldown_done(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level);
/*
* Discard an EL. No secret can be provided for the EL ever again.
*/
void ossl_qrl_enc_level_set_discard(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level);
#endif
| 5,627 | 36.271523 | 80 | h |
openssl | openssl-master/ssl/quic/quic_record_util.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/quic_record_util.h"
#include "internal/quic_record_rx.h"
#include "internal/quic_record_tx.h"
#include "internal/quic_wire_pkt.h"
#include "../ssl_local.h"
#include <openssl/kdf.h>
#include <openssl/core_names.h>
/*
* QUIC Key Derivation Utilities
* =============================
*/
int ossl_quic_hkdf_extract(OSSL_LIB_CTX *libctx,
const char *propq,
const EVP_MD *md,
const unsigned char *salt, size_t salt_len,
const unsigned char *ikm, size_t ikm_len,
unsigned char *out, size_t out_len)
{
int ret = 0;
EVP_KDF *kdf = NULL;
EVP_KDF_CTX *kctx = NULL;
OSSL_PARAM params[7], *p = params;
int mode = EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY;
const char *md_name;
if ((md_name = EVP_MD_get0_name(md)) == NULL
|| (kdf = EVP_KDF_fetch(libctx, OSSL_KDF_NAME_HKDF, propq)) == NULL
|| (kctx = EVP_KDF_CTX_new(kdf)) == NULL)
goto err;
*p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode);
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
(char *)md_name, 0);
*p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT,
(unsigned char *)salt, salt_len);
*p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
(unsigned char *)ikm, ikm_len);
*p++ = OSSL_PARAM_construct_end();
ret = EVP_KDF_derive(kctx, out, out_len, params);
err:
EVP_KDF_CTX_free(kctx);
EVP_KDF_free(kdf);
return ret;
}
/* Constants used for key derivation in QUIC v1. */
static const unsigned char quic_client_in_label[] = {
0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x69, 0x6e /* "client in" */
};
static const unsigned char quic_server_in_label[] = {
0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x69, 0x6e /* "server in" */
};
/* Salt used to derive Initial packet protection keys (RFC 9001 Section 5.2). */
static const unsigned char quic_v1_initial_salt[] = {
0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17,
0x9a, 0xe6, 0xa4, 0xc8, 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a
};
int ossl_quic_provide_initial_secret(OSSL_LIB_CTX *libctx,
const char *propq,
const QUIC_CONN_ID *dst_conn_id,
int is_server,
struct ossl_qrx_st *qrx,
struct ossl_qtx_st *qtx)
{
unsigned char initial_secret[32];
unsigned char client_initial_secret[32], server_initial_secret[32];
unsigned char *rx_secret, *tx_secret;
EVP_MD *sha256;
if (qrx == NULL && qtx == NULL)
return 1;
/* Initial encryption always uses SHA-256. */
if ((sha256 = EVP_MD_fetch(libctx, "SHA256", propq)) == NULL)
return 0;
if (is_server) {
rx_secret = client_initial_secret;
tx_secret = server_initial_secret;
} else {
rx_secret = server_initial_secret;
tx_secret = client_initial_secret;
}
/* Derive initial secret from destination connection ID. */
if (!ossl_quic_hkdf_extract(libctx, propq,
sha256,
quic_v1_initial_salt,
sizeof(quic_v1_initial_salt),
dst_conn_id->id,
dst_conn_id->id_len,
initial_secret,
sizeof(initial_secret)))
goto err;
/* Derive "client in" secret. */
if (((qtx != NULL && tx_secret == client_initial_secret)
|| (qrx != NULL && rx_secret == client_initial_secret))
&& !tls13_hkdf_expand_ex(libctx, propq,
sha256,
initial_secret,
quic_client_in_label,
sizeof(quic_client_in_label),
NULL, 0,
client_initial_secret,
sizeof(client_initial_secret), 0))
goto err;
/* Derive "server in" secret. */
if (((qtx != NULL && tx_secret == server_initial_secret)
|| (qrx != NULL && rx_secret == server_initial_secret))
&& !tls13_hkdf_expand_ex(libctx, propq,
sha256,
initial_secret,
quic_server_in_label,
sizeof(quic_server_in_label),
NULL, 0,
server_initial_secret,
sizeof(server_initial_secret), 0))
goto err;
/* Setup RX EL. Initial encryption always uses AES-128-GCM. */
if (qrx != NULL
&& !ossl_qrx_provide_secret(qrx, QUIC_ENC_LEVEL_INITIAL,
QRL_SUITE_AES128GCM,
sha256,
rx_secret,
sizeof(server_initial_secret)))
goto err;
/*
* ossl_qrx_provide_secret takes ownership of our ref to SHA256, so if we
* are initialising both sides, get a new ref for the following call for the
* TX side.
*/
if (qrx != NULL && qtx != NULL && !EVP_MD_up_ref(sha256)) {
sha256 = NULL;
goto err;
}
/* Setup TX cipher. */
if (qtx != NULL
&& !ossl_qtx_provide_secret(qtx, QUIC_ENC_LEVEL_INITIAL,
QRL_SUITE_AES128GCM,
sha256,
tx_secret,
sizeof(server_initial_secret)))
goto err;
return 1;
err:
EVP_MD_free(sha256);
return 0;
}
/*
* QUIC Record Layer Ciphersuite Info
* ==================================
*/
struct suite_info {
const char *cipher_name, *md_name;
uint32_t secret_len, cipher_key_len, cipher_iv_len, cipher_tag_len;
uint32_t hdr_prot_key_len, hdr_prot_cipher_id;
uint64_t max_pkt, max_forged_pkt;
};
static const struct suite_info suite_aes128gcm = {
"AES-128-GCM", "SHA256", 32, 16, 12, 16, 16,
QUIC_HDR_PROT_CIPHER_AES_128,
((uint64_t)1) << 23, /* Limits as prescribed by RFC 9001 */
((uint64_t)1) << 52,
};
static const struct suite_info suite_aes256gcm = {
"AES-256-GCM", "SHA384", 48, 32, 12, 16, 32,
QUIC_HDR_PROT_CIPHER_AES_256,
((uint64_t)1) << 23, /* Limits as prescribed by RFC 9001 */
((uint64_t)1) << 52,
};
static const struct suite_info suite_chacha20poly1305 = {
"ChaCha20-Poly1305", "SHA256", 32, 32, 12, 16, 32,
QUIC_HDR_PROT_CIPHER_CHACHA,
/* Do not use UINT64_MAX here as this represents an invalid value */
UINT64_MAX - 1, /* No applicable limit for this suite (RFC 9001) */
((uint64_t)1) << 36, /* Limit as prescribed by RFC 9001 */
};
static const struct suite_info *get_suite(uint32_t suite_id)
{
switch (suite_id) {
case QRL_SUITE_AES128GCM:
return &suite_aes128gcm;
case QRL_SUITE_AES256GCM:
return &suite_aes256gcm;
case QRL_SUITE_CHACHA20POLY1305:
return &suite_chacha20poly1305;
default:
return NULL;
}
}
const char *ossl_qrl_get_suite_cipher_name(uint32_t suite_id)
{
const struct suite_info *c = get_suite(suite_id);
return c != NULL ? c->cipher_name : NULL;
}
const char *ossl_qrl_get_suite_md_name(uint32_t suite_id)
{
const struct suite_info *c = get_suite(suite_id);
return c != NULL ? c->md_name : NULL;
}
uint32_t ossl_qrl_get_suite_secret_len(uint32_t suite_id)
{
const struct suite_info *c = get_suite(suite_id);
return c != NULL ? c->secret_len : 0;
}
uint32_t ossl_qrl_get_suite_cipher_key_len(uint32_t suite_id)
{
const struct suite_info *c = get_suite(suite_id);
return c != NULL ? c->cipher_key_len : 0;
}
uint32_t ossl_qrl_get_suite_cipher_iv_len(uint32_t suite_id)
{
const struct suite_info *c = get_suite(suite_id);
return c != NULL ? c->cipher_iv_len : 0;
}
uint32_t ossl_qrl_get_suite_cipher_tag_len(uint32_t suite_id)
{
const struct suite_info *c = get_suite(suite_id);
return c != NULL ? c->cipher_tag_len : 0;
}
uint32_t ossl_qrl_get_suite_hdr_prot_cipher_id(uint32_t suite_id)
{
const struct suite_info *c = get_suite(suite_id);
return c != NULL ? c->hdr_prot_cipher_id : 0;
}
uint32_t ossl_qrl_get_suite_hdr_prot_key_len(uint32_t suite_id)
{
const struct suite_info *c = get_suite(suite_id);
return c != NULL ? c->hdr_prot_key_len : 0;
}
uint64_t ossl_qrl_get_suite_max_pkt(uint32_t suite_id)
{
const struct suite_info *c = get_suite(suite_id);
return c != NULL ? c->max_pkt : UINT64_MAX;
}
uint64_t ossl_qrl_get_suite_max_forged_pkt(uint32_t suite_id)
{
const struct suite_info *c = get_suite(suite_id);
return c != NULL ? c->max_forged_pkt : UINT64_MAX;
}
| 9,501 | 33.179856 | 80 | c |
openssl | openssl-master/ssl/quic/quic_rstream.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/err.h>
#include "internal/common.h"
#include "internal/time.h"
#include "internal/quic_stream.h"
#include "internal/quic_sf_list.h"
#include "internal/ring_buf.h"
struct quic_rstream_st {
SFRAME_LIST fl;
QUIC_RXFC *rxfc;
OSSL_STATM *statm;
UINT_RANGE head_range;
struct ring_buf rbuf;
};
QUIC_RSTREAM *ossl_quic_rstream_new(QUIC_RXFC *rxfc,
OSSL_STATM *statm, size_t rbuf_size)
{
QUIC_RSTREAM *ret = OPENSSL_zalloc(sizeof(*ret));
if (ret == NULL)
return NULL;
ring_buf_init(&ret->rbuf);
if (!ring_buf_resize(&ret->rbuf, rbuf_size, 0)) {
OPENSSL_free(ret);
return NULL;
}
ossl_sframe_list_init(&ret->fl);
ret->rxfc = rxfc;
ret->statm = statm;
return ret;
}
void ossl_quic_rstream_free(QUIC_RSTREAM *qrs)
{
int cleanse;
if (qrs == NULL)
return;
cleanse = qrs->fl.cleanse;
ossl_sframe_list_destroy(&qrs->fl);
ring_buf_destroy(&qrs->rbuf, cleanse);
OPENSSL_free(qrs);
}
int ossl_quic_rstream_queue_data(QUIC_RSTREAM *qrs, OSSL_QRX_PKT *pkt,
uint64_t offset,
const unsigned char *data, uint64_t data_len,
int fin)
{
UINT_RANGE range;
if ((data == NULL && data_len != 0) || (data_len == 0 && fin == 0)) {
/* empty frame allowed only at the end of the stream */
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return 0;
}
range.start = offset;
range.end = offset + data_len;
return ossl_sframe_list_insert(&qrs->fl, &range, pkt, data, fin);
}
static int read_internal(QUIC_RSTREAM *qrs, unsigned char *buf, size_t size,
size_t *readbytes, int *fin, int drop)
{
void *iter = NULL;
UINT_RANGE range;
const unsigned char *data;
uint64_t offset = 0;
size_t readbytes_ = 0;
int fin_ = 0, ret = 1;
while (ossl_sframe_list_peek(&qrs->fl, &iter, &range, &data, &fin_)) {
size_t l = (size_t)(range.end - range.start);
if (l > size) {
l = size;
fin_ = 0;
}
offset = range.start + l;
if (l == 0)
break;
if (data == NULL) {
size_t max_len;
data = ring_buf_get_ptr(&qrs->rbuf, range.start, &max_len);
if (!ossl_assert(data != NULL))
return 0;
if (max_len < l) {
memcpy(buf, data, max_len);
size -= max_len;
buf += max_len;
readbytes_ += max_len;
l -= max_len;
data = ring_buf_get_ptr(&qrs->rbuf, range.start + max_len,
&max_len);
if (!ossl_assert(data != NULL) || !ossl_assert(max_len > l))
return 0;
}
}
memcpy(buf, data, l);
size -= l;
buf += l;
readbytes_ += l;
if (size == 0)
break;
}
if (drop && offset != 0) {
ret = ossl_sframe_list_drop_frames(&qrs->fl, offset);
ring_buf_cpop_range(&qrs->rbuf, 0, offset - 1, qrs->fl.cleanse);
}
if (ret) {
*readbytes = readbytes_;
*fin = fin_;
}
return ret;
}
static OSSL_TIME get_rtt(QUIC_RSTREAM *qrs)
{
OSSL_TIME rtt;
if (qrs->statm != NULL) {
OSSL_RTT_INFO rtt_info;
ossl_statm_get_rtt_info(qrs->statm, &rtt_info);
rtt = rtt_info.smoothed_rtt;
} else {
rtt = ossl_time_zero();
}
return rtt;
}
int ossl_quic_rstream_read(QUIC_RSTREAM *qrs, unsigned char *buf, size_t size,
size_t *readbytes, int *fin)
{
OSSL_TIME rtt = get_rtt(qrs);
if (!read_internal(qrs, buf, size, readbytes, fin, 1))
return 0;
if (qrs->rxfc != NULL
&& !ossl_quic_rxfc_on_retire(qrs->rxfc, *readbytes, rtt))
return 0;
return 1;
}
int ossl_quic_rstream_peek(QUIC_RSTREAM *qrs, unsigned char *buf, size_t size,
size_t *readbytes, int *fin)
{
return read_internal(qrs, buf, size, readbytes, fin, 0);
}
int ossl_quic_rstream_available(QUIC_RSTREAM *qrs, size_t *avail, int *fin)
{
void *iter = NULL;
UINT_RANGE range;
const unsigned char *data;
uint64_t avail_ = 0;
while (ossl_sframe_list_peek(&qrs->fl, &iter, &range, &data, fin))
avail_ += range.end - range.start;
#if SIZE_MAX < UINT64_MAX
*avail = avail_ > SIZE_MAX ? SIZE_MAX : (size_t)avail_;
#else
*avail = (size_t)avail_;
#endif
return 1;
}
int ossl_quic_rstream_get_record(QUIC_RSTREAM *qrs,
const unsigned char **record, size_t *rec_len,
int *fin)
{
const unsigned char *record_ = NULL;
size_t rec_len_, max_len;
if (!ossl_sframe_list_lock_head(&qrs->fl, &qrs->head_range, &record_, fin)) {
/* No head frame to lock and return */
*record = NULL;
*rec_len = 0;
return 1;
}
/* if final empty frame, we drop it immediately */
if (qrs->head_range.end == qrs->head_range.start) {
if (!ossl_assert(*fin))
return 0;
if (!ossl_sframe_list_drop_frames(&qrs->fl, qrs->head_range.end))
return 0;
}
rec_len_ = (size_t)(qrs->head_range.end - qrs->head_range.start);
if (record_ == NULL && rec_len_ != 0) {
record_ = ring_buf_get_ptr(&qrs->rbuf, qrs->head_range.start,
&max_len);
if (!ossl_assert(record_ != NULL))
return 0;
if (max_len < rec_len_) {
rec_len_ = max_len;
qrs->head_range.end = qrs->head_range.start + max_len;
}
}
*rec_len = rec_len_;
*record = record_;
return 1;
}
int ossl_quic_rstream_release_record(QUIC_RSTREAM *qrs, size_t read_len)
{
uint64_t offset;
if (!ossl_sframe_list_is_head_locked(&qrs->fl))
return 0;
if (read_len > qrs->head_range.end - qrs->head_range.start) {
if (read_len != SIZE_MAX)
return 0;
offset = qrs->head_range.end;
} else {
offset = qrs->head_range.start + read_len;
}
if (!ossl_sframe_list_drop_frames(&qrs->fl, offset))
return 0;
if (offset > 0)
ring_buf_cpop_range(&qrs->rbuf, 0, offset - 1, qrs->fl.cleanse);
if (qrs->rxfc != NULL) {
OSSL_TIME rtt = get_rtt(qrs);
if (!ossl_quic_rxfc_on_retire(qrs->rxfc, offset, rtt))
return 0;
}
return 1;
}
static int write_at_ring_buf_cb(uint64_t logical_offset,
const unsigned char *buf,
size_t buf_len,
void *cb_arg)
{
struct ring_buf *rbuf = cb_arg;
return ring_buf_write_at(rbuf, logical_offset, buf, buf_len);
}
int ossl_quic_rstream_move_to_rbuf(QUIC_RSTREAM *qrs)
{
if (ring_buf_avail(&qrs->rbuf) == 0)
return 0;
return ossl_sframe_list_move_data(&qrs->fl,
write_at_ring_buf_cb, &qrs->rbuf);
}
int ossl_quic_rstream_resize_rbuf(QUIC_RSTREAM *qrs, size_t rbuf_size)
{
/* TODO(QUIC): Do we need to distinguish different error conditions ? */
if (ossl_sframe_list_is_head_locked(&qrs->fl))
return 0;
if (!ring_buf_resize(&qrs->rbuf, rbuf_size, qrs->fl.cleanse))
return 0;
return 1;
}
void ossl_quic_rstream_set_cleanse(QUIC_RSTREAM *qrs, int cleanse)
{
qrs->fl.cleanse = cleanse;
}
| 7,906 | 25.622896 | 81 | c |
openssl | openssl-master/ssl/quic/quic_sf_list.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/uint_set.h"
#include "internal/common.h"
#include "internal/quic_sf_list.h"
struct stream_frame_st {
struct stream_frame_st *prev, *next;
UINT_RANGE range;
OSSL_QRX_PKT *pkt;
const unsigned char *data;
};
static void stream_frame_free(SFRAME_LIST *fl, STREAM_FRAME *sf)
{
if (fl->cleanse && sf->data != NULL)
OPENSSL_cleanse((unsigned char *)sf->data,
(size_t)(sf->range.end - sf->range.start));
ossl_qrx_pkt_release(sf->pkt);
OPENSSL_free(sf);
}
static STREAM_FRAME *stream_frame_new(UINT_RANGE *range, OSSL_QRX_PKT *pkt,
const unsigned char *data)
{
STREAM_FRAME *sf = OPENSSL_zalloc(sizeof(*sf));
if (sf == NULL)
return NULL;
if (pkt != NULL)
ossl_qrx_pkt_up_ref(pkt);
sf->range = *range;
sf->pkt = pkt;
sf->data = data;
return sf;
}
void ossl_sframe_list_init(SFRAME_LIST *fl)
{
memset(fl, 0, sizeof(*fl));
}
void ossl_sframe_list_destroy(SFRAME_LIST *fl)
{
STREAM_FRAME *sf, *next_frame;
for (sf = fl->head; sf != NULL; sf = next_frame) {
next_frame = sf->next;
stream_frame_free(fl, sf);
}
}
static int append_frame(SFRAME_LIST *fl, UINT_RANGE *range,
OSSL_QRX_PKT *pkt,
const unsigned char *data)
{
STREAM_FRAME *new_frame;
if ((new_frame = stream_frame_new(range, pkt, data)) == NULL)
return 0;
new_frame->prev = fl->tail;
if (fl->tail != NULL)
fl->tail->next = new_frame;
fl->tail = new_frame;
++fl->num_frames;
return 1;
}
int ossl_sframe_list_insert(SFRAME_LIST *fl, UINT_RANGE *range,
OSSL_QRX_PKT *pkt,
const unsigned char *data, int fin)
{
STREAM_FRAME *sf, *new_frame, *prev_frame, *next_frame;
#ifndef NDEBUG
uint64_t curr_end = fl->tail != NULL ? fl->tail->range.end
: fl->offset;
/* This check for FINAL_SIZE_ERROR is handled by QUIC FC already */
assert((!fin || curr_end <= range->end)
&& (!fl->fin || curr_end >= range->end));
#endif
if (fl->offset >= range->end)
goto end;
/* nothing there yet */
if (fl->tail == NULL) {
fl->tail = fl->head = stream_frame_new(range, pkt, data);
if (fl->tail == NULL)
return 0;
++fl->num_frames;
goto end;
}
/* optimize insertion at the end */
if (fl->tail->range.start < range->start) {
if (fl->tail->range.end >= range->end)
goto end;
if (!append_frame(fl, range, pkt, data))
return 0;
goto end;
}
prev_frame = NULL;
for (sf = fl->head; sf != NULL && sf->range.start < range->start;
sf = sf->next)
prev_frame = sf;
if (!ossl_assert(sf != NULL))
/* frame list invariant broken */
return 0;
if (prev_frame != NULL && prev_frame->range.end >= range->end)
goto end;
/*
* Now we must create a new frame although in the end we might drop it,
* because we will be potentially dropping existing overlapping frames.
*/
new_frame = stream_frame_new(range, pkt, data);
if (new_frame == NULL)
return 0;
for (next_frame = sf;
next_frame != NULL && next_frame->range.end <= range->end;) {
STREAM_FRAME *drop_frame = next_frame;
next_frame = next_frame->next;
if (next_frame != NULL)
next_frame->prev = drop_frame->prev;
if (prev_frame != NULL)
prev_frame->next = drop_frame->next;
if (fl->head == drop_frame)
fl->head = next_frame;
if (fl->tail == drop_frame)
fl->tail = prev_frame;
--fl->num_frames;
stream_frame_free(fl, drop_frame);
}
if (next_frame != NULL) {
/* check whether the new_frame is redundant because there is no gap */
if (prev_frame != NULL
&& next_frame->range.start <= prev_frame->range.end) {
stream_frame_free(fl, new_frame);
goto end;
}
next_frame->prev = new_frame;
} else {
fl->tail = new_frame;
}
new_frame->next = next_frame;
new_frame->prev = prev_frame;
if (prev_frame != NULL)
prev_frame->next = new_frame;
else
fl->head = new_frame;
++fl->num_frames;
end:
fl->fin = fin || fl->fin;
return 1;
}
int ossl_sframe_list_peek(const SFRAME_LIST *fl, void **iter,
UINT_RANGE *range, const unsigned char **data,
int *fin)
{
STREAM_FRAME *sf = *iter;
uint64_t start;
if (sf == NULL) {
start = fl->offset;
sf = fl->head;
} else {
start = sf->range.end;
sf = sf->next;
}
range->start = start;
if (sf == NULL || sf->range.start > start
|| !ossl_assert(start < sf->range.end)) {
range->end = start;
*data = NULL;
*iter = NULL;
/* set fin only if we are at the end */
*fin = sf == NULL ? fl->fin : 0;
return 0;
}
range->end = sf->range.end;
if (sf->data != NULL)
*data = sf->data + (start - sf->range.start);
else
*data = NULL;
*fin = sf->next == NULL ? fl->fin : 0;
*iter = sf;
return 1;
}
int ossl_sframe_list_drop_frames(SFRAME_LIST *fl, uint64_t limit)
{
STREAM_FRAME *sf;
/* offset cannot move back or past the data received */
if (!ossl_assert(limit >= fl->offset)
|| !ossl_assert(fl->tail == NULL
|| limit <= fl->tail->range.end)
|| !ossl_assert(fl->tail != NULL
|| limit == fl->offset))
return 0;
fl->offset = limit;
for (sf = fl->head; sf != NULL && sf->range.end <= limit;) {
STREAM_FRAME *drop_frame = sf;
sf = sf->next;
--fl->num_frames;
stream_frame_free(fl, drop_frame);
}
fl->head = sf;
if (sf != NULL)
sf->prev = NULL;
else
fl->tail = NULL;
fl->head_locked = 0;
return 1;
}
int ossl_sframe_list_lock_head(SFRAME_LIST *fl, UINT_RANGE *range,
const unsigned char **data,
int *fin)
{
int ret;
void *iter = NULL;
if (fl->head_locked)
return 0;
ret = ossl_sframe_list_peek(fl, &iter, range, data, fin);
if (ret)
fl->head_locked = 1;
return ret;
}
int ossl_sframe_list_is_head_locked(SFRAME_LIST *fl)
{
return fl->head_locked;
}
int ossl_sframe_list_move_data(SFRAME_LIST *fl,
sframe_list_write_at_cb *write_at_cb,
void *cb_arg)
{
STREAM_FRAME *sf = fl->head, *prev_frame = NULL;
uint64_t limit = fl->offset;
if (sf == NULL)
return 1;
if (fl->head_locked)
sf = sf->next;
for (; sf != NULL; sf = sf->next) {
size_t len;
const unsigned char *data = sf->data;
if (limit < sf->range.start)
limit = sf->range.start;
if (data != NULL) {
if (limit > sf->range.start)
data += (size_t)(limit - sf->range.start);
len = (size_t)(sf->range.end - limit);
if (!write_at_cb(limit, data, len, cb_arg))
/* data did not fit */
return 0;
if (fl->cleanse)
OPENSSL_cleanse((unsigned char *)sf->data,
(size_t)(sf->range.end - sf->range.start));
/* release the packet */
sf->data = NULL;
ossl_qrx_pkt_release(sf->pkt);
sf->pkt = NULL;
}
limit = sf->range.end;
/* merge contiguous frames */
if (prev_frame != NULL
&& prev_frame->range.end >= sf->range.start) {
prev_frame->range.end = sf->range.end;
prev_frame->next = sf->next;
if (sf->next != NULL)
sf->next->prev = prev_frame;
else
fl->tail = prev_frame;
--fl->num_frames;
stream_frame_free(fl, sf);
sf = prev_frame;
continue;
}
prev_frame = sf;
}
return 1;
}
| 8,655 | 24.838806 | 78 | c |
openssl | openssl-master/ssl/quic/quic_sstream.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/quic_stream.h"
#include "internal/uint_set.h"
#include "internal/common.h"
#include "internal/ring_buf.h"
/*
* ==================================================================
* QUIC Send Stream
*/
struct quic_sstream_st {
struct ring_buf ring_buf;
/*
* Any logical byte in the stream is in one of these states:
*
* - NEW: The byte has not yet been transmitted, or has been lost and is
* in need of retransmission.
*
* - IN_FLIGHT: The byte has been transmitted but is awaiting
* acknowledgement. We continue to store the data in case we return
* to the NEW state.
*
* - ACKED: The byte has been acknowledged and we can cease storing it.
* We do not necessarily cull it immediately, so there may be a delay
* between reaching the ACKED state and the buffer space actually being
* recycled.
*
* A logical byte in the stream is
*
* - in the NEW state if it is in new_set;
* - is in the ACKED state if it is in acked_set
* (and may or may not have been culled);
* - is in the IN_FLIGHT state otherwise.
*
* Invariant: No logical byte is ever in both new_set and acked_set.
*/
UINT_SET new_set, acked_set;
/*
* The current size of the stream is ring_buf.head_offset. If
* have_final_size is true, this is also the final size of the stream.
*/
unsigned int have_final_size : 1;
unsigned int sent_final_size : 1;
unsigned int acked_final_size : 1;
unsigned int cleanse : 1;
};
static void qss_cull(QUIC_SSTREAM *qss);
QUIC_SSTREAM *ossl_quic_sstream_new(size_t init_buf_size)
{
QUIC_SSTREAM *qss;
qss = OPENSSL_zalloc(sizeof(QUIC_SSTREAM));
if (qss == NULL)
return NULL;
ring_buf_init(&qss->ring_buf);
if (!ring_buf_resize(&qss->ring_buf, init_buf_size, 0)) {
ring_buf_destroy(&qss->ring_buf, 0);
OPENSSL_free(qss);
return NULL;
}
ossl_uint_set_init(&qss->new_set);
ossl_uint_set_init(&qss->acked_set);
return qss;
}
void ossl_quic_sstream_free(QUIC_SSTREAM *qss)
{
if (qss == NULL)
return;
ossl_uint_set_destroy(&qss->new_set);
ossl_uint_set_destroy(&qss->acked_set);
ring_buf_destroy(&qss->ring_buf, qss->cleanse);
OPENSSL_free(qss);
}
int ossl_quic_sstream_get_stream_frame(QUIC_SSTREAM *qss,
size_t skip,
OSSL_QUIC_FRAME_STREAM *hdr,
OSSL_QTX_IOVEC *iov,
size_t *num_iov)
{
size_t num_iov_ = 0, src_len = 0, total_len = 0, i;
uint64_t max_len;
const unsigned char *src = NULL;
UINT_SET_ITEM *range = ossl_list_uint_set_head(&qss->new_set);
if (*num_iov < 2)
return 0;
for (i = 0; i < skip && range != NULL; ++i)
range = ossl_list_uint_set_next(range);
if (range == NULL) {
if (i < skip)
/* Don't return FIN for infinitely increasing skip */
return 0;
/* No new bytes to send, but we might have a FIN */
if (!qss->have_final_size || qss->sent_final_size)
return 0;
hdr->offset = qss->ring_buf.head_offset;
hdr->len = 0;
hdr->is_fin = 1;
*num_iov = 0;
return 1;
}
/*
* We can only send a contiguous range of logical bytes in a single
* stream frame, so limit ourselves to the range of the first set entry.
*
* Set entries never have 'adjacent' entries so we don't have to worry
* about them here.
*/
max_len = range->range.end - range->range.start + 1;
for (i = 0;; ++i) {
if (total_len >= max_len)
break;
if (!ring_buf_get_buf_at(&qss->ring_buf,
range->range.start + total_len,
&src, &src_len))
return 0;
if (src_len == 0)
break;
assert(i < 2);
if (total_len + src_len > max_len)
src_len = (size_t)(max_len - total_len);
iov[num_iov_].buf = src;
iov[num_iov_].buf_len = src_len;
total_len += src_len;
++num_iov_;
}
hdr->offset = range->range.start;
hdr->len = total_len;
hdr->is_fin = qss->have_final_size
&& hdr->offset + hdr->len == qss->ring_buf.head_offset;
*num_iov = num_iov_;
return 1;
}
int ossl_quic_sstream_has_pending(QUIC_SSTREAM *qss)
{
OSSL_QUIC_FRAME_STREAM shdr;
OSSL_QTX_IOVEC iov[2];
size_t num_iov = OSSL_NELEM(iov);
return ossl_quic_sstream_get_stream_frame(qss, 0, &shdr, iov, &num_iov);
}
uint64_t ossl_quic_sstream_get_cur_size(QUIC_SSTREAM *qss)
{
return qss->ring_buf.head_offset;
}
int ossl_quic_sstream_mark_transmitted(QUIC_SSTREAM *qss,
uint64_t start,
uint64_t end)
{
UINT_RANGE r;
r.start = start;
r.end = end;
if (!ossl_uint_set_remove(&qss->new_set, &r))
return 0;
return 1;
}
int ossl_quic_sstream_mark_transmitted_fin(QUIC_SSTREAM *qss,
uint64_t final_size)
{
/*
* We do not really need final_size since we already know the size of the
* stream, but this serves as a sanity check.
*/
if (!qss->have_final_size || final_size != qss->ring_buf.head_offset)
return 0;
qss->sent_final_size = 1;
return 1;
}
int ossl_quic_sstream_mark_lost(QUIC_SSTREAM *qss,
uint64_t start,
uint64_t end)
{
UINT_RANGE r;
r.start = start;
r.end = end;
/*
* We lost a range of stream data bytes, so reinsert them into the new set,
* so that they are returned once more by ossl_quic_sstream_get_stream_frame.
*/
if (!ossl_uint_set_insert(&qss->new_set, &r))
return 0;
return 1;
}
int ossl_quic_sstream_mark_lost_fin(QUIC_SSTREAM *qss)
{
if (qss->acked_final_size)
/* Does not make sense to lose a FIN after it has been ACKed */
return 0;
/* FIN was lost, so we need to transmit it again. */
qss->sent_final_size = 0;
return 1;
}
int ossl_quic_sstream_mark_acked(QUIC_SSTREAM *qss,
uint64_t start,
uint64_t end)
{
UINT_RANGE r;
r.start = start;
r.end = end;
if (!ossl_uint_set_insert(&qss->acked_set, &r))
return 0;
qss_cull(qss);
return 1;
}
int ossl_quic_sstream_mark_acked_fin(QUIC_SSTREAM *qss)
{
if (!qss->have_final_size)
/* Cannot ack final size before we have a final size */
return 0;
qss->acked_final_size = 1;
return 1;
}
void ossl_quic_sstream_fin(QUIC_SSTREAM *qss)
{
if (qss->have_final_size)
return;
qss->have_final_size = 1;
}
int ossl_quic_sstream_get_final_size(QUIC_SSTREAM *qss, uint64_t *final_size)
{
if (!qss->have_final_size)
return 0;
if (final_size != NULL)
*final_size = qss->ring_buf.head_offset;
return 1;
}
int ossl_quic_sstream_append(QUIC_SSTREAM *qss,
const unsigned char *buf,
size_t buf_len,
size_t *consumed)
{
size_t l, consumed_ = 0;
UINT_RANGE r;
struct ring_buf old_ring_buf = qss->ring_buf;
if (qss->have_final_size) {
*consumed = 0;
return 0;
}
/*
* Note: It is assumed that ossl_quic_sstream_append will be called during a
* call to e.g. SSL_write and this function is therefore designed to support
* such semantics. In particular, the buffer pointed to by buf is only
* assumed to be valid for the duration of this call, therefore we must copy
* the data here. We will later copy-and-encrypt the data during packet
* encryption, so this is a two-copy design. Supporting a one-copy design in
* the future will require applications to use a different kind of API.
* Supporting such changes in future will require corresponding enhancements
* to this code.
*/
while (buf_len > 0) {
l = ring_buf_push(&qss->ring_buf, buf, buf_len);
if (l == 0)
break;
buf += l;
buf_len -= l;
consumed_ += l;
}
if (consumed_ > 0) {
r.start = old_ring_buf.head_offset;
r.end = r.start + consumed_ - 1;
assert(r.end + 1 == qss->ring_buf.head_offset);
if (!ossl_uint_set_insert(&qss->new_set, &r)) {
qss->ring_buf = old_ring_buf;
*consumed = 0;
return 0;
}
}
*consumed = consumed_;
return 1;
}
static void qss_cull(QUIC_SSTREAM *qss)
{
UINT_SET_ITEM *h = ossl_list_uint_set_head(&qss->acked_set);
/*
* Potentially cull data from our ring buffer. This can happen once data has
* been ACKed and we know we are never going to have to transmit it again.
*
* Since we use a ring buffer design for simplicity, we cannot cull byte n +
* k (for k > 0) from the ring buffer until byte n has also been culled.
* This means if parts of the stream get acknowledged out of order we might
* keep around some data we technically don't need to for a while. The
* impact of this is likely to be small and limited to quite a short
* duration, and doesn't justify the use of a more complex design.
*/
/*
* We only need to check the first range entry in the integer set because we
* can only cull contiguous areas at the start of the ring buffer anyway.
*/
if (h != NULL)
ring_buf_cpop_range(&qss->ring_buf, h->range.start, h->range.end,
qss->cleanse);
}
int ossl_quic_sstream_set_buffer_size(QUIC_SSTREAM *qss, size_t num_bytes)
{
return ring_buf_resize(&qss->ring_buf, num_bytes, qss->cleanse);
}
size_t ossl_quic_sstream_get_buffer_size(QUIC_SSTREAM *qss)
{
return qss->ring_buf.alloc;
}
size_t ossl_quic_sstream_get_buffer_used(QUIC_SSTREAM *qss)
{
return ring_buf_used(&qss->ring_buf);
}
size_t ossl_quic_sstream_get_buffer_avail(QUIC_SSTREAM *qss)
{
return ring_buf_avail(&qss->ring_buf);
}
int ossl_quic_sstream_is_totally_acked(QUIC_SSTREAM *qss)
{
UINT_RANGE r;
uint64_t cur_size;
if ((qss->have_final_size && !qss->acked_final_size)
|| ossl_list_uint_set_num(&qss->acked_set) != 1)
return 0;
r = ossl_list_uint_set_head(&qss->acked_set)->range;
cur_size = qss->ring_buf.head_offset;
/*
* The invariants of UINT_SET guarantee a single list element if we have a
* single contiguous range, which is what we should have if everything has
* been acked.
*/
assert(r.end + 1 <= cur_size);
return r.start == 0 && r.end + 1 == cur_size;
}
void ossl_quic_sstream_adjust_iov(size_t len,
OSSL_QTX_IOVEC *iov,
size_t num_iov)
{
size_t running = 0, i, iovlen;
for (i = 0, running = 0; i < num_iov; ++i) {
iovlen = iov[i].buf_len;
if (running >= len)
iov[i].buf_len = 0;
else if (running + iovlen > len)
iov[i].buf_len = len - running;
running += iovlen;
}
}
void ossl_quic_sstream_set_cleanse(QUIC_SSTREAM *qss, int cleanse)
{
qss->cleanse = cleanse;
}
| 11,921 | 27.385714 | 81 | c |
openssl | openssl-master/ssl/quic/quic_statm.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/quic_statm.h"
void ossl_statm_update_rtt(OSSL_STATM *statm,
OSSL_TIME ack_delay,
OSSL_TIME override_latest_rtt)
{
OSSL_TIME adjusted_rtt, latest_rtt = override_latest_rtt;
/* Use provided RTT value, or else last RTT value. */
if (ossl_time_is_zero(latest_rtt))
latest_rtt = statm->latest_rtt;
else
statm->latest_rtt = latest_rtt;
if (!statm->have_first_sample) {
statm->min_rtt = latest_rtt;
statm->smoothed_rtt = latest_rtt;
statm->rtt_variance = ossl_time_divide(latest_rtt, 2);
statm->have_first_sample = 1;
return;
}
/* Update minimum RTT. */
if (ossl_time_compare(latest_rtt, statm->min_rtt) < 0)
statm->min_rtt = latest_rtt;
/*
* Enforcement of max_ack_delay is the responsibility of
* the caller as it is context-dependent.
*/
adjusted_rtt = latest_rtt;
if (ossl_time_compare(latest_rtt, ossl_time_add(statm->min_rtt, ack_delay)) >= 0)
adjusted_rtt = ossl_time_subtract(latest_rtt, ack_delay);
statm->rtt_variance = ossl_time_divide(ossl_time_add(ossl_time_multiply(statm->rtt_variance, 3),
ossl_time_abs_difference(statm->smoothed_rtt,
adjusted_rtt)), 4);
statm->smoothed_rtt = ossl_time_divide(ossl_time_add(ossl_time_multiply(statm->smoothed_rtt, 7),
adjusted_rtt), 8);
}
/* RFC 9002 kInitialRtt value. RFC recommended value. */
#define K_INITIAL_RTT ossl_ms2time(333)
int ossl_statm_init(OSSL_STATM *statm)
{
statm->smoothed_rtt = K_INITIAL_RTT;
statm->latest_rtt = ossl_time_zero();
statm->min_rtt = ossl_time_infinite();
statm->rtt_variance = ossl_time_divide(K_INITIAL_RTT, 2);
statm->have_first_sample = 0;
statm->max_ack_delay = ossl_time_infinite();
return 1;
}
void ossl_statm_destroy(OSSL_STATM *statm)
{
/* No-op. */
}
void ossl_statm_set_max_ack_delay(OSSL_STATM *statm, OSSL_TIME max_ack_delay)
{
statm->max_ack_delay = max_ack_delay;
}
void ossl_statm_get_rtt_info(OSSL_STATM *statm, OSSL_RTT_INFO *rtt_info)
{
rtt_info->min_rtt = statm->min_rtt;
rtt_info->latest_rtt = statm->latest_rtt;
rtt_info->smoothed_rtt = statm->smoothed_rtt;
rtt_info->rtt_variance = statm->rtt_variance;
rtt_info->max_ack_delay = statm->max_ack_delay;
}
| 3,008 | 34.821429 | 102 | c |
openssl | openssl-master/ssl/quic/quic_stream_map.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/quic_stream_map.h"
#include "internal/nelem.h"
/*
* QUIC Stream Map
* ===============
*/
DEFINE_LHASH_OF_EX(QUIC_STREAM);
/* Circular list management. */
static void list_insert_tail(QUIC_STREAM_LIST_NODE *l,
QUIC_STREAM_LIST_NODE *n)
{
/* Must not be in list. */
assert(n->prev == NULL && n->next == NULL
&& l->prev != NULL && l->next != NULL);
n->prev = l->prev;
n->prev->next = n;
l->prev = n;
n->next = l;
}
static void list_remove(QUIC_STREAM_LIST_NODE *l,
QUIC_STREAM_LIST_NODE *n)
{
assert(n->prev != NULL && n->next != NULL
&& n->prev != n && n->next != n);
n->prev->next = n->next;
n->next->prev = n->prev;
n->next = n->prev = NULL;
}
static QUIC_STREAM *list_next(QUIC_STREAM_LIST_NODE *l, QUIC_STREAM_LIST_NODE *n,
size_t off)
{
assert(n->prev != NULL && n->next != NULL
&& (n == l || (n->prev != n && n->next != n))
&& l->prev != NULL && l->next != NULL);
n = n->next;
if (n == l)
n = n->next;
if (n == l)
return NULL;
assert(n != NULL);
return (QUIC_STREAM *)(((char *)n) - off);
}
#define active_next(l, s) list_next((l), &(s)->active_node, \
offsetof(QUIC_STREAM, active_node))
#define accept_next(l, s) list_next((l), &(s)->accept_node, \
offsetof(QUIC_STREAM, accept_node))
#define ready_for_gc_next(l, s) list_next((l), &(s)->ready_for_gc_node, \
offsetof(QUIC_STREAM, ready_for_gc_node))
#define accept_head(l) list_next((l), (l), \
offsetof(QUIC_STREAM, accept_node))
#define ready_for_gc_head(l) list_next((l), (l), \
offsetof(QUIC_STREAM, ready_for_gc_node))
static unsigned long hash_stream(const QUIC_STREAM *s)
{
return (unsigned long)s->id;
}
static int cmp_stream(const QUIC_STREAM *a, const QUIC_STREAM *b)
{
if (a->id < b->id)
return -1;
if (a->id > b->id)
return 1;
return 0;
}
int ossl_quic_stream_map_init(QUIC_STREAM_MAP *qsm,
uint64_t (*get_stream_limit_cb)(int uni, void *arg),
void *get_stream_limit_cb_arg,
QUIC_RXFC *max_streams_bidi_rxfc,
QUIC_RXFC *max_streams_uni_rxfc,
int is_server)
{
qsm->map = lh_QUIC_STREAM_new(hash_stream, cmp_stream);
qsm->active_list.prev = qsm->active_list.next = &qsm->active_list;
qsm->accept_list.prev = qsm->accept_list.next = &qsm->accept_list;
qsm->ready_for_gc_list.prev = qsm->ready_for_gc_list.next
= &qsm->ready_for_gc_list;
qsm->rr_stepping = 1;
qsm->rr_counter = 0;
qsm->rr_cur = NULL;
qsm->num_accept = 0;
qsm->get_stream_limit_cb = get_stream_limit_cb;
qsm->get_stream_limit_cb_arg = get_stream_limit_cb_arg;
qsm->max_streams_bidi_rxfc = max_streams_bidi_rxfc;
qsm->max_streams_uni_rxfc = max_streams_uni_rxfc;
qsm->is_server = is_server;
return 1;
}
static void release_each(QUIC_STREAM *stream, void *arg)
{
QUIC_STREAM_MAP *qsm = arg;
ossl_quic_stream_map_release(qsm, stream);
}
void ossl_quic_stream_map_cleanup(QUIC_STREAM_MAP *qsm)
{
ossl_quic_stream_map_visit(qsm, release_each, qsm);
lh_QUIC_STREAM_free(qsm->map);
qsm->map = NULL;
}
void ossl_quic_stream_map_visit(QUIC_STREAM_MAP *qsm,
void (*visit_cb)(QUIC_STREAM *stream, void *arg),
void *visit_cb_arg)
{
lh_QUIC_STREAM_doall_arg(qsm->map, visit_cb, visit_cb_arg);
}
QUIC_STREAM *ossl_quic_stream_map_alloc(QUIC_STREAM_MAP *qsm,
uint64_t stream_id,
int type)
{
QUIC_STREAM *s;
QUIC_STREAM key;
key.id = stream_id;
s = lh_QUIC_STREAM_retrieve(qsm->map, &key);
if (s != NULL)
return NULL;
s = OPENSSL_zalloc(sizeof(*s));
if (s == NULL)
return NULL;
s->id = stream_id;
s->type = type;
s->as_server = qsm->is_server;
s->send_state = (ossl_quic_stream_is_local_init(s)
|| ossl_quic_stream_is_bidi(s))
? QUIC_SSTREAM_STATE_READY
: QUIC_SSTREAM_STATE_NONE;
s->recv_state = (!ossl_quic_stream_is_local_init(s)
|| ossl_quic_stream_is_bidi(s))
? QUIC_RSTREAM_STATE_RECV
: QUIC_RSTREAM_STATE_NONE;
s->send_final_size = UINT64_MAX;
lh_QUIC_STREAM_insert(qsm->map, s);
return s;
}
void ossl_quic_stream_map_release(QUIC_STREAM_MAP *qsm, QUIC_STREAM *stream)
{
if (stream == NULL)
return;
if (stream->active_node.next != NULL)
list_remove(&qsm->active_list, &stream->active_node);
if (stream->accept_node.next != NULL)
list_remove(&qsm->accept_list, &stream->accept_node);
if (stream->ready_for_gc_node.next != NULL)
list_remove(&qsm->ready_for_gc_list, &stream->ready_for_gc_node);
ossl_quic_sstream_free(stream->sstream);
stream->sstream = NULL;
ossl_quic_rstream_free(stream->rstream);
stream->rstream = NULL;
lh_QUIC_STREAM_delete(qsm->map, stream);
OPENSSL_free(stream);
}
QUIC_STREAM *ossl_quic_stream_map_get_by_id(QUIC_STREAM_MAP *qsm,
uint64_t stream_id)
{
QUIC_STREAM key;
key.id = stream_id;
return lh_QUIC_STREAM_retrieve(qsm->map, &key);
}
static void stream_map_mark_active(QUIC_STREAM_MAP *qsm, QUIC_STREAM *s)
{
if (s->active)
return;
list_insert_tail(&qsm->active_list, &s->active_node);
if (qsm->rr_cur == NULL)
qsm->rr_cur = s;
s->active = 1;
}
static void stream_map_mark_inactive(QUIC_STREAM_MAP *qsm, QUIC_STREAM *s)
{
if (!s->active)
return;
if (qsm->rr_cur == s)
qsm->rr_cur = active_next(&qsm->active_list, s);
if (qsm->rr_cur == s)
qsm->rr_cur = NULL;
list_remove(&qsm->active_list, &s->active_node);
s->active = 0;
}
void ossl_quic_stream_map_set_rr_stepping(QUIC_STREAM_MAP *qsm, size_t stepping)
{
qsm->rr_stepping = stepping;
qsm->rr_counter = 0;
}
static int stream_has_data_to_send(QUIC_STREAM *s)
{
OSSL_QUIC_FRAME_STREAM shdr;
OSSL_QTX_IOVEC iov[2];
size_t num_iov;
uint64_t fc_credit, fc_swm, fc_limit;
switch (s->send_state) {
case QUIC_SSTREAM_STATE_READY:
case QUIC_SSTREAM_STATE_SEND:
case QUIC_SSTREAM_STATE_DATA_SENT:
/*
* We can still have data to send in DATA_SENT due to retransmissions,
* etc.
*/
break;
default:
return 0; /* Nothing to send. */
}
/*
* We cannot determine if we have data to send simply by checking if
* ossl_quic_txfc_get_credit() is zero, because we may also have older
* stream data we need to retransmit. The SSTREAM returns older data first,
* so we do a simple comparison of the next chunk the SSTREAM wants to send
* against the TXFC CWM.
*/
num_iov = OSSL_NELEM(iov);
if (!ossl_quic_sstream_get_stream_frame(s->sstream, 0, &shdr, iov,
&num_iov))
return 0;
fc_credit = ossl_quic_txfc_get_credit(&s->txfc);
fc_swm = ossl_quic_txfc_get_swm(&s->txfc);
fc_limit = fc_swm + fc_credit;
return (shdr.is_fin && shdr.len == 0) || shdr.offset < fc_limit;
}
static ossl_unused int qsm_send_part_permits_gc(const QUIC_STREAM *qs)
{
switch (qs->send_state) {
case QUIC_SSTREAM_STATE_NONE:
case QUIC_SSTREAM_STATE_DATA_RECVD:
case QUIC_SSTREAM_STATE_RESET_RECVD:
return 1;
default:
return 0;
}
}
static int qsm_ready_for_gc(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs)
{
int recv_stream_fully_drained = 0; /* TODO(QUIC): Optimisation */
/*
* If sstream has no FIN, we auto-reset it at marked-for-deletion time, so
* we don't need to worry about that here.
*/
assert(!qs->deleted
|| !ossl_quic_stream_has_send(qs)
|| ossl_quic_stream_send_is_reset(qs)
|| ossl_quic_stream_send_get_final_size(qs, NULL));
return
qs->deleted
&& (!ossl_quic_stream_has_recv(qs)
|| recv_stream_fully_drained
|| qs->acked_stop_sending)
&& (!ossl_quic_stream_has_send(qs)
|| qs->send_state == QUIC_SSTREAM_STATE_DATA_RECVD
|| qs->send_state == QUIC_SSTREAM_STATE_RESET_RECVD);
}
void ossl_quic_stream_map_update_state(QUIC_STREAM_MAP *qsm, QUIC_STREAM *s)
{
int should_be_active, allowed_by_stream_limit = 1;
if (qsm->get_stream_limit_cb != NULL
&& ossl_quic_stream_is_server_init(s) == qsm->is_server) {
int uni = !ossl_quic_stream_is_bidi(s);
uint64_t stream_limit, stream_ordinal = s->id >> 2;
stream_limit
= qsm->get_stream_limit_cb(uni, qsm->get_stream_limit_cb_arg);
allowed_by_stream_limit = (stream_ordinal < stream_limit);
}
if (s->send_state == QUIC_SSTREAM_STATE_DATA_SENT
&& ossl_quic_sstream_is_totally_acked(s->sstream))
ossl_quic_stream_map_notify_totally_acked(qsm, s);
if (!s->ready_for_gc) {
s->ready_for_gc = qsm_ready_for_gc(qsm, s);
if (s->ready_for_gc)
list_insert_tail(&qsm->ready_for_gc_list, &s->ready_for_gc_node);
}
should_be_active
= allowed_by_stream_limit
&& !s->ready_for_gc
&& ((ossl_quic_stream_has_recv(s)
&& !ossl_quic_stream_recv_is_reset(s)
&& (s->recv_state == QUIC_RSTREAM_STATE_RECV
&& (s->want_max_stream_data
|| ossl_quic_rxfc_has_cwm_changed(&s->rxfc, 0))))
|| s->want_stop_sending
|| s->want_reset_stream
|| (!s->peer_stop_sending && stream_has_data_to_send(s)));
if (should_be_active)
stream_map_mark_active(qsm, s);
else
stream_map_mark_inactive(qsm, s);
}
/*
* Stream Send Part State Management
* =================================
*/
int ossl_quic_stream_map_ensure_send_part_id(QUIC_STREAM_MAP *qsm,
QUIC_STREAM *qs)
{
switch (qs->send_state) {
case QUIC_SSTREAM_STATE_NONE:
/* Stream without send part - caller error. */
return 0;
case QUIC_SSTREAM_STATE_READY:
/*
* We always allocate a stream ID upfront, so we don't need to do it
* here.
*/
qs->send_state = QUIC_SSTREAM_STATE_SEND;
return 1;
default:
/* Nothing to do. */
return 1;
}
}
int ossl_quic_stream_map_notify_all_data_sent(QUIC_STREAM_MAP *qsm,
QUIC_STREAM *qs)
{
switch (qs->send_state) {
default:
/* Wrong state - caller error. */
case QUIC_SSTREAM_STATE_NONE:
/* Stream without send part - caller error. */
return 0;
case QUIC_SSTREAM_STATE_SEND:
if (!ossl_quic_sstream_get_final_size(qs->sstream, &qs->send_final_size))
return 0;
qs->send_state = QUIC_SSTREAM_STATE_DATA_SENT;
return 1;
}
}
int ossl_quic_stream_map_notify_totally_acked(QUIC_STREAM_MAP *qsm,
QUIC_STREAM *qs)
{
switch (qs->send_state) {
default:
/* Wrong state - caller error. */
case QUIC_SSTREAM_STATE_NONE:
/* Stream without send part - caller error. */
return 0;
case QUIC_SSTREAM_STATE_DATA_SENT:
qs->send_state = QUIC_SSTREAM_STATE_DATA_RECVD;
/* We no longer need a QUIC_SSTREAM in this state. */
ossl_quic_sstream_free(qs->sstream);
qs->sstream = NULL;
return 1;
}
}
int ossl_quic_stream_map_reset_stream_send_part(QUIC_STREAM_MAP *qsm,
QUIC_STREAM *qs,
uint64_t aec)
{
switch (qs->send_state) {
default:
case QUIC_SSTREAM_STATE_NONE:
/*
* RESET_STREAM pertains to sending part only, so we cannot reset a
* receive-only stream.
*/
case QUIC_SSTREAM_STATE_DATA_RECVD:
/*
* RFC 9000 s. 3.3: A sender MUST NOT [...] send RESET_STREAM from a
* terminal state. If the stream has already finished normally and the
* peer has acknowledged this, we cannot reset it.
*/
return 0;
case QUIC_SSTREAM_STATE_READY:
if (!ossl_quic_stream_map_ensure_send_part_id(qsm, qs))
return 0;
/* FALLTHROUGH */
case QUIC_SSTREAM_STATE_SEND:
/*
* If we already have a final size (e.g. because we are coming from
* DATA_SENT), we have to be consistent with that, so don't change it.
* If we don't already have a final size, determine a final size value.
* This is the value which we will end up using for a RESET_STREAM frame
* for flow control purposes. We could send the stream size (total
* number of bytes appended to QUIC_SSTREAM by the application), but it
* is in our interest to exclude any bytes we have not actually
* transmitted yet, to avoid unnecessarily consuming flow control
* credit. We can get this from the TXFC.
*/
qs->send_final_size = ossl_quic_txfc_get_swm(&qs->txfc);
/* FALLTHROUGH */
case QUIC_SSTREAM_STATE_DATA_SENT:
qs->reset_stream_aec = aec;
qs->want_reset_stream = 1;
qs->send_state = QUIC_SSTREAM_STATE_RESET_SENT;
ossl_quic_sstream_free(qs->sstream);
qs->sstream = NULL;
ossl_quic_stream_map_update_state(qsm, qs);
return 1;
case QUIC_SSTREAM_STATE_RESET_SENT:
case QUIC_SSTREAM_STATE_RESET_RECVD:
/*
* Idempotent - no-op. In any case, do not send RESET_STREAM again - as
* mentioned, we must not send it from a terminal state.
*/
return 1;
}
}
int ossl_quic_stream_map_notify_reset_stream_acked(QUIC_STREAM_MAP *qsm,
QUIC_STREAM *qs)
{
switch (qs->send_state) {
default:
/* Wrong state - caller error. */
case QUIC_SSTREAM_STATE_NONE:
/* Stream without send part - caller error. */
return 0;
case QUIC_SSTREAM_STATE_RESET_SENT:
qs->send_state = QUIC_SSTREAM_STATE_RESET_RECVD;
return 1;
case QUIC_SSTREAM_STATE_RESET_RECVD:
/* Already in the correct state. */
return 1;
}
}
/*
* Stream Receive Part State Management
* ====================================
*/
int ossl_quic_stream_map_notify_size_known_recv_part(QUIC_STREAM_MAP *qsm,
QUIC_STREAM *qs,
uint64_t final_size)
{
switch (qs->recv_state) {
default:
/* Wrong state - caller error. */
case QUIC_RSTREAM_STATE_NONE:
/* Stream without receive part - caller error. */
return 0;
case QUIC_RSTREAM_STATE_RECV:
qs->recv_state = QUIC_RSTREAM_STATE_SIZE_KNOWN;
return 1;
}
}
int ossl_quic_stream_map_notify_totally_received(QUIC_STREAM_MAP *qsm,
QUIC_STREAM *qs)
{
switch (qs->recv_state) {
default:
/* Wrong state - caller error. */
case QUIC_RSTREAM_STATE_NONE:
/* Stream without receive part - caller error. */
return 0;
case QUIC_RSTREAM_STATE_SIZE_KNOWN:
qs->recv_state = QUIC_RSTREAM_STATE_DATA_RECVD;
qs->want_stop_sending = 0;
return 1;
}
}
int ossl_quic_stream_map_notify_totally_read(QUIC_STREAM_MAP *qsm,
QUIC_STREAM *qs)
{
switch (qs->recv_state) {
default:
/* Wrong state - caller error. */
case QUIC_RSTREAM_STATE_NONE:
/* Stream without receive part - caller error. */
return 0;
case QUIC_RSTREAM_STATE_DATA_RECVD:
qs->recv_state = QUIC_RSTREAM_STATE_DATA_READ;
/* QUIC_RSTREAM is no longer needed */
ossl_quic_rstream_free(qs->rstream);
qs->rstream = NULL;
return 1;
}
}
int ossl_quic_stream_map_notify_reset_recv_part(QUIC_STREAM_MAP *qsm,
QUIC_STREAM *qs,
uint64_t app_error_code,
uint64_t final_size)
{
uint64_t prev_final_size;
switch (qs->recv_state) {
default:
case QUIC_RSTREAM_STATE_NONE:
/* Stream without receive part - caller error. */
return 0;
case QUIC_RSTREAM_STATE_RECV:
case QUIC_RSTREAM_STATE_SIZE_KNOWN:
case QUIC_RSTREAM_STATE_DATA_RECVD:
if (ossl_quic_stream_recv_get_final_size(qs, &prev_final_size)
&& prev_final_size != final_size)
/* Cannot change previous final size. */
return 0;
qs->recv_state = QUIC_RSTREAM_STATE_RESET_RECVD;
qs->peer_reset_stream_aec = app_error_code;
/* RFC 9000 s. 3.3: No point sending STOP_SENDING if already reset. */
qs->want_stop_sending = 0;
/* QUIC_RSTREAM is no longer needed */
ossl_quic_rstream_free(qs->rstream);
qs->rstream = NULL;
ossl_quic_stream_map_update_state(qsm, qs);
return 1;
case QUIC_RSTREAM_STATE_DATA_READ:
/*
* If we already retired the FIN to the application this is moot
* - just ignore.
*/
case QUIC_RSTREAM_STATE_RESET_RECVD:
case QUIC_RSTREAM_STATE_RESET_READ:
/* Could be a reordered/retransmitted frame - just ignore. */
return 1;
}
}
int ossl_quic_stream_map_notify_app_read_reset_recv_part(QUIC_STREAM_MAP *qsm,
QUIC_STREAM *qs)
{
switch (qs->recv_state) {
default:
/* Wrong state - caller error. */
case QUIC_RSTREAM_STATE_NONE:
/* Stream without receive part - caller error. */
return 0;
case QUIC_RSTREAM_STATE_RESET_RECVD:
qs->recv_state = QUIC_RSTREAM_STATE_RESET_READ;
return 1;
}
}
int ossl_quic_stream_map_stop_sending_recv_part(QUIC_STREAM_MAP *qsm,
QUIC_STREAM *qs,
uint64_t aec)
{
if (qs->stop_sending)
return 0;
switch (qs->recv_state) {
default:
case QUIC_RSTREAM_STATE_NONE:
/* Send-only stream, so this makes no sense. */
case QUIC_RSTREAM_STATE_DATA_RECVD:
case QUIC_RSTREAM_STATE_DATA_READ:
/*
* Not really any point in STOP_SENDING if we already received all data.
*/
case QUIC_RSTREAM_STATE_RESET_RECVD:
case QUIC_RSTREAM_STATE_RESET_READ:
/*
* RFC 9000 s. 3.5: "STOP_SENDING SHOULD only be sent for a stream that
* has not been reset by the peer."
*
* No point in STOP_SENDING if the peer already reset their send part.
*/
return 0;
case QUIC_RSTREAM_STATE_RECV:
case QUIC_RSTREAM_STATE_SIZE_KNOWN:
/*
* RFC 9000 s. 3.5: "If the stream is in the Recv or Size Known state,
* the transport SHOULD signal this by sending a STOP_SENDING frame to
* prompt closure of the stream in the opposite direction."
*
* Note that it does make sense to send STOP_SENDING for a receive part
* of a stream which has a known size (because we have received a FIN)
* but which still has other (previous) stream data yet to be received.
*/
break;
}
qs->stop_sending = 1;
qs->stop_sending_aec = aec;
return ossl_quic_stream_map_schedule_stop_sending(qsm, qs);
}
/* Called to mark STOP_SENDING for generation, or regeneration after loss. */
int ossl_quic_stream_map_schedule_stop_sending(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs)
{
if (!qs->stop_sending)
return 0;
/*
* Ignore the call as a no-op if already scheduled, or in a state
* where it makes no sense to send STOP_SENDING.
*/
if (qs->want_stop_sending)
return 1;
switch (qs->recv_state) {
default:
return 1; /* ignore */
case QUIC_RSTREAM_STATE_RECV:
case QUIC_RSTREAM_STATE_SIZE_KNOWN:
/*
* RFC 9000 s. 3.5: "An endpoint is expected to send another
* STOP_SENDING frame if a packet containing a previous STOP_SENDING is
* lost. However, once either all stream data or a RESET_STREAM frame
* has been received for the stream -- that is, the stream is in any
* state other than "Recv" or "Size Known" -- sending a STOP_SENDING
* frame is unnecessary."
*/
break;
}
qs->want_stop_sending = 1;
ossl_quic_stream_map_update_state(qsm, qs);
return 1;
}
QUIC_STREAM *ossl_quic_stream_map_peek_accept_queue(QUIC_STREAM_MAP *qsm)
{
return accept_head(&qsm->accept_list);
}
void ossl_quic_stream_map_push_accept_queue(QUIC_STREAM_MAP *qsm,
QUIC_STREAM *s)
{
list_insert_tail(&qsm->accept_list, &s->accept_node);
++qsm->num_accept;
}
static QUIC_RXFC *qsm_get_max_streams_rxfc(QUIC_STREAM_MAP *qsm, QUIC_STREAM *s)
{
return ossl_quic_stream_is_bidi(s)
? qsm->max_streams_bidi_rxfc
: qsm->max_streams_uni_rxfc;
}
void ossl_quic_stream_map_remove_from_accept_queue(QUIC_STREAM_MAP *qsm,
QUIC_STREAM *s,
OSSL_TIME rtt)
{
QUIC_RXFC *max_streams_rxfc;
list_remove(&qsm->accept_list, &s->accept_node);
--qsm->num_accept;
if ((max_streams_rxfc = qsm_get_max_streams_rxfc(qsm, s)) != NULL)
ossl_quic_rxfc_on_retire(max_streams_rxfc, 1, rtt);
}
size_t ossl_quic_stream_map_get_accept_queue_len(QUIC_STREAM_MAP *qsm)
{
return qsm->num_accept;
}
void ossl_quic_stream_map_gc(QUIC_STREAM_MAP *qsm)
{
QUIC_STREAM *qs, *qs_head, *qsn = NULL;
for (qs = qs_head = ready_for_gc_head(&qsm->ready_for_gc_list);
qs != NULL && qs != qs_head;
qs = qsn)
{
qsn = ready_for_gc_next(&qsm->ready_for_gc_list, qs);
ossl_quic_stream_map_release(qsm, qs);
}
}
/*
* QUIC Stream Iterator
* ====================
*/
void ossl_quic_stream_iter_init(QUIC_STREAM_ITER *it, QUIC_STREAM_MAP *qsm,
int advance_rr)
{
it->qsm = qsm;
it->stream = it->first_stream = qsm->rr_cur;
if (advance_rr && it->stream != NULL
&& ++qsm->rr_counter >= qsm->rr_stepping) {
qsm->rr_counter = 0;
qsm->rr_cur = active_next(&qsm->active_list, qsm->rr_cur);
}
}
void ossl_quic_stream_iter_next(QUIC_STREAM_ITER *it)
{
if (it->stream == NULL)
return;
it->stream = active_next(&it->qsm->active_list, it->stream);
if (it->stream == it->first_stream)
it->stream = NULL;
}
| 23,800 | 29.750646 | 85 | c |
openssl | openssl-master/ssl/quic/quic_thread_assist.c | /*
* Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/macros.h>
#include "quic_local.h"
#include "internal/time.h"
#include "internal/thread.h"
#include "internal/thread_arch.h"
#include "internal/quic_thread_assist.h"
#if !defined(OPENSSL_NO_QUIC_THREAD_ASSIST)
/* Main loop for the QUIC assist thread. */
static unsigned int assist_thread_main(void *arg)
{
QUIC_THREAD_ASSIST *qta = arg;
CRYPTO_MUTEX *m = ossl_quic_channel_get_mutex(qta->ch);
QUIC_REACTOR *rtor;
ossl_crypto_mutex_lock(m);
rtor = ossl_quic_channel_get_reactor(qta->ch);
for (;;) {
if (qta->teardown)
break;
ossl_crypto_condvar_wait_timeout(qta->cv, m,
ossl_quic_reactor_get_tick_deadline(rtor));
/*
* We have now been woken up. This can be for one of the following
* reasons:
*
* - We have been asked to teardown (qta->teardown is set);
* - The tick deadline has passed.
* - The tick deadline has changed.
*
* For robustness, this loop also handles spurious wakeups correctly
* (which does not require any extra code).
*/
if (qta->teardown)
break;
ossl_quic_reactor_tick(rtor, QUIC_REACTOR_TICK_FLAG_CHANNEL_ONLY);
}
ossl_crypto_mutex_unlock(m);
return 1;
}
int ossl_quic_thread_assist_init_start(QUIC_THREAD_ASSIST *qta,
QUIC_CHANNEL *ch)
{
CRYPTO_MUTEX *mutex = ossl_quic_channel_get_mutex(ch);
if (mutex == NULL)
return 0;
qta->ch = ch;
qta->teardown = 0;
qta->joined = 0;
qta->cv = ossl_crypto_condvar_new();
if (qta->cv == NULL)
return 0;
qta->t = ossl_crypto_thread_native_start(assist_thread_main,
qta, /*joinable=*/1);
if (qta->t == NULL) {
ossl_crypto_condvar_free(qta->cv);
return 0;
}
return 1;
}
int ossl_quic_thread_assist_stop_async(QUIC_THREAD_ASSIST *qta)
{
if (!qta->teardown) {
qta->teardown = 1;
ossl_crypto_condvar_signal(qta->cv);
}
return 1;
}
int ossl_quic_thread_assist_wait_stopped(QUIC_THREAD_ASSIST *qta)
{
CRYPTO_THREAD_RETVAL rv;
CRYPTO_MUTEX *m = ossl_quic_channel_get_mutex(qta->ch);
if (qta->joined)
return 1;
if (!ossl_quic_thread_assist_stop_async(qta))
return 0;
ossl_crypto_mutex_unlock(m);
if (!ossl_crypto_thread_native_join(qta->t, &rv)) {
ossl_crypto_mutex_lock(m);
return 0;
}
qta->joined = 1;
ossl_crypto_mutex_lock(m);
return 1;
}
int ossl_quic_thread_assist_cleanup(QUIC_THREAD_ASSIST *qta)
{
if (!ossl_assert(qta->joined))
return 0;
ossl_crypto_condvar_free(&qta->cv);
ossl_crypto_thread_native_clean(qta->t);
qta->ch = NULL;
qta->t = NULL;
return 1;
}
int ossl_quic_thread_assist_notify_deadline_changed(QUIC_THREAD_ASSIST *qta)
{
if (qta->teardown)
return 0;
ossl_crypto_condvar_signal(qta->cv);
return 1;
}
#endif
| 3,430 | 23.333333 | 84 | c |
openssl | openssl-master/ssl/quic/quic_tls.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/ssl.h>
#include "internal/recordmethod.h"
#include "internal/quic_tls.h"
#include "../ssl_local.h"
#define QUIC_TLS_FATAL(rl, ad, err) \
do { \
(rl)->alert = (ad); \
ERR_raise(ERR_LIB_SSL, (err)); \
(rl)->qtls->inerror = 1; \
} while(0)
struct quic_tls_st {
QUIC_TLS_ARGS args;
/*
* Transport parameters which client should send. Buffer lifetime must
* exceed the lifetime of the QUIC_TLS object.
*/
const unsigned char *local_transport_params;
size_t local_transport_params_len;
/* Whether our SSL object for TLS has been configured for use in QUIC */
unsigned int configured : 1;
/* Set if we have hit any error state */
unsigned int inerror : 1;
/* Set if the handshake has completed */
unsigned int complete : 1;
};
struct ossl_record_layer_st {
QUIC_TLS *qtls;
/* Protection level */
int level;
/* Only used for retry flags */
BIO *dummybio;
/* Number of bytes written so far if we are part way through a write */
size_t written;
/* If we are part way through a write, a copy of the template */
OSSL_RECORD_TEMPLATE template;
/*
* If we hit an error, what alert code should be used
*/
int alert;
/* Amount of crypto stream data we read in the last call to quic_read_record */
size_t recread;
/* Amount of crypto stream data read but not yet released */
size_t recunreleased;
/* Callbacks */
OSSL_FUNC_rlayer_msg_callback_fn *msg_callback;
void *cbarg;
};
static int
quic_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
int role, int direction, int level, uint16_t epoch,
unsigned char *secret, size_t secretlen,
unsigned char *key, size_t keylen, unsigned char *iv,
size_t ivlen, unsigned char *mackey, size_t mackeylen,
const EVP_CIPHER *ciph, size_t taglen,
int mactype,
const EVP_MD *md, COMP_METHOD *comp,
const EVP_MD *kdfdigest, BIO *prev, BIO *transport,
BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
const OSSL_PARAM *settings, const OSSL_PARAM *options,
const OSSL_DISPATCH *fns, void *cbarg, void *rlarg,
OSSL_RECORD_LAYER **retrl)
{
OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
uint32_t enc_level;
int qdir;
uint32_t suite_id = 0;
if (rl == NULL) {
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
rl->qtls = (QUIC_TLS *)rlarg;
rl->level = level;
rl->dummybio = transport;
rl->cbarg = cbarg;
*retrl = rl;
if (fns != NULL) {
for (; fns->function_id != 0; fns++) {
switch (fns->function_id) {
break;
case OSSL_FUNC_RLAYER_MSG_CALLBACK:
rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns);
break;
default:
/* Just ignore anything we don't understand */
break;
}
}
}
switch (level) {
case OSSL_RECORD_PROTECTION_LEVEL_NONE:
return 1;
case OSSL_RECORD_PROTECTION_LEVEL_EARLY:
enc_level = QUIC_ENC_LEVEL_0RTT;
break;
case OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE:
enc_level = QUIC_ENC_LEVEL_HANDSHAKE;
break;
case OSSL_RECORD_PROTECTION_LEVEL_APPLICATION:
enc_level = QUIC_ENC_LEVEL_1RTT;
break;
default:
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (direction == OSSL_RECORD_DIRECTION_READ)
qdir = 0;
else
qdir = 1;
if (EVP_CIPHER_is_a(ciph, "AES-128-GCM")) {
suite_id = QRL_SUITE_AES128GCM;
} else if (EVP_CIPHER_is_a(ciph, "AES-256-GCM")) {
suite_id = QRL_SUITE_AES256GCM;
} else if (EVP_CIPHER_is_a(ciph, "CHACHA20-POLY1305")) {
suite_id = QRL_SUITE_CHACHA20POLY1305;
} else {
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_CIPHER_TYPE);
goto err;
}
/* We pass a ref to the md in a successful yield_secret_cb call */
/* TODO(QUIC): This cast is horrible. We should try and remove it */
if (!EVP_MD_up_ref((EVP_MD *)kdfdigest)) {
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
goto err;
}
if (!rl->qtls->args.yield_secret_cb(enc_level, qdir, suite_id,
(EVP_MD *)kdfdigest, secret, secretlen,
rl->qtls->args.yield_secret_cb_arg)) {
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
EVP_MD_free((EVP_MD *)kdfdigest);
goto err;
}
return 1;
err:
*retrl = NULL;
OPENSSL_free(rl);
return 0;
}
static int quic_free(OSSL_RECORD_LAYER *rl)
{
if (rl == NULL)
return 1;
OPENSSL_free(rl);
return 1;
}
static int quic_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
{
/*
* Read ahead isn't really a thing for QUIC so we never have unprocessed
* data pending
*/
return 0;
}
static int quic_processed_read_pending(OSSL_RECORD_LAYER *rl)
{
/*
* This is currently only ever used by:
* - SSL_has_pending()
* - to check whether we have more records that we want to supply to the
* upper layers
*
* We only ever supply 1 record at a time to the upper layers, and
* SSL_has_pending() will go via the QUIC method not the TLS method so that
* use case doesn't apply here.
* Therefore we can ignore this for now and always return 0. We might
* eventually want to change this to check in the receive buffers to see if
* we have any more data pending.
*/
return 0;
}
static size_t quic_get_max_records(OSSL_RECORD_LAYER *rl, int type, size_t len,
size_t maxfrag, size_t *preffrag)
{
return 1;
}
static int quic_write_records(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *template,
size_t numtempl)
{
size_t consumed;
unsigned char alert;
if (!ossl_assert(numtempl == 1)) {
/* How could this be? quic_get_max_records() always returns 1 */
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
BIO_clear_retry_flags(rl->dummybio);
if (rl->msg_callback != NULL) {
unsigned char dummyrec[SSL3_RT_HEADER_LENGTH];
/*
* For the purposes of the callback we "pretend" to be normal TLS,
* and manufacture a dummy record header
*/
dummyrec[0] = (rl->level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
? template->type
: SSL3_RT_APPLICATION_DATA;
dummyrec[1] = (unsigned char)((template->version >> 8) & 0xff);
dummyrec[2] = (unsigned char)(template->version & 0xff);
/*
* We assume that buflen is always <= UINT16_MAX. Since this is
* generated by libssl itself we actually expect it to never
* exceed SSL3_RT_MAX_PLAIN_LENGTH - so it should be a safe
* assumption
*/
dummyrec[3] = (unsigned char)((template->buflen >> 8) & 0xff);
dummyrec[4] = (unsigned char)(template->buflen & 0xff);
rl->msg_callback(1, TLS1_3_VERSION, SSL3_RT_HEADER, dummyrec,
SSL3_RT_HEADER_LENGTH, rl->cbarg);
if (rl->level != OSSL_RECORD_PROTECTION_LEVEL_NONE) {
rl->msg_callback(1, TLS1_3_VERSION, SSL3_RT_INNER_CONTENT_TYPE,
&template->type, 1, rl->cbarg);
}
}
switch (template->type) {
case SSL3_RT_ALERT:
if (template->buflen != 2) {
/*
* We assume that libssl always sends both bytes of an alert to
* us in one go, and never fragments it. If we ever get more
* or less bytes than exactly 2 then this is very unexpected.
*/
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_VALUE);
return OSSL_RECORD_RETURN_FATAL;
}
/*
* Byte 0 is the alert level (we ignore it) and byte 1 is the alert
* description that we are actually interested in.
*/
alert = template->buf[1];
if (!rl->qtls->args.alert_cb(rl->qtls->args.alert_cb_arg, alert)) {
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
break;
case SSL3_RT_HANDSHAKE:
/*
* We expect this to only fail on some fatal error (e.g. malloc
* failure)
*/
if (!rl->qtls->args.crypto_send_cb(template->buf + rl->written,
template->buflen - rl->written,
&consumed,
rl->qtls->args.crypto_send_cb_arg)) {
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
/*
* We might have written less than we wanted to if we have filled the
* send stream buffer.
*/
if (consumed + rl->written != template->buflen) {
if (!ossl_assert(consumed + rl->written < template->buflen)) {
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
/*
* We've not written everything we wanted to. Take a copy of the
* template, remember how much we wrote so far and signal a retry.
* The buffer supplied in the template is guaranteed to be the same
* on a retry for handshake data
*/
rl->written += consumed;
rl->template = *template;
BIO_set_retry_write(rl->dummybio);
return OSSL_RECORD_RETURN_RETRY;
}
rl->written = 0;
break;
default:
/* Anything else is unexpected and an error */
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
return OSSL_RECORD_RETURN_SUCCESS;
}
static int quic_retry_write_records(OSSL_RECORD_LAYER *rl)
{
return quic_write_records(rl, &rl->template, 1);
}
static int quic_read_record(OSSL_RECORD_LAYER *rl, void **rechandle,
int *rversion, int *type, const unsigned char **data,
size_t *datalen, uint16_t *epoch,
unsigned char *seq_num)
{
if (rl->recread != 0 || rl->recunreleased != 0)
return OSSL_RECORD_RETURN_FATAL;
BIO_clear_retry_flags(rl->dummybio);
if (!rl->qtls->args.crypto_recv_rcd_cb(data, datalen,
rl->qtls->args.crypto_recv_rcd_cb_arg)) {
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
if (*datalen == 0) {
BIO_set_retry_read(rl->dummybio);
return OSSL_RECORD_RETURN_RETRY;
}
*rechandle = rl;
*rversion = TLS1_3_VERSION;
*type = SSL3_RT_HANDSHAKE;
rl->recread = rl->recunreleased = *datalen;
/* epoch/seq_num are not relevant for TLS */
if (rl->msg_callback != NULL) {
unsigned char dummyrec[SSL3_RT_HEADER_LENGTH];
/*
* For the purposes of the callback we "pretend" to be normal TLS,
* and manufacture a dummy record header
*/
dummyrec[0] = (rl->level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
? SSL3_RT_HANDSHAKE
: SSL3_RT_APPLICATION_DATA;
dummyrec[1] = (unsigned char)((TLS1_2_VERSION >> 8) & 0xff);
dummyrec[2] = (unsigned char)(TLS1_2_VERSION & 0xff);
/*
* *datalen will always fit into 2 bytes because our original buffer
* size is less than that.
*/
dummyrec[3] = (unsigned char)((*datalen >> 8) & 0xff);
dummyrec[4] = (unsigned char)(*datalen & 0xff);
rl->msg_callback(0, TLS1_3_VERSION, SSL3_RT_HEADER, dummyrec,
SSL3_RT_HEADER_LENGTH, rl->cbarg);
rl->msg_callback(0, TLS1_3_VERSION, SSL3_RT_INNER_CONTENT_TYPE, type, 1,
rl->cbarg);
}
return OSSL_RECORD_RETURN_SUCCESS;
}
static int quic_release_record(OSSL_RECORD_LAYER *rl, void *rechandle,
size_t length)
{
if (!ossl_assert(rl->recread > 0)
|| !ossl_assert(rl->recunreleased <= rl->recread)
|| !ossl_assert(rl == rechandle)
|| !ossl_assert(length <= rl->recunreleased)) {
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
rl->recunreleased -= length;
if (rl->recunreleased > 0)
return OSSL_RECORD_RETURN_SUCCESS;
if (!rl->qtls->args.crypto_release_rcd_cb(rl->recread,
rl->qtls->args.crypto_release_rcd_cb_arg)) {
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
rl->recread = 0;
return OSSL_RECORD_RETURN_SUCCESS;
}
static int quic_get_alert_code(OSSL_RECORD_LAYER *rl)
{
return rl->alert;
}
static int quic_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
{
/* We only support TLSv1.3, so its bad if we negotiate anything else */
if (!ossl_assert(version == TLS1_3_VERSION)) {
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
static void quic_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
{
/* We don't care */
}
static void quic_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
{
/* We don't care */
}
static void quic_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
{
/* We don't care */
}
static void quic_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
const char **longstr)
{
/*
* According to the docs, valid read state strings are: "RH"/"read header",
* "RB"/"read body", and "unknown"/"unknown". We don't read records in quite
* that way, so we report every "normal" state as "read header". In the
* event of error then we report "unknown".
*/
if (rl->qtls->inerror) {
if (shortstr != NULL)
*shortstr = "unknown";
if (longstr != NULL)
*longstr = "unknown";
} else {
if (shortstr != NULL)
*shortstr = "RH";
if (longstr != NULL)
*longstr = "read header";
}
}
static int quic_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options)
{
/*
* We don't support any options yet - but we might do at some point so
* this could be useful.
*/
return 1;
}
static const COMP_METHOD *quic_get_compression(OSSL_RECORD_LAYER *rl)
{
/* We only support TLSv1.3 which doesn't have compression */
return NULL;
}
static void quic_set_max_frag_len(OSSL_RECORD_LAYER *rl, size_t max_frag_len)
{
/* This really doesn't make any sense for QUIC. Ignore it */
}
static int quic_alloc_buffers(OSSL_RECORD_LAYER *rl)
{
/*
* This is a hint only. We don't support it (yet), so just ignore the
* request
*/
return 1;
}
static int quic_free_buffers(OSSL_RECORD_LAYER *rl)
{
/*
* This is a hint only. We don't support it (yet), so just ignore the
* request
*/
return 1;
}
static int quic_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
{
/*
* Can be called to set the buffering BIO - which is then never used by us.
* We ignore it
*/
return 1;
}
/*
* Never called functions
*
* Due to the way we are configured and used we never expect any of the next set
* of functions to be called. Therefore we set them to always fail.
*/
static size_t quic_app_data_pending(OSSL_RECORD_LAYER *rl)
{
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return (size_t)ossl_assert(0);
}
static size_t quic_get_max_record_overhead(OSSL_RECORD_LAYER *rl)
{
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return (size_t)ossl_assert(0);
}
static int quic_increment_sequence_ctr(OSSL_RECORD_LAYER *rl)
{
QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return ossl_assert(0);
}
/* End of never called functions */
static const OSSL_RECORD_METHOD quic_tls_record_method = {
quic_new_record_layer,
quic_free,
quic_unprocessed_read_pending,
quic_processed_read_pending,
quic_app_data_pending, /* Never called */
quic_get_max_records,
quic_write_records,
quic_retry_write_records,
quic_read_record,
quic_release_record,
quic_get_alert_code,
quic_set1_bio,
quic_set_protocol_version,
quic_set_plain_alerts,
quic_set_first_handshake,
quic_set_max_pipelines,
NULL, /* set_in_init: Optional - we don't need it */
quic_get_state,
quic_set_options,
quic_get_compression,
quic_set_max_frag_len,
quic_get_max_record_overhead, /* Never called */
quic_increment_sequence_ctr, /* Never called */
quic_alloc_buffers,
quic_free_buffers
};
static int add_transport_params_cb(SSL *s, unsigned int ext_type,
unsigned int context,
const unsigned char **out, size_t *outlen,
X509 *x, size_t chainidx, int *al,
void *add_arg)
{
QUIC_TLS *qtls = add_arg;
*out = qtls->local_transport_params;
*outlen = qtls->local_transport_params_len;
return 1;
}
static void free_transport_params_cb(SSL *s, unsigned int ext_type,
unsigned int context,
const unsigned char *out,
void *add_arg)
{
}
static int parse_transport_params_cb(SSL *s, unsigned int ext_type,
unsigned int context,
const unsigned char *in,
size_t inlen, X509 *x,
size_t chainidx,
int *al, void *parse_arg)
{
QUIC_TLS *qtls = parse_arg;
return qtls->args.got_transport_params_cb(in, inlen,
qtls->args.got_transport_params_cb_arg);
}
QUIC_TLS *ossl_quic_tls_new(const QUIC_TLS_ARGS *args)
{
QUIC_TLS *qtls;
if (args->crypto_send_cb == NULL
|| args->crypto_recv_rcd_cb == NULL
|| args->crypto_release_rcd_cb == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
qtls = OPENSSL_zalloc(sizeof(*qtls));
if (qtls == NULL)
return NULL;
qtls->args = *args;
return qtls;
}
void ossl_quic_tls_free(QUIC_TLS *qtls)
{
OPENSSL_free(qtls);
}
int ossl_quic_tls_tick(QUIC_TLS *qtls)
{
int ret;
const unsigned char *alpn;
unsigned int alpnlen;
/*
* TODO(QUIC): There are various calls here that could fail and ordinarily
* would result in an ERR_raise call - but "tick" calls aren't supposed to
* fail "loudly" - so its unclear how we will report these errors. The
* ERR_raise calls are omitted from this function for now.
*/
if (qtls->inerror)
return 0;
if (qtls->complete)
return 1;
if (!qtls->configured) {
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(qtls->args.s);
SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(sc);
BIO *nullbio;
/*
* No matter how the user has configured us, there are certain
* requirements for QUIC-TLS that we enforce
*/
/* ALPN is a requirement for QUIC and must be set */
if (qtls->args.is_server) {
if (sctx->ext.alpn_select_cb == NULL) {
qtls->inerror = 1;
return 0;
}
} else {
if (sc->ext.alpn == NULL || sc->ext.alpn_len == 0) {
qtls->inerror = 1;
return 0;
}
}
if (!SSL_set_min_proto_version(qtls->args.s, TLS1_3_VERSION)) {
qtls->inerror = 1;
return 0;
}
SSL_clear_options(qtls->args.s, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
ossl_ssl_set_custom_record_layer(sc, &quic_tls_record_method, qtls);
if (!ossl_tls_add_custom_ext_intern(NULL, &sc->cert->custext,
qtls->args.is_server ? ENDPOINT_SERVER
: ENDPOINT_CLIENT,
TLSEXT_TYPE_quic_transport_parameters,
SSL_EXT_TLS1_3_ONLY
| SSL_EXT_CLIENT_HELLO
| SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
add_transport_params_cb,
free_transport_params_cb, qtls,
parse_transport_params_cb, qtls)) {
qtls->inerror = 1;
return 0;
}
nullbio = BIO_new(BIO_s_null());
if (nullbio == NULL) {
qtls->inerror = 1;
return 0;
}
/*
* Our custom record layer doesn't use the BIO - but libssl generally
* expects one to be present.
*/
SSL_set_bio(qtls->args.s, nullbio, nullbio);
if (qtls->args.is_server) {
SSL_set_accept_state(qtls->args.s);
if (!SSL_set_num_tickets(qtls->args.s, 0)) {
qtls->inerror = 1;
return 0;
}
} else {
SSL_set_connect_state(qtls->args.s);
}
qtls->configured = 1;
}
ret = SSL_do_handshake(qtls->args.s);
if (ret <= 0) {
switch (SSL_get_error(qtls->args.s, ret)) {
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
return 1;
default:
qtls->inerror = 1;
return 0;
}
}
/* Validate that we have ALPN */
SSL_get0_alpn_selected(qtls->args.s, &alpn, &alpnlen);
if (alpn == NULL || alpnlen == 0) {
qtls->inerror = 1;
return 0;
}
qtls->complete = 1;
return qtls->args.handshake_complete_cb(qtls->args.handshake_complete_cb_arg);
}
int ossl_quic_tls_set_transport_params(QUIC_TLS *qtls,
const unsigned char *transport_params,
size_t transport_params_len)
{
qtls->local_transport_params = transport_params;
qtls->local_transport_params_len = transport_params_len;
return 1;
}
| 23,615 | 30.614458 | 90 | c |
openssl | openssl-master/ssl/quic/quic_trace.c | /*
* Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/bio.h>
#include "../ssl_local.h"
#include "internal/quic_wire_pkt.h"
static const char *packet_type(int type)
{
switch (type) {
case QUIC_PKT_TYPE_INITIAL:
return "Initial";
case QUIC_PKT_TYPE_0RTT:
return "0RTT";
case QUIC_PKT_TYPE_HANDSHAKE:
return "Handshake";
case QUIC_PKT_TYPE_RETRY:
return "Retry";
case QUIC_PKT_TYPE_1RTT:
return "1RTT";
case QUIC_PKT_TYPE_VERSION_NEG:
return "VersionNeg";
default:
return "Unknown";
}
}
/* Print a non-NUL terminated string to BIO */
static void put_str(BIO *bio, char *str, size_t slen)
{
size_t i;
for (i = 0; i < slen; i++)
BIO_printf(bio, "%c", str[i]);
}
static void put_data(BIO *bio, const uint8_t *data, size_t datalen)
{
size_t i;
for (i = 0; i < datalen; i++)
BIO_printf(bio, "%02x", data[i]);
}
static void put_conn_id(BIO *bio, QUIC_CONN_ID *id)
{
if (id->id_len == 0) {
BIO_puts(bio, "<zero length id>");
return;
}
BIO_puts(bio, "0x");
put_data(bio, id->id, id->id_len);
}
static void put_token(BIO *bio, const uint8_t *token, size_t token_len)
{
if (token_len == 0)
BIO_puts(bio, "<zerlo length token>");
else
put_data(bio, token, token_len);
}
static int frame_ack(BIO *bio, PACKET *pkt)
{
OSSL_QUIC_FRAME_ACK ack;
OSSL_QUIC_ACK_RANGE *ack_ranges = NULL;
uint64_t total_ranges = 0;
uint64_t i;
if (!ossl_quic_wire_peek_frame_ack_num_ranges(pkt, &total_ranges)
/* In case sizeof(uint64_t) > sizeof(size_t) */
|| total_ranges > SIZE_MAX / sizeof(ack_ranges[0])
|| (ack_ranges = OPENSSL_zalloc(sizeof(ack_ranges[0])
* (size_t)total_ranges)) == NULL)
return 0;
ack.ack_ranges = ack_ranges;
ack.num_ack_ranges = (size_t)total_ranges;
/* Ack delay exponent is 0, so we can get the raw delay time below */
if (!ossl_quic_wire_decode_frame_ack(pkt, 0, &ack, NULL))
return 0;
BIO_printf(bio, " Largest acked: %llu\n",
(unsigned long long)ack.ack_ranges[0].end);
BIO_printf(bio, " Ack delay (raw) %llu\n",
(unsigned long long)ossl_time2ticks(ack.delay_time));
BIO_printf(bio, " Ack range count: %llu\n",
(unsigned long long)total_ranges - 1);
BIO_printf(bio, " First ack range: %llu\n",
(unsigned long long)(ack.ack_ranges[0].end
- ack.ack_ranges[0].start));
for (i = 1; i < total_ranges; i++) {
BIO_printf(bio, " Gap: %llu\n",
(unsigned long long)(ack.ack_ranges[i - 1].start
- ack.ack_ranges[i].end - 2));
BIO_printf(bio, " Ack range len: %llu\n",
(unsigned long long)(ack.ack_ranges[i].end
- ack.ack_ranges[i].start));
}
OPENSSL_free(ack_ranges);
return 1;
}
static int frame_reset_stream(BIO *bio, PACKET *pkt)
{
OSSL_QUIC_FRAME_RESET_STREAM frame_data;
if (!ossl_quic_wire_decode_frame_reset_stream(pkt, &frame_data))
return 0;
BIO_printf(bio, " Stream id: %llu\n",
(unsigned long long)frame_data.stream_id);
BIO_printf(bio, " App Protocol Error Code: %llu\n",
(unsigned long long)frame_data.app_error_code);
BIO_printf(bio, " Final size: %llu\n",
(unsigned long long)frame_data.final_size);
return 1;
}
static int frame_stop_sending(BIO *bio, PACKET *pkt)
{
OSSL_QUIC_FRAME_STOP_SENDING frame_data;
if (!ossl_quic_wire_decode_frame_stop_sending(pkt, &frame_data))
return 0;
BIO_printf(bio, " Stream id: %llu\n",
(unsigned long long)frame_data.stream_id);
BIO_printf(bio, " App Protocol Error Code: %llu\n",
(unsigned long long)frame_data.app_error_code);
return 1;
}
static int frame_crypto(BIO *bio, PACKET *pkt)
{
OSSL_QUIC_FRAME_CRYPTO frame_data;
if (!ossl_quic_wire_decode_frame_crypto(pkt, 1, &frame_data))
return 0;
BIO_printf(bio, " Offset: %llu\n", (unsigned long long)frame_data.offset);
BIO_printf(bio, " Len: %llu\n", (unsigned long long)frame_data.len);
return 1;
}
static int frame_new_token(BIO *bio, PACKET *pkt)
{
const uint8_t *token;
size_t token_len;
if (!ossl_quic_wire_decode_frame_new_token(pkt, &token, &token_len))
return 0;
BIO_puts(bio, " Token: ");
put_token(bio, token, token_len);
BIO_puts(bio, "\n");
return 1;
}
static int frame_stream(BIO *bio, PACKET *pkt, uint64_t frame_type)
{
OSSL_QUIC_FRAME_STREAM frame_data;
BIO_puts(bio, "Stream");
switch(frame_type) {
case OSSL_QUIC_FRAME_TYPE_STREAM:
BIO_puts(bio, "\n");
break;
case OSSL_QUIC_FRAME_TYPE_STREAM_FIN:
BIO_puts(bio, " (Fin)\n");
break;
case OSSL_QUIC_FRAME_TYPE_STREAM_LEN:
BIO_puts(bio, " (Len)\n");
break;
case OSSL_QUIC_FRAME_TYPE_STREAM_LEN_FIN:
BIO_puts(bio, " (Len, Fin)\n");
break;
case OSSL_QUIC_FRAME_TYPE_STREAM_OFF:
BIO_puts(bio, " (Off)\n");
break;
case OSSL_QUIC_FRAME_TYPE_STREAM_OFF_FIN:
BIO_puts(bio, " (Off, Fin)\n");
break;
case OSSL_QUIC_FRAME_TYPE_STREAM_OFF_LEN:
BIO_puts(bio, " (Off, Len)\n");
break;
case OSSL_QUIC_FRAME_TYPE_STREAM_OFF_LEN_FIN:
BIO_puts(bio, " (Off, Len, Fin)\n");
break;
default:
return 0;
}
if (!ossl_quic_wire_decode_frame_stream(pkt, 1, &frame_data))
return 0;
BIO_printf(bio, " Stream id: %llu\n",
(unsigned long long)frame_data.stream_id);
BIO_printf(bio, " Offset: %llu\n",
(unsigned long long)frame_data.offset);
/*
* It would be nice to find a way of passing the implicit length through
* to the msg_callback. But this is not currently possible.
*/
if (frame_data.has_explicit_len)
BIO_printf(bio, " Len: %llu\n", (unsigned long long)frame_data.len);
else
BIO_puts(bio, " Len: <implicit length>\n");
return 1;
}
static int frame_max_data(BIO *bio, PACKET *pkt)
{
uint64_t max_data = 0;
if (!ossl_quic_wire_decode_frame_max_data(pkt, &max_data))
return 0;
BIO_printf(bio, " Max Data: %llu\n", (unsigned long long)max_data);
return 1;
}
static int frame_max_stream_data(BIO *bio, PACKET *pkt)
{
uint64_t stream_id = 0;
uint64_t max_stream_data = 0;
if (!ossl_quic_wire_decode_frame_max_stream_data(pkt, &stream_id,
&max_stream_data))
return 0;
BIO_printf(bio, " Max Stream Data: %llu\n",
(unsigned long long)max_stream_data);
return 1;
}
static int frame_max_streams(BIO *bio, PACKET *pkt)
{
uint64_t max_streams = 0;
if (!ossl_quic_wire_decode_frame_max_streams(pkt, &max_streams))
return 0;
BIO_printf(bio, " Max Streams: %llu\n", (unsigned long long)max_streams);
return 1;
}
static int frame_data_blocked(BIO *bio, PACKET *pkt)
{
uint64_t max_data = 0;
if (!ossl_quic_wire_decode_frame_data_blocked(pkt, &max_data))
return 0;
BIO_printf(bio, " Max Data: %llu\n", (unsigned long long)max_data);
return 1;
}
static int frame_stream_data_blocked(BIO *bio, PACKET *pkt)
{
uint64_t stream_id = 0;
uint64_t max_data = 0;
if (!ossl_quic_wire_decode_frame_stream_data_blocked(pkt, &stream_id,
&max_data))
return 0;
BIO_printf(bio, " Stream id: %llu\n", (unsigned long long)stream_id);
BIO_printf(bio, " Max Data: %llu\n", (unsigned long long)max_data);
return 1;
}
static int frame_streams_blocked(BIO *bio, PACKET *pkt)
{
uint64_t max_data = 0;
if (!ossl_quic_wire_decode_frame_streams_blocked(pkt, &max_data))
return 0;
BIO_printf(bio, " Max Data: %llu\n", (unsigned long long)max_data);
return 1;
}
static int frame_new_conn_id(BIO *bio, PACKET *pkt)
{
OSSL_QUIC_FRAME_NEW_CONN_ID frame_data;
if (!ossl_quic_wire_decode_frame_new_conn_id(pkt, &frame_data))
return 0;
BIO_printf(bio, " Sequence Number: %llu\n",
(unsigned long long)frame_data.seq_num);
BIO_printf(bio, " Retire prior to: %llu\n",
(unsigned long long)frame_data.retire_prior_to);
BIO_puts(bio, " Connection id: ");
put_conn_id(bio, &frame_data.conn_id);
BIO_puts(bio, "\n Stateless Reset Token: ");
put_data(bio, frame_data.stateless_reset_token, 16);
BIO_puts(bio, "\n");
return 1;
}
static int frame_retire_conn_id(BIO *bio, PACKET *pkt)
{
uint64_t seq_num;
if (!ossl_quic_wire_decode_frame_retire_conn_id(pkt, &seq_num))
return 0;
BIO_printf(bio, " Sequence Number: %llu\n", (unsigned long long)seq_num);
return 1;
}
static int frame_path_challenge(BIO *bio, PACKET *pkt)
{
uint64_t data = 0;
if (!ossl_quic_wire_decode_frame_path_challenge(pkt, &data))
return 0;
BIO_printf(bio, " Data: %016llx\n", (unsigned long long)data);
return 1;
}
static int frame_path_response(BIO *bio, PACKET *pkt)
{
uint64_t data = 0;
if (!ossl_quic_wire_decode_frame_path_response(pkt, &data))
return 0;
BIO_printf(bio, " Data: %016llx\n", (unsigned long long)data);
return 1;
}
static int frame_conn_closed(BIO *bio, PACKET *pkt)
{
OSSL_QUIC_FRAME_CONN_CLOSE frame_data;
if (!ossl_quic_wire_decode_frame_conn_close(pkt, &frame_data))
return 0;
BIO_printf(bio, " Error Code: %llu\n",
(unsigned long long)frame_data.error_code);
BIO_puts(bio, " Reason: ");
put_str(bio, frame_data.reason, frame_data.reason_len);
BIO_puts(bio, "\n");
return 1;
}
static int trace_frame_data(BIO *bio, PACKET *pkt)
{
uint64_t frame_type;
if (!ossl_quic_wire_peek_frame_header(pkt, &frame_type, NULL))
return 0;
switch (frame_type) {
case OSSL_QUIC_FRAME_TYPE_PING:
BIO_puts(bio, "Ping\n");
if (!ossl_quic_wire_decode_frame_ping(pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_PADDING:
BIO_puts(bio, "Padding\n");
ossl_quic_wire_decode_padding(pkt);
break;
case OSSL_QUIC_FRAME_TYPE_ACK_WITHOUT_ECN:
case OSSL_QUIC_FRAME_TYPE_ACK_WITH_ECN:
BIO_puts(bio, "Ack ");
if (frame_type == OSSL_QUIC_FRAME_TYPE_ACK_WITH_ECN)
BIO_puts(bio, " (with ECN)\n");
else
BIO_puts(bio, " (without ECN)\n");
if (!frame_ack(bio, pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_RESET_STREAM:
BIO_puts(bio, "Reset stream\n");
if (!frame_reset_stream(bio, pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_STOP_SENDING:
BIO_puts(bio, "Stop sending\n");
if (!frame_stop_sending(bio, pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_CRYPTO:
BIO_puts(bio, "Crypto\n");
if (!frame_crypto(bio, pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_NEW_TOKEN:
BIO_puts(bio, "New token\n");
if (!frame_new_token(bio, pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_STREAM:
case OSSL_QUIC_FRAME_TYPE_STREAM_FIN:
case OSSL_QUIC_FRAME_TYPE_STREAM_LEN:
case OSSL_QUIC_FRAME_TYPE_STREAM_LEN_FIN:
case OSSL_QUIC_FRAME_TYPE_STREAM_OFF:
case OSSL_QUIC_FRAME_TYPE_STREAM_OFF_FIN:
case OSSL_QUIC_FRAME_TYPE_STREAM_OFF_LEN:
case OSSL_QUIC_FRAME_TYPE_STREAM_OFF_LEN_FIN:
/* frame_stream() prints the frame type string */
if (!frame_stream(bio, pkt, frame_type))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_MAX_DATA:
BIO_puts(bio, "Max data\n");
if (!frame_max_data(bio, pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_MAX_STREAM_DATA:
BIO_puts(bio, "Max stream data\n");
if (!frame_max_stream_data(bio, pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_BIDI:
case OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_UNI:
BIO_puts(bio, "Max streams ");
if (frame_type == OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_BIDI)
BIO_puts(bio, " (Bidi)\n");
else
BIO_puts(bio, " (Uni)\n");
if (!frame_max_streams(bio, pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_DATA_BLOCKED:
BIO_puts(bio, "Data blocked\n");
if (!frame_data_blocked(bio, pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_STREAM_DATA_BLOCKED:
BIO_puts(bio, "Stream data blocked\n");
if (!frame_stream_data_blocked(bio, pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_STREAMS_BLOCKED_BIDI:
case OSSL_QUIC_FRAME_TYPE_STREAMS_BLOCKED_UNI:
BIO_puts(bio, "Streams blocked");
if (frame_type == OSSL_QUIC_FRAME_TYPE_STREAMS_BLOCKED_BIDI)
BIO_puts(bio, " (Bidi)\n");
else
BIO_puts(bio, " (Uni)\n");
if (!frame_streams_blocked(bio, pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID:
BIO_puts(bio, "New conn id\n");
if (!frame_new_conn_id(bio, pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID:
BIO_puts(bio, "Retire conn id\n");
if (!frame_retire_conn_id(bio, pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_PATH_CHALLENGE:
BIO_puts(bio, "Path challenge\n");
if (!frame_path_challenge(bio, pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_PATH_RESPONSE:
BIO_puts(bio, "Path response\n");
if (!frame_path_response(bio, pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_CONN_CLOSE_APP:
case OSSL_QUIC_FRAME_TYPE_CONN_CLOSE_TRANSPORT:
BIO_puts(bio, "Connection close");
if (frame_type == OSSL_QUIC_FRAME_TYPE_CONN_CLOSE_APP)
BIO_puts(bio, " (app)\n");
else
BIO_puts(bio, " (transport)\n");
if (!frame_conn_closed(bio, pkt))
return 0;
break;
case OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE:
BIO_puts(bio, "Handshake done\n");
if (!ossl_quic_wire_decode_frame_handshake_done(pkt))
return 0;
break;
default:
return 0;
}
if (PACKET_remaining(pkt) != 0)
BIO_puts(bio, " <unexpected trailing frame data skipped>\n");
return 1;
}
int ossl_quic_trace(int write_p, int version, int content_type,
const void *buf, size_t msglen, SSL *ssl, void *arg)
{
BIO *bio = arg;
PACKET pkt;
switch (content_type) {
case SSL3_RT_QUIC_DATAGRAM:
BIO_puts(bio, write_p ? "Sent" : "Received");
/*
* Unfortunately there is no way of receiving auxiliary information
* about the datagram through the msg_callback API such as the peer
* address
*/
BIO_printf(bio, " Datagram\n Length: %zu\n", msglen);
break;
case SSL3_RT_QUIC_PACKET:
{
QUIC_PKT_HDR hdr;
size_t i;
if (!PACKET_buf_init(&pkt, buf, msglen))
return 0;
/* Decode the packet header */
/*
* TODO(QUIC): We need to query the short connection id len here,
* e.g. via some API SSL_get_short_conn_id_len()
*/
if (ossl_quic_wire_decode_pkt_hdr(&pkt, 0, 0, 1, &hdr, NULL) != 1)
return 0;
BIO_puts(bio, write_p ? "Sent" : "Received");
BIO_puts(bio, " Packet\n");
BIO_printf(bio, " Packet Type: %s\n", packet_type(hdr.type));
if (hdr.type != QUIC_PKT_TYPE_1RTT)
BIO_printf(bio, " Version: 0x%08lx\n",
(unsigned long)hdr.version);
BIO_puts(bio, " Destination Conn Id: ");
put_conn_id(bio, &hdr.dst_conn_id);
BIO_puts(bio, "\n");
if (hdr.type != QUIC_PKT_TYPE_1RTT) {
BIO_puts(bio, " Source Conn Id: ");
put_conn_id(bio, &hdr.src_conn_id);
BIO_puts(bio, "\n");
}
BIO_printf(bio, " Payload length: %zu\n", hdr.len);
if (hdr.type == QUIC_PKT_TYPE_INITIAL) {
BIO_puts(bio, " Token: ");
put_token(bio, hdr.token, hdr.token_len);
BIO_puts(bio, "\n");
}
if (hdr.type != QUIC_PKT_TYPE_VERSION_NEG
&& hdr.type != QUIC_PKT_TYPE_RETRY) {
BIO_puts(bio, " Packet Number: 0x");
/* Will always be at least 1 byte */
for (i = 0; i < hdr.pn_len; i++)
BIO_printf(bio, "%02x", hdr.pn[i]);
BIO_puts(bio, "\n");
}
break;
}
case SSL3_RT_QUIC_FRAME_PADDING:
case SSL3_RT_QUIC_FRAME_FULL:
case SSL3_RT_QUIC_FRAME_HEADER:
{
BIO_puts(bio, write_p ? "Sent" : "Received");
BIO_puts(bio, " Frame: ");
if (!PACKET_buf_init(&pkt, buf, msglen))
return 0;
if (!trace_frame_data(bio, &pkt)) {
BIO_puts(bio, " <error processing frame data>\n");
return 0;
}
}
break;
default:
/* Unrecognised content_type. We defer to SSL_trace */
return 0;
}
return 1;
}
| 18,199 | 27.393136 | 81 | c |
openssl | openssl-master/ssl/quic/quic_tserver.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/quic_tserver.h"
#include "internal/quic_channel.h"
#include "internal/quic_statm.h"
#include "internal/common.h"
#include "internal/time.h"
/*
* QUIC Test Server Module
* =======================
*/
struct quic_tserver_st {
QUIC_TSERVER_ARGS args;
/*
* The QUIC channel providing the core QUIC connection implementation.
*/
QUIC_CHANNEL *ch;
/* The mutex we give to the QUIC channel. */
CRYPTO_MUTEX *mutex;
/* SSL_CTX for creating the underlying TLS connection */
SSL_CTX *ctx;
/* SSL for the underlying TLS connection */
SSL *tls;
/* The current peer L4 address. AF_UNSPEC if we do not have a peer yet. */
BIO_ADDR cur_peer_addr;
/* Are we connected to a peer? */
unsigned int connected : 1;
};
static int alpn_select_cb(SSL *ssl, const unsigned char **out,
unsigned char *outlen, const unsigned char *in,
unsigned int inlen, void *arg)
{
QUIC_TSERVER *srv = arg;
static const unsigned char alpndeflt[] = {
8, 'o', 's', 's', 'l', 't', 'e', 's', 't'
};
static const unsigned char *alpn;
size_t alpnlen;
if (srv->args.alpn == NULL) {
alpn = alpndeflt;
alpnlen = sizeof(alpn);
} else {
alpn = srv->args.alpn;
alpnlen = srv->args.alpnlen;
}
if (SSL_select_next_proto((unsigned char **)out, outlen, alpn, alpnlen,
in, inlen) != OPENSSL_NPN_NEGOTIATED)
return SSL_TLSEXT_ERR_ALERT_FATAL;
return SSL_TLSEXT_ERR_OK;
}
QUIC_TSERVER *ossl_quic_tserver_new(const QUIC_TSERVER_ARGS *args,
const char *certfile, const char *keyfile)
{
QUIC_TSERVER *srv = NULL;
QUIC_CHANNEL_ARGS ch_args = {0};
if (args->net_rbio == NULL || args->net_wbio == NULL)
goto err;
if ((srv = OPENSSL_zalloc(sizeof(*srv))) == NULL)
goto err;
srv->args = *args;
#if defined(OPENSSL_THREADS)
if ((srv->mutex = ossl_crypto_mutex_new()) == NULL)
goto err;
#endif
srv->ctx = SSL_CTX_new_ex(srv->args.libctx, srv->args.propq, TLS_method());
if (srv->ctx == NULL)
goto err;
if (SSL_CTX_use_certificate_file(srv->ctx, certfile, SSL_FILETYPE_PEM) <= 0)
goto err;
if (SSL_CTX_use_PrivateKey_file(srv->ctx, keyfile, SSL_FILETYPE_PEM) <= 0)
goto err;
SSL_CTX_set_alpn_select_cb(srv->ctx, alpn_select_cb, srv);
srv->tls = SSL_new(srv->ctx);
if (srv->tls == NULL)
goto err;
ch_args.libctx = srv->args.libctx;
ch_args.propq = srv->args.propq;
ch_args.tls = srv->tls;
ch_args.mutex = srv->mutex;
ch_args.is_server = 1;
ch_args.now_cb = srv->args.now_cb;
ch_args.now_cb_arg = srv->args.now_cb_arg;
if ((srv->ch = ossl_quic_channel_new(&ch_args)) == NULL)
goto err;
if (!ossl_quic_channel_set_net_rbio(srv->ch, srv->args.net_rbio)
|| !ossl_quic_channel_set_net_wbio(srv->ch, srv->args.net_wbio))
goto err;
return srv;
err:
if (srv != NULL) {
ossl_quic_channel_free(srv->ch);
#if defined(OPENSSL_THREADS)
ossl_crypto_mutex_free(&srv->mutex);
#endif
}
OPENSSL_free(srv);
return NULL;
}
void ossl_quic_tserver_free(QUIC_TSERVER *srv)
{
if (srv == NULL)
return;
ossl_quic_channel_free(srv->ch);
BIO_free(srv->args.net_rbio);
BIO_free(srv->args.net_wbio);
SSL_free(srv->tls);
SSL_CTX_free(srv->ctx);
#if defined(OPENSSL_THREADS)
ossl_crypto_mutex_free(&srv->mutex);
#endif
OPENSSL_free(srv);
}
/* Set mutator callbacks for test framework support */
int ossl_quic_tserver_set_plain_packet_mutator(QUIC_TSERVER *srv,
ossl_mutate_packet_cb mutatecb,
ossl_finish_mutate_cb finishmutatecb,
void *mutatearg)
{
return ossl_quic_channel_set_mutator(srv->ch, mutatecb, finishmutatecb,
mutatearg);
}
int ossl_quic_tserver_set_handshake_mutator(QUIC_TSERVER *srv,
ossl_statem_mutate_handshake_cb mutate_handshake_cb,
ossl_statem_finish_mutate_handshake_cb finish_mutate_handshake_cb,
void *mutatearg)
{
return ossl_statem_set_mutator(ossl_quic_channel_get0_ssl(srv->ch),
mutate_handshake_cb,
finish_mutate_handshake_cb,
mutatearg);
}
int ossl_quic_tserver_tick(QUIC_TSERVER *srv)
{
ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(srv->ch), 0);
if (ossl_quic_channel_is_active(srv->ch))
srv->connected = 1;
return 1;
}
int ossl_quic_tserver_is_connected(QUIC_TSERVER *srv)
{
return ossl_quic_channel_is_active(srv->ch);
}
/* Returns 1 if the server is in any terminating or terminated state */
int ossl_quic_tserver_is_term_any(const QUIC_TSERVER *srv)
{
return ossl_quic_channel_is_term_any(srv->ch);
}
const QUIC_TERMINATE_CAUSE *
ossl_quic_tserver_get_terminate_cause(const QUIC_TSERVER *srv)
{
return ossl_quic_channel_get_terminate_cause(srv->ch);
}
/* Returns 1 if the server is in a terminated state */
int ossl_quic_tserver_is_terminated(const QUIC_TSERVER *srv)
{
return ossl_quic_channel_is_terminated(srv->ch);
}
int ossl_quic_tserver_is_handshake_confirmed(const QUIC_TSERVER *srv)
{
return ossl_quic_channel_is_handshake_confirmed(srv->ch);
}
int ossl_quic_tserver_read(QUIC_TSERVER *srv,
uint64_t stream_id,
unsigned char *buf,
size_t buf_len,
size_t *bytes_read)
{
int is_fin = 0;
QUIC_STREAM *qs;
if (!ossl_quic_channel_is_active(srv->ch))
return 0;
qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(srv->ch),
stream_id);
if (qs == NULL) {
int is_client_init
= ((stream_id & QUIC_STREAM_INITIATOR_MASK)
== QUIC_STREAM_INITIATOR_CLIENT);
/*
* A client-initiated stream might spontaneously come into existence, so
* allow trying to read on a client-initiated stream before it exists.
* Otherwise, fail.
*/
if (!is_client_init)
return 0;
*bytes_read = 0;
return 1;
}
if (qs->recv_state == QUIC_RSTREAM_STATE_DATA_READ
|| !ossl_quic_stream_has_recv_buffer(qs))
return 0;
if (!ossl_quic_rstream_read(qs->rstream, buf, buf_len,
bytes_read, &is_fin))
return 0;
if (*bytes_read > 0) {
/*
* We have read at least one byte from the stream. Inform stream-level
* RXFC of the retirement of controlled bytes. Update the active stream
* status (the RXFC may now want to emit a frame granting more credit to
* the peer).
*/
OSSL_RTT_INFO rtt_info;
ossl_statm_get_rtt_info(ossl_quic_channel_get_statm(srv->ch), &rtt_info);
if (!ossl_quic_rxfc_on_retire(&qs->rxfc, *bytes_read,
rtt_info.smoothed_rtt))
return 0;
}
if (is_fin)
ossl_quic_stream_map_notify_totally_read(ossl_quic_channel_get_qsm(srv->ch),
qs);
if (*bytes_read > 0)
ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(srv->ch), qs);
return 1;
}
int ossl_quic_tserver_has_read_ended(QUIC_TSERVER *srv, uint64_t stream_id)
{
QUIC_STREAM *qs;
unsigned char buf[1];
size_t bytes_read = 0;
int is_fin = 0;
qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(srv->ch),
stream_id);
if (qs == NULL)
return 0;
if (qs->recv_state == QUIC_RSTREAM_STATE_DATA_READ)
return 1;
if (!ossl_quic_stream_has_recv_buffer(qs))
return 0;
/*
* If we do not have the DATA_READ, it is possible we should still return 1
* if there is a lone FIN (but no more data) remaining to be retired from
* the RSTREAM, for example because ossl_quic_tserver_read() has not been
* called since the FIN was received.
*/
if (!ossl_quic_rstream_peek(qs->rstream, buf, sizeof(buf),
&bytes_read, &is_fin))
return 0;
if (is_fin && bytes_read == 0) {
/* If we have a FIN awaiting retirement and no data before it... */
/* Let RSTREAM know we've consumed this FIN. */
ossl_quic_rstream_read(qs->rstream, buf, sizeof(buf),
&bytes_read, &is_fin); /* best effort */
assert(is_fin && bytes_read == 0);
assert(qs->recv_state == QUIC_RSTREAM_STATE_DATA_RECVD);
ossl_quic_stream_map_notify_totally_read(ossl_quic_channel_get_qsm(srv->ch),
qs);
ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(srv->ch), qs);
return 1;
}
return 0;
}
int ossl_quic_tserver_write(QUIC_TSERVER *srv,
uint64_t stream_id,
const unsigned char *buf,
size_t buf_len,
size_t *bytes_written)
{
QUIC_STREAM *qs;
if (!ossl_quic_channel_is_active(srv->ch))
return 0;
qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(srv->ch),
stream_id);
if (qs == NULL || !ossl_quic_stream_has_send_buffer(qs))
return 0;
if (!ossl_quic_sstream_append(qs->sstream,
buf, buf_len, bytes_written))
return 0;
if (*bytes_written > 0)
/*
* We have appended at least one byte to the stream. Potentially mark
* the stream as active, depending on FC.
*/
ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(srv->ch), qs);
/* Try and send. */
ossl_quic_tserver_tick(srv);
return 1;
}
int ossl_quic_tserver_conclude(QUIC_TSERVER *srv, uint64_t stream_id)
{
QUIC_STREAM *qs;
if (!ossl_quic_channel_is_active(srv->ch))
return 0;
qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(srv->ch),
stream_id);
if (qs == NULL || !ossl_quic_stream_has_send_buffer(qs))
return 0;
if (!ossl_quic_sstream_get_final_size(qs->sstream, NULL)) {
ossl_quic_sstream_fin(qs->sstream);
ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(srv->ch), qs);
}
ossl_quic_tserver_tick(srv);
return 1;
}
int ossl_quic_tserver_stream_new(QUIC_TSERVER *srv,
int is_uni,
uint64_t *stream_id)
{
QUIC_STREAM *qs;
if (!ossl_quic_channel_is_active(srv->ch))
return 0;
if ((qs = ossl_quic_channel_new_stream_local(srv->ch, is_uni)) == NULL)
return 0;
*stream_id = qs->id;
return 1;
}
BIO *ossl_quic_tserver_get0_rbio(QUIC_TSERVER *srv)
{
return srv->args.net_rbio;
}
int ossl_quic_tserver_stream_has_peer_stop_sending(QUIC_TSERVER *srv,
uint64_t stream_id,
uint64_t *app_error_code)
{
QUIC_STREAM *qs;
qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(srv->ch),
stream_id);
if (qs == NULL)
return 0;
if (qs->peer_stop_sending && app_error_code != NULL)
*app_error_code = qs->peer_stop_sending_aec;
return qs->peer_stop_sending;
}
int ossl_quic_tserver_stream_has_peer_reset_stream(QUIC_TSERVER *srv,
uint64_t stream_id,
uint64_t *app_error_code)
{
QUIC_STREAM *qs;
qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(srv->ch),
stream_id);
if (qs == NULL)
return 0;
if (ossl_quic_stream_recv_is_reset(qs) && app_error_code != NULL)
*app_error_code = qs->peer_reset_stream_aec;
return ossl_quic_stream_recv_is_reset(qs);
}
int ossl_quic_tserver_set_new_local_cid(QUIC_TSERVER *srv,
const QUIC_CONN_ID *conn_id)
{
/* Replace existing local connection ID in the QUIC_CHANNEL */
return ossl_quic_channel_replace_local_cid(srv->ch, conn_id);
}
uint64_t ossl_quic_tserver_pop_incoming_stream(QUIC_TSERVER *srv)
{
QUIC_STREAM_MAP *qsm = ossl_quic_channel_get_qsm(srv->ch);
QUIC_STREAM *qs = ossl_quic_stream_map_peek_accept_queue(qsm);
if (qs == NULL)
return UINT64_MAX;
ossl_quic_stream_map_remove_from_accept_queue(qsm, qs, ossl_time_zero());
return qs->id;
}
int ossl_quic_tserver_is_stream_totally_acked(QUIC_TSERVER *srv,
uint64_t stream_id)
{
QUIC_STREAM *qs;
qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(srv->ch),
stream_id);
if (qs == NULL)
return 1;
return ossl_quic_sstream_is_totally_acked(qs->sstream);
}
int ossl_quic_tserver_get_net_read_desired(QUIC_TSERVER *srv)
{
return ossl_quic_reactor_net_read_desired(
ossl_quic_channel_get_reactor(srv->ch));
}
int ossl_quic_tserver_get_net_write_desired(QUIC_TSERVER *srv)
{
return ossl_quic_reactor_net_write_desired(
ossl_quic_channel_get_reactor(srv->ch));
}
OSSL_TIME ossl_quic_tserver_get_deadline(QUIC_TSERVER *srv)
{
return ossl_quic_reactor_get_tick_deadline(
ossl_quic_channel_get_reactor(srv->ch));
}
int ossl_quic_tserver_shutdown(QUIC_TSERVER *srv)
{
ossl_quic_channel_local_close(srv->ch, 0);
/* TODO(QUIC): !SSL_SHUTDOWN_FLAG_NO_STREAM_FLUSH */
if (ossl_quic_channel_is_terminated(srv->ch))
return 1;
ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(srv->ch), 0);
return ossl_quic_channel_is_terminated(srv->ch);
}
int ossl_quic_tserver_ping(QUIC_TSERVER *srv)
{
if (ossl_quic_channel_is_terminated(srv->ch))
return 0;
if (!ossl_quic_channel_ping(srv->ch))
return 0;
ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(srv->ch), 0);
return 1;
}
| 15,028 | 28.819444 | 110 | c |
openssl | openssl-master/ssl/quic/quic_txpim.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/quic_txpim.h"
#include <stdlib.h>
typedef struct quic_txpim_pkt_ex_st QUIC_TXPIM_PKT_EX;
struct quic_txpim_pkt_ex_st {
QUIC_TXPIM_PKT public;
QUIC_TXPIM_PKT_EX *prev, *next;
QUIC_TXPIM_CHUNK *chunks;
size_t num_chunks, alloc_chunks;
unsigned int chunks_need_sort : 1;
};
typedef struct quic_txpim_pkt_ex_list {
QUIC_TXPIM_PKT_EX *head, *tail;
} QUIC_TXPIM_PKT_EX_LIST;
struct quic_txpim_st {
QUIC_TXPIM_PKT_EX_LIST free_list;
size_t in_use;
};
#define MAX_ALLOC_CHUNKS 512
QUIC_TXPIM *ossl_quic_txpim_new(void)
{
QUIC_TXPIM *txpim = OPENSSL_zalloc(sizeof(*txpim));
if (txpim == NULL)
return NULL;
return txpim;
}
static void free_list(QUIC_TXPIM_PKT_EX_LIST *l)
{
QUIC_TXPIM_PKT_EX *n, *nnext;
for (n = l->head; n != NULL; n = nnext) {
nnext = n->next;
OPENSSL_free(n->chunks);
OPENSSL_free(n);
}
l->head = l->tail = NULL;
}
void ossl_quic_txpim_free(QUIC_TXPIM *txpim)
{
if (txpim == NULL)
return;
assert(txpim->in_use == 0);
free_list(&txpim->free_list);
OPENSSL_free(txpim);
}
static void list_remove(QUIC_TXPIM_PKT_EX_LIST *l, QUIC_TXPIM_PKT_EX *n)
{
if (l->head == n)
l->head = n->next;
if (l->tail == n)
l->tail = n->prev;
if (n->prev != NULL)
n->prev->next = n->next;
if (n->next != NULL)
n->next->prev = n->prev;
n->prev = n->next = NULL;
}
static void list_insert_tail(QUIC_TXPIM_PKT_EX_LIST *l, QUIC_TXPIM_PKT_EX *n)
{
n->prev = l->tail;
n->next = NULL;
l->tail = n;
if (n->prev != NULL)
n->prev->next = n;
if (l->head == NULL)
l->head = n;
}
static QUIC_TXPIM_PKT_EX *txpim_get_free(QUIC_TXPIM *txpim)
{
QUIC_TXPIM_PKT_EX *ex = txpim->free_list.head;
if (ex != NULL)
return ex;
ex = OPENSSL_zalloc(sizeof(*ex));
if (ex == NULL)
return NULL;
list_insert_tail(&txpim->free_list, ex);
return ex;
}
static void txpim_clear(QUIC_TXPIM_PKT_EX *ex)
{
memset(&ex->public.ackm_pkt, 0, sizeof(ex->public.ackm_pkt));
ossl_quic_txpim_pkt_clear_chunks(&ex->public);
ex->public.retx_head = NULL;
ex->public.fifd = NULL;
ex->public.had_handshake_done_frame = 0;
ex->public.had_max_data_frame = 0;
ex->public.had_max_streams_bidi_frame = 0;
ex->public.had_max_streams_uni_frame = 0;
ex->public.had_ack_frame = 0;
}
QUIC_TXPIM_PKT *ossl_quic_txpim_pkt_alloc(QUIC_TXPIM *txpim)
{
QUIC_TXPIM_PKT_EX *ex = txpim_get_free(txpim);
if (ex == NULL)
return NULL;
txpim_clear(ex);
list_remove(&txpim->free_list, ex);
++txpim->in_use;
return &ex->public;
}
void ossl_quic_txpim_pkt_release(QUIC_TXPIM *txpim, QUIC_TXPIM_PKT *fpkt)
{
QUIC_TXPIM_PKT_EX *ex = (QUIC_TXPIM_PKT_EX *)fpkt;
assert(txpim->in_use > 0);
--txpim->in_use;
list_insert_tail(&txpim->free_list, ex);
}
void ossl_quic_txpim_pkt_add_cfq_item(QUIC_TXPIM_PKT *fpkt,
QUIC_CFQ_ITEM *item)
{
item->pkt_next = fpkt->retx_head;
item->pkt_prev = NULL;
fpkt->retx_head = item;
}
void ossl_quic_txpim_pkt_clear_chunks(QUIC_TXPIM_PKT *fpkt)
{
QUIC_TXPIM_PKT_EX *ex = (QUIC_TXPIM_PKT_EX *)fpkt;
ex->num_chunks = 0;
}
int ossl_quic_txpim_pkt_append_chunk(QUIC_TXPIM_PKT *fpkt,
const QUIC_TXPIM_CHUNK *chunk)
{
QUIC_TXPIM_PKT_EX *ex = (QUIC_TXPIM_PKT_EX *)fpkt;
QUIC_TXPIM_CHUNK *new_chunk;
size_t new_alloc_chunks = ex->alloc_chunks;
if (ex->num_chunks == ex->alloc_chunks) {
new_alloc_chunks = (ex->alloc_chunks == 0) ? 4 : ex->alloc_chunks * 8 / 5;
if (new_alloc_chunks > MAX_ALLOC_CHUNKS)
new_alloc_chunks = MAX_ALLOC_CHUNKS;
if (ex->num_chunks == new_alloc_chunks)
return 0;
new_chunk = OPENSSL_realloc(ex->chunks,
new_alloc_chunks * sizeof(QUIC_TXPIM_CHUNK));
if (new_chunk == NULL)
return 0;
ex->chunks = new_chunk;
ex->alloc_chunks = new_alloc_chunks;
}
ex->chunks[ex->num_chunks++] = *chunk;
ex->chunks_need_sort = 1;
return 1;
}
static int compare(const void *a, const void *b)
{
const QUIC_TXPIM_CHUNK *ac = a, *bc = b;
if (ac->stream_id < bc->stream_id)
return -1;
else if (ac->stream_id > bc->stream_id)
return 1;
if (ac->start < bc->start)
return -1;
else if (ac->start > bc->start)
return 1;
return 0;
}
const QUIC_TXPIM_CHUNK *ossl_quic_txpim_pkt_get_chunks(const QUIC_TXPIM_PKT *fpkt)
{
QUIC_TXPIM_PKT_EX *ex = (QUIC_TXPIM_PKT_EX *)fpkt;
if (ex->chunks_need_sort) {
/*
* List of chunks will generally be very small so there is no issue
* simply sorting here.
*/
qsort(ex->chunks, ex->num_chunks, sizeof(QUIC_TXPIM_CHUNK), compare);
ex->chunks_need_sort = 0;
}
return ex->chunks;
}
size_t ossl_quic_txpim_pkt_get_num_chunks(const QUIC_TXPIM_PKT *fpkt)
{
QUIC_TXPIM_PKT_EX *ex = (QUIC_TXPIM_PKT_EX *)fpkt;
return ex->num_chunks;
}
size_t ossl_quic_txpim_get_in_use(const QUIC_TXPIM *txpim)
{
return txpim->in_use;
}
| 5,772 | 24.209607 | 82 | c |
openssl | openssl-master/ssl/quic/uint_set.c | /*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/uint_set.h"
#include "internal/common.h"
#include <assert.h>
/*
* uint64_t Integer Sets
* =====================
*
* This data structure supports the following operations:
*
* Insert Range: Adds an inclusive range of integers [start, end]
* to the set. Equivalent to Insert for each number
* in the range.
*
* Remove Range: Removes an inclusive range of integers [start, end]
* from the set. Not all of the range need already be in
* the set, but any part of the range in the set is removed.
*
* Query: Is an integer in the data structure?
*
* The data structure can be iterated.
*
* For greater efficiency in tracking large numbers of contiguous integers, we
* track integer ranges rather than individual integers. The data structure
* manages a list of integer ranges [[start, end]...]. Internally this is
* implemented as a doubly linked sorted list of range structures, which are
* automatically split and merged as necessary.
*
* This data structure requires O(n) traversal of the list for insertion,
* removal and query when we are not adding/removing ranges which are near the
* beginning or end of the set of ranges. For the applications for which this
* data structure is used (e.g. QUIC PN tracking for ACK generation), it is
* expected that the number of integer ranges needed at any given time will
* generally be small and that most operations will be close to the beginning or
* end of the range.
*
* Invariant: The data structure is always sorted in ascending order by value.
*
* Invariant: No two adjacent ranges ever 'border' one another (have no
* numerical gap between them) as the data structure always ensures
* such ranges are merged.
*
* Invariant: No two ranges ever overlap.
*
* Invariant: No range [a, b] ever has a > b.
*
* Invariant: Since ranges are represented using inclusive bounds, no range
* item inside the data structure can represent a span of zero
* integers.
*/
void ossl_uint_set_init(UINT_SET *s)
{
ossl_list_uint_set_init(s);
}
void ossl_uint_set_destroy(UINT_SET *s)
{
UINT_SET_ITEM *x, *xnext;
for (x = ossl_list_uint_set_head(s); x != NULL; x = xnext) {
xnext = ossl_list_uint_set_next(x);
OPENSSL_free(x);
}
}
/* Possible merge of x, prev(x) */
static void uint_set_merge_adjacent(UINT_SET *s, UINT_SET_ITEM *x)
{
UINT_SET_ITEM *xprev = ossl_list_uint_set_prev(x);
if (xprev == NULL)
return;
if (x->range.start - 1 != xprev->range.end)
return;
x->range.start = xprev->range.start;
ossl_list_uint_set_remove(s, xprev);
OPENSSL_free(xprev);
}
static uint64_t u64_min(uint64_t x, uint64_t y)
{
return x < y ? x : y;
}
static uint64_t u64_max(uint64_t x, uint64_t y)
{
return x > y ? x : y;
}
/*
* Returns 1 if there exists an integer x which falls within both ranges a and
* b.
*/
static int uint_range_overlaps(const UINT_RANGE *a,
const UINT_RANGE *b)
{
return u64_min(a->end, b->end)
>= u64_max(a->start, b->start);
}
static UINT_SET_ITEM *create_set_item(uint64_t start, uint64_t end)
{
UINT_SET_ITEM *x = OPENSSL_malloc(sizeof(UINT_SET_ITEM));
ossl_list_uint_set_init_elem(x);
if (x != NULL) {
x->range.start = start;
x->range.end = end;
}
return x;
}
int ossl_uint_set_insert(UINT_SET *s, const UINT_RANGE *range)
{
UINT_SET_ITEM *x, *xnext, *z, *zprev, *f;
uint64_t start = range->start, end = range->end;
if (!ossl_assert(start <= end))
return 0;
if (ossl_list_uint_set_is_empty(s)) {
/* Nothing in the set yet, so just add this range. */
x = create_set_item(start, end);
if (x == NULL)
return 0;
ossl_list_uint_set_insert_head(s, x);
return 1;
}
z = ossl_list_uint_set_tail(s);
if (start > z->range.end) {
/*
* Range is after the latest range in the set, so append.
*
* Note: The case where the range is before the earliest range in the
* set is handled as a degenerate case of the final case below. See
* optimization note (*) below.
*/
if (z->range.end + 1 == start) {
z->range.end = end;
return 1;
}
x = create_set_item(start, end);
if (x == NULL)
return 0;
ossl_list_uint_set_insert_tail(s, x);
return 1;
}
f = ossl_list_uint_set_head(s);
if (start <= f->range.start && end >= z->range.end) {
/*
* New range dwarfs all ranges in our set.
*
* Free everything except the first range in the set, which we scavenge
* and reuse.
*/
x = ossl_list_uint_set_head(s);
x->range.start = start;
x->range.end = end;
for (x = ossl_list_uint_set_next(x); x != NULL; x = xnext) {
xnext = ossl_list_uint_set_next(x);
ossl_list_uint_set_remove(s, x);
}
return 1;
}
/*
* Walk backwards since we will most often be inserting at the end. As an
* optimization, test the head node first and skip iterating over the
* entire list if we are inserting at the start. The assumption is that
* insertion at the start and end of the space will be the most common
* operations. (*)
*/
z = end < f->range.start ? f : z;
for (; z != NULL; z = zprev) {
zprev = ossl_list_uint_set_prev(z);
/* An existing range dwarfs our new range (optimisation). */
if (z->range.start <= start && z->range.end >= end)
return 1;
if (uint_range_overlaps(&z->range, range)) {
/*
* Our new range overlaps an existing range, or possibly several
* existing ranges.
*/
UINT_SET_ITEM *ovend = z;
ovend->range.end = u64_max(end, z->range.end);
/* Get earliest overlapping range. */
while (zprev != NULL && uint_range_overlaps(&zprev->range, range)) {
z = zprev;
zprev = ossl_list_uint_set_prev(z);
}
ovend->range.start = u64_min(start, z->range.start);
/* Replace sequence of nodes z..ovend with updated ovend only. */
while (z != ovend) {
z = ossl_list_uint_set_next(x = z);
ossl_list_uint_set_remove(s, x);
OPENSSL_free(x);
}
break;
} else if (end < z->range.start
&& (zprev == NULL || start > zprev->range.end)) {
if (z->range.start == end + 1) {
/* We can extend the following range backwards. */
z->range.start = start;
/*
* If this closes a gap we now need to merge
* consecutive nodes.
*/
uint_set_merge_adjacent(s, z);
} else if (zprev != NULL && zprev->range.end + 1 == start) {
/* We can extend the preceding range forwards. */
zprev->range.end = end;
/*
* If this closes a gap we now need to merge
* consecutive nodes.
*/
uint_set_merge_adjacent(s, z);
} else {
/*
* The new interval is between intervals without overlapping or
* touching them, so insert between, preserving sort.
*/
x = create_set_item(start, end);
if (x == NULL)
return 0;
ossl_list_uint_set_insert_before(s, z, x);
}
break;
}
}
return 1;
}
int ossl_uint_set_remove(UINT_SET *s, const UINT_RANGE *range)
{
UINT_SET_ITEM *z, *zprev, *y;
uint64_t start = range->start, end = range->end;
if (!ossl_assert(start <= end))
return 0;
/* Walk backwards since we will most often be removing at the end. */
for (z = ossl_list_uint_set_tail(s); z != NULL; z = zprev) {
zprev = ossl_list_uint_set_prev(z);
if (start > z->range.end)
/* No overlapping ranges can exist beyond this point, so stop. */
break;
if (start <= z->range.start && end >= z->range.end) {
/*
* The range being removed dwarfs this range, so it should be
* removed.
*/
ossl_list_uint_set_remove(s, z);
OPENSSL_free(z);
} else if (start <= z->range.start) {
/*
* The range being removed includes start of this range, but does
* not cover the entire range (as this would be caught by the case
* above). Shorten the range.
*/
assert(end < z->range.end);
z->range.start = end + 1;
} else if (end >= z->range.end) {
/*
* The range being removed includes the end of this range, but does
* not cover the entire range (as this would be caught by the case
* above). Shorten the range. We can also stop iterating.
*/
assert(start > z->range.start);
assert(start > 0);
z->range.end = start - 1;
break;
} else if (start > z->range.start && end < z->range.end) {
/*
* The range being removed falls entirely in this range, so cut it
* into two. Cases where a zero-length range would be created are
* handled by the above cases.
*/
y = create_set_item(end + 1, z->range.end);
ossl_list_uint_set_insert_after(s, z, y);
break;
} else {
/* Assert no partial overlap; all cases should be covered above. */
assert(!uint_range_overlaps(&z->range, range));
}
}
return 1;
}
int ossl_uint_set_query(const UINT_SET *s, uint64_t v)
{
UINT_SET_ITEM *x;
if (ossl_list_uint_set_is_empty(s))
return 0;
for (x = ossl_list_uint_set_tail(s); x != NULL; x = ossl_list_uint_set_prev(x))
if (x->range.start <= v && x->range.end >= v)
return 1;
else if (x->range.end < v)
return 0;
return 0;
}
| 10,806 | 31.649547 | 83 | c |
openssl | openssl-master/ssl/record/rec_layer_d1.c | /*
* Copyright 2005-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <errno.h>
#include "../ssl_local.h"
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include "record_local.h"
#include "internal/packet.h"
#include "internal/cryptlib.h"
int DTLS_RECORD_LAYER_new(RECORD_LAYER *rl)
{
DTLS_RECORD_LAYER *d;
if ((d = OPENSSL_malloc(sizeof(*d))) == NULL)
return 0;
rl->d = d;
d->buffered_app_data.q = pqueue_new();
if (d->buffered_app_data.q == NULL) {
OPENSSL_free(d);
rl->d = NULL;
return 0;
}
return 1;
}
void DTLS_RECORD_LAYER_free(RECORD_LAYER *rl)
{
if (rl->d == NULL)
return;
DTLS_RECORD_LAYER_clear(rl);
pqueue_free(rl->d->buffered_app_data.q);
OPENSSL_free(rl->d);
rl->d = NULL;
}
void DTLS_RECORD_LAYER_clear(RECORD_LAYER *rl)
{
DTLS_RECORD_LAYER *d;
pitem *item = NULL;
TLS_RECORD *rec;
pqueue *buffered_app_data;
d = rl->d;
while ((item = pqueue_pop(d->buffered_app_data.q)) != NULL) {
rec = (TLS_RECORD *)item->data;
if (rl->s->options & SSL_OP_CLEANSE_PLAINTEXT)
OPENSSL_cleanse(rec->allocdata, rec->length);
OPENSSL_free(rec->allocdata);
OPENSSL_free(item->data);
pitem_free(item);
}
buffered_app_data = d->buffered_app_data.q;
memset(d, 0, sizeof(*d));
d->buffered_app_data.q = buffered_app_data;
}
static int dtls_buffer_record(SSL_CONNECTION *s, TLS_RECORD *rec)
{
TLS_RECORD *rdata;
pitem *item;
record_pqueue *queue = &(s->rlayer.d->buffered_app_data);
/* Limit the size of the queue to prevent DOS attacks */
if (pqueue_size(queue->q) >= 100)
return 0;
/* We don't buffer partially read records */
if (!ossl_assert(rec->off == 0))
return -1;
rdata = OPENSSL_malloc(sizeof(*rdata));
item = pitem_new(rec->seq_num, rdata);
if (rdata == NULL || item == NULL) {
OPENSSL_free(rdata);
pitem_free(item);
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return -1;
}
*rdata = *rec;
/*
* We will release the record from the record layer soon, so we take a copy
* now. Copying data isn't good - but this should be infrequent so we
* accept it here.
*/
rdata->data = rdata->allocdata = OPENSSL_memdup(rec->data, rec->length);
if (rdata->data == NULL) {
OPENSSL_free(rdata);
pitem_free(item);
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
return -1;
}
/*
* We use a NULL rechandle to indicate that the data field has been
* allocated by us.
*/
rdata->rechandle = NULL;
item->data = rdata;
#ifndef OPENSSL_NO_SCTP
/* Store bio_dgram_sctp_rcvinfo struct */
if (BIO_dgram_is_sctp(s->rbio) &&
(ossl_statem_get_state(s) == TLS_ST_SR_FINISHED
|| ossl_statem_get_state(s) == TLS_ST_CR_FINISHED)) {
BIO_ctrl(s->rbio, BIO_CTRL_DGRAM_SCTP_GET_RCVINFO,
sizeof(rdata->recordinfo), &rdata->recordinfo);
}
#endif
if (pqueue_insert(queue->q, item) == NULL) {
/* Must be a duplicate so ignore it */
OPENSSL_free(rdata->allocdata);
OPENSSL_free(rdata);
pitem_free(item);
}
return 1;
}
/* Unbuffer a previously buffered TLS_RECORD structure if any */
static void dtls_unbuffer_record(SSL_CONNECTION *s)
{
TLS_RECORD *rdata;
pitem *item;
/* If we already have records to handle then do nothing */
if (s->rlayer.curr_rec < s->rlayer.num_recs)
return;
item = pqueue_pop(s->rlayer.d->buffered_app_data.q);
if (item != NULL) {
rdata = (TLS_RECORD *)item->data;
s->rlayer.tlsrecs[0] = *rdata;
s->rlayer.num_recs = 1;
s->rlayer.curr_rec = 0;
#ifndef OPENSSL_NO_SCTP
/* Restore bio_dgram_sctp_rcvinfo struct */
if (BIO_dgram_is_sctp(s->rbio)) {
BIO_ctrl(s->rbio, BIO_CTRL_DGRAM_SCTP_SET_RCVINFO,
sizeof(rdata->recordinfo), &rdata->recordinfo);
}
#endif
OPENSSL_free(item->data);
pitem_free(item);
}
}
/*-
* Return up to 'len' payload bytes received in 'type' records.
* 'type' is one of the following:
*
* - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
* - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
* - 0 (during a shutdown, no data has to be returned)
*
* If we don't have stored data to work from, read a SSL/TLS record first
* (possibly multiple records if we still don't have anything to return).
*
* This function must handle any surprises the peer may have for us, such as
* Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
* messages are treated as if they were handshake messages *if* the |recd_type|
* argument is non NULL.
* Also if record payloads contain fragments too small to process, we store
* them until there is enough for the respective protocol (the record protocol
* may use arbitrary fragmentation and even interleaving):
* Change cipher spec protocol
* just 1 byte needed, no need for keeping anything stored
* Alert protocol
* 2 bytes needed (AlertLevel, AlertDescription)
* Handshake protocol
* 4 bytes needed (HandshakeType, uint24 length) -- we just have
* to detect unexpected Client Hello and Hello Request messages
* here, anything else is handled by higher layers
* Application data protocol
* none of our business
*/
int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
size_t len, int peek, size_t *readbytes)
{
int i, j, ret;
size_t n;
TLS_RECORD *rr;
void (*cb) (const SSL *ssl, int type2, int val) = NULL;
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
if (sc == NULL)
return -1;
if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
(type != SSL3_RT_HANDSHAKE)) ||
(peek && (type != SSL3_RT_APPLICATION_DATA))) {
SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return -1;
}
if (!ossl_statem_get_in_handshake(sc) && SSL_in_init(s)) {
/* type == SSL3_RT_APPLICATION_DATA */
i = sc->handshake_func(s);
/* SSLfatal() already called if appropriate */
if (i < 0)
return i;
if (i == 0)
return -1;
}
start:
sc->rwstate = SSL_NOTHING;
/*
* We are not handshaking and have no data yet, so process data buffered
* during the last handshake in advance, if any.
*/
if (SSL_is_init_finished(s))
dtls_unbuffer_record(sc);
/* Check for timeout */
if (dtls1_handle_timeout(sc) > 0) {
goto start;
} else if (ossl_statem_in_error(sc)) {
/* dtls1_handle_timeout() has failed with a fatal error */
return -1;
}
/* get new packet if necessary */
if (sc->rlayer.curr_rec >= sc->rlayer.num_recs) {
sc->rlayer.curr_rec = sc->rlayer.num_recs = 0;
do {
rr = &sc->rlayer.tlsrecs[sc->rlayer.num_recs];
ret = HANDLE_RLAYER_READ_RETURN(sc,
sc->rlayer.rrlmethod->read_record(sc->rlayer.rrl,
&rr->rechandle,
&rr->version, &rr->type,
&rr->data, &rr->length,
&rr->epoch, rr->seq_num));
if (ret <= 0) {
ret = dtls1_read_failed(sc, ret);
/*
* Anything other than a timeout is an error. SSLfatal() already
* called if appropriate.
*/
if (ret <= 0)
return ret;
else
goto start;
}
rr->off = 0;
sc->rlayer.num_recs++;
} while (sc->rlayer.rrlmethod->processed_read_pending(sc->rlayer.rrl)
&& sc->rlayer.num_recs < SSL_MAX_PIPELINES);
}
rr = &sc->rlayer.tlsrecs[sc->rlayer.curr_rec];
/*
* Reset the count of consecutive warning alerts if we've got a non-empty
* record that isn't an alert.
*/
if (rr->type != SSL3_RT_ALERT && rr->length != 0)
sc->rlayer.alert_count = 0;
/* we now have a packet which can be read and processed */
if (sc->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
* reset by ssl3_get_finished */
&& (rr->type != SSL3_RT_HANDSHAKE)) {
/*
* We now have application data between CCS and Finished. Most likely
* the packets were reordered on their way, so buffer the application
* data for later processing rather than dropping the connection.
*/
if (dtls_buffer_record(sc, rr) < 0) {
/* SSLfatal() already called */
return -1;
}
if (!ssl_release_record(sc, rr, 0))
return -1;
goto start;
}
/*
* If the other end has shut down, throw anything we read away (even in
* 'peek' mode)
*/
if (sc->shutdown & SSL_RECEIVED_SHUTDOWN) {
if (!ssl_release_record(sc, rr, 0))
return -1;
sc->rwstate = SSL_NOTHING;
return 0;
}
if (type == rr->type
|| (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
&& type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {
/*
* SSL3_RT_APPLICATION_DATA or
* SSL3_RT_HANDSHAKE or
* SSL3_RT_CHANGE_CIPHER_SPEC
*/
/*
* make sure that we are not getting application data when we are
* doing a handshake for the first time
*/
if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA)
&& (SSL_IS_FIRST_HANDSHAKE(sc))) {
SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE,
SSL_R_APP_DATA_IN_HANDSHAKE);
return -1;
}
if (recvd_type != NULL)
*recvd_type = rr->type;
if (len == 0) {
/*
* Release a zero length record. This ensures multiple calls to
* SSL_read() with a zero length buffer will eventually cause
* SSL_pending() to report data as being available.
*/
if (rr->length == 0 && !ssl_release_record(sc, rr, 0))
return -1;
return 0;
}
if (len > rr->length)
n = rr->length;
else
n = len;
memcpy(buf, &(rr->data[rr->off]), n);
if (peek) {
if (rr->length == 0 && !ssl_release_record(sc, rr, 0))
return -1;
} else {
if (!ssl_release_record(sc, rr, n))
return -1;
}
#ifndef OPENSSL_NO_SCTP
/*
* We might had to delay a close_notify alert because of reordered
* app data. If there was an alert and there is no message to read
* anymore, finally set shutdown.
*/
if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
sc->d1->shutdown_received
&& BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s)) <= 0) {
sc->shutdown |= SSL_RECEIVED_SHUTDOWN;
return 0;
}
#endif
*readbytes = n;
return 1;
}
/*
* If we get here, then type != rr->type; if we have a handshake message,
* then it was unexpected (Hello Request or Client Hello).
*/
if (rr->type == SSL3_RT_ALERT) {
unsigned int alert_level, alert_descr;
const unsigned char *alert_bytes = rr->data + rr->off;
PACKET alert;
if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
|| !PACKET_get_1(&alert, &alert_level)
|| !PACKET_get_1(&alert, &alert_descr)
|| PACKET_remaining(&alert) != 0) {
SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
return -1;
}
if (sc->msg_callback)
sc->msg_callback(0, sc->version, SSL3_RT_ALERT, alert_bytes, 2, s,
sc->msg_callback_arg);
if (sc->info_callback != NULL)
cb = sc->info_callback;
else if (s->ctx->info_callback != NULL)
cb = s->ctx->info_callback;
if (cb != NULL) {
j = (alert_level << 8) | alert_descr;
cb(s, SSL_CB_READ_ALERT, j);
}
if (alert_level == SSL3_AL_WARNING) {
sc->s3.warn_alert = alert_descr;
if (!ssl_release_record(sc, rr, 0))
return -1;
sc->rlayer.alert_count++;
if (sc->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE,
SSL_R_TOO_MANY_WARN_ALERTS);
return -1;
}
if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
#ifndef OPENSSL_NO_SCTP
/*
* With SCTP and streams the socket may deliver app data
* after a close_notify alert. We have to check this first so
* that nothing gets discarded.
*/
if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s)) > 0) {
sc->d1->shutdown_received = 1;
sc->rwstate = SSL_READING;
BIO_clear_retry_flags(SSL_get_rbio(s));
BIO_set_retry_read(SSL_get_rbio(s));
return -1;
}
#endif
sc->shutdown |= SSL_RECEIVED_SHUTDOWN;
return 0;
}
} else if (alert_level == SSL3_AL_FATAL) {
sc->rwstate = SSL_NOTHING;
sc->s3.fatal_alert = alert_descr;
SSLfatal_data(sc, SSL_AD_NO_ALERT,
SSL_AD_REASON_OFFSET + alert_descr,
"SSL alert number %d", alert_descr);
sc->shutdown |= SSL_RECEIVED_SHUTDOWN;
if (!ssl_release_record(sc, rr, 0))
return -1;
SSL_CTX_remove_session(sc->session_ctx, sc->session);
return 0;
} else {
SSLfatal(sc, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
return -1;
}
goto start;
}
if (sc->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
* shutdown */
sc->rwstate = SSL_NOTHING;
if (!ssl_release_record(sc, rr, 0))
return -1;
return 0;
}
if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
/*
* We can't process a CCS now, because previous handshake messages
* are still missing, so just drop it.
*/
if (!ssl_release_record(sc, rr, 0))
return -1;
goto start;
}
/*
* Unexpected handshake message (Client Hello, or protocol violation)
*/
if (rr->type == SSL3_RT_HANDSHAKE && !ossl_statem_get_in_handshake(sc)) {
struct hm_header_st msg_hdr;
/*
* This may just be a stale retransmit. Also sanity check that we have
* at least enough record bytes for a message header
*/
if (rr->epoch != sc->rlayer.d->r_epoch
|| rr->length < DTLS1_HM_HEADER_LENGTH) {
if (!ssl_release_record(sc, rr, 0))
return -1;
goto start;
}
dtls1_get_message_header(rr->data, &msg_hdr);
/*
* If we are server, we may have a repeated FINISHED of the client
* here, then retransmit our CCS and FINISHED.
*/
if (msg_hdr.type == SSL3_MT_FINISHED) {
if (dtls1_check_timeout_num(sc) < 0) {
/* SSLfatal) already called */
return -1;
}
if (dtls1_retransmit_buffered_messages(sc) <= 0) {
/* Fail if we encountered a fatal error */
if (ossl_statem_in_error(sc))
return -1;
}
if (!ssl_release_record(sc, rr, 0))
return -1;
if (!(sc->mode & SSL_MODE_AUTO_RETRY)) {
if (!sc->rlayer.rrlmethod->unprocessed_read_pending(sc->rlayer.rrl)) {
/* no read-ahead left? */
BIO *bio;
sc->rwstate = SSL_READING;
bio = SSL_get_rbio(s);
BIO_clear_retry_flags(bio);
BIO_set_retry_read(bio);
return -1;
}
}
goto start;
}
/*
* To get here we must be trying to read app data but found handshake
* data. But if we're trying to read app data, and we're not in init
* (which is tested for at the top of this function) then init must be
* finished
*/
if (!ossl_assert(SSL_is_init_finished(s))) {
SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return -1;
}
/* We found handshake data, so we're going back into init */
ossl_statem_set_in_init(sc, 1);
i = sc->handshake_func(s);
/* SSLfatal() called if appropriate */
if (i < 0)
return i;
if (i == 0)
return -1;
if (!(sc->mode & SSL_MODE_AUTO_RETRY)) {
if (!sc->rlayer.rrlmethod->unprocessed_read_pending(sc->rlayer.rrl)) {
/* no read-ahead left? */
BIO *bio;
/*
* In the case where we try to read application data, but we
* trigger an SSL handshake, we return -1 with the retry
* option set. Otherwise renegotiation may cause nasty
* problems in the blocking world
*/
sc->rwstate = SSL_READING;
bio = SSL_get_rbio(s);
BIO_clear_retry_flags(bio);
BIO_set_retry_read(bio);
return -1;
}
}
goto start;
}
switch (rr->type) {
default:
SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
return -1;
case SSL3_RT_CHANGE_CIPHER_SPEC:
case SSL3_RT_ALERT:
case SSL3_RT_HANDSHAKE:
/*
* we already handled all of these, with the possible exception of
* SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
* that should not happen when type != rr->type
*/
SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
return -1;
case SSL3_RT_APPLICATION_DATA:
/*
* At this point, we were expecting handshake data, but have
* application data. If the library was running inside ssl3_read()
* (i.e. in_read_app_data is set) and it makes sense to read
* application data at this point (session renegotiation not yet
* started), we will indulge it.
*/
if (sc->s3.in_read_app_data &&
(sc->s3.total_renegotiations != 0) &&
ossl_statem_app_data_allowed(sc)) {
sc->s3.in_read_app_data = 2;
return -1;
} else {
SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
return -1;
}
}
/* not reached */
}
/*
* Call this to write data in records of type 'type' It will return <= 0 if
* not all data has been sent or non-blocking IO.
*/
int dtls1_write_bytes(SSL_CONNECTION *s, int type, const void *buf,
size_t len, size_t *written)
{
int i;
if (!ossl_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH)) {
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return -1;
}
s->rwstate = SSL_NOTHING;
i = do_dtls1_write(s, type, buf, len, written);
return i;
}
int do_dtls1_write(SSL_CONNECTION *sc, int type, const unsigned char *buf,
size_t len, size_t *written)
{
int i;
OSSL_RECORD_TEMPLATE tmpl;
SSL *s = SSL_CONNECTION_GET_SSL(sc);
int ret;
/* If we have an alert to send, lets send it */
if (sc->s3.alert_dispatch > 0) {
i = s->method->ssl_dispatch_alert(s);
if (i <= 0)
return i;
/* if it went, fall through and send more stuff */
}
if (len == 0)
return 0;
if (len > ssl_get_max_send_fragment(sc)) {
SSLfatal(sc, SSL_AD_INTERNAL_ERROR, SSL_R_EXCEEDS_MAX_FRAGMENT_SIZE);
return 0;
}
tmpl.type = type;
/*
* Special case: for hello verify request, client version 1.0 and we
* haven't decided which version to use yet send back using version 1.0
* header: otherwise some clients will ignore it.
*/
if (s->method->version == DTLS_ANY_VERSION
&& sc->max_proto_version != DTLS1_BAD_VER)
tmpl.version = DTLS1_VERSION;
else
tmpl.version = sc->version;
tmpl.buf = buf;
tmpl.buflen = len;
ret = HANDLE_RLAYER_WRITE_RETURN(sc,
sc->rlayer.wrlmethod->write_records(sc->rlayer.wrl, &tmpl, 1));
if (ret > 0)
*written = (int)len;
return ret;
}
void dtls1_increment_epoch(SSL_CONNECTION *s, int rw)
{
if (rw & SSL3_CC_READ) {
s->rlayer.d->r_epoch++;
/*
* We must not use any buffered messages received from the previous
* epoch
*/
dtls1_clear_received_buffer(s);
} else {
s->rlayer.d->w_epoch++;
}
}
| 21,979 | 31.276065 | 86 | c |
openssl | openssl-master/ssl/record/record.h | /*
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/core_dispatch.h>
#include "internal/recordmethod.h"
/*****************************************************************************
* *
* These structures should be considered PRIVATE to the record layer. No *
* non-record layer code should be using these structures in any way. *
* *
*****************************************************************************/
#define SEQ_NUM_SIZE 8
typedef struct tls_record_st {
void *rechandle;
int version;
int type;
/* The data buffer containing bytes from the record */
const unsigned char *data;
/*
* Buffer that we allocated to store data. If non NULL always the same as
* data (but non-const)
*/
unsigned char *allocdata;
/* Number of remaining to be read in the data buffer */
size_t length;
/* Offset into the data buffer where to start reading */
size_t off;
/* epoch number. DTLS only */
uint16_t epoch;
/* sequence number. DTLS only */
unsigned char seq_num[SEQ_NUM_SIZE];
#ifndef OPENSSL_NO_SCTP
struct bio_dgram_sctp_rcvinfo recordinfo;
#endif
} TLS_RECORD;
typedef struct record_pqueue_st {
uint16_t epoch;
struct pqueue_st *q;
} record_pqueue;
typedef struct dtls_record_layer_st {
/*
* The current data and handshake epoch. This is initially
* undefined, and starts at zero once the initial handshake is
* completed
*/
uint16_t r_epoch;
uint16_t w_epoch;
/*
* Buffered application records. Only for records between CCS and
* Finished to prevent either protocol violation or unnecessary message
* loss.
*/
record_pqueue buffered_app_data;
} DTLS_RECORD_LAYER;
/*****************************************************************************
* *
* This structure should be considered "opaque" to anything outside of the *
* record layer. No non-record layer code should be accessing the members of *
* this structure. *
* *
*****************************************************************************/
typedef struct record_layer_st {
/* The parent SSL_CONNECTION structure */
SSL_CONNECTION *s;
/* Custom record layer: always selected if set */
const OSSL_RECORD_METHOD *custom_rlmethod;
/* Record layer specific argument */
void *rlarg;
/* Method to use for the read record layer*/
const OSSL_RECORD_METHOD *rrlmethod;
/* Method to use for the write record layer*/
const OSSL_RECORD_METHOD *wrlmethod;
/* The read record layer object itself */
OSSL_RECORD_LAYER *rrl;
/* The write record layer object itself */
OSSL_RECORD_LAYER *wrl;
/* BIO to store data destined for the next read record layer epoch */
BIO *rrlnext;
/* Default read buffer length to be passed to the record layer */
size_t default_read_buf_len;
/*
* Read as many input bytes as possible (for
* non-blocking reads)
*/
int read_ahead;
/* number of bytes sent so far */
size_t wnum;
unsigned char handshake_fragment[4];
size_t handshake_fragment_len;
/* partial write - check the numbers match */
/* number bytes written */
size_t wpend_tot;
int wpend_type;
/* number of bytes submitted */
size_t wpend_ret;
const unsigned char *wpend_buf;
/* Count of the number of consecutive warning alerts received */
unsigned int alert_count;
DTLS_RECORD_LAYER *d;
/* TLS1.3 padding callback */
size_t (*record_padding_cb)(SSL *s, int type, size_t len, void *arg);
void *record_padding_arg;
size_t block_padding;
/* How many records we have read from the record layer */
size_t num_recs;
/* The next record from the record layer that we need to process */
size_t curr_rec;
/* Record layer data to be processed */
TLS_RECORD tlsrecs[SSL_MAX_PIPELINES];
} RECORD_LAYER;
/*****************************************************************************
* *
* The following macros/functions represent the libssl internal API to the *
* record layer. Any libssl code may call these functions/macros *
* *
*****************************************************************************/
#define RECORD_LAYER_set_read_ahead(rl, ra) ((rl)->read_ahead = (ra))
#define RECORD_LAYER_get_read_ahead(rl) ((rl)->read_ahead)
#define DTLS_RECORD_LAYER_get_w_epoch(rl) ((rl)->d->w_epoch)
void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s);
void RECORD_LAYER_clear(RECORD_LAYER *rl);
int RECORD_LAYER_read_pending(const RECORD_LAYER *rl);
int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl);
int RECORD_LAYER_write_pending(const RECORD_LAYER *rl);
int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl);
__owur size_t ssl3_pending(const SSL *s);
__owur int ssl3_write_bytes(SSL *s, int type, const void *buf, size_t len,
size_t *written);
__owur int ssl3_read_bytes(SSL *s, int type, int *recvd_type,
unsigned char *buf, size_t len, int peek,
size_t *readbytes);
int DTLS_RECORD_LAYER_new(RECORD_LAYER *rl);
void DTLS_RECORD_LAYER_free(RECORD_LAYER *rl);
void DTLS_RECORD_LAYER_clear(RECORD_LAYER *rl);
__owur int dtls1_read_bytes(SSL *s, int type, int *recvd_type,
unsigned char *buf, size_t len, int peek,
size_t *readbytes);
__owur int dtls1_write_bytes(SSL_CONNECTION *s, int type, const void *buf,
size_t len, size_t *written);
int do_dtls1_write(SSL_CONNECTION *s, int type, const unsigned char *buf,
size_t len, size_t *written);
void dtls1_increment_epoch(SSL_CONNECTION *s, int rw);
int ssl_release_record(SSL_CONNECTION *s, TLS_RECORD *rr, size_t length);
# define HANDLE_RLAYER_READ_RETURN(s, ret) \
ossl_tls_handle_rlayer_return(s, 0, ret, OPENSSL_FILE, OPENSSL_LINE)
# define HANDLE_RLAYER_WRITE_RETURN(s, ret) \
ossl_tls_handle_rlayer_return(s, 1, ret, OPENSSL_FILE, OPENSSL_LINE)
int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int writing, int ret,
char *file, int line);
int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
int direction, int level,
unsigned char *secret, size_t secretlen,
unsigned char *key, size_t keylen,
unsigned char *iv, size_t ivlen,
unsigned char *mackey, size_t mackeylen,
const EVP_CIPHER *ciph, size_t taglen,
int mactype, const EVP_MD *md,
const SSL_COMP *comp, const EVP_MD *kdfdigest);
int ssl_set_record_protocol_version(SSL_CONNECTION *s, int vers);
# define OSSL_FUNC_RLAYER_SKIP_EARLY_DATA 1
OSSL_CORE_MAKE_FUNC(int, rlayer_skip_early_data, (void *cbarg))
# define OSSL_FUNC_RLAYER_MSG_CALLBACK 2
OSSL_CORE_MAKE_FUNC(void, rlayer_msg_callback, (int write_p, int version,
int content_type,
const void *buf, size_t len,
void *cbarg))
# define OSSL_FUNC_RLAYER_SECURITY 3
OSSL_CORE_MAKE_FUNC(int, rlayer_security, (void *cbarg, int op, int bits,
int nid, void *other))
# define OSSL_FUNC_RLAYER_PADDING 4
OSSL_CORE_MAKE_FUNC(size_t, rlayer_padding, (void *cbarg, int type, size_t len))
| 8,453 | 40.851485 | 80 | h |
openssl | openssl-master/ssl/record/record_local.h | /*
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*****************************************************************************
* *
* The following macros/functions are PRIVATE to the record layer. They *
* should NOT be used outside of the record layer. *
* *
*****************************************************************************/
#define MAX_WARN_ALERT_COUNT 5
/* Functions/macros provided by the RECORD_LAYER component */
#define DTLS_RECORD_LAYER_get_r_epoch(rl) ((rl)->d->r_epoch)
| 978 | 43.5 | 79 | h |
openssl | openssl-master/ssl/record/methods/ktls_meth.c | /*
* Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/evp.h>
#include <openssl/core_names.h>
#include <openssl/rand.h>
#include "../../ssl_local.h"
#include "../record_local.h"
#include "recmethod_local.h"
#include "internal/ktls.h"
static struct record_functions_st ossl_ktls_funcs;
#if defined(__FreeBSD__)
# include "crypto/cryptodev.h"
/*-
* Check if a given cipher is supported by the KTLS interface.
* The kernel might still fail the setsockopt() if no suitable
* provider is found, but this checks if the socket option
* supports the cipher suite used at all.
*/
static int ktls_int_check_supported_cipher(OSSL_RECORD_LAYER *rl,
const EVP_CIPHER *c,
const EVP_MD *md,
size_t taglen)
{
switch (rl->version) {
case TLS1_VERSION:
case TLS1_1_VERSION:
case TLS1_2_VERSION:
#ifdef OPENSSL_KTLS_TLS13
case TLS1_3_VERSION:
#endif
break;
default:
return 0;
}
if (EVP_CIPHER_is_a(c, "AES-128-GCM")
|| EVP_CIPHER_is_a(c, "AES-256-GCM")
# ifdef OPENSSL_KTLS_CHACHA20_POLY1305
|| EVP_CIPHER_is_a(c, "CHACHA20-POLY1305")
# endif
)
return 1;
if (!EVP_CIPHER_is_a(c, "AES-128-CBC")
&& !EVP_CIPHER_is_a(c, "AES-256-CBC"))
return 0;
if (rl->use_etm)
return 0;
if (md == NULL)
return 0;
if (EVP_MD_is_a(md, "SHA1")
|| EVP_MD_is_a(md, "SHA2-256")
|| EVP_MD_is_a(md, "SHA2-384"))
return 1;
return 0;
}
/* Function to configure kernel TLS structure */
static
int ktls_configure_crypto(OSSL_LIB_CTX *libctx, int version, const EVP_CIPHER *c,
EVP_MD *md, void *rl_sequence,
ktls_crypto_info_t *crypto_info, int is_tx,
unsigned char *iv, size_t ivlen,
unsigned char *key, size_t keylen,
unsigned char *mac_key, size_t mac_secret_size)
{
memset(crypto_info, 0, sizeof(*crypto_info));
if (EVP_CIPHER_is_a(c, "AES-128-GCM")
|| EVP_CIPHER_is_a(c, "AES-256-GCM")) {
crypto_info->cipher_algorithm = CRYPTO_AES_NIST_GCM_16;
crypto_info->iv_len = ivlen;
} else
# ifdef OPENSSL_KTLS_CHACHA20_POLY1305
if (EVP_CIPHER_is_a(c, "CHACHA20-POLY1305")) {
crypto_info->cipher_algorithm = CRYPTO_CHACHA20_POLY1305;
crypto_info->iv_len = ivlen;
} else
# endif
if (EVP_CIPHER_is_a(c, "AES-128-CBC") || EVP_CIPHER_is_a(c, "AES-256-CBC")) {
if (md == NULL)
return 0;
if (EVP_MD_is_a(md, "SHA1"))
crypto_info->auth_algorithm = CRYPTO_SHA1_HMAC;
else if (EVP_MD_is_a(md, "SHA2-256")) {
crypto_info->auth_algorithm = CRYPTO_SHA2_256_HMAC;
else if (EVP_MD_is_a(md, "SHA2-384"))
crypto_info->auth_algorithm = CRYPTO_SHA2_384_HMAC;
else
return 0;
crypto_info->cipher_algorithm = CRYPTO_AES_CBC;
crypto_info->iv_len = ivlen;
crypto_info->auth_key = mac_key;
crypto_info->auth_key_len = mac_secret_size;
} else {
return 0;
}
crypto_info->cipher_key = key;
crypto_info->cipher_key_len = keylen;
crypto_info->iv = iv;
crypto_info->tls_vmajor = (version >> 8) & 0x000000ff;
crypto_info->tls_vminor = (version & 0x000000ff);
# ifdef TCP_RXTLS_ENABLE
memcpy(crypto_info->rec_seq, rl_sequence, sizeof(crypto_info->rec_seq));
# else
if (!is_tx)
return 0;
# endif
return 1;
};
#endif /* __FreeBSD__ */
#if defined(OPENSSL_SYS_LINUX)
/* Function to check supported ciphers in Linux */
static int ktls_int_check_supported_cipher(OSSL_RECORD_LAYER *rl,
const EVP_CIPHER *c,
const EVP_MD *md,
size_t taglen)
{
switch (rl->version) {
case TLS1_2_VERSION:
#ifdef OPENSSL_KTLS_TLS13
case TLS1_3_VERSION:
#endif
break;
default:
return 0;
}
/*
* Check that cipher is AES_GCM_128, AES_GCM_256, AES_CCM_128
* or Chacha20-Poly1305
*/
# ifdef OPENSSL_KTLS_AES_CCM_128
if (EVP_CIPHER_is_a(c, "AES-128-CCM")) {
if (taglen != EVP_CCM_TLS_TAG_LEN)
return 0;
return 1;
} else
# endif
if (0
# ifdef OPENSSL_KTLS_AES_GCM_128
|| EVP_CIPHER_is_a(c, "AES-128-GCM")
# endif
# ifdef OPENSSL_KTLS_AES_GCM_256
|| EVP_CIPHER_is_a(c, "AES-256-GCM")
# endif
# ifdef OPENSSL_KTLS_CHACHA20_POLY1305
|| EVP_CIPHER_is_a(c, "ChaCha20-Poly1305")
# endif
) {
return 1;
}
return 0;
}
/* Function to configure kernel TLS structure */
static
int ktls_configure_crypto(OSSL_LIB_CTX *libctx, int version, const EVP_CIPHER *c,
const EVP_MD *md, void *rl_sequence,
ktls_crypto_info_t *crypto_info, int is_tx,
unsigned char *iv, size_t ivlen,
unsigned char *key, size_t keylen,
unsigned char *mac_key, size_t mac_secret_size)
{
unsigned char geniv[EVP_GCM_TLS_EXPLICIT_IV_LEN];
unsigned char *eiv = NULL;
# ifdef OPENSSL_NO_KTLS_RX
if (!is_tx)
return 0;
# endif
if (EVP_CIPHER_get_mode(c) == EVP_CIPH_GCM_MODE
|| EVP_CIPHER_get_mode(c) == EVP_CIPH_CCM_MODE) {
if (!ossl_assert(EVP_GCM_TLS_FIXED_IV_LEN == EVP_CCM_TLS_FIXED_IV_LEN)
|| !ossl_assert(EVP_GCM_TLS_EXPLICIT_IV_LEN
== EVP_CCM_TLS_EXPLICIT_IV_LEN))
return 0;
if (version == TLS1_2_VERSION) {
if (!ossl_assert(ivlen == EVP_GCM_TLS_FIXED_IV_LEN))
return 0;
if (is_tx) {
if (RAND_bytes_ex(libctx, geniv,
EVP_GCM_TLS_EXPLICIT_IV_LEN, 0) <= 0)
return 0;
} else {
memset(geniv, 0, EVP_GCM_TLS_EXPLICIT_IV_LEN);
}
eiv = geniv;
} else {
if (!ossl_assert(ivlen == EVP_GCM_TLS_FIXED_IV_LEN
+ EVP_GCM_TLS_EXPLICIT_IV_LEN))
return 0;
eiv = iv + TLS_CIPHER_AES_GCM_128_SALT_SIZE;
}
}
memset(crypto_info, 0, sizeof(*crypto_info));
switch (EVP_CIPHER_get_nid(c)) {
# ifdef OPENSSL_KTLS_AES_GCM_128
case NID_aes_128_gcm:
if (!ossl_assert(TLS_CIPHER_AES_GCM_128_SALT_SIZE
== EVP_GCM_TLS_FIXED_IV_LEN)
|| !ossl_assert(TLS_CIPHER_AES_GCM_128_IV_SIZE
== EVP_GCM_TLS_EXPLICIT_IV_LEN))
return 0;
crypto_info->gcm128.info.cipher_type = TLS_CIPHER_AES_GCM_128;
crypto_info->gcm128.info.version = version;
crypto_info->tls_crypto_info_len = sizeof(crypto_info->gcm128);
memcpy(crypto_info->gcm128.iv, eiv, TLS_CIPHER_AES_GCM_128_IV_SIZE);
memcpy(crypto_info->gcm128.salt, iv, TLS_CIPHER_AES_GCM_128_SALT_SIZE);
memcpy(crypto_info->gcm128.key, key, keylen);
memcpy(crypto_info->gcm128.rec_seq, rl_sequence,
TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE);
return 1;
# endif
# ifdef OPENSSL_KTLS_AES_GCM_256
case NID_aes_256_gcm:
if (!ossl_assert(TLS_CIPHER_AES_GCM_256_SALT_SIZE
== EVP_GCM_TLS_FIXED_IV_LEN)
|| !ossl_assert(TLS_CIPHER_AES_GCM_256_IV_SIZE
== EVP_GCM_TLS_EXPLICIT_IV_LEN))
return 0;
crypto_info->gcm256.info.cipher_type = TLS_CIPHER_AES_GCM_256;
crypto_info->gcm256.info.version = version;
crypto_info->tls_crypto_info_len = sizeof(crypto_info->gcm256);
memcpy(crypto_info->gcm256.iv, eiv, TLS_CIPHER_AES_GCM_256_IV_SIZE);
memcpy(crypto_info->gcm256.salt, iv, TLS_CIPHER_AES_GCM_256_SALT_SIZE);
memcpy(crypto_info->gcm256.key, key, keylen);
memcpy(crypto_info->gcm256.rec_seq, rl_sequence,
TLS_CIPHER_AES_GCM_256_REC_SEQ_SIZE);
return 1;
# endif
# ifdef OPENSSL_KTLS_AES_CCM_128
case NID_aes_128_ccm:
if (!ossl_assert(TLS_CIPHER_AES_CCM_128_SALT_SIZE
== EVP_CCM_TLS_FIXED_IV_LEN)
|| !ossl_assert(TLS_CIPHER_AES_CCM_128_IV_SIZE
== EVP_CCM_TLS_EXPLICIT_IV_LEN))
return 0;
crypto_info->ccm128.info.cipher_type = TLS_CIPHER_AES_CCM_128;
crypto_info->ccm128.info.version = version;
crypto_info->tls_crypto_info_len = sizeof(crypto_info->ccm128);
memcpy(crypto_info->ccm128.iv, eiv, TLS_CIPHER_AES_CCM_128_IV_SIZE);
memcpy(crypto_info->ccm128.salt, iv, TLS_CIPHER_AES_CCM_128_SALT_SIZE);
memcpy(crypto_info->ccm128.key, key, keylen);
memcpy(crypto_info->ccm128.rec_seq, rl_sequence,
TLS_CIPHER_AES_CCM_128_REC_SEQ_SIZE);
return 1;
# endif
# ifdef OPENSSL_KTLS_CHACHA20_POLY1305
case NID_chacha20_poly1305:
if (!ossl_assert(ivlen == TLS_CIPHER_CHACHA20_POLY1305_IV_SIZE))
return 0;
crypto_info->chacha20poly1305.info.cipher_type
= TLS_CIPHER_CHACHA20_POLY1305;
crypto_info->chacha20poly1305.info.version = version;
crypto_info->tls_crypto_info_len = sizeof(crypto_info->chacha20poly1305);
memcpy(crypto_info->chacha20poly1305.iv, iv, ivlen);
memcpy(crypto_info->chacha20poly1305.key, key, keylen);
memcpy(crypto_info->chacha20poly1305.rec_seq, rl_sequence,
TLS_CIPHER_CHACHA20_POLY1305_REC_SEQ_SIZE);
return 1;
# endif
default:
return 0;
}
}
#endif /* OPENSSL_SYS_LINUX */
static int ktls_set_crypto_state(OSSL_RECORD_LAYER *rl, int level,
unsigned char *key, size_t keylen,
unsigned char *iv, size_t ivlen,
unsigned char *mackey, size_t mackeylen,
const EVP_CIPHER *ciph,
size_t taglen,
int mactype,
const EVP_MD *md,
COMP_METHOD *comp)
{
ktls_crypto_info_t crypto_info;
/*
* Check if we are suitable for KTLS. If not suitable we return
* OSSL_RECORD_RETURN_NON_FATAL_ERR so that other record layers can be tried
* instead
*/
if (comp != NULL)
return OSSL_RECORD_RETURN_NON_FATAL_ERR;
/* ktls supports only the maximum fragment size */
if (rl->max_frag_len != SSL3_RT_MAX_PLAIN_LENGTH)
return OSSL_RECORD_RETURN_NON_FATAL_ERR;
/* check that cipher is supported */
if (!ktls_int_check_supported_cipher(rl, ciph, md, taglen))
return OSSL_RECORD_RETURN_NON_FATAL_ERR;
/* All future data will get encrypted by ktls. Flush the BIO or skip ktls */
if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) {
if (BIO_flush(rl->bio) <= 0)
return OSSL_RECORD_RETURN_NON_FATAL_ERR;
/* KTLS does not support record padding */
if (rl->padding != NULL || rl->block_padding > 0)
return OSSL_RECORD_RETURN_NON_FATAL_ERR;
}
if (!ktls_configure_crypto(rl->libctx, rl->version, ciph, md, rl->sequence,
&crypto_info,
rl->direction == OSSL_RECORD_DIRECTION_WRITE,
iv, ivlen, key, keylen, mackey, mackeylen))
return OSSL_RECORD_RETURN_NON_FATAL_ERR;
if (!BIO_set_ktls(rl->bio, &crypto_info, rl->direction))
return OSSL_RECORD_RETURN_NON_FATAL_ERR;
if (rl->direction == OSSL_RECORD_DIRECTION_WRITE &&
(rl->options & SSL_OP_ENABLE_KTLS_TX_ZEROCOPY_SENDFILE) != 0)
/* Ignore errors. The application opts in to using the zerocopy
* optimization. If the running kernel doesn't support it, just
* continue without the optimization.
*/
BIO_set_ktls_tx_zerocopy_sendfile(rl->bio);
return OSSL_RECORD_RETURN_SUCCESS;
}
static int ktls_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
int clearold, size_t *readbytes)
{
int ret;
ret = tls_default_read_n(rl, n, max, extend, clearold, readbytes);
if (ret < OSSL_RECORD_RETURN_RETRY) {
switch (errno) {
case EBADMSG:
RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
break;
case EMSGSIZE:
RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
SSL_R_PACKET_LENGTH_TOO_LONG);
break;
case EINVAL:
RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
SSL_R_WRONG_VERSION_NUMBER);
break;
default:
break;
}
}
return ret;
}
static int ktls_cipher(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *inrecs,
size_t n_recs, int sending, SSL_MAC_BUF *mac,
size_t macsize)
{
return 1;
}
static int ktls_validate_record_header(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
{
if (rec->rec_version != TLS1_2_VERSION) {
RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_WRONG_VERSION_NUMBER);
return 0;
}
return 1;
}
static int ktls_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
{
if (rl->version == TLS1_3_VERSION)
return tls13_common_post_process_record(rl, rec);
return 1;
}
static int
ktls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
int role, int direction, int level, uint16_t epoch,
unsigned char *secret, size_t secretlen,
unsigned char *key, size_t keylen, unsigned char *iv,
size_t ivlen, unsigned char *mackey, size_t mackeylen,
const EVP_CIPHER *ciph, size_t taglen,
int mactype,
const EVP_MD *md, COMP_METHOD *comp,
const EVP_MD *kdfdigest, BIO *prev, BIO *transport,
BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
const OSSL_PARAM *settings, const OSSL_PARAM *options,
const OSSL_DISPATCH *fns, void *cbarg, void *rlarg,
OSSL_RECORD_LAYER **retrl)
{
int ret;
ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
key, keylen, iv, ivlen, mackey, mackeylen,
ciph, taglen, mactype, md, comp, prev,
transport, next, local, peer, settings,
options, fns, cbarg, retrl);
if (ret != OSSL_RECORD_RETURN_SUCCESS)
return ret;
(*retrl)->funcs = &ossl_ktls_funcs;
ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
ivlen, mackey, mackeylen, ciph,
taglen, mactype, md, comp);
if (ret != OSSL_RECORD_RETURN_SUCCESS) {
OPENSSL_free(*retrl);
*retrl = NULL;
} else {
/*
* With KTLS we always try and read as much as possible and fill the
* buffer
*/
(*retrl)->read_ahead = 1;
}
return ret;
}
static int ktls_allocate_write_buffers(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *templates,
size_t numtempl, size_t *prefix)
{
if (!ossl_assert(numtempl == 1))
return 0;
/*
* We just use the end application buffer in the case of KTLS, so nothing
* to do. We pretend we set up one buffer.
*/
rl->numwpipes = 1;
return 1;
}
static int ktls_initialise_write_packets(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *templates,
size_t numtempl,
OSSL_RECORD_TEMPLATE *prefixtempl,
WPACKET *pkt,
TLS_BUFFER *bufs,
size_t *wpinited)
{
TLS_BUFFER *wb;
/*
* We just use the application buffer directly and don't use any WPACKET
* structures
*/
wb = &bufs[0];
wb->type = templates[0].type;
/*
* ktls doesn't modify the buffer, but to avoid a warning we need
* to discard the const qualifier.
* This doesn't leak memory because the buffers have never been allocated
* with KTLS
*/
TLS_BUFFER_set_buf(wb, (unsigned char *)templates[0].buf);
TLS_BUFFER_set_offset(wb, 0);
TLS_BUFFER_set_app_buffer(wb, 1);
return 1;
}
static int ktls_prepare_record_header(OSSL_RECORD_LAYER *rl,
WPACKET *thispkt,
OSSL_RECORD_TEMPLATE *templ,
unsigned int rectype,
unsigned char **recdata)
{
/* The kernel writes the record header, so nothing to do */
*recdata = NULL;
return 1;
}
static int ktls_prepare_for_encryption(OSSL_RECORD_LAYER *rl,
size_t mac_size,
WPACKET *thispkt,
TLS_RL_RECORD *thiswr)
{
/* No encryption, so nothing to do */
return 1;
}
static int ktls_post_encryption_processing(OSSL_RECORD_LAYER *rl,
size_t mac_size,
OSSL_RECORD_TEMPLATE *templ,
WPACKET *thispkt,
TLS_RL_RECORD *thiswr)
{
/* The kernel does anything that is needed, so nothing to do here */
return 1;
}
static int ktls_prepare_write_bio(OSSL_RECORD_LAYER *rl, int type)
{
/*
* To prevent coalescing of control and data messages,
* such as in buffer_write, we flush the BIO
*/
if (type != SSL3_RT_APPLICATION_DATA) {
int ret, i = BIO_flush(rl->bio);
if (i <= 0) {
if (BIO_should_retry(rl->bio))
ret = OSSL_RECORD_RETURN_RETRY;
else
ret = OSSL_RECORD_RETURN_FATAL;
return ret;
}
BIO_set_ktls_ctrl_msg(rl->bio, type);
}
return OSSL_RECORD_RETURN_SUCCESS;
}
static int ktls_alloc_buffers(OSSL_RECORD_LAYER *rl)
{
/* We use the application buffer directly for writing */
if (rl->direction == OSSL_RECORD_DIRECTION_WRITE)
return 1;
return tls_alloc_buffers(rl);
}
static int ktls_free_buffers(OSSL_RECORD_LAYER *rl)
{
/* We use the application buffer directly for writing */
if (rl->direction == OSSL_RECORD_DIRECTION_WRITE)
return 1;
return tls_free_buffers(rl);
}
static struct record_functions_st ossl_ktls_funcs = {
ktls_set_crypto_state,
ktls_cipher,
NULL,
tls_default_set_protocol_version,
ktls_read_n,
tls_get_more_records,
ktls_validate_record_header,
ktls_post_process_record,
tls_get_max_records_default,
tls_write_records_default,
ktls_allocate_write_buffers,
ktls_initialise_write_packets,
NULL,
ktls_prepare_record_header,
NULL,
ktls_prepare_for_encryption,
ktls_post_encryption_processing,
ktls_prepare_write_bio
};
const OSSL_RECORD_METHOD ossl_ktls_record_method = {
ktls_new_record_layer,
tls_free,
tls_unprocessed_read_pending,
tls_processed_read_pending,
tls_app_data_pending,
tls_get_max_records,
tls_write_records,
tls_retry_write_records,
tls_read_record,
tls_release_record,
tls_get_alert_code,
tls_set1_bio,
tls_set_protocol_version,
tls_set_plain_alerts,
tls_set_first_handshake,
tls_set_max_pipelines,
NULL,
tls_get_state,
tls_set_options,
tls_get_compression,
tls_set_max_frag_len,
NULL,
tls_increment_sequence_ctr,
ktls_alloc_buffers,
ktls_free_buffers
};
| 20,694 | 32.815359 | 81 | c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.