mem: Constify all APIs wherever it applies

Bug: 505090843
Signed-off-by: Xiangfei Ding <xfding@google.com>
Change-Id: Idd24c82587533ade3bc348b0311f6f526a6a6964
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/104008
Reviewed-by: David Benjamin <davidben@google.com>
diff --git a/crypto/bio/bio.cc b/crypto/bio/bio.cc
index aabf06d..28c3f4b 100644
--- a/crypto/bio/bio.cc
+++ b/crypto/bio/bio.cc
@@ -74,6 +74,13 @@
   return 1;
 }
 
+BIO *BIO_dup_ref(const BIO *bio) {
+  if (bio == nullptr) {
+    return nullptr;
+  }
+  return FromOpaque(bio)->DupRefInternal();
+}
+
 void BIO_vfree(BIO *bio) { BIO_free(bio); }
 
 void BIO_free_all(BIO *bio) { BIO_free(bio); }
@@ -291,9 +298,7 @@
   impl->retry_reason = 0;
 }
 
-int BIO_method_type(const BIO *bio) {
-  return FromOpaque(bio)->method->type;
-}
+int BIO_method_type(const BIO *bio) { return FromOpaque(bio)->method->type; }
 
 void BIO_copy_next_retry(BIO *bio) {
   auto *impl = FromOpaque(bio);
diff --git a/crypto/cms/cms.cc b/crypto/cms/cms.cc
index e8ba962..ddd9d60 100644
--- a/crypto/cms/cms.cc
+++ b/crypto/cms/cms.cc
@@ -56,8 +56,9 @@
 
 BSSL_NAMESPACE_END
 
-CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs,
-                          BIO *data, uint32_t flags) {
+CMS_ContentInfo *CMS_sign(const X509 *signcert, const EVP_PKEY *pkey,
+                          const STACK_OF(X509) *certs, BIO *data,
+                          uint32_t flags) {
   // We only support external signatures and do not support embedding
   // certificates in SignedData.
   if ((flags & CMS_DETACHED) == 0 || sk_X509_num(certs) != 0) {
@@ -88,8 +89,8 @@
 
 void CMS_ContentInfo_free(CMS_ContentInfo *cms) { Delete(FromOpaque(cms)); }
 
-CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, X509 *signcert,
-                                EVP_PKEY *pkey, const EVP_MD *md,
+CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, const X509 *signcert,
+                                const EVP_PKEY *pkey, const EVP_MD *md,
                                 uint32_t flags) {
   auto *impl = FromOpaque(cms);
   if (  // Already finalized.
diff --git a/crypto/dsa/dsa.cc b/crypto/dsa/dsa.cc
index 2048c44..9bb2df1 100644
--- a/crypto/dsa/dsa.cc
+++ b/crypto/dsa/dsa.cc
@@ -76,9 +76,7 @@
   if (dsa == nullptr) {
     return nullptr;
   }
-  auto *ptr = const_cast<DSA *>(dsa);
-  DSA_up_ref(ptr);
-  return ptr;
+  return FromOpaque(dsa)->DupRefInternal();
 }
 
 unsigned DSA_bits(const DSA *dsa) {
diff --git a/crypto/evp/evp.cc b/crypto/evp/evp.cc
index 6348a1e..f52a967 100644
--- a/crypto/evp/evp.cc
+++ b/crypto/evp/evp.cc
@@ -63,9 +63,7 @@
   if (pkey == nullptr) {
     return nullptr;
   }
-  auto pkey_ref = const_cast<EVP_PKEY *>(pkey);
-  EVP_PKEY_up_ref(pkey_ref);
-  return pkey_ref;
+  return FromOpaque(pkey)->DupRefInternal();
 }
 
 int EVP_PKEY_is_opaque(const EVP_PKEY *pkey) {
diff --git a/crypto/evp/evp_ctx.cc b/crypto/evp/evp_ctx.cc
index a0d7810..e01e92a 100644
--- a/crypto/evp/evp_ctx.cc
+++ b/crypto/evp/evp_ctx.cc
@@ -30,7 +30,8 @@
 using namespace bssl;
 
 static UniquePtr<EvpPkeyCtx> evp_pkey_ctx_new(
-    EvpPkey *pkey, const EVP_PKEY_ALG *alg, const EVP_PKEY_CTX_METHOD *pmeth) {
+    const EvpPkey *pkey, const EVP_PKEY_ALG *alg,
+    const EVP_PKEY_CTX_METHOD *pmeth) {
   assert(pkey != nullptr || alg != nullptr);
   UniquePtr<EvpPkeyCtx> ret = MakeUnique<EvpPkeyCtx>();
   if (!ret) {
@@ -49,7 +50,7 @@
   return ret;
 }
 
-EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e) {
+EVP_PKEY_CTX *EVP_PKEY_CTX_new(const EVP_PKEY *pkey, ENGINE *e) {
   auto *pkey_impl = FromOpaque(pkey);
   if (pkey_impl == nullptr || pkey_impl->ameth == nullptr) {
     OPENSSL_PUT_ERROR(EVP, ERR_R_PASSED_NULL_PARAMETER);
@@ -151,7 +152,7 @@
   return ret.release();
 }
 
-EVP_PKEY *EVP_PKEY_CTX_get0_pkey(EVP_PKEY_CTX *ctx) {
+EVP_PKEY *EVP_PKEY_CTX_get0_pkey(const EVP_PKEY_CTX *ctx) {
   auto *impl = FromOpaque(ctx);
   return impl->pkey.get();
 }
@@ -315,7 +316,7 @@
   return 1;
 }
 
-int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer) {
+int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, const EVP_PKEY *peer) {
   auto *impl = FromOpaque(ctx);
   if (!impl || !impl->pmeth ||
       !(impl->pmeth->derive || impl->pmeth->encrypt || impl->pmeth->decrypt) ||
@@ -330,7 +331,8 @@
     return 0;
   }
 
-  int ret = impl->pmeth->ctrl(impl, EVP_PKEY_CTRL_PEER_KEY, 0, peer);
+  int ret = impl->pmeth->ctrl(impl, EVP_PKEY_CTRL_PEER_KEY, 0,
+                              const_cast<EVP_PKEY *>(peer));
 
   if (ret <= 0) {
     return 0;
@@ -357,7 +359,7 @@
   }
 
   impl->peerkey = UpRef(FromOpaque(peer));
-  ret = impl->pmeth->ctrl(impl, EVP_PKEY_CTRL_PEER_KEY, 1, peer);
+  ret = impl->pmeth->ctrl(impl, EVP_PKEY_CTRL_PEER_KEY, 1, impl->peerkey.get());
   if (ret <= 0) {
     impl->peerkey = nullptr;
     return 0;
diff --git a/crypto/evp/evp_test.cc b/crypto/evp/evp_test.cc
index cf23c64..aa85220 100644
--- a/crypto/evp/evp_test.cc
+++ b/crypto/evp/evp_test.cc
@@ -42,12 +42,10 @@
 #include <openssl/xwing.h>
 
 #include "../bytestring/internal.h"
-#include "../fipsmodule/bcm_interface.h"
 #include "../test/der_trailing_data.h"
 #include "../test/file_test.h"
 #include "../test/test_util.h"
 #include "../test/wycheproof_util.h"
-#include "internal.h"
 
 
 BSSL_NAMESPACE_BEGIN
@@ -1151,7 +1149,7 @@
   int (*key_op)(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *out_len,
                 const uint8_t *in, size_t in_len) = nullptr;
   int (*md_op_init)(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, const EVP_MD *type,
-                    ENGINE *e, EVP_PKEY *pkey) = nullptr;
+                    ENGINE *e, const EVP_PKEY *pkey) = nullptr;
   bool is_verify = false;
   if (t->GetType() == "Decrypt") {
     key_op_init = EVP_PKEY_decrypt_init;
diff --git a/crypto/evp/sign.cc b/crypto/evp/sign.cc
index afccef5..3503c40 100644
--- a/crypto/evp/sign.cc
+++ b/crypto/evp/sign.cc
@@ -19,8 +19,6 @@
 #include <openssl/digest.h>
 #include <openssl/err.h>
 
-#include "internal.h"
-
 
 int EVP_SignInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl) {
   return EVP_DigestInit_ex(ctx, type, impl);
@@ -35,7 +33,7 @@
 }
 
 int EVP_SignFinal(const EVP_MD_CTX *ctx, uint8_t *sig, unsigned *out_sig_len,
-                  EVP_PKEY *pkey) {
+                  const EVP_PKEY *pkey) {
   // Ensure the final result will fit in `unsigned`.
   size_t sig_len = EVP_PKEY_size(pkey);
   if (sig_len > UINT_MAX) {
@@ -75,7 +73,7 @@
 }
 
 int EVP_VerifyFinal(EVP_MD_CTX *ctx, const uint8_t *sig, size_t sig_len,
-                    EVP_PKEY *pkey) {
+                    const EVP_PKEY *pkey) {
   uint8_t m[EVP_MAX_MD_SIZE];
   unsigned m_len;
   bssl::ScopedEVP_MD_CTX tmp_ctx;
@@ -85,11 +83,9 @@
   }
 
   bssl::UniquePtr<EVP_PKEY_CTX> pkctx(EVP_PKEY_CTX_new(pkey, nullptr));
-  if (!pkctx ||
-      !EVP_PKEY_verify_init(pkctx.get()) ||
+  if (!pkctx || !EVP_PKEY_verify_init(pkctx.get()) ||
       !EVP_PKEY_CTX_set_signature_md(pkctx.get(), ctx->digest)) {
     return 0;
   }
   return EVP_PKEY_verify(pkctx.get(), sig, sig_len, m, m_len);
 }
-
diff --git a/crypto/fipsmodule/dh/dh.cc.inc b/crypto/fipsmodule/dh/dh.cc.inc
index d018f76..8dfcdee 100644
--- a/crypto/fipsmodule/dh/dh.cc.inc
+++ b/crypto/fipsmodule/dh/dh.cc.inc
@@ -353,6 +353,13 @@
   return 1;
 }
 
+DH *DH_dup_ref(const DH *dh) {
+  if (dh == nullptr) {
+    return nullptr;
+  }
+  return FromOpaque(dh)->DupRefInternal();
+}
+
 DH *DH_get_rfc7919_2048() {
   // This is the prime from https://tools.ietf.org/html/rfc7919#appendix-A.1,
   // which is specifically approved for FIPS in appendix D of SP 800-56Ar3.
diff --git a/crypto/fipsmodule/digestsign/digestsign.cc.inc b/crypto/fipsmodule/digestsign/digestsign.cc.inc
index 8920546..a886d46 100644
--- a/crypto/fipsmodule/digestsign/digestsign.cc.inc
+++ b/crypto/fipsmodule/digestsign/digestsign.cc.inc
@@ -41,7 +41,7 @@
 }
 
 static int do_sigver_init(EVP_MD_CTX *ctx, EVP_PKEY_CTX **out_pctx,
-                          const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey,
+                          const EVP_MD *type, ENGINE *e, const EVP_PKEY *pkey,
                           enum evp_sign_verify_t op) {
   UniquePtr<EVP_PKEY_CTX> pctx(EVP_PKEY_CTX_new(pkey, e));
   if (pctx == nullptr) {
@@ -84,12 +84,12 @@
 }
 
 int EVP_DigestSignInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, const EVP_MD *type,
-                       ENGINE *e, EVP_PKEY *pkey) {
+                       ENGINE *e, const EVP_PKEY *pkey) {
   return do_sigver_init(ctx, pctx, type, e, pkey, evp_sign);
 }
 
 int EVP_DigestVerifyInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx,
-                         const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey) {
+                         const EVP_MD *type, ENGINE *e, const EVP_PKEY *pkey) {
   return do_sigver_init(ctx, pctx, type, e, pkey, evp_verify);
 }
 
@@ -143,8 +143,7 @@
   }
 }
 
-int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const uint8_t *sig,
-                          size_t sig_len) {
+int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const uint8_t *sig, size_t sig_len) {
   if (!uses_prehash(ctx->pctx, evp_verify)) {
     OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
     return 0;
diff --git a/crypto/fipsmodule/ec/ec_key.cc.inc b/crypto/fipsmodule/ec/ec_key.cc.inc
index e1e4e4b..078e541 100644
--- a/crypto/fipsmodule/ec/ec_key.cc.inc
+++ b/crypto/fipsmodule/ec/ec_key.cc.inc
@@ -150,9 +150,7 @@
   if (key == nullptr) {
     return nullptr;
   }
-  auto *ptr = const_cast<EC_KEY *>(key);
-  EC_KEY_up_ref(ptr);
-  return ptr;
+  return FromOpaque(key)->DupRefInternal();
 }
 
 int EC_KEY_is_opaque(const EC_KEY *key) {
diff --git a/crypto/fipsmodule/rsa/rsa.cc.inc b/crypto/fipsmodule/rsa/rsa.cc.inc
index 34a219f..cf406b2 100644
--- a/crypto/fipsmodule/rsa/rsa.cc.inc
+++ b/crypto/fipsmodule/rsa/rsa.cc.inc
@@ -225,9 +225,7 @@
   if (rsa == nullptr) {
     return nullptr;
   }
-  auto *ptr = const_cast<RSA *>(rsa);
-  RSA_up_ref(ptr);
-  return ptr;
+  return FromOpaque(rsa)->DupRefInternal();
 }
 
 unsigned RSA_bits(const RSA *rsa) {
diff --git a/crypto/mem_internal.h b/crypto/mem_internal.h
index 59927e1..488052f 100644
--- a/crypto/mem_internal.h
+++ b/crypto/mem_internal.h
@@ -135,6 +135,13 @@
     // ref-count variable.
     CRYPTO_refcount_inc(&references_);
   }
+
+  // Only the implementations of `FOO_dup_ref` should call these.
+  Derived *DupRefInternal() const {
+    UpRefInternal();
+    return const_cast<Derived *>(static_cast<const Derived *>(this));
+  }
+
   bool DecRefInternal() {
     if (CRYPTO_refcount_dec_and_test_zero(&references_)) {
       Derived *d = static_cast<Derived *>(this);
diff --git a/crypto/pkcs7/internal.h b/crypto/pkcs7/internal.h
index a6ab04e..66f8955 100644
--- a/crypto/pkcs7/internal.h
+++ b/crypto/pkcs7/internal.h
@@ -59,7 +59,7 @@
 //
 // Note: CMS v1 and PKCS#7 v1.5 are not completely compatible, but they overlap
 // in all cases implemented by this function.
-int pkcs7_add_external_signature(CBB *out, X509 *sign_cert, EVP_PKEY *key,
+int pkcs7_add_external_signature(CBB *out, X509 *sign_cert, const EVP_PKEY *key,
                                  const EVP_MD *md, BIO *data, bool use_key_id);
 
 BSSL_NAMESPACE_END
diff --git a/crypto/pkcs7/pkcs7_x509.cc b/crypto/pkcs7/pkcs7_x509.cc
index cb9a725..c179e3a 100644
--- a/crypto/pkcs7/pkcs7_x509.cc
+++ b/crypto/pkcs7/pkcs7_x509.cc
@@ -472,9 +472,9 @@
   return 1;
 }
 
-int bssl::pkcs7_add_external_signature(CBB *out, X509 *sign_cert, EVP_PKEY *key,
-                                       const EVP_MD *md, BIO *data,
-                                       bool use_key_id) {
+int bssl::pkcs7_add_external_signature(CBB *out, X509 *sign_cert,
+                                       const EVP_PKEY *key, const EVP_MD *md,
+                                       BIO *data, bool use_key_id) {
   signer_info_data si_data;
   si_data.use_key_id = use_key_id;
   si_data.sign_cert = sign_cert;
@@ -494,7 +494,7 @@
       /*cert_crl_cb=*/nullptr, write_signer_info, &si_data);
 }
 
-PKCS7 *PKCS7_sign(X509 *sign_cert, EVP_PKEY *pkey, STACK_OF(X509) *certs,
+PKCS7 *PKCS7_sign(X509 *sign_cert, const EVP_PKEY *pkey, STACK_OF(X509) *certs,
                   BIO *data, int flags) {
   ScopedCBB cbb;
   if (!CBB_init(cbb.get(), 2048)) {
diff --git a/crypto/pool/pool.cc b/crypto/pool/pool.cc
index a308ab8..21e2203 100644
--- a/crypto/pool/pool.cc
+++ b/crypto/pool/pool.cc
@@ -99,9 +99,7 @@
   if (pool == nullptr) {
     return nullptr;
   }
-  auto *ptr = const_cast<CRYPTO_BUFFER_POOL *>(pool);
-  CRYPTO_BUFFER_POOL_up_ref(ptr);
-  return ptr;
+  return FromOpaque(pool)->DupRefInternal();
 }
 
 void CryptoBuffer::UpRefInternal() const {
diff --git a/crypto/trust_token/trust_token.cc b/crypto/trust_token/trust_token.cc
index d0e5c24..b295a6b 100644
--- a/crypto/trust_token/trust_token.cc
+++ b/crypto/trust_token/trust_token.cc
@@ -279,13 +279,13 @@
   return 1;
 }
 
-int TRUST_TOKEN_CLIENT_set_srr_key(TRUST_TOKEN_CLIENT *ctx, EVP_PKEY *key) {
+int TRUST_TOKEN_CLIENT_set_srr_key(TRUST_TOKEN_CLIENT *ctx,
+                                   const EVP_PKEY *key) {
   if (!ctx->method->has_srr) {
     return 1;
   }
   EVP_PKEY_free(ctx->srr_key);
-  EVP_PKEY_up_ref(key);
-  ctx->srr_key = key;
+  ctx->srr_key = EVP_PKEY_dup_ref(key);
   return 1;
 }
 
@@ -515,10 +515,10 @@
   return 1;
 }
 
-int TRUST_TOKEN_ISSUER_set_srr_key(TRUST_TOKEN_ISSUER *ctx, EVP_PKEY *key) {
+int TRUST_TOKEN_ISSUER_set_srr_key(TRUST_TOKEN_ISSUER *ctx,
+                                   const EVP_PKEY *key) {
   EVP_PKEY_free(ctx->srr_key);
-  EVP_PKEY_up_ref(key);
-  ctx->srr_key = key;
+  ctx->srr_key = EVP_PKEY_dup_ref(key);
   return 1;
 }
 
diff --git a/crypto/x509/a_sign.cc b/crypto/x509/a_sign.cc
index 3e313d4..f09e80a 100644
--- a/crypto/x509/a_sign.cc
+++ b/crypto/x509/a_sign.cc
@@ -31,7 +31,7 @@
 using namespace bssl;
 
 int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2,
-                   ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey,
+                   ASN1_BIT_STRING *signature, void *asn, const EVP_PKEY *pkey,
                    const EVP_MD *type) {
   if (signature->type != V_ASN1_BIT_STRING) {
     OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TYPE);
diff --git a/crypto/x509/internal.h b/crypto/x509/internal.h
index a5e3629..9bf8d2c 100644
--- a/crypto/x509/internal.h
+++ b/crypto/x509/internal.h
@@ -61,7 +61,7 @@
 int x509_parse_public_key(CBS *cbs, X509_PUBKEY *out,
                           Span<const EVP_PKEY_ALG *const> algs);
 int x509_marshal_public_key(CBB *cbb, const X509_PUBKEY *in);
-int x509_pubkey_set1(X509_PUBKEY *key, EVP_PKEY *pkey);
+int x509_pubkey_set1(X509_PUBKEY *key, const EVP_PKEY *pkey);
 
 // X509_PUBKEY is an `ASN1_ITEM` whose ASN.1 type is SubjectPublicKeyInfo and C
 // type is `X509_PUBKEY*`.
diff --git a/crypto/x509/v3_purp.cc b/crypto/x509/v3_purp.cc
index e48c012..cf9f79e 100644
--- a/crypto/x509/v3_purp.cc
+++ b/crypto/x509/v3_purp.cc
@@ -342,7 +342,7 @@
 }
 
 int X509_check_ca(const X509 *x) {
-  if (!x509v3_cache_extensions(const_cast<X509*>(x))) {
+  if (!x509v3_cache_extensions(const_cast<X509 *>(x))) {
     return 0;
   }
   return check_ca(x);
diff --git a/crypto/x509/x509_lu.cc b/crypto/x509/x509_lu.cc
index 91c3b2d..c112679 100644
--- a/crypto/x509/x509_lu.cc
+++ b/crypto/x509/x509_lu.cc
@@ -153,9 +153,7 @@
   if (store == nullptr) {
     return nullptr;
   }
-  auto *ptr = const_cast<X509_STORE *>(store);
-  X509_STORE_up_ref(ptr);
-  return ptr;
+  return FromOpaque(store)->DupRefInternal();
 }
 
 void X509_STORE_free(X509_STORE *vfy) {
diff --git a/crypto/x509/x509_set.cc b/crypto/x509/x509_set.cc
index ae45063..2ede541 100644
--- a/crypto/x509/x509_set.cc
+++ b/crypto/x509/x509_set.cc
@@ -143,7 +143,7 @@
   }
 }
 
-int X509_set_pubkey(X509 *x, EVP_PKEY *pkey) {
+int X509_set_pubkey(X509 *x, const EVP_PKEY *pkey) {
   if (x == nullptr) {
     return 0;
   }
diff --git a/crypto/x509/x509cset.cc b/crypto/x509/x509cset.cc
index 19e938a..5ece53d 100644
--- a/crypto/x509/x509cset.cc
+++ b/crypto/x509/x509cset.cc
@@ -103,6 +103,15 @@
   return 1;
 }
 
+X509_CRL *X509_CRL_dup_ref(const X509_CRL *crl) {
+  if (crl == nullptr) {
+    return nullptr;
+  }
+  auto *ptr = const_cast<X509_CRL *>(crl);
+  CRYPTO_refcount_inc(&ptr->references);
+  return ptr;
+}
+
 long X509_CRL_get_version(const X509_CRL *crl) {
   return ASN1_INTEGER_get(crl->crl->version);
 }
diff --git a/crypto/x509/x_pubkey.cc b/crypto/x509/x_pubkey.cc
index 4862f1f..3d59a1e 100644
--- a/crypto/x509/x_pubkey.cc
+++ b/crypto/x509/x_pubkey.cc
@@ -118,7 +118,7 @@
 
 BSSL_NAMESPACE_END
 
-int bssl::x509_pubkey_set1(X509_PUBKEY *key, EVP_PKEY *pkey) {
+int bssl::x509_pubkey_set1(X509_PUBKEY *key, const EVP_PKEY *pkey) {
   ScopedCBB cbb;
   if (!CBB_init(cbb.get(), 64) || !EVP_marshal_public_key(cbb.get(), pkey)) {
     OPENSSL_PUT_ERROR(X509, X509_R_PUBLIC_KEY_ENCODE_ERROR);
diff --git a/crypto/x509/x_x509.cc b/crypto/x509/x_x509.cc
index 9a5493d..a2f1f1d 100644
--- a/crypto/x509/x_x509.cc
+++ b/crypto/x509/x_x509.cc
@@ -331,9 +331,7 @@
   if (x == nullptr) {
     return nullptr;
   }
-  auto *x_ref = const_cast<X509 *>(x);
-  X509_up_ref(x_ref);
-  return x_ref;
+  return FromOpaque(x)->DupRefInternal();
 }
 
 int X509_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused,
diff --git a/include/openssl/base.h b/include/openssl/base.h
index 4e075b3..e2741eb 100644
--- a/include/openssl/base.h
+++ b/include/openssl/base.h
@@ -395,7 +395,7 @@
 #if defined(BORINGSSL_NO_CXX)
 
 #define BORINGSSL_MAKE_DELETER(type, deleter)
-#define BORINGSSL_MAKE_UP_REF(type, up_ref_func)
+#define BORINGSSL_MAKE_UP_REF(type, dup_ref_func)
 #define BORINGSSL_MAKE_STACK_TRAITS(type, init_func, cleanup_func)
 #define BORINGSSL_MAKE_STACK_TRAITS_MOVABLE(type, init_func, cleanup_func, \
                                             move_func)
@@ -527,12 +527,9 @@
 template <typename T>
 using UniquePtr = std::unique_ptr<T, internal::Deleter>;
 
-#define BORINGSSL_MAKE_UP_REF(type, up_ref_func)             \
-  inline UniquePtr<type> UpRef(type *v) {                    \
-    if (v != nullptr) {                                      \
-      up_ref_func(v);                                        \
-    }                                                        \
-    return UniquePtr<type>(v);                               \
+#define BORINGSSL_MAKE_UP_REF(type, dup_ref_func)            \
+  inline UniquePtr<type> UpRef(const type *v) {              \
+    return UniquePtr<type>(dup_ref_func(v));                 \
   }                                                          \
                                                              \
   inline UniquePtr<type> UpRef(const UniquePtr<type> &ptr) { \
diff --git a/include/openssl/bio.h b/include/openssl/bio.h
index 630be3e..48ee4ae 100644
--- a/include/openssl/bio.h
+++ b/include/openssl/bio.h
@@ -15,7 +15,7 @@
 #ifndef OPENSSL_HEADER_BIO_H
 #define OPENSSL_HEADER_BIO_H
 
-#include <openssl/base.h>   // IWYU pragma: export
+#include <openssl/base.h>  // IWYU pragma: export
 
 #include <stdio.h>  // For FILE
 
@@ -65,6 +65,10 @@
 // BIO_up_ref increments the reference count of `bio` and returns one.
 OPENSSL_EXPORT int BIO_up_ref(BIO *bio);
 
+// BIO_dup_ref increments the reference count of `bio` and returns the same
+// handle.
+OPENSSL_EXPORT BIO *BIO_dup_ref(const BIO *bio);
+
 
 // Basic I/O.
 
@@ -613,18 +617,20 @@
 
 #define BIO_CTRL_DGRAM_QUERY_MTU 40  // as kernel for current MTU
 
-#define BIO_CTRL_DGRAM_SET_MTU 42 /* set cached value for  MTU. want to use
-                                     this if asking the kernel fails */
+#define BIO_CTRL_DGRAM_SET_MTU                 \
+  42 /* set cached value for  MTU. want to use \
+        this if asking the kernel fails */
 
-#define BIO_CTRL_DGRAM_MTU_EXCEEDED 43 /* check whether the MTU was exceed in
-                                          the previous write operation. */
+#define BIO_CTRL_DGRAM_MTU_EXCEEDED         \
+  43 /* check whether the MTU was exceed in \
+        the previous write operation. */
 
 // BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT is unsupported as it is unused by consumers
 // and depends on `timeval`, which is not 2038-clean on all platforms.
 
-#define BIO_CTRL_DGRAM_GET_PEER           46
+#define BIO_CTRL_DGRAM_GET_PEER 46
 
-#define BIO_CTRL_DGRAM_GET_FALLBACK_MTU   47
+#define BIO_CTRL_DGRAM_GET_FALLBACK_MTU 47
 
 
 // BIO Pairs.
@@ -1031,7 +1037,7 @@
 BSSL_NAMESPACE_BEGIN
 
 BORINGSSL_MAKE_DELETER(BIO, BIO_free)
-BORINGSSL_MAKE_UP_REF(BIO, BIO_up_ref)
+BORINGSSL_MAKE_UP_REF(BIO, BIO_dup_ref)
 BORINGSSL_MAKE_DELETER(BIO_METHOD, BIO_meth_free)
 
 BSSL_NAMESPACE_END
diff --git a/include/openssl/cms.h b/include/openssl/cms.h
index d365a46..5a44517 100644
--- a/include/openssl/cms.h
+++ b/include/openssl/cms.h
@@ -15,7 +15,7 @@
 #ifndef OPENSSL_HEADER_CMS_H
 #define OPENSSL_HEADER_CMS_H
 
-#include <openssl/base.h>   // IWYU pragma: export
+#include <openssl/base.h>  // IWYU pragma: export
 
 #include <openssl/stack.h>
 
@@ -69,8 +69,9 @@
 // incomplete. `data` will then be ignored and should be NULL. The caller can
 // then continue configuring it and finalizing it with `CMS_final`. Otherwise,
 // the object will be finalized with `data` and `flags` passed to `CMS_final`.
-OPENSSL_EXPORT CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey,
-                                         STACK_OF(X509) *certs, BIO *data,
+OPENSSL_EXPORT CMS_ContentInfo *CMS_sign(const X509 *signcert,
+                                         const EVP_PKEY *pkey,
+                                         const STACK_OF(X509) *certs, BIO *data,
                                          uint32_t flags);
 
 // CMS_ContentInfo_free releases memory associated with `cms`.
@@ -102,7 +103,8 @@
 // Subsequent calls will fail. Additionally, only RSA keys are currently
 // supported for `pkey`.
 OPENSSL_EXPORT CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms,
-                                               X509 *signcert, EVP_PKEY *pkey,
+                                               const X509 *signcert,
+                                               const EVP_PKEY *pkey,
                                                const EVP_MD *md,
                                                uint32_t flags);
 
diff --git a/include/openssl/dh.h b/include/openssl/dh.h
index 59e8c9c..6cb5d9e 100644
--- a/include/openssl/dh.h
+++ b/include/openssl/dh.h
@@ -15,7 +15,7 @@
 #ifndef OPENSSL_HEADER_DH_H
 #define OPENSSL_HEADER_DH_H
 
-#include <openssl/base.h>   // IWYU pragma: export
+#include <openssl/base.h>  // IWYU pragma: export
 
 #if defined(__cplusplus)
 extern "C" {
@@ -49,6 +49,11 @@
 // mutate `dh` for thread-safety purposes and may be used concurrently.
 OPENSSL_EXPORT int DH_up_ref(DH *dh);
 
+// DH_dup_ref increments the reference count of `dh` and returns the same
+// handle. It does not mutate `dh` for thread-safety purposes and may be used
+// concurrently.
+OPENSSL_EXPORT DH *DH_dup_ref(const DH *dh);
+
 
 // Properties.
 
@@ -317,7 +322,7 @@
 BSSL_NAMESPACE_BEGIN
 
 BORINGSSL_MAKE_DELETER(DH, DH_free)
-BORINGSSL_MAKE_UP_REF(DH, DH_up_ref)
+BORINGSSL_MAKE_UP_REF(DH, DH_dup_ref)
 
 BSSL_NAMESPACE_END
 
diff --git a/include/openssl/dsa.h b/include/openssl/dsa.h
index 3ae4d11..a77bf91 100644
--- a/include/openssl/dsa.h
+++ b/include/openssl/dsa.h
@@ -375,7 +375,7 @@
 BSSL_NAMESPACE_BEGIN
 
 BORINGSSL_MAKE_DELETER(DSA, DSA_free)
-BORINGSSL_MAKE_UP_REF(DSA, DSA_up_ref)
+BORINGSSL_MAKE_UP_REF(DSA, DSA_dup_ref)
 BORINGSSL_MAKE_DELETER(DSA_SIG, DSA_SIG_free)
 
 BSSL_NAMESPACE_END
diff --git a/include/openssl/ec_key.h b/include/openssl/ec_key.h
index d894a67..296b7c0 100644
--- a/include/openssl/ec_key.h
+++ b/include/openssl/ec_key.h
@@ -352,7 +352,7 @@
 BSSL_NAMESPACE_BEGIN
 
 BORINGSSL_MAKE_DELETER(EC_KEY, EC_KEY_free)
-BORINGSSL_MAKE_UP_REF(EC_KEY, EC_KEY_up_ref)
+BORINGSSL_MAKE_UP_REF(EC_KEY, EC_KEY_dup_ref)
 
 BSSL_NAMESPACE_END
 
diff --git a/include/openssl/evp.h b/include/openssl/evp.h
index 8a767ca..4af1726 100644
--- a/include/openssl/evp.h
+++ b/include/openssl/evp.h
@@ -498,13 +498,10 @@
 // Ed25519, `type` should be NULL. The `EVP_MD_CTX` itself is unused but is
 // present so the API is uniform. See `EVP_DigestSign`.
 //
-// This function does not mutate `pkey` for thread-safety purposes and may be
-// used concurrently with other non-mutating functions on `pkey`.
-//
 // It returns one on success, or zero on error.
 OPENSSL_EXPORT int EVP_DigestSignInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx,
                                       const EVP_MD *type, ENGINE *e,
-                                      EVP_PKEY *pkey);
+                                      const EVP_PKEY *pkey);
 
 // EVP_DigestSignUpdate appends `len` bytes from `data` to the data which will
 // be signed in `EVP_DigestSignFinal`. It returns one.
@@ -554,13 +551,10 @@
 // Ed25519, `type` should be NULL. The `EVP_MD_CTX` itself is unused but is
 // present so the API is uniform. See `EVP_DigestVerify`.
 //
-// This function does not mutate `pkey` for thread-safety purposes and may be
-// used concurrently with other non-mutating functions on `pkey`.
-//
 // It returns one on success, or zero on error.
 OPENSSL_EXPORT int EVP_DigestVerifyInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx,
                                         const EVP_MD *type, ENGINE *e,
-                                        EVP_PKEY *pkey);
+                                        const EVP_PKEY *pkey);
 
 // EVP_DigestVerifyUpdate appends `len` bytes from `data` to the data which
 // will be verified by `EVP_DigestVerifyFinal`. It returns one.
@@ -615,13 +609,9 @@
 // actual size of the signature is written to `*out_sig_len`.
 //
 // It returns one on success and zero otherwise.
-//
-// It does not modify `ctx`, thus it's possible to continue to use `ctx` in
-// order to sign a longer message. It also does not mutate `pkey` for
-// thread-safety purposes and may be used concurrently with other non-mutating
-// functions on `pkey`.
 OPENSSL_EXPORT int EVP_SignFinal(const EVP_MD_CTX *ctx, uint8_t *sig,
-                                 unsigned int *out_sig_len, EVP_PKEY *pkey);
+                                 unsigned int *out_sig_len,
+                                 const EVP_PKEY *pkey);
 
 
 // Verifying (old functions)
@@ -650,13 +640,8 @@
 // calls to `EVP_VerifyUpdate`.
 //
 // It returns one on success and zero otherwise.
-//
-// It does not modify `ctx`, thus it's possible to continue to use `ctx` in
-// order to verify a longer message. It also does not mutate `pkey` for
-// thread-safety purposes and may be used concurrently with other non-mutating
-// functions on `pkey`.
 OPENSSL_EXPORT int EVP_VerifyFinal(EVP_MD_CTX *ctx, const uint8_t *sig,
-                                   size_t sig_len, EVP_PKEY *pkey);
+                                   size_t sig_len, const EVP_PKEY *pkey);
 
 
 // Printing
@@ -752,7 +737,7 @@
 
 // EVP_PKEY_CTX_new allocates a fresh `EVP_PKEY_CTX` for use with `pkey`. It
 // returns the context or NULL on error.
-OPENSSL_EXPORT EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e);
+OPENSSL_EXPORT EVP_PKEY_CTX *EVP_PKEY_CTX_new(const EVP_PKEY *pkey, ENGINE *e);
 
 // EVP_PKEY_CTX_new_id allocates a fresh `EVP_PKEY_CTX` for a key of type `id`
 // (e.g. `EVP_PKEY_HMAC`). This can be used for key generation where
@@ -770,7 +755,7 @@
 OPENSSL_EXPORT EVP_PKEY_CTX *EVP_PKEY_CTX_dup(EVP_PKEY_CTX *ctx);
 
 // EVP_PKEY_CTX_get0_pkey returns the `EVP_PKEY` associated with `ctx`.
-OPENSSL_EXPORT EVP_PKEY *EVP_PKEY_CTX_get0_pkey(EVP_PKEY_CTX *ctx);
+OPENSSL_EXPORT EVP_PKEY *EVP_PKEY_CTX_get0_pkey(const EVP_PKEY_CTX *ctx);
 
 // EVP_PKEY_sign_init initialises an `EVP_PKEY_CTX` for a signing operation. It
 // should be called before `EVP_PKEY_sign`.
@@ -897,7 +882,8 @@
 // by `ctx` to `peer`. It should be called after `EVP_PKEY_derive_init`. (For
 // example, this is used to set the peer's key in (EC)DH.) It returns one on
 // success and zero on error.
-OPENSSL_EXPORT int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer);
+OPENSSL_EXPORT int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx,
+                                            const EVP_PKEY *peer);
 
 // EVP_PKEY_derive derives a shared key from `ctx`. If `key` is non-NULL then,
 // on entry, `out_key_len` must contain the amount of space at `key`. If
@@ -1633,7 +1619,7 @@
 BSSL_NAMESPACE_BEGIN
 
 BORINGSSL_MAKE_DELETER(EVP_PKEY, EVP_PKEY_free)
-BORINGSSL_MAKE_UP_REF(EVP_PKEY, EVP_PKEY_up_ref)
+BORINGSSL_MAKE_UP_REF(EVP_PKEY, EVP_PKEY_dup_ref)
 BORINGSSL_MAKE_DELETER(EVP_PKEY_CTX, EVP_PKEY_CTX_free)
 
 BSSL_NAMESPACE_END
diff --git a/include/openssl/pkcs7.h b/include/openssl/pkcs7.h
index 85c851e..b8f5b2b 100644
--- a/include/openssl/pkcs7.h
+++ b/include/openssl/pkcs7.h
@@ -15,7 +15,7 @@
 #ifndef OPENSSL_HEADER_PKCS7_H
 #define OPENSSL_HEADER_PKCS7_H
 
-#include <openssl/base.h>   // IWYU pragma: export
+#include <openssl/base.h>  // IWYU pragma: export
 
 #include <openssl/stack.h>
 
@@ -59,8 +59,8 @@
 
 // PKCS7_bundle_certificates behaves like `PKCS7_bundle_raw_certificates` but
 // takes `X509` objects as input.
-OPENSSL_EXPORT int PKCS7_bundle_certificates(
-    CBB *out, const STACK_OF(X509) *certs);
+OPENSSL_EXPORT int PKCS7_bundle_certificates(CBB *out,
+                                             const STACK_OF(X509) *certs);
 
 // PKCS7_get_CRLs parses a PKCS#7, SignedData structure from `cbs` and appends
 // the included CRLs to `out_crls`. It returns one on success and zero on error.
@@ -144,8 +144,7 @@
 
 // d2i_PKCS7 parses a BER-encoded, PKCS#7 signed data ContentInfo structure from
 // `len` bytes at `*inp`, as described in `d2i_SAMPLE`.
-OPENSSL_EXPORT PKCS7 *d2i_PKCS7(PKCS7 **out, const uint8_t **inp,
-                                size_t len);
+OPENSSL_EXPORT PKCS7 *d2i_PKCS7(PKCS7 **out, const uint8_t **inp, size_t len);
 
 // d2i_PKCS7_bio behaves like `d2i_PKCS7` but reads the input from `bio`.  If
 // the length of the object is indefinite the full contents of `bio` are read.
@@ -215,7 +214,7 @@
 //
 // Note this function only implements a subset of the corresponding OpenSSL
 // function. It is provided for backwards compatibility only.
-OPENSSL_EXPORT PKCS7 *PKCS7_sign(X509 *sign_cert, EVP_PKEY *pkey,
+OPENSSL_EXPORT PKCS7 *PKCS7_sign(X509 *sign_cert, const EVP_PKEY *pkey,
                                  STACK_OF(X509) *certs, BIO *data, int flags);
 
 
diff --git a/include/openssl/pool.h b/include/openssl/pool.h
index 6eb759c..2c3855b 100644
--- a/include/openssl/pool.h
+++ b/include/openssl/pool.h
@@ -130,9 +130,9 @@
 BSSL_NAMESPACE_BEGIN
 
 BORINGSSL_MAKE_DELETER(CRYPTO_BUFFER_POOL, CRYPTO_BUFFER_POOL_free)
-BORINGSSL_MAKE_UP_REF(CRYPTO_BUFFER_POOL, CRYPTO_BUFFER_POOL_up_ref)
+BORINGSSL_MAKE_UP_REF(CRYPTO_BUFFER_POOL, CRYPTO_BUFFER_POOL_dup_ref)
 BORINGSSL_MAKE_DELETER(CRYPTO_BUFFER, CRYPTO_BUFFER_free)
-BORINGSSL_MAKE_UP_REF(CRYPTO_BUFFER, CRYPTO_BUFFER_up_ref)
+BORINGSSL_MAKE_UP_REF(CRYPTO_BUFFER, CRYPTO_BUFFER_dup_ref)
 
 BSSL_NAMESPACE_END
 
diff --git a/include/openssl/prefix_symbols.h b/include/openssl/prefix_symbols.h
index 65fffbb..9a25eb8 100644
--- a/include/openssl/prefix_symbols.h
+++ b/include/openssl/prefix_symbols.h
@@ -233,6 +233,7 @@
 #pragma redefine_extname BIO_ctrl_get_write_guarantee BORINGSSL_ADD_USER_LABEL_AND_PREFIX(BIO_ctrl_get_write_guarantee)
 #pragma redefine_extname BIO_ctrl_pending BORINGSSL_ADD_USER_LABEL_AND_PREFIX(BIO_ctrl_pending)
 #pragma redefine_extname BIO_do_connect BORINGSSL_ADD_USER_LABEL_AND_PREFIX(BIO_do_connect)
+#pragma redefine_extname BIO_dup_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(BIO_dup_ref)
 #pragma redefine_extname BIO_eof BORINGSSL_ADD_USER_LABEL_AND_PREFIX(BIO_eof)
 #pragma redefine_extname BIO_f_base64 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(BIO_f_base64)
 #pragma redefine_extname BIO_f_ssl BORINGSSL_ADD_USER_LABEL_AND_PREFIX(BIO_f_ssl)
@@ -698,6 +699,7 @@
 #pragma redefine_extname DH_compute_key BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DH_compute_key)
 #pragma redefine_extname DH_compute_key_hashed BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DH_compute_key_hashed)
 #pragma redefine_extname DH_compute_key_padded BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DH_compute_key_padded)
+#pragma redefine_extname DH_dup_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DH_dup_ref)
 #pragma redefine_extname DH_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DH_free)
 #pragma redefine_extname DH_generate_key BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DH_generate_key)
 #pragma redefine_extname DH_generate_parameters BORINGSSL_ADD_USER_LABEL_AND_PREFIX(DH_generate_parameters)
@@ -2580,6 +2582,7 @@
 #pragma redefine_extname X509_CRL_delete_ext BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_CRL_delete_ext)
 #pragma redefine_extname X509_CRL_digest BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_CRL_digest)
 #pragma redefine_extname X509_CRL_dup BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_CRL_dup)
+#pragma redefine_extname X509_CRL_dup_ref BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_CRL_dup_ref)
 #pragma redefine_extname X509_CRL_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_CRL_free)
 #pragma redefine_extname X509_CRL_get0_by_cert BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_CRL_get0_by_cert)
 #pragma redefine_extname X509_CRL_get0_by_serial BORINGSSL_ADD_USER_LABEL_AND_PREFIX(X509_CRL_get0_by_serial)
@@ -3397,6 +3400,7 @@
 #define BIO_ctrl_get_write_guarantee BORINGSSL_ADD_PREFIX(BIO_ctrl_get_write_guarantee)
 #define BIO_ctrl_pending BORINGSSL_ADD_PREFIX(BIO_ctrl_pending)
 #define BIO_do_connect BORINGSSL_ADD_PREFIX(BIO_do_connect)
+#define BIO_dup_ref BORINGSSL_ADD_PREFIX(BIO_dup_ref)
 #define BIO_eof BORINGSSL_ADD_PREFIX(BIO_eof)
 #define BIO_f_base64 BORINGSSL_ADD_PREFIX(BIO_f_base64)
 #define BIO_f_ssl BORINGSSL_ADD_PREFIX(BIO_f_ssl)
@@ -3862,6 +3866,7 @@
 #define DH_compute_key BORINGSSL_ADD_PREFIX(DH_compute_key)
 #define DH_compute_key_hashed BORINGSSL_ADD_PREFIX(DH_compute_key_hashed)
 #define DH_compute_key_padded BORINGSSL_ADD_PREFIX(DH_compute_key_padded)
+#define DH_dup_ref BORINGSSL_ADD_PREFIX(DH_dup_ref)
 #define DH_free BORINGSSL_ADD_PREFIX(DH_free)
 #define DH_generate_key BORINGSSL_ADD_PREFIX(DH_generate_key)
 #define DH_generate_parameters BORINGSSL_ADD_PREFIX(DH_generate_parameters)
@@ -5744,6 +5749,7 @@
 #define X509_CRL_delete_ext BORINGSSL_ADD_PREFIX(X509_CRL_delete_ext)
 #define X509_CRL_digest BORINGSSL_ADD_PREFIX(X509_CRL_digest)
 #define X509_CRL_dup BORINGSSL_ADD_PREFIX(X509_CRL_dup)
+#define X509_CRL_dup_ref BORINGSSL_ADD_PREFIX(X509_CRL_dup_ref)
 #define X509_CRL_free BORINGSSL_ADD_PREFIX(X509_CRL_free)
 #define X509_CRL_get0_by_cert BORINGSSL_ADD_PREFIX(X509_CRL_get0_by_cert)
 #define X509_CRL_get0_by_serial BORINGSSL_ADD_PREFIX(X509_CRL_get0_by_serial)
diff --git a/include/openssl/rsa.h b/include/openssl/rsa.h
index 1abc611..f7c6cfa 100644
--- a/include/openssl/rsa.h
+++ b/include/openssl/rsa.h
@@ -837,7 +837,7 @@
 BSSL_NAMESPACE_BEGIN
 
 BORINGSSL_MAKE_DELETER(RSA, RSA_free)
-BORINGSSL_MAKE_UP_REF(RSA, RSA_up_ref)
+BORINGSSL_MAKE_UP_REF(RSA, RSA_dup_ref)
 
 BSSL_NAMESPACE_END
 
diff --git a/include/openssl/ssl.h b/include/openssl/ssl.h
index 06f01db..6960f1e 100644
--- a/include/openssl/ssl.h
+++ b/include/openssl/ssl.h
@@ -6167,13 +6167,13 @@
 
 BORINGSSL_MAKE_DELETER(SSL, SSL_free)
 BORINGSSL_MAKE_DELETER(SSL_CREDENTIAL, SSL_CREDENTIAL_free)
-BORINGSSL_MAKE_UP_REF(SSL_CREDENTIAL, SSL_CREDENTIAL_up_ref)
+BORINGSSL_MAKE_UP_REF(SSL_CREDENTIAL, SSL_CREDENTIAL_dup_ref)
 BORINGSSL_MAKE_DELETER(SSL_CTX, SSL_CTX_free)
-BORINGSSL_MAKE_UP_REF(SSL_CTX, SSL_CTX_up_ref)
+BORINGSSL_MAKE_UP_REF(SSL_CTX, SSL_CTX_dup_ref)
 BORINGSSL_MAKE_DELETER(SSL_ECH_KEYS, SSL_ECH_KEYS_free)
-BORINGSSL_MAKE_UP_REF(SSL_ECH_KEYS, SSL_ECH_KEYS_up_ref)
+BORINGSSL_MAKE_UP_REF(SSL_ECH_KEYS, SSL_ECH_KEYS_dup_ref)
 BORINGSSL_MAKE_DELETER(SSL_SESSION, SSL_SESSION_free)
-BORINGSSL_MAKE_UP_REF(SSL_SESSION, SSL_SESSION_up_ref)
+BORINGSSL_MAKE_UP_REF(SSL_SESSION, SSL_SESSION_dup_ref)
 
 // SSL_get_traffic_secrets sets `*out_read_traffic_secret` and
 // `*out_write_traffic_secret` to reference the current TLS 1.3 traffic secrets
diff --git a/include/openssl/trust_token.h b/include/openssl/trust_token.h
index cf909ae..e0fbcea 100644
--- a/include/openssl/trust_token.h
+++ b/include/openssl/trust_token.h
@@ -15,7 +15,7 @@
 #ifndef OPENSSL_HEADER_TRUST_TOKEN_H
 #define OPENSSL_HEADER_TRUST_TOKEN_H
 
-#include <openssl/base.h>   // IWYU pragma: export
+#include <openssl/base.h>  // IWYU pragma: export
 #include <openssl/stack.h>
 
 #if defined(__cplusplus)
@@ -152,7 +152,7 @@
 // TRUST_TOKEN_CLIENT_set_srr_key sets the public key used to verify the SRR. It
 // returns one on success and zero on error.
 OPENSSL_EXPORT int TRUST_TOKEN_CLIENT_set_srr_key(TRUST_TOKEN_CLIENT *ctx,
-                                                  EVP_PKEY *key);
+                                                  const EVP_PKEY *key);
 
 // TRUST_TOKEN_CLIENT_begin_issuance produces a request for `count` trust tokens
 // and serializes the request into a newly-allocated buffer, setting `*out` to
@@ -180,11 +180,9 @@
 // arrives without the specified key present. The caller takes ownership of the
 // list and must call `sk_TRUST_TOKEN_pop_free` when done. The list is empty if
 // issuance fails.
-OPENSSL_EXPORT STACK_OF(TRUST_TOKEN) *
-    TRUST_TOKEN_CLIENT_finish_issuance(TRUST_TOKEN_CLIENT *ctx,
-                                       size_t *out_key_index,
-                                       const uint8_t *response,
-                                       size_t response_len);
+OPENSSL_EXPORT STACK_OF(TRUST_TOKEN) *TRUST_TOKEN_CLIENT_finish_issuance(
+    TRUST_TOKEN_CLIENT *ctx, size_t *out_key_index, const uint8_t *response,
+    size_t response_len);
 
 
 // TRUST_TOKEN_CLIENT_begin_redemption produces a request to redeem a token
@@ -243,7 +241,7 @@
 // TRUST_TOKEN_ISSUER_set_srr_key sets the private key used to sign the SRR. It
 // returns one on success and zero on error.
 OPENSSL_EXPORT int TRUST_TOKEN_ISSUER_set_srr_key(TRUST_TOKEN_ISSUER *ctx,
-                                                  EVP_PKEY *key);
+                                                  const EVP_PKEY *key);
 
 // TRUST_TOKEN_ISSUER_issue ingests `request` for token issuance
 // and generates up to `max_issuance` valid tokens, producing a list of blinded
diff --git a/include/openssl/x509.h b/include/openssl/x509.h
index 9271654..3cbd863 100644
--- a/include/openssl/x509.h
+++ b/include/openssl/x509.h
@@ -486,9 +486,8 @@
 OPENSSL_EXPORT int X509_set_subject_name(X509 *x509, const X509_NAME *name);
 
 // X509_set_pubkey sets `x509`'s public key to `pkey`. It returns one on success
-// and zero on error. This function does not take ownership of `pkey` and
-// internally copies and updates reference counts as needed.
-OPENSSL_EXPORT int X509_set_pubkey(X509 *x509, EVP_PKEY *pkey);
+// and zero on error.
+OPENSSL_EXPORT int X509_set_pubkey(X509 *x509, const EVP_PKEY *pkey);
 
 // X509_delete_ext removes the extension in `x` at index `loc` and returns the
 // removed extension, or NULL if `loc` was out of bounds. If non-NULL, the
@@ -682,6 +681,10 @@
 // X509_CRL_up_ref adds one to the reference count of `crl` and returns one.
 OPENSSL_EXPORT int X509_CRL_up_ref(X509_CRL *crl);
 
+// X509_CRL_dup_ref adds one to the reference count of `crl` and returns the
+// same.
+OPENSSL_EXPORT X509_CRL *X509_CRL_dup_ref(const X509_CRL *crl);
+
 // X509_CRL_dup returns a newly-allocated copy of `crl`, or NULL on error. This
 // function works by serializing the structure, so if `crl` is incomplete, it
 // may fail.
@@ -4519,7 +4522,7 @@
 OPENSSL_EXPORT int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1,
                                   X509_ALGOR *algor2,
                                   ASN1_BIT_STRING *signature, void *data,
-                                  EVP_PKEY *pkey, const EVP_MD *type);
+                                  const EVP_PKEY *pkey, const EVP_MD *type);
 
 // ASN1_item_sign_ctx behaves like `ASN1_item_sign` except the signature is
 // signed with `ctx`, `ctx`, which must have been initialized with
@@ -5333,11 +5336,11 @@
 BORINGSSL_MAKE_DELETER(RSA_PSS_PARAMS, RSA_PSS_PARAMS_free)
 BORINGSSL_MAKE_DELETER(USERNOTICE, USERNOTICE_free)
 BORINGSSL_MAKE_DELETER(X509, X509_free)
-BORINGSSL_MAKE_UP_REF(X509, X509_up_ref)
+BORINGSSL_MAKE_UP_REF(X509, X509_dup_ref)
 BORINGSSL_MAKE_DELETER(X509_ALGOR, X509_ALGOR_free)
 BORINGSSL_MAKE_DELETER(X509_ATTRIBUTE, X509_ATTRIBUTE_free)
 BORINGSSL_MAKE_DELETER(X509_CRL, X509_CRL_free)
-BORINGSSL_MAKE_UP_REF(X509_CRL, X509_CRL_up_ref)
+BORINGSSL_MAKE_UP_REF(X509_CRL, X509_CRL_dup_ref)
 BORINGSSL_MAKE_DELETER(X509_EXTENSION, X509_EXTENSION_free)
 BORINGSSL_MAKE_DELETER(X509_INFO, X509_INFO_free)
 BORINGSSL_MAKE_DELETER(X509_LOOKUP, X509_LOOKUP_free)
@@ -5349,7 +5352,7 @@
 BORINGSSL_MAKE_DELETER(X509_REVOKED, X509_REVOKED_free)
 BORINGSSL_MAKE_DELETER(X509_SIG, X509_SIG_free)
 BORINGSSL_MAKE_DELETER(X509_STORE, X509_STORE_free)
-BORINGSSL_MAKE_UP_REF(X509_STORE, X509_STORE_up_ref)
+BORINGSSL_MAKE_UP_REF(X509_STORE, X509_STORE_dup_ref)
 BORINGSSL_MAKE_DELETER(X509_STORE_CTX, X509_STORE_CTX_free)
 BORINGSSL_MAKE_DELETER(X509_VERIFY_PARAM, X509_VERIFY_PARAM_free)
 
diff --git a/pki/simple_path_builder_delegate.cc b/pki/simple_path_builder_delegate.cc
index 2a96ab0..15db9bf 100644
--- a/pki/simple_path_builder_delegate.cc
+++ b/pki/simple_path_builder_delegate.cc
@@ -27,7 +27,6 @@
 #include "cert_error_params.h"
 #include "cert_errors.h"
 #include "signature_algorithm.h"
-#include "verify_signed_data.h"
 
 BSSL_NAMESPACE_BEGIN
 
@@ -74,7 +73,7 @@
 }
 
 bool SimplePathBuilderDelegate::IsCosignatureVerificationResultAcceptable(
-    const MTCAnchor* mtc_anchor,
+    const MTCAnchor *mtc_anchor,
     std::vector<std::vector<uint8_t>> valid_additional_cosigners) {
   return true;
 }
@@ -111,8 +110,8 @@
   return false;
 }
 
-bool SimplePathBuilderDelegate::IsPublicKeyAcceptable(EVP_PKEY *public_key,
-                                                      CertErrors *errors) {
+bool SimplePathBuilderDelegate::IsPublicKeyAcceptable(
+    const EVP_PKEY *public_key, CertErrors *errors) {
   int pkey_id = EVP_PKEY_id(public_key);
   if (pkey_id == EVP_PKEY_RSA) {
     // Extract the modulus length from the key.
diff --git a/pki/simple_path_builder_delegate.h b/pki/simple_path_builder_delegate.h
index c78a948..bdfed65 100644
--- a/pki/simple_path_builder_delegate.h
+++ b/pki/simple_path_builder_delegate.h
@@ -62,7 +62,8 @@
                                       CertErrors *errors) override;
 
   // Requires RSA keys be >= `min_rsa_modulus_length_bits_`.
-  bool IsPublicKeyAcceptable(EVP_PKEY *public_key, CertErrors *errors) override;
+  bool IsPublicKeyAcceptable(const EVP_PKEY *public_key,
+                             CertErrors *errors) override;
 
   // No-op implementation.
   void CheckPathAfterVerification(const CertPathBuilder &path_builder,
@@ -89,7 +90,7 @@
 
   // No-op implementation (does not require any valid additional cosigners).
   bool IsCosignatureVerificationResultAcceptable(
-      const MTCAnchor* mtc_anchor,
+      const MTCAnchor *mtc_anchor,
       std::vector<std::vector<uint8_t>> valid_additional_cosigners) override;
 
  private:
diff --git a/pki/verify_certificate_chain.h b/pki/verify_certificate_chain.h
index 7d4f814..f9f6cf4 100644
--- a/pki/verify_certificate_chain.h
+++ b/pki/verify_certificate_chain.h
@@ -47,8 +47,8 @@
                        // certificate.
   CLIENT_AUTH_STRICT_LEAF,  // Same as above, but only for leaf cert.
   RCS_MLS_CLIENT_AUTH,      // Client auth for RCS-MLS.
-  C2PA_TIMESTAMPING,    // Leaf can sign timestamps for C2PA.
-  C2PA_MANIFEST,        // Leaf can sign manifests for C2PA.
+  C2PA_TIMESTAMPING,        // Leaf can sign timestamps for C2PA.
+  C2PA_MANIFEST,            // Leaf can sign manifests for C2PA.
 };
 
 enum class InitialExplicitPolicy {
@@ -87,7 +87,7 @@
   // implementations may add any further details on why the public key was
   // deemed unacceptable by adding warnings to `errors`.  `public_key` can be
   // assumed to be non-null.
-  virtual bool IsPublicKeyAcceptable(EVP_PKEY *public_key,
+  virtual bool IsPublicKeyAcceptable(const EVP_PKEY *public_key,
                                      CertErrors *errors) = 0;
 
   // This is called during verification to obtain a pointer to a signature
@@ -121,7 +121,7 @@
   // the cosigner_ids of the additional valid cosigners, if any, and will not
   // contain the `ca_id` of `mtc_anchor`.
   virtual bool IsCosignatureVerificationResultAcceptable(
-      const MTCAnchor* mtc_anchor,
+      const MTCAnchor *mtc_anchor,
       std::vector<std::vector<uint8_t>> valid_additional_cosigners) = 0;
 
   // This is called during verification or path building to decide if debug
diff --git a/pki/verify_signed_data.cc b/pki/verify_signed_data.cc
index 6caa753..352a9da 100644
--- a/pki/verify_signed_data.cc
+++ b/pki/verify_signed_data.cc
@@ -24,7 +24,6 @@
 #include <openssl/rsa.h>
 #include <openssl/sha2.h>
 
-#include "cert_errors.h"
 #include "input.h"
 #include "parse_values.h"
 #include "parser.h"
@@ -48,7 +47,7 @@
 std::string SignatureVerifyCacheKey(std::string_view algorithm_name,
                                     der::Input signed_data,
                                     der::Input signature_value_bytes,
-                                    EVP_PKEY *public_key) {
+                                    const EVP_PKEY *public_key) {
   SHA256_CTX s_ctx;
   bssl::ScopedCBB public_key_cbb;
   uint8_t digest[SHA256_DIGEST_LENGTH];
@@ -171,7 +170,7 @@
 
 bool VerifySignedData(SignatureAlgorithm algorithm, der::Input signed_data,
                       const der::BitString &signature_value,
-                      EVP_PKEY *public_key, SignatureVerifyCache *cache) {
+                      const EVP_PKEY *public_key, SignatureVerifyCache *cache) {
   int expected_pkey_id = 1;
   const EVP_MD *digest = nullptr;
   bool is_rsa_pss = false;
diff --git a/pki/verify_signed_data.h b/pki/verify_signed_data.h
index 13cb540..8916840 100644
--- a/pki/verify_signed_data.h
+++ b/pki/verify_signed_data.h
@@ -39,7 +39,7 @@
 // Returns true if verification was successful.
 [[nodiscard]] OPENSSL_EXPORT bool VerifySignedData(
     SignatureAlgorithm algorithm, der::Input signed_data,
-    const der::BitString &signature_value, EVP_PKEY *public_key,
+    const der::BitString &signature_value, const EVP_PKEY *public_key,
     SignatureVerifyCache *cache);
 
 // Same as above overload, only the public key is inputted as an SPKI and will
diff --git a/ssl/encrypted_client_hello.cc b/ssl/encrypted_client_hello.cc
index 335d406..85c0ce0 100644
--- a/ssl/encrypted_client_hello.cc
+++ b/ssl/encrypted_client_hello.cc
@@ -1029,9 +1029,7 @@
   if (keys == nullptr) {
     return nullptr;
   }
-  auto *ptr = const_cast<SSL_ECH_KEYS *>(keys);
-  SSL_ECH_KEYS_up_ref(ptr);
-  return ptr;
+  return FromOpaque(keys)->DupRefInternal();
 }
 
 void SSL_ECH_KEYS_free(SSL_ECH_KEYS *keys) {
diff --git a/ssl/extensions.cc b/ssl/extensions.cc
index 8bb3925..db650c8 100644
--- a/ssl/extensions.cc
+++ b/ssl/extensions.cc
@@ -348,7 +348,7 @@
 }
 
 bool tls12_check_peer_sigalg(const SSL_HANDSHAKE *hs, uint8_t *out_alert,
-                             uint16_t sigalg, EVP_PKEY *pkey) {
+                             uint16_t sigalg, const EVP_PKEY *pkey) {
   // The peer must have selected an algorithm that is consistent with its public
   // key, the TLS version, and what we advertised.
   Span<const uint16_t> sigalgs = tls12_get_verify_sigalgs(hs);
diff --git a/ssl/internal.h b/ssl/internal.h
index e125e1d..b62b287 100644
--- a/ssl/internal.h
+++ b/ssl/internal.h
@@ -883,13 +883,13 @@
 
 // ssl_pkey_supports_algorithm returns whether `pkey` may be used to sign
 // `sigalg`.
-bool ssl_pkey_supports_algorithm(const SSLImpl *ssl, EVP_PKEY *pkey,
+bool ssl_pkey_supports_algorithm(const SSLImpl *ssl, const EVP_PKEY *pkey,
                                  uint16_t sigalg, bool is_verify);
 
 // ssl_public_key_verify verifies that the `signature` is valid for the public
 // key `pkey` and input `in`, using the signature algorithm `sigalg`.
 bool ssl_public_key_verify(SSLImpl *ssl, Span<const uint8_t> signature,
-                           uint16_t sigalg, EVP_PKEY *pkey,
+                           uint16_t sigalg, const EVP_PKEY *pkey,
                            Span<const uint8_t> in);
 
 
@@ -2511,7 +2511,7 @@
 // signature from `pkey`. It returns true on success and false on error, setting
 // `*out_alert` to an alert to send.
 bool tls12_check_peer_sigalg(const SSL_HANDSHAKE *hs, uint8_t *out_alert,
-                             uint16_t sigalg, EVP_PKEY *pkey);
+                             uint16_t sigalg, const EVP_PKEY *pkey);
 
 
 // Underdocumented functions.
diff --git a/ssl/ssl_credential.cc b/ssl/ssl_credential.cc
index 9eff530..f0f5a40 100644
--- a/ssl/ssl_credential.cc
+++ b/ssl/ssl_credential.cc
@@ -487,9 +487,7 @@
   if (cred == nullptr) {
     return nullptr;
   }
-  auto *cred_impl = FromOpaque(cred);
-  cred_impl->UpRefInternal();
-  return const_cast<SSL_CREDENTIAL *>(cred);
+  return FromOpaque(cred)->DupRefInternal();
 }
 
 void SSL_CREDENTIAL_free(SSL_CREDENTIAL *cred) {
diff --git a/ssl/ssl_lib.cc b/ssl/ssl_lib.cc
index a6c9842..1569182 100644
--- a/ssl/ssl_lib.cc
+++ b/ssl/ssl_lib.cc
@@ -443,9 +443,7 @@
   if (ctx == nullptr) {
     return nullptr;
   }
-  auto *ptr = const_cast<SSL_CTX *>(ctx);
-  SSL_CTX_up_ref(ptr);
-  return ptr;
+  return FromOpaque(ctx)->DupRefInternal();
 }
 
 void SSL_CTX_free(SSL_CTX *ctx) {
diff --git a/ssl/ssl_privkey.cc b/ssl/ssl_privkey.cc
index ae7c9bb..2ed2f10 100644
--- a/ssl/ssl_privkey.cc
+++ b/ssl/ssl_privkey.cc
@@ -142,7 +142,7 @@
       spki.data(), spki.size(), algs, std::size(algs)));
 }
 
-bool ssl_pkey_supports_algorithm(const SSLImpl *ssl, EVP_PKEY *pkey,
+bool ssl_pkey_supports_algorithm(const SSLImpl *ssl, const EVP_PKEY *pkey,
                                  uint16_t sigalg, bool is_verify) {
   const SSL_SIGNATURE_ALGORITHM *alg = get_signature_algorithm(sigalg);
   if (alg == nullptr || EVP_PKEY_id(pkey) != alg->pkey_type) {
@@ -197,7 +197,7 @@
   return true;
 }
 
-static bool setup_ctx(SSLImpl *ssl, EVP_MD_CTX *ctx, EVP_PKEY *pkey,
+static bool setup_ctx(SSLImpl *ssl, EVP_MD_CTX *ctx, const EVP_PKEY *pkey,
                       uint16_t sigalg, bool is_verify) {
   if (!ssl_pkey_supports_algorithm(ssl, pkey, sigalg, is_verify)) {
     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SIGNATURE_TYPE);
@@ -273,7 +273,7 @@
         ret = key_method->complete(ssl, out, out_len, max_out);
       } else {
         ret = key_method->sign(ssl, out, out_len, max_out, sigalg, in.data(),
-                              in.size());
+                               in.size());
       }
       if (ret == ssl_private_key_failure) {
         OPENSSL_PUT_ERROR(SSL, SSL_R_PRIVATE_KEY_OPERATION_FAILED);
@@ -305,7 +305,7 @@
 }
 
 bool ssl_public_key_verify(SSLImpl *ssl, Span<const uint8_t> signature,
-                           uint16_t sigalg, EVP_PKEY *pkey,
+                           uint16_t sigalg, const EVP_PKEY *pkey,
                            Span<const uint8_t> in) {
   ScopedEVP_MD_CTX ctx;
   if (!setup_ctx(ssl, ctx.get(), pkey, sigalg, true /* verify */)) {
diff --git a/ssl/ssl_session.cc b/ssl/ssl_session.cc
index 9ad5b33..93c5d41 100644
--- a/ssl/ssl_session.cc
+++ b/ssl/ssl_session.cc
@@ -897,9 +897,7 @@
   if (session == nullptr) {
     return nullptr;
   }
-  auto *ptr = const_cast<SSL_SESSION *>(session);
-  SSL_SESSION_up_ref(ptr);
-  return ptr;
+  return FromOpaque(session)->DupRefInternal();
 }
 
 void SSL_SESSION_free(SSL_SESSION *session) {
diff --git a/tool/pkcs12.cc b/tool/pkcs12.cc
index d5bdbde..fb28fce 100644
--- a/tool/pkcs12.cc
+++ b/tool/pkcs12.cc
@@ -18,7 +18,6 @@
 #include <string>
 #include <vector>
 
-#include <errno.h>
 #include <fcntl.h>
 #include <stdint.h>
 #include <string.h>
diff --git a/tool/server.cc b/tool/server.cc
index 9a4f2cf..fff60db 100644
--- a/tool/server.cc
+++ b/tool/server.cc
@@ -14,8 +14,6 @@
 
 #include <openssl/base.h>
 
-#include <memory>
-
 #include <openssl/digest.h>
 #include <openssl/err.h>
 #include <openssl/evp.h>
@@ -157,8 +155,7 @@
 static bool LoadOCSPResponse(SSL_CTX *ctx, const char *filename) {
   ScopedFILE f(fopen(filename, "rb"));
   std::vector<uint8_t> data;
-  if (f == nullptr ||
-      !ReadAll(&data, f.get())) {
+  if (f == nullptr || !ReadAll(&data, f.get())) {
     fprintf(stderr, "Error reading %s.\n", filename);
     return false;
   }
@@ -207,8 +204,7 @@
 
   // macOS requires an explicit EKU extension.
   bssl::UniquePtr<STACK_OF(ASN1_OBJECT)> ekus(sk_ASN1_OBJECT_new_null());
-  if (!ekus ||
-      !sk_ASN1_OBJECT_push(ekus.get(), OBJ_nid2obj(NID_server_auth)) ||
+  if (!ekus || !sk_ASN1_OBJECT_push(ekus.get(), OBJ_nid2obj(NID_server_auth)) ||
       !X509_add1_ext_i2d(x509.get(), NID_ext_key_usage, ekus.get(), /*crit=*/1,
                          /*flags=*/0)) {
     return nullptr;
@@ -383,8 +379,7 @@
   }
 
   if (args_map.count("-ech-key") + args_map.count("-ech-config") == 1) {
-    fprintf(stderr,
-            "-ech-config and -ech-key must be specified together.\n");
+    fprintf(stderr, "-ech-config and -ech-key must be specified together.\n");
     return false;
   }
 
@@ -393,8 +388,7 @@
     std::string ech_key_path = args_map["-ech-key"];
     ScopedFILE ech_key_file(fopen(ech_key_path.c_str(), "rb"));
     std::vector<uint8_t> ech_key;
-    if (ech_key_file == nullptr ||
-        !ReadAll(&ech_key, ech_key_file.get())) {
+    if (ech_key_file == nullptr || !ReadAll(&ech_key, ech_key_file.get())) {
       fprintf(stderr, "Error reading %s\n", ech_key_path.c_str());
       return false;
     }
@@ -461,7 +455,8 @@
 
   if (args_map.count("-ocsp-response") != 0 &&
       !LoadOCSPResponse(ctx.get(), args_map["-ocsp-response"].c_str())) {
-    fprintf(stderr, "Failed to load OCSP response: %s\n", args_map["-ocsp-response"].c_str());
+    fprintf(stderr, "Failed to load OCSP response: %s\n",
+            args_map["-ocsp-response"].c_str());
     return false;
   }