Fix encoding bug in i2c_ASN1_INTEGER
authorDr. Stephen Henson <steve@openssl.org>
Thu, 16 Apr 2015 15:43:09 +0000 (16:43 +0100)
committerDr. Stephen Henson <steve@openssl.org>
Sat, 18 Apr 2015 13:41:06 +0000 (14:41 +0100)
Fix bug where i2c_ASN1_INTEGER mishandles zero if it is marked as
negative.

Thanks to Huzaifa Sidhpurwala <huzaifas@redhat.com> and
Hanno Böck <hanno@hboeck.de> for reporting this issue.

Reviewed-by: Rich Salz <rsalz@openssl.org>
crypto/asn1/a_int.c

index f7f90ff9014ef44ecda248dbfc16face243909e2..3920d5ce96e9489abdebb878b0b4df9a8e5a80ed 100644 (file)
@@ -125,6 +125,8 @@ int i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp)
     else {
         ret = a->length;
         i = a->data[0];
     else {
         ret = a->length;
         i = a->data[0];
+        if (ret == 1 && i == 0)
+            neg = 0;
         if (!neg && (i > 127)) {
             pad = 1;
             pb = 0;
         if (!neg && (i > 127)) {
             pad = 1;
             pb = 0;
@@ -163,7 +165,7 @@ int i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp)
         p += a->length - 1;
         i = a->length;
         /* Copy zeros to destination as long as source is zero */
         p += a->length - 1;
         i = a->length;
         /* Copy zeros to destination as long as source is zero */
-        while (!*n) {
+        while (!*n && i > 1) {
             *(p--) = 0;
             n--;
             i--;
             *(p--) = 0;
             n--;
             i--;
@@ -418,7 +420,7 @@ ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai)
         ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_NESTED_ASN1_ERROR);
         goto err;
     }
         ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_NESTED_ASN1_ERROR);
         goto err;
     }
-    if (BN_is_negative(bn))
+    if (BN_is_negative(bn) && !BN_is_zero(bn))
         ret->type = V_ASN1_NEG_INTEGER;
     else
         ret->type = V_ASN1_INTEGER;
         ret->type = V_ASN1_NEG_INTEGER;
     else
         ret->type = V_ASN1_INTEGER;