Commit 9044e5f425 for openssl.org

commit 9044e5f42556e5a3bdf49226406144d806123697
Author: Bob Beck <beck@openssl.org>
Date:   Mon May 11 11:15:02 2026 -0600

    Convert internal use of ASN1_STRING_set and ASN1_STRING_length

    to use their non-deprecated replacements. For "pretty-printing"
    applications and test code that use a length and require an int, size_t lengths
    are simply cast to an int. For writes and protocol level things
    size_t lengths are checked against INT_MAX and take the error
    path if the returned value is too large to be used for a funciton
    that takes an integer length.

    Reviewed-by: Milan Broz <mbroz@openssl.org>
    Reviewed-by: Norbert Pocs <norbertp@openssl.org>
    MergeDate: Sat Jul 18 13:01:19 2026
    (Merged from https://github.com/openssl/openssl/pull/31194)

diff --git a/apps/asn1parse.c b/apps/asn1parse.c
index ed5ebd076f..b8449762fe 100644
--- a/apps/asn1parse.c
+++ b/apps/asn1parse.c
@@ -82,7 +82,8 @@ int asn1parse_main(int argc, char **argv)
     const unsigned char *ctmpbuf;
     int indent = 0, noout = 0, dump = 0, informat = FORMAT_PEM;
     int offset = 0, ret = 1, i, j;
-    long num, tmplen;
+    long num;
+    size_t tmplen;
     const unsigned char *tmpbuf;
     unsigned int length = 0;
     OPTION_CHOICE o;
@@ -241,12 +242,12 @@ int asn1parse_main(int argc, char **argv)

     if (sk_OPENSSL_STRING_num(osk)) {
         tmpbuf = str;
-        tmplen = num;
+        tmplen = (size_t)num;
         for (i = 0; i < sk_OPENSSL_STRING_num(osk); i++) {
             ASN1_TYPE *atmp;
             int typ;
             j = strtol(sk_OPENSSL_STRING_value(osk, i), NULL, 0);
-            if (j <= 0 || j >= tmplen) {
+            if (j <= 0 || (size_t)j >= tmplen) {
                 BIO_printf(bio_err, "'%s' is out of range\n",
                     sk_OPENSSL_STRING_value(osk, i));
                 continue;
@@ -255,7 +256,7 @@ int asn1parse_main(int argc, char **argv)
             tmplen -= j;
             atmp = at;
             ctmpbuf = tmpbuf;
-            at = d2i_ASN1_TYPE(NULL, &ctmpbuf, tmplen);
+            at = d2i_ASN1_TYPE(NULL, &ctmpbuf, (long)tmplen);
             ASN1_TYPE_free(atmp);
             if (!at) {
                 BIO_puts(bio_err, "Error parsing structure\n");
@@ -272,11 +273,16 @@ int asn1parse_main(int argc, char **argv)
             }
             /* hmm... this is a little evil but it works */
             tmpbuf = ASN1_STRING_get0_data(at->value.asn1_string);
-            tmplen = ASN1_STRING_length(at->value.asn1_string);
+            tmplen = ASN1_STRING_length_ex(at->value.asn1_string);
+            if (tmplen > INT_MAX) {
+                BIO_puts(bio_err, "ASN.1 string length exceeds INT_MAX\n");
+                ERR_print_errors(bio_err);
+                goto end;
+            }
         }
         /* XXX casts away const */
         str = (unsigned char *)tmpbuf;
-        num = tmplen;
+        num = (int)tmplen;
     }

     if (offset < 0 || offset >= num) {
diff --git a/apps/ca.c b/apps/ca.c
index c0a58f4d16..8f98bc9a6a 100644
--- a/apps/ca.c
+++ b/apps/ca.c
@@ -1077,8 +1077,8 @@ end_of_options:
             X509 *xi = sk_X509_value(cert_sk, i);
             const ASN1_INTEGER *serialNumber = X509_get0_serialNumber(xi);
             const unsigned char *psn = ASN1_STRING_get0_data(serialNumber);
-            const int snl = ASN1_STRING_length(serialNumber);
-            const int filen_len = 2 * (snl > 0 ? snl : 1) + sizeof(".pem");
+            const size_t snl = ASN1_STRING_length_ex(serialNumber);
+            const size_t filen_len = 2 * (snl > 0 ? snl : 1) + sizeof(".pem");
             char *n = new_cert + outdirlen;

             if (outdirlen + filen_len > PATH_MAX) {
@@ -1089,7 +1089,7 @@ end_of_options:
             if (snl > 0) {
                 static const char HEX_DIGITS[] = "0123456789ABCDEF";

-                for (j = 0; j < snl; j++, psn++) {
+                for (j = 0; (size_t)j < snl; j++, psn++) {
                     *n++ = HEX_DIGITS[*psn >> 4];
                     *n++ = HEX_DIGITS[*psn & 0x0F];
                 }
@@ -1523,8 +1523,10 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509,
             goto end;
         }
         if (type != V_ASN1_BMPSTRING && type != V_ASN1_UTF8STRING) {
-            j = ASN1_PRINTABLE_type(ASN1_STRING_get0_data(str),
-                ASN1_STRING_length(str));
+            size_t tmp = ASN1_STRING_length_ex(str);
+            if (tmp > INT_MAX)
+                goto end;
+            j = ASN1_PRINTABLE_type(ASN1_STRING_get0_data(str), (int)tmp);
             if ((j == V_ASN1_T61STRING && type != V_ASN1_T61STRING)
                 || (j == V_ASN1_IA5STRING && type == V_ASN1_PRINTABLESTRING)) {
                 BIO_puts(bio_err,
@@ -1901,9 +1903,9 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509,
     /* We now just add it to the database as DB_TYPE_VAL('V') */
     row[DB_type] = OPENSSL_strdup("V");
     tm = X509_get0_notAfter(ret);
-    row[DB_exp_date] = app_malloc(ASN1_STRING_length(tm) + 1, "row expdate");
-    memcpy(row[DB_exp_date], ASN1_STRING_get0_data(tm), ASN1_STRING_length(tm));
-    row[DB_exp_date][ASN1_STRING_length(tm)] = '\0';
+    row[DB_exp_date] = app_malloc(ASN1_STRING_length_ex(tm) + 1, "row expdate");
+    memcpy(row[DB_exp_date], ASN1_STRING_get0_data(tm), ASN1_STRING_length_ex(tm));
+    row[DB_exp_date][ASN1_STRING_length_ex(tm)] = '\0';
     row[DB_rev_date] = NULL;
     row[DB_file] = OPENSSL_strdup("unknown");
     if ((row[DB_type] == NULL) || (row[DB_file] == NULL)
@@ -2137,9 +2139,9 @@ static int do_revoke(X509 *x509, CA_DB *db, REVINFO_TYPE rev_type,
         /* We now just add it to the database as DB_TYPE_REV('V') */
         row[DB_type] = OPENSSL_strdup("V");
         tm = X509_get0_notAfter(x509);
-        row[DB_exp_date] = app_malloc(ASN1_STRING_length(tm) + 1, "row exp_data");
-        memcpy(row[DB_exp_date], ASN1_STRING_get0_data(tm), ASN1_STRING_length(tm));
-        row[DB_exp_date][ASN1_STRING_length(tm)] = '\0';
+        row[DB_exp_date] = app_malloc(ASN1_STRING_length_ex(tm) + 1, "row exp_data");
+        memcpy(row[DB_exp_date], ASN1_STRING_get0_data(tm), ASN1_STRING_length_ex(tm));
+        row[DB_exp_date][ASN1_STRING_length_ex(tm)] = '\0';
         row[DB_rev_date] = NULL;
         row[DB_file] = OPENSSL_strdup("unknown");

@@ -2350,7 +2352,7 @@ static char *make_revocation_str(REVINFO_TYPE rev_type, const char *rev_arg)
     const char *reason = NULL, *other = NULL;
     ASN1_OBJECT *otmp;
     ASN1_UTCTIME *revtm = NULL;
-    int i;
+    size_t i;

     switch (rev_type) {
     case REV_NONE:
@@ -2407,12 +2409,12 @@ static char *make_revocation_str(REVINFO_TYPE rev_type, const char *rev_arg)
     if (!revtm)
         return NULL;

-    i = ASN1_STRING_length(revtm) + 1;
+    i = ASN1_STRING_length_ex(revtm) + 1;

     if (reason)
-        i += (int)(strlen(reason) + 1);
+        i += strlen(reason) + 1;
     if (other)
-        i += (int)(strlen(other) + 1);
+        i += strlen(other) + 1;

     str = app_malloc(i, "revocation reason");
     OPENSSL_strlcpy(str, (const char *)ASN1_STRING_get0_data(revtm), i);
@@ -2492,7 +2494,7 @@ static int old_entry_print(const ASN1_OBJECT *obj, const ASN1_STRING *str)
 {
     char buf[25], *pbuf;
     const char *p;
-    int j;
+    size_t j;

     j = i2a_ASN1_OBJECT(bio_err, obj);
     pbuf = buf;
@@ -2514,7 +2516,7 @@ static int old_entry_print(const ASN1_OBJECT *obj, const ASN1_STRING *str)
         BIO_printf(bio_err, "ASN.1 %2d:'", ASN1_STRING_type(str));

     p = (const char *)ASN1_STRING_get0_data(str);
-    for (j = ASN1_STRING_length(str); j > 0; j--) {
+    for (j = ASN1_STRING_length_ex(str); j > 0; j--) {
         if ((*p >= ' ') && (*p <= '~'))
             BIO_printf(bio_err, "%c", *p);
         else if (*p & 0x80)
diff --git a/apps/cmp.c b/apps/cmp.c
index a0770dcb97..abe6de5cb9 100644
--- a/apps/cmp.c
+++ b/apps/cmp.c
@@ -2140,7 +2140,7 @@ static int add_certProfile(OSSL_CMP_CTX *ctx, const char *name)
         return 0;
     if ((utf8string = ASN1_UTF8STRING_new()) == NULL)
         goto err;
-    if (!ASN1_STRING_set(utf8string, name, (int)strlen(name))) {
+    if (!ASN1_STRING_set_string(utf8string, name)) {
         ASN1_STRING_free(utf8string);
         goto err;
     }
@@ -2215,7 +2215,7 @@ static int handle_opt_geninfo(OSSL_CMP_CTX *ctx)
             else
                 *end++ = '\0';
             if ((text = ASN1_UTF8STRING_new()) == NULL
-                || !ASN1_STRING_set(text, ptr, -1))
+                || !ASN1_STRING_set_string(text, ptr))
                 goto oom;
             ptr = end;
             ASN1_TYPE_set(type, V_ASN1_UTF8STRING, text);
diff --git a/apps/cms.c b/apps/cms.c
index 46f9b3b11e..5e32ab55af 100644
--- a/apps/cms.c
+++ b/apps/cms.c
@@ -1580,13 +1580,15 @@ static void receipt_request_print(CMS_ContentInfo *cms)
             ERR_print_errors(bio_err);
         } else {
             const char *id;
-            int idlen;
+            size_t idlen;
             CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst,
                 &rlist, &rto);
             BIO_puts(bio_err, "  Signed Content ID:\n");
-            idlen = ASN1_STRING_length(scid);
+            idlen = ASN1_STRING_length_ex(scid);
+            if (idlen > INT_MAX)
+                idlen = INT_MAX;
             id = (const char *)ASN1_STRING_get0_data(scid);
-            BIO_dump_indent(bio_err, id, idlen, 4);
+            BIO_dump_indent(bio_err, id, (int)idlen, 4);
             BIO_puts(bio_err, "  Receipts From");
             if (rlist != NULL) {
                 BIO_puts(bio_err, " List:\n");
diff --git a/apps/lib/apps.c b/apps/lib/apps.c
index 36fcb20e2a..b44e4b2bef 100644
--- a/apps/lib/apps.c
+++ b/apps/lib/apps.c
@@ -2833,7 +2833,7 @@ static const char *get_dp_url(DIST_POINT *dp)
     for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
         gen = sk_GENERAL_NAME_value(gens, i);
         uri = GENERAL_NAME_get0_value(gen, &gtype);
-        if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
+        if (gtype == GEN_URI && ASN1_STRING_length_ex(uri) > 6) {
             const char *uptr = (const char *)ASN1_STRING_get0_data(uri);

             if (IS_HTTP(uptr)) /* can/should not use HTTPS here */
@@ -3722,7 +3722,7 @@ int has_stdin_waiting(void)
 int corrupt_signature(ASN1_STRING *signature)
 {
     const unsigned char *valid = ASN1_STRING_get0_data(signature);
-    int length = ASN1_STRING_length(signature);
+    size_t length = ASN1_STRING_length_ex(signature);
     unsigned char *s = OPENSSL_memdup(valid, length);

     if (s == NULL)
@@ -3730,7 +3730,7 @@ int corrupt_signature(ASN1_STRING *signature)

     s[length - 1] ^= 0x1;

-    ASN1_STRING_set0(signature, s, length);
+    ASN1_STRING_set0(signature, s, (int)length);
     return 1;
 }

diff --git a/apps/lib/cmp_mock_srv.c b/apps/lib/cmp_mock_srv.c
index 43cf6af314..825a2b6709 100644
--- a/apps/lib/cmp_mock_srv.c
+++ b/apps/lib/cmp_mock_srv.c
@@ -345,7 +345,7 @@ static OSSL_CMP_PKISI *process_cert_request(OSSL_CMP_SRV_CTX *srv_ctx,
             STACK_OF(ASN1_UTF8STRING) *strs;
             ASN1_UTF8STRING *str;
             const char *data;
-            int len;
+            size_t len;

             if (OBJ_obj2nid(obj) == NID_id_it_certProfile) {
                 if (!OSSL_CMP_ITAV_get0_certProfile(itav, &strs))
@@ -360,7 +360,7 @@ static OSSL_CMP_PKISI *process_cert_request(OSSL_CMP_SRV_CTX *srv_ctx,
                     ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_INVALID_ARGUMENT);
                     return NULL;
                 }
-                if (((len = ASN1_STRING_length(str)) != (int)sizeof("profile1") - 1)
+                if (((len = ASN1_STRING_length_ex(str)) != sizeof("profile1") - 1)
                     || memcmp(data, "profile1", len) != 0) {
                     ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_CERTPROFILE);
                     return NULL;
diff --git a/apps/pkcs12.c b/apps/pkcs12.c
index f817999562..e37aefc7a3 100644
--- a/apps/pkcs12.c
+++ b/apps/pkcs12.c
@@ -833,7 +833,7 @@ int pkcs12_main(int argc, char **argv)
                     ASN1_INTEGER_get(pbkdf2_param->iter));
                 BIO_printf(bio_err, "Key length: %ld, Salt length: %d\n",
                     ASN1_INTEGER_get(pbkdf2_param->keylength),
-                    ASN1_STRING_length(pbkdf2_param->salt->value.octet_string));
+                    (int)ASN1_STRING_length_ex(pbkdf2_param->salt->value.octet_string));
                 if (pbkdf2_param->prf == NULL) {
                     prfnid = NID_hmacWithSHA1;
                 } else {
@@ -847,8 +847,8 @@ int pkcs12_main(int argc, char **argv)
             BIO_printf(bio_err, ", Iteration %ld\n",
                 tmaciter != NULL ? ASN1_INTEGER_get(tmaciter) : 1L);
             BIO_printf(bio_err, "MAC length: %ld, salt length: %ld\n",
-                tmac != NULL ? ASN1_STRING_length(tmac) : 0L,
-                tsalt != NULL ? ASN1_STRING_length(tsalt) : 0L);
+                tmac != NULL ? (long)ASN1_STRING_length_ex(tmac) : 0L,
+                tsalt != NULL ? (long)ASN1_STRING_length_ex(tsalt) : 0L);
         }
     }

@@ -1231,7 +1231,7 @@ static int alg_print(const X509_ALGOR *alg)
             }
             BIO_printf(bio_err, ", Salt length: %d, Cost(N): %ld, "
                                 "Block size(r): %ld, Parallelism(p): %ld",
-                ASN1_STRING_length(kdf->salt),
+                (int)ASN1_STRING_length_ex(kdf->salt),
                 ASN1_INTEGER_get(kdf->costParameter),
                 ASN1_INTEGER_get(kdf->blockSize),
                 ASN1_INTEGER_get(kdf->parallelizationParameter));
@@ -1282,25 +1282,25 @@ void print_attribute(BIO *out, const ASN1_TYPE *av)
     switch (av->type) {
     case V_ASN1_BMPSTRING:
         value = OPENSSL_uni2asc(ASN1_STRING_get0_data(av->value.bmpstring),
-            ASN1_STRING_length(av->value.bmpstring));
+            (int)ASN1_STRING_length_ex(av->value.bmpstring));
         BIO_printf(out, "%s\n", value);
         OPENSSL_free(value);
         break;

     case V_ASN1_UTF8STRING:
-        BIO_printf(out, "%.*s\n", ASN1_STRING_length(av->value.utf8string),
+        BIO_printf(out, "%.*s\n", (int)ASN1_STRING_length_ex(av->value.utf8string),
             ASN1_STRING_get0_data(av->value.utf8string));
         break;

     case V_ASN1_OCTET_STRING:
         hex_print(out, ASN1_STRING_get0_data(av->value.octet_string),
-            ASN1_STRING_length(av->value.octet_string));
+            (int)ASN1_STRING_length_ex(av->value.octet_string));
         BIO_puts(out, "\n");
         break;

     case V_ASN1_BIT_STRING:
         hex_print(out, ASN1_STRING_get0_data(av->value.bit_string),
-            ASN1_STRING_length(av->value.bit_string));
+            (int)ASN1_STRING_length_ex(av->value.bit_string));
         BIO_puts(out, "\n");
         break;

diff --git a/apps/s_client.c b/apps/s_client.c
index d247cd836d..65aff3eb42 100644
--- a/apps/s_client.c
+++ b/apps/s_client.c
@@ -3049,6 +3049,7 @@ re_start:
         ASN1_TYPE *atyp = NULL;
         BIO *ldapbio = BIO_new(BIO_s_mem());
         CONF *cnf = NCONF_new(NULL);
+        size_t ssl_request_len;

         if (ldapbio == NULL || cnf == NULL) {
             BIO_free(ldapbio);
@@ -3081,11 +3082,18 @@ re_start:
             BIO_puts(bio_err, "ASN1_generate_nconf failed\n");
             goto end;
         }
+        ssl_request_len = ASN1_STRING_length_ex(atyp->value.sequence);
+        if (ssl_request_len > INT_MAX) {
+            NCONF_free(cnf);
+            ASN1_TYPE_free(atyp);
+            BIO_puts(bio_err, "generated NCONF size is too large\n");
+            goto end;
+        }
         NCONF_free(cnf);

         /* Send SSLRequest packet */
         BIO_write(sbio, ASN1_STRING_get0_data(atyp->value.sequence),
-            ASN1_STRING_length(atyp->value.sequence));
+            (int)ssl_request_len);
         (void)BIO_flush(sbio);
         ASN1_TYPE_free(atyp);

diff --git a/apps/spkac.c b/apps/spkac.c
index bcf5626277..27b2392bb9 100644
--- a/apps/spkac.c
+++ b/apps/spkac.c
@@ -155,8 +155,8 @@ int spkac_main(int argc, char **argv)
         if (spki == NULL)
             goto end;
         if (challenge != NULL
-            && !ASN1_STRING_set(spki->spkac->challenge,
-                challenge, (int)strlen(challenge)))
+            && !ASN1_STRING_set_string(spki->spkac->challenge,
+                challenge))
             goto end;
         if (!NETSCAPE_SPKI_set_pubkey(spki, pkey)) {
             BIO_puts(bio_err, "Error setting public key\n");
diff --git a/apps/ts.c b/apps/ts.c
index aaec526154..2049eb9331 100644
--- a/apps/ts.c
+++ b/apps/ts.c
@@ -583,7 +583,7 @@ static ASN1_INTEGER *create_nonce(int bits)
     if ((nonce = ASN1_INTEGER_new()) == NULL)
         goto err;

-    if (!ASN1_STRING_set(nonce, buf, len))
+    if (!ASN1_STRING_set_data(nonce, buf, len))
         goto err;

     ret = nonce;
diff --git a/crypto/asn1/a_bitstr.c b/crypto/asn1/a_bitstr.c
index 914ff98400..fdefb80e26 100644
--- a/crypto/asn1/a_bitstr.c
+++ b/crypto/asn1/a_bitstr.c
@@ -18,7 +18,7 @@
 #ifndef OPENSSL_NO_DEPRECATED_4_1
 int ASN1_BIT_STRING_set(ASN1_BIT_STRING *x, unsigned char *d, int len)
 {
-    return ASN1_STRING_set(x, d, len);
+    return ossl_asn1_string_set_internal(x, d, len, /*add_nul_byte=*/0);
 }
 #endif

@@ -263,8 +263,9 @@ int ASN1_BIT_STRING_set1(ASN1_BIT_STRING *abs, const uint8_t *data, size_t lengt
     if (length > 0 && (data[length - 1] & ((1 << unused_bits) - 1)) != 0)
         return 0;

-    if (!ASN1_STRING_set(abs, data, (int)length))
+    if (!ossl_asn1_string_set_internal(abs, data, (int)length, /*add_nul_byte=*/0))
         return 0;
+
     abs->type = V_ASN1_BIT_STRING;

     ossl_asn1_bit_string_set_unused_bits(abs, unused_bits);
diff --git a/crypto/asn1/a_int.c b/crypto/asn1/a_int.c
index 3b10ee99e5..10db6b6a3c 100644
--- a/crypto/asn1/a_int.c
+++ b/crypto/asn1/a_int.c
@@ -316,7 +316,7 @@ ASN1_INTEGER *ossl_c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp,
     } else
         ret = *a;

-    if (r > INT_MAX || ASN1_STRING_set(ret, NULL, (int)r) == 0) {
+    if (ASN1_STRING_set_data(ret, NULL, r) == 0) {
         ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
         goto err;
     }
@@ -371,7 +371,7 @@ static int asn1_string_set_int64(ASN1_STRING *a, int64_t r, int itype)
         off = asn1_put_uint64(tbuf, r);
         a->type &= ~V_ASN1_NEG;
     }
-    return ASN1_STRING_set(a, tbuf + off, (int)(sizeof(tbuf) - off));
+    return ASN1_STRING_set_data(a, tbuf + off, (sizeof(tbuf) - off));
 }

 static int asn1_string_get_uint64(uint64_t *pr, const ASN1_STRING *a,
@@ -399,7 +399,7 @@ static int asn1_string_set_uint64(ASN1_STRING *a, uint64_t r, int itype)

     a->type = itype;
     off = asn1_put_uint64(tbuf, r);
-    return ASN1_STRING_set(a, tbuf + off, (int)(sizeof(tbuf) - off));
+    return ASN1_STRING_set_data(a, tbuf + off, (sizeof(tbuf) - off));
 }

 /*
@@ -503,7 +503,7 @@ static ASN1_STRING *bn_to_asn1_string(const BIGNUM *bn, ASN1_STRING *ai,
     if (len == 0)
         len = 1;

-    if (ASN1_STRING_set(ret, NULL, len) == 0) {
+    if (ASN1_STRING_set_data(ret, NULL, len) == 0) {
         ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
         goto err;
     }
diff --git a/crypto/asn1/a_mbstr.c b/crypto/asn1/a_mbstr.c
index 9329472e9b..e70fe92db5 100644
--- a/crypto/asn1/a_mbstr.c
+++ b/crypto/asn1/a_mbstr.c
@@ -171,7 +171,7 @@ int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
     }
     /* If both the same type just copy across */
     if (inform == outform) {
-        if (!ASN1_STRING_set(dest, in, len)) {
+        if (!ASN1_STRING_set_data(dest, in, len)) {
             if (free_out) {
                 ASN1_STRING_free(dest);
                 *out = NULL;
diff --git a/crypto/asn1/a_time.c b/crypto/asn1/a_time.c
index 56366fe531..341bd5142d 100644
--- a/crypto/asn1/a_time.c
+++ b/crypto/asn1/a_time.c
@@ -271,7 +271,7 @@ ASN1_TIME *ossl_asn1_time_from_tm(ASN1_TIME *s, struct tm *ts, int type)
     if (tmps == NULL)
         return NULL;

-    if (!ASN1_STRING_set(tmps, NULL, len))
+    if (!ASN1_STRING_set_data(tmps, NULL, len))
         goto err;

     tmps->type = type;
diff --git a/crypto/asn1/asn1_gen.c b/crypto/asn1/asn1_gen.c
index 35abf85ca4..6fbf581b49 100644
--- a/crypto/asn1/asn1_gen.c
+++ b/crypto/asn1/asn1_gen.c
@@ -651,7 +651,7 @@ static ASN1_TYPE *asn1_str2type(const char *str, int format, int utype)
             ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
             goto bad_str;
         }
-        if (!ASN1_STRING_set(atmp->value.asn1_string, str, -1)) {
+        if (!ASN1_STRING_set_string(atmp->value.asn1_string, str)) {
             ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
             goto bad_str;
         }
@@ -706,7 +706,7 @@ static ASN1_TYPE *asn1_str2type(const char *str, int format, int utype)
             atmp->value.asn1_string->length = rdlen;
             atmp->value.asn1_string->type = utype;
         } else if (format == ASN1_GEN_FORMAT_ASCII) {
-            if (!ASN1_STRING_set(atmp->value.asn1_string, str, -1)) {
+            if (!ASN1_STRING_set_string(atmp->value.asn1_string, str)) {
                 ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
                 goto bad_str;
             }
diff --git a/crypto/asn1/asn1_lib.c b/crypto/asn1/asn1_lib.c
index 2bde572eaf..4b9e720bad 100644
--- a/crypto/asn1/asn1_lib.c
+++ b/crypto/asn1/asn1_lib.c
@@ -552,7 +552,7 @@ char *ossl_sk_ASN1_UTF8STRING2text(STACK_OF(ASN1_UTF8STRING) *text,
         current = sk_ASN1_UTF8STRING_value(text, i);
         if (i > 0)
             length += sep_len;
-        length += ASN1_STRING_length(current);
+        length += ASN1_STRING_length_ex(current);
         if (max_len != 0 && length > max_len)
             return NULL;
     }
@@ -562,7 +562,7 @@ char *ossl_sk_ASN1_UTF8STRING2text(STACK_OF(ASN1_UTF8STRING) *text,
     p = result;
     for (i = 0; i < sk_ASN1_UTF8STRING_num(text); i++) {
         current = sk_ASN1_UTF8STRING_value(text, i);
-        length = ASN1_STRING_length(current);
+        length = ASN1_STRING_length_ex(current);
         if (i > 0 && sep_len > 0) {
             strncpy(p, sep, sep_len + 1); /* using + 1 to silence gcc warning */
             p += sep_len;
diff --git a/crypto/asn1/asn1_local.h b/crypto/asn1/asn1_local.h
index 0fd1d0a842..6f3ee7983c 100644
--- a/crypto/asn1/asn1_local.h
+++ b/crypto/asn1/asn1_local.h
@@ -102,5 +102,7 @@ int ossl_asn1_time_time_t_to_tm(const time_t *time, struct tm *out_tm);
 int ossl_asn1_time_tm_to_time_t(const struct tm *tm, time_t *out);
 int ossl_asn1_call_aux_cb(const ASN1_AUX *aux, int operation,
     const ASN1_VALUE **in, const ASN1_ITEM *it, void *exarg);
+int ossl_asn1_string_set_internal(ASN1_STRING *str, const uint8_t *data,
+    int len_in, int add_nul_byte);

 #endif /* !defined(OSSL_LIBCRYPTO_ASN1_ASN1_LOCAL_H) */
diff --git a/crypto/asn1/evp_asn1.c b/crypto/asn1/evp_asn1.c
index 2d50dc657b..2f081e56d3 100644
--- a/crypto/asn1/evp_asn1.c
+++ b/crypto/asn1/evp_asn1.c
@@ -34,6 +34,7 @@ int ASN1_TYPE_set_octetstring(ASN1_TYPE *a, unsigned char *data, int len)
 int ASN1_TYPE_get_octetstring(const ASN1_TYPE *a, unsigned char *data, int max_len)
 {
     int ret, num;
+    size_t tmp;
     const unsigned char *p;

     if ((a->type != V_ASN1_OCTET_STRING) || (a->value.octet_string == NULL)) {
@@ -41,7 +42,13 @@ int ASN1_TYPE_get_octetstring(const ASN1_TYPE *a, unsigned char *data, int max_l
         return -1;
     }
     p = ASN1_STRING_get0_data(a->value.octet_string);
-    ret = ASN1_STRING_length(a->value.octet_string);
+    tmp = ASN1_STRING_length_ex(a->value.octet_string);
+    if (tmp > INT_MAX) {
+        ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LARGE);
+        return -1;
+    }
+    ret = (int)tmp;
+
     if (ret < max_len)
         num = ret;
     else
@@ -69,11 +76,19 @@ static ossl_inline void asn1_type_init_oct(ASN1_OCTET_STRING *oct,
 static int asn1_type_get_int_oct(ASN1_OCTET_STRING *oct, int32_t anum,
     long *num, unsigned char *data, int max_len)
 {
-    int ret = ASN1_STRING_length(oct), n;
+    int ret, n;
+    size_t tmp;

     if (num != NULL)
         *num = anum;

+    tmp = ASN1_STRING_length_ex(oct);
+
+    if (tmp > INT_MAX)
+        tmp = INT_MAX;
+
+    ret = (int)tmp;
+
     if (max_len > ret)
         n = ret;
     else
diff --git a/crypto/asn1/p5_scrypt.c b/crypto/asn1/p5_scrypt.c
index 64980a1a68..9e1b537b9f 100644
--- a/crypto/asn1/p5_scrypt.c
+++ b/crypto/asn1/p5_scrypt.c
@@ -173,7 +173,7 @@ static X509_ALGOR *pkcs5_scrypt_set(const unsigned char *salt, int saltlen,
         saltlen = PKCS5_DEFAULT_PBE2_SALT_LEN;

     /* This will either copy salt or grow the buffer */
-    if (ASN1_STRING_set(sparam->salt, salt, saltlen) == 0) {
+    if (ASN1_STRING_set_data(sparam->salt, salt, saltlen) == 0) {
         ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
         goto err;
     }
diff --git a/crypto/asn1/p8_pkey.c b/crypto/asn1/p8_pkey.c
index 143f503dea..77f03e82ef 100644
--- a/crypto/asn1/p8_pkey.c
+++ b/crypto/asn1/p8_pkey.c
@@ -72,11 +72,13 @@ int PKCS8_pkey_get0(const ASN1_OBJECT **ppkalg,
     const unsigned char **pk, int *ppklen,
     const X509_ALGOR **pa, const PKCS8_PRIV_KEY_INFO *p8)
 {
+    if (ASN1_STRING_length_ex(p8->pkey) > INT_MAX)
+        return 0;
     if (ppkalg)
         *ppkalg = p8->pkeyalg->algorithm;
     if (pk) {
         *pk = ASN1_STRING_get0_data(p8->pkey);
-        *ppklen = ASN1_STRING_length(p8->pkey);
+        *ppklen = (int)ASN1_STRING_length_ex(p8->pkey);
     }
     if (pa)
         *pa = p8->pkeyalg;
diff --git a/crypto/asn1/tasn_dec.c b/crypto/asn1/tasn_dec.c
index 197fd24105..911eb42be7 100644
--- a/crypto/asn1/tasn_dec.c
+++ b/crypto/asn1/tasn_dec.c
@@ -983,7 +983,7 @@ static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, long len,
             ASN1_STRING_set0(stmp, (unsigned char *)cont /* UGLY CAST! */, ilen);
             *free_cont = 0;
         } else {
-            if (!ASN1_STRING_set(stmp, cont, ilen)) {
+            if (!ASN1_STRING_set_data(stmp, cont, len)) {
                 ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
                 ASN1_STRING_free(stmp);
                 *pval = NULL;
diff --git a/crypto/cmp/cmp_protect.c b/crypto/cmp/cmp_protect.c
index b0f52e9f36..c0dba8392d 100644
--- a/crypto/cmp/cmp_protect.c
+++ b/crypto/cmp/cmp_protect.c
@@ -73,7 +73,11 @@ ASN1_BIT_STRING *ossl_cmp_calc_protection(const OSSL_CMP_CTX *ctx,

         pbm_str = (ASN1_STRING *)ppval;
         pbm_str_uc = ASN1_STRING_get0_data(pbm_str);
-        pbm = d2i_OSSL_CRMF_PBMPARAMETER(NULL, &pbm_str_uc, ASN1_STRING_length(pbm_str));
+        if (ASN1_STRING_length_ex(pbm_str) > INT_MAX) {
+            ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_ALGORITHM_OID);
+            goto end;
+        }
+        pbm = d2i_OSSL_CRMF_PBMPARAMETER(NULL, &pbm_str_uc, (long)ASN1_STRING_length_ex(pbm_str));
         if (pbm == NULL) {
             ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_ALGORITHM_OID);
             goto end;
@@ -81,7 +85,7 @@ ASN1_BIT_STRING *ossl_cmp_calc_protection(const OSSL_CMP_CTX *ctx,

         if (!OSSL_CRMF_pbm_new(ctx->libctx, ctx->propq,
                 pbm, prot_part_der, prot_part_der_len,
-                ASN1_STRING_get0_data(ctx->secretValue), ASN1_STRING_length(ctx->secretValue),
+                ASN1_STRING_get0_data(ctx->secretValue), ASN1_STRING_length_ex(ctx->secretValue),
                 &protection, &sig_len))
             goto end;

@@ -202,7 +206,7 @@ static X509_ALGOR *pbmac_algor(const OSSL_CMP_CTX *ctx)
         goto err;
     if ((pbm_der_len = i2d_OSSL_CRMF_PBMPARAMETER(pbm, &pbm_der)) < 0)
         goto err;
-    if (!ASN1_STRING_set(pbm_str, pbm_der, pbm_der_len))
+    if (!ASN1_STRING_set_data(pbm_str, pbm_der, pbm_der_len))
         goto err;
     alg = ossl_X509_ALGOR_from_nid(NID_id_PasswordBasedMAC,
         V_ASN1_SEQUENCE, pbm_str);
diff --git a/crypto/cmp/cmp_status.c b/crypto/cmp/cmp_status.c
index 40e1ee671e..063bbe808c 100644
--- a/crypto/cmp/cmp_status.c
+++ b/crypto/cmp/cmp_status.c
@@ -214,7 +214,7 @@ static char *snprint_PKIStatusInfo_parts(int status, int fail_info,
         for (i = 0; i < n_status_strings; i++) {
             text = sk_ASN1_UTF8STRING_value(status_strings, i);
             printed_chars = BIO_snprintf(write_ptr, bufsize, "\"%.*s\"%s",
-                ASN1_STRING_length(text),
+                (int)ASN1_STRING_length_ex(text),
                 ASN1_STRING_get0_data(text),
                 i < n_status_strings - 1 ? ", " : "");
             ADVANCE_BUFFER;
@@ -275,7 +275,7 @@ OSSL_CMP_PKISI *OSSL_CMP_STATUSINFO_new(int status, int fail_info,

     if (text != NULL) {
         if ((utf8_text = ASN1_UTF8STRING_new()) == NULL
-            || !ASN1_STRING_set(utf8_text, text, -1))
+            || !ASN1_STRING_set_string(utf8_text, text))
             goto err;
         if ((si->statusString = sk_ASN1_UTF8STRING_new_null()) == NULL)
             goto err;
diff --git a/crypto/cmp/cmp_util.c b/crypto/cmp/cmp_util.c
index c658529c7e..f3a0c86d53 100644
--- a/crypto/cmp/cmp_util.c
+++ b/crypto/cmp/cmp_util.c
@@ -227,7 +227,7 @@ int ossl_cmp_sk_ASN1_UTF8STRING_push_str(STACK_OF(ASN1_UTF8STRING) *sk,
         return 0;
     if ((utf8string = ASN1_UTF8STRING_new()) == NULL)
         return 0;
-    if (!ASN1_STRING_set(utf8string, text, len))
+    if (!ASN1_STRING_set_data(utf8string, (const uint8_t *)text, len))
         goto err;
     if (!sk_ASN1_UTF8STRING_push(sk, utf8string))
         goto err;
diff --git a/crypto/cms/cms_dd.c b/crypto/cms/cms_dd.c
index 2e1dd78f5e..e307460e44 100644
--- a/crypto/cms/cms_dd.c
+++ b/crypto/cms/cms_dd.c
@@ -92,7 +92,7 @@ int ossl_cms_DigestedData_do_final(const CMS_ContentInfo *cms, BIO *chain,
         else
             r = 1;
     } else {
-        if (!ASN1_STRING_set(dd->digest, md, mdlen))
+        if (!ASN1_STRING_set_data(dd->digest, md, mdlen))
             goto err;
         r = 1;
     }
diff --git a/crypto/cms/cms_dh.c b/crypto/cms/cms_dh.c
index a3ae620dea..03cef7455a 100644
--- a/crypto/cms/cms_dh.c
+++ b/crypto/cms/cms_dh.c
@@ -29,7 +29,7 @@ static int dh_cms_set_peerkey(EVP_PKEY_CTX *pctx,
     BIGNUM *bnpub = NULL;
     const unsigned char *p;
     unsigned char *buf = NULL;
-    int plen;
+    size_t plen;

     X509_ALGOR_get0(&aoid, &atype, &aval, alg);
     if (OBJ_obj2nid(aoid) != NID_dhpublicnumber)
@@ -43,29 +43,33 @@ static int dh_cms_set_peerkey(EVP_PKEY_CTX *pctx,
         goto err;

     /* Get public key */
-    plen = ASN1_STRING_length(pubkey);
+    plen = ASN1_STRING_length_ex(pubkey);
+    if (plen > INT_MAX)
+        goto err;
     p = ASN1_STRING_get0_data(pubkey);
     if (p == NULL || plen == 0)
         goto err;

-    if ((public_key = d2i_ASN1_INTEGER(NULL, &p, plen)) == NULL)
+    if ((public_key = d2i_ASN1_INTEGER(NULL, &p, (int)plen)) == NULL)
         goto err;
     /*
      * Pad to full p parameter size as that is checked by
      * EVP_PKEY_set1_encoded_public_key()
      */
     plen = EVP_PKEY_get_size(pk);
+    if (plen > INT_MAX)
+        goto err;
     if ((bnpub = ASN1_INTEGER_to_BN(public_key, NULL)) == NULL)
         goto err;
     if ((buf = OPENSSL_malloc(plen)) == NULL)
         goto err;
-    if (BN_bn2binpad(bnpub, buf, plen) < 0)
+    if (BN_bn2binpad(bnpub, buf, (int)plen) < 0)
         goto err;

     pkpeer = EVP_PKEY_new();
     if (pkpeer == NULL
         || !EVP_PKEY_copy_parameters(pkpeer, pk)
-        || EVP_PKEY_set1_encoded_public_key(pkpeer, buf, plen) <= 0)
+        || EVP_PKEY_set1_encoded_public_key(pkpeer, buf, (int)plen) <= 0)
         goto err;

     if (EVP_PKEY_derive_set_peer(pctx, pkpeer) > 0)
@@ -85,8 +89,9 @@ static int dh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri)
     ASN1_OCTET_STRING *ukm;
     const unsigned char *p;
     unsigned char *dukm = NULL;
-    int dukmlen = 0;
-    int keylen, plen;
+    size_t dukmlen = 0;
+    int keylen;
+    size_t plen;
     EVP_CIPHER *kekcipher = NULL;
     EVP_CIPHER_CTX *kekctx;
     const ASN1_OBJECT *aoid;
@@ -116,8 +121,10 @@ static int dh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri)
         goto err;

     p = ASN1_STRING_get0_data(parameter);
-    plen = ASN1_STRING_length(parameter);
-    kekalg = d2i_X509_ALGOR(NULL, &p, plen);
+    plen = ASN1_STRING_length_ex(parameter);
+    if (plen > INT_MAX)
+        goto err;
+    kekalg = d2i_X509_ALGOR(NULL, &p, (int)plen);
     if (kekalg == NULL)
         goto err;
     kekctx = CMS_RecipientInfo_kari_get0_ctx(ri);
@@ -146,13 +153,15 @@ static int dh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri)
         goto err;

     if (ukm != NULL) {
-        dukmlen = ASN1_STRING_length(ukm);
-        dukm = OPENSSL_memdup(ASN1_STRING_get0_data(ukm), dukmlen);
+        dukmlen = ASN1_STRING_length_ex(ukm);
+        if (dukmlen > INT_MAX)
+            goto err;
+        dukm = OPENSSL_memdup(ASN1_STRING_get0_data(ukm), (int)dukmlen);
         if (dukm == NULL)
             goto err;
     }

-    if (EVP_PKEY_CTX_set0_dh_kdf_ukm(pctx, dukm, dukmlen) <= 0)
+    if (EVP_PKEY_CTX_set0_dh_kdf_ukm(pctx, dukm, (int)dukmlen) <= 0)
         goto err;
     dukm = NULL;

@@ -206,7 +215,7 @@ static int dh_cms_encrypt(CMS_RecipientInfo *ri)
     ASN1_OCTET_STRING *ukm;
     unsigned char *penc = NULL, *dukm = NULL;
     int penclen;
-    int dukmlen = 0;
+    size_t dukmlen = 0;
     int rv = 0;
     int kdf_type, wrap_nid;
     const EVP_MD *kdf_md;
@@ -298,13 +307,15 @@ static int dh_cms_encrypt(CMS_RecipientInfo *ri)
         goto err;

     if (ukm != NULL) {
-        dukmlen = ASN1_STRING_length(ukm);
+        dukmlen = ASN1_STRING_length_ex(ukm);
+        if (dukmlen > INT_MAX)
+            goto err;
         dukm = OPENSSL_memdup(ASN1_STRING_get0_data(ukm), dukmlen);
         if (dukm == NULL)
             goto err;
     }

-    if (EVP_PKEY_CTX_set0_dh_kdf_ukm(pctx, dukm, dukmlen) <= 0)
+    if (EVP_PKEY_CTX_set0_dh_kdf_ukm(pctx, dukm, (int)dukmlen) <= 0)
         goto err;
     dukm = NULL;

diff --git a/crypto/cms/cms_ec.c b/crypto/cms/cms_ec.c
index 8a8fe3f912..98ab266779 100644
--- a/crypto/cms/cms_ec.c
+++ b/crypto/cms/cms_ec.c
@@ -79,7 +79,7 @@ static int ecdh_cms_set_peerkey(EVP_PKEY_CTX *pctx,
     int rv = 0;
     EVP_PKEY *pkpeer = NULL;
     const unsigned char *p;
-    int plen;
+    size_t plen;

     X509_ALGOR_get0(&aoid, &atype, &aval, alg);
     if (OBJ_obj2nid(aoid) != NID_X9_62_id_ecPublicKey)
@@ -106,12 +106,14 @@ static int ecdh_cms_set_peerkey(EVP_PKEY_CTX *pctx,
             goto err;
     }
     /* We have parameters now set public key */
-    plen = ASN1_STRING_length(pubkey);
+    plen = ASN1_STRING_length_ex(pubkey);
+    if (plen > INT_MAX)
+        goto err;
     p = ASN1_STRING_get0_data(pubkey);
     if (p == NULL || plen == 0)
         goto err;

-    if (EVP_PKEY_set1_encoded_public_key(pkpeer, p, plen) <= 0)
+    if (EVP_PKEY_set1_encoded_public_key(pkpeer, p, (int)plen) <= 0)
         goto err;

     if (EVP_PKEY_derive_set_peer(pctx, pkpeer) > 0)
@@ -163,7 +165,8 @@ static int ecdh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri)
     ASN1_OCTET_STRING *ukm;
     const unsigned char *p;
     unsigned char *der = NULL;
-    int plen, keylen;
+    int keylen, plen_i;
+    size_t plen;
     EVP_CIPHER *kekcipher = NULL;
     EVP_CIPHER_CTX *kekctx;
     const ASN1_OBJECT *aoid = NULL;
@@ -186,8 +189,10 @@ static int ecdh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri)
         return 0;

     p = ASN1_STRING_get0_data(parameter);
-    plen = ASN1_STRING_length(parameter);
-    kekalg = d2i_X509_ALGOR(NULL, &p, plen);
+    plen = ASN1_STRING_length_ex(parameter);
+    if (plen > INT_MAX)
+        goto err;
+    kekalg = d2i_X509_ALGOR(NULL, &p, (int)plen);
     if (kekalg == NULL)
         goto err;
     kekctx = CMS_RecipientInfo_kari_get0_ctx(ri);
@@ -206,12 +211,12 @@ static int ecdh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri)
     if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0)
         goto err;

-    plen = CMS_SharedInfo_encode(&der, kekalg, ukm, keylen);
+    plen_i = CMS_SharedInfo_encode(&der, kekalg, ukm, keylen);

-    if (plen <= 0)
+    if (plen_i <= 0)
         goto err;

-    if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, der, plen) <= 0)
+    if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, der, plen_i) <= 0)
         goto err;
     der = NULL;

diff --git a/crypto/cms/cms_env.c b/crypto/cms/cms_env.c
index 8413f497db..c29e2019ee 100644
--- a/crypto/cms/cms_env.c
+++ b/crypto/cms/cms_env.c
@@ -278,12 +278,17 @@ BIO *CMS_EnvelopedData_decrypt(CMS_EnvelopedData *env, BIO *detached_data,
     CMS_ContentInfo *ci;
     BIO *bio = NULL;
     int res = 0;
+    size_t secret_len = 0;

     if (env == NULL) {
         ERR_raise(ERR_LIB_CMS, ERR_R_PASSED_NULL_PARAMETER);
         return NULL;
     }

+    if (secret != NULL
+        && (secret_len = ASN1_STRING_length_ex(secret)) > INT_MAX)
+        return NULL;
+
     if ((ci = CMS_ContentInfo_new_ex(libctx, propq)) == NULL
         || (bio = BIO_new(BIO_s_mem())) == NULL)
         goto end;
@@ -291,7 +296,7 @@ BIO *CMS_EnvelopedData_decrypt(CMS_EnvelopedData *env, BIO *detached_data,
     ci->d.envelopedData = env;
     if (secret != NULL
         && CMS_decrypt_set1_password(ci, (unsigned char *)ASN1_STRING_get0_data(secret),
-               ASN1_STRING_length(secret))
+               (int)secret_len)
             != 1)
         goto end;
     res = CMS_decrypt(ci, secret == NULL ? pkey : NULL,
diff --git a/crypto/cms/cms_ess.c b/crypto/cms/cms_ess.c
index cafb827394..bfe0ccbf3d 100644
--- a/crypto/cms/cms_ess.c
+++ b/crypto/cms/cms_ess.c
@@ -131,7 +131,7 @@ CMS_ReceiptRequest *CMS_ReceiptRequest_create0_ex(
     if (id)
         ASN1_STRING_set0(rr->signedContentIdentifier, id, idlen);
     else {
-        if (!ASN1_STRING_set(rr->signedContentIdentifier, NULL, 32)) {
+        if (!ASN1_STRING_set_data(rr->signedContentIdentifier, NULL, 32)) {
             ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
             goto err;
         }
diff --git a/crypto/cms/cms_kemri.c b/crypto/cms/cms_kemri.c
index 1d867c0db1..3284ebc23a 100644
--- a/crypto/cms/cms_kemri.c
+++ b/crypto/cms/cms_kemri.c
@@ -388,7 +388,7 @@ int ossl_cms_RecipientInfo_kemri_decrypt(const CMS_ContentInfo *cms,
         goto err;

     kem_ct = ASN1_STRING_get0_data(kemri->kemct);
-    kem_ct_len = ASN1_STRING_length(kemri->kemct);
+    kem_ct_len = ASN1_STRING_length_ex(kemri->kemct);

     if (EVP_PKEY_decapsulate(kemri->pctx, NULL, &kem_secret_len, kem_ct, kem_ct_len) <= 0)
         return 0;
diff --git a/crypto/cms/cms_rsa.c b/crypto/cms/cms_rsa.c
index fc7fc6c284..1b351f6cd1 100644
--- a/crypto/cms/cms_rsa.c
+++ b/crypto/cms/cms_rsa.c
@@ -43,7 +43,7 @@ static int rsa_cms_decrypt(CMS_RecipientInfo *ri)
     int nid;
     int rv = -1;
     const unsigned char *label = NULL;
-    int labellen = 0;
+    size_t labellen = 0;
     const EVP_MD *mgf1md = NULL, *md = NULL;
     RSA_OAEP_PARAMS *oaep;
     const ASN1_OBJECT *aoid;
@@ -90,7 +90,9 @@ static int rsa_cms_decrypt(CMS_RecipientInfo *ri)
         }

         label = ASN1_STRING_get0_data(parameter);
-        labellen = ASN1_STRING_length(parameter);
+        labellen = ASN1_STRING_length_ex(parameter);
+        if (labellen > INT_MAX)
+            goto err;
     }

     if (EVP_PKEY_CTX_set_rsa_padding(pkctx, RSA_PKCS1_OAEP_PADDING) <= 0)
@@ -105,7 +107,7 @@ static int rsa_cms_decrypt(CMS_RecipientInfo *ri)
         if (dup_label == NULL)
             goto err;

-        if (EVP_PKEY_CTX_set0_rsa_oaep_label(pkctx, dup_label, labellen) <= 0) {
+        if (EVP_PKEY_CTX_set0_rsa_oaep_label(pkctx, dup_label, (int)labellen) <= 0) {
             OPENSSL_free(dup_label);
             goto err;
         }
diff --git a/crypto/cms/cms_sd.c b/crypto/cms/cms_sd.c
index 6466aacec1..352f75a45c 100644
--- a/crypto/cms/cms_sd.c
+++ b/crypto/cms/cms_sd.c
@@ -304,7 +304,7 @@ static int ossl_cms_add1_signing_cert(CMS_SignerInfo *si,

     p = pp;
     i2d_ESS_SIGNING_CERT(sc, &p);
-    if (!(seq = ASN1_STRING_new()) || !ASN1_STRING_set(seq, pp, len)) {
+    if (!(seq = ASN1_STRING_new()) || !ASN1_STRING_set_data(seq, pp, len)) {
         ASN1_STRING_free(seq);
         OPENSSL_free(pp);
         return 0;
@@ -329,7 +329,7 @@ static int ossl_cms_add1_signing_cert_v2(CMS_SignerInfo *si,

     p = pp;
     i2d_ESS_SIGNING_CERT_V2(sc, &p);
-    if (!(seq = ASN1_STRING_new()) || !ASN1_STRING_set(seq, pp, len)) {
+    if (!(seq = ASN1_STRING_new()) || !ASN1_STRING_set_data(seq, pp, len)) {
         ASN1_STRING_free(seq);
         OPENSSL_free(pp);
         return 0;
diff --git a/crypto/ct/ct_oct.c b/crypto/ct/ct_oct.c
index b8bef582a9..4f5fd8d027 100644
--- a/crypto/ct/ct_oct.c
+++ b/crypto/ct/ct_oct.c
@@ -381,7 +381,7 @@ STACK_OF(SCT) *d2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp,
         return NULL;

     p = ASN1_STRING_get0_data(oct);
-    if ((sk = o2i_SCT_LIST(a, &p, ASN1_STRING_length(oct))) != NULL)
+    if ((sk = o2i_SCT_LIST(a, &p, ASN1_STRING_length_ex(oct))) != NULL)
         *pp += len;

     ASN1_OCTET_STRING_free(oct);
diff --git a/crypto/ec/ec_asn1.c b/crypto/ec/ec_asn1.c
index fdc3ce94c7..835f759935 100644
--- a/crypto/ec/ec_asn1.c
+++ b/crypto/ec/ec_asn1.c
@@ -966,9 +966,10 @@ EC_KEY *d2i_ECPrivateKey(EC_KEY **a, const unsigned char **in, long len)

     if (priv_key->privateKey) {
         ASN1_OCTET_STRING *pkey = priv_key->privateKey;
-        if (EC_KEY_oct2priv(ret, ASN1_STRING_get0_data(pkey),
-                ASN1_STRING_length(pkey))
-            == 0)
+        size_t pkey_len = ASN1_STRING_length_ex(pkey);
+        if (pkey_len > INT_MAX)
+            goto err;
+        if (EC_KEY_oct2priv(ret, ASN1_STRING_get0_data(pkey), (int)pkey_len) == 0)
             goto err;
     } else {
         ERR_raise(ERR_LIB_EC, EC_R_MISSING_PRIVATE_KEY);
@@ -987,11 +988,13 @@ EC_KEY *d2i_ECPrivateKey(EC_KEY **a, const unsigned char **in, long len)

     if (priv_key->publicKey) {
         const unsigned char *pub_oct;
-        int pub_oct_len;
+        size_t pub_oct_len;

         pub_oct = ASN1_STRING_get0_data(priv_key->publicKey);
-        pub_oct_len = ASN1_STRING_length(priv_key->publicKey);
-        if (!EC_KEY_oct2key(ret, pub_oct, pub_oct_len, NULL)) {
+        pub_oct_len = ASN1_STRING_length_ex(priv_key->publicKey);
+        if (pub_oct_len > INT_MAX)
+            goto err;
+        if (!EC_KEY_oct2key(ret, pub_oct, (int)pub_oct_len, NULL)) {
             ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
             goto err;
         }
diff --git a/crypto/ec/ecx_backend.c b/crypto/ec/ecx_backend.c
index 710ad31a66..d95e8bb084 100644
--- a/crypto/ec/ecx_backend.c
+++ b/crypto/ec/ecx_backend.c
@@ -230,15 +230,19 @@ ECX_KEY *ossl_ecx_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf,
     const X509_ALGOR *palg;

     if (!PKCS8_pkey_get0(NULL, &p, &plen, &palg, p8inf))
-        return 0;
+        goto err;

     oct = d2i_ASN1_OCTET_STRING(NULL, &p, plen);
     if (oct == NULL) {
         p = NULL;
         plen = 0;
     } else {
+        size_t tmp;
         p = ASN1_STRING_get0_data(oct);
-        plen = ASN1_STRING_length(oct);
+        tmp = ASN1_STRING_length_ex(oct);
+        if (tmp > INT_MAX)
+            goto err;
+        plen = (int)tmp;
     }

     /*
@@ -247,6 +251,7 @@ ECX_KEY *ossl_ecx_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf,
      */
     ecx = ossl_ecx_key_op(palg, p, plen, EVP_PKEY_NONE, KEY_OP_PRIVATE,
         libctx, propq);
+err:
     ASN1_OCTET_STRING_free(oct);
     return ecx;
 }
diff --git a/crypto/ocsp/ocsp_ext.c b/crypto/ocsp/ocsp_ext.c
index e6467aa0ae..038be72b04 100644
--- a/crypto/ocsp/ocsp_ext.c
+++ b/crypto/ocsp/ocsp_ext.c
@@ -360,7 +360,7 @@ X509_EXTENSION *OCSP_crlID_new(const char *url, long *n, char *tim)
     if (url) {
         if ((cid->crlUrl = ASN1_IA5STRING_new()) == NULL)
             goto err;
-        if (!(ASN1_STRING_set(cid->crlUrl, url, -1)))
+        if (!(ASN1_STRING_set_string(cid->crlUrl, url)))
             goto err;
     }
     if (n) {
@@ -446,7 +446,7 @@ X509_EXTENSION *OCSP_url_svcloc_new(const X509_NAME *issuer, const char **urls)
             goto err;
         if ((ia5 = ASN1_IA5STRING_new()) == NULL)
             goto err;
-        if (!ASN1_STRING_set((ASN1_STRING *)ia5, *urls, -1))
+        if (!ASN1_STRING_set_string((ASN1_STRING *)ia5, *urls))
             goto err;
         /* ad->location is allocated inside ACCESS_DESCRIPTION_new */
         ad->location->type = GEN_URI;
diff --git a/crypto/ocsp/ocsp_srv.c b/crypto/ocsp/ocsp_srv.c
index beecad63a2..fa99da8a7f 100644
--- a/crypto/ocsp/ocsp_srv.c
+++ b/crypto/ocsp/ocsp_srv.c
@@ -301,7 +301,7 @@ int OCSP_RESPID_match_ex(OCSP_RESPID *respid, X509 *cert, OSSL_LIB_CTX *libctx,
         if (!X509_pubkey_digest(cert, sha1, md, NULL))
             goto err;

-        ret = (ASN1_STRING_length(respid->value.byKey) == SHA_DIGEST_LENGTH)
+        ret = (ASN1_STRING_length_ex(respid->value.byKey) == SHA_DIGEST_LENGTH)
             && (memcmp(ASN1_STRING_get0_data(respid->value.byKey), md,
                     SHA_DIGEST_LENGTH)
                 == 0);
diff --git a/crypto/pkcs12/p12_mutl.c b/crypto/pkcs12/p12_mutl.c
index 2888efd689..60843bd951 100644
--- a/crypto/pkcs12/p12_mutl.c
+++ b/crypto/pkcs12/p12_mutl.c
@@ -350,7 +350,7 @@ int PKCS12_verify_mac(PKCS12 *p12, const char *pass, int passlen)
         }
     }
     X509_SIG_get0(p12->mac->dinfo, NULL, &macoct);
-    if ((maclen != (unsigned int)ASN1_STRING_length(macoct))
+    if ((maclen != ASN1_STRING_length_ex(macoct))
         || CRYPTO_memcmp(mac, ASN1_STRING_get0_data(macoct), maclen) != 0)
         return 0;

diff --git a/crypto/pkcs7/pk7_attr.c b/crypto/pkcs7/pk7_attr.c
index b865d97356..28f073f36f 100644
--- a/crypto/pkcs7/pk7_attr.c
+++ b/crypto/pkcs7/pk7_attr.c
@@ -30,7 +30,7 @@ int PKCS7_add_attrib_smimecap(PKCS7_SIGNER_INFO *si,
     }
     seq->length = ASN1_item_i2d((ASN1_VALUE *)cap, &seq->data,
         ASN1_ITEM_rptr(X509_ALGORS));
-    if (ASN1_STRING_length(seq) <= 0 || ASN1_STRING_get0_data(seq) == NULL) {
+    if (ASN1_STRING_length_ex(seq) == 0 || ASN1_STRING_get0_data(seq) == NULL) {
         ASN1_STRING_free(seq);
         return 1;
     }
@@ -46,14 +46,17 @@ STACK_OF(X509_ALGOR) *PKCS7_get_smimecap(PKCS7_SIGNER_INFO *si)
 {
     const ASN1_TYPE *cap;
     const unsigned char *p;
+    size_t len;

     cap = PKCS7_get_signed_attribute(si, NID_SMIMECapabilities);
     if (cap == NULL || (cap->type != V_ASN1_SEQUENCE))
         return NULL;
     p = ASN1_STRING_get0_data(cap->value.sequence);
+    len = ASN1_STRING_length_ex(cap->value.sequence);
+    if (len > INT_MAX)
+        return NULL;
     return (STACK_OF(X509_ALGOR) *)
-        ASN1_item_d2i(NULL, &p, ASN1_STRING_length(cap->value.sequence),
-            ASN1_ITEM_rptr(X509_ALGORS));
+        ASN1_item_d2i(NULL, &p, (int)len, ASN1_ITEM_rptr(X509_ALGORS));
 }

 /* Basic smime-capabilities OID and optional integer arg */
@@ -129,7 +132,7 @@ int PKCS7_add1_attrib_digest(PKCS7_SIGNER_INFO *si,
     os = ASN1_OCTET_STRING_new();
     if (os == NULL)
         return 0;
-    if (!ASN1_STRING_set(os, md, mdlen)
+    if (!ASN1_STRING_set_data(os, md, mdlen)
         || !PKCS7_add_signed_attribute(si, NID_pkcs9_messageDigest,
             V_ASN1_OCTET_STRING, os)) {
         ASN1_OCTET_STRING_free(os);
diff --git a/crypto/pkcs7/pk7_doit.c b/crypto/pkcs7/pk7_doit.c
index 1878b4aac2..33d2eaafdf 100644
--- a/crypto/pkcs7/pk7_doit.c
+++ b/crypto/pkcs7/pk7_doit.c
@@ -74,16 +74,19 @@ static ASN1_OCTET_STRING *pkcs7_get1_data(PKCS7 *p7)
     if (PKCS7_type_is_other(p7) && (p7->d.other != NULL)
         && (p7->d.other->type == V_ASN1_SEQUENCE)
         && (p7->d.other->value.sequence != NULL)
-        && (ASN1_STRING_length(p7->d.other->value.sequence) > 0)) {
+        && (ASN1_STRING_length_ex(p7->d.other->value.sequence) > 0)) {
         const unsigned char *data = ASN1_STRING_get0_data(p7->d.other->value.sequence);
         long len;
         int inf, tag, class;
+        size_t tmp;

+        tmp = ASN1_STRING_length_ex(p7->d.other->value.sequence);
+        if (tmp > INT_MAX)
+            return NULL;
         os = ASN1_OCTET_STRING_new();
         if (os == NULL)
             return NULL;
-        inf = ASN1_get_object(&data, &len, &tag, &class,
-            ASN1_STRING_length(p7->d.other->value.sequence));
+        inf = ASN1_get_object(&data, &len, &tag, &class, (int)tmp);
         if (inf != V_ASN1_CONSTRUCTED || tag != V_ASN1_SEQUENCE
             || !ASN1_OCTET_STRING_set(os, data, len)) {
             ASN1_OCTET_STRING_free(os);
@@ -198,7 +201,7 @@ static int pkcs7_decrypt_rinfo(unsigned char **pek, int *peklen,
         goto err;

     ret = evp_pkey_decrypt_alloc(pctx, &ek, &eklen, fixlen,
-        ASN1_STRING_get0_data(ri->enc_key), ASN1_STRING_length(ri->enc_key));
+        ASN1_STRING_get0_data(ri->enc_key), ASN1_STRING_length_ex(ri->enc_key));
     if (ret <= 0)
         goto err;

@@ -371,7 +374,7 @@ BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio)
     if (bio == NULL) {
         if (PKCS7_is_detached(p7)) {
             bio = BIO_new(BIO_s_null());
-        } else if (os != NULL && ASN1_STRING_length(os) > 0) {
+        } else if (os != NULL && ASN1_STRING_length_ex(os) > 0) {
             /*
              * bio needs a copy of os->data instead of a pointer because
              * the data will be used after os has been freed
@@ -380,8 +383,8 @@ BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio)
             if (bio != NULL) {
                 BIO_set_mem_eof_return(bio, 0);
                 const unsigned char *os_data = ASN1_STRING_get0_data(os);
-                int os_len = ASN1_STRING_length(os);
-                if (BIO_write(bio, os_data, os_len) != os_len) {
+                size_t os_len = ASN1_STRING_length_ex(os);
+                if (os_len > INT_MAX || BIO_write(bio, os_data, (int)os_len) != (int)os_len) {
                     BIO_free_all(bio);
                     bio = NULL;
                 }
@@ -656,10 +659,12 @@ BIO *PKCS7_dataDecode(PKCS7 *p7, EVP_PKEY *pkey, BIO *in_bio, X509 *pcert)
     if (in_bio != NULL) {
         bio = in_bio;
     } else {
-        int data_body_len = ASN1_STRING_length(data_body);
+        size_t data_body_len = ASN1_STRING_length_ex(data_body);
+        if (data_body_len > INT_MAX)
+            goto err;
         if (data_body_len > 0)
             bio = BIO_new_mem_buf(ASN1_STRING_get0_data(data_body),
-                data_body_len);
+                (int)data_body_len);
         else {
             bio = BIO_new(BIO_s_mem());
             if (bio == NULL)
@@ -1110,7 +1115,7 @@ int PKCS7_signatureVerify(BIO *bio, PKCS7 *p7, PKCS7_SIGNER_INFO *si,
             ERR_raise(ERR_LIB_PKCS7, PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
             goto err;
         }
-        if ((ASN1_STRING_length(message_digest) != (int)md_len)
+        if ((ASN1_STRING_length_ex(message_digest) != md_len)
             || (memcmp(ASN1_STRING_get0_data(message_digest), md_dat, md_len))) {
             ERR_raise(ERR_LIB_PKCS7, PKCS7_R_DIGEST_FAILURE);
             ret = -1;
@@ -1142,8 +1147,12 @@ int PKCS7_signatureVerify(BIO *bio, PKCS7 *p7, PKCS7_SIGNER_INFO *si,
     }

     const unsigned char *sig_data = ASN1_STRING_get0_data(os);
-    int sig_len = ASN1_STRING_length(os);
-    i = EVP_VerifyFinal_ex(mdc_tmp, sig_data, sig_len, pkey, libctx, propq);
+    size_t sig_len = ASN1_STRING_length_ex(os);
+    if (sig_len > INT_MAX) {
+        ret = -1;
+        goto err;
+    }
+    i = EVP_VerifyFinal_ex(mdc_tmp, sig_data, (int)sig_len, pkey, libctx, propq);
     if (i <= 0) {
         ERR_raise(ERR_LIB_PKCS7, PKCS7_R_SIGNATURE_FAILURE);
         ret = -1;
diff --git a/crypto/pkcs7/pk7_smime.c b/crypto/pkcs7/pk7_smime.c
index 49129690de..7ede4b6694 100644
--- a/crypto/pkcs7/pk7_smime.c
+++ b/crypto/pkcs7/pk7_smime.c
@@ -199,9 +199,15 @@ static int pkcs7_copy_existing_digest(PKCS7 *p7, PKCS7_SIGNER_INFO *si)
         }
     }

-    if (osdig != NULL)
-        return PKCS7_add1_attrib_digest(si, ASN1_STRING_get0_data(osdig), ASN1_STRING_length(osdig));
+    if (osdig != NULL) {
+        size_t len;
+        len = ASN1_STRING_length_ex(osdig);
+        if (len > INT_MAX)
+            goto err;
+        return PKCS7_add1_attrib_digest(si, ASN1_STRING_get0_data(osdig), (int)len);
+    }

+err:
     ERR_raise(ERR_LIB_PKCS7, PKCS7_R_NO_MATCHING_DIGEST_TYPE_FOUND);
     return 0;
 }
diff --git a/crypto/sm2/sm2_crypt.c b/crypto/sm2/sm2_crypt.c
index a1cbd88c2d..6e787f5d28 100644
--- a/crypto/sm2/sm2_crypt.c
+++ b/crypto/sm2/sm2_crypt.c
@@ -78,7 +78,7 @@ int ossl_sm2_plaintext_size(const unsigned char *ct, size_t ct_size,
         return 0;
     }

-    *pt_size = ASN1_STRING_length(sm2_ctext->C2);
+    *pt_size = ASN1_STRING_length_ex(sm2_ctext->C2);
     SM2_Ciphertext_free(sm2_ctext);

     return 1;
@@ -309,7 +309,7 @@ int ossl_sm2_decrypt(const EC_KEY *key,
     uint8_t *msg_mask = NULL;
     const uint8_t *C2 = NULL;
     const uint8_t *C3 = NULL;
-    int msg_len = 0;
+    size_t c3_len, msg_len = 0;
     EVP_MD_CTX *hash = NULL;
     OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key);
     const char *propq = ossl_ec_key_get0_propq(key);
@@ -326,14 +326,18 @@ int ossl_sm2_decrypt(const EC_KEY *key,
         goto done;
     }

-    if (ASN1_STRING_length(sm2_ctext->C3) != hash_size) {
+    msg_len = ASN1_STRING_length_ex(sm2_ctext->C2);
+    if (msg_len > INT_MAX)
+        goto done;
+
+    c3_len = ASN1_STRING_length_ex(sm2_ctext->C3);
+    if (c3_len > INT_MAX || c3_len != (size_t)hash_size) {
         ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING);
         goto done;
     }

     C2 = ASN1_STRING_get0_data(sm2_ctext->C2);
     C3 = ASN1_STRING_get0_data(sm2_ctext->C3);
-    msg_len = ASN1_STRING_length(sm2_ctext->C2);
     if (*ptext_len < (size_t)msg_len) {
         ERR_raise(ERR_LIB_SM2, SM2_R_BUFFER_TOO_SMALL);
         goto done;
@@ -378,7 +382,7 @@ int ossl_sm2_decrypt(const EC_KEY *key,

     if (BN_bn2binpad(x2, x2y2, field_size) < 0
         || BN_bn2binpad(y2, x2y2 + field_size, field_size) < 0
-        || !ossl_ecdh_kdf_X9_63(msg_mask, msg_len, x2y2, 2 * field_size,
+        || !ossl_ecdh_kdf_X9_63(msg_mask, (int)msg_len, x2y2, 2 * field_size,
             NULL, 0, digest, libctx, propq)) {
         ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
         goto done;
@@ -389,7 +393,7 @@ int ossl_sm2_decrypt(const EC_KEY *key,
         goto done;
     }

-    for (i = 0; i != msg_len; ++i)
+    for (i = 0; i != (int)msg_len; ++i)
         ptext_buf[i] = C2[i] ^ msg_mask[i];

     hash = EVP_MD_CTX_new();
@@ -400,7 +404,7 @@ int ossl_sm2_decrypt(const EC_KEY *key,

     if (!EVP_DigestInit(hash, digest)
         || !EVP_DigestUpdate(hash, x2y2, field_size)
-        || !EVP_DigestUpdate(hash, ptext_buf, msg_len)
+        || !EVP_DigestUpdate(hash, ptext_buf, (int)msg_len)
         || !EVP_DigestUpdate(hash, x2y2 + field_size, field_size)
         || !EVP_DigestFinal(hash, computed_C3, NULL)) {
         ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
@@ -413,7 +417,7 @@ int ossl_sm2_decrypt(const EC_KEY *key,
     }

     rc = 1;
-    *ptext_len = msg_len;
+    *ptext_len = (int)msg_len;

 done:
     if (rc == 0)
diff --git a/crypto/ts/ts_asn1.c b/crypto/ts/ts_asn1.c
index b44002ef2f..56d41df554 100644
--- a/crypto/ts/ts_asn1.c
+++ b/crypto/ts/ts_asn1.c
@@ -208,6 +208,7 @@ TS_TST_INFO *PKCS7_to_TS_TST_INFO(PKCS7 *token)
     ASN1_TYPE *tst_info_wrapper;
     ASN1_OCTET_STRING *tst_info_der;
     const unsigned char *p;
+    size_t len;

     if (!PKCS7_type_is_signed(token)) {
         ERR_raise(ERR_LIB_TS, TS_R_BAD_PKCS7_TYPE);
@@ -230,5 +231,10 @@ TS_TST_INFO *PKCS7_to_TS_TST_INFO(PKCS7 *token)
     }
     tst_info_der = tst_info_wrapper->value.octet_string;
     p = ASN1_STRING_get0_data(tst_info_der);
-    return d2i_TS_TST_INFO(NULL, &p, ASN1_STRING_length(tst_info_der));
+    len = ASN1_STRING_length_ex(tst_info_der);
+    if (len > INT_MAX) {
+        ERR_raise(ERR_LIB_TS, TS_R_BAD_TYPE);
+        return NULL;
+    }
+    return d2i_TS_TST_INFO(NULL, &p, (int)len);
 }
diff --git a/crypto/ts/ts_lib.c b/crypto/ts/ts_lib.c
index 8b46fb4744..26b3994ccb 100644
--- a/crypto/ts/ts_lib.c
+++ b/crypto/ts/ts_lib.c
@@ -86,7 +86,7 @@ int TS_MSG_IMPRINT_print_bio(BIO *bio, TS_MSG_IMPRINT *a)
     BIO_printf(bio, "Message data:\n");
     msg = a->hashed_msg;
     BIO_dump_indent(bio, (const char *)ASN1_STRING_get0_data(msg),
-        ASN1_STRING_length(msg), 4);
+        (int)ASN1_STRING_length_ex(msg), 4);

     return 1;
 }
diff --git a/crypto/ts/ts_rsp_sign.c b/crypto/ts/ts_rsp_sign.c
index 1421275fd9..e9151f750e 100644
--- a/crypto/ts/ts_rsp_sign.c
+++ b/crypto/ts/ts_rsp_sign.c
@@ -298,7 +298,7 @@ int TS_RESP_CTX_set_status_info(TS_RESP_CTX *ctx,
     }
     if (text) {
         if ((utf8_text = ASN1_UTF8STRING_new()) == NULL
-            || !ASN1_STRING_set(utf8_text, text, (int)strlen(text))) {
+            || !ASN1_STRING_set_string(utf8_text, text)) {
             ERR_raise(ERR_LIB_TS, ERR_R_ASN1_LIB);
             goto err;
         }
@@ -487,7 +487,7 @@ static int ts_RESP_check_request(TS_RESP_CTX *ctx)
         return 0;
     }
     digest = msg_imprint->hashed_msg;
-    if (ASN1_STRING_length(digest) != md_size) {
+    if (ASN1_STRING_length_ex(digest) != (size_t)md_size) {
         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
             "Bad message digest.");
         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_DATA_FORMAT);
@@ -645,7 +645,7 @@ static int ossl_ess_add1_signing_cert(PKCS7_SIGNER_INFO *si,

     p = pp;
     i2d_ESS_SIGNING_CERT(sc, &p);
-    if ((seq = ASN1_STRING_new()) == NULL || !ASN1_STRING_set(seq, pp, len)) {
+    if ((seq = ASN1_STRING_new()) == NULL || !ASN1_STRING_set_data(seq, pp, len)) {
         ASN1_STRING_free(seq);
         OPENSSL_free(pp);
         return 0;
@@ -676,7 +676,7 @@ static int ossl_ess_add1_signing_cert_v2(PKCS7_SIGNER_INFO *si,

     p = pp;
     i2d_ESS_SIGNING_CERT_V2(sc, &p);
-    if ((seq = ASN1_STRING_new()) == NULL || !ASN1_STRING_set(seq, pp, len)) {
+    if ((seq = ASN1_STRING_new()) == NULL || !ASN1_STRING_set_data(seq, pp, len)) {
         ASN1_STRING_free(seq);
         OPENSSL_free(pp);
         return 0;
diff --git a/crypto/ts/ts_rsp_verify.c b/crypto/ts/ts_rsp_verify.c
index 1dc70c125b..1b45243ca8 100644
--- a/crypto/ts/ts_rsp_verify.c
+++ b/crypto/ts/ts_rsp_verify.c
@@ -207,24 +207,32 @@ static ESS_SIGNING_CERT *ossl_ess_get_signing_cert(const PKCS7_SIGNER_INFO *si)
 {
     const ASN1_TYPE *attr;
     const unsigned char *p;
+    size_t len;

     attr = PKCS7_get_signed_attribute(si, NID_id_smime_aa_signingCertificate);
     if (attr == NULL || attr->type != V_ASN1_SEQUENCE)
         return NULL;
     p = ASN1_STRING_get0_data(attr->value.sequence);
-    return d2i_ESS_SIGNING_CERT(NULL, &p, ASN1_STRING_length(attr->value.sequence));
+    len = ASN1_STRING_length_ex(attr->value.sequence);
+    if (len > INT_MAX)
+        return NULL;
+    return d2i_ESS_SIGNING_CERT(NULL, &p, (int)len);
 }

 static ESS_SIGNING_CERT_V2 *ossl_ess_get_signing_cert_v2(const PKCS7_SIGNER_INFO *si)
 {
     const ASN1_TYPE *attr;
     const unsigned char *p;
+    size_t len;

     attr = PKCS7_get_signed_attribute(si, NID_id_smime_aa_signingCertificateV2);
     if (attr == NULL || attr->type != V_ASN1_SEQUENCE)
         return NULL;
     p = ASN1_STRING_get0_data(attr->value.sequence);
-    return d2i_ESS_SIGNING_CERT_V2(NULL, &p, ASN1_STRING_length(attr->value.sequence));
+    len = ASN1_STRING_length_ex(attr->value.sequence);
+    if (len > INT_MAX)
+        return NULL;
+    return d2i_ESS_SIGNING_CERT_V2(NULL, &p, (int)len);
 }

 static int ts_check_signing_certs(const PKCS7_SIGNER_INFO *si,
@@ -482,6 +490,7 @@ static int ts_check_imprints(X509_ALGOR *algor_a,
     TS_MSG_IMPRINT *b = tst_info->msg_imprint;
     X509_ALGOR *algor_b = b->hash_algo;
     int ret = 0;
+    size_t len;

     if (algor_a) {
         if (OBJ_cmp(algor_a->algorithm, algor_b->algorithm))
@@ -495,7 +504,11 @@ static int ts_check_imprints(X509_ALGOR *algor_a,
             goto err;
     }

-    ret = len_a == (unsigned)ASN1_STRING_length(b->hashed_msg) && memcmp(imprint_a, ASN1_STRING_get0_data(b->hashed_msg), len_a) == 0;
+    len = ASN1_STRING_length_ex(b->hashed_msg);
+    if (len > INT_MAX)
+        goto err;
+
+    ret = len_a == (unsigned)len && memcmp(imprint_a, ASN1_STRING_get0_data(b->hashed_msg), len) == 0;
 err:
     if (!ret)
         ERR_raise(ERR_LIB_TS, TS_R_MESSAGE_IMPRINT_MISMATCH);
diff --git a/crypto/ts/ts_verify_ctx.c b/crypto/ts/ts_verify_ctx.c
index ec9993ed9f..76835866d7 100644
--- a/crypto/ts/ts_verify_ctx.c
+++ b/crypto/ts/ts_verify_ctx.c
@@ -142,6 +142,7 @@ TS_VERIFY_CTX *TS_REQ_to_TS_VERIFY_CTX(TS_REQ *req, TS_VERIFY_CTX *ctx)
     X509_ALGOR *md_alg;
     ASN1_OCTET_STRING *msg;
     const ASN1_INTEGER *nonce;
+    size_t tmp;

     OPENSSL_assert(req != NULL);
     if (ret)
@@ -162,8 +163,11 @@ TS_VERIFY_CTX *TS_REQ_to_TS_VERIFY_CTX(TS_REQ *req, TS_VERIFY_CTX *ctx)
     if ((ret->md_alg = X509_ALGOR_dup(md_alg)) == NULL)
         goto err;
     msg = imprint->hashed_msg;
-    ret->imprint_len = ASN1_STRING_length(msg);
-    if (ret->imprint_len <= 0)
+    tmp = ASN1_STRING_length_ex(msg);
+    if (tmp > INT_MAX)
+        goto err;
+    ret->imprint_len = (unsigned int)tmp;
+    if (ret->imprint_len == 0)
         goto err;
     if ((ret->imprint = OPENSSL_malloc(ret->imprint_len)) == NULL)
         goto err;
diff --git a/crypto/x509/t_x509.c b/crypto/x509/t_x509.c
index cf8062a902..abe1b7557d 100644
--- a/crypto/x509/t_x509.c
+++ b/crypto/x509/t_x509.c
@@ -244,7 +244,7 @@ int X509_ocspid_print(BIO *bp, const X509 *x)
         goto err;

     if (!EVP_Digest(ASN1_STRING_get0_data(keybstr),
-            ASN1_STRING_length(keybstr), SHA1md, NULL, md, NULL))
+            ASN1_STRING_length_ex(keybstr), SHA1md, NULL, md, NULL))
         goto err;
     for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
         if (BIO_printf(bp, "%02X", SHA1md[i]) <= 0)
diff --git a/crypto/x509/v3_addr.c b/crypto/x509/v3_addr.c
index bdaa74a0d1..e245e2b08a 100644
--- a/crypto/x509/v3_addr.c
+++ b/crypto/x509/v3_addr.c
@@ -409,6 +409,11 @@ static int make_addressPrefix(IPAddressOrRange **result, unsigned char *addr,
 {
     int bytelen = (prefixlen + 7) / 8, bitlen = prefixlen % 8;
     IPAddressOrRange *aor;
+    unsigned char *prefix = NULL;
+    uint8_t unused_bits = 0;
+
+    if (bitlen > 0)
+        unused_bits = 8 - bitlen;

     if (prefixlen < 0 || prefixlen > (afilen * 8))
         return 0;
@@ -417,19 +422,23 @@ static int make_addressPrefix(IPAddressOrRange **result, unsigned char *addr,
     aor->type = IPAddressOrRange_addressPrefix;
     if (aor->u.addressPrefix == NULL && (aor->u.addressPrefix = ASN1_BIT_STRING_new()) == NULL)
         goto err;
-    /* BIT_STRING is a typedef of STRING
-     * this function allows to set value without checking invalid bits
-     * as they are nullified after setting */
-    if (!ASN1_STRING_set(aor->u.addressPrefix, addr, bytelen))
+    if (bytelen > 0) {
+        prefix = OPENSSL_malloc(bytelen);
+        if (prefix == NULL)
+            goto err;
+        memcpy(prefix, addr, bytelen);
+        if (unused_bits)
+            prefix[bytelen - 1] &= ~(0xFF >> bitlen);
+    }
+    if (!ASN1_BIT_STRING_set1(aor->u.addressPrefix, prefix, bytelen, unused_bits))
         goto err;
-    if (bitlen > 0)
-        aor->u.addressPrefix->data[bytelen - 1] &= ~(0xFF >> bitlen);
-    ossl_asn1_bit_string_set_unused_bits(aor->u.addressPrefix, 8 - bitlen);
-
     *result = aor;
+
+    OPENSSL_free(prefix);
     return 1;

 err:
+    OPENSSL_free(prefix);
     IPAddressOrRange_free(aor);
     return 0;
 }
diff --git a/crypto/x509/v3_akid.c b/crypto/x509/v3_akid.c
index f500165d0d..95b904c757 100644
--- a/crypto/x509/v3_akid.c
+++ b/crypto/x509/v3_akid.c
@@ -186,7 +186,7 @@ static AUTHORITY_KEYID *v2i_AUTHORITY_KEYID(X509V3_EXT_METHOD *method,
             && !(same_issuer && !ss)) {
             ikeyid = X509V3_EXT_d2i(ext);
             /* Ignore empty keyids in the issuer cert */
-            if (ASN1_STRING_length(ikeyid) == 0) {
+            if (ASN1_STRING_length_ex(ikeyid) == 0) {
                 ASN1_OCTET_STRING_free(ikeyid);
                 ikeyid = NULL;
             }
diff --git a/crypto/x509/v3_cpols.c b/crypto/x509/v3_cpols.c
index 0dc8f76ad4..2cc71f567b 100644
--- a/crypto/x509/v3_cpols.c
+++ b/crypto/x509/v3_cpols.c
@@ -208,8 +208,7 @@ static POLICYINFO *policy_section(X509V3_CTX *ctx,
                 ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
                 goto err;
             }
-            if (!ASN1_STRING_set(qual->d.cpsuri, cnf->value,
-                    (int)strlen(cnf->value))) {
+            if (!ASN1_STRING_set_string(qual->d.cpsuri, cnf->value)) {
                 ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
                 goto err;
             }
@@ -325,7 +324,7 @@ static POLICYQUALINFO *notice_section(X509V3_CTX *ctx,
             if (tag_len != 0)
                 value += tag_len + 1;
             len = (int)strlen(value);
-            if (!ASN1_STRING_set(not->exptext, value, len)) {
+            if (!ASN1_STRING_set_data(not->exptext, (uint8_t *)value, len)) {
                 ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
                 goto err;
             }
@@ -344,8 +343,7 @@ static POLICYQUALINFO *notice_section(X509V3_CTX *ctx,
                 nref->organization->type = V_ASN1_IA5STRING;
             else
                 nref->organization->type = V_ASN1_VISIBLESTRING;
-            if (!ASN1_STRING_set(nref->organization, cnf->value,
-                    (int)strlen(cnf->value))) {
+            if (!ASN1_STRING_set_string(nref->organization, cnf->value)) {
                 ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
                 goto err;
             }
diff --git a/crypto/x509/v3_ia5.c b/crypto/x509/v3_ia5.c
index 539c43a141..a8fa52a439 100644
--- a/crypto/x509/v3_ia5.c
+++ b/crypto/x509/v3_ia5.c
@@ -52,7 +52,7 @@ ASN1_IA5STRING *s2i_ASN1_IA5STRING(X509V3_EXT_METHOD *method,
         ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
         return NULL;
     }
-    if (!ASN1_STRING_set((ASN1_STRING *)ia5, str, (int)strlen(str))) {
+    if (!ASN1_STRING_set_string((ASN1_STRING *)ia5, str)) {
         ASN1_IA5STRING_free(ia5);
         return NULL;
     }
diff --git a/crypto/x509/v3_ist.c b/crypto/x509/v3_ist.c
index 0409b52d60..a4d3437192 100644
--- a/crypto/x509/v3_ist.c
+++ b/crypto/x509/v3_ist.c
@@ -52,28 +52,28 @@ static ISSUER_SIGN_TOOL *v2i_issuer_sign_tool(X509V3_EXT_METHOD *method, X509V3_
         if (strcmp(cnf->name, "signTool") == 0) {
             if (ist->signTool == NULL
                 || cnf->value == NULL
-                || !ASN1_STRING_set(ist->signTool, cnf->value, (int)strlen(cnf->value))) {
+                || !ASN1_STRING_set_string(ist->signTool, cnf->value)) {
                 ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
                 goto err;
             }
         } else if (strcmp(cnf->name, "cATool") == 0) {
             if (ist->cATool == NULL
                 || cnf->value == NULL
-                || !ASN1_STRING_set(ist->cATool, cnf->value, (int)strlen(cnf->value))) {
+                || !ASN1_STRING_set_string(ist->cATool, cnf->value)) {
                 ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
                 goto err;
             }
         } else if (strcmp(cnf->name, "signToolCert") == 0) {
             if (ist->signToolCert == NULL
                 || cnf->value == NULL
-                || !ASN1_STRING_set(ist->signToolCert, cnf->value, (int)strlen(cnf->value))) {
+                || !ASN1_STRING_set_string(ist->signToolCert, cnf->value)) {
                 ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
                 goto err;
             }
         } else if (strcmp(cnf->name, "cAToolCert") == 0) {
             if (ist->cAToolCert == NULL
                 || cnf->value == NULL
-                || !ASN1_STRING_set(ist->cAToolCert, cnf->value, (int)strlen(cnf->value))) {
+                || !ASN1_STRING_set_string(ist->cAToolCert, cnf->value)) {
                 ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
                 goto err;
             }
diff --git a/crypto/x509/v3_lib.c b/crypto/x509/v3_lib.c
index aee7ad119f..a099177dba 100644
--- a/crypto/x509/v3_lib.c
+++ b/crypto/x509/v3_lib.c
@@ -169,16 +169,18 @@ void *X509V3_EXT_d2i(const X509_EXTENSION *ext)
     const X509V3_EXT_METHOD *method;
     const unsigned char *p;
     const ASN1_STRING *extvalue;
-    int extlen;
+    size_t extlen;

     if ((method = X509V3_EXT_get(ext)) == NULL)
         return NULL;
     extvalue = X509_EXTENSION_get_data(ext);
     p = ASN1_STRING_get0_data(extvalue);
-    extlen = ASN1_STRING_length(extvalue);
+    extlen = ASN1_STRING_length_ex(extvalue);
+    if (extlen > INT_MAX)
+        return NULL;
     if (method->it)
-        return ASN1_item_d2i(NULL, &p, extlen, ASN1_ITEM_ptr(method->it));
-    return method->d2i(NULL, &p, extlen);
+        return ASN1_item_d2i(NULL, &p, (int)extlen, ASN1_ITEM_ptr(method->it));
+    return method->d2i(NULL, &p, (int)extlen);
 }

 /*-
diff --git a/crypto/x509/v3_prn.c b/crypto/x509/v3_prn.c
index 4a0df33ea3..0fb7c9e38a 100644
--- a/crypto/x509/v3_prn.c
+++ b/crypto/x509/v3_prn.c
@@ -73,24 +73,26 @@ int X509V3_EXT_print(BIO *out, const X509_EXTENSION *ext, unsigned long flag,
     char *value = NULL;
     const ASN1_OCTET_STRING *extoct;
     const unsigned char *p;
-    int extlen;
+    size_t extlen;
     const X509V3_EXT_METHOD *method;
     STACK_OF(CONF_VALUE) *nval = NULL;
     int ok = 1;

     extoct = X509_EXTENSION_get_data(ext);
     p = ASN1_STRING_get0_data(extoct);
-    extlen = ASN1_STRING_length(extoct);
+    extlen = ASN1_STRING_length_ex(extoct);
+    if (extlen > INT_MAX)
+        return 0;

     if ((method = X509V3_EXT_get(ext)) == NULL)
-        return unknown_ext_print(out, p, extlen, flag, indent, 0);
+        return unknown_ext_print(out, p, (int)extlen, flag, indent, 0);
     if (method->it)
-        ext_str = ASN1_item_d2i(NULL, &p, extlen, ASN1_ITEM_ptr(method->it));
+        ext_str = ASN1_item_d2i(NULL, &p, (int)extlen, ASN1_ITEM_ptr(method->it));
     else
-        ext_str = method->d2i(NULL, &p, extlen);
+        ext_str = method->d2i(NULL, &p, (int)extlen);

     if (!ext_str)
-        return unknown_ext_print(out, p, extlen, flag, indent, 1);
+        return unknown_ext_print(out, p, (int)extlen, flag, indent, 1);

     if (method->i2s) {
         if ((value = method->i2s(method, ext_str)) == NULL) {
diff --git a/crypto/x509/v3_san.c b/crypto/x509/v3_san.c
index 0f12939d6d..f1b028f78c 100644
--- a/crypto/x509/v3_san.c
+++ b/crypto/x509/v3_san.c
@@ -575,7 +575,8 @@ GENERAL_NAME *a2i_GENERAL_NAME(GENERAL_NAME *out,
     }

     if (is_string) {
-        if ((gen->d.ia5 = ASN1_IA5STRING_new()) == NULL || !ASN1_STRING_set(gen->d.ia5, (unsigned char *)value, (int)strlen(value))) {
+        if ((gen->d.ia5 = ASN1_IA5STRING_new()) == NULL
+            || !ASN1_STRING_set_string(gen->d.ia5, value)) {
             ASN1_IA5STRING_free(gen->d.ia5);
             gen->d.ia5 = NULL;
             ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
diff --git a/crypto/x509/v3_utf8.c b/crypto/x509/v3_utf8.c
index 49095ffdd9..dc7c86fb7f 100644
--- a/crypto/x509/v3_utf8.c
+++ b/crypto/x509/v3_utf8.c
@@ -55,7 +55,7 @@ ASN1_UTF8STRING *s2i_ASN1_UTF8STRING(X509V3_EXT_METHOD *method,
         ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
         return NULL;
     }
-    if (!ASN1_STRING_set((ASN1_STRING *)utf8, str, (int)strlen(str))) {
+    if (!ASN1_STRING_set_string(utf8, str)) {
         ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
         ASN1_UTF8STRING_free(utf8);
         return NULL;
diff --git a/crypto/x509/x509_att.c b/crypto/x509/x509_att.c
index ee631db75a..e08e490274 100644
--- a/crypto/x509/x509_att.c
+++ b/crypto/x509/x509_att.c
@@ -365,7 +365,7 @@ int X509_ATTRIBUTE_set1_data(X509_ATTRIBUTE *attr, int attrtype,
         atype = stmp->type;
     } else if (len != -1) {
         if ((stmp = ASN1_STRING_type_new(attrtype)) == NULL
-            || !ASN1_STRING_set(stmp, data, len)) {
+            || !ASN1_STRING_set_data(stmp, data, len)) {
             ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
             goto err;
         }
diff --git a/crypto/x509/x509name.c b/crypto/x509/x509name.c
index ebd58a2012..58167d9a78 100644
--- a/crypto/x509/x509name.c
+++ b/crypto/x509/x509name.c
@@ -332,9 +332,12 @@ int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type,
                    OBJ_obj2nid(ne->object))
             ? 1
             : 0;
-    if (len < 0)
-        len = (int)strlen((const char *)bytes);
-    i = ASN1_STRING_set(ne->value, bytes, len);
+    if (len < -1)
+        return 0;
+    if (len == -1)
+        i = ASN1_STRING_set_string(ne->value, (const char *)bytes);
+    else
+        i = ASN1_STRING_set_data(ne->value, bytes, (size_t)len);
     if (!i)
         return 0;
     if (type != V_ASN1_UNDEF) {
diff --git a/crypto/x509/x_x509a.c b/crypto/x509/x_x509a.c
index 6dfd68f74d..3fa17fb925 100644
--- a/crypto/x509/x_x509a.c
+++ b/crypto/x509/x_x509a.c
@@ -50,6 +50,8 @@ static X509_CERT_AUX *aux_get(X509 *x)
 int X509_alias_set1(X509 *x, const unsigned char *name, int len)
 {
     X509_CERT_AUX *aux;
+    size_t len_s;
+
     if (!name) {
         if (!x || !x->aux || !x->aux->alias)
             return 1;
@@ -59,14 +61,25 @@ int X509_alias_set1(X509 *x, const unsigned char *name, int len)
     }
     if ((aux = aux_get(x)) == NULL)
         return 0;
+
+    if (len < -1)
+        return 0;
+
+    if (len == -1)
+        len_s = strlen((const char *)name);
+    else
+        len_s = len;
+
     if (aux->alias == NULL && (aux->alias = ASN1_UTF8STRING_new()) == NULL)
         return 0;
-    return ASN1_STRING_set(aux->alias, name, len);
+    return ASN1_STRING_set_data(aux->alias, name, len_s);
 }

 int X509_keyid_set1(X509 *x, const unsigned char *id, int len)
 {
     X509_CERT_AUX *aux;
+    size_t len_s;
+
     if (!id) {
         if (!x || !x->aux || !x->aux->keyid)
             return 1;
@@ -76,10 +89,19 @@ int X509_keyid_set1(X509 *x, const unsigned char *id, int len)
     }
     if ((aux = aux_get(x)) == NULL)
         return 0;
+
+    if (len < -1)
+        return 0;
+
+    if (len == -1)
+        len_s = strlen((const char *)id);
+    else
+        len_s = len;
+
     if (aux->keyid == NULL
         && (aux->keyid = ASN1_OCTET_STRING_new()) == NULL)
         return 0;
-    return ASN1_STRING_set(aux->keyid, id, len);
+    return ASN1_STRING_set_data(aux->keyid, id, len_s);
 }

 const unsigned char *X509_alias_get0(const X509 *x, int *len)
diff --git a/ssl/statem/statem_srvr.c b/ssl/statem/statem_srvr.c
index a90d401679..2f8bdcea94 100644
--- a/ssl/statem/statem_srvr.c
+++ b/ssl/statem/statem_srvr.c
@@ -3562,7 +3562,8 @@ static int tls_process_cke_gost(SSL_CONNECTION *s, PACKET *pkt)
     EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
     unsigned char premaster_secret[32];
     const unsigned char *start;
-    size_t outlen = sizeof(premaster_secret), inlen;
+    size_t outlen = sizeof(premaster_secret);
+    size_t inlen;
     unsigned long alg_a;
     GOST_KX_MESSAGE *pKX = NULL;
     const unsigned char *ptr;
@@ -3628,7 +3629,10 @@ static int tls_process_cke_gost(SSL_CONNECTION *s, PACKET *pkt)
         goto err;
     }

-    inlen = ASN1_STRING_length(pKX->kxBlob->value.sequence);
+    inlen = ASN1_STRING_length_ex(pKX->kxBlob->value.sequence);
+    if (inlen > INT_MAX)
+        goto err;
+
     start = ASN1_STRING_get0_data(pKX->kxBlob->value.sequence);

     if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start,
diff --git a/test/asn1_string_test.c b/test/asn1_string_test.c
index 24d679444b..865003eeb9 100644
--- a/test/asn1_string_test.c
+++ b/test/asn1_string_test.c
@@ -390,7 +390,6 @@ asn1_bit_string_set1_test(int idx)
 }

 static int
-
 asn1_string_new_not_owned_test(void)
 {
     int success = 0;
diff --git a/test/cmp_hdr_test.c b/test/cmp_hdr_test.c
index cbffb87b23..30f19f6238 100644
--- a/test/cmp_hdr_test.c
+++ b/test/cmp_hdr_test.c
@@ -252,7 +252,7 @@ static int execute_HDR_push0_freeText_test(CMP_HDR_TEST_FIXTURE *fixture)
     if (!TEST_ptr(text))
         return 0;

-    if (!ASN1_STRING_set(text, "A free text", -1))
+    if (!ASN1_STRING_set_string(text, "A free text"))
         goto err;

     if (!TEST_int_eq(ossl_cmp_hdr_push0_freeText(fixture->hdr, text), 1))
@@ -285,7 +285,7 @@ static int execute_HDR_push1_freeText_test(CMP_HDR_TEST_FIXTURE *fixture)
     if (!TEST_ptr(text))
         goto err;

-    if (!ASN1_STRING_set(text, "A free text", -1))
+    if (!ASN1_STRING_set_string(text, "A free text"))
         goto err;

     if (!TEST_int_eq(ossl_cmp_hdr_push1_freeText(fixture->hdr, text), 1))
diff --git a/test/helpers/pkcs12.c b/test/helpers/pkcs12.c
index abc70db1b7..3ecfd020b6 100644
--- a/test/helpers/pkcs12.c
+++ b/test/helpers/pkcs12.c
@@ -468,21 +468,21 @@ static int check_asn1_string(const ASN1_TYPE *av, const char *txt)
     switch (av->type) {
     case V_ASN1_BMPSTRING:
         value = OPENSSL_uni2asc(ASN1_STRING_get0_data(av->value.bmpstring),
-            ASN1_STRING_length(av->value.bmpstring));
+            (int)ASN1_STRING_length_ex(av->value.bmpstring));
         if (!TEST_str_eq(txt, (char *)value))
             goto err;
         break;

     case V_ASN1_UTF8STRING:
         if (!TEST_mem_eq(txt, strlen(txt), ASN1_STRING_get0_data(av->value.utf8string),
-                ASN1_STRING_length(av->value.utf8string)))
+                ASN1_STRING_length_ex(av->value.utf8string)))
             goto err;
         break;

     case V_ASN1_OCTET_STRING:
         if (!TEST_mem_eq(txt, strlen(txt),
                 (char *)ASN1_STRING_get0_data(av->value.octet_string),
-                ASN1_STRING_length(av->value.octet_string)))
+                ASN1_STRING_length_ex(av->value.octet_string)))
             goto err;
         break;

diff --git a/test/tls-provider.c b/test/tls-provider.c
index 6652034936..c516cb04b4 100644
--- a/test/tls-provider.c
+++ b/test/tls-provider.c
@@ -1282,7 +1282,7 @@ static XORKEY *xor_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf,
         plen = 0;
     } else {
         p = ASN1_STRING_get0_data(oct);
-        plen = ASN1_STRING_length(oct);
+        plen = (int)ASN1_STRING_length_ex(oct);
     }

     xork = xor_key_op(palg, p, plen, KEY_OP_PRIVATE,
diff --git a/test/v3nametest.c b/test/v3nametest.c
index 8ae7a9e54f..757db8a18e 100644
--- a/test/v3nametest.c
+++ b/test/v3nametest.c
@@ -149,7 +149,7 @@ static int set_altname(X509 *crt, ...)
         ia5 = ASN1_IA5STRING_new();
         if (ia5 == NULL)
             goto out;
-        if (!ASN1_STRING_set(ia5, name, -1))
+        if (!ASN1_STRING_set_string(ia5, name))
             goto out;
         switch (type) {
         case GEN_EMAIL:
diff --git a/test/x509_internal_test.c b/test/x509_internal_test.c
index 19a7c2469d..1176ef49ef 100644
--- a/test/x509_internal_test.c
+++ b/test/x509_internal_test.c
@@ -152,7 +152,7 @@ static int test_a2i_ipaddress(int idx)
 {
     int good = 1;
     ASN1_OCTET_STRING *ip;
-    int len = a2i_ipaddress_tests[idx].length;
+    size_t len = a2i_ipaddress_tests[idx].length;

     ip = a2i_IPADDRESS(a2i_ipaddress_tests[idx].ipasc);
     if (len == 0) {
@@ -162,7 +162,7 @@ static int test_a2i_ipaddress(int idx)
         }
     } else {
         if (!TEST_ptr(ip)
-            || !TEST_int_eq(ASN1_STRING_length(ip), len)
+            || !TEST_size_t_eq(ASN1_STRING_length_ex(ip), len)
             || !TEST_mem_eq(ASN1_STRING_get0_data(ip), len,
                 a2i_ipaddress_tests[idx].data, len)) {
             good = 0;