+static int derive_secret_key_and_iv(SSL *s, int send, const EVP_MD *md,
+ const EVP_CIPHER *ciph,
+ const unsigned char *insecret,
+ const unsigned char *hash,
+ const unsigned char *label,
+ size_t labellen, unsigned char *secret,
+ unsigned char *iv, EVP_CIPHER_CTX *ciph_ctx)
+{
+ unsigned char key[EVP_MAX_KEY_LENGTH];
+ size_t ivlen, keylen, taglen;
+ size_t hashlen = EVP_MD_size(md);
+
+ if (!tls13_hkdf_expand(s, md, insecret, label, labellen, hash, secret,
+ hashlen)) {
+ SSLerr(SSL_F_DERIVE_SECRET_KEY_AND_IV, ERR_R_INTERNAL_ERROR);
+ goto err;
+ }
+
+ /* TODO(size_t): convert me */
+ keylen = EVP_CIPHER_key_length(ciph);
+ if (EVP_CIPHER_mode(ciph) == EVP_CIPH_CCM_MODE) {
+ uint32_t algenc;
+
+ ivlen = EVP_CCM_TLS_IV_LEN;
+ if (s->s3->tmp.new_cipher == NULL) {
+ /* We've not selected a cipher yet - we must be doing early data */
+ algenc = s->session->cipher->algorithm_enc;
+ } else {
+ algenc = s->s3->tmp.new_cipher->algorithm_enc;
+ }
+ if (algenc & (SSL_AES128CCM8 | SSL_AES256CCM8))
+ taglen = EVP_CCM8_TLS_TAG_LEN;
+ else
+ taglen = EVP_CCM_TLS_TAG_LEN;
+ } else {
+ ivlen = EVP_CIPHER_iv_length(ciph);
+ taglen = 0;
+ }
+
+ if (!tls13_derive_key(s, md, secret, key, keylen)
+ || !tls13_derive_iv(s, md, secret, iv, ivlen)) {
+ SSLerr(SSL_F_DERIVE_SECRET_KEY_AND_IV, ERR_R_INTERNAL_ERROR);
+ goto err;
+ }
+
+ if (EVP_CipherInit_ex(ciph_ctx, ciph, NULL, NULL, NULL, send) <= 0
+ || !EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL)
+ || (taglen != 0 && !EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_TAG,
+ taglen, NULL))
+ || EVP_CipherInit_ex(ciph_ctx, NULL, NULL, key, NULL, -1) <= 0) {
+ SSLerr(SSL_F_DERIVE_SECRET_KEY_AND_IV, ERR_R_EVP_LIB);
+ goto err;
+ }
+
+#ifdef OPENSSL_SSL_TRACE_CRYPTO
+ if (s->msg_callback) {
+ int wh = send ? TLS1_RT_CRYPTO_WRITE : 0;
+
+ if (ciph->key_len)
+ s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_KEY,
+ key, ciph->key_len, s, s->msg_callback_arg);
+
+ wh |= TLS1_RT_CRYPTO_IV;
+ s->msg_callback(2, s->version, wh, iv, ivlen, s,
+ s->msg_callback_arg);
+ }
+#endif
+
+ return 1;
+ err:
+ OPENSSL_cleanse(key, sizeof(key));
+ return 0;
+}
+