idx
int64
project
string
commit_id
string
project_url
string
commit_url
string
commit_message
string
target
int64
func
string
func_hash
float64
file_name
string
file_hash
float64
cwe
sequence
cve
string
cve_desc
string
nvd_url
string
216,871
openssl
23446958685a593d4d9434475734b99138902ed2
https://github.com/openssl/openssl
https://github.com/openssl/openssl/commit/23446958685a593d4d9434475734b99138902ed2
Fix printing of PROXY_CERT_INFO_EXTENSION to not assume NUL terminated strings ASN.1 strings may not be NUL terminated. Don't assume they are. CVE-2021-3712 Reviewed-by: Viktor Dukhovni <[email protected]> Reviewed-by: Paul Dale <[email protected]>
1
static int i2r_pci(X509V3_EXT_METHOD *method, PROXY_CERT_INFO_EXTENSION *pci, BIO *out, int indent) { BIO_printf(out, "%*sPath Length Constraint: ", indent, ""); if (pci->pcPathLengthConstraint) i2a_ASN1_INTEGER(out, pci->pcPathLengthConstraint); else BIO_printf(out, "infinite"); BIO_puts(out, "\n"); BIO_printf(out, "%*sPolicy Language: ", indent, ""); i2a_ASN1_OBJECT(out, pci->proxyPolicy->policyLanguage); BIO_puts(out, "\n"); if (pci->proxyPolicy->policy && pci->proxyPolicy->policy->data) BIO_printf(out, "%*sPolicy Text: %s\n", indent, "", pci->proxyPolicy->policy->data); return 1; }
277,287,998,004,405,700,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2021-3712
ASN.1 strings are represented internally within OpenSSL as an ASN1_STRING structure which contains a buffer holding the string data and a field holding the buffer length. This contrasts with normal C strings which are repesented as a buffer for the string data which is terminated with a NUL (0) byte. Although not a strict requirement, ASN.1 strings that are parsed using OpenSSL's own "d2i" functions (and other similar parsing functions) as well as any string whose value has been set with the ASN1_STRING_set() function will additionally NUL terminate the byte array in the ASN1_STRING structure. However, it is possible for applications to directly construct valid ASN1_STRING structures which do not NUL terminate the byte array by directly setting the "data" and "length" fields in the ASN1_STRING array. This can also happen by using the ASN1_STRING_set0() function. Numerous OpenSSL functions that print ASN.1 data have been found to assume that the ASN1_STRING byte array will be NUL terminated, even though this is not guaranteed for strings that have been directly constructed. Where an application requests an ASN.1 structure to be printed, and where that ASN.1 structure contains ASN1_STRINGs that have been directly constructed by the application without NUL terminating the "data" field, then a read buffer overrun can occur. The same thing can also occur during name constraints processing of certificates (for example if a certificate has been directly constructed by the application instead of loading it via the OpenSSL parsing functions, and the certificate contains non NUL terminated ASN1_STRING structures). It can also occur in the X509_get1_email(), X509_REQ_get1_email() and X509_get1_ocsp() functions. If a malicious actor can cause an application to directly construct an ASN1_STRING and then process it through one of the affected OpenSSL functions then this issue could be hit. This might result in a crash (causing a Denial of Service attack). It could also result in the disclosure of private memory contents (such as private keys, or sensitive plaintext). Fixed in OpenSSL 1.1.1l (Affected 1.1.1-1.1.1k). Fixed in OpenSSL 1.0.2za (Affected 1.0.2-1.0.2y).
https://nvd.nist.gov/vuln/detail/CVE-2021-3712
507,853
openssl
23446958685a593d4d9434475734b99138902ed2
https://github.com/openssl/openssl
https://github.com/openssl/openssl/commit/23446958685a593d4d9434475734b99138902ed2
Fix printing of PROXY_CERT_INFO_EXTENSION to not assume NUL terminated strings ASN.1 strings may not be NUL terminated. Don't assume they are. CVE-2021-3712 Reviewed-by: Viktor Dukhovni <[email protected]> Reviewed-by: Paul Dale <[email protected]>
0
static int i2r_pci(X509V3_EXT_METHOD *method, PROXY_CERT_INFO_EXTENSION *pci, BIO *out, int indent) { BIO_printf(out, "%*sPath Length Constraint: ", indent, ""); if (pci->pcPathLengthConstraint) i2a_ASN1_INTEGER(out, pci->pcPathLengthConstraint); else BIO_printf(out, "infinite"); BIO_puts(out, "\n"); BIO_printf(out, "%*sPolicy Language: ", indent, ""); i2a_ASN1_OBJECT(out, pci->proxyPolicy->policyLanguage); BIO_puts(out, "\n"); if (pci->proxyPolicy->policy && pci->proxyPolicy->policy->data) BIO_printf(out, "%*sPolicy Text: %.*s\n", indent, "", pci->proxyPolicy->policy->length, pci->proxyPolicy->policy->data); return 1; }
291,842,418,864,040,780,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2021-3712
ASN.1 strings are represented internally within OpenSSL as an ASN1_STRING structure which contains a buffer holding the string data and a field holding the buffer length. This contrasts with normal C strings which are repesented as a buffer for the string data which is terminated with a NUL (0) byte. Although not a strict requirement, ASN.1 strings that are parsed using OpenSSL's own "d2i" functions (and other similar parsing functions) as well as any string whose value has been set with the ASN1_STRING_set() function will additionally NUL terminate the byte array in the ASN1_STRING structure. However, it is possible for applications to directly construct valid ASN1_STRING structures which do not NUL terminate the byte array by directly setting the "data" and "length" fields in the ASN1_STRING array. This can also happen by using the ASN1_STRING_set0() function. Numerous OpenSSL functions that print ASN.1 data have been found to assume that the ASN1_STRING byte array will be NUL terminated, even though this is not guaranteed for strings that have been directly constructed. Where an application requests an ASN.1 structure to be printed, and where that ASN.1 structure contains ASN1_STRINGs that have been directly constructed by the application without NUL terminating the "data" field, then a read buffer overrun can occur. The same thing can also occur during name constraints processing of certificates (for example if a certificate has been directly constructed by the application instead of loading it via the OpenSSL parsing functions, and the certificate contains non NUL terminated ASN1_STRING structures). It can also occur in the X509_get1_email(), X509_REQ_get1_email() and X509_get1_ocsp() functions. If a malicious actor can cause an application to directly construct an ASN1_STRING and then process it through one of the affected OpenSSL functions then this issue could be hit. This might result in a crash (causing a Denial of Service attack). It could also result in the disclosure of private memory contents (such as private keys, or sensitive plaintext). Fixed in OpenSSL 1.1.1l (Affected 1.1.1-1.1.1k). Fixed in OpenSSL 1.0.2za (Affected 1.0.2-1.0.2y).
https://nvd.nist.gov/vuln/detail/CVE-2021-3712
216,874
openssl
d9d838ddc0ed083fb4c26dd067e71aad7c65ad16
https://github.com/openssl/openssl
https://github.com/openssl/openssl/commit/d9d838ddc0ed083fb4c26dd067e71aad7c65ad16
Fix a read buffer overrun in X509_aux_print(). The ASN1_STRING_get0_data(3) manual explitely cautions the reader that the data is not necessarily NUL-terminated, and the function X509_alias_set1(3) does not sanitize the data passed into it in any way either, so we must assume the return value from X509_alias_get0(3) is merely a byte array and not necessarily a string in the sense of the C language. I found this bug while writing manual pages for X509_print_ex(3) and related functions. Theo Buehler <[email protected]> checked my patch to fix the same bug in LibreSSL, see http://cvsweb.openbsd.org/src/lib/libcrypto/asn1/t_x509a.c#rev1.9 As an aside, note that the function still produces incomplete and misleading results when the data contains a NUL byte in the middle and that error handling is consistently absent throughout, even though the function provides an "int" return value obviously intended to be 1 for success and 0 for failure, and even though this function is called by another function that also wants to return 1 for success and 0 for failure and even does so in many of its code paths, though not in others. But let's stay focussed. Many things would be nice to have in the wide wild world, but a buffer overflow must not be allowed to remain in our backyard. CLA: trivial Reviewed-by: Tim Hudson <[email protected]> Reviewed-by: Paul Dale <[email protected]> Reviewed-by: Tomas Mraz <[email protected]> (Merged from https://github.com/openssl/openssl/pull/16108) (cherry picked from commit c5dc9ab965f2a69bca964c709e648158f3e4cd67)
1
int X509_aux_print(BIO *out, X509 *x, int indent) { char oidstr[80], first; STACK_OF(ASN1_OBJECT) *trust, *reject; const unsigned char *alias, *keyid; int keyidlen; int i; if (X509_trusted(x) == 0) return 1; trust = X509_get0_trust_objects(x); reject = X509_get0_reject_objects(x); if (trust) { first = 1; BIO_printf(out, "%*sTrusted Uses:\n%*s", indent, "", indent + 2, ""); for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++) { if (!first) BIO_puts(out, ", "); else first = 0; OBJ_obj2txt(oidstr, sizeof(oidstr), sk_ASN1_OBJECT_value(trust, i), 0); BIO_puts(out, oidstr); } BIO_puts(out, "\n"); } else BIO_printf(out, "%*sNo Trusted Uses.\n", indent, ""); if (reject) { first = 1; BIO_printf(out, "%*sRejected Uses:\n%*s", indent, "", indent + 2, ""); for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++) { if (!first) BIO_puts(out, ", "); else first = 0; OBJ_obj2txt(oidstr, sizeof(oidstr), sk_ASN1_OBJECT_value(reject, i), 0); BIO_puts(out, oidstr); } BIO_puts(out, "\n"); } else BIO_printf(out, "%*sNo Rejected Uses.\n", indent, ""); alias = X509_alias_get0(x, NULL); if (alias) BIO_printf(out, "%*sAlias: %s\n", indent, "", alias); keyid = X509_keyid_get0(x, &keyidlen); if (keyid) { BIO_printf(out, "%*sKey Id: ", indent, ""); for (i = 0; i < keyidlen; i++) BIO_printf(out, "%s%02X", i ? ":" : "", keyid[i]); BIO_write(out, "\n", 1); } return 1; }
252,393,493,912,061,800,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2021-3712
ASN.1 strings are represented internally within OpenSSL as an ASN1_STRING structure which contains a buffer holding the string data and a field holding the buffer length. This contrasts with normal C strings which are repesented as a buffer for the string data which is terminated with a NUL (0) byte. Although not a strict requirement, ASN.1 strings that are parsed using OpenSSL's own "d2i" functions (and other similar parsing functions) as well as any string whose value has been set with the ASN1_STRING_set() function will additionally NUL terminate the byte array in the ASN1_STRING structure. However, it is possible for applications to directly construct valid ASN1_STRING structures which do not NUL terminate the byte array by directly setting the "data" and "length" fields in the ASN1_STRING array. This can also happen by using the ASN1_STRING_set0() function. Numerous OpenSSL functions that print ASN.1 data have been found to assume that the ASN1_STRING byte array will be NUL terminated, even though this is not guaranteed for strings that have been directly constructed. Where an application requests an ASN.1 structure to be printed, and where that ASN.1 structure contains ASN1_STRINGs that have been directly constructed by the application without NUL terminating the "data" field, then a read buffer overrun can occur. The same thing can also occur during name constraints processing of certificates (for example if a certificate has been directly constructed by the application instead of loading it via the OpenSSL parsing functions, and the certificate contains non NUL terminated ASN1_STRING structures). It can also occur in the X509_get1_email(), X509_REQ_get1_email() and X509_get1_ocsp() functions. If a malicious actor can cause an application to directly construct an ASN1_STRING and then process it through one of the affected OpenSSL functions then this issue could be hit. This might result in a crash (causing a Denial of Service attack). It could also result in the disclosure of private memory contents (such as private keys, or sensitive plaintext). Fixed in OpenSSL 1.1.1l (Affected 1.1.1-1.1.1k). Fixed in OpenSSL 1.0.2za (Affected 1.0.2-1.0.2y).
https://nvd.nist.gov/vuln/detail/CVE-2021-3712
507,868
openssl
d9d838ddc0ed083fb4c26dd067e71aad7c65ad16
https://github.com/openssl/openssl
https://github.com/openssl/openssl/commit/d9d838ddc0ed083fb4c26dd067e71aad7c65ad16
Fix a read buffer overrun in X509_aux_print(). The ASN1_STRING_get0_data(3) manual explitely cautions the reader that the data is not necessarily NUL-terminated, and the function X509_alias_set1(3) does not sanitize the data passed into it in any way either, so we must assume the return value from X509_alias_get0(3) is merely a byte array and not necessarily a string in the sense of the C language. I found this bug while writing manual pages for X509_print_ex(3) and related functions. Theo Buehler <[email protected]> checked my patch to fix the same bug in LibreSSL, see http://cvsweb.openbsd.org/src/lib/libcrypto/asn1/t_x509a.c#rev1.9 As an aside, note that the function still produces incomplete and misleading results when the data contains a NUL byte in the middle and that error handling is consistently absent throughout, even though the function provides an "int" return value obviously intended to be 1 for success and 0 for failure, and even though this function is called by another function that also wants to return 1 for success and 0 for failure and even does so in many of its code paths, though not in others. But let's stay focussed. Many things would be nice to have in the wide wild world, but a buffer overflow must not be allowed to remain in our backyard. CLA: trivial Reviewed-by: Tim Hudson <[email protected]> Reviewed-by: Paul Dale <[email protected]> Reviewed-by: Tomas Mraz <[email protected]> (Merged from https://github.com/openssl/openssl/pull/16108) (cherry picked from commit c5dc9ab965f2a69bca964c709e648158f3e4cd67)
0
int X509_aux_print(BIO *out, X509 *x, int indent) { char oidstr[80], first; STACK_OF(ASN1_OBJECT) *trust, *reject; const unsigned char *alias, *keyid; int keyidlen; int i; if (X509_trusted(x) == 0) return 1; trust = X509_get0_trust_objects(x); reject = X509_get0_reject_objects(x); if (trust) { first = 1; BIO_printf(out, "%*sTrusted Uses:\n%*s", indent, "", indent + 2, ""); for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++) { if (!first) BIO_puts(out, ", "); else first = 0; OBJ_obj2txt(oidstr, sizeof(oidstr), sk_ASN1_OBJECT_value(trust, i), 0); BIO_puts(out, oidstr); } BIO_puts(out, "\n"); } else BIO_printf(out, "%*sNo Trusted Uses.\n", indent, ""); if (reject) { first = 1; BIO_printf(out, "%*sRejected Uses:\n%*s", indent, "", indent + 2, ""); for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++) { if (!first) BIO_puts(out, ", "); else first = 0; OBJ_obj2txt(oidstr, sizeof(oidstr), sk_ASN1_OBJECT_value(reject, i), 0); BIO_puts(out, oidstr); } BIO_puts(out, "\n"); } else BIO_printf(out, "%*sNo Rejected Uses.\n", indent, ""); alias = X509_alias_get0(x, &i); if (alias) BIO_printf(out, "%*sAlias: %.*s\n", indent, "", i, alias); keyid = X509_keyid_get0(x, &keyidlen); if (keyid) { BIO_printf(out, "%*sKey Id: ", indent, ""); for (i = 0; i < keyidlen; i++) BIO_printf(out, "%s%02X", i ? ":" : "", keyid[i]); BIO_write(out, "\n", 1); } return 1; }
259,335,861,165,031,600,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2021-3712
ASN.1 strings are represented internally within OpenSSL as an ASN1_STRING structure which contains a buffer holding the string data and a field holding the buffer length. This contrasts with normal C strings which are repesented as a buffer for the string data which is terminated with a NUL (0) byte. Although not a strict requirement, ASN.1 strings that are parsed using OpenSSL's own "d2i" functions (and other similar parsing functions) as well as any string whose value has been set with the ASN1_STRING_set() function will additionally NUL terminate the byte array in the ASN1_STRING structure. However, it is possible for applications to directly construct valid ASN1_STRING structures which do not NUL terminate the byte array by directly setting the "data" and "length" fields in the ASN1_STRING array. This can also happen by using the ASN1_STRING_set0() function. Numerous OpenSSL functions that print ASN.1 data have been found to assume that the ASN1_STRING byte array will be NUL terminated, even though this is not guaranteed for strings that have been directly constructed. Where an application requests an ASN.1 structure to be printed, and where that ASN.1 structure contains ASN1_STRINGs that have been directly constructed by the application without NUL terminating the "data" field, then a read buffer overrun can occur. The same thing can also occur during name constraints processing of certificates (for example if a certificate has been directly constructed by the application instead of loading it via the OpenSSL parsing functions, and the certificate contains non NUL terminated ASN1_STRING structures). It can also occur in the X509_get1_email(), X509_REQ_get1_email() and X509_get1_ocsp() functions. If a malicious actor can cause an application to directly construct an ASN1_STRING and then process it through one of the affected OpenSSL functions then this issue could be hit. This might result in a crash (causing a Denial of Service attack). It could also result in the disclosure of private memory contents (such as private keys, or sensitive plaintext). Fixed in OpenSSL 1.1.1l (Affected 1.1.1-1.1.1k). Fixed in OpenSSL 1.0.2za (Affected 1.0.2-1.0.2y).
https://nvd.nist.gov/vuln/detail/CVE-2021-3712
216,907
openssl
3118eb64934499d93db3230748a452351d1d9a65
https://github.com/openssl/openssl
https://git.openssl.org/gitweb/?p=openssl.git;a=commitdiff;h=3118eb64934499d93db3230748a452351d1d9a65
Fix possible infinite loop in BN_mod_sqrt() The calculation in some cases does not finish for non-prime p. This fixes CVE-2022-0778. Based on patch by David Benjamin <[email protected]>. Reviewed-by: Paul Dale <[email protected]> Reviewed-by: Matt Caswell <[email protected]>
1
BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) /* * Returns 'ret' such that ret^2 == a (mod p), using the Tonelli/Shanks * algorithm (cf. Henri Cohen, "A Course in Algebraic Computational Number * Theory", algorithm 1.5.1). 'p' must be prime! */ { BIGNUM *ret = in; int err = 1; int r; BIGNUM *A, *b, *q, *t, *x, *y; int e, i, j; if (!BN_is_odd(p) || BN_abs_is_word(p, 1)) { if (BN_abs_is_word(p, 2)) { if (ret == NULL) ret = BN_new(); if (ret == NULL) goto end; if (!BN_set_word(ret, BN_is_bit_set(a, 0))) { if (ret != in) BN_free(ret); return NULL; } bn_check_top(ret); return ret; } BNerr(BN_F_BN_MOD_SQRT, BN_R_P_IS_NOT_PRIME); return NULL; } if (BN_is_zero(a) || BN_is_one(a)) { if (ret == NULL) ret = BN_new(); if (ret == NULL) goto end; if (!BN_set_word(ret, BN_is_one(a))) { if (ret != in) BN_free(ret); return NULL; } bn_check_top(ret); return ret; } BN_CTX_start(ctx); A = BN_CTX_get(ctx); b = BN_CTX_get(ctx); q = BN_CTX_get(ctx); t = BN_CTX_get(ctx); x = BN_CTX_get(ctx); y = BN_CTX_get(ctx); if (y == NULL) goto end; if (ret == NULL) ret = BN_new(); if (ret == NULL) goto end; /* A = a mod p */ if (!BN_nnmod(A, a, p, ctx)) goto end; /* now write |p| - 1 as 2^e*q where q is odd */ e = 1; while (!BN_is_bit_set(p, e)) e++; /* we'll set q later (if needed) */ if (e == 1) { /*- * The easy case: (|p|-1)/2 is odd, so 2 has an inverse * modulo (|p|-1)/2, and square roots can be computed * directly by modular exponentiation. * We have * 2 * (|p|+1)/4 == 1 (mod (|p|-1)/2), * so we can use exponent (|p|+1)/4, i.e. (|p|-3)/4 + 1. */ if (!BN_rshift(q, p, 2)) goto end; q->neg = 0; if (!BN_add_word(q, 1)) goto end; if (!BN_mod_exp(ret, A, q, p, ctx)) goto end; err = 0; goto vrfy; } if (e == 2) { /*- * |p| == 5 (mod 8) * * In this case 2 is always a non-square since * Legendre(2,p) = (-1)^((p^2-1)/8) for any odd prime. * So if a really is a square, then 2*a is a non-square. * Thus for * b := (2*a)^((|p|-5)/8), * i := (2*a)*b^2 * we have * i^2 = (2*a)^((1 + (|p|-5)/4)*2) * = (2*a)^((p-1)/2) * = -1; * so if we set * x := a*b*(i-1), * then * x^2 = a^2 * b^2 * (i^2 - 2*i + 1) * = a^2 * b^2 * (-2*i) * = a*(-i)*(2*a*b^2) * = a*(-i)*i * = a. * * (This is due to A.O.L. Atkin, * Subject: Square Roots and Cognate Matters modulo p=8n+5. * URL: https://listserv.nodak.edu/cgi-bin/wa.exe?A2=ind9211&L=NMBRTHRY&P=4026 * November 1992.) */ /* t := 2*a */ if (!BN_mod_lshift1_quick(t, A, p)) goto end; /* b := (2*a)^((|p|-5)/8) */ if (!BN_rshift(q, p, 3)) goto end; q->neg = 0; if (!BN_mod_exp(b, t, q, p, ctx)) goto end; /* y := b^2 */ if (!BN_mod_sqr(y, b, p, ctx)) goto end; /* t := (2*a)*b^2 - 1 */ if (!BN_mod_mul(t, t, y, p, ctx)) goto end; if (!BN_sub_word(t, 1)) goto end; /* x = a*b*t */ if (!BN_mod_mul(x, A, b, p, ctx)) goto end; if (!BN_mod_mul(x, x, t, p, ctx)) goto end; if (!BN_copy(ret, x)) goto end; err = 0; goto vrfy; } /* * e > 2, so we really have to use the Tonelli/Shanks algorithm. First, * find some y that is not a square. */ if (!BN_copy(q, p)) goto end; /* use 'q' as temp */ q->neg = 0; i = 2; do { /* * For efficiency, try small numbers first; if this fails, try random * numbers. */ if (i < 22) { if (!BN_set_word(y, i)) goto end; } else { if (!BN_priv_rand(y, BN_num_bits(p), 0, 0)) goto end; if (BN_ucmp(y, p) >= 0) { if (!(p->neg ? BN_add : BN_sub) (y, y, p)) goto end; } /* now 0 <= y < |p| */ if (BN_is_zero(y)) if (!BN_set_word(y, i)) goto end; } r = BN_kronecker(y, q, ctx); /* here 'q' is |p| */ if (r < -1) goto end; if (r == 0) { /* m divides p */ BNerr(BN_F_BN_MOD_SQRT, BN_R_P_IS_NOT_PRIME); goto end; } } while (r == 1 && ++i < 82); if (r != -1) { /* * Many rounds and still no non-square -- this is more likely a bug * than just bad luck. Even if p is not prime, we should have found * some y such that r == -1. */ BNerr(BN_F_BN_MOD_SQRT, BN_R_TOO_MANY_ITERATIONS); goto end; } /* Here's our actual 'q': */ if (!BN_rshift(q, q, e)) goto end; /* * Now that we have some non-square, we can find an element of order 2^e * by computing its q'th power. */ if (!BN_mod_exp(y, y, q, p, ctx)) goto end; if (BN_is_one(y)) { BNerr(BN_F_BN_MOD_SQRT, BN_R_P_IS_NOT_PRIME); goto end; } /*- * Now we know that (if p is indeed prime) there is an integer * k, 0 <= k < 2^e, such that * * a^q * y^k == 1 (mod p). * * As a^q is a square and y is not, k must be even. * q+1 is even, too, so there is an element * * X := a^((q+1)/2) * y^(k/2), * * and it satisfies * * X^2 = a^q * a * y^k * = a, * * so it is the square root that we are looking for. */ /* t := (q-1)/2 (note that q is odd) */ if (!BN_rshift1(t, q)) goto end; /* x := a^((q-1)/2) */ if (BN_is_zero(t)) { /* special case: p = 2^e + 1 */ if (!BN_nnmod(t, A, p, ctx)) goto end; if (BN_is_zero(t)) { /* special case: a == 0 (mod p) */ BN_zero(ret); err = 0; goto end; } else if (!BN_one(x)) goto end; } else { if (!BN_mod_exp(x, A, t, p, ctx)) goto end; if (BN_is_zero(x)) { /* special case: a == 0 (mod p) */ BN_zero(ret); err = 0; goto end; } } /* b := a*x^2 (= a^q) */ if (!BN_mod_sqr(b, x, p, ctx)) goto end; if (!BN_mod_mul(b, b, A, p, ctx)) goto end; /* x := a*x (= a^((q+1)/2)) */ if (!BN_mod_mul(x, x, A, p, ctx)) goto end; while (1) { /*- * Now b is a^q * y^k for some even k (0 <= k < 2^E * where E refers to the original value of e, which we * don't keep in a variable), and x is a^((q+1)/2) * y^(k/2). * * We have a*b = x^2, * y^2^(e-1) = -1, * b^2^(e-1) = 1. */ if (BN_is_one(b)) { if (!BN_copy(ret, x)) goto end; err = 0; goto vrfy; } /* find smallest i such that b^(2^i) = 1 */ i = 1; if (!BN_mod_sqr(t, b, p, ctx)) goto end; while (!BN_is_one(t)) { i++; if (i == e) { BNerr(BN_F_BN_MOD_SQRT, BN_R_NOT_A_SQUARE); goto end; } if (!BN_mod_mul(t, t, t, p, ctx)) goto end; } /* t := y^2^(e - i - 1) */ if (!BN_copy(t, y)) goto end; for (j = e - i - 1; j > 0; j--) { if (!BN_mod_sqr(t, t, p, ctx)) goto end; } if (!BN_mod_mul(y, t, t, p, ctx)) goto end; if (!BN_mod_mul(x, x, t, p, ctx)) goto end; if (!BN_mod_mul(b, b, y, p, ctx)) goto end; e = i; } vrfy: if (!err) { /* * verify the result -- the input might have been not a square (test * added in 0.9.8) */ if (!BN_mod_sqr(x, ret, p, ctx)) err = 1; if (!err && 0 != BN_cmp(x, A)) { BNerr(BN_F_BN_MOD_SQRT, BN_R_NOT_A_SQUARE); err = 1; } } end: if (err) { if (ret != in) BN_clear_free(ret); ret = NULL; } BN_CTX_end(ctx); bn_check_top(ret); return ret; }
44,827,292,692,614,650,000,000,000,000,000,000,000
None
null
[ "CWE-835" ]
CVE-2022-0778
The BN_mod_sqrt() function, which computes a modular square root, contains a bug that can cause it to loop forever for non-prime moduli. Internally this function is used when parsing certificates that contain elliptic curve public keys in compressed form or explicit elliptic curve parameters with a base point encoded in compressed form. It is possible to trigger the infinite loop by crafting a certificate that has invalid explicit curve parameters. Since certificate parsing happens prior to verification of the certificate signature, any process that parses an externally supplied certificate may thus be subject to a denial of service attack. The infinite loop can also be reached when parsing crafted private keys as they can contain explicit elliptic curve parameters. Thus vulnerable situations include: - TLS clients consuming server certificates - TLS servers consuming client certificates - Hosting providers taking certificates or private keys from customers - Certificate authorities parsing certification requests from subscribers - Anything else which parses ASN.1 elliptic curve parameters Also any other applications that use the BN_mod_sqrt() where the attacker can control the parameter values are vulnerable to this DoS issue. In the OpenSSL 1.0.2 version the public key is not parsed during initial parsing of the certificate which makes it slightly harder to trigger the infinite loop. However any operation which requires the public key from the certificate will trigger the infinite loop. In particular the attacker can use a self-signed certificate to trigger the loop during verification of the certificate signature. This issue affects OpenSSL versions 1.0.2, 1.1.1 and 3.0. It was addressed in the releases of 1.1.1n and 3.0.2 on the 15th March 2022. Fixed in OpenSSL 3.0.2 (Affected 3.0.0,3.0.1). Fixed in OpenSSL 1.1.1n (Affected 1.1.1-1.1.1m). Fixed in OpenSSL 1.0.2zd (Affected 1.0.2-1.0.2zc).
https://nvd.nist.gov/vuln/detail/CVE-2022-0778
509,581
openssl
3118eb64934499d93db3230748a452351d1d9a65
https://github.com/openssl/openssl
https://git.openssl.org/gitweb/?p=openssl.git;a=commitdiff;h=3118eb64934499d93db3230748a452351d1d9a65
Fix possible infinite loop in BN_mod_sqrt() The calculation in some cases does not finish for non-prime p. This fixes CVE-2022-0778. Based on patch by David Benjamin <[email protected]>. Reviewed-by: Paul Dale <[email protected]> Reviewed-by: Matt Caswell <[email protected]>
0
BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) /* * Returns 'ret' such that ret^2 == a (mod p), using the Tonelli/Shanks * algorithm (cf. Henri Cohen, "A Course in Algebraic Computational Number * Theory", algorithm 1.5.1). 'p' must be prime, otherwise an error or * an incorrect "result" will be returned. */ { BIGNUM *ret = in; int err = 1; int r; BIGNUM *A, *b, *q, *t, *x, *y; int e, i, j; if (!BN_is_odd(p) || BN_abs_is_word(p, 1)) { if (BN_abs_is_word(p, 2)) { if (ret == NULL) ret = BN_new(); if (ret == NULL) goto end; if (!BN_set_word(ret, BN_is_bit_set(a, 0))) { if (ret != in) BN_free(ret); return NULL; } bn_check_top(ret); return ret; } BNerr(BN_F_BN_MOD_SQRT, BN_R_P_IS_NOT_PRIME); return NULL; } if (BN_is_zero(a) || BN_is_one(a)) { if (ret == NULL) ret = BN_new(); if (ret == NULL) goto end; if (!BN_set_word(ret, BN_is_one(a))) { if (ret != in) BN_free(ret); return NULL; } bn_check_top(ret); return ret; } BN_CTX_start(ctx); A = BN_CTX_get(ctx); b = BN_CTX_get(ctx); q = BN_CTX_get(ctx); t = BN_CTX_get(ctx); x = BN_CTX_get(ctx); y = BN_CTX_get(ctx); if (y == NULL) goto end; if (ret == NULL) ret = BN_new(); if (ret == NULL) goto end; /* A = a mod p */ if (!BN_nnmod(A, a, p, ctx)) goto end; /* now write |p| - 1 as 2^e*q where q is odd */ e = 1; while (!BN_is_bit_set(p, e)) e++; /* we'll set q later (if needed) */ if (e == 1) { /*- * The easy case: (|p|-1)/2 is odd, so 2 has an inverse * modulo (|p|-1)/2, and square roots can be computed * directly by modular exponentiation. * We have * 2 * (|p|+1)/4 == 1 (mod (|p|-1)/2), * so we can use exponent (|p|+1)/4, i.e. (|p|-3)/4 + 1. */ if (!BN_rshift(q, p, 2)) goto end; q->neg = 0; if (!BN_add_word(q, 1)) goto end; if (!BN_mod_exp(ret, A, q, p, ctx)) goto end; err = 0; goto vrfy; } if (e == 2) { /*- * |p| == 5 (mod 8) * * In this case 2 is always a non-square since * Legendre(2,p) = (-1)^((p^2-1)/8) for any odd prime. * So if a really is a square, then 2*a is a non-square. * Thus for * b := (2*a)^((|p|-5)/8), * i := (2*a)*b^2 * we have * i^2 = (2*a)^((1 + (|p|-5)/4)*2) * = (2*a)^((p-1)/2) * = -1; * so if we set * x := a*b*(i-1), * then * x^2 = a^2 * b^2 * (i^2 - 2*i + 1) * = a^2 * b^2 * (-2*i) * = a*(-i)*(2*a*b^2) * = a*(-i)*i * = a. * * (This is due to A.O.L. Atkin, * Subject: Square Roots and Cognate Matters modulo p=8n+5. * URL: https://listserv.nodak.edu/cgi-bin/wa.exe?A2=ind9211&L=NMBRTHRY&P=4026 * November 1992.) */ /* t := 2*a */ if (!BN_mod_lshift1_quick(t, A, p)) goto end; /* b := (2*a)^((|p|-5)/8) */ if (!BN_rshift(q, p, 3)) goto end; q->neg = 0; if (!BN_mod_exp(b, t, q, p, ctx)) goto end; /* y := b^2 */ if (!BN_mod_sqr(y, b, p, ctx)) goto end; /* t := (2*a)*b^2 - 1 */ if (!BN_mod_mul(t, t, y, p, ctx)) goto end; if (!BN_sub_word(t, 1)) goto end; /* x = a*b*t */ if (!BN_mod_mul(x, A, b, p, ctx)) goto end; if (!BN_mod_mul(x, x, t, p, ctx)) goto end; if (!BN_copy(ret, x)) goto end; err = 0; goto vrfy; } /* * e > 2, so we really have to use the Tonelli/Shanks algorithm. First, * find some y that is not a square. */ if (!BN_copy(q, p)) goto end; /* use 'q' as temp */ q->neg = 0; i = 2; do { /* * For efficiency, try small numbers first; if this fails, try random * numbers. */ if (i < 22) { if (!BN_set_word(y, i)) goto end; } else { if (!BN_priv_rand(y, BN_num_bits(p), 0, 0)) goto end; if (BN_ucmp(y, p) >= 0) { if (!(p->neg ? BN_add : BN_sub) (y, y, p)) goto end; } /* now 0 <= y < |p| */ if (BN_is_zero(y)) if (!BN_set_word(y, i)) goto end; } r = BN_kronecker(y, q, ctx); /* here 'q' is |p| */ if (r < -1) goto end; if (r == 0) { /* m divides p */ BNerr(BN_F_BN_MOD_SQRT, BN_R_P_IS_NOT_PRIME); goto end; } } while (r == 1 && ++i < 82); if (r != -1) { /* * Many rounds and still no non-square -- this is more likely a bug * than just bad luck. Even if p is not prime, we should have found * some y such that r == -1. */ BNerr(BN_F_BN_MOD_SQRT, BN_R_TOO_MANY_ITERATIONS); goto end; } /* Here's our actual 'q': */ if (!BN_rshift(q, q, e)) goto end; /* * Now that we have some non-square, we can find an element of order 2^e * by computing its q'th power. */ if (!BN_mod_exp(y, y, q, p, ctx)) goto end; if (BN_is_one(y)) { BNerr(BN_F_BN_MOD_SQRT, BN_R_P_IS_NOT_PRIME); goto end; } /*- * Now we know that (if p is indeed prime) there is an integer * k, 0 <= k < 2^e, such that * * a^q * y^k == 1 (mod p). * * As a^q is a square and y is not, k must be even. * q+1 is even, too, so there is an element * * X := a^((q+1)/2) * y^(k/2), * * and it satisfies * * X^2 = a^q * a * y^k * = a, * * so it is the square root that we are looking for. */ /* t := (q-1)/2 (note that q is odd) */ if (!BN_rshift1(t, q)) goto end; /* x := a^((q-1)/2) */ if (BN_is_zero(t)) { /* special case: p = 2^e + 1 */ if (!BN_nnmod(t, A, p, ctx)) goto end; if (BN_is_zero(t)) { /* special case: a == 0 (mod p) */ BN_zero(ret); err = 0; goto end; } else if (!BN_one(x)) goto end; } else { if (!BN_mod_exp(x, A, t, p, ctx)) goto end; if (BN_is_zero(x)) { /* special case: a == 0 (mod p) */ BN_zero(ret); err = 0; goto end; } } /* b := a*x^2 (= a^q) */ if (!BN_mod_sqr(b, x, p, ctx)) goto end; if (!BN_mod_mul(b, b, A, p, ctx)) goto end; /* x := a*x (= a^((q+1)/2)) */ if (!BN_mod_mul(x, x, A, p, ctx)) goto end; while (1) { /*- * Now b is a^q * y^k for some even k (0 <= k < 2^E * where E refers to the original value of e, which we * don't keep in a variable), and x is a^((q+1)/2) * y^(k/2). * * We have a*b = x^2, * y^2^(e-1) = -1, * b^2^(e-1) = 1. */ if (BN_is_one(b)) { if (!BN_copy(ret, x)) goto end; err = 0; goto vrfy; } /* Find the smallest i, 0 < i < e, such that b^(2^i) = 1. */ for (i = 1; i < e; i++) { if (i == 1) { if (!BN_mod_sqr(t, b, p, ctx)) goto end; } else { if (!BN_mod_mul(t, t, t, p, ctx)) goto end; } if (BN_is_one(t)) break; } /* If not found, a is not a square or p is not prime. */ if (i >= e) { BNerr(BN_F_BN_MOD_SQRT, BN_R_NOT_A_SQUARE); goto end; } /* t := y^2^(e - i - 1) */ if (!BN_copy(t, y)) goto end; for (j = e - i - 1; j > 0; j--) { if (!BN_mod_sqr(t, t, p, ctx)) goto end; } if (!BN_mod_mul(y, t, t, p, ctx)) goto end; if (!BN_mod_mul(x, x, t, p, ctx)) goto end; if (!BN_mod_mul(b, b, y, p, ctx)) goto end; e = i; } vrfy: if (!err) { /* * verify the result -- the input might have been not a square (test * added in 0.9.8) */ if (!BN_mod_sqr(x, ret, p, ctx)) err = 1; if (!err && 0 != BN_cmp(x, A)) { BNerr(BN_F_BN_MOD_SQRT, BN_R_NOT_A_SQUARE); err = 1; } } end: if (err) { if (ret != in) BN_clear_free(ret); ret = NULL; } BN_CTX_end(ctx); bn_check_top(ret); return ret; }
248,690,382,993,613,740,000,000,000,000,000,000,000
None
null
[ "CWE-835" ]
CVE-2022-0778
The BN_mod_sqrt() function, which computes a modular square root, contains a bug that can cause it to loop forever for non-prime moduli. Internally this function is used when parsing certificates that contain elliptic curve public keys in compressed form or explicit elliptic curve parameters with a base point encoded in compressed form. It is possible to trigger the infinite loop by crafting a certificate that has invalid explicit curve parameters. Since certificate parsing happens prior to verification of the certificate signature, any process that parses an externally supplied certificate may thus be subject to a denial of service attack. The infinite loop can also be reached when parsing crafted private keys as they can contain explicit elliptic curve parameters. Thus vulnerable situations include: - TLS clients consuming server certificates - TLS servers consuming client certificates - Hosting providers taking certificates or private keys from customers - Certificate authorities parsing certification requests from subscribers - Anything else which parses ASN.1 elliptic curve parameters Also any other applications that use the BN_mod_sqrt() where the attacker can control the parameter values are vulnerable to this DoS issue. In the OpenSSL 1.0.2 version the public key is not parsed during initial parsing of the certificate which makes it slightly harder to trigger the infinite loop. However any operation which requires the public key from the certificate will trigger the infinite loop. In particular the attacker can use a self-signed certificate to trigger the loop during verification of the certificate signature. This issue affects OpenSSL versions 1.0.2, 1.1.1 and 3.0. It was addressed in the releases of 1.1.1n and 3.0.2 on the 15th March 2022. Fixed in OpenSSL 3.0.2 (Affected 3.0.0,3.0.1). Fixed in OpenSSL 1.1.1n (Affected 1.1.1-1.1.1m). Fixed in OpenSSL 1.0.2zd (Affected 1.0.2-1.0.2zc).
https://nvd.nist.gov/vuln/detail/CVE-2022-0778
216,944
server
3c209bfc040ddfc41ece8357d772547432353fd2
https://github.com/MariaDB/server
https://github.com/MariaDB/server/commit/3c209bfc040ddfc41ece8357d772547432353fd2
MDEV-25994: Crash with union of my_decimal type in ORDER BY clause When single-row subquery fails with "Subquery reutrns more than 1 row" error, it will raise an error and return NULL. On the other hand, Item_singlerow_subselect sets item->maybe_null=0 for table-less subqueries like "(SELECT not_null_value)" (*) This discrepancy (item with maybe_null=0 returning NULL) causes the code in Type_handler_decimal_result::make_sort_key_part() to crash. Fixed this by allowing inference (*) only when the subquery is NOT a UNION.
1
bool Item_singlerow_subselect::fix_length_and_dec() { if ((max_columns= engine->cols()) == 1) { if (engine->fix_length_and_dec(row= &value)) return TRUE; } else { if (!(row= (Item_cache**) current_thd->alloc(sizeof(Item_cache*) * max_columns)) || engine->fix_length_and_dec(row)) return TRUE; value= *row; } unsigned_flag= value->unsigned_flag; /* If there are not tables in subquery then ability to have NULL value depends on SELECT list (if single row subquery have tables then it always can be NULL if there are not records fetched). */ if (engine->no_tables()) maybe_null= engine->may_be_null(); else { for (uint i= 0; i < max_columns; i++) row[i]->maybe_null= TRUE; } return FALSE; }
239,302,885,543,348,250,000,000,000,000,000,000,000
None
null
[ "CWE-89" ]
CVE-2022-27380
An issue in the component my_decimal::operator= of MariaDB Server v10.6.3 and below was discovered to allow attackers to cause a Denial of Service (DoS) via specially crafted SQL statements.
https://nvd.nist.gov/vuln/detail/CVE-2022-27380
511,887
server
3c209bfc040ddfc41ece8357d772547432353fd2
https://github.com/MariaDB/server
https://github.com/MariaDB/server/commit/3c209bfc040ddfc41ece8357d772547432353fd2
MDEV-25994: Crash with union of my_decimal type in ORDER BY clause When single-row subquery fails with "Subquery reutrns more than 1 row" error, it will raise an error and return NULL. On the other hand, Item_singlerow_subselect sets item->maybe_null=0 for table-less subqueries like "(SELECT not_null_value)" (*) This discrepancy (item with maybe_null=0 returning NULL) causes the code in Type_handler_decimal_result::make_sort_key_part() to crash. Fixed this by allowing inference (*) only when the subquery is NOT a UNION.
0
bool Item_singlerow_subselect::fix_length_and_dec() { if ((max_columns= engine->cols()) == 1) { if (engine->fix_length_and_dec(row= &value)) return TRUE; } else { if (!(row= (Item_cache**) current_thd->alloc(sizeof(Item_cache*) * max_columns)) || engine->fix_length_and_dec(row)) return TRUE; value= *row; } unsigned_flag= value->unsigned_flag; /* If the subquery has no tables (1) and is not a UNION (2), like: (SELECT subq_value) then its NULLability is the same as subq_value's NULLability. (1): A subquery that uses a table will return NULL when the table is empty. (2): A UNION subquery will return NULL if it produces a "Subquery returns more than one row" error. */ if (engine->no_tables() && engine->engine_type() != subselect_engine::UNION_ENGINE) maybe_null= engine->may_be_null(); else { for (uint i= 0; i < max_columns; i++) row[i]->maybe_null= TRUE; } return FALSE; }
262,929,527,540,289,200,000,000,000,000,000,000,000
None
null
[ "CWE-89" ]
CVE-2022-27380
An issue in the component my_decimal::operator= of MariaDB Server v10.6.3 and below was discovered to allow attackers to cause a Denial of Service (DoS) via specially crafted SQL statements.
https://nvd.nist.gov/vuln/detail/CVE-2022-27380
216,966
server
af810407f78b7f792a9bb8c47c8c532eb3b3a758
https://github.com/MariaDB/server
https://github.com/MariaDB/server/commit/af810407f78b7f792a9bb8c47c8c532eb3b3a758
MDEV-28098 incorrect key in "dup value" error after long unique reset errkey after using it, so that it wouldn't affect the next error message in the next statement
1
void handler::print_error(int error, myf errflag) { bool fatal_error= 0; DBUG_ENTER("handler::print_error"); DBUG_PRINT("enter",("error: %d",error)); if (ha_thd()->transaction_rollback_request) { /* Ensure this becomes a true error */ errflag&= ~(ME_WARNING | ME_NOTE); } int textno= -1; // impossible value switch (error) { case EACCES: textno=ER_OPEN_AS_READONLY; break; case EAGAIN: textno=ER_FILE_USED; break; case ENOENT: case ENOTDIR: case ELOOP: textno=ER_FILE_NOT_FOUND; break; case ENOSPC: case HA_ERR_DISK_FULL: textno= ER_DISK_FULL; SET_FATAL_ERROR; // Ensure error is logged break; case HA_ERR_KEY_NOT_FOUND: case HA_ERR_NO_ACTIVE_RECORD: case HA_ERR_RECORD_DELETED: case HA_ERR_END_OF_FILE: /* This errors is not not normally fatal (for example for reads). However if you get it during an update or delete, then its fatal. As the user is calling print_error() (which is not done on read), we assume something when wrong with the update or delete. */ SET_FATAL_ERROR; textno=ER_KEY_NOT_FOUND; break; case HA_ERR_ABORTED_BY_USER: { DBUG_ASSERT(ha_thd()->killed); ha_thd()->send_kill_message(); DBUG_VOID_RETURN; } case HA_ERR_WRONG_MRG_TABLE_DEF: textno=ER_WRONG_MRG_TABLE; break; case HA_ERR_FOUND_DUPP_KEY: { if (table) { uint key_nr=get_dup_key(error); if ((int) key_nr >= 0 && key_nr < table->s->keys) { print_keydup_error(table, &table->key_info[key_nr], errflag); DBUG_VOID_RETURN; } } textno=ER_DUP_KEY; break; } case HA_ERR_FOREIGN_DUPLICATE_KEY: { char rec_buf[MAX_KEY_LENGTH]; String rec(rec_buf, sizeof(rec_buf), system_charset_info); /* Table is opened and defined at this point */ /* Just print the subset of fields that are part of the first index, printing the whole row from there is not easy. */ key_unpack(&rec, table, &table->key_info[0]); char child_table_name[NAME_LEN + 1]; char child_key_name[NAME_LEN + 1]; if (get_foreign_dup_key(child_table_name, sizeof(child_table_name), child_key_name, sizeof(child_key_name))) { my_error(ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO, errflag, table_share->table_name.str, rec.c_ptr_safe(), child_table_name, child_key_name); } else { my_error(ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO, errflag, table_share->table_name.str, rec.c_ptr_safe()); } DBUG_VOID_RETURN; } case HA_ERR_NULL_IN_SPATIAL: my_error(ER_CANT_CREATE_GEOMETRY_OBJECT, errflag); DBUG_VOID_RETURN; case HA_ERR_FOUND_DUPP_UNIQUE: textno=ER_DUP_UNIQUE; break; case HA_ERR_RECORD_CHANGED: /* This is not fatal error when using HANDLER interface SET_FATAL_ERROR; */ textno=ER_CHECKREAD; break; case HA_ERR_CRASHED: SET_FATAL_ERROR; textno=ER_NOT_KEYFILE; break; case HA_ERR_WRONG_IN_RECORD: SET_FATAL_ERROR; textno= ER_CRASHED_ON_USAGE; break; case HA_ERR_CRASHED_ON_USAGE: SET_FATAL_ERROR; textno=ER_CRASHED_ON_USAGE; break; case HA_ERR_NOT_A_TABLE: textno= error; break; case HA_ERR_CRASHED_ON_REPAIR: SET_FATAL_ERROR; textno=ER_CRASHED_ON_REPAIR; break; case HA_ERR_OUT_OF_MEM: textno=ER_OUT_OF_RESOURCES; break; case HA_ERR_WRONG_COMMAND: my_error(ER_ILLEGAL_HA, MYF(0), table_type(), table_share->db.str, table_share->table_name.str); DBUG_VOID_RETURN; break; case HA_ERR_OLD_FILE: textno=ER_OLD_KEYFILE; break; case HA_ERR_UNSUPPORTED: textno=ER_UNSUPPORTED_EXTENSION; break; case HA_ERR_RECORD_FILE_FULL: { textno=ER_RECORD_FILE_FULL; /* Write the error message to error log */ errflag|= ME_ERROR_LOG; break; } case HA_ERR_INDEX_FILE_FULL: { textno=ER_INDEX_FILE_FULL; /* Write the error message to error log */ errflag|= ME_ERROR_LOG; break; } case HA_ERR_LOCK_WAIT_TIMEOUT: textno=ER_LOCK_WAIT_TIMEOUT; break; case HA_ERR_LOCK_TABLE_FULL: textno=ER_LOCK_TABLE_FULL; break; case HA_ERR_LOCK_DEADLOCK: { String str, full_err_msg(ER_DEFAULT(ER_LOCK_DEADLOCK), system_charset_info); get_error_message(error, &str); full_err_msg.append(str); my_printf_error(ER_LOCK_DEADLOCK, "%s", errflag, full_err_msg.c_ptr_safe()); DBUG_VOID_RETURN; } case HA_ERR_READ_ONLY_TRANSACTION: textno=ER_READ_ONLY_TRANSACTION; break; case HA_ERR_CANNOT_ADD_FOREIGN: textno=ER_CANNOT_ADD_FOREIGN; break; case HA_ERR_ROW_IS_REFERENCED: { String str; get_error_message(error, &str); my_printf_error(ER_ROW_IS_REFERENCED_2, ER(str.length() ? ER_ROW_IS_REFERENCED_2 : ER_ROW_IS_REFERENCED), errflag, str.c_ptr_safe()); DBUG_VOID_RETURN; } case HA_ERR_NO_REFERENCED_ROW: { String str; get_error_message(error, &str); my_printf_error(ER_NO_REFERENCED_ROW_2, ER(str.length() ? ER_NO_REFERENCED_ROW_2 : ER_NO_REFERENCED_ROW), errflag, str.c_ptr_safe()); DBUG_VOID_RETURN; } case HA_ERR_TABLE_DEF_CHANGED: textno=ER_TABLE_DEF_CHANGED; break; case HA_ERR_NO_SUCH_TABLE: my_error(ER_NO_SUCH_TABLE_IN_ENGINE, errflag, table_share->db.str, table_share->table_name.str); DBUG_VOID_RETURN; case HA_ERR_RBR_LOGGING_FAILED: textno= ER_BINLOG_ROW_LOGGING_FAILED; break; case HA_ERR_DROP_INDEX_FK: { const char *ptr= "???"; uint key_nr= get_dup_key(error); if ((int) key_nr >= 0) ptr= table->key_info[key_nr].name.str; my_error(ER_DROP_INDEX_FK, errflag, ptr); DBUG_VOID_RETURN; } case HA_ERR_TABLE_NEEDS_UPGRADE: textno= ER_TABLE_NEEDS_UPGRADE; my_error(ER_TABLE_NEEDS_UPGRADE, errflag, "TABLE", table_share->table_name.str); DBUG_VOID_RETURN; case HA_ERR_NO_PARTITION_FOUND: textno=ER_WRONG_PARTITION_NAME; break; case HA_ERR_TABLE_READONLY: textno= ER_OPEN_AS_READONLY; break; case HA_ERR_AUTOINC_READ_FAILED: textno= ER_AUTOINC_READ_FAILED; break; case HA_ERR_AUTOINC_ERANGE: textno= error; my_error(textno, errflag, table->next_number_field->field_name.str, table->in_use->get_stmt_da()->current_row_for_warning()); DBUG_VOID_RETURN; break; case HA_ERR_TOO_MANY_CONCURRENT_TRXS: textno= ER_TOO_MANY_CONCURRENT_TRXS; break; case HA_ERR_INDEX_COL_TOO_LONG: textno= ER_INDEX_COLUMN_TOO_LONG; break; case HA_ERR_NOT_IN_LOCK_PARTITIONS: textno=ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET; break; case HA_ERR_INDEX_CORRUPT: textno= ER_INDEX_CORRUPT; break; case HA_ERR_UNDO_REC_TOO_BIG: textno= ER_UNDO_RECORD_TOO_BIG; break; case HA_ERR_TABLE_IN_FK_CHECK: textno= ER_TABLE_IN_FK_CHECK; break; case HA_ERR_PARTITION_LIST: my_error(ER_VERS_NOT_ALLOWED, errflag, table->s->db.str, table->s->table_name.str); DBUG_VOID_RETURN; default: { /* The error was "unknown" to this function. Ask handler if it has got a message for this error */ bool temporary= FALSE; String str; temporary= get_error_message(error, &str); if (!str.is_empty()) { const char* engine= table_type(); if (temporary) my_error(ER_GET_TEMPORARY_ERRMSG, errflag, error, str.c_ptr(), engine); else { SET_FATAL_ERROR; my_error(ER_GET_ERRMSG, errflag, error, str.c_ptr(), engine); } } else my_error(ER_GET_ERRNO, errflag, error, table_type()); DBUG_VOID_RETURN; } } DBUG_ASSERT(textno > 0); if (unlikely(fatal_error)) { /* Ensure this becomes a true error */ errflag&= ~(ME_WARNING | ME_NOTE); if ((debug_assert_if_crashed_table || global_system_variables.log_warnings > 1)) { /* Log error to log before we crash or if extended warnings are requested */ errflag|= ME_ERROR_LOG; } } /* if we got an OS error from a file-based engine, specify a path of error */ if (error < HA_ERR_FIRST && bas_ext()[0]) { char buff[FN_REFLEN]; strxnmov(buff, sizeof(buff), table_share->normalized_path.str, bas_ext()[0], NULL); my_error(textno, errflag, buff, error); } else my_error(textno, errflag, table_share->table_name.str, error); DBUG_VOID_RETURN; }
176,899,003,449,109,900,000,000,000,000,000,000,000
None
null
[ "CWE-416" ]
CVE-2022-27457
MariaDB Server v10.6.3 and below was discovered to contain an use-after-free in the component my_mb_wc_latin1 at /strings/ctype-latin1.c.
https://nvd.nist.gov/vuln/detail/CVE-2022-27457
514,535
server
af810407f78b7f792a9bb8c47c8c532eb3b3a758
https://github.com/MariaDB/server
https://github.com/MariaDB/server/commit/af810407f78b7f792a9bb8c47c8c532eb3b3a758
MDEV-28098 incorrect key in "dup value" error after long unique reset errkey after using it, so that it wouldn't affect the next error message in the next statement
0
void handler::print_error(int error, myf errflag) { bool fatal_error= 0; DBUG_ENTER("handler::print_error"); DBUG_PRINT("enter",("error: %d",error)); if (ha_thd()->transaction_rollback_request) { /* Ensure this becomes a true error */ errflag&= ~(ME_WARNING | ME_NOTE); } int textno= -1; // impossible value switch (error) { case EACCES: textno=ER_OPEN_AS_READONLY; break; case EAGAIN: textno=ER_FILE_USED; break; case ENOENT: case ENOTDIR: case ELOOP: textno=ER_FILE_NOT_FOUND; break; case ENOSPC: case HA_ERR_DISK_FULL: textno= ER_DISK_FULL; SET_FATAL_ERROR; // Ensure error is logged break; case HA_ERR_KEY_NOT_FOUND: case HA_ERR_NO_ACTIVE_RECORD: case HA_ERR_RECORD_DELETED: case HA_ERR_END_OF_FILE: /* This errors is not not normally fatal (for example for reads). However if you get it during an update or delete, then its fatal. As the user is calling print_error() (which is not done on read), we assume something when wrong with the update or delete. */ SET_FATAL_ERROR; textno=ER_KEY_NOT_FOUND; break; case HA_ERR_ABORTED_BY_USER: { DBUG_ASSERT(ha_thd()->killed); ha_thd()->send_kill_message(); DBUG_VOID_RETURN; } case HA_ERR_WRONG_MRG_TABLE_DEF: textno=ER_WRONG_MRG_TABLE; break; case HA_ERR_FOUND_DUPP_KEY: { if (table) { uint key_nr=get_dup_key(error); if ((int) key_nr >= 0 && key_nr < table->s->keys) { print_keydup_error(table, &table->key_info[key_nr], errflag); table->file->errkey= -1; DBUG_VOID_RETURN; } } textno=ER_DUP_KEY; break; } case HA_ERR_FOREIGN_DUPLICATE_KEY: { char rec_buf[MAX_KEY_LENGTH]; String rec(rec_buf, sizeof(rec_buf), system_charset_info); /* Table is opened and defined at this point */ /* Just print the subset of fields that are part of the first index, printing the whole row from there is not easy. */ key_unpack(&rec, table, &table->key_info[0]); char child_table_name[NAME_LEN + 1]; char child_key_name[NAME_LEN + 1]; if (get_foreign_dup_key(child_table_name, sizeof(child_table_name), child_key_name, sizeof(child_key_name))) { my_error(ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO, errflag, table_share->table_name.str, rec.c_ptr_safe(), child_table_name, child_key_name); } else { my_error(ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO, errflag, table_share->table_name.str, rec.c_ptr_safe()); } DBUG_VOID_RETURN; } case HA_ERR_NULL_IN_SPATIAL: my_error(ER_CANT_CREATE_GEOMETRY_OBJECT, errflag); DBUG_VOID_RETURN; case HA_ERR_FOUND_DUPP_UNIQUE: textno=ER_DUP_UNIQUE; break; case HA_ERR_RECORD_CHANGED: /* This is not fatal error when using HANDLER interface SET_FATAL_ERROR; */ textno=ER_CHECKREAD; break; case HA_ERR_CRASHED: SET_FATAL_ERROR; textno=ER_NOT_KEYFILE; break; case HA_ERR_WRONG_IN_RECORD: SET_FATAL_ERROR; textno= ER_CRASHED_ON_USAGE; break; case HA_ERR_CRASHED_ON_USAGE: SET_FATAL_ERROR; textno=ER_CRASHED_ON_USAGE; break; case HA_ERR_NOT_A_TABLE: textno= error; break; case HA_ERR_CRASHED_ON_REPAIR: SET_FATAL_ERROR; textno=ER_CRASHED_ON_REPAIR; break; case HA_ERR_OUT_OF_MEM: textno=ER_OUT_OF_RESOURCES; break; case HA_ERR_WRONG_COMMAND: my_error(ER_ILLEGAL_HA, MYF(0), table_type(), table_share->db.str, table_share->table_name.str); DBUG_VOID_RETURN; break; case HA_ERR_OLD_FILE: textno=ER_OLD_KEYFILE; break; case HA_ERR_UNSUPPORTED: textno=ER_UNSUPPORTED_EXTENSION; break; case HA_ERR_RECORD_FILE_FULL: { textno=ER_RECORD_FILE_FULL; /* Write the error message to error log */ errflag|= ME_ERROR_LOG; break; } case HA_ERR_INDEX_FILE_FULL: { textno=ER_INDEX_FILE_FULL; /* Write the error message to error log */ errflag|= ME_ERROR_LOG; break; } case HA_ERR_LOCK_WAIT_TIMEOUT: textno=ER_LOCK_WAIT_TIMEOUT; break; case HA_ERR_LOCK_TABLE_FULL: textno=ER_LOCK_TABLE_FULL; break; case HA_ERR_LOCK_DEADLOCK: { String str, full_err_msg(ER_DEFAULT(ER_LOCK_DEADLOCK), system_charset_info); get_error_message(error, &str); full_err_msg.append(str); my_printf_error(ER_LOCK_DEADLOCK, "%s", errflag, full_err_msg.c_ptr_safe()); DBUG_VOID_RETURN; } case HA_ERR_READ_ONLY_TRANSACTION: textno=ER_READ_ONLY_TRANSACTION; break; case HA_ERR_CANNOT_ADD_FOREIGN: textno=ER_CANNOT_ADD_FOREIGN; break; case HA_ERR_ROW_IS_REFERENCED: { String str; get_error_message(error, &str); my_printf_error(ER_ROW_IS_REFERENCED_2, ER(str.length() ? ER_ROW_IS_REFERENCED_2 : ER_ROW_IS_REFERENCED), errflag, str.c_ptr_safe()); DBUG_VOID_RETURN; } case HA_ERR_NO_REFERENCED_ROW: { String str; get_error_message(error, &str); my_printf_error(ER_NO_REFERENCED_ROW_2, ER(str.length() ? ER_NO_REFERENCED_ROW_2 : ER_NO_REFERENCED_ROW), errflag, str.c_ptr_safe()); DBUG_VOID_RETURN; } case HA_ERR_TABLE_DEF_CHANGED: textno=ER_TABLE_DEF_CHANGED; break; case HA_ERR_NO_SUCH_TABLE: my_error(ER_NO_SUCH_TABLE_IN_ENGINE, errflag, table_share->db.str, table_share->table_name.str); DBUG_VOID_RETURN; case HA_ERR_RBR_LOGGING_FAILED: textno= ER_BINLOG_ROW_LOGGING_FAILED; break; case HA_ERR_DROP_INDEX_FK: { const char *ptr= "???"; uint key_nr= get_dup_key(error); if ((int) key_nr >= 0) ptr= table->key_info[key_nr].name.str; my_error(ER_DROP_INDEX_FK, errflag, ptr); DBUG_VOID_RETURN; } case HA_ERR_TABLE_NEEDS_UPGRADE: textno= ER_TABLE_NEEDS_UPGRADE; my_error(ER_TABLE_NEEDS_UPGRADE, errflag, "TABLE", table_share->table_name.str); DBUG_VOID_RETURN; case HA_ERR_NO_PARTITION_FOUND: textno=ER_WRONG_PARTITION_NAME; break; case HA_ERR_TABLE_READONLY: textno= ER_OPEN_AS_READONLY; break; case HA_ERR_AUTOINC_READ_FAILED: textno= ER_AUTOINC_READ_FAILED; break; case HA_ERR_AUTOINC_ERANGE: textno= error; my_error(textno, errflag, table->next_number_field->field_name.str, table->in_use->get_stmt_da()->current_row_for_warning()); DBUG_VOID_RETURN; break; case HA_ERR_TOO_MANY_CONCURRENT_TRXS: textno= ER_TOO_MANY_CONCURRENT_TRXS; break; case HA_ERR_INDEX_COL_TOO_LONG: textno= ER_INDEX_COLUMN_TOO_LONG; break; case HA_ERR_NOT_IN_LOCK_PARTITIONS: textno=ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET; break; case HA_ERR_INDEX_CORRUPT: textno= ER_INDEX_CORRUPT; break; case HA_ERR_UNDO_REC_TOO_BIG: textno= ER_UNDO_RECORD_TOO_BIG; break; case HA_ERR_TABLE_IN_FK_CHECK: textno= ER_TABLE_IN_FK_CHECK; break; case HA_ERR_PARTITION_LIST: my_error(ER_VERS_NOT_ALLOWED, errflag, table->s->db.str, table->s->table_name.str); DBUG_VOID_RETURN; default: { /* The error was "unknown" to this function. Ask handler if it has got a message for this error */ bool temporary= FALSE; String str; temporary= get_error_message(error, &str); if (!str.is_empty()) { const char* engine= table_type(); if (temporary) my_error(ER_GET_TEMPORARY_ERRMSG, errflag, error, str.c_ptr(), engine); else { SET_FATAL_ERROR; my_error(ER_GET_ERRMSG, errflag, error, str.c_ptr(), engine); } } else my_error(ER_GET_ERRNO, errflag, error, table_type()); DBUG_VOID_RETURN; } } DBUG_ASSERT(textno > 0); if (unlikely(fatal_error)) { /* Ensure this becomes a true error */ errflag&= ~(ME_WARNING | ME_NOTE); if ((debug_assert_if_crashed_table || global_system_variables.log_warnings > 1)) { /* Log error to log before we crash or if extended warnings are requested */ errflag|= ME_ERROR_LOG; } } /* if we got an OS error from a file-based engine, specify a path of error */ if (error < HA_ERR_FIRST && bas_ext()[0]) { char buff[FN_REFLEN]; strxnmov(buff, sizeof(buff), table_share->normalized_path.str, bas_ext()[0], NULL); my_error(textno, errflag, buff, error); } else my_error(textno, errflag, table_share->table_name.str, error); DBUG_VOID_RETURN; }
166,818,593,904,132,840,000,000,000,000,000,000,000
None
null
[ "CWE-416" ]
CVE-2022-27457
MariaDB Server v10.6.3 and below was discovered to contain an use-after-free in the component my_mb_wc_latin1 at /strings/ctype-latin1.c.
https://nvd.nist.gov/vuln/detail/CVE-2022-27457
216,969
openssl
2eda98790c5c2741d76d23cc1e74b0dc4f4b391a
https://github.com/openssl/openssl
https://github.com/openssl/openssl/commit/2eda98790c5c2741d76d23cc1e74b0dc4f4b391a
Fix OCSP_basic_verify signer certificate validation The function `OCSP_basic_verify` validates the signer certificate on an OCSP response. The internal function, ocsp_verify_signer, is responsible for this and is expected to return a 0 value in the event of a failure to verify. Unfortunately, due to a bug, it actually returns with a postive success response in this case. In the normal course of events OCSP_basic_verify will then continue and will fail anyway in the ocsp_check_issuer function because the supplied "chain" value will be empty in the case that ocsp_verify_signer failed to verify the chain. This will cause OCSP_basic_verify to return with a negative result (fatal error). Normally in the event of a failure to verify it should return with 0. However, in the case of the OCSP_NOCHECKS flag being used, OCSP_basic_verify will return with a positvie result. This could lead to callers trusting an OCSP Basic response when it should not be. CVE-2022-1343 Fixes #18053 Reviewed-by: Paul Dale <[email protected]> Reviewed-by: Tomas Mraz <[email protected]> Reviewed-by: Matt Caswell <[email protected]>
1
static int ocsp_verify_signer(X509 *signer, int response, X509_STORE *st, unsigned long flags, STACK_OF(X509) *untrusted, STACK_OF(X509) **chain) { X509_STORE_CTX *ctx = X509_STORE_CTX_new(); X509_VERIFY_PARAM *vp; int ret = -1; if (ctx == NULL) { ERR_raise(ERR_LIB_OCSP, ERR_R_MALLOC_FAILURE); goto end; } if (!X509_STORE_CTX_init(ctx, st, signer, untrusted)) { ERR_raise(ERR_LIB_OCSP, ERR_R_X509_LIB); goto end; } if ((vp = X509_STORE_CTX_get0_param(ctx)) == NULL) goto end; if ((flags & OCSP_PARTIAL_CHAIN) != 0) X509_VERIFY_PARAM_set_flags(vp, X509_V_FLAG_PARTIAL_CHAIN); if (response && X509_get_ext_by_NID(signer, NID_id_pkix_OCSP_noCheck, -1) >= 0) /* * Locally disable revocation status checking for OCSP responder cert. * Done here for CRLs; should be done also for OCSP-based checks. */ X509_VERIFY_PARAM_clear_flags(vp, X509_V_FLAG_CRL_CHECK); X509_STORE_CTX_set_purpose(ctx, X509_PURPOSE_OCSP_HELPER); X509_STORE_CTX_set_trust(ctx, X509_TRUST_OCSP_REQUEST); ret = X509_verify_cert(ctx); if (ret <= 0) { ret = X509_STORE_CTX_get_error(ctx); ERR_raise_data(ERR_LIB_OCSP, OCSP_R_CERTIFICATE_VERIFY_ERROR, "Verify error: %s", X509_verify_cert_error_string(ret)); goto end; } if (chain != NULL) *chain = X509_STORE_CTX_get1_chain(ctx); end: X509_STORE_CTX_free(ctx); return ret; }
135,340,782,496,843,480,000,000,000,000,000,000,000
None
null
[ "CWE-703" ]
CVE-2022-1343
The function `OCSP_basic_verify` verifies the signer certificate on an OCSP response. In the case where the (non-default) flag OCSP_NOCHECKS is used then the response will be positive (meaning a successful verification) even in the case where the response signing certificate fails to verify. It is anticipated that most users of `OCSP_basic_verify` will not use the OCSP_NOCHECKS flag. In this case the `OCSP_basic_verify` function will return a negative value (indicating a fatal error) in the case of a certificate verification failure. The normal expected return value in this case would be 0. This issue also impacts the command line OpenSSL "ocsp" application. When verifying an ocsp response with the "-no_cert_checks" option the command line application will report that the verification is successful even though it has in fact failed. In this case the incorrect successful response will also be accompanied by error messages showing the failure and contradicting the apparently successful result. Fixed in OpenSSL 3.0.3 (Affected 3.0.0,3.0.1,3.0.2).
https://nvd.nist.gov/vuln/detail/CVE-2022-1343
514,677
openssl
2eda98790c5c2741d76d23cc1e74b0dc4f4b391a
https://github.com/openssl/openssl
https://github.com/openssl/openssl/commit/2eda98790c5c2741d76d23cc1e74b0dc4f4b391a
Fix OCSP_basic_verify signer certificate validation The function `OCSP_basic_verify` validates the signer certificate on an OCSP response. The internal function, ocsp_verify_signer, is responsible for this and is expected to return a 0 value in the event of a failure to verify. Unfortunately, due to a bug, it actually returns with a postive success response in this case. In the normal course of events OCSP_basic_verify will then continue and will fail anyway in the ocsp_check_issuer function because the supplied "chain" value will be empty in the case that ocsp_verify_signer failed to verify the chain. This will cause OCSP_basic_verify to return with a negative result (fatal error). Normally in the event of a failure to verify it should return with 0. However, in the case of the OCSP_NOCHECKS flag being used, OCSP_basic_verify will return with a positvie result. This could lead to callers trusting an OCSP Basic response when it should not be. CVE-2022-1343 Fixes #18053 Reviewed-by: Paul Dale <[email protected]> Reviewed-by: Tomas Mraz <[email protected]> Reviewed-by: Matt Caswell <[email protected]>
0
static int ocsp_verify_signer(X509 *signer, int response, X509_STORE *st, unsigned long flags, STACK_OF(X509) *untrusted, STACK_OF(X509) **chain) { X509_STORE_CTX *ctx = X509_STORE_CTX_new(); X509_VERIFY_PARAM *vp; int ret = -1; if (ctx == NULL) { ERR_raise(ERR_LIB_OCSP, ERR_R_MALLOC_FAILURE); goto end; } if (!X509_STORE_CTX_init(ctx, st, signer, untrusted)) { ERR_raise(ERR_LIB_OCSP, ERR_R_X509_LIB); goto end; } if ((vp = X509_STORE_CTX_get0_param(ctx)) == NULL) goto end; if ((flags & OCSP_PARTIAL_CHAIN) != 0) X509_VERIFY_PARAM_set_flags(vp, X509_V_FLAG_PARTIAL_CHAIN); if (response && X509_get_ext_by_NID(signer, NID_id_pkix_OCSP_noCheck, -1) >= 0) /* * Locally disable revocation status checking for OCSP responder cert. * Done here for CRLs; should be done also for OCSP-based checks. */ X509_VERIFY_PARAM_clear_flags(vp, X509_V_FLAG_CRL_CHECK); X509_STORE_CTX_set_purpose(ctx, X509_PURPOSE_OCSP_HELPER); X509_STORE_CTX_set_trust(ctx, X509_TRUST_OCSP_REQUEST); ret = X509_verify_cert(ctx); if (ret <= 0) { int err = X509_STORE_CTX_get_error(ctx); ERR_raise_data(ERR_LIB_OCSP, OCSP_R_CERTIFICATE_VERIFY_ERROR, "Verify error: %s", X509_verify_cert_error_string(err)); goto end; } if (chain != NULL) *chain = X509_STORE_CTX_get1_chain(ctx); end: X509_STORE_CTX_free(ctx); return ret; }
216,092,094,613,497,180,000,000,000,000,000,000,000
None
null
[ "CWE-703" ]
CVE-2022-1343
The function `OCSP_basic_verify` verifies the signer certificate on an OCSP response. In the case where the (non-default) flag OCSP_NOCHECKS is used then the response will be positive (meaning a successful verification) even in the case where the response signing certificate fails to verify. It is anticipated that most users of `OCSP_basic_verify` will not use the OCSP_NOCHECKS flag. In this case the `OCSP_basic_verify` function will return a negative value (indicating a fatal error) in the case of a certificate verification failure. The normal expected return value in this case would be 0. This issue also impacts the command line OpenSSL "ocsp" application. When verifying an ocsp response with the "-no_cert_checks" option the command line application will report that the verification is successful even though it has in fact failed. In this case the incorrect successful response will also be accompanied by error messages showing the failure and contradicting the apparently successful result. Fixed in OpenSSL 3.0.3 (Affected 3.0.0,3.0.1,3.0.2).
https://nvd.nist.gov/vuln/detail/CVE-2022-1343
216,972
server
b1351c15946349f9daa7e5297fb2ac6f3139e4a8
https://github.com/MariaDB/server
https://github.com/MariaDB/server/commit/b1351c15946349f9daa7e5297fb2ac6f3139e4a8
MDEV-26574 An improper locking bug due to unreleased lock in the ds_xbstream.cc release lock in all as cases n xbstream_open, also fix the case where malloc would return NULL.
1
xbstream_open(ds_ctxt_t *ctxt, const char *path, MY_STAT *mystat) { ds_file_t *file; ds_stream_file_t *stream_file; ds_stream_ctxt_t *stream_ctxt; ds_ctxt_t *dest_ctxt; xb_wstream_t *xbstream; xb_wstream_file_t *xbstream_file; xb_ad(ctxt->pipe_ctxt != NULL); dest_ctxt = ctxt->pipe_ctxt; stream_ctxt = (ds_stream_ctxt_t *) ctxt->ptr; pthread_mutex_lock(&stream_ctxt->mutex); if (stream_ctxt->dest_file == NULL) { stream_ctxt->dest_file = ds_open(dest_ctxt, path, mystat); if (stream_ctxt->dest_file == NULL) { return NULL; } } pthread_mutex_unlock(&stream_ctxt->mutex); file = (ds_file_t *) my_malloc(sizeof(ds_file_t) + sizeof(ds_stream_file_t), MYF(MY_FAE)); stream_file = (ds_stream_file_t *) (file + 1); xbstream = stream_ctxt->xbstream; xbstream_file = xb_stream_write_open(xbstream, path, mystat, stream_ctxt, my_xbstream_write_callback); if (xbstream_file == NULL) { msg("xb_stream_write_open() failed."); goto err; } stream_file->xbstream_file = xbstream_file; stream_file->stream_ctxt = stream_ctxt; file->ptr = stream_file; file->path = stream_ctxt->dest_file->path; return file; err: if (stream_ctxt->dest_file) { ds_close(stream_ctxt->dest_file); stream_ctxt->dest_file = NULL; } my_free(file); return NULL; }
133,283,141,336,811,140,000,000,000,000,000,000,000
None
null
[ "CWE-703" ]
CVE-2022-31621
MariaDB Server before 10.7 is vulnerable to Denial of Service. In extra/mariabackup/ds_xbstream.cc, when an error occurs (stream_ctxt->dest_file == NULL) while executing the method xbstream_open, the held lock is not released correctly, which allows local users to trigger a denial of service due to the deadlock.
https://nvd.nist.gov/vuln/detail/CVE-2022-31621
514,715
server
b1351c15946349f9daa7e5297fb2ac6f3139e4a8
https://github.com/MariaDB/server
https://github.com/MariaDB/server/commit/b1351c15946349f9daa7e5297fb2ac6f3139e4a8
MDEV-26574 An improper locking bug due to unreleased lock in the ds_xbstream.cc release lock in all as cases n xbstream_open, also fix the case where malloc would return NULL.
0
xbstream_open(ds_ctxt_t *ctxt, const char *path, MY_STAT *mystat) { ds_file_t *file; ds_stream_file_t *stream_file; ds_stream_ctxt_t *stream_ctxt; ds_ctxt_t *dest_ctxt; xb_wstream_t *xbstream; xb_wstream_file_t *xbstream_file; xb_ad(ctxt->pipe_ctxt != NULL); dest_ctxt = ctxt->pipe_ctxt; stream_ctxt = (ds_stream_ctxt_t *) ctxt->ptr; pthread_mutex_lock(&stream_ctxt->mutex); if (stream_ctxt->dest_file == NULL) { stream_ctxt->dest_file = ds_open(dest_ctxt, path, mystat); } pthread_mutex_unlock(&stream_ctxt->mutex); if (stream_ctxt->dest_file == NULL) { return NULL; } file = (ds_file_t *) my_malloc(sizeof(ds_file_t) + sizeof(ds_stream_file_t), MYF(MY_FAE)); if (!file) { msg("my_malloc() failed."); goto err; } stream_file = (ds_stream_file_t *) (file + 1); xbstream = stream_ctxt->xbstream; xbstream_file = xb_stream_write_open(xbstream, path, mystat, stream_ctxt, my_xbstream_write_callback); if (xbstream_file == NULL) { msg("xb_stream_write_open() failed."); goto err; } stream_file->xbstream_file = xbstream_file; stream_file->stream_ctxt = stream_ctxt; file->ptr = stream_file; file->path = stream_ctxt->dest_file->path; return file; err: if (stream_ctxt->dest_file) { ds_close(stream_ctxt->dest_file); stream_ctxt->dest_file = NULL; } my_free(file); return NULL; }
109,927,311,295,173,080,000,000,000,000,000,000,000
None
null
[ "CWE-703" ]
CVE-2022-31621
MariaDB Server before 10.7 is vulnerable to Denial of Service. In extra/mariabackup/ds_xbstream.cc, when an error occurs (stream_ctxt->dest_file == NULL) while executing the method xbstream_open, the held lock is not released correctly, which allows local users to trigger a denial of service due to the deadlock.
https://nvd.nist.gov/vuln/detail/CVE-2022-31621
216,974
server
7c30bc38a588b22b01f11130cfe99e7f36accf94
https://github.com/MariaDB/server
https://github.com/MariaDB/server/commit/7c30bc38a588b22b01f11130cfe99e7f36accf94
MDEV-26561 mariabackup release locks The previous threads locked need to be released too. This occurs if the initialization of any of the non-first mutex/conditition variables errors occurs.
1
create_worker_threads(uint n) { comp_thread_ctxt_t *threads; uint i; threads = (comp_thread_ctxt_t *) my_malloc(sizeof(comp_thread_ctxt_t) * n, MYF(MY_FAE)); for (i = 0; i < n; i++) { comp_thread_ctxt_t *thd = threads + i; thd->num = i + 1; thd->started = FALSE; thd->cancelled = FALSE; thd->data_avail = FALSE; thd->to = (char *) my_malloc(COMPRESS_CHUNK_SIZE + MY_QLZ_COMPRESS_OVERHEAD, MYF(MY_FAE)); /* Initialize the control mutex and condition var */ if (pthread_mutex_init(&thd->ctrl_mutex, NULL) || pthread_cond_init(&thd->ctrl_cond, NULL)) { goto err; } /* Initialize and data mutex and condition var */ if (pthread_mutex_init(&thd->data_mutex, NULL) || pthread_cond_init(&thd->data_cond, NULL)) { goto err; } pthread_mutex_lock(&thd->ctrl_mutex); if (pthread_create(&thd->id, NULL, compress_worker_thread_func, thd)) { msg("compress: pthread_create() failed: " "errno = %d", errno); pthread_mutex_unlock(&thd->ctrl_mutex); goto err; } } /* Wait for the threads to start */ for (i = 0; i < n; i++) { comp_thread_ctxt_t *thd = threads + i; while (thd->started == FALSE) pthread_cond_wait(&thd->ctrl_cond, &thd->ctrl_mutex); pthread_mutex_unlock(&thd->ctrl_mutex); } return threads; err: my_free(threads); return NULL; }
67,434,126,023,970,640,000,000,000,000,000,000,000
None
null
[ "CWE-703" ]
CVE-2022-31623
MariaDB Server before 10.7 is vulnerable to Denial of Service. In extra/mariabackup/ds_compress.cc, when an error occurs (i.e., going to the err label) while executing the method create_worker_threads, the held lock thd->ctrl_mutex is not released correctly, which allows local users to trigger a denial of service due to the deadlock.
https://nvd.nist.gov/vuln/detail/CVE-2022-31623
514,724
server
7c30bc38a588b22b01f11130cfe99e7f36accf94
https://github.com/MariaDB/server
https://github.com/MariaDB/server/commit/7c30bc38a588b22b01f11130cfe99e7f36accf94
MDEV-26561 mariabackup release locks The previous threads locked need to be released too. This occurs if the initialization of any of the non-first mutex/conditition variables errors occurs.
0
create_worker_threads(uint n) { comp_thread_ctxt_t *threads; uint i; threads = (comp_thread_ctxt_t *) my_malloc(sizeof(comp_thread_ctxt_t) * n, MYF(MY_FAE)); for (i = 0; i < n; i++) { comp_thread_ctxt_t *thd = threads + i; thd->num = i + 1; thd->started = FALSE; thd->cancelled = FALSE; thd->data_avail = FALSE; thd->to = (char *) my_malloc(COMPRESS_CHUNK_SIZE + MY_QLZ_COMPRESS_OVERHEAD, MYF(MY_FAE)); /* Initialize the control mutex and condition var */ if (pthread_mutex_init(&thd->ctrl_mutex, NULL) || pthread_cond_init(&thd->ctrl_cond, NULL)) { goto err; } /* Initialize and data mutex and condition var */ if (pthread_mutex_init(&thd->data_mutex, NULL) || pthread_cond_init(&thd->data_cond, NULL)) { goto err; } pthread_mutex_lock(&thd->ctrl_mutex); if (pthread_create(&thd->id, NULL, compress_worker_thread_func, thd)) { msg("compress: pthread_create() failed: " "errno = %d", errno); pthread_mutex_unlock(&thd->ctrl_mutex); goto err; } } /* Wait for the threads to start */ for (i = 0; i < n; i++) { comp_thread_ctxt_t *thd = threads + i; while (thd->started == FALSE) pthread_cond_wait(&thd->ctrl_cond, &thd->ctrl_mutex); pthread_mutex_unlock(&thd->ctrl_mutex); } return threads; err: while (i > 0) { comp_thread_ctxt_t *thd; i--; thd = threads + i; pthread_mutex_unlock(&thd->ctrl_mutex); } my_free(threads); return NULL; }
40,328,221,301,176,333,000,000,000,000,000,000,000
None
null
[ "CWE-703" ]
CVE-2022-31623
MariaDB Server before 10.7 is vulnerable to Denial of Service. In extra/mariabackup/ds_compress.cc, when an error occurs (i.e., going to the err label) while executing the method create_worker_threads, the held lock thd->ctrl_mutex is not released correctly, which allows local users to trigger a denial of service due to the deadlock.
https://nvd.nist.gov/vuln/detail/CVE-2022-31623
216,975
openssl
4d8a88c134df634ba610ff8db1eb8478ac5fd345
https://github.com/openssl/openssl
https://github.com/openssl/openssl/commit/4d8a88c134df634ba610ff8db1eb8478ac5fd345
rsa: fix bn_reduce_once_in_place call for rsaz_mod_exp_avx512_x2 bn_reduce_once_in_place expects the number of BN_ULONG, but factor_size is moduli bit size. Fixes #18625. Signed-off-by: Xi Ruoyao <[email protected]> Reviewed-by: Tomas Mraz <[email protected]> Reviewed-by: Paul Dale <[email protected]> (Merged from https://github.com/openssl/openssl/pull/18626)
1
int ossl_rsaz_mod_exp_avx512_x2(BN_ULONG *res1, const BN_ULONG *base1, const BN_ULONG *exp1, const BN_ULONG *m1, const BN_ULONG *rr1, BN_ULONG k0_1, BN_ULONG *res2, const BN_ULONG *base2, const BN_ULONG *exp2, const BN_ULONG *m2, const BN_ULONG *rr2, BN_ULONG k0_2, int factor_size) { typedef void (*AMM)(BN_ULONG *res, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, BN_ULONG k0); int ret = 0; /* * Number of word-size (BN_ULONG) digits to store exponent in redundant * representation. */ int exp_digits = number_of_digits(factor_size + 2, DIGIT_SIZE); int coeff_pow = 4 * (DIGIT_SIZE * exp_digits - factor_size); /* Number of YMM registers required to store exponent's digits */ int ymm_regs_num = NUMBER_OF_REGISTERS(exp_digits, 256 /* ymm bit size */); /* Capacity of the register set (in qwords) to store exponent */ int regs_capacity = ymm_regs_num * 4; BN_ULONG *base1_red, *m1_red, *rr1_red; BN_ULONG *base2_red, *m2_red, *rr2_red; BN_ULONG *coeff_red; BN_ULONG *storage = NULL; BN_ULONG *storage_aligned = NULL; int storage_len_bytes = 7 * regs_capacity * sizeof(BN_ULONG) + 64 /* alignment */; const BN_ULONG *exp[2] = {0}; BN_ULONG k0[2] = {0}; /* AMM = Almost Montgomery Multiplication */ AMM amm = NULL; switch (factor_size) { case 1024: amm = ossl_rsaz_amm52x20_x1_ifma256; break; case 1536: amm = ossl_rsaz_amm52x30_x1_ifma256; break; case 2048: amm = ossl_rsaz_amm52x40_x1_ifma256; break; default: goto err; } storage = (BN_ULONG *)OPENSSL_malloc(storage_len_bytes); if (storage == NULL) goto err; storage_aligned = (BN_ULONG *)ALIGN_OF(storage, 64); /* Memory layout for red(undant) representations */ base1_red = storage_aligned; base2_red = storage_aligned + 1 * regs_capacity; m1_red = storage_aligned + 2 * regs_capacity; m2_red = storage_aligned + 3 * regs_capacity; rr1_red = storage_aligned + 4 * regs_capacity; rr2_red = storage_aligned + 5 * regs_capacity; coeff_red = storage_aligned + 6 * regs_capacity; /* Convert base_i, m_i, rr_i, from regular to 52-bit radix */ to_words52(base1_red, regs_capacity, base1, factor_size); to_words52(base2_red, regs_capacity, base2, factor_size); to_words52(m1_red, regs_capacity, m1, factor_size); to_words52(m2_red, regs_capacity, m2, factor_size); to_words52(rr1_red, regs_capacity, rr1, factor_size); to_words52(rr2_red, regs_capacity, rr2, factor_size); /* * Compute target domain Montgomery converters RR' for each modulus * based on precomputed original domain's RR. * * RR -> RR' transformation steps: * (1) coeff = 2^k * (2) t = AMM(RR,RR) = RR^2 / R' mod m * (3) RR' = AMM(t, coeff) = RR^2 * 2^k / R'^2 mod m * where * k = 4 * (52 * digits52 - modlen) * R = 2^(64 * ceil(modlen/64)) mod m * RR = R^2 mod m * R' = 2^(52 * ceil(modlen/52)) mod m * * EX/ modlen = 1024: k = 64, RR = 2^2048 mod m, RR' = 2^2080 mod m */ memset(coeff_red, 0, exp_digits * sizeof(BN_ULONG)); /* (1) in reduced domain representation */ set_bit(coeff_red, 64 * (int)(coeff_pow / 52) + coeff_pow % 52); amm(rr1_red, rr1_red, rr1_red, m1_red, k0_1); /* (2) for m1 */ amm(rr1_red, rr1_red, coeff_red, m1_red, k0_1); /* (3) for m1 */ amm(rr2_red, rr2_red, rr2_red, m2_red, k0_2); /* (2) for m2 */ amm(rr2_red, rr2_red, coeff_red, m2_red, k0_2); /* (3) for m2 */ exp[0] = exp1; exp[1] = exp2; k0[0] = k0_1; k0[1] = k0_2; /* Dual (2-exps in parallel) exponentiation */ ret = RSAZ_mod_exp_x2_ifma256(rr1_red, base1_red, exp, m1_red, rr1_red, k0, factor_size); if (!ret) goto err; /* Convert rr_i back to regular radix */ from_words52(res1, factor_size, rr1_red); from_words52(res2, factor_size, rr2_red); bn_reduce_once_in_place(res1, /*carry=*/0, m1, storage, factor_size); bn_reduce_once_in_place(res2, /*carry=*/0, m2, storage, factor_size); err: if (storage != NULL) { OPENSSL_cleanse(storage, storage_len_bytes); OPENSSL_free(storage); } return ret; }
13,768,713,307,638,353,000,000,000,000,000,000,000
None
null
[ "CWE-787" ]
CVE-2022-2274
The OpenSSL 3.0.4 release introduced a serious bug in the RSA implementation for X86_64 CPUs supporting the AVX512IFMA instructions. This issue makes the RSA implementation with 2048 bit private keys incorrect on such machines and memory corruption will happen during the computation. As a consequence of the memory corruption an attacker may be able to trigger a remote code execution on the machine performing the computation. SSL/TLS servers or other servers using 2048 bit RSA private keys running on machines supporting AVX512IFMA instructions of the X86_64 architecture are affected by this issue.
https://nvd.nist.gov/vuln/detail/CVE-2022-2274
514,727
openssl
4d8a88c134df634ba610ff8db1eb8478ac5fd345
https://github.com/openssl/openssl
https://github.com/openssl/openssl/commit/4d8a88c134df634ba610ff8db1eb8478ac5fd345
rsa: fix bn_reduce_once_in_place call for rsaz_mod_exp_avx512_x2 bn_reduce_once_in_place expects the number of BN_ULONG, but factor_size is moduli bit size. Fixes #18625. Signed-off-by: Xi Ruoyao <[email protected]> Reviewed-by: Tomas Mraz <[email protected]> Reviewed-by: Paul Dale <[email protected]> (Merged from https://github.com/openssl/openssl/pull/18626)
0
int ossl_rsaz_mod_exp_avx512_x2(BN_ULONG *res1, const BN_ULONG *base1, const BN_ULONG *exp1, const BN_ULONG *m1, const BN_ULONG *rr1, BN_ULONG k0_1, BN_ULONG *res2, const BN_ULONG *base2, const BN_ULONG *exp2, const BN_ULONG *m2, const BN_ULONG *rr2, BN_ULONG k0_2, int factor_size) { typedef void (*AMM)(BN_ULONG *res, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, BN_ULONG k0); int ret = 0; /* * Number of word-size (BN_ULONG) digits to store exponent in redundant * representation. */ int exp_digits = number_of_digits(factor_size + 2, DIGIT_SIZE); int coeff_pow = 4 * (DIGIT_SIZE * exp_digits - factor_size); /* Number of YMM registers required to store exponent's digits */ int ymm_regs_num = NUMBER_OF_REGISTERS(exp_digits, 256 /* ymm bit size */); /* Capacity of the register set (in qwords) to store exponent */ int regs_capacity = ymm_regs_num * 4; BN_ULONG *base1_red, *m1_red, *rr1_red; BN_ULONG *base2_red, *m2_red, *rr2_red; BN_ULONG *coeff_red; BN_ULONG *storage = NULL; BN_ULONG *storage_aligned = NULL; int storage_len_bytes = 7 * regs_capacity * sizeof(BN_ULONG) + 64 /* alignment */; const BN_ULONG *exp[2] = {0}; BN_ULONG k0[2] = {0}; /* AMM = Almost Montgomery Multiplication */ AMM amm = NULL; switch (factor_size) { case 1024: amm = ossl_rsaz_amm52x20_x1_ifma256; break; case 1536: amm = ossl_rsaz_amm52x30_x1_ifma256; break; case 2048: amm = ossl_rsaz_amm52x40_x1_ifma256; break; default: goto err; } storage = (BN_ULONG *)OPENSSL_malloc(storage_len_bytes); if (storage == NULL) goto err; storage_aligned = (BN_ULONG *)ALIGN_OF(storage, 64); /* Memory layout for red(undant) representations */ base1_red = storage_aligned; base2_red = storage_aligned + 1 * regs_capacity; m1_red = storage_aligned + 2 * regs_capacity; m2_red = storage_aligned + 3 * regs_capacity; rr1_red = storage_aligned + 4 * regs_capacity; rr2_red = storage_aligned + 5 * regs_capacity; coeff_red = storage_aligned + 6 * regs_capacity; /* Convert base_i, m_i, rr_i, from regular to 52-bit radix */ to_words52(base1_red, regs_capacity, base1, factor_size); to_words52(base2_red, regs_capacity, base2, factor_size); to_words52(m1_red, regs_capacity, m1, factor_size); to_words52(m2_red, regs_capacity, m2, factor_size); to_words52(rr1_red, regs_capacity, rr1, factor_size); to_words52(rr2_red, regs_capacity, rr2, factor_size); /* * Compute target domain Montgomery converters RR' for each modulus * based on precomputed original domain's RR. * * RR -> RR' transformation steps: * (1) coeff = 2^k * (2) t = AMM(RR,RR) = RR^2 / R' mod m * (3) RR' = AMM(t, coeff) = RR^2 * 2^k / R'^2 mod m * where * k = 4 * (52 * digits52 - modlen) * R = 2^(64 * ceil(modlen/64)) mod m * RR = R^2 mod m * R' = 2^(52 * ceil(modlen/52)) mod m * * EX/ modlen = 1024: k = 64, RR = 2^2048 mod m, RR' = 2^2080 mod m */ memset(coeff_red, 0, exp_digits * sizeof(BN_ULONG)); /* (1) in reduced domain representation */ set_bit(coeff_red, 64 * (int)(coeff_pow / 52) + coeff_pow % 52); amm(rr1_red, rr1_red, rr1_red, m1_red, k0_1); /* (2) for m1 */ amm(rr1_red, rr1_red, coeff_red, m1_red, k0_1); /* (3) for m1 */ amm(rr2_red, rr2_red, rr2_red, m2_red, k0_2); /* (2) for m2 */ amm(rr2_red, rr2_red, coeff_red, m2_red, k0_2); /* (3) for m2 */ exp[0] = exp1; exp[1] = exp2; k0[0] = k0_1; k0[1] = k0_2; /* Dual (2-exps in parallel) exponentiation */ ret = RSAZ_mod_exp_x2_ifma256(rr1_red, base1_red, exp, m1_red, rr1_red, k0, factor_size); if (!ret) goto err; /* Convert rr_i back to regular radix */ from_words52(res1, factor_size, rr1_red); from_words52(res2, factor_size, rr2_red); /* bn_reduce_once_in_place expects number of BN_ULONG, not bit size */ factor_size /= sizeof(BN_ULONG) * 8; bn_reduce_once_in_place(res1, /*carry=*/0, m1, storage, factor_size); bn_reduce_once_in_place(res2, /*carry=*/0, m2, storage, factor_size); err: if (storage != NULL) { OPENSSL_cleanse(storage, storage_len_bytes); OPENSSL_free(storage); } return ret; }
22,144,793,980,359,746,000,000,000,000,000,000,000
None
null
[ "CWE-787" ]
CVE-2022-2274
The OpenSSL 3.0.4 release introduced a serious bug in the RSA implementation for X86_64 CPUs supporting the AVX512IFMA instructions. This issue makes the RSA implementation with 2048 bit private keys incorrect on such machines and memory corruption will happen during the computation. As a consequence of the memory corruption an attacker may be able to trigger a remote code execution on the machine performing the computation. SSL/TLS servers or other servers using 2048 bit RSA private keys running on machines supporting AVX512IFMA instructions of the X86_64 architecture are affected by this issue.
https://nvd.nist.gov/vuln/detail/CVE-2022-2274
217,011
qemu
3517fb726741c109cae7995f9ea46f0cab6187d6
https://github.com/bonzini/qemu
https://github.com/qemu/qemu/commit/3517fb726741c109cae7995f9ea46f0cab6187d6
target/loongarch: Clean up tlb when cpu reset We should make sure that tlb is clean when cpu reset. Signed-off-by: Song Gao <[email protected]> Message-Id: <[email protected]> Reviewed-by: Richard Henderson <[email protected]> Signed-off-by: Richard Henderson <[email protected]>
1
static void loongarch_cpu_reset(DeviceState *dev) { CPUState *cs = CPU(dev); LoongArchCPU *cpu = LOONGARCH_CPU(cs); LoongArchCPUClass *lacc = LOONGARCH_CPU_GET_CLASS(cpu); CPULoongArchState *env = &cpu->env; lacc->parent_reset(dev); env->fcsr0_mask = FCSR0_M1 | FCSR0_M2 | FCSR0_M3; env->fcsr0 = 0x0; int n; /* Set csr registers value after reset */ env->CSR_CRMD = FIELD_DP64(env->CSR_CRMD, CSR_CRMD, PLV, 0); env->CSR_CRMD = FIELD_DP64(env->CSR_CRMD, CSR_CRMD, IE, 0); env->CSR_CRMD = FIELD_DP64(env->CSR_CRMD, CSR_CRMD, DA, 1); env->CSR_CRMD = FIELD_DP64(env->CSR_CRMD, CSR_CRMD, PG, 0); env->CSR_CRMD = FIELD_DP64(env->CSR_CRMD, CSR_CRMD, DATF, 1); env->CSR_CRMD = FIELD_DP64(env->CSR_CRMD, CSR_CRMD, DATM, 1); env->CSR_EUEN = FIELD_DP64(env->CSR_EUEN, CSR_EUEN, FPE, 0); env->CSR_EUEN = FIELD_DP64(env->CSR_EUEN, CSR_EUEN, SXE, 0); env->CSR_EUEN = FIELD_DP64(env->CSR_EUEN, CSR_EUEN, ASXE, 0); env->CSR_EUEN = FIELD_DP64(env->CSR_EUEN, CSR_EUEN, BTE, 0); env->CSR_MISC = 0; env->CSR_ECFG = FIELD_DP64(env->CSR_ECFG, CSR_ECFG, VS, 0); env->CSR_ECFG = FIELD_DP64(env->CSR_ECFG, CSR_ECFG, LIE, 0); env->CSR_ESTAT = env->CSR_ESTAT & (~MAKE_64BIT_MASK(0, 2)); env->CSR_RVACFG = FIELD_DP64(env->CSR_RVACFG, CSR_RVACFG, RBITS, 0); env->CSR_TCFG = FIELD_DP64(env->CSR_TCFG, CSR_TCFG, EN, 0); env->CSR_LLBCTL = FIELD_DP64(env->CSR_LLBCTL, CSR_LLBCTL, KLO, 0); env->CSR_TLBRERA = FIELD_DP64(env->CSR_TLBRERA, CSR_TLBRERA, ISTLBR, 0); env->CSR_MERRCTL = FIELD_DP64(env->CSR_MERRCTL, CSR_MERRCTL, ISMERR, 0); env->CSR_PRCFG3 = FIELD_DP64(env->CSR_PRCFG3, CSR_PRCFG3, TLB_TYPE, 2); env->CSR_PRCFG3 = FIELD_DP64(env->CSR_PRCFG3, CSR_PRCFG3, MTLB_ENTRY, 63); env->CSR_PRCFG3 = FIELD_DP64(env->CSR_PRCFG3, CSR_PRCFG3, STLB_WAYS, 7); env->CSR_PRCFG3 = FIELD_DP64(env->CSR_PRCFG3, CSR_PRCFG3, STLB_SETS, 8); for (n = 0; n < 4; n++) { env->CSR_DMW[n] = FIELD_DP64(env->CSR_DMW[n], CSR_DMW, PLV0, 0); env->CSR_DMW[n] = FIELD_DP64(env->CSR_DMW[n], CSR_DMW, PLV1, 0); env->CSR_DMW[n] = FIELD_DP64(env->CSR_DMW[n], CSR_DMW, PLV2, 0); env->CSR_DMW[n] = FIELD_DP64(env->CSR_DMW[n], CSR_DMW, PLV3, 0); } #ifndef CONFIG_USER_ONLY env->pc = 0x1c000000; #endif restore_fp_status(env); cs->exception_index = -1; }
189,863,556,959,363,100,000,000,000,000,000,000,000
None
null
[ "CWE-908" ]
CVE-2022-35414
softmmu/physmem.c in QEMU through 7.0.0 can perform an uninitialized read on the translate_fail path, leading to an io_readx or io_writex crash. NOTE: a third party states that the Non-virtualization Use Case in the qemu.org reference applies here, i.e., "Bugs affecting the non-virtualization use case are not considered security bugs at this time.
https://nvd.nist.gov/vuln/detail/CVE-2022-35414
515,809
qemu
3517fb726741c109cae7995f9ea46f0cab6187d6
https://github.com/bonzini/qemu
https://github.com/qemu/qemu/commit/3517fb726741c109cae7995f9ea46f0cab6187d6
target/loongarch: Clean up tlb when cpu reset We should make sure that tlb is clean when cpu reset. Signed-off-by: Song Gao <[email protected]> Message-Id: <[email protected]> Reviewed-by: Richard Henderson <[email protected]> Signed-off-by: Richard Henderson <[email protected]>
0
static void loongarch_cpu_reset(DeviceState *dev) { CPUState *cs = CPU(dev); LoongArchCPU *cpu = LOONGARCH_CPU(cs); LoongArchCPUClass *lacc = LOONGARCH_CPU_GET_CLASS(cpu); CPULoongArchState *env = &cpu->env; lacc->parent_reset(dev); env->fcsr0_mask = FCSR0_M1 | FCSR0_M2 | FCSR0_M3; env->fcsr0 = 0x0; int n; /* Set csr registers value after reset */ env->CSR_CRMD = FIELD_DP64(env->CSR_CRMD, CSR_CRMD, PLV, 0); env->CSR_CRMD = FIELD_DP64(env->CSR_CRMD, CSR_CRMD, IE, 0); env->CSR_CRMD = FIELD_DP64(env->CSR_CRMD, CSR_CRMD, DA, 1); env->CSR_CRMD = FIELD_DP64(env->CSR_CRMD, CSR_CRMD, PG, 0); env->CSR_CRMD = FIELD_DP64(env->CSR_CRMD, CSR_CRMD, DATF, 1); env->CSR_CRMD = FIELD_DP64(env->CSR_CRMD, CSR_CRMD, DATM, 1); env->CSR_EUEN = FIELD_DP64(env->CSR_EUEN, CSR_EUEN, FPE, 0); env->CSR_EUEN = FIELD_DP64(env->CSR_EUEN, CSR_EUEN, SXE, 0); env->CSR_EUEN = FIELD_DP64(env->CSR_EUEN, CSR_EUEN, ASXE, 0); env->CSR_EUEN = FIELD_DP64(env->CSR_EUEN, CSR_EUEN, BTE, 0); env->CSR_MISC = 0; env->CSR_ECFG = FIELD_DP64(env->CSR_ECFG, CSR_ECFG, VS, 0); env->CSR_ECFG = FIELD_DP64(env->CSR_ECFG, CSR_ECFG, LIE, 0); env->CSR_ESTAT = env->CSR_ESTAT & (~MAKE_64BIT_MASK(0, 2)); env->CSR_RVACFG = FIELD_DP64(env->CSR_RVACFG, CSR_RVACFG, RBITS, 0); env->CSR_TCFG = FIELD_DP64(env->CSR_TCFG, CSR_TCFG, EN, 0); env->CSR_LLBCTL = FIELD_DP64(env->CSR_LLBCTL, CSR_LLBCTL, KLO, 0); env->CSR_TLBRERA = FIELD_DP64(env->CSR_TLBRERA, CSR_TLBRERA, ISTLBR, 0); env->CSR_MERRCTL = FIELD_DP64(env->CSR_MERRCTL, CSR_MERRCTL, ISMERR, 0); env->CSR_PRCFG3 = FIELD_DP64(env->CSR_PRCFG3, CSR_PRCFG3, TLB_TYPE, 2); env->CSR_PRCFG3 = FIELD_DP64(env->CSR_PRCFG3, CSR_PRCFG3, MTLB_ENTRY, 63); env->CSR_PRCFG3 = FIELD_DP64(env->CSR_PRCFG3, CSR_PRCFG3, STLB_WAYS, 7); env->CSR_PRCFG3 = FIELD_DP64(env->CSR_PRCFG3, CSR_PRCFG3, STLB_SETS, 8); for (n = 0; n < 4; n++) { env->CSR_DMW[n] = FIELD_DP64(env->CSR_DMW[n], CSR_DMW, PLV0, 0); env->CSR_DMW[n] = FIELD_DP64(env->CSR_DMW[n], CSR_DMW, PLV1, 0); env->CSR_DMW[n] = FIELD_DP64(env->CSR_DMW[n], CSR_DMW, PLV2, 0); env->CSR_DMW[n] = FIELD_DP64(env->CSR_DMW[n], CSR_DMW, PLV3, 0); } #ifndef CONFIG_USER_ONLY env->pc = 0x1c000000; memset(env->tlb, 0, sizeof(env->tlb)); #endif restore_fp_status(env); cs->exception_index = -1; }
336,031,391,612,226,240,000,000,000,000,000,000,000
None
null
[ "CWE-908" ]
CVE-2022-35414
softmmu/physmem.c in QEMU through 7.0.0 can perform an uninitialized read on the translate_fail path, leading to an io_readx or io_writex crash. NOTE: a third party states that the Non-virtualization Use Case in the qemu.org reference applies here, i.e., "Bugs affecting the non-virtualization use case are not considered security bugs at this time.
https://nvd.nist.gov/vuln/detail/CVE-2022-35414
217,013
html-parser
b9aae1e43eb2c8e989510187cff0ba3e996f9a4c
http://github.com/gisle/html-parser
http://github.com/gisle/html-parser/commit/b9aae1e43eb2c8e989510187cff0ba3e996f9a4c
decode_entities confused by trailing incomplete entity Mark Martinec reported crashed when running SpamAssassin, given a particular HTML junk mail to parse. The problem was caused by HTML::Parsers decode_entities function confusing itself when it encountered strings with incomplete entities at the end of the string.
1
decode_entities(pTHX_ SV* sv, HV* entity2char, bool expand_prefix) { STRLEN len; char *s = SvPV_force(sv, len); char *t = s; char *end = s + len; char *ent_start; char *repl; STRLEN repl_len; #ifdef UNICODE_HTML_PARSER char buf[UTF8_MAXLEN]; int repl_utf8; int high_surrogate = 0; #else char buf[1]; #endif #if defined(__GNUC__) && defined(UNICODE_HTML_PARSER) /* gcc -Wall reports this variable as possibly used uninitialized */ repl_utf8 = 0; #endif while (s < end) { assert(t <= s); if ((*t++ = *s++) != '&') continue; ent_start = s; repl = 0; if (*s == '#') { UV num = 0; UV prev = 0; int ok = 0; s++; if (*s == 'x' || *s == 'X') { s++; while (*s) { char *tmp = strchr(PL_hexdigit, *s); if (!tmp) break; num = num << 4 | ((tmp - PL_hexdigit) & 15); if (prev && num <= prev) { /* overflow */ ok = 0; break; } prev = num; s++; ok = 1; } } else { while (isDIGIT(*s)) { num = num * 10 + (*s - '0'); if (prev && num < prev) { /* overflow */ ok = 0; break; } prev = num; s++; ok = 1; } } if (ok) { #ifdef UNICODE_HTML_PARSER if (!SvUTF8(sv) && num <= 255) { buf[0] = (char) num; repl = buf; repl_len = 1; repl_utf8 = 0; } else { char *tmp; if ((num & 0xFFFFFC00) == 0xDC00) { /* low-surrogate */ if (high_surrogate != 0) { t -= 3; /* Back up past 0xFFFD */ num = ((high_surrogate - 0xD800) << 10) + (num - 0xDC00) + 0x10000; high_surrogate = 0; } else { num = 0xFFFD; } } else if ((num & 0xFFFFFC00) == 0xD800) { /* high-surrogate */ high_surrogate = num; num = 0xFFFD; } else { high_surrogate = 0; /* otherwise invalid? */ if ((num >= 0xFDD0 && num <= 0xFDEF) || ((num & 0xFFFE) == 0xFFFE) || num > 0x10FFFF) { num = 0xFFFD; } } tmp = (char*)uvuni_to_utf8((U8*)buf, num); repl = buf; repl_len = tmp - buf; repl_utf8 = 1; } #else if (num <= 255) { buf[0] = (char) num & 0xFF; repl = buf; repl_len = 1; } #endif } } else { char *ent_name = s; while (isALNUM(*s)) s++; if (ent_name != s && entity2char) { SV** svp; if ( (svp = hv_fetch(entity2char, ent_name, s - ent_name, 0)) || (*s == ';' && (svp = hv_fetch(entity2char, ent_name, s - ent_name + 1, 0))) ) { repl = SvPV(*svp, repl_len); #ifdef UNICODE_HTML_PARSER repl_utf8 = SvUTF8(*svp); #endif } else if (expand_prefix) { char *ss = s - 1; while (ss > ent_name) { svp = hv_fetch(entity2char, ent_name, ss - ent_name, 0); if (svp) { repl = SvPV(*svp, repl_len); #ifdef UNICODE_HTML_PARSER repl_utf8 = SvUTF8(*svp); #endif s = ss; break; } ss--; } } } #ifdef UNICODE_HTML_PARSER high_surrogate = 0; #endif } if (repl) { char *repl_allocated = 0; if (*s == ';') s++; t--; /* '&' already copied, undo it */ #ifdef UNICODE_HTML_PARSER if (*s != '&') { high_surrogate = 0; } if (!SvUTF8(sv) && repl_utf8) { /* need to upgrade sv before we continue */ STRLEN before_gap_len = t - SvPVX(sv); char *before_gap = (char*)bytes_to_utf8((U8*)SvPVX(sv), &before_gap_len); STRLEN after_gap_len = end - s; char *after_gap = (char*)bytes_to_utf8((U8*)s, &after_gap_len); sv_setpvn(sv, before_gap, before_gap_len); sv_catpvn(sv, after_gap, after_gap_len); SvUTF8_on(sv); Safefree(before_gap); Safefree(after_gap); s = t = SvPVX(sv) + before_gap_len; end = SvPVX(sv) + before_gap_len + after_gap_len; } else if (SvUTF8(sv) && !repl_utf8) { repl = (char*)bytes_to_utf8((U8*)repl, &repl_len); repl_allocated = repl; } #endif if (t + repl_len > s) { /* need to grow the string */ grow_gap(aTHX_ sv, repl_len - (s - t), &t, &s, &end); } /* copy replacement string into string */ while (repl_len--) *t++ = *repl++; if (repl_allocated) Safefree(repl_allocated); } else { while (ent_start < s) *t++ = *ent_start++; } } *t = '\0'; SvCUR_set(sv, t - SvPVX(sv)); return sv; }
55,873,461,094,162,610,000,000,000,000,000,000,000
None
null
[ "CWE-20" ]
CVE-2009-3627
The decode_entities function in util.c in HTML-Parser before 3.63 allows context-dependent attackers to cause a denial of service (infinite loop) via an incomplete SGML numeric character reference, which triggers generation of an invalid UTF-8 character.
https://nvd.nist.gov/vuln/detail/CVE-2009-3627
515,837
html-parser
b9aae1e43eb2c8e989510187cff0ba3e996f9a4c
http://github.com/gisle/html-parser
http://github.com/gisle/html-parser/commit/b9aae1e43eb2c8e989510187cff0ba3e996f9a4c
decode_entities confused by trailing incomplete entity Mark Martinec reported crashed when running SpamAssassin, given a particular HTML junk mail to parse. The problem was caused by HTML::Parsers decode_entities function confusing itself when it encountered strings with incomplete entities at the end of the string.
0
decode_entities(pTHX_ SV* sv, HV* entity2char, bool expand_prefix) { STRLEN len; char *s = SvPV_force(sv, len); char *t = s; char *end = s + len; char *ent_start; char *repl; STRLEN repl_len; #ifdef UNICODE_HTML_PARSER char buf[UTF8_MAXLEN]; int repl_utf8; int high_surrogate = 0; #else char buf[1]; #endif #if defined(__GNUC__) && defined(UNICODE_HTML_PARSER) /* gcc -Wall reports this variable as possibly used uninitialized */ repl_utf8 = 0; #endif while (s < end) { assert(t <= s); if ((*t++ = *s++) != '&') continue; ent_start = s; repl = 0; if (s < end && *s == '#') { UV num = 0; UV prev = 0; int ok = 0; s++; if (s < end && (*s == 'x' || *s == 'X')) { s++; while (s < end) { char *tmp = strchr(PL_hexdigit, *s); if (!tmp) break; num = num << 4 | ((tmp - PL_hexdigit) & 15); if (prev && num <= prev) { /* overflow */ ok = 0; break; } prev = num; s++; ok = 1; } } else { while (s < end && isDIGIT(*s)) { num = num * 10 + (*s - '0'); if (prev && num < prev) { /* overflow */ ok = 0; break; } prev = num; s++; ok = 1; } } if (ok) { #ifdef UNICODE_HTML_PARSER if (!SvUTF8(sv) && num <= 255) { buf[0] = (char) num; repl = buf; repl_len = 1; repl_utf8 = 0; } else { char *tmp; if ((num & 0xFFFFFC00) == 0xDC00) { /* low-surrogate */ if (high_surrogate != 0) { t -= 3; /* Back up past 0xFFFD */ num = ((high_surrogate - 0xD800) << 10) + (num - 0xDC00) + 0x10000; high_surrogate = 0; } else { num = 0xFFFD; } } else if ((num & 0xFFFFFC00) == 0xD800) { /* high-surrogate */ high_surrogate = num; num = 0xFFFD; } else { high_surrogate = 0; /* otherwise invalid? */ if ((num >= 0xFDD0 && num <= 0xFDEF) || ((num & 0xFFFE) == 0xFFFE) || num > 0x10FFFF) { num = 0xFFFD; } } tmp = (char*)uvuni_to_utf8((U8*)buf, num); repl = buf; repl_len = tmp - buf; repl_utf8 = 1; } #else if (num <= 255) { buf[0] = (char) num & 0xFF; repl = buf; repl_len = 1; } #endif } } else { char *ent_name = s; while (s < end && isALNUM(*s)) s++; if (ent_name != s && entity2char) { SV** svp; if ( (svp = hv_fetch(entity2char, ent_name, s - ent_name, 0)) || (*s == ';' && (svp = hv_fetch(entity2char, ent_name, s - ent_name + 1, 0))) ) { repl = SvPV(*svp, repl_len); #ifdef UNICODE_HTML_PARSER repl_utf8 = SvUTF8(*svp); #endif } else if (expand_prefix) { char *ss = s - 1; while (ss > ent_name) { svp = hv_fetch(entity2char, ent_name, ss - ent_name, 0); if (svp) { repl = SvPV(*svp, repl_len); #ifdef UNICODE_HTML_PARSER repl_utf8 = SvUTF8(*svp); #endif s = ss; break; } ss--; } } } #ifdef UNICODE_HTML_PARSER high_surrogate = 0; #endif } if (repl) { char *repl_allocated = 0; if (s < end && *s == ';') s++; t--; /* '&' already copied, undo it */ #ifdef UNICODE_HTML_PARSER if (*s != '&') { high_surrogate = 0; } if (!SvUTF8(sv) && repl_utf8) { /* need to upgrade sv before we continue */ STRLEN before_gap_len = t - SvPVX(sv); char *before_gap = (char*)bytes_to_utf8((U8*)SvPVX(sv), &before_gap_len); STRLEN after_gap_len = end - s; char *after_gap = (char*)bytes_to_utf8((U8*)s, &after_gap_len); sv_setpvn(sv, before_gap, before_gap_len); sv_catpvn(sv, after_gap, after_gap_len); SvUTF8_on(sv); Safefree(before_gap); Safefree(after_gap); s = t = SvPVX(sv) + before_gap_len; end = SvPVX(sv) + before_gap_len + after_gap_len; } else if (SvUTF8(sv) && !repl_utf8) { repl = (char*)bytes_to_utf8((U8*)repl, &repl_len); repl_allocated = repl; } #endif if (t + repl_len > s) { /* need to grow the string */ grow_gap(aTHX_ sv, repl_len - (s - t), &t, &s, &end); } /* copy replacement string into string */ while (repl_len--) *t++ = *repl++; if (repl_allocated) Safefree(repl_allocated); } else { while (ent_start < s) *t++ = *ent_start++; } } *t = '\0'; SvCUR_set(sv, t - SvPVX(sv)); return sv; }
324,129,469,800,921,000,000,000,000,000,000,000,000
None
null
[ "CWE-20" ]
CVE-2009-3627
The decode_entities function in util.c in HTML-Parser before 3.63 allows context-dependent attackers to cause a denial of service (infinite loop) via an incomplete SGML numeric character reference, which triggers generation of an invalid UTF-8 character.
https://nvd.nist.gov/vuln/detail/CVE-2009-3627
217,024
platform_bionic
7f5aa4f35e23fd37425b3a5041737cdf58f87385
https://github.com/android/platform_bionic
https://github.com/android/platform_bionic/commit/7f5aa4f35e23fd37425b3a5041737cdf58f87385
bionic: fix integer overflows in chk_malloc(), leak_malloc(), and leak_memalign() The allocation size in chk_malloc(), leak_malloc(), and leak_memalign() functions may be rounded up to a small value, leading to buffer overflows. The code only runs in debugging mode. This patch complements commit 6f04a0f4 (CVE-2009-0607). Change-Id: Id899bcd2bcd2ea2205e5753c433390710032dc83 Signed-off-by: Xi Wang <[email protected]>
1
void* leak_malloc(size_t bytes) { // allocate enough space infront of the allocation to store the pointer for // the alloc structure. This will making free'ing the structer really fast! // 1. allocate enough memory and include our header // 2. set the base pointer to be right after our header void* base = dlmalloc(bytes + sizeof(AllocationEntry)); if (base != NULL) { pthread_mutex_lock(&gAllocationsMutex); intptr_t backtrace[BACKTRACE_SIZE]; size_t numEntries = get_backtrace(backtrace, BACKTRACE_SIZE); AllocationEntry* header = (AllocationEntry*)base; header->entry = record_backtrace(backtrace, numEntries, bytes); header->guard = GUARD; // now increment base to point to after our header. // this should just work since our header is 8 bytes. base = (AllocationEntry*)base + 1; pthread_mutex_unlock(&gAllocationsMutex); } return base; }
230,226,643,357,187,370,000,000,000,000,000,000,000
None
null
[ "CWE-189" ]
CVE-2012-2674
Multiple integer overflows in the (1) chk_malloc, (2) leak_malloc, and (3) leak_memalign functions in libc/bionic/malloc_debug_leak.c in Bionic (libc) for Android, when libc.debug.malloc is set, make it easier for context-dependent attackers to perform memory-related attacks such as buffer overflows via a large size value, which causes less memory to be allocated than expected.
https://nvd.nist.gov/vuln/detail/CVE-2012-2674
515,997
platform_bionic
7f5aa4f35e23fd37425b3a5041737cdf58f87385
https://github.com/android/platform_bionic
https://github.com/android/platform_bionic/commit/7f5aa4f35e23fd37425b3a5041737cdf58f87385
bionic: fix integer overflows in chk_malloc(), leak_malloc(), and leak_memalign() The allocation size in chk_malloc(), leak_malloc(), and leak_memalign() functions may be rounded up to a small value, leading to buffer overflows. The code only runs in debugging mode. This patch complements commit 6f04a0f4 (CVE-2009-0607). Change-Id: Id899bcd2bcd2ea2205e5753c433390710032dc83 Signed-off-by: Xi Wang <[email protected]>
0
void* leak_malloc(size_t bytes) { // allocate enough space infront of the allocation to store the pointer for // the alloc structure. This will making free'ing the structer really fast! // 1. allocate enough memory and include our header // 2. set the base pointer to be right after our header size_t size = bytes + sizeof(AllocationEntry); if (size < bytes) { // Overflow. return NULL; } void* base = dlmalloc(size); if (base != NULL) { pthread_mutex_lock(&gAllocationsMutex); intptr_t backtrace[BACKTRACE_SIZE]; size_t numEntries = get_backtrace(backtrace, BACKTRACE_SIZE); AllocationEntry* header = (AllocationEntry*)base; header->entry = record_backtrace(backtrace, numEntries, bytes); header->guard = GUARD; // now increment base to point to after our header. // this should just work since our header is 8 bytes. base = (AllocationEntry*)base + 1; pthread_mutex_unlock(&gAllocationsMutex); } return base; }
331,569,411,028,560,230,000,000,000,000,000,000,000
None
null
[ "CWE-189" ]
CVE-2012-2674
Multiple integer overflows in the (1) chk_malloc, (2) leak_malloc, and (3) leak_memalign functions in libc/bionic/malloc_debug_leak.c in Bionic (libc) for Android, when libc.debug.malloc is set, make it easier for context-dependent attackers to perform memory-related attacks such as buffer overflows via a large size value, which causes less memory to be allocated than expected.
https://nvd.nist.gov/vuln/detail/CVE-2012-2674
217,025
platform_bionic
7f5aa4f35e23fd37425b3a5041737cdf58f87385
https://github.com/android/platform_bionic
https://github.com/android/platform_bionic/commit/7f5aa4f35e23fd37425b3a5041737cdf58f87385
bionic: fix integer overflows in chk_malloc(), leak_malloc(), and leak_memalign() The allocation size in chk_malloc(), leak_malloc(), and leak_memalign() functions may be rounded up to a small value, leading to buffer overflows. The code only runs in debugging mode. This patch complements commit 6f04a0f4 (CVE-2009-0607). Change-Id: Id899bcd2bcd2ea2205e5753c433390710032dc83 Signed-off-by: Xi Wang <[email protected]>
1
void* chk_malloc(size_t bytes) { char* buffer = (char*)dlmalloc(bytes + CHK_OVERHEAD_SIZE); if (buffer) { memset(buffer, CHK_SENTINEL_VALUE, bytes + CHK_OVERHEAD_SIZE); size_t offset = dlmalloc_usable_size(buffer) - sizeof(size_t); *(size_t *)(buffer + offset) = bytes; buffer += CHK_SENTINEL_HEAD_SIZE; } return buffer; }
207,891,667,812,877,170,000,000,000,000,000,000,000
None
null
[ "CWE-189" ]
CVE-2012-2674
Multiple integer overflows in the (1) chk_malloc, (2) leak_malloc, and (3) leak_memalign functions in libc/bionic/malloc_debug_leak.c in Bionic (libc) for Android, when libc.debug.malloc is set, make it easier for context-dependent attackers to perform memory-related attacks such as buffer overflows via a large size value, which causes less memory to be allocated than expected.
https://nvd.nist.gov/vuln/detail/CVE-2012-2674
515,993
platform_bionic
7f5aa4f35e23fd37425b3a5041737cdf58f87385
https://github.com/android/platform_bionic
https://github.com/android/platform_bionic/commit/7f5aa4f35e23fd37425b3a5041737cdf58f87385
bionic: fix integer overflows in chk_malloc(), leak_malloc(), and leak_memalign() The allocation size in chk_malloc(), leak_malloc(), and leak_memalign() functions may be rounded up to a small value, leading to buffer overflows. The code only runs in debugging mode. This patch complements commit 6f04a0f4 (CVE-2009-0607). Change-Id: Id899bcd2bcd2ea2205e5753c433390710032dc83 Signed-off-by: Xi Wang <[email protected]>
0
void* chk_malloc(size_t bytes) { size_t size = bytes + CHK_OVERHEAD_SIZE; if (size < bytes) { // Overflow. return NULL; } uint8_t* buffer = (uint8_t*) dlmalloc(size); if (buffer) { memset(buffer, CHK_SENTINEL_VALUE, bytes + CHK_OVERHEAD_SIZE); size_t offset = dlmalloc_usable_size(buffer) - sizeof(size_t); *(size_t *)(buffer + offset) = bytes; buffer += CHK_SENTINEL_HEAD_SIZE; } return buffer; }
337,156,802,310,075,100,000,000,000,000,000,000,000
None
null
[ "CWE-189" ]
CVE-2012-2674
Multiple integer overflows in the (1) chk_malloc, (2) leak_malloc, and (3) leak_memalign functions in libc/bionic/malloc_debug_leak.c in Bionic (libc) for Android, when libc.debug.malloc is set, make it easier for context-dependent attackers to perform memory-related attacks such as buffer overflows via a large size value, which causes less memory to be allocated than expected.
https://nvd.nist.gov/vuln/detail/CVE-2012-2674
217,026
platform_bionic
7f5aa4f35e23fd37425b3a5041737cdf58f87385
https://github.com/android/platform_bionic
https://github.com/android/platform_bionic/commit/7f5aa4f35e23fd37425b3a5041737cdf58f87385
bionic: fix integer overflows in chk_malloc(), leak_malloc(), and leak_memalign() The allocation size in chk_malloc(), leak_malloc(), and leak_memalign() functions may be rounded up to a small value, leading to buffer overflows. The code only runs in debugging mode. This patch complements commit 6f04a0f4 (CVE-2009-0607). Change-Id: Id899bcd2bcd2ea2205e5753c433390710032dc83 Signed-off-by: Xi Wang <[email protected]>
1
void* leak_memalign(size_t alignment, size_t bytes) { // we can just use malloc if (alignment <= MALLOC_ALIGNMENT) return leak_malloc(bytes); // need to make sure it's a power of two if (alignment & (alignment-1)) alignment = 1L << (31 - __builtin_clz(alignment)); // here, aligment is at least MALLOC_ALIGNMENT<<1 bytes // we will align by at least MALLOC_ALIGNMENT bytes // and at most alignment-MALLOC_ALIGNMENT bytes size_t size = (alignment-MALLOC_ALIGNMENT) + bytes; void* base = leak_malloc(size); if (base != NULL) { intptr_t ptr = (intptr_t)base; if ((ptr % alignment) == 0) return base; // align the pointer ptr += ((-ptr) % alignment); // there is always enough space for the base pointer and the guard ((void**)ptr)[-1] = MEMALIGN_GUARD; ((void**)ptr)[-2] = base; return (void*)ptr; } return base; }
113,652,545,145,346,360,000,000,000,000,000,000,000
None
null
[ "CWE-189" ]
CVE-2012-2674
Multiple integer overflows in the (1) chk_malloc, (2) leak_malloc, and (3) leak_memalign functions in libc/bionic/malloc_debug_leak.c in Bionic (libc) for Android, when libc.debug.malloc is set, make it easier for context-dependent attackers to perform memory-related attacks such as buffer overflows via a large size value, which causes less memory to be allocated than expected.
https://nvd.nist.gov/vuln/detail/CVE-2012-2674
516,002
platform_bionic
7f5aa4f35e23fd37425b3a5041737cdf58f87385
https://github.com/android/platform_bionic
https://github.com/android/platform_bionic/commit/7f5aa4f35e23fd37425b3a5041737cdf58f87385
bionic: fix integer overflows in chk_malloc(), leak_malloc(), and leak_memalign() The allocation size in chk_malloc(), leak_malloc(), and leak_memalign() functions may be rounded up to a small value, leading to buffer overflows. The code only runs in debugging mode. This patch complements commit 6f04a0f4 (CVE-2009-0607). Change-Id: Id899bcd2bcd2ea2205e5753c433390710032dc83 Signed-off-by: Xi Wang <[email protected]>
0
void* leak_memalign(size_t alignment, size_t bytes) { // we can just use malloc if (alignment <= MALLOC_ALIGNMENT) return leak_malloc(bytes); // need to make sure it's a power of two if (alignment & (alignment-1)) alignment = 1L << (31 - __builtin_clz(alignment)); // here, aligment is at least MALLOC_ALIGNMENT<<1 bytes // we will align by at least MALLOC_ALIGNMENT bytes // and at most alignment-MALLOC_ALIGNMENT bytes size_t size = (alignment-MALLOC_ALIGNMENT) + bytes; if (size < bytes) { // Overflow. return NULL; } void* base = leak_malloc(size); if (base != NULL) { intptr_t ptr = (intptr_t)base; if ((ptr % alignment) == 0) return base; // align the pointer ptr += ((-ptr) % alignment); // there is always enough space for the base pointer and the guard ((void**)ptr)[-1] = MEMALIGN_GUARD; ((void**)ptr)[-2] = base; return (void*)ptr; } return base; }
146,050,602,257,073,810,000,000,000,000,000,000,000
None
null
[ "CWE-189" ]
CVE-2012-2674
Multiple integer overflows in the (1) chk_malloc, (2) leak_malloc, and (3) leak_memalign functions in libc/bionic/malloc_debug_leak.c in Bionic (libc) for Android, when libc.debug.malloc is set, make it easier for context-dependent attackers to perform memory-related attacks such as buffer overflows via a large size value, which causes less memory to be allocated than expected.
https://nvd.nist.gov/vuln/detail/CVE-2012-2674
217,027
nedmalloc
2965eca30c408c13473c4146a9d47d547d288db1
https://github.com/ned14/nedmalloc
https://github.com/ned14/nedmalloc/commit/2965eca30c408c13473c4146a9d47d547d288db1
Avoid overflowing allocation size in calloc()
1
NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedpcalloc(nedpool *p, size_t no, size_t size) THROWSPEC { unsigned flags=NEDMALLOC_FORCERESERVE(p, 0, no*size); return nedpmalloc2(p, size*no, 0, M2_ZERO_MEMORY|flags); }
276,074,049,330,858,100,000,000,000,000,000,000,000
None
null
[ "CWE-189" ]
CVE-2012-2675
Multiple integer overflows in the (1) CallMalloc (malloc) and (2) nedpcalloc (calloc) functions in nedmalloc (nedmalloc.c) before 1.10 beta2 make it easier for context-dependent attackers to perform memory-related attacks such as buffer overflows via a large size value, which causes less memory to be allocated than expected.
https://nvd.nist.gov/vuln/detail/CVE-2012-2675
516,019
nedmalloc
2965eca30c408c13473c4146a9d47d547d288db1
https://github.com/ned14/nedmalloc
https://github.com/ned14/nedmalloc/commit/2965eca30c408c13473c4146a9d47d547d288db1
Avoid overflowing allocation size in calloc()
0
NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedpmalloc(nedpool *p, size_t size) THROWSPEC { unsigned flags=NEDMALLOC_FORCERESERVE(p, 0, size); return nedpmalloc2(p, size, 0, flags); }
18,285,440,970,008,720,000,000,000,000,000,000,000
None
null
[ "CWE-189" ]
CVE-2012-2675
Multiple integer overflows in the (1) CallMalloc (malloc) and (2) nedpcalloc (calloc) functions in nedmalloc (nedmalloc.c) before 1.10 beta2 make it easier for context-dependent attackers to perform memory-related attacks such as buffer overflows via a large size value, which causes less memory to be allocated than expected.
https://nvd.nist.gov/vuln/detail/CVE-2012-2675
217,028
squidclamav
80f74451f628264d1d9a1f1c0bbcebc932ba5e00
https://github.com/darold/squidclamav
https://github.com/darold/squidclamav/commit/80f74451f628264d1d9a1f1c0bbcebc932ba5e00
Add a workaround for a squidGuard bug that unescape the URL and send it back unescaped. This could conduct in wrong result and ssquidclamav crash especially with URL containing the %0D or %0A character. John Xue
1
int squidclamav_check_preview_handler(char *preview_data, int preview_data_len, ci_request_t * req) { ci_headers_list_t *req_header; struct http_info httpinf; av_req_data_t *data = ci_service_data(req); char *clientip; struct hostent *clientname; unsigned long ip; char *username; char *content_type; ci_off_t content_length; char *chain_ret = NULL; char *ret = NULL; int chkipdone = 0; ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: processing preview header.\n"); if (preview_data_len) ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: preview data size is %d\n", preview_data_len); /* Extract the HTTP header from the request */ if ((req_header = ci_http_request_headers(req)) == NULL) { ci_debug_printf(0, "ERROR squidclamav_check_preview_handler: bad http header, aborting.\n"); return CI_ERROR; } /* Get the Authenticated user */ if ((username = ci_headers_value(req->request_header, "X-Authenticated-User")) != NULL) { ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: X-Authenticated-User: %s\n", username); /* if a TRUSTUSER match => no squidguard and no virus scan */ if (simple_pattern_compare(username, TRUSTUSER) == 1) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No squidguard and antivir check (TRUSTUSER match) for user: %s\n", username); return CI_MOD_ALLOW204; } } else { /* set null client to - */ username = (char *)malloc(sizeof(char)*2); strcpy(username, "-"); } /* Check client Ip against SquidClamav trustclient */ if ((clientip = ci_headers_value(req->request_header, "X-Client-IP")) != NULL) { ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: X-Client-IP: %s\n", clientip); ip = inet_addr(clientip); chkipdone = 0; if (dnslookup == 1) { if ( (clientname = gethostbyaddr((char *)&ip, sizeof(ip), AF_INET)) != NULL) { if (clientname->h_name != NULL) { /* if a TRUSTCLIENT match => no squidguard and no virus scan */ if (client_pattern_compare(clientip, clientname->h_name) > 0) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No squidguard and antivir check (TRUSTCLIENT match) for client: %s(%s)\n", clientname->h_name, clientip); return CI_MOD_ALLOW204; } chkipdone = 1; } } } if (chkipdone == 0) { /* if a TRUSTCLIENT match => no squidguard and no virus scan */ if (client_pattern_compare(clientip, NULL) > 0) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No squidguard and antivir check (TRUSTCLIENT match) for client: %s\n", clientip); return CI_MOD_ALLOW204; } } } else { /* set null client to - */ clientip = (char *)malloc(sizeof(char)*2); strcpy(clientip, "-"); } /* Get the requested URL */ if (!extract_http_info(req, req_header, &httpinf)) { /* Something wrong in the header or unknow method */ ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: bad http header, aborting.\n"); return CI_MOD_ALLOW204; } ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: URL requested: %s\n", httpinf.url); /* Check the URL against SquidClamav Whitelist */ if (simple_pattern_compare(httpinf.url, WHITELIST) == 1) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No squidguard and antivir check (WHITELIST match) for url: %s\n", httpinf.url); return CI_MOD_ALLOW204; } /* Check URL header against squidGuard */ if (usepipe == 1) { ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: Sending request to chained program: %s\n", squidguard); ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: Request: %s %s %s %s\n", httpinf.url,clientip,username,httpinf.method); fprintf(sgfpw,"%s %s %s %s\n",httpinf.url,clientip,username,httpinf.method); fflush(sgfpw); /* the chained redirector must return empty line if ok or the redirection url */ chain_ret = (char *)malloc(sizeof(char)*MAX_URL_SIZE); if (chain_ret != NULL) { ret = fgets(chain_ret,MAX_URL_SIZE,sgfpr); if ((ret != NULL) && (strlen(chain_ret) > 1)) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: Chained program redirection received: %s\n", chain_ret); if (logredir) ci_debug_printf(0, "INFO Chained program redirection received: %s\n", chain_ret); /* Create the redirection url to squid */ data->blocked = 1; generate_redirect_page(strtok(chain_ret, " "), req, data); xfree(chain_ret); chain_ret = NULL; return CI_MOD_CONTINUE; } xfree(chain_ret); chain_ret = NULL; } } /* CONNECT method (https) can not be scanned so abort */ if (strcmp(httpinf.method, "CONNECT") == 0) { ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: method %s can't be scanned.\n", httpinf.method); return CI_MOD_ALLOW204; } /* Check the URL against SquidClamav abort */ if (simple_pattern_compare(httpinf.url, ABORT) == 1) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No antivir check (ABORT match) for url: %s\n", httpinf.url); return CI_MOD_ALLOW204; } /* Get the content length header */ content_length = ci_http_content_length(req); ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: Content-Length: %d\n", (int)content_length); if ((content_length > 0) && (maxsize > 0) && (content_length >= maxsize)) { ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: No antivir check, content-length upper than maxsize (%d > %d)\n", content_length, (int)maxsize); return CI_MOD_ALLOW204; } /* Get the content type header */ if ((content_type = http_content_type(req)) != NULL) { ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: Content-Type: %s\n", content_type); /* Check the Content-Type against SquidClamav abortcontent */ if (simple_pattern_compare(content_type, ABORTCONTENT)) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No antivir check (ABORTCONTENT match) for content-type: %s\n", content_type); return CI_MOD_ALLOW204; } } /* No data, so nothing to scan */ if (!data || !ci_req_hasbody(req)) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No body data, allow 204\n"); return CI_MOD_ALLOW204; } if (preview_data_len == 0) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: can not begin to scan url: No preview data.\n"); return CI_MOD_ALLOW204; } data->url = ci_buffer_alloc(strlen(httpinf.url)+1); strcpy(data->url, httpinf.url); if (username != NULL) { data->user = ci_buffer_alloc(strlen(username)+1); strcpy(data->user, username); } else { data->user = NULL; } if (clientip != NULL) { data->clientip = ci_buffer_alloc(strlen(clientip)+1); strcpy(data->clientip, clientip); } else { ci_debug_printf(0, "ERROR squidclamav_check_preview_handler: clientip is null, you must set 'icap_send_client_ip on' into squid.conf\n"); data->clientip = NULL; } data->body = ci_simple_file_new(0); if ((SEND_PERCENT_BYTES >= 0) && (START_SEND_AFTER == 0)) { ci_req_unlock_data(req); ci_simple_file_lock_all(data->body); } if (!data->body) return CI_ERROR; if (preview_data_len) { if (ci_simple_file_write(data->body, preview_data, preview_data_len, ci_req_hasalldata(req)) == CI_ERROR) return CI_ERROR; } return CI_MOD_CONTINUE; }
113,201,592,654,248,630,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2012-3501
The squidclamav_check_preview_handler function in squidclamav.c in SquidClamav 5.x before 5.8 and 6.x before 6.7 passes an unescaped URL to a system command call, which allows remote attackers to cause a denial of service (daemon crash) via a URL with certain characters, as demonstrated using %0D or %0A.
https://nvd.nist.gov/vuln/detail/CVE-2012-3501
516,090
squidclamav
80f74451f628264d1d9a1f1c0bbcebc932ba5e00
https://github.com/darold/squidclamav
https://github.com/darold/squidclamav/commit/80f74451f628264d1d9a1f1c0bbcebc932ba5e00
Add a workaround for a squidGuard bug that unescape the URL and send it back unescaped. This could conduct in wrong result and ssquidclamav crash especially with URL containing the %0D or %0A character. John Xue
0
int squidclamav_check_preview_handler(char *preview_data, int preview_data_len, ci_request_t * req) { ci_headers_list_t *req_header; struct http_info httpinf; av_req_data_t *data = ci_service_data(req); char *clientip; struct hostent *clientname; unsigned long ip; char *username; char *content_type; ci_off_t content_length; char *chain_ret = NULL; char *ret = NULL; int chkipdone = 0; ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: processing preview header.\n"); if (preview_data_len) ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: preview data size is %d\n", preview_data_len); /* Extract the HTTP header from the request */ if ((req_header = ci_http_request_headers(req)) == NULL) { ci_debug_printf(0, "ERROR squidclamav_check_preview_handler: bad http header, aborting.\n"); return CI_ERROR; } /* Get the Authenticated user */ if ((username = ci_headers_value(req->request_header, "X-Authenticated-User")) != NULL) { ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: X-Authenticated-User: %s\n", username); /* if a TRUSTUSER match => no squidguard and no virus scan */ if (simple_pattern_compare(username, TRUSTUSER) == 1) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No squidguard and antivir check (TRUSTUSER match) for user: %s\n", username); return CI_MOD_ALLOW204; } } else { /* set null client to - */ username = (char *)malloc(sizeof(char)*2); strcpy(username, "-"); } /* Check client Ip against SquidClamav trustclient */ if ((clientip = ci_headers_value(req->request_header, "X-Client-IP")) != NULL) { ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: X-Client-IP: %s\n", clientip); ip = inet_addr(clientip); chkipdone = 0; if (dnslookup == 1) { if ( (clientname = gethostbyaddr((char *)&ip, sizeof(ip), AF_INET)) != NULL) { if (clientname->h_name != NULL) { /* if a TRUSTCLIENT match => no squidguard and no virus scan */ if (client_pattern_compare(clientip, clientname->h_name) > 0) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No squidguard and antivir check (TRUSTCLIENT match) for client: %s(%s)\n", clientname->h_name, clientip); return CI_MOD_ALLOW204; } chkipdone = 1; } } } if (chkipdone == 0) { /* if a TRUSTCLIENT match => no squidguard and no virus scan */ if (client_pattern_compare(clientip, NULL) > 0) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No squidguard and antivir check (TRUSTCLIENT match) for client: %s\n", clientip); return CI_MOD_ALLOW204; } } } else { /* set null client to - */ clientip = (char *)malloc(sizeof(char)*2); strcpy(clientip, "-"); } /* Get the requested URL */ if (!extract_http_info(req, req_header, &httpinf)) { /* Something wrong in the header or unknow method */ ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: bad http header, aborting.\n"); return CI_MOD_ALLOW204; } ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: URL requested: %s\n", httpinf.url); /* Check the URL against SquidClamav Whitelist */ if (simple_pattern_compare(httpinf.url, WHITELIST) == 1) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No squidguard and antivir check (WHITELIST match) for url: %s\n", httpinf.url); return CI_MOD_ALLOW204; } /* Check URL header against squidGuard */ if (usepipe == 1) { char *rbuff = NULL; ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: Sending request to chained program: %s\n", squidguard); ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: Request: %s %s %s %s\n", httpinf.url,clientip,username,httpinf.method); /* escaping escaped character to prevent unescaping by squidguard */ rbuff = replace(httpinf.url, "%", "%25"); fprintf(sgfpw,"%s %s %s %s\n",rbuff,clientip,username,httpinf.method); fflush(sgfpw); xfree(rbuff); /* the chained redirector must return empty line if ok or the redirection url */ chain_ret = (char *)malloc(sizeof(char)*MAX_URL_SIZE); if (chain_ret != NULL) { ret = fgets(chain_ret,MAX_URL_SIZE,sgfpr); if ((ret != NULL) && (strlen(chain_ret) > 1)) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: Chained program redirection received: %s\n", chain_ret); if (logredir) ci_debug_printf(0, "INFO Chained program redirection received: %s\n", chain_ret); /* Create the redirection url to squid */ data->blocked = 1; generate_redirect_page(strtok(chain_ret, " "), req, data); xfree(chain_ret); chain_ret = NULL; return CI_MOD_CONTINUE; } xfree(chain_ret); chain_ret = NULL; } } /* CONNECT method (https) can not be scanned so abort */ if (strcmp(httpinf.method, "CONNECT") == 0) { ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: method %s can't be scanned.\n", httpinf.method); return CI_MOD_ALLOW204; } /* Check the URL against SquidClamav abort */ if (simple_pattern_compare(httpinf.url, ABORT) == 1) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No antivir check (ABORT match) for url: %s\n", httpinf.url); return CI_MOD_ALLOW204; } /* Get the content length header */ content_length = ci_http_content_length(req); ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: Content-Length: %d\n", (int)content_length); if ((content_length > 0) && (maxsize > 0) && (content_length >= maxsize)) { ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: No antivir check, content-length upper than maxsize (%d > %d)\n", content_length, (int)maxsize); return CI_MOD_ALLOW204; } /* Get the content type header */ if ((content_type = http_content_type(req)) != NULL) { ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: Content-Type: %s\n", content_type); /* Check the Content-Type against SquidClamav abortcontent */ if (simple_pattern_compare(content_type, ABORTCONTENT)) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No antivir check (ABORTCONTENT match) for content-type: %s\n", content_type); return CI_MOD_ALLOW204; } } /* No data, so nothing to scan */ if (!data || !ci_req_hasbody(req)) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No body data, allow 204\n"); return CI_MOD_ALLOW204; } if (preview_data_len == 0) { ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: can not begin to scan url: No preview data.\n"); return CI_MOD_ALLOW204; } data->url = ci_buffer_alloc(strlen(httpinf.url)+1); strcpy(data->url, httpinf.url); if (username != NULL) { data->user = ci_buffer_alloc(strlen(username)+1); strcpy(data->user, username); } else { data->user = NULL; } if (clientip != NULL) { data->clientip = ci_buffer_alloc(strlen(clientip)+1); strcpy(data->clientip, clientip); } else { ci_debug_printf(0, "ERROR squidclamav_check_preview_handler: clientip is null, you must set 'icap_send_client_ip on' into squid.conf\n"); data->clientip = NULL; } data->body = ci_simple_file_new(0); if ((SEND_PERCENT_BYTES >= 0) && (START_SEND_AFTER == 0)) { ci_req_unlock_data(req); ci_simple_file_lock_all(data->body); } if (!data->body) return CI_ERROR; if (preview_data_len) { if (ci_simple_file_write(data->body, preview_data, preview_data_len, ci_req_hasalldata(req)) == CI_ERROR) return CI_ERROR; } return CI_MOD_CONTINUE; }
275,224,704,382,283,940,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2012-3501
The squidclamav_check_preview_handler function in squidclamav.c in SquidClamav 5.x before 5.8 and 6.x before 6.7 passes an unescaped URL to a system command call, which allows remote attackers to cause a denial of service (daemon crash) via a URL with certain characters, as demonstrated using %0D or %0A.
https://nvd.nist.gov/vuln/detail/CVE-2012-3501
217,130
illumos-gate
1d276e0b382cf066dae93640746d8b4c54d15452
https://github.com/illumos/illumos-gate
https://github.com/illumos/illumos-gate/commit/1d276e0b382cf066dae93640746d8b4c54d15452
13242 parse_user_name in PAM is sloppy Reviewed by: Alex Wilson <[email protected]> Approved by: Gordon Ross <[email protected]>
1
parse_user_name(char *user_input, char **ret_username) { register char *ptr; register int index = 0; char username[PAM_MAX_RESP_SIZE]; /* Set the default value for *ret_username */ *ret_username = NULL; /* * Set the initial value for username - this is a buffer holds * the user name. */ bzero((void *)username, PAM_MAX_RESP_SIZE); /* * The user_input is guaranteed to be terminated by a null character. */ ptr = user_input; /* Skip all the leading whitespaces if there are any. */ while ((*ptr == ' ') || (*ptr == '\t')) ptr++; if (*ptr == '\0') { /* * We should never get here since the user_input we got * in pam_get_user() is not all whitespaces nor just "\0". */ return (PAM_BUF_ERR); } /* * username will be the first string we get from user_input * - we skip leading whitespaces and ignore trailing whitespaces */ while (*ptr != '\0') { if ((*ptr == ' ') || (*ptr == '\t')) break; else { username[index] = *ptr; index++; ptr++; } } /* ret_username will be freed in pam_get_user(). */ if ((*ret_username = malloc(index + 1)) == NULL) return (PAM_BUF_ERR); (void) strcpy(*ret_username, username); return (PAM_SUCCESS); }
91,358,304,056,509,070,000,000,000,000,000,000,000
None
null
[ "CWE-120" ]
CVE-2020-27678
An issue was discovered in illumos before 2020-10-22, as used in OmniOS before r151030by, r151032ay, and r151034y and SmartOS before 20201022. There is a buffer overflow in parse_user_name in lib/libpam/pam_framework.c.
https://nvd.nist.gov/vuln/detail/CVE-2020-27678
516,902
illumos-gate
1d276e0b382cf066dae93640746d8b4c54d15452
https://github.com/illumos/illumos-gate
https://github.com/illumos/illumos-gate/commit/1d276e0b382cf066dae93640746d8b4c54d15452
13242 parse_user_name in PAM is sloppy Reviewed by: Alex Wilson <[email protected]> Approved by: Gordon Ross <[email protected]>
0
parse_user_name(char *user_input, char **ret_username) { register char *ptr; register int index = 0; char username[PAM_MAX_RESP_SIZE]; /* Set the default value for *ret_username */ *ret_username = NULL; /* * Set the initial value for username - this is a buffer holds * the user name. */ bzero((void *)username, PAM_MAX_RESP_SIZE); /* * The user_input is guaranteed to be terminated by a null character. */ ptr = user_input; /* Skip all the leading whitespaces if there are any. */ while ((*ptr == ' ') || (*ptr == '\t')) ptr++; if (*ptr == '\0') { /* * We should never get here since the user_input we got * in pam_get_user() is not all whitespaces nor just "\0". */ return (PAM_BUF_ERR); } /* * username will be the first string we get from user_input * - we skip leading whitespaces and ignore trailing whitespaces */ while (*ptr != '\0') { if ((*ptr == ' ') || (*ptr == '\t') || (index >= PAM_MAX_RESP_SIZE)) { break; } else { username[index] = *ptr; index++; ptr++; } } /* ret_username will be freed in pam_get_user(). */ if (index >= PAM_MAX_RESP_SIZE || (*ret_username = strdup(username)) == NULL) return (PAM_BUF_ERR); return (PAM_SUCCESS); }
73,177,564,007,800,570,000,000,000,000,000,000,000
None
null
[ "CWE-120" ]
CVE-2020-27678
An issue was discovered in illumos before 2020-10-22, as used in OmniOS before r151030by, r151032ay, and r151034y and SmartOS before 20201022. There is a buffer overflow in parse_user_name in lib/libpam/pam_framework.c.
https://nvd.nist.gov/vuln/detail/CVE-2020-27678
217,132
xdelta-devel
ef93ff74203e030073b898c05e8b4860b5d09ef2
https://github.com/jmacd/xdelta-devel
https://github.com/jmacd/xdelta-devel/commit/ef93ff74203e030073b898c05e8b4860b5d09ef2
Add appheader tests; fix buffer overflow in main_get_appheader
1
main_get_appheader (xd3_stream *stream, main_file *ifile, main_file *output, main_file *sfile) { uint8_t *apphead; usize_t appheadsz; int ret; /* The user may disable the application header. Once the appheader * is set, this disables setting it again. */ if (! option_use_appheader) { return; } ret = xd3_get_appheader (stream, & apphead, & appheadsz); /* Ignore failure, it only means we haven't received a header yet. */ if (ret != 0) { return; } if (appheadsz > 0) { char *start = (char*)apphead; char *slash; int place = 0; char *parsed[4]; memset (parsed, 0, sizeof (parsed)); while ((slash = strchr (start, '/')) != NULL) { *slash = 0; parsed[place++] = start; start = slash + 1; } parsed[place++] = start; /* First take the output parameters. */ if (place == 2 || place == 4) { main_get_appheader_params (output, parsed, 1, "output", ifile); } /* Then take the source parameters. */ if (place == 4) { main_get_appheader_params (sfile, parsed+2, 0, "source", ifile); } } option_use_appheader = 0; return; }
281,373,746,731,901,400,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2014-9765
Buffer overflow in the main_get_appheader function in xdelta3-main.h in xdelta3 before 3.0.9 allows remote attackers to execute arbitrary code via a crafted input file.
https://nvd.nist.gov/vuln/detail/CVE-2014-9765
517,037
xdelta-devel
ef93ff74203e030073b898c05e8b4860b5d09ef2
https://github.com/jmacd/xdelta-devel
https://github.com/jmacd/xdelta-devel/commit/ef93ff74203e030073b898c05e8b4860b5d09ef2
Add appheader tests; fix buffer overflow in main_get_appheader
0
main_get_appheader (xd3_stream *stream, main_file *ifile, main_file *output, main_file *sfile) { uint8_t *apphead; usize_t appheadsz; int ret; /* The user may disable the application header. Once the appheader * is set, this disables setting it again. */ if (! option_use_appheader) { return; } ret = xd3_get_appheader (stream, & apphead, & appheadsz); /* Ignore failure, it only means we haven't received a header yet. */ if (ret != 0) { return; } if (appheadsz > 0) { const int kMaxArgs = 4; char *start = (char*)apphead; char *slash; int place = 0; char *parsed[kMaxArgs]; memset (parsed, 0, sizeof (parsed)); while ((slash = strchr (start, '/')) != NULL && place < (kMaxArgs-1)) { *slash = 0; parsed[place++] = start; start = slash + 1; } parsed[place++] = start; /* First take the output parameters. */ if (place == 2 || place == 4) { main_get_appheader_params (output, parsed, 1, "output", ifile); } /* Then take the source parameters. */ if (place == 4) { main_get_appheader_params (sfile, parsed+2, 0, "source", ifile); } } option_use_appheader = 0; return; }
174,889,360,678,033,000,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2014-9765
Buffer overflow in the main_get_appheader function in xdelta3-main.h in xdelta3 before 3.0.9 allows remote attackers to execute arbitrary code via a crafted input file.
https://nvd.nist.gov/vuln/detail/CVE-2014-9765
217,161
pam_radius
01173ec2426627dbb1e0d96c06c3ffa0b14d36d0
https://github.com/FreeRADIUS/pam_radius
https://github.com/FreeRADIUS/pam_radius/commit/01173ec2426627dbb1e0d96c06c3ffa0b14d36d0
Use "length", which has been limited in size
1
static void add_password(AUTH_HDR *request, unsigned char type, CONST char *password, char *secret) { MD5_CTX md5_secret, my_md5; unsigned char misc[AUTH_VECTOR_LEN]; int i; int length = strlen(password); unsigned char hashed[256 + AUTH_PASS_LEN]; /* can't be longer than this */ unsigned char *vector; attribute_t *attr; if (length > MAXPASS) { /* shorten the password for now */ length = MAXPASS; } if (length == 0) { length = AUTH_PASS_LEN; /* 0 maps to 16 */ } if ((length & (AUTH_PASS_LEN - 1)) != 0) { length += (AUTH_PASS_LEN - 1); /* round it up */ length &= ~(AUTH_PASS_LEN - 1); /* chop it off */ } /* 16*N maps to itself */ memset(hashed, 0, length); memcpy(hashed, password, strlen(password)); attr = find_attribute(request, PW_PASSWORD); if (type == PW_PASSWORD) { vector = request->vector; } else { vector = attr->data; /* attr CANNOT be NULL here. */ } /* ************************************************************ */ /* encrypt the password */ /* password : e[0] = p[0] ^ MD5(secret + vector) */ MD5Init(&md5_secret); MD5Update(&md5_secret, (unsigned char *) secret, strlen(secret)); my_md5 = md5_secret; /* so we won't re-do the hash later */ MD5Update(&my_md5, vector, AUTH_VECTOR_LEN); MD5Final(misc, &my_md5); /* set the final vector */ xor(hashed, misc, AUTH_PASS_LEN); /* For each step through, e[i] = p[i] ^ MD5(secret + e[i-1]) */ for (i = 1; i < (length >> 4); i++) { my_md5 = md5_secret; /* grab old value of the hash */ MD5Update(&my_md5, &hashed[(i-1) * AUTH_PASS_LEN], AUTH_PASS_LEN); MD5Final(misc, &my_md5); /* set the final vector */ xor(&hashed[i * AUTH_PASS_LEN], misc, AUTH_PASS_LEN); } if (type == PW_OLD_PASSWORD) { attr = find_attribute(request, PW_OLD_PASSWORD); } if (!attr) { add_attribute(request, type, hashed, length); } else { memcpy(attr->data, hashed, length); /* overwrite the packet */ } }
33,288,235,879,950,576,000,000,000,000,000,000,000
None
null
[ "CWE-787" ]
CVE-2015-9542
add_password in pam_radius_auth.c in pam_radius 1.4.0 does not correctly check the length of the input password, and is vulnerable to a stack-based buffer overflow during memcpy(). An attacker could send a crafted password to an application (loading the pam_radius library) and crash it. Arbitrary code execution might be possible, depending on the application, C library, compiler, and other factors.
https://nvd.nist.gov/vuln/detail/CVE-2015-9542
517,189
pam_radius
01173ec2426627dbb1e0d96c06c3ffa0b14d36d0
https://github.com/FreeRADIUS/pam_radius
https://github.com/FreeRADIUS/pam_radius/commit/01173ec2426627dbb1e0d96c06c3ffa0b14d36d0
Use "length", which has been limited in size
0
static void add_password(AUTH_HDR *request, unsigned char type, CONST char *password, char *secret) { MD5_CTX md5_secret, my_md5; unsigned char misc[AUTH_VECTOR_LEN]; int i; int length = strlen(password); unsigned char hashed[256 + AUTH_PASS_LEN]; /* can't be longer than this */ unsigned char *vector; attribute_t *attr; if (length > MAXPASS) { /* shorten the password for now */ length = MAXPASS; } if (length == 0) { length = AUTH_PASS_LEN; /* 0 maps to 16 */ } if ((length & (AUTH_PASS_LEN - 1)) != 0) { length += (AUTH_PASS_LEN - 1); /* round it up */ length &= ~(AUTH_PASS_LEN - 1); /* chop it off */ } /* 16*N maps to itself */ memset(hashed, 0, length); memcpy(hashed, password, length); attr = find_attribute(request, PW_PASSWORD); if (type == PW_PASSWORD) { vector = request->vector; } else { vector = attr->data; /* attr CANNOT be NULL here. */ } /* ************************************************************ */ /* encrypt the password */ /* password : e[0] = p[0] ^ MD5(secret + vector) */ MD5Init(&md5_secret); MD5Update(&md5_secret, (unsigned char *) secret, strlen(secret)); my_md5 = md5_secret; /* so we won't re-do the hash later */ MD5Update(&my_md5, vector, AUTH_VECTOR_LEN); MD5Final(misc, &my_md5); /* set the final vector */ xor(hashed, misc, AUTH_PASS_LEN); /* For each step through, e[i] = p[i] ^ MD5(secret + e[i-1]) */ for (i = 1; i < (length >> 4); i++) { my_md5 = md5_secret; /* grab old value of the hash */ MD5Update(&my_md5, &hashed[(i-1) * AUTH_PASS_LEN], AUTH_PASS_LEN); MD5Final(misc, &my_md5); /* set the final vector */ xor(&hashed[i * AUTH_PASS_LEN], misc, AUTH_PASS_LEN); } if (type == PW_OLD_PASSWORD) { attr = find_attribute(request, PW_OLD_PASSWORD); } if (!attr) { add_attribute(request, type, hashed, length); } else { memcpy(attr->data, hashed, length); /* overwrite the packet */ } }
53,245,594,408,979,590,000,000,000,000,000,000,000
None
null
[ "CWE-787" ]
CVE-2015-9542
add_password in pam_radius_auth.c in pam_radius 1.4.0 does not correctly check the length of the input password, and is vulnerable to a stack-based buffer overflow during memcpy(). An attacker could send a crafted password to an application (loading the pam_radius library) and crash it. Arbitrary code execution might be possible, depending on the application, C library, compiler, and other factors.
https://nvd.nist.gov/vuln/detail/CVE-2015-9542
217,162
neovim
4fad66fbe637818b6b3d6bc5d21923ba72795040
https://github.com/neovim/neovim
https://github.com/neovim/neovim/commit/4fad66fbe637818b6b3d6bc5d21923ba72795040
vim-patch:8.0.0056 Problem: When setting 'filetype' there is no check for a valid name. Solution: Only allow valid characters in 'filetype', 'syntax' and 'keymap'. https://github.com/vim/vim/commit/d0b5138ba4bccff8a744c99836041ef6322ed39a
1
did_set_string_option ( int opt_idx, /* index in options[] table */ char_u **varp, /* pointer to the option variable */ int new_value_alloced, /* new value was allocated */ char_u *oldval, /* previous value of the option */ char_u *errbuf, /* buffer for errors, or NULL */ int opt_flags /* OPT_LOCAL and/or OPT_GLOBAL */ ) { char_u *errmsg = NULL; char_u *s, *p; int did_chartab = FALSE; char_u **gvarp; bool free_oldval = (options[opt_idx].flags & P_ALLOCED); /* Get the global option to compare with, otherwise we would have to check * two values for all local options. */ gvarp = (char_u **)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL); /* Disallow changing some options from secure mode */ if ((secure || sandbox != 0) && (options[opt_idx].flags & P_SECURE)) { errmsg = e_secure; } /* Check for a "normal" file name in some options. Disallow a path * separator (slash and/or backslash), wildcards and characters that are * often illegal in a file name. */ else if ((options[opt_idx].flags & P_NFNAME) && vim_strpbrk(*varp, (char_u *)"/\\*?[|<>") != NULL) { errmsg = e_invarg; } /* 'backupcopy' */ else if (gvarp == &p_bkc) { char_u *bkc = p_bkc; unsigned int *flags = &bkc_flags; if (opt_flags & OPT_LOCAL) { bkc = curbuf->b_p_bkc; flags = &curbuf->b_bkc_flags; } if ((opt_flags & OPT_LOCAL) && *bkc == NUL) { // make the local value empty: use the global value *flags = 0; } else { if (opt_strings_flags(bkc, p_bkc_values, flags, true) != OK) { errmsg = e_invarg; } if (((*flags & BKC_AUTO) != 0) + ((*flags & BKC_YES) != 0) + ((*flags & BKC_NO) != 0) != 1) { // Must have exactly one of "auto", "yes" and "no". (void)opt_strings_flags(oldval, p_bkc_values, flags, true); errmsg = e_invarg; } } } /* 'backupext' and 'patchmode' */ else if (varp == &p_bex || varp == &p_pm) { if (STRCMP(*p_bex == '.' ? p_bex + 1 : p_bex, *p_pm == '.' ? p_pm + 1 : p_pm) == 0) errmsg = (char_u *)N_("E589: 'backupext' and 'patchmode' are equal"); } /* 'breakindentopt' */ else if (varp == &curwin->w_p_briopt) { if (briopt_check(curwin) == FAIL) errmsg = e_invarg; } else if (varp == &p_isi || varp == &(curbuf->b_p_isk) || varp == &p_isp || varp == &p_isf) { // 'isident', 'iskeyword', 'isprint or 'isfname' option: refill g_chartab[] // If the new option is invalid, use old value. 'lisp' option: refill // g_chartab[] for '-' char if (init_chartab() == FAIL) { did_chartab = TRUE; /* need to restore it below */ errmsg = e_invarg; /* error in value */ } } /* 'helpfile' */ else if (varp == &p_hf) { /* May compute new values for $VIM and $VIMRUNTIME */ if (didset_vim) { vim_setenv("VIM", ""); didset_vim = FALSE; } if (didset_vimruntime) { vim_setenv("VIMRUNTIME", ""); didset_vimruntime = FALSE; } } /* 'colorcolumn' */ else if (varp == &curwin->w_p_cc) errmsg = check_colorcolumn(curwin); /* 'helplang' */ else if (varp == &p_hlg) { /* Check for "", "ab", "ab,cd", etc. */ for (s = p_hlg; *s != NUL; s += 3) { if (s[1] == NUL || ((s[2] != ',' || s[3] == NUL) && s[2] != NUL)) { errmsg = e_invarg; break; } if (s[2] == NUL) break; } } /* 'highlight' */ else if (varp == &p_hl) { if (highlight_changed() == FAIL) errmsg = e_invarg; /* invalid flags */ } /* 'nrformats' */ else if (gvarp == &p_nf) { if (check_opt_strings(*varp, p_nf_values, TRUE) != OK) errmsg = e_invarg; } else if (varp == &p_ssop) { // 'sessionoptions' if (opt_strings_flags(p_ssop, p_ssop_values, &ssop_flags, true) != OK) errmsg = e_invarg; if ((ssop_flags & SSOP_CURDIR) && (ssop_flags & SSOP_SESDIR)) { /* Don't allow both "sesdir" and "curdir". */ (void)opt_strings_flags(oldval, p_ssop_values, &ssop_flags, true); errmsg = e_invarg; } } else if (varp == &p_vop) { // 'viewoptions' if (opt_strings_flags(p_vop, p_ssop_values, &vop_flags, true) != OK) errmsg = e_invarg; } /* 'scrollopt' */ else if (varp == &p_sbo) { if (check_opt_strings(p_sbo, p_scbopt_values, TRUE) != OK) errmsg = e_invarg; } else if (varp == &p_ambw || (int *)varp == &p_emoji) { // 'ambiwidth' if (check_opt_strings(p_ambw, p_ambw_values, false) != OK) { errmsg = e_invarg; } else if (set_chars_option(&p_lcs) != NULL) { errmsg = (char_u *)_("E834: Conflicts with value of 'listchars'"); } else if (set_chars_option(&p_fcs) != NULL) { errmsg = (char_u *)_("E835: Conflicts with value of 'fillchars'"); } } /* 'background' */ else if (varp == &p_bg) { if (check_opt_strings(p_bg, p_bg_values, FALSE) == OK) { int dark = (*p_bg == 'd'); init_highlight(FALSE, FALSE); if (dark != (*p_bg == 'd') && get_var_value((char_u *)"g:colors_name") != NULL) { /* The color scheme must have set 'background' back to another * value, that's not what we want here. Disable the color * scheme and set the colors again. */ do_unlet((char_u *)"g:colors_name", TRUE); free_string_option(p_bg); p_bg = vim_strsave((char_u *)(dark ? "dark" : "light")); check_string_option(&p_bg); init_highlight(FALSE, FALSE); } } else errmsg = e_invarg; } /* 'wildmode' */ else if (varp == &p_wim) { if (check_opt_wim() == FAIL) errmsg = e_invarg; } /* 'wildoptions' */ else if (varp == &p_wop) { if (check_opt_strings(p_wop, p_wop_values, TRUE) != OK) errmsg = e_invarg; } /* 'winaltkeys' */ else if (varp == &p_wak) { if (*p_wak == NUL || check_opt_strings(p_wak, p_wak_values, FALSE) != OK) errmsg = e_invarg; } /* 'eventignore' */ else if (varp == &p_ei) { if (check_ei() == FAIL) errmsg = e_invarg; /* 'encoding' and 'fileencoding' */ } else if (varp == &p_enc || gvarp == &p_fenc) { if (gvarp == &p_fenc) { if (!MODIFIABLE(curbuf) && opt_flags != OPT_GLOBAL) { errmsg = e_modifiable; } else if (vim_strchr(*varp, ',') != NULL) { // No comma allowed in 'fileencoding'; catches confusing it // with 'fileencodings'. errmsg = e_invarg; } else { // May show a "+" in the title now. redraw_titles(); // Add 'fileencoding' to the swap file. ml_setflags(curbuf); } } if (errmsg == NULL) { /* canonize the value, so that STRCMP() can be used on it */ p = enc_canonize(*varp); xfree(*varp); *varp = p; if (varp == &p_enc) { // only encoding=utf-8 allowed if (STRCMP(p_enc, "utf-8") != 0) { errmsg = e_invarg; } } } } else if (varp == &p_penc) { /* Canonize printencoding if VIM standard one */ p = enc_canonize(p_penc); xfree(p_penc); p_penc = p; } else if (varp == &curbuf->b_p_keymap) { /* load or unload key mapping tables */ errmsg = keymap_init(); if (errmsg == NULL) { if (*curbuf->b_p_keymap != NUL) { /* Installed a new keymap, switch on using it. */ curbuf->b_p_iminsert = B_IMODE_LMAP; if (curbuf->b_p_imsearch != B_IMODE_USE_INSERT) curbuf->b_p_imsearch = B_IMODE_LMAP; } else { /* Cleared the keymap, may reset 'iminsert' and 'imsearch'. */ if (curbuf->b_p_iminsert == B_IMODE_LMAP) curbuf->b_p_iminsert = B_IMODE_NONE; if (curbuf->b_p_imsearch == B_IMODE_LMAP) curbuf->b_p_imsearch = B_IMODE_USE_INSERT; } if ((opt_flags & OPT_LOCAL) == 0) { set_iminsert_global(); set_imsearch_global(); } status_redraw_curbuf(); } } /* 'fileformat' */ else if (gvarp == &p_ff) { if (!MODIFIABLE(curbuf) && !(opt_flags & OPT_GLOBAL)) errmsg = e_modifiable; else if (check_opt_strings(*varp, p_ff_values, FALSE) != OK) errmsg = e_invarg; else { redraw_titles(); /* update flag in swap file */ ml_setflags(curbuf); /* Redraw needed when switching to/from "mac": a CR in the text * will be displayed differently. */ if (get_fileformat(curbuf) == EOL_MAC || *oldval == 'm') redraw_curbuf_later(NOT_VALID); } } /* 'fileformats' */ else if (varp == &p_ffs) { if (check_opt_strings(p_ffs, p_ff_values, TRUE) != OK) { errmsg = e_invarg; } } /* 'matchpairs' */ else if (gvarp == &p_mps) { if (has_mbyte) { for (p = *varp; *p != NUL; ++p) { int x2 = -1; int x3 = -1; if (*p != NUL) p += mb_ptr2len(p); if (*p != NUL) x2 = *p++; if (*p != NUL) { x3 = mb_ptr2char(p); p += mb_ptr2len(p); } if (x2 != ':' || x3 == -1 || (*p != NUL && *p != ',')) { errmsg = e_invarg; break; } if (*p == NUL) break; } } else { /* Check for "x:y,x:y" */ for (p = *varp; *p != NUL; p += 4) { if (p[1] != ':' || p[2] == NUL || (p[3] != NUL && p[3] != ',')) { errmsg = e_invarg; break; } if (p[3] == NUL) break; } } } /* 'comments' */ else if (gvarp == &p_com) { for (s = *varp; *s; ) { while (*s && *s != ':') { if (vim_strchr((char_u *)COM_ALL, *s) == NULL && !ascii_isdigit(*s) && *s != '-') { errmsg = illegal_char(errbuf, *s); break; } ++s; } if (*s++ == NUL) errmsg = (char_u *)N_("E524: Missing colon"); else if (*s == ',' || *s == NUL) errmsg = (char_u *)N_("E525: Zero length string"); if (errmsg != NULL) break; while (*s && *s != ',') { if (*s == '\\' && s[1] != NUL) ++s; ++s; } s = skip_to_option_part(s); } } /* 'listchars' */ else if (varp == &p_lcs) { errmsg = set_chars_option(varp); } /* 'fillchars' */ else if (varp == &p_fcs) { errmsg = set_chars_option(varp); } /* 'cedit' */ else if (varp == &p_cedit) { errmsg = check_cedit(); } /* 'verbosefile' */ else if (varp == &p_vfile) { verbose_stop(); if (*p_vfile != NUL && verbose_open() == FAIL) errmsg = e_invarg; /* 'shada' */ } else if (varp == &p_shada) { // TODO(ZyX-I): Remove this code in the future, alongside with &viminfo // option. opt_idx = ((options[opt_idx].fullname[0] == 'v') ? (shada_idx == -1 ? ((shada_idx = findoption((char_u *) "shada"))) : shada_idx) : opt_idx); for (s = p_shada; *s; ) { /* Check it's a valid character */ if (vim_strchr((char_u *)"!\"%'/:<@cfhnrs", *s) == NULL) { errmsg = illegal_char(errbuf, *s); break; } if (*s == 'n') { /* name is always last one */ break; } else if (*s == 'r') { /* skip until next ',' */ while (*++s && *s != ',') ; } else if (*s == '%') { /* optional number */ while (ascii_isdigit(*++s)) ; } else if (*s == '!' || *s == 'h' || *s == 'c') ++s; /* no extra chars */ else { /* must have a number */ while (ascii_isdigit(*++s)) ; if (!ascii_isdigit(*(s - 1))) { if (errbuf != NULL) { sprintf((char *)errbuf, _("E526: Missing number after <%s>"), transchar_byte(*(s - 1))); errmsg = errbuf; } else errmsg = (char_u *)""; break; } } if (*s == ',') ++s; else if (*s) { if (errbuf != NULL) errmsg = (char_u *)N_("E527: Missing comma"); else errmsg = (char_u *)""; break; } } if (*p_shada && errmsg == NULL && get_shada_parameter('\'') < 0) errmsg = (char_u *)N_("E528: Must specify a ' value"); } /* 'showbreak' */ else if (varp == &p_sbr) { for (s = p_sbr; *s; ) { if (ptr2cells(s) != 1) errmsg = (char_u *)N_("E595: contains unprintable or wide character"); mb_ptr_adv(s); } } /* 'guicursor' */ else if (varp == &p_guicursor) errmsg = parse_shape_opt(SHAPE_CURSOR); else if (varp == &p_popt) errmsg = parse_printoptions(); else if (varp == &p_pmfn) errmsg = parse_printmbfont(); /* 'langmap' */ else if (varp == &p_langmap) langmap_set(); /* 'breakat' */ else if (varp == &p_breakat) fill_breakat_flags(); /* 'titlestring' and 'iconstring' */ else if (varp == &p_titlestring || varp == &p_iconstring) { int flagval = (varp == &p_titlestring) ? STL_IN_TITLE : STL_IN_ICON; /* NULL => statusline syntax */ if (vim_strchr(*varp, '%') && check_stl_option(*varp) == NULL) stl_syntax |= flagval; else stl_syntax &= ~flagval; did_set_title(varp == &p_iconstring); } /* 'selection' */ else if (varp == &p_sel) { if (*p_sel == NUL || check_opt_strings(p_sel, p_sel_values, FALSE) != OK) errmsg = e_invarg; } /* 'selectmode' */ else if (varp == &p_slm) { if (check_opt_strings(p_slm, p_slm_values, TRUE) != OK) errmsg = e_invarg; } /* 'keymodel' */ else if (varp == &p_km) { if (check_opt_strings(p_km, p_km_values, TRUE) != OK) errmsg = e_invarg; else { km_stopsel = (vim_strchr(p_km, 'o') != NULL); km_startsel = (vim_strchr(p_km, 'a') != NULL); } } /* 'mousemodel' */ else if (varp == &p_mousem) { if (check_opt_strings(p_mousem, p_mousem_values, FALSE) != OK) errmsg = e_invarg; } else if (varp == &p_swb) { // 'switchbuf' if (opt_strings_flags(p_swb, p_swb_values, &swb_flags, true) != OK) errmsg = e_invarg; } /* 'debug' */ else if (varp == &p_debug) { if (check_opt_strings(p_debug, p_debug_values, TRUE) != OK) errmsg = e_invarg; } else if (varp == &p_dy) { // 'display' if (opt_strings_flags(p_dy, p_dy_values, &dy_flags, true) != OK) errmsg = e_invarg; else (void)init_chartab(); } /* 'eadirection' */ else if (varp == &p_ead) { if (check_opt_strings(p_ead, p_ead_values, FALSE) != OK) errmsg = e_invarg; } else if (varp == &p_cb) { // 'clipboard' if (opt_strings_flags(p_cb, p_cb_values, &cb_flags, true) != OK) { errmsg = e_invarg; } } else if (varp == &(curwin->w_s->b_p_spl) // 'spell' || varp == &(curwin->w_s->b_p_spf)) { // When 'spelllang' or 'spellfile' is set and there is a window for this // buffer in which 'spell' is set load the wordlists. errmsg = did_set_spell_option(varp == &(curwin->w_s->b_p_spf)); } /* When 'spellcapcheck' is set compile the regexp program. */ else if (varp == &(curwin->w_s->b_p_spc)) { errmsg = compile_cap_prog(curwin->w_s); } /* 'spellsuggest' */ else if (varp == &p_sps) { if (spell_check_sps() != OK) errmsg = e_invarg; } /* 'mkspellmem' */ else if (varp == &p_msm) { if (spell_check_msm() != OK) errmsg = e_invarg; } /* When 'bufhidden' is set, check for valid value. */ else if (gvarp == &p_bh) { if (check_opt_strings(curbuf->b_p_bh, p_bufhidden_values, FALSE) != OK) errmsg = e_invarg; } /* When 'buftype' is set, check for valid value. */ else if (gvarp == &p_bt) { if ((curbuf->terminal && curbuf->b_p_bt[0] != 't') || (!curbuf->terminal && curbuf->b_p_bt[0] == 't') || check_opt_strings(curbuf->b_p_bt, p_buftype_values, FALSE) != OK) { errmsg = e_invarg; } else { if (curwin->w_status_height) { curwin->w_redr_status = TRUE; redraw_later(VALID); } curbuf->b_help = (curbuf->b_p_bt[0] == 'h'); redraw_titles(); } } /* 'statusline' or 'rulerformat' */ else if (gvarp == &p_stl || varp == &p_ruf) { int wid; if (varp == &p_ruf) /* reset ru_wid first */ ru_wid = 0; s = *varp; if (varp == &p_ruf && *s == '%') { /* set ru_wid if 'ruf' starts with "%99(" */ if (*++s == '-') /* ignore a '-' */ s++; wid = getdigits_int(&s); if (wid && *s == '(' && (errmsg = check_stl_option(p_ruf)) == NULL) ru_wid = wid; else errmsg = check_stl_option(p_ruf); } /* check 'statusline' only if it doesn't start with "%!" */ else if (varp == &p_ruf || s[0] != '%' || s[1] != '!') errmsg = check_stl_option(s); if (varp == &p_ruf && errmsg == NULL) comp_col(); } /* check if it is a valid value for 'complete' -- Acevedo */ else if (gvarp == &p_cpt) { for (s = *varp; *s; ) { while (*s == ',' || *s == ' ') s++; if (!*s) break; if (vim_strchr((char_u *)".wbuksid]tU", *s) == NULL) { errmsg = illegal_char(errbuf, *s); break; } if (*++s != NUL && *s != ',' && *s != ' ') { if (s[-1] == 'k' || s[-1] == 's') { /* skip optional filename after 'k' and 's' */ while (*s && *s != ',' && *s != ' ') { if (*s == '\\') ++s; ++s; } } else { if (errbuf != NULL) { sprintf((char *)errbuf, _("E535: Illegal character after <%c>"), *--s); errmsg = errbuf; } else errmsg = (char_u *)""; break; } } } } /* 'completeopt' */ else if (varp == &p_cot) { if (check_opt_strings(p_cot, p_cot_values, true) != OK) { errmsg = e_invarg; } else { completeopt_was_set(); } } /* 'pastetoggle': translate key codes like in a mapping */ else if (varp == &p_pt) { if (*p_pt) { (void)replace_termcodes(p_pt, STRLEN(p_pt), &p, true, true, false, CPO_TO_CPO_FLAGS); if (p != NULL) { if (new_value_alloced) free_string_option(p_pt); p_pt = p; new_value_alloced = TRUE; } } } /* 'backspace' */ else if (varp == &p_bs) { if (ascii_isdigit(*p_bs)) { if (*p_bs >'2' || p_bs[1] != NUL) errmsg = e_invarg; } else if (check_opt_strings(p_bs, p_bs_values, TRUE) != OK) errmsg = e_invarg; } else if (varp == &p_bo) { if (opt_strings_flags(p_bo, p_bo_values, &bo_flags, true) != OK) { errmsg = e_invarg; } } else if (gvarp == &p_tc) { // 'tagcase' unsigned int *flags; if (opt_flags & OPT_LOCAL) { p = curbuf->b_p_tc; flags = &curbuf->b_tc_flags; } else { p = p_tc; flags = &tc_flags; } if ((opt_flags & OPT_LOCAL) && *p == NUL) { // make the local value empty: use the global value *flags = 0; } else if (*p == NUL || opt_strings_flags(p, p_tc_values, flags, false) != OK) { errmsg = e_invarg; } } else if (varp == &p_cmp) { // 'casemap' if (opt_strings_flags(p_cmp, p_cmp_values, &cmp_flags, true) != OK) errmsg = e_invarg; } /* 'diffopt' */ else if (varp == &p_dip) { if (diffopt_changed() == FAIL) errmsg = e_invarg; } /* 'foldmethod' */ else if (gvarp == &curwin->w_allbuf_opt.wo_fdm) { if (check_opt_strings(*varp, p_fdm_values, FALSE) != OK || *curwin->w_p_fdm == NUL) errmsg = e_invarg; else { foldUpdateAll(curwin); if (foldmethodIsDiff(curwin)) newFoldLevel(); } } /* 'foldexpr' */ else if (varp == &curwin->w_p_fde) { if (foldmethodIsExpr(curwin)) foldUpdateAll(curwin); } /* 'foldmarker' */ else if (gvarp == &curwin->w_allbuf_opt.wo_fmr) { p = vim_strchr(*varp, ','); if (p == NULL) errmsg = (char_u *)N_("E536: comma required"); else if (p == *varp || p[1] == NUL) errmsg = e_invarg; else if (foldmethodIsMarker(curwin)) foldUpdateAll(curwin); } /* 'commentstring' */ else if (gvarp == &p_cms) { if (**varp != NUL && strstr((char *)*varp, "%s") == NULL) errmsg = (char_u *)N_( "E537: 'commentstring' must be empty or contain %s"); } else if (varp == &p_fdo) { // 'foldopen' if (opt_strings_flags(p_fdo, p_fdo_values, &fdo_flags, true) != OK) errmsg = e_invarg; } /* 'foldclose' */ else if (varp == &p_fcl) { if (check_opt_strings(p_fcl, p_fcl_values, TRUE) != OK) errmsg = e_invarg; } /* 'foldignore' */ else if (gvarp == &curwin->w_allbuf_opt.wo_fdi) { if (foldmethodIsIndent(curwin)) foldUpdateAll(curwin); } else if (varp == &p_ve) { // 'virtualedit' if (opt_strings_flags(p_ve, p_ve_values, &ve_flags, true) != OK) errmsg = e_invarg; else if (STRCMP(p_ve, oldval) != 0) { /* Recompute cursor position in case the new 've' setting * changes something. */ validate_virtcol(); coladvance(curwin->w_virtcol); } } else if (varp == &p_csqf) { if (p_csqf != NULL) { p = p_csqf; while (*p != NUL) { if (vim_strchr((char_u *)CSQF_CMDS, *p) == NULL || p[1] == NUL || vim_strchr((char_u *)CSQF_FLAGS, p[1]) == NULL || (p[2] != NUL && p[2] != ',')) { errmsg = e_invarg; break; } else if (p[2] == NUL) break; else p += 3; } } } /* 'cinoptions' */ else if (gvarp == &p_cino) { /* TODO: recognize errors */ parse_cino(curbuf); // inccommand } else if (varp == &p_icm) { if (check_opt_strings(p_icm, p_icm_values, false) != OK) { errmsg = e_invarg; } // Options that are a list of flags. } else { p = NULL; if (varp == &p_ww) p = (char_u *)WW_ALL; if (varp == &p_shm) p = (char_u *)SHM_ALL; else if (varp == &(p_cpo)) p = (char_u *)CPO_VI; else if (varp == &(curbuf->b_p_fo)) p = (char_u *)FO_ALL; else if (varp == &curwin->w_p_cocu) p = (char_u *)COCU_ALL; else if (varp == &p_mouse) { p = (char_u *)MOUSE_ALL; } if (p != NULL) { for (s = *varp; *s; ++s) if (vim_strchr(p, *s) == NULL) { errmsg = illegal_char(errbuf, *s); break; } } } /* * If error detected, restore the previous value. */ if (errmsg != NULL) { if (new_value_alloced) free_string_option(*varp); *varp = oldval; /* * When resetting some values, need to act on it. */ if (did_chartab) (void)init_chartab(); if (varp == &p_hl) (void)highlight_changed(); } else { /* Remember where the option was set. */ set_option_scriptID_idx(opt_idx, opt_flags, current_SID); /* * Free string options that are in allocated memory. * Use "free_oldval", because recursiveness may change the flags under * our fingers (esp. init_highlight()). */ if (free_oldval) free_string_option(oldval); if (new_value_alloced) options[opt_idx].flags |= P_ALLOCED; else options[opt_idx].flags &= ~P_ALLOCED; if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0 && ((int)options[opt_idx].indir & PV_BOTH)) { /* global option with local value set to use global value; free * the local value and make it empty */ p = get_varp_scope(&(options[opt_idx]), OPT_LOCAL); free_string_option(*(char_u **)p); *(char_u **)p = empty_option; } /* May set global value for local option. */ else if (!(opt_flags & OPT_LOCAL) && opt_flags != OPT_GLOBAL) set_string_option_global(opt_idx, varp); /* * Trigger the autocommand only after setting the flags. */ /* When 'syntax' is set, load the syntax of that name */ if (varp == &(curbuf->b_p_syn)) { apply_autocmds(EVENT_SYNTAX, curbuf->b_p_syn, curbuf->b_fname, TRUE, curbuf); } else if (varp == &(curbuf->b_p_ft)) { /* 'filetype' is set, trigger the FileType autocommand */ did_filetype = TRUE; apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname, TRUE, curbuf); } if (varp == &(curwin->w_s->b_p_spl)) { char_u fname[200]; char_u *q = curwin->w_s->b_p_spl; /* Skip the first name if it is "cjk". */ if (STRNCMP(q, "cjk,", 4) == 0) q += 4; /* * Source the spell/LANG.vim in 'runtimepath'. * They could set 'spellcapcheck' depending on the language. * Use the first name in 'spelllang' up to '_region' or * '.encoding'. */ for (p = q; *p != NUL; ++p) if (vim_strchr((char_u *)"_.,", *p) != NULL) break; vim_snprintf((char *)fname, sizeof(fname), "spell/%.*s.vim", (int)(p - q), q); source_runtime(fname, DIP_ALL); } } if (varp == &p_mouse) { if (*p_mouse == NUL) { ui_mouse_off(); } else { setmouse(); // in case 'mouse' changed } } if (curwin->w_curswant != MAXCOL && (options[opt_idx].flags & (P_CURSWANT | P_RALL)) != 0) curwin->w_set_curswant = TRUE; check_redraw(options[opt_idx].flags); return errmsg; }
5,057,343,703,970,560,000,000,000,000,000,000,000
None
null
[ "CWE-20" ]
CVE-2016-1248
vim before patch 8.0.0056 does not properly validate values for the 'filetype', 'syntax' and 'keymap' options, which may result in the execution of arbitrary code if a file with a specially crafted modeline is opened.
https://nvd.nist.gov/vuln/detail/CVE-2016-1248
517,286
neovim
4fad66fbe637818b6b3d6bc5d21923ba72795040
https://github.com/neovim/neovim
https://github.com/neovim/neovim/commit/4fad66fbe637818b6b3d6bc5d21923ba72795040
vim-patch:8.0.0056 Problem: When setting 'filetype' there is no check for a valid name. Solution: Only allow valid characters in 'filetype', 'syntax' and 'keymap'. https://github.com/vim/vim/commit/d0b5138ba4bccff8a744c99836041ef6322ed39a
0
did_set_string_option ( int opt_idx, /* index in options[] table */ char_u **varp, /* pointer to the option variable */ int new_value_alloced, /* new value was allocated */ char_u *oldval, /* previous value of the option */ char_u *errbuf, /* buffer for errors, or NULL */ int opt_flags /* OPT_LOCAL and/or OPT_GLOBAL */ ) { char_u *errmsg = NULL; char_u *s, *p; int did_chartab = FALSE; char_u **gvarp; bool free_oldval = (options[opt_idx].flags & P_ALLOCED); /* Get the global option to compare with, otherwise we would have to check * two values for all local options. */ gvarp = (char_u **)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL); /* Disallow changing some options from secure mode */ if ((secure || sandbox != 0) && (options[opt_idx].flags & P_SECURE)) { errmsg = e_secure; } /* Check for a "normal" file name in some options. Disallow a path * separator (slash and/or backslash), wildcards and characters that are * often illegal in a file name. */ else if ((options[opt_idx].flags & P_NFNAME) && vim_strpbrk(*varp, (char_u *)"/\\*?[|<>") != NULL) { errmsg = e_invarg; } /* 'backupcopy' */ else if (gvarp == &p_bkc) { char_u *bkc = p_bkc; unsigned int *flags = &bkc_flags; if (opt_flags & OPT_LOCAL) { bkc = curbuf->b_p_bkc; flags = &curbuf->b_bkc_flags; } if ((opt_flags & OPT_LOCAL) && *bkc == NUL) { // make the local value empty: use the global value *flags = 0; } else { if (opt_strings_flags(bkc, p_bkc_values, flags, true) != OK) { errmsg = e_invarg; } if (((*flags & BKC_AUTO) != 0) + ((*flags & BKC_YES) != 0) + ((*flags & BKC_NO) != 0) != 1) { // Must have exactly one of "auto", "yes" and "no". (void)opt_strings_flags(oldval, p_bkc_values, flags, true); errmsg = e_invarg; } } } /* 'backupext' and 'patchmode' */ else if (varp == &p_bex || varp == &p_pm) { if (STRCMP(*p_bex == '.' ? p_bex + 1 : p_bex, *p_pm == '.' ? p_pm + 1 : p_pm) == 0) errmsg = (char_u *)N_("E589: 'backupext' and 'patchmode' are equal"); } /* 'breakindentopt' */ else if (varp == &curwin->w_p_briopt) { if (briopt_check(curwin) == FAIL) errmsg = e_invarg; } else if (varp == &p_isi || varp == &(curbuf->b_p_isk) || varp == &p_isp || varp == &p_isf) { // 'isident', 'iskeyword', 'isprint or 'isfname' option: refill g_chartab[] // If the new option is invalid, use old value. 'lisp' option: refill // g_chartab[] for '-' char if (init_chartab() == FAIL) { did_chartab = TRUE; /* need to restore it below */ errmsg = e_invarg; /* error in value */ } } /* 'helpfile' */ else if (varp == &p_hf) { /* May compute new values for $VIM and $VIMRUNTIME */ if (didset_vim) { vim_setenv("VIM", ""); didset_vim = FALSE; } if (didset_vimruntime) { vim_setenv("VIMRUNTIME", ""); didset_vimruntime = FALSE; } } /* 'colorcolumn' */ else if (varp == &curwin->w_p_cc) errmsg = check_colorcolumn(curwin); /* 'helplang' */ else if (varp == &p_hlg) { /* Check for "", "ab", "ab,cd", etc. */ for (s = p_hlg; *s != NUL; s += 3) { if (s[1] == NUL || ((s[2] != ',' || s[3] == NUL) && s[2] != NUL)) { errmsg = e_invarg; break; } if (s[2] == NUL) break; } } /* 'highlight' */ else if (varp == &p_hl) { if (highlight_changed() == FAIL) errmsg = e_invarg; /* invalid flags */ } /* 'nrformats' */ else if (gvarp == &p_nf) { if (check_opt_strings(*varp, p_nf_values, TRUE) != OK) errmsg = e_invarg; } else if (varp == &p_ssop) { // 'sessionoptions' if (opt_strings_flags(p_ssop, p_ssop_values, &ssop_flags, true) != OK) errmsg = e_invarg; if ((ssop_flags & SSOP_CURDIR) && (ssop_flags & SSOP_SESDIR)) { /* Don't allow both "sesdir" and "curdir". */ (void)opt_strings_flags(oldval, p_ssop_values, &ssop_flags, true); errmsg = e_invarg; } } else if (varp == &p_vop) { // 'viewoptions' if (opt_strings_flags(p_vop, p_ssop_values, &vop_flags, true) != OK) errmsg = e_invarg; } /* 'scrollopt' */ else if (varp == &p_sbo) { if (check_opt_strings(p_sbo, p_scbopt_values, TRUE) != OK) errmsg = e_invarg; } else if (varp == &p_ambw || (int *)varp == &p_emoji) { // 'ambiwidth' if (check_opt_strings(p_ambw, p_ambw_values, false) != OK) { errmsg = e_invarg; } else if (set_chars_option(&p_lcs) != NULL) { errmsg = (char_u *)_("E834: Conflicts with value of 'listchars'"); } else if (set_chars_option(&p_fcs) != NULL) { errmsg = (char_u *)_("E835: Conflicts with value of 'fillchars'"); } } /* 'background' */ else if (varp == &p_bg) { if (check_opt_strings(p_bg, p_bg_values, FALSE) == OK) { int dark = (*p_bg == 'd'); init_highlight(FALSE, FALSE); if (dark != (*p_bg == 'd') && get_var_value((char_u *)"g:colors_name") != NULL) { /* The color scheme must have set 'background' back to another * value, that's not what we want here. Disable the color * scheme and set the colors again. */ do_unlet((char_u *)"g:colors_name", TRUE); free_string_option(p_bg); p_bg = vim_strsave((char_u *)(dark ? "dark" : "light")); check_string_option(&p_bg); init_highlight(FALSE, FALSE); } } else errmsg = e_invarg; } /* 'wildmode' */ else if (varp == &p_wim) { if (check_opt_wim() == FAIL) errmsg = e_invarg; } /* 'wildoptions' */ else if (varp == &p_wop) { if (check_opt_strings(p_wop, p_wop_values, TRUE) != OK) errmsg = e_invarg; } /* 'winaltkeys' */ else if (varp == &p_wak) { if (*p_wak == NUL || check_opt_strings(p_wak, p_wak_values, FALSE) != OK) errmsg = e_invarg; } /* 'eventignore' */ else if (varp == &p_ei) { if (check_ei() == FAIL) errmsg = e_invarg; /* 'encoding' and 'fileencoding' */ } else if (varp == &p_enc || gvarp == &p_fenc) { if (gvarp == &p_fenc) { if (!MODIFIABLE(curbuf) && opt_flags != OPT_GLOBAL) { errmsg = e_modifiable; } else if (vim_strchr(*varp, ',') != NULL) { // No comma allowed in 'fileencoding'; catches confusing it // with 'fileencodings'. errmsg = e_invarg; } else { // May show a "+" in the title now. redraw_titles(); // Add 'fileencoding' to the swap file. ml_setflags(curbuf); } } if (errmsg == NULL) { /* canonize the value, so that STRCMP() can be used on it */ p = enc_canonize(*varp); xfree(*varp); *varp = p; if (varp == &p_enc) { // only encoding=utf-8 allowed if (STRCMP(p_enc, "utf-8") != 0) { errmsg = e_invarg; } } } } else if (varp == &p_penc) { /* Canonize printencoding if VIM standard one */ p = enc_canonize(p_penc); xfree(p_penc); p_penc = p; } else if (varp == &curbuf->b_p_keymap) { if (!valid_filetype(*varp)) { errmsg = e_invarg; } else { // load or unload key mapping tables errmsg = keymap_init(); } if (errmsg == NULL) { if (*curbuf->b_p_keymap != NUL) { /* Installed a new keymap, switch on using it. */ curbuf->b_p_iminsert = B_IMODE_LMAP; if (curbuf->b_p_imsearch != B_IMODE_USE_INSERT) curbuf->b_p_imsearch = B_IMODE_LMAP; } else { /* Cleared the keymap, may reset 'iminsert' and 'imsearch'. */ if (curbuf->b_p_iminsert == B_IMODE_LMAP) curbuf->b_p_iminsert = B_IMODE_NONE; if (curbuf->b_p_imsearch == B_IMODE_LMAP) curbuf->b_p_imsearch = B_IMODE_USE_INSERT; } if ((opt_flags & OPT_LOCAL) == 0) { set_iminsert_global(); set_imsearch_global(); } status_redraw_curbuf(); } } /* 'fileformat' */ else if (gvarp == &p_ff) { if (!MODIFIABLE(curbuf) && !(opt_flags & OPT_GLOBAL)) errmsg = e_modifiable; else if (check_opt_strings(*varp, p_ff_values, FALSE) != OK) errmsg = e_invarg; else { redraw_titles(); /* update flag in swap file */ ml_setflags(curbuf); /* Redraw needed when switching to/from "mac": a CR in the text * will be displayed differently. */ if (get_fileformat(curbuf) == EOL_MAC || *oldval == 'm') redraw_curbuf_later(NOT_VALID); } } /* 'fileformats' */ else if (varp == &p_ffs) { if (check_opt_strings(p_ffs, p_ff_values, TRUE) != OK) { errmsg = e_invarg; } } /* 'matchpairs' */ else if (gvarp == &p_mps) { if (has_mbyte) { for (p = *varp; *p != NUL; ++p) { int x2 = -1; int x3 = -1; if (*p != NUL) p += mb_ptr2len(p); if (*p != NUL) x2 = *p++; if (*p != NUL) { x3 = mb_ptr2char(p); p += mb_ptr2len(p); } if (x2 != ':' || x3 == -1 || (*p != NUL && *p != ',')) { errmsg = e_invarg; break; } if (*p == NUL) break; } } else { /* Check for "x:y,x:y" */ for (p = *varp; *p != NUL; p += 4) { if (p[1] != ':' || p[2] == NUL || (p[3] != NUL && p[3] != ',')) { errmsg = e_invarg; break; } if (p[3] == NUL) break; } } } /* 'comments' */ else if (gvarp == &p_com) { for (s = *varp; *s; ) { while (*s && *s != ':') { if (vim_strchr((char_u *)COM_ALL, *s) == NULL && !ascii_isdigit(*s) && *s != '-') { errmsg = illegal_char(errbuf, *s); break; } ++s; } if (*s++ == NUL) errmsg = (char_u *)N_("E524: Missing colon"); else if (*s == ',' || *s == NUL) errmsg = (char_u *)N_("E525: Zero length string"); if (errmsg != NULL) break; while (*s && *s != ',') { if (*s == '\\' && s[1] != NUL) ++s; ++s; } s = skip_to_option_part(s); } } /* 'listchars' */ else if (varp == &p_lcs) { errmsg = set_chars_option(varp); } /* 'fillchars' */ else if (varp == &p_fcs) { errmsg = set_chars_option(varp); } /* 'cedit' */ else if (varp == &p_cedit) { errmsg = check_cedit(); } /* 'verbosefile' */ else if (varp == &p_vfile) { verbose_stop(); if (*p_vfile != NUL && verbose_open() == FAIL) errmsg = e_invarg; /* 'shada' */ } else if (varp == &p_shada) { // TODO(ZyX-I): Remove this code in the future, alongside with &viminfo // option. opt_idx = ((options[opt_idx].fullname[0] == 'v') ? (shada_idx == -1 ? ((shada_idx = findoption((char_u *) "shada"))) : shada_idx) : opt_idx); for (s = p_shada; *s; ) { /* Check it's a valid character */ if (vim_strchr((char_u *)"!\"%'/:<@cfhnrs", *s) == NULL) { errmsg = illegal_char(errbuf, *s); break; } if (*s == 'n') { /* name is always last one */ break; } else if (*s == 'r') { /* skip until next ',' */ while (*++s && *s != ',') ; } else if (*s == '%') { /* optional number */ while (ascii_isdigit(*++s)) ; } else if (*s == '!' || *s == 'h' || *s == 'c') ++s; /* no extra chars */ else { /* must have a number */ while (ascii_isdigit(*++s)) ; if (!ascii_isdigit(*(s - 1))) { if (errbuf != NULL) { sprintf((char *)errbuf, _("E526: Missing number after <%s>"), transchar_byte(*(s - 1))); errmsg = errbuf; } else errmsg = (char_u *)""; break; } } if (*s == ',') ++s; else if (*s) { if (errbuf != NULL) errmsg = (char_u *)N_("E527: Missing comma"); else errmsg = (char_u *)""; break; } } if (*p_shada && errmsg == NULL && get_shada_parameter('\'') < 0) errmsg = (char_u *)N_("E528: Must specify a ' value"); } /* 'showbreak' */ else if (varp == &p_sbr) { for (s = p_sbr; *s; ) { if (ptr2cells(s) != 1) errmsg = (char_u *)N_("E595: contains unprintable or wide character"); mb_ptr_adv(s); } } /* 'guicursor' */ else if (varp == &p_guicursor) errmsg = parse_shape_opt(SHAPE_CURSOR); else if (varp == &p_popt) errmsg = parse_printoptions(); else if (varp == &p_pmfn) errmsg = parse_printmbfont(); /* 'langmap' */ else if (varp == &p_langmap) langmap_set(); /* 'breakat' */ else if (varp == &p_breakat) fill_breakat_flags(); /* 'titlestring' and 'iconstring' */ else if (varp == &p_titlestring || varp == &p_iconstring) { int flagval = (varp == &p_titlestring) ? STL_IN_TITLE : STL_IN_ICON; /* NULL => statusline syntax */ if (vim_strchr(*varp, '%') && check_stl_option(*varp) == NULL) stl_syntax |= flagval; else stl_syntax &= ~flagval; did_set_title(varp == &p_iconstring); } /* 'selection' */ else if (varp == &p_sel) { if (*p_sel == NUL || check_opt_strings(p_sel, p_sel_values, FALSE) != OK) errmsg = e_invarg; } /* 'selectmode' */ else if (varp == &p_slm) { if (check_opt_strings(p_slm, p_slm_values, TRUE) != OK) errmsg = e_invarg; } /* 'keymodel' */ else if (varp == &p_km) { if (check_opt_strings(p_km, p_km_values, TRUE) != OK) errmsg = e_invarg; else { km_stopsel = (vim_strchr(p_km, 'o') != NULL); km_startsel = (vim_strchr(p_km, 'a') != NULL); } } /* 'mousemodel' */ else if (varp == &p_mousem) { if (check_opt_strings(p_mousem, p_mousem_values, FALSE) != OK) errmsg = e_invarg; } else if (varp == &p_swb) { // 'switchbuf' if (opt_strings_flags(p_swb, p_swb_values, &swb_flags, true) != OK) errmsg = e_invarg; } /* 'debug' */ else if (varp == &p_debug) { if (check_opt_strings(p_debug, p_debug_values, TRUE) != OK) errmsg = e_invarg; } else if (varp == &p_dy) { // 'display' if (opt_strings_flags(p_dy, p_dy_values, &dy_flags, true) != OK) errmsg = e_invarg; else (void)init_chartab(); } /* 'eadirection' */ else if (varp == &p_ead) { if (check_opt_strings(p_ead, p_ead_values, FALSE) != OK) errmsg = e_invarg; } else if (varp == &p_cb) { // 'clipboard' if (opt_strings_flags(p_cb, p_cb_values, &cb_flags, true) != OK) { errmsg = e_invarg; } } else if (varp == &(curwin->w_s->b_p_spl) // 'spell' || varp == &(curwin->w_s->b_p_spf)) { // When 'spelllang' or 'spellfile' is set and there is a window for this // buffer in which 'spell' is set load the wordlists. errmsg = did_set_spell_option(varp == &(curwin->w_s->b_p_spf)); } /* When 'spellcapcheck' is set compile the regexp program. */ else if (varp == &(curwin->w_s->b_p_spc)) { errmsg = compile_cap_prog(curwin->w_s); } /* 'spellsuggest' */ else if (varp == &p_sps) { if (spell_check_sps() != OK) errmsg = e_invarg; } /* 'mkspellmem' */ else if (varp == &p_msm) { if (spell_check_msm() != OK) errmsg = e_invarg; } /* When 'bufhidden' is set, check for valid value. */ else if (gvarp == &p_bh) { if (check_opt_strings(curbuf->b_p_bh, p_bufhidden_values, FALSE) != OK) errmsg = e_invarg; } /* When 'buftype' is set, check for valid value. */ else if (gvarp == &p_bt) { if ((curbuf->terminal && curbuf->b_p_bt[0] != 't') || (!curbuf->terminal && curbuf->b_p_bt[0] == 't') || check_opt_strings(curbuf->b_p_bt, p_buftype_values, FALSE) != OK) { errmsg = e_invarg; } else { if (curwin->w_status_height) { curwin->w_redr_status = TRUE; redraw_later(VALID); } curbuf->b_help = (curbuf->b_p_bt[0] == 'h'); redraw_titles(); } } /* 'statusline' or 'rulerformat' */ else if (gvarp == &p_stl || varp == &p_ruf) { int wid; if (varp == &p_ruf) /* reset ru_wid first */ ru_wid = 0; s = *varp; if (varp == &p_ruf && *s == '%') { /* set ru_wid if 'ruf' starts with "%99(" */ if (*++s == '-') /* ignore a '-' */ s++; wid = getdigits_int(&s); if (wid && *s == '(' && (errmsg = check_stl_option(p_ruf)) == NULL) ru_wid = wid; else errmsg = check_stl_option(p_ruf); } /* check 'statusline' only if it doesn't start with "%!" */ else if (varp == &p_ruf || s[0] != '%' || s[1] != '!') errmsg = check_stl_option(s); if (varp == &p_ruf && errmsg == NULL) comp_col(); } /* check if it is a valid value for 'complete' -- Acevedo */ else if (gvarp == &p_cpt) { for (s = *varp; *s; ) { while (*s == ',' || *s == ' ') s++; if (!*s) break; if (vim_strchr((char_u *)".wbuksid]tU", *s) == NULL) { errmsg = illegal_char(errbuf, *s); break; } if (*++s != NUL && *s != ',' && *s != ' ') { if (s[-1] == 'k' || s[-1] == 's') { /* skip optional filename after 'k' and 's' */ while (*s && *s != ',' && *s != ' ') { if (*s == '\\') ++s; ++s; } } else { if (errbuf != NULL) { sprintf((char *)errbuf, _("E535: Illegal character after <%c>"), *--s); errmsg = errbuf; } else errmsg = (char_u *)""; break; } } } } /* 'completeopt' */ else if (varp == &p_cot) { if (check_opt_strings(p_cot, p_cot_values, true) != OK) { errmsg = e_invarg; } else { completeopt_was_set(); } } /* 'pastetoggle': translate key codes like in a mapping */ else if (varp == &p_pt) { if (*p_pt) { (void)replace_termcodes(p_pt, STRLEN(p_pt), &p, true, true, false, CPO_TO_CPO_FLAGS); if (p != NULL) { if (new_value_alloced) free_string_option(p_pt); p_pt = p; new_value_alloced = TRUE; } } } /* 'backspace' */ else if (varp == &p_bs) { if (ascii_isdigit(*p_bs)) { if (*p_bs >'2' || p_bs[1] != NUL) errmsg = e_invarg; } else if (check_opt_strings(p_bs, p_bs_values, TRUE) != OK) errmsg = e_invarg; } else if (varp == &p_bo) { if (opt_strings_flags(p_bo, p_bo_values, &bo_flags, true) != OK) { errmsg = e_invarg; } } else if (gvarp == &p_tc) { // 'tagcase' unsigned int *flags; if (opt_flags & OPT_LOCAL) { p = curbuf->b_p_tc; flags = &curbuf->b_tc_flags; } else { p = p_tc; flags = &tc_flags; } if ((opt_flags & OPT_LOCAL) && *p == NUL) { // make the local value empty: use the global value *flags = 0; } else if (*p == NUL || opt_strings_flags(p, p_tc_values, flags, false) != OK) { errmsg = e_invarg; } } else if (varp == &p_cmp) { // 'casemap' if (opt_strings_flags(p_cmp, p_cmp_values, &cmp_flags, true) != OK) errmsg = e_invarg; } /* 'diffopt' */ else if (varp == &p_dip) { if (diffopt_changed() == FAIL) errmsg = e_invarg; } /* 'foldmethod' */ else if (gvarp == &curwin->w_allbuf_opt.wo_fdm) { if (check_opt_strings(*varp, p_fdm_values, FALSE) != OK || *curwin->w_p_fdm == NUL) errmsg = e_invarg; else { foldUpdateAll(curwin); if (foldmethodIsDiff(curwin)) newFoldLevel(); } } /* 'foldexpr' */ else if (varp == &curwin->w_p_fde) { if (foldmethodIsExpr(curwin)) foldUpdateAll(curwin); } /* 'foldmarker' */ else if (gvarp == &curwin->w_allbuf_opt.wo_fmr) { p = vim_strchr(*varp, ','); if (p == NULL) errmsg = (char_u *)N_("E536: comma required"); else if (p == *varp || p[1] == NUL) errmsg = e_invarg; else if (foldmethodIsMarker(curwin)) foldUpdateAll(curwin); } /* 'commentstring' */ else if (gvarp == &p_cms) { if (**varp != NUL && strstr((char *)*varp, "%s") == NULL) errmsg = (char_u *)N_( "E537: 'commentstring' must be empty or contain %s"); } else if (varp == &p_fdo) { // 'foldopen' if (opt_strings_flags(p_fdo, p_fdo_values, &fdo_flags, true) != OK) errmsg = e_invarg; } /* 'foldclose' */ else if (varp == &p_fcl) { if (check_opt_strings(p_fcl, p_fcl_values, TRUE) != OK) errmsg = e_invarg; } /* 'foldignore' */ else if (gvarp == &curwin->w_allbuf_opt.wo_fdi) { if (foldmethodIsIndent(curwin)) foldUpdateAll(curwin); } else if (varp == &p_ve) { // 'virtualedit' if (opt_strings_flags(p_ve, p_ve_values, &ve_flags, true) != OK) errmsg = e_invarg; else if (STRCMP(p_ve, oldval) != 0) { /* Recompute cursor position in case the new 've' setting * changes something. */ validate_virtcol(); coladvance(curwin->w_virtcol); } } else if (varp == &p_csqf) { if (p_csqf != NULL) { p = p_csqf; while (*p != NUL) { if (vim_strchr((char_u *)CSQF_CMDS, *p) == NULL || p[1] == NUL || vim_strchr((char_u *)CSQF_FLAGS, p[1]) == NULL || (p[2] != NUL && p[2] != ',')) { errmsg = e_invarg; break; } else if (p[2] == NUL) break; else p += 3; } } } /* 'cinoptions' */ else if (gvarp == &p_cino) { /* TODO: recognize errors */ parse_cino(curbuf); // inccommand } else if (varp == &p_icm) { if (check_opt_strings(p_icm, p_icm_values, false) != OK) { errmsg = e_invarg; } } else if (gvarp == &p_ft) { if (!valid_filetype(*varp)) { errmsg = e_invarg; } } else if (gvarp == &p_syn) { if (!valid_filetype(*varp)) { errmsg = e_invarg; } } else { // Options that are a list of flags. p = NULL; if (varp == &p_ww) p = (char_u *)WW_ALL; if (varp == &p_shm) p = (char_u *)SHM_ALL; else if (varp == &(p_cpo)) p = (char_u *)CPO_VI; else if (varp == &(curbuf->b_p_fo)) p = (char_u *)FO_ALL; else if (varp == &curwin->w_p_cocu) p = (char_u *)COCU_ALL; else if (varp == &p_mouse) { p = (char_u *)MOUSE_ALL; } if (p != NULL) { for (s = *varp; *s; ++s) if (vim_strchr(p, *s) == NULL) { errmsg = illegal_char(errbuf, *s); break; } } } /* * If error detected, restore the previous value. */ if (errmsg != NULL) { if (new_value_alloced) free_string_option(*varp); *varp = oldval; /* * When resetting some values, need to act on it. */ if (did_chartab) (void)init_chartab(); if (varp == &p_hl) (void)highlight_changed(); } else { /* Remember where the option was set. */ set_option_scriptID_idx(opt_idx, opt_flags, current_SID); /* * Free string options that are in allocated memory. * Use "free_oldval", because recursiveness may change the flags under * our fingers (esp. init_highlight()). */ if (free_oldval) free_string_option(oldval); if (new_value_alloced) options[opt_idx].flags |= P_ALLOCED; else options[opt_idx].flags &= ~P_ALLOCED; if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0 && ((int)options[opt_idx].indir & PV_BOTH)) { /* global option with local value set to use global value; free * the local value and make it empty */ p = get_varp_scope(&(options[opt_idx]), OPT_LOCAL); free_string_option(*(char_u **)p); *(char_u **)p = empty_option; } /* May set global value for local option. */ else if (!(opt_flags & OPT_LOCAL) && opt_flags != OPT_GLOBAL) set_string_option_global(opt_idx, varp); /* * Trigger the autocommand only after setting the flags. */ /* When 'syntax' is set, load the syntax of that name */ if (varp == &(curbuf->b_p_syn)) { apply_autocmds(EVENT_SYNTAX, curbuf->b_p_syn, curbuf->b_fname, TRUE, curbuf); } else if (varp == &(curbuf->b_p_ft)) { /* 'filetype' is set, trigger the FileType autocommand */ did_filetype = TRUE; apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname, TRUE, curbuf); } if (varp == &(curwin->w_s->b_p_spl)) { char_u fname[200]; char_u *q = curwin->w_s->b_p_spl; /* Skip the first name if it is "cjk". */ if (STRNCMP(q, "cjk,", 4) == 0) q += 4; /* * Source the spell/LANG.vim in 'runtimepath'. * They could set 'spellcapcheck' depending on the language. * Use the first name in 'spelllang' up to '_region' or * '.encoding'. */ for (p = q; *p != NUL; ++p) if (vim_strchr((char_u *)"_.,", *p) != NULL) break; vim_snprintf((char *)fname, sizeof(fname), "spell/%.*s.vim", (int)(p - q), q); source_runtime(fname, DIP_ALL); } } if (varp == &p_mouse) { if (*p_mouse == NUL) { ui_mouse_off(); } else { setmouse(); // in case 'mouse' changed } } if (curwin->w_curswant != MAXCOL && (options[opt_idx].flags & (P_CURSWANT | P_RALL)) != 0) curwin->w_set_curswant = TRUE; check_redraw(options[opt_idx].flags); return errmsg; }
209,905,660,793,532,500,000,000,000,000,000,000,000
None
null
[ "CWE-20" ]
CVE-2016-1248
vim before patch 8.0.0056 does not properly validate values for the 'filetype', 'syntax' and 'keymap' options, which may result in the execution of arbitrary code if a file with a specially crafted modeline is opened.
https://nvd.nist.gov/vuln/detail/CVE-2016-1248
217,177
monit
f12d0cdb42d4e74dffe1525d4062c815c48ac57a
https://bitbucket.org/tildeslash/monit
https://bitbucket.org/tildeslash/monit/commits/f12d0cdb42d4e74dffe1525d4062c815c48ac57a
Fixed: Buffer overrun vulnerability in URL decoding. Thanks to Zack Flack for report.
1
static char x2c(char *hex) { register char digit; digit = ((hex[0] >= 'A') ? ((hex[0] & 0xdf) - 'A')+10 : (hex[0] - '0')); digit *= 16; digit += (hex[1] >= 'A' ? ((hex[1] & 0xdf) - 'A')+10 : (hex[1] - '0')); return(digit); }
156,938,523,355,548,540,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2019-11455
A buffer over-read in Util_urlDecode in util.c in Tildeslash Monit before 5.25.3 allows a remote authenticated attacker to retrieve the contents of adjacent memory via manipulation of GET or POST parameters. The attacker can also cause a denial of service (application outage).
https://nvd.nist.gov/vuln/detail/CVE-2019-11455
517,462
monit
f12d0cdb42d4e74dffe1525d4062c815c48ac57a
https://bitbucket.org/tildeslash/monit
https://bitbucket.org/tildeslash/monit/commits/f12d0cdb42d4e74dffe1525d4062c815c48ac57a
Fixed: Buffer overrun vulnerability in URL decoding. Thanks to Zack Flack for report.
0
static char _x2c(char *hex) { register char digit; digit = ((hex[0] >= 'A') ? ((hex[0] & 0xdf) - 'A')+10 : (hex[0] - '0')); digit *= 16; digit += (hex[1] >= 'A' ? ((hex[1] & 0xdf) - 'A')+10 : (hex[1] - '0')); return(digit); }
204,361,104,051,965,230,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2019-11455
A buffer over-read in Util_urlDecode in util.c in Tildeslash Monit before 5.25.3 allows a remote authenticated attacker to retrieve the contents of adjacent memory via manipulation of GET or POST parameters. The attacker can also cause a denial of service (application outage).
https://nvd.nist.gov/vuln/detail/CVE-2019-11455
217,178
ChakraCore
402f3d967c0a905ec5b9ca9c240783d3f2c15724
https://github.com/Microsoft/ChakraCore
https://github.com/Microsoft/ChakraCore/commit/402f3d967c0a905ec5b9ca9c240783d3f2c15724
[CVE-2017-0028] Fix binding of 'async' identifier in the presence of async arrow function.
1
ParseNodePtr Parser::ParseTerm(BOOL fAllowCall, LPCOLESTR pNameHint, uint32 *pHintLength, uint32 *pShortNameOffset, _Inout_opt_ IdentToken* pToken /*= nullptr*/, bool fUnaryOrParen /*= false*/, _Out_opt_ BOOL* pfCanAssign /*= nullptr*/, _Inout_opt_ BOOL* pfLikelyPattern /*= nullptr*/, _Out_opt_ bool* pfIsDotOrIndex /*= nullptr*/, _Inout_opt_ charcount_t *plastRParen /*= nullptr*/) { ParseNodePtr pnode = nullptr; charcount_t ichMin = 0; size_t iecpMin = 0; size_t iuMin; IdentToken term; BOOL fInNew = FALSE; BOOL fCanAssign = TRUE; bool isAsyncExpr = false; bool isLambdaExpr = false; Assert(pToken == nullptr || pToken->tk == tkNone); // Must be empty initially if (this->IsBackgroundParser()) { PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackParseOneTerm); } else { PROBE_STACK(m_scriptContext, Js::Constants::MinStackParseOneTerm); } switch (m_token.tk) { case tkID: { PidRefStack *ref = nullptr; IdentPtr pid = m_token.GetIdentifier(m_phtbl); charcount_t ichLim = m_pscan->IchLimTok(); size_t iecpLim = m_pscan->IecpLimTok(); ichMin = m_pscan->IchMinTok(); iecpMin = m_pscan->IecpMinTok(); if (pid == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled()) { isAsyncExpr = true; } bool previousAwaitIsKeyword = m_pscan->SetAwaitIsKeyword(isAsyncExpr); m_pscan->Scan(); m_pscan->SetAwaitIsKeyword(previousAwaitIsKeyword); // We search for an Async expression (a function declaration or an async lambda expression) if (isAsyncExpr && !m_pscan->FHadNewLine()) { if (m_token.tk == tkFUNCTION) { goto LFunction; } else if (m_token.tk == tkID || m_token.tk == tkAWAIT) { isLambdaExpr = true; goto LFunction; } } // Don't push a reference if this is a single lambda parameter, because we'll reparse with // a correct function ID. if (m_token.tk != tkDArrow) { ref = this->PushPidRef(pid); } if (buildAST) { pnode = CreateNameNode(pid); pnode->ichMin = ichMin; pnode->ichLim = ichLim; pnode->sxPid.SetSymRef(ref); } else { // Remember the identifier start and end in case it turns out to be a statement label. term.tk = tkID; term.pid = pid; // Record the identifier for detection of eval term.ichMin = static_cast<charcount_t>(iecpMin); term.ichLim = static_cast<charcount_t>(iecpLim); } CheckArgumentsUse(pid, GetCurrentFunctionNode()); break; } case tkTHIS: if (buildAST) { pnode = CreateNodeWithScanner<knopThis>(); } fCanAssign = FALSE; m_pscan->Scan(); break; case tkLParen: { ichMin = m_pscan->IchMinTok(); iuMin = m_pscan->IecpMinTok(); m_pscan->Scan(); if (m_token.tk == tkRParen) { // Empty parens can only be legal as an empty parameter list to a lambda declaration. // We're in a lambda if the next token is =>. fAllowCall = FALSE; m_pscan->Scan(); // If the token after the right paren is not => or if there was a newline between () and => this is a syntax error if (!m_doingFastScan && (m_token.tk != tkDArrow || m_pscan->FHadNewLine())) { Error(ERRsyntax); } if (buildAST) { pnode = CreateNodeWithScanner<knopEmpty>(); } break; } // Advance the block ID here in case this parenthetical expression turns out to be a lambda parameter list. // That way the pid ref stacks will be created in their correct final form, and we can simply fix // up function ID's. uint saveNextBlockId = m_nextBlockId; uint saveCurrBlockId = GetCurrentBlock()->sxBlock.blockId; GetCurrentBlock()->sxBlock.blockId = m_nextBlockId++; this->m_parenDepth++; pnode = ParseExpr<buildAST>(koplNo, &fCanAssign, TRUE, FALSE, nullptr, nullptr /*nameLength*/, nullptr /*pShortNameOffset*/, &term, true, nullptr, plastRParen); this->m_parenDepth--; if (buildAST && plastRParen) { *plastRParen = m_pscan->IchLimTok(); } ChkCurTok(tkRParen, ERRnoRparen); GetCurrentBlock()->sxBlock.blockId = saveCurrBlockId; if (m_token.tk == tkDArrow) { // We're going to rewind and reinterpret the expression as a parameter list. // Put back the original next-block-ID so the existing pid ref stacks will be correct. m_nextBlockId = saveNextBlockId; } // Emit a deferred ... error if one was parsed. if (m_deferEllipsisError && m_token.tk != tkDArrow) { m_pscan->SeekTo(m_EllipsisErrLoc); Error(ERRInvalidSpreadUse); } else { m_deferEllipsisError = false; } break; } case tkIntCon: if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber()) { Error(ERRES5NoOctal); } if (buildAST) { pnode = CreateIntNodeWithScanner(m_token.GetLong()); } fCanAssign = FALSE; m_pscan->Scan(); break; case tkFltCon: if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber()) { Error(ERRES5NoOctal); } if (buildAST) { pnode = CreateNodeWithScanner<knopFlt>(); pnode->sxFlt.dbl = m_token.GetDouble(); pnode->sxFlt.maybeInt = m_token.GetDoubleMayBeInt(); } fCanAssign = FALSE; m_pscan->Scan(); break; case tkStrCon: if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber()) { Error(ERRES5NoOctal); } if (buildAST) { pnode = CreateStrNodeWithScanner(m_token.GetStr()); } else { // Subtract the string literal length from the total char count for the purpose // of deciding whether to defer parsing and byte code generation. this->ReduceDeferredScriptLength(m_pscan->IchLimTok() - m_pscan->IchMinTok()); } fCanAssign = FALSE; m_pscan->Scan(); break; case tkTRUE: if (buildAST) { pnode = CreateNodeWithScanner<knopTrue>(); } fCanAssign = FALSE; m_pscan->Scan(); break; case tkFALSE: if (buildAST) { pnode = CreateNodeWithScanner<knopFalse>(); } fCanAssign = FALSE; m_pscan->Scan(); break; case tkNULL: if (buildAST) { pnode = CreateNodeWithScanner<knopNull>(); } fCanAssign = FALSE; m_pscan->Scan(); break; case tkDiv: case tkAsgDiv: pnode = ParseRegExp<buildAST>(); fCanAssign = FALSE; m_pscan->Scan(); break; case tkNEW: { ichMin = m_pscan->IchMinTok(); m_pscan->Scan(); if (m_token.tk == tkDot && m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled()) { pnode = ParseMetaProperty<buildAST>(tkNEW, ichMin, &fCanAssign); m_pscan->Scan(); } else { ParseNodePtr pnodeExpr = ParseTerm<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset); if (buildAST) { pnode = CreateCallNode(knopNew, pnodeExpr, nullptr); pnode->ichMin = ichMin; } fInNew = TRUE; fCanAssign = FALSE; } break; } case tkLBrack: { ichMin = m_pscan->IchMinTok(); m_pscan->Scan(); pnode = ParseArrayLiteral<buildAST>(); if (buildAST) { pnode->ichMin = ichMin; pnode->ichLim = m_pscan->IchLimTok(); } if (this->m_arrayDepth == 0) { Assert(m_pscan->IchLimTok() - ichMin > m_funcInArray); this->ReduceDeferredScriptLength(m_pscan->IchLimTok() - ichMin - this->m_funcInArray); this->m_funcInArray = 0; this->m_funcInArrayDepth = 0; } ChkCurTok(tkRBrack, ERRnoRbrack); if (!IsES6DestructuringEnabled()) { fCanAssign = FALSE; } else if (pfLikelyPattern != nullptr && !IsPostFixOperators()) { *pfLikelyPattern = TRUE; } break; } case tkLCurly: { ichMin = m_pscan->IchMinTok(); m_pscan->ScanForcingPid(); ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(pNameHint, pHintLength); if (buildAST) { pnode = CreateUniNode(knopObject, pnodeMemberList); pnode->ichMin = ichMin; pnode->ichLim = m_pscan->IchLimTok(); } ChkCurTok(tkRCurly, ERRnoRcurly); if (!IsES6DestructuringEnabled()) { fCanAssign = FALSE; } else if (pfLikelyPattern != nullptr && !IsPostFixOperators()) { *pfLikelyPattern = TRUE; } break; } case tkFUNCTION: { LFunction : if (m_grfscr & fscrDeferredFncExpression) { // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the // first time we see it. // // Normally, deferred functions will be parsed in ParseStatement upon encountering the 'function' token. The first // token of the source code of the function may not a 'function' token though, so we still need to reset this flag // for the first function we parse. This can happen in compat modes, for instance, for a function expression enclosed // in parentheses, where the legacy behavior was to include the parentheses in the function's source code. m_grfscr &= ~fscrDeferredFncExpression; } ushort flags = fFncNoFlgs; if (isLambdaExpr) { flags |= fFncLambda; } if (isAsyncExpr) { flags |= fFncAsync; } pnode = ParseFncDecl<buildAST>(flags, pNameHint, false, true, fUnaryOrParen); if (isAsyncExpr) { pnode->sxFnc.cbMin = iecpMin; pnode->ichMin = ichMin; } fCanAssign = FALSE; break; } case tkCLASS: if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled()) { pnode = ParseClassDecl<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset); } else { goto LUnknown; } fCanAssign = FALSE; break; case tkStrTmplBasic: case tkStrTmplBegin: pnode = ParseStringTemplateDecl<buildAST>(nullptr); fCanAssign = FALSE; break; case tkSUPER: if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled()) { pnode = ParseSuper<buildAST>(pnode, !!fAllowCall); } else { goto LUnknown; } break; case tkCASE: { if (!m_doingFastScan) { goto LUnknown; } ParseNodePtr pnodeUnused; pnode = ParseCase<buildAST>(&pnodeUnused); break; } case tkELSE: if (!m_doingFastScan) { goto LUnknown; } m_pscan->Scan(); ParseStatement<buildAST>(); break; default: LUnknown : Error(ERRsyntax); break; } pnode = ParsePostfixOperators<buildAST>(pnode, fAllowCall, fInNew, isAsyncExpr, &fCanAssign, &term, pfIsDotOrIndex); // Pass back identifier if requested if (pToken && term.tk == tkID) { *pToken = term; } if (pfCanAssign) { *pfCanAssign = fCanAssign; } return pnode; }
274,209,213,099,014,600,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-0028
A remote code execution vulnerability exists when Microsoft scripting engine improperly accesses objects in memory. The vulnerability could corrupt memory in a way that enables an attacker to execute arbitrary code in the context of the current user. An attacker who successfully exploited the vulnerability could gain the same user rights as the current user, aka "Scripting Engine Memory Corruption Vulnerability."
https://nvd.nist.gov/vuln/detail/CVE-2017-0028
517,605
ChakraCore
402f3d967c0a905ec5b9ca9c240783d3f2c15724
https://github.com/Microsoft/ChakraCore
https://github.com/Microsoft/ChakraCore/commit/402f3d967c0a905ec5b9ca9c240783d3f2c15724
[CVE-2017-0028] Fix binding of 'async' identifier in the presence of async arrow function.
0
ParseNodePtr Parser::ParseTerm(BOOL fAllowCall, LPCOLESTR pNameHint, uint32 *pHintLength, uint32 *pShortNameOffset, _Inout_opt_ IdentToken* pToken /*= nullptr*/, bool fUnaryOrParen /*= false*/, _Out_opt_ BOOL* pfCanAssign /*= nullptr*/, _Inout_opt_ BOOL* pfLikelyPattern /*= nullptr*/, _Out_opt_ bool* pfIsDotOrIndex /*= nullptr*/, _Inout_opt_ charcount_t *plastRParen /*= nullptr*/) { ParseNodePtr pnode = nullptr; PidRefStack *savedTopAsyncRef = nullptr; charcount_t ichMin = 0; size_t iecpMin = 0; size_t iuMin; IdentToken term; BOOL fInNew = FALSE; BOOL fCanAssign = TRUE; bool isAsyncExpr = false; bool isLambdaExpr = false; Assert(pToken == nullptr || pToken->tk == tkNone); // Must be empty initially if (this->IsBackgroundParser()) { PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackParseOneTerm); } else { PROBE_STACK(m_scriptContext, Js::Constants::MinStackParseOneTerm); } switch (m_token.tk) { case tkID: { PidRefStack *ref = nullptr; IdentPtr pid = m_token.GetIdentifier(m_phtbl); charcount_t ichLim = m_pscan->IchLimTok(); size_t iecpLim = m_pscan->IecpLimTok(); ichMin = m_pscan->IchMinTok(); iecpMin = m_pscan->IecpMinTok(); if (pid == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled()) { isAsyncExpr = true; } bool previousAwaitIsKeyword = m_pscan->SetAwaitIsKeyword(isAsyncExpr); m_pscan->Scan(); m_pscan->SetAwaitIsKeyword(previousAwaitIsKeyword); // We search for an Async expression (a function declaration or an async lambda expression) if (isAsyncExpr && !m_pscan->FHadNewLine()) { if (m_token.tk == tkFUNCTION) { goto LFunction; } else if (m_token.tk == tkID || m_token.tk == tkAWAIT) { isLambdaExpr = true; goto LFunction; } else if (m_token.tk == tkLParen) { // This is potentially an async arrow function. Save the state of the async references // in case it needs to be restored. (Note that the case of a single parameter with no ()'s // is detected upstream and need not be handled here.) savedTopAsyncRef = pid->GetTopRef(); } } // Don't push a reference if this is a single lambda parameter, because we'll reparse with // a correct function ID. if (m_token.tk != tkDArrow) { ref = this->PushPidRef(pid); } if (buildAST) { pnode = CreateNameNode(pid); pnode->ichMin = ichMin; pnode->ichLim = ichLim; pnode->sxPid.SetSymRef(ref); } else { // Remember the identifier start and end in case it turns out to be a statement label. term.tk = tkID; term.pid = pid; // Record the identifier for detection of eval term.ichMin = static_cast<charcount_t>(iecpMin); term.ichLim = static_cast<charcount_t>(iecpLim); } CheckArgumentsUse(pid, GetCurrentFunctionNode()); break; } case tkTHIS: if (buildAST) { pnode = CreateNodeWithScanner<knopThis>(); } fCanAssign = FALSE; m_pscan->Scan(); break; case tkLParen: { ichMin = m_pscan->IchMinTok(); iuMin = m_pscan->IecpMinTok(); m_pscan->Scan(); if (m_token.tk == tkRParen) { // Empty parens can only be legal as an empty parameter list to a lambda declaration. // We're in a lambda if the next token is =>. fAllowCall = FALSE; m_pscan->Scan(); // If the token after the right paren is not => or if there was a newline between () and => this is a syntax error if (!m_doingFastScan && (m_token.tk != tkDArrow || m_pscan->FHadNewLine())) { Error(ERRsyntax); } if (buildAST) { pnode = CreateNodeWithScanner<knopEmpty>(); } break; } // Advance the block ID here in case this parenthetical expression turns out to be a lambda parameter list. // That way the pid ref stacks will be created in their correct final form, and we can simply fix // up function ID's. uint saveNextBlockId = m_nextBlockId; uint saveCurrBlockId = GetCurrentBlock()->sxBlock.blockId; GetCurrentBlock()->sxBlock.blockId = m_nextBlockId++; this->m_parenDepth++; pnode = ParseExpr<buildAST>(koplNo, &fCanAssign, TRUE, FALSE, nullptr, nullptr /*nameLength*/, nullptr /*pShortNameOffset*/, &term, true, nullptr, plastRParen); this->m_parenDepth--; if (buildAST && plastRParen) { *plastRParen = m_pscan->IchLimTok(); } ChkCurTok(tkRParen, ERRnoRparen); GetCurrentBlock()->sxBlock.blockId = saveCurrBlockId; if (m_token.tk == tkDArrow) { // We're going to rewind and reinterpret the expression as a parameter list. // Put back the original next-block-ID so the existing pid ref stacks will be correct. m_nextBlockId = saveNextBlockId; } // Emit a deferred ... error if one was parsed. if (m_deferEllipsisError && m_token.tk != tkDArrow) { m_pscan->SeekTo(m_EllipsisErrLoc); Error(ERRInvalidSpreadUse); } else { m_deferEllipsisError = false; } break; } case tkIntCon: if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber()) { Error(ERRES5NoOctal); } if (buildAST) { pnode = CreateIntNodeWithScanner(m_token.GetLong()); } fCanAssign = FALSE; m_pscan->Scan(); break; case tkFltCon: if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber()) { Error(ERRES5NoOctal); } if (buildAST) { pnode = CreateNodeWithScanner<knopFlt>(); pnode->sxFlt.dbl = m_token.GetDouble(); pnode->sxFlt.maybeInt = m_token.GetDoubleMayBeInt(); } fCanAssign = FALSE; m_pscan->Scan(); break; case tkStrCon: if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber()) { Error(ERRES5NoOctal); } if (buildAST) { pnode = CreateStrNodeWithScanner(m_token.GetStr()); } else { // Subtract the string literal length from the total char count for the purpose // of deciding whether to defer parsing and byte code generation. this->ReduceDeferredScriptLength(m_pscan->IchLimTok() - m_pscan->IchMinTok()); } fCanAssign = FALSE; m_pscan->Scan(); break; case tkTRUE: if (buildAST) { pnode = CreateNodeWithScanner<knopTrue>(); } fCanAssign = FALSE; m_pscan->Scan(); break; case tkFALSE: if (buildAST) { pnode = CreateNodeWithScanner<knopFalse>(); } fCanAssign = FALSE; m_pscan->Scan(); break; case tkNULL: if (buildAST) { pnode = CreateNodeWithScanner<knopNull>(); } fCanAssign = FALSE; m_pscan->Scan(); break; case tkDiv: case tkAsgDiv: pnode = ParseRegExp<buildAST>(); fCanAssign = FALSE; m_pscan->Scan(); break; case tkNEW: { ichMin = m_pscan->IchMinTok(); m_pscan->Scan(); if (m_token.tk == tkDot && m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled()) { pnode = ParseMetaProperty<buildAST>(tkNEW, ichMin, &fCanAssign); m_pscan->Scan(); } else { ParseNodePtr pnodeExpr = ParseTerm<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset); if (buildAST) { pnode = CreateCallNode(knopNew, pnodeExpr, nullptr); pnode->ichMin = ichMin; } fInNew = TRUE; fCanAssign = FALSE; } break; } case tkLBrack: { ichMin = m_pscan->IchMinTok(); m_pscan->Scan(); pnode = ParseArrayLiteral<buildAST>(); if (buildAST) { pnode->ichMin = ichMin; pnode->ichLim = m_pscan->IchLimTok(); } if (this->m_arrayDepth == 0) { Assert(m_pscan->IchLimTok() - ichMin > m_funcInArray); this->ReduceDeferredScriptLength(m_pscan->IchLimTok() - ichMin - this->m_funcInArray); this->m_funcInArray = 0; this->m_funcInArrayDepth = 0; } ChkCurTok(tkRBrack, ERRnoRbrack); if (!IsES6DestructuringEnabled()) { fCanAssign = FALSE; } else if (pfLikelyPattern != nullptr && !IsPostFixOperators()) { *pfLikelyPattern = TRUE; } break; } case tkLCurly: { ichMin = m_pscan->IchMinTok(); m_pscan->ScanForcingPid(); ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(pNameHint, pHintLength); if (buildAST) { pnode = CreateUniNode(knopObject, pnodeMemberList); pnode->ichMin = ichMin; pnode->ichLim = m_pscan->IchLimTok(); } ChkCurTok(tkRCurly, ERRnoRcurly); if (!IsES6DestructuringEnabled()) { fCanAssign = FALSE; } else if (pfLikelyPattern != nullptr && !IsPostFixOperators()) { *pfLikelyPattern = TRUE; } break; } case tkFUNCTION: { LFunction : if (m_grfscr & fscrDeferredFncExpression) { // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the // first time we see it. // // Normally, deferred functions will be parsed in ParseStatement upon encountering the 'function' token. The first // token of the source code of the function may not a 'function' token though, so we still need to reset this flag // for the first function we parse. This can happen in compat modes, for instance, for a function expression enclosed // in parentheses, where the legacy behavior was to include the parentheses in the function's source code. m_grfscr &= ~fscrDeferredFncExpression; } ushort flags = fFncNoFlgs; if (isLambdaExpr) { flags |= fFncLambda; } if (isAsyncExpr) { flags |= fFncAsync; } pnode = ParseFncDecl<buildAST>(flags, pNameHint, false, true, fUnaryOrParen); if (isAsyncExpr) { pnode->sxFnc.cbMin = iecpMin; pnode->ichMin = ichMin; } fCanAssign = FALSE; break; } case tkCLASS: if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled()) { pnode = ParseClassDecl<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset); } else { goto LUnknown; } fCanAssign = FALSE; break; case tkStrTmplBasic: case tkStrTmplBegin: pnode = ParseStringTemplateDecl<buildAST>(nullptr); fCanAssign = FALSE; break; case tkSUPER: if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled()) { pnode = ParseSuper<buildAST>(pnode, !!fAllowCall); } else { goto LUnknown; } break; case tkCASE: { if (!m_doingFastScan) { goto LUnknown; } ParseNodePtr pnodeUnused; pnode = ParseCase<buildAST>(&pnodeUnused); break; } case tkELSE: if (!m_doingFastScan) { goto LUnknown; } m_pscan->Scan(); ParseStatement<buildAST>(); break; default: LUnknown : Error(ERRsyntax); break; } pnode = ParsePostfixOperators<buildAST>(pnode, fAllowCall, fInNew, isAsyncExpr, &fCanAssign, &term, pfIsDotOrIndex); if (savedTopAsyncRef != nullptr && this->m_token.tk == tkDArrow) { // This is an async arrow function; we're going to back up and reparse it. // Make sure we don't leave behind a bogus reference to the 'async' identifier. for (IdentPtr pid = wellKnownPropertyPids.async; pid->GetTopRef() != savedTopAsyncRef;) { Assert(pid->GetTopRef() != nullptr); pid->RemovePrevPidRef(nullptr); } } // Pass back identifier if requested if (pToken && term.tk == tkID) { *pToken = term; } if (pfCanAssign) { *pfCanAssign = fCanAssign; } return pnode; }
313,369,564,772,743,500,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-0028
A remote code execution vulnerability exists when Microsoft scripting engine improperly accesses objects in memory. The vulnerability could corrupt memory in a way that enables an attacker to execute arbitrary code in the context of the current user. An attacker who successfully exploited the vulnerability could gain the same user rights as the current user, aka "Scripting Engine Memory Corruption Vulnerability."
https://nvd.nist.gov/vuln/detail/CVE-2017-0028
217,184
JPEGsnoop
b4e458612d4294e0cfe01dbf1c0b09a07a8133a4
https://github.com/ImpulseAdventure/JPEGsnoop
https://github.com/ImpulseAdventure/JPEGsnoop/commit/b4e458612d4294e0cfe01dbf1c0b09a07a8133a4#diff-cf9182aecc9d630e8db2e0e35f1eec65
Fixed div0 vulnerability in SampFact
1
unsigned CjfifDecode::DecodeMarker() { TCHAR acIdentifier[MAX_IDENTIFIER]; CString strTmp; CString strFull; // Used for concatenation unsigned nLength; // General purpose unsigned nTmpVal; unsigned nCode; unsigned long nPosEnd; unsigned long nPosSaved; // General-purpose saved position in file unsigned long nPosExifStart; unsigned nRet; // General purpose return value bool bRet; unsigned long nPosMarkerStart; // Offset for current marker unsigned nColTransform = 0; // Color Transform from APP14 marker // For DQT CString strDqtPrecision = _T(""); CString strDqtZigZagOrder = _T(""); if (Buf(m_nPos) != 0xFF) { if (m_nPos == 0) { // Don't give error message if we've already alerted them of AVI / PSD if ((!m_bAvi) && (!m_bPsd)) { strTmp.Format(_T("NOTE: File did not start with JPEG marker. Consider using [Tools->Img Search Fwd] to locate embedded JPEG.")); m_pLog->AddLineErr(strTmp); } } else { strTmp.Format(_T("ERROR: Expected marker 0xFF, got 0x%02X @ offset 0x%08X. Consider using [Tools->Img Search Fwd/Rev]."),Buf(m_nPos),m_nPos); m_pLog->AddLineErr(strTmp); } m_nPos++; return DECMARK_ERR; } m_nPos++; // Read the current marker code nCode = Buf(m_nPos++); // Handle Marker Padding // // According to Section B.1.1.2: // "Any marker may optionally be preceded by any number of fill bytes, which are bytes assigned code XFF." // unsigned nSkipMarkerPad = 0; while (nCode == 0xFF) { // Count the pad nSkipMarkerPad++; // Read another byte nCode = Buf(m_nPos++); } // Report out any padding if (nSkipMarkerPad>0) { strTmp.Format(_T("*** Skipped %u marker pad bytes ***"),nSkipMarkerPad); m_pLog->AddLineHdr(strTmp); } // Save the current marker offset nPosMarkerStart = m_nPos; AddHeader(nCode); switch (nCode) { case JFIF_SOI: // SOI m_bStateSoi = true; break; case JFIF_APP12: // Photoshop DUCKY (Save For Web) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); //nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(" Length = %u"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; m_nPos += 2; // Move past length now that we've used it _tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); acIdentifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case strTmp.Format(_T(" Identifier = [%s]"),acIdentifier); m_pLog->AddLine(strTmp); m_nPos += (unsigned)_tcslen(acIdentifier)+1; if (_tcscmp(acIdentifier,_T("Ducky")) != 0) { m_pLog->AddLine(_T(" Not Photoshop DUCKY. Skipping remainder.")); } else // Photoshop { // Please see reference on http://cpan.uwinnipeg.ca/htdocs/Image-ExifTool/Image/ExifTool/APP12.pm.html // A direct indexed approach should be safe m_nImgQualPhotoshopSfw = Buf(m_nPos+6); strTmp.Format(_T(" Photoshop Save For Web Quality = [%d]"),m_nImgQualPhotoshopSfw); m_pLog->AddLine(strTmp); } // Restore original position in file to a point // after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP14: // JPEG Adobe tag nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); strTmp.Format(_T(" Length = %u"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; // Some files had very short segment (eg. nLength=2) if (nLength < 2+12) { m_pLog->AddLine(_T(" Segment too short for Identifier. Skipping remainder.")); m_nPos = nPosSaved+nLength; break; } m_nPos += 2; // Move past length now that we've used it // TODO: Confirm Adobe flag m_nPos += 5; nTmpVal = Buf(m_nPos+0)*256 + Buf(m_nPos+1); strTmp.Format(_T(" DCTEncodeVersion = %u"),nTmpVal); m_pLog->AddLine(strTmp); nTmpVal = Buf(m_nPos+2)*256 + Buf(m_nPos+3); strTmp.Format(_T(" APP14Flags0 = %u"),nTmpVal); m_pLog->AddLine(strTmp); nTmpVal = Buf(m_nPos+4)*256 + Buf(m_nPos+5); strTmp.Format(_T(" APP14Flags1 = %u"),nTmpVal); m_pLog->AddLine(strTmp); nColTransform = Buf(m_nPos+6); switch (nColTransform) { case APP14_COLXFM_UNK_RGB: strTmp.Format(_T(" ColorTransform = %u [Unknown (RGB or CMYK)]"),nColTransform); break; case APP14_COLXFM_YCC: strTmp.Format(_T(" ColorTransform = %u [YCbCr]"),nColTransform); break; case APP14_COLXFM_YCCK: strTmp.Format(_T(" ColorTransform = %u [YCCK]"),nColTransform); break; default: strTmp.Format(_T(" ColorTransform = %u [???]"),nColTransform); break; } m_pLog->AddLine(strTmp); m_nApp14ColTransform = (nColTransform & 0xFF); // Restore original position in file to a point // after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP13: // Photoshop (Save As) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); //nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(" Length = %u"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; // Some files had very short segment (eg. nLength=2) if (nLength < 2+20) { m_pLog->AddLine(_T(" Segment too short for Identifier. Skipping remainder.")); m_nPos = nPosSaved+nLength; break; } m_nPos += 2; // Move past length now that we've used it _tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); acIdentifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case strTmp.Format(_T(" Identifier = [%s]"),acIdentifier); m_pLog->AddLine(strTmp); m_nPos += (unsigned)_tcslen(acIdentifier)+1; if (_tcscmp(acIdentifier,_T("Photoshop 3.0")) != 0) { m_pLog->AddLine(_T(" Not Photoshop. Skipping remainder.")); } else // Photoshop { DecodeApp13Ps(); } // Restore original position in file to a point // after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP1: nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); //nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(" Length = %u"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; m_nPos += 2; // Move past length now that we've used it _tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); acIdentifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case strTmp.Format(_T(" Identifier = [%s]"),acIdentifier); m_pLog->AddLine(strTmp); m_nPos += (unsigned)_tcslen(acIdentifier); if (!_tcsnccmp(acIdentifier,_T("http://ns.adobe.com/xap/1.0/\x00"),29) != 0) { // XMP m_pLog->AddLine(_T(" XMP = ")); m_nPos++; unsigned nPosMarkerEnd = nPosSaved+nLength-1; unsigned sXmpLen = nPosMarkerEnd-m_nPos; char cXmpChar; bool bNonSpace; CString strLine; // Reset state strLine = _T(" |"); bNonSpace = false; for (unsigned nInd=0;nInd<sXmpLen;nInd++) { // Get the next char cXmpChar = (char)m_pWBuf->Buf(m_nPos+nInd); // Detect a non-space in line if ((cXmpChar != 0x20) && (cXmpChar != 0x0A)) { bNonSpace = true; } // Detect Linefeed, print out line if (cXmpChar == 0x0A) { // Only print line if some non-space elements! if (bNonSpace) { m_pLog->AddLine(strLine); } // Reset state strLine = _T(" |"); bNonSpace = false; } else { // Add the char strLine.AppendChar(cXmpChar); } } } else if (!_tcscmp(acIdentifier,_T("Exif")) != 0) { // Only decode it further if it is EXIF format m_nPos += 2; // Skip two 00 bytes nPosExifStart = m_nPos; // Save m_nPos @ start of EXIF used for all IFD offsets // =========== EXIF TIFF Header (Start) =========== // - Defined in Exif 2.2 Standard (JEITA CP-3451) section 4.5.2 // - Contents (8 bytes total) // - Byte order (2 bytes) // - 0x002A (2 bytes) // - Offset of 0th IFD (4 bytes) unsigned char acIdentifierTiff[9]; strFull = _T(""); strTmp = _T(""); strFull = _T(" Identifier TIFF = "); for (unsigned int i=0;i<8;i++) { acIdentifierTiff[i] = (unsigned char)Buf(m_nPos++); } strTmp = PrintAsHexUC(acIdentifierTiff,8); strFull += strTmp; m_pLog->AddLine(strFull); switch (acIdentifierTiff[0]*256+acIdentifierTiff[1]) { case 0x4949: // "II" // Intel alignment m_nImgExifEndian = 0; m_pLog->AddLine(_T(" Endian = Intel (little)")); break; case 0x4D4D: // "MM" // Motorola alignment m_nImgExifEndian = 1; m_pLog->AddLine(_T(" Endian = Motorola (big)")); break; } // We expect the TAG mark of 0x002A (depending on endian mode) unsigned test_002a; test_002a = ByteSwap2(acIdentifierTiff[2],acIdentifierTiff[3]); strTmp.Format(_T(" TAG Mark x002A = 0x%04X"),test_002a); m_pLog->AddLine(strTmp); unsigned nIfdCount; // Current IFD # unsigned nOffsetIfd1; // Mark pointer to EXIF Sub IFD as 0 so that we can // detect if the tag never showed up. m_nImgExifSubIfdPtr = 0; m_nImgExifMakerPtr = 0; m_nImgExifGpsIfdPtr = 0; m_nImgExifInteropIfdPtr = 0; bool exif_done = FALSE; nOffsetIfd1 = ByteSwap4(acIdentifierTiff[4],acIdentifierTiff[5], acIdentifierTiff[6],acIdentifierTiff[7]); // =========== EXIF TIFF Header (End) =========== // =========== EXIF IFD 0 =========== // Do we start the 0th IFD for the "Primary Image Data"? // Even though the nOffsetIfd1 pointer should indicate to // us where the IFD should start (0x0008 if immediately after // EXIF TIFF Header), I have observed JPEG files that // do not contain the IFD. Therefore, we must check for this // condition by comparing against the APP marker length. // Example file: http://img9.imageshack.us/img9/194/90114543.jpg if ((nPosSaved + nLength) <= (nPosExifStart+nOffsetIfd1)) { // We've run out of space for any IFD, so cancel now exif_done = true; m_pLog->AddLine(_T(" NOTE: No IFD entries")); } nIfdCount = 0; while (!exif_done) { m_pLog->AddLine(_T("")); strTmp.Format(_T("IFD%u"),nIfdCount); // Process the IFD nRet = DecodeExifIfd(strTmp,nPosExifStart,nOffsetIfd1); // Now that we have gone through all entries in the IFD directory, // we read the offset to the next IFD nOffsetIfd1 = ByteSwap4(Buf(m_nPos+0),Buf(m_nPos+1),Buf(m_nPos+2),Buf(m_nPos+3)); m_nPos += 4; strTmp.Format(_T(" Offset to Next IFD = 0x%08X"),nOffsetIfd1); m_pLog->AddLine(strTmp); if (nRet != 0) { // Error condition (DecodeExifIfd returned error) nOffsetIfd1 = 0x00000000; } if (nOffsetIfd1 == 0x00000000) { // Either error condition or truly end of IFDs exif_done = TRUE; } else { nIfdCount++; } } // while ! exif_done // If EXIF SubIFD was defined, then handle it now if (m_nImgExifSubIfdPtr != 0) { m_pLog->AddLine(_T("")); DecodeExifIfd(_T("SubIFD"),nPosExifStart,m_nImgExifSubIfdPtr); } if (m_nImgExifMakerPtr != 0) { m_pLog->AddLine(_T("")); DecodeExifIfd(_T("MakerIFD"),nPosExifStart,m_nImgExifMakerPtr); } if (m_nImgExifGpsIfdPtr != 0) { m_pLog->AddLine(_T("")); DecodeExifIfd(_T("GPSIFD"),nPosExifStart,m_nImgExifGpsIfdPtr); } if (m_nImgExifInteropIfdPtr != 0) { m_pLog->AddLine(_T("")); DecodeExifIfd(_T("InteropIFD"),nPosExifStart,m_nImgExifInteropIfdPtr); } } else { strTmp.Format(_T("Identifier [%s] not supported. Skipping remainder."),(LPCTSTR)acIdentifier); m_pLog->AddLine(strTmp); } ////////// // Dump out Makernote area // TODO: Disabled for now #if 0 unsigned ptr_base; if (m_bVerbose) { if (m_nImgExifMakerPtr != 0) { // FIXME: Seems that nPosExifStart is not initialized in VERBOSE mode ptr_base = nPosExifStart+m_nImgExifMakerPtr; m_pLog->AddLine(_T("Exif Maker IFD DUMP")); strFull.Format(_T(" MarkerOffset @ 0x%08X"),ptr_base); m_pLog->AddLine(strFull); } } #endif // End of dump out makernote area // Restore file position m_nPos = nPosSaved; // Restore original position in file to a point // after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP2: // Typically used for Flashpix and possibly ICC profiles // Photoshop (Save As) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); //nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(" Length = %u"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; m_nPos += 2; // Move past length now that we've used it _tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); acIdentifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case strTmp.Format(_T(" Identifier = [%s]"),acIdentifier); m_pLog->AddLine(strTmp); m_nPos += (unsigned)_tcslen(acIdentifier)+1; if (_tcscmp(acIdentifier,_T("FPXR")) == 0) { // Photoshop m_pLog->AddLine(_T(" FlashPix:")); DecodeApp2Flashpix(); } else if (_tcscmp(acIdentifier,_T("ICC_PROFILE")) == 0) { // ICC Profile m_pLog->AddLine(_T(" ICC Profile:")); DecodeApp2IccProfile(nLength); } else { m_pLog->AddLine(_T(" Not supported. Skipping remainder.")); } // Restore original position in file to a point // after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP3: case JFIF_APP4: case JFIF_APP5: case JFIF_APP6: case JFIF_APP7: case JFIF_APP8: case JFIF_APP9: case JFIF_APP10: case JFIF_APP11: //case JFIF_APP12: // Handled separately //case JFIF_APP13: // Handled separately //case JFIF_APP14: // Handled separately case JFIF_APP15: nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); //nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(" Length = %u"),nLength); m_pLog->AddLine(strTmp); if (m_bVerbose) { strFull = _T(""); for (unsigned int i=0;i<nLength;i++) { // Start a new line for every 16 codes if ((i % 16) == 0) { strFull.Format(_T(" MarkerOffset [%04X]: "),i); } else if ((i % 8) == 0) { strFull += _T(" "); } nTmpVal = Buf(m_nPos+i); strTmp.Format(_T("%02X "),nTmpVal); strFull += strTmp; if ((i%16) == 15) { m_pLog->AddLine(strFull); strFull = _T(""); } } m_pLog->AddLine(strFull); strFull = _T(""); for (unsigned int i=0;i<nLength;i++) { // Start a new line for every 16 codes if ((i % 32) == 0) { strFull.Format(_T(" MarkerOffset [%04X]: "),i); } else if ((i % 8) == 0) { strFull += _T(" "); } nTmpVal = Buf(m_nPos+i); if (_istprint(nTmpVal)) { strTmp.Format(_T("%c"),nTmpVal); strFull += strTmp; } else { strFull += _T("."); } if ((i%32)==31) { m_pLog->AddLine(strFull); } } m_pLog->AddLine(strFull); } // nVerbose m_nPos += nLength; break; case JFIF_APP0: // APP0 nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); //nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); m_nPos+=2; strTmp.Format(_T(" Length = %u"),nLength); m_pLog->AddLine(strTmp); _tcscpy_s(m_acApp0Identifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); m_acApp0Identifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case strTmp.Format(_T(" Identifier = [%s]"),m_acApp0Identifier); m_pLog->AddLine(strTmp); if (!_tcscmp(m_acApp0Identifier,_T("JFIF"))) { // Only process remainder if it is JFIF. This marker // is also used for application-specific functions. m_nPos += (unsigned)(_tcslen(m_acApp0Identifier)+1); m_nImgVersionMajor = Buf(m_nPos++); m_nImgVersionMinor = Buf(m_nPos++); strTmp.Format(_T(" version = [%u.%u]"),m_nImgVersionMajor,m_nImgVersionMinor); m_pLog->AddLine(strTmp); m_nImgUnits = Buf(m_nPos++); m_nImgDensityX = Buf(m_nPos)*256 + Buf(m_nPos+1); //m_nImgDensityX = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); m_nPos+=2; m_nImgDensityY = Buf(m_nPos)*256 + Buf(m_nPos+1); //m_nImgDensityY = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); m_nPos+=2; strTmp.Format(_T(" density = %u x %u "),m_nImgDensityX,m_nImgDensityY); strFull = strTmp; switch (m_nImgUnits) { case 0: strFull += _T("(aspect ratio)"); m_pLog->AddLine(strFull); break; case 1: strFull += _T("DPI (dots per inch)"); m_pLog->AddLine(strFull); break; case 2: strFull += _T("DPcm (dots per cm)"); m_pLog->AddLine(strFull); break; default: strTmp.Format(_T("ERROR: Unknown ImgUnits parameter [%u]"),m_nImgUnits); strFull += strTmp; m_pLog->AddLineWarn(strFull); //return DECMARK_ERR; break; } m_nImgThumbSizeX = Buf(m_nPos++); m_nImgThumbSizeY = Buf(m_nPos++); strTmp.Format(_T(" thumbnail = %u x %u"),m_nImgThumbSizeX,m_nImgThumbSizeY); m_pLog->AddLine(strTmp); // Unpack the thumbnail: unsigned thumbnail_r,thumbnail_g,thumbnail_b; if (m_nImgThumbSizeX && m_nImgThumbSizeY) { for (unsigned y=0;y<m_nImgThumbSizeY;y++) { strFull.Format(_T(" Thumb[%03u] = "),y); for (unsigned x=0;x<m_nImgThumbSizeX;x++) { thumbnail_r = Buf(m_nPos++); thumbnail_g = Buf(m_nPos++); thumbnail_b = Buf(m_nPos++); strTmp.Format(_T("(0x%02X,0x%02X,0x%02X) "),thumbnail_r,thumbnail_g,thumbnail_b); strFull += strTmp; m_pLog->AddLine(strFull); } } } // TODO: // - In JPEG-B mode (GeoRaster), we will need to fake out // the DHT & DQT tables here. Unfortunately, we'll have to // rely on the user to put us into this mode as there is nothing // in the file that specifies this mode. /* // TODO: Need to ensure that Faked DHT is correct table AddHeader(JFIF_DHT_FAKE); DecodeDHT(true); // Need to mark DHT tables as OK m_bStateDht = true; m_bStateDhtFake = true; m_bStateDhtOk = true; // ... same for DQT */ } else if (!_tcsnccmp(m_acApp0Identifier,_T("AVI1"),4)) { // AVI MJPEG type // Need to fill in predefined DHT table from spec: // OpenDML file format for AVI, section "Proposed Data Chunk Format" // Described in MMREG.H m_pLog->AddLine(_T(" Detected MotionJPEG")); m_pLog->AddLine(_T(" Importing standard Huffman table...")); m_pLog->AddLine(_T("")); AddHeader(JFIF_DHT_FAKE); DecodeDHT(true); // Need to mark DHT tables as OK m_bStateDht = true; m_bStateDhtFake = true; m_bStateDhtOk = true; m_nPos += nLength-2; // Skip over, and undo length short read } else { // Not JFIF or AVI1 m_pLog->AddLine(_T(" Not known APP0 type. Skipping remainder.")); m_nPos += nLength-2; } if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_DQT: // Define quantization tables m_bStateDqt = true; unsigned nDqtPrecision_Pq; unsigned nDqtQuantDestId_Tq; nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Lq nPosEnd = m_nPos+nLength; m_nPos+=2; //XXX strTmp.Format(_T(" Table length <Lq> = %u"),nLength); strTmp.Format(_T(" Table length = %u"),nLength); m_pLog->AddLine(strTmp); while (nPosEnd > m_nPos) { strTmp.Format(_T(" ----")); m_pLog->AddLine(strTmp); nTmpVal = Buf(m_nPos++); // Pq | Tq nDqtPrecision_Pq = (nTmpVal & 0xF0) >> 4; // Pq, range 0-1 nDqtQuantDestId_Tq = nTmpVal & 0x0F; // Tq, range 0-3 // Decode per ITU-T.81 standard #if 1 if (nDqtPrecision_Pq == 0) { strDqtPrecision = _T("8 bits"); } else if (nDqtPrecision_Pq == 1) { strDqtPrecision = _T("16 bits"); } else { strTmp.Format(_T(" Unsupported precision value [%u]"),nDqtPrecision_Pq); m_pLog->AddLineWarn(strTmp); strDqtPrecision = _T("???"); // FIXME: Consider terminating marker parsing early } if (!ValidateValue(nDqtPrecision_Pq,0,1,_T("DQT Precision <Pq>"),true,0)) return DECMARK_ERR; if (!ValidateValue(nDqtQuantDestId_Tq,0,3,_T("DQT Destination ID <Tq>"),true,0)) return DECMARK_ERR; strTmp.Format(_T(" Precision=%s"),(LPCTSTR)strDqtPrecision); m_pLog->AddLine(strTmp); #else // Decode with additional DQT extension (ITU-T-JPEG-Plus-Proposal_R3.doc) if ((nDqtPrecision_Pq & 0xE) == 0) { // Per ITU-T.81 Standard if (nDqtPrecision_Pq == 0) { strDqtPrecision = _T("8 bits"); } else if (nDqtPrecision_Pq == 1) { strDqtPrecision = _T("16 bits"); } strTmp.Format(_T(" Precision=%s"),strDqtPrecision); m_pLog->AddLine(strTmp); } else { // Non-standard // JPEG-Plus-Proposal-R3: // - Alternative sub-block-wise sequence strTmp.Format(_T(" Non-Standard DQT Extension detected")); m_pLog->AddLineWarn(strTmp); // FIXME: Should prevent attempt to decode until this is implemented if (nDqtPrecision_Pq == 0) { strDqtPrecision = _T("8 bits"); } else if (nDqtPrecision_Pq == 1) { strDqtPrecision = _T("16 bits"); } strTmp.Format(_T(" Precision=%s"),strDqtPrecision); m_pLog->AddLine(strTmp); if ((nDqtPrecision_Pq & 0x2) == 0) { strDqtZigZagOrder = _T("Diagonal zig-zag coeff scan seqeunce"); } else if ((nDqtPrecision_Pq & 0x2) == 1) { strDqtZigZagOrder = _T("Alternate coeff scan seqeunce"); } strTmp.Format(_T(" Coeff Scan Sequence=%s"),strDqtZigZagOrder); m_pLog->AddLine(strTmp); if ((nDqtPrecision_Pq & 0x4) == 1) { strTmp.Format(_T(" Custom coeff scan sequence")); m_pLog->AddLine(strTmp); // Now expect sequence of 64 coefficient entries CString strSequence = _T(""); for (unsigned nInd=0;nInd<64;nInd++) { nTmpVal = Buf(m_nPos++); strTmp.Format(_T("%u"),nTmpVal); strSequence += strTmp; if (nInd!=63) { strSequence += _T(", "); } } strTmp.Format(_T(" Custom sequence = [ %s ]"),strSequence); m_pLog->AddLine(strTmp); } } #endif strTmp.Format(_T(" Destination ID=%u"),nDqtQuantDestId_Tq); if (nDqtQuantDestId_Tq == 0) { strTmp += _T(" (Luminance)"); } else if (nDqtQuantDestId_Tq == 1) { strTmp += _T(" (Chrominance)"); } else if (nDqtQuantDestId_Tq == 2) { strTmp += _T(" (Chrominance)"); } else { strTmp += _T(" (???)"); } m_pLog->AddLine(strTmp); // FIXME: The following is somewhat superseded by ValidateValue() above // with the exception of skipping remainder if (nDqtQuantDestId_Tq >= MAX_DQT_DEST_ID) { strTmp.Format(_T("ERROR: Destination ID <Tq> = %u, >= %u"),nDqtQuantDestId_Tq,MAX_DQT_DEST_ID); m_pLog->AddLineErr(strTmp); if (!m_pAppConfig->bRelaxedParsing) { m_pLog->AddLineErr(_T(" Stopping decode")); return DECMARK_ERR; } else { // Now skip remainder of DQT // FIXME strTmp.Format(_T(" Skipping remainder of marker [%u bytes]"),nPosMarkerStart + nLength - m_nPos); m_pLog->AddLineWarn(strTmp); m_pLog->AddLine(_T("")); m_nPos = nPosMarkerStart + nLength; return DECMARK_OK; } } bool bQuantAllOnes = true; double dComparePercent; double dSumPercent=0; double dSumPercentSqr=0; for (unsigned nCoeffInd=0;nCoeffInd<MAX_DQT_COEFF;nCoeffInd++) { nTmpVal = Buf(m_nPos++); if (nDqtPrecision_Pq == 1) { // 16-bit DQT entries! nTmpVal <<= 8; nTmpVal += Buf(m_nPos++); } m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]] = nTmpVal; /* scaling factor in percent */ // Now calculate the comparison with the Annex sample // FIXME: Should probably use check for landscape orientation and // rotate comparison matrix accordingly if (nDqtQuantDestId_Tq == 0) { if (m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]] != 0) { m_afStdQuantLumCompare[glb_anZigZag[nCoeffInd]] = (float)(glb_anStdQuantLum[glb_anZigZag[nCoeffInd]]) / (float)(m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]]); dComparePercent = 100.0 * (double)(m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]]) / (double)(glb_anStdQuantLum[glb_anZigZag[nCoeffInd]]); } else { m_afStdQuantLumCompare[glb_anZigZag[nCoeffInd]] = (float)999.99; dComparePercent = 999.99; } } else { if (m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]] != 0) { m_afStdQuantChrCompare[glb_anZigZag[nCoeffInd]] = (float)(glb_anStdQuantChr[glb_anZigZag[nCoeffInd]]) / (float)(m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]]); dComparePercent = 100.0 * (double)(m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]]) / (double)(glb_anStdQuantChr[glb_anZigZag[nCoeffInd]]); } else { m_afStdQuantChrCompare[glb_anZigZag[nCoeffInd]] = (float)999.99; } } dSumPercent += dComparePercent; dSumPercentSqr += dComparePercent * dComparePercent; // Check just in case entire table are ones (Quality 100) if (m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]] != 1) bQuantAllOnes = 0; } // 0..63 // Note that the DQT table that we are saving is already // after doing zigzag reordering: // From high freq -> low freq // To X,Y, left-to-right, top-to-bottom // Flag this DQT table as being set! m_abImgDqtSet[nDqtQuantDestId_Tq] = true; unsigned nCoeffInd; // Now display the table for (unsigned nDqtY=0;nDqtY<8;nDqtY++) { strFull.Format(_T(" DQT, Row #%u: "),nDqtY); for (unsigned nDqtX=0;nDqtX<8;nDqtX++) { nCoeffInd = nDqtY*8+nDqtX; strTmp.Format(_T("%3u "),m_anImgDqtTbl[nDqtQuantDestId_Tq][nCoeffInd]); strFull += strTmp; // Store the DQT entry into the Image Decoder bRet = m_pImgDec->SetDqtEntry(nDqtQuantDestId_Tq,nCoeffInd,glb_anUnZigZag[nCoeffInd], m_anImgDqtTbl[nDqtQuantDestId_Tq][nCoeffInd]); DecodeErrCheck(bRet); } // Now add the compare with Annex K // Decided to disable this as it was confusing users /* strFull += _T(" AnnexRatio: <"); for (unsigned nDqtX=0;nDqtX<8;nDqtX++) { nCoeffInd = nDqtY*8+nDqtX; if (nDqtQuantDestId_Tq == 0) { strTmp.Format(_T("%5.1f "),m_afStdQuantLumCompare[nCoeffInd]); } else { strTmp.Format(_T("%5.1f "),m_afStdQuantChrCompare[nCoeffInd]); } strFull += strTmp; } strFull += _T(">"); */ m_pLog->AddLine(strFull); } // Perform some statistical analysis of the quality factor // to determine the likelihood of the current quantization // table being a scaled version of the "standard" tables. // If the variance is high, it is unlikely to be the case. double dQuality; double dVariance; dSumPercent /= 64.0; /* mean scale factor */ dSumPercentSqr /= 64.0; dVariance = dSumPercentSqr - (dSumPercent * dSumPercent); /* variance */ // Generate the equivalent IJQ "quality" factor if (bQuantAllOnes) /* special case for all-ones table */ dQuality = 100.0; else if (dSumPercent <= 100.0) dQuality = (200.0 - dSumPercent) / 2.0; else dQuality = 5000.0 / dSumPercent; // Save the quality rating for later m_adImgDqtQual[nDqtQuantDestId_Tq] = dQuality; strTmp.Format(_T(" Approx quality factor = %.2f (scaling=%.2f variance=%.2f)"), dQuality,dSumPercent,dVariance); m_pLog->AddLine(strTmp); } m_bStateDqtOk = true; if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_DAC: // DAC (Arithmetic Coding) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // La m_nPos+=2; //XXX strTmp.Format(_T(" Arithmetic coding header length <La> = %u"),nLength); strTmp.Format(_T(" Arithmetic coding header length = %u"),nLength); m_pLog->AddLine(strTmp); unsigned nDAC_n; unsigned nDAC_Tc,nDAC_Tb; unsigned nDAC_Cs; nDAC_n = (nLength>2)?(nLength-2)/2:0; for (unsigned nInd=0;nInd<nDAC_n;nInd++) { nTmpVal = Buf(m_nPos++); // Tc,Tb nDAC_Tc = (nTmpVal & 0xF0) >> 4; nDAC_Tb = (nTmpVal & 0x0F); //XXX strTmp.Format(_T(" #%02u: Table class <Tc> = %u"),nInd+1,nDAC_Tc); strTmp.Format(_T(" #%02u: Table class = %u"),nInd+1,nDAC_Tc); m_pLog->AddLine(strTmp); //XXX strTmp.Format(_T(" #%02u: Table destination identifier <Tb> = %u"),nInd+1,nDAC_Tb); strTmp.Format(_T(" #%02u: Table destination identifier = %u"),nInd+1,nDAC_Tb); m_pLog->AddLine(strTmp); nDAC_Cs = Buf(m_nPos++); // Cs //XXX strTmp.Format(_T(" #%02u: Conditioning table value <Cs> = %u"),nInd+1,nDAC_Cs); strTmp.Format(_T(" #%02u: Conditioning table value = %u"),nInd+1,nDAC_Cs); m_pLog->AddLine(strTmp); if (!ValidateValue(nDAC_Tc,0,1,_T("Table class <Tc>"),true,0)) return DECMARK_ERR; if (!ValidateValue(nDAC_Tb,0,3,_T("Table destination ID <Tb>"),true,0)) return DECMARK_ERR; // Parameter range constraints per Table B.6: // ------------|-------------------------|-------------------|------------ // | Sequential DCT | Progressive DCT | Lossless // Parameter | Baseline Extended | | // ------------|-----------|-------------|-------------------|------------ // Cs | Undef | Tc=0: 0-255 | Tc=0: 0-255 | 0-255 // | | Tc=1: 1-63 | Tc=1: 1-63 | // ------------|-----------|-------------|-------------------|------------ // However, to keep it simple (and not depend on lossless mode), // we will only check the maximal range if (!ValidateValue(nDAC_Cs,0,255,_T("Conditioning table value <Cs>"),true,0)) return DECMARK_ERR; } if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_DNL: // DNL (Define number of lines) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Ld m_nPos+=2; //XXX strTmp.Format(_T(" Header length <Ld> = %u"),nLength); strTmp.Format(_T(" Header length = %u"),nLength); m_pLog->AddLine(strTmp); nTmpVal = Buf(m_nPos)*256 + Buf(m_nPos+1); // NL m_nPos+=2; //XXX strTmp.Format(_T(" Number of lines <NL> = %u"),nTmpVal); strTmp.Format(_T(" Number of lines = %u"),nTmpVal); m_pLog->AddLine(strTmp); if (!ValidateValue(nTmpVal,1,65535,_T("Number of lines <NL>"),true,1)) return DECMARK_ERR; if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_EXP: nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Le m_nPos+=2; //XXX strTmp.Format(_T(" Header length <Le> = %u"),nLength); strTmp.Format(_T(" Header length = %u"),nLength); m_pLog->AddLine(strTmp); unsigned nEXP_Eh,nEXP_Ev; nTmpVal = Buf(m_nPos)*256 + Buf(m_nPos+1); // Eh,Ev nEXP_Eh = (nTmpVal & 0xF0) >> 4; nEXP_Ev = (nTmpVal & 0x0F); m_nPos+=2; //XXX strTmp.Format(_T(" Expand horizontally <Eh> = %u"),nEXP_Eh); strTmp.Format(_T(" Expand horizontally = %u"),nEXP_Eh); m_pLog->AddLine(strTmp); //XXX strTmp.Format(_T(" Expand vertically <Ev> = %u"),nEXP_Ev); strTmp.Format(_T(" Expand vertically = %u"),nEXP_Ev); m_pLog->AddLine(strTmp); if (!ValidateValue(nEXP_Eh,0,1,_T("Expand horizontally <Eh>"),true,0)) return DECMARK_ERR; if (!ValidateValue(nEXP_Ev,0,1,_T("Expand vertically <Ev>"),true,0)) return DECMARK_ERR; if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_SOF0: // SOF0 (Baseline DCT) case JFIF_SOF1: // SOF1 (Extended sequential) case JFIF_SOF2: // SOF2 (Progressive) case JFIF_SOF3: case JFIF_SOF5: case JFIF_SOF6: case JFIF_SOF7: case JFIF_SOF9: case JFIF_SOF10: case JFIF_SOF11: case JFIF_SOF13: case JFIF_SOF14: case JFIF_SOF15: // TODO: // - JFIF_DHP should be able to reuse the JFIF_SOF marker parsing // however as we don't support hierarchical image decode, we // would want to skip the update of class members. m_bStateSof = true; // Determine if this is a SOF mode that we support // At this time, we only support Baseline DCT & Extended Sequential Baseline DCT // (non-differential) with Huffman coding. Progressive, Lossless, // Differential and Arithmetic coded modes are not supported. m_bImgSofUnsupported = true; if (nCode == JFIF_SOF0) { m_bImgSofUnsupported = false; } if (nCode == JFIF_SOF1) { m_bImgSofUnsupported = false; } // For reference, note progressive scan files even though // we don't currently support their decode if (nCode == JFIF_SOF2) { m_bImgProgressive = true; } nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Lf m_nPos+=2; //XXX strTmp.Format(_T(" Frame header length <Lf> = %u"),nLength); strTmp.Format(_T(" Frame header length = %u"),nLength); m_pLog->AddLine(strTmp); m_nSofPrecision_P = Buf(m_nPos++); // P //XXX strTmp.Format(_T(" Precision <P> = %u"),m_nSofPrecision_P); strTmp.Format(_T(" Precision = %u"),m_nSofPrecision_P); m_pLog->AddLine(strTmp); if (!ValidateValue(m_nSofPrecision_P,2,16,_T("Precision <P>"),true,8)) return DECMARK_ERR; m_nSofNumLines_Y = Buf(m_nPos)*256 + Buf(m_nPos+1); // Y m_nPos += 2; //XXX strTmp.Format(_T(" Number of Lines <Y> = %u"),m_nSofNumLines_Y); strTmp.Format(_T(" Number of Lines = %u"),m_nSofNumLines_Y); m_pLog->AddLine(strTmp); if (!ValidateValue(m_nSofNumLines_Y,0,65535,_T("Number of Lines <Y>"),true,0)) return DECMARK_ERR; m_nSofSampsPerLine_X = Buf(m_nPos)*256 + Buf(m_nPos+1); // X m_nPos += 2; //XXX strTmp.Format(_T(" Samples per Line <X> = %u"),m_nSofSampsPerLine_X); strTmp.Format(_T(" Samples per Line = %u"),m_nSofSampsPerLine_X); m_pLog->AddLine(strTmp); if (!ValidateValue(m_nSofSampsPerLine_X,1,65535,_T("Samples per Line <X>"),true,1)) return DECMARK_ERR; strTmp.Format(_T(" Image Size = %u x %u"),m_nSofSampsPerLine_X,m_nSofNumLines_Y); m_pLog->AddLine(strTmp); // Determine orientation // m_nSofSampsPerLine_X = X // m_nSofNumLines_Y = Y m_eImgLandscape = ENUM_LANDSCAPE_YES; if (m_nSofNumLines_Y > m_nSofSampsPerLine_X) m_eImgLandscape = ENUM_LANDSCAPE_NO; strTmp.Format(_T(" Raw Image Orientation = %s"),(m_eImgLandscape==ENUM_LANDSCAPE_YES)?_T("Landscape"):_T("Portrait")); m_pLog->AddLine(strTmp); m_nSofNumComps_Nf = Buf(m_nPos++); // Nf, range 1..255 //XXX strTmp.Format(_T(" Number of Img components <Nf> = %u"),m_nSofNumComps_Nf); strTmp.Format(_T(" Number of Img components = %u"),m_nSofNumComps_Nf); m_pLog->AddLine(strTmp); if (!ValidateValue(m_nSofNumComps_Nf,1,255,_T("Number of Img components <Nf>"),true,1)) return DECMARK_ERR; unsigned nCompIdent; unsigned anSofSampFact[MAX_SOF_COMP_NF]; m_nSofHorzSampFactMax_Hmax = 0; m_nSofVertSampFactMax_Vmax = 0; // Now clear the output image content (all components) // TODO: Migrate some of the bitmap allocation / clearing from // DecodeScanImg() into ResetImageContent() and call here //m_pImgDec->ResetImageContent(); // Per JFIF v1.02: // - Nf = 1 or 3 // - C1 = Y // - C2 = Cb // - C3 = Cr for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = Buf(m_nPos++); // Ci, range 0..255 m_anSofQuantCompId[nCompInd] = nCompIdent; //if (!ValidateValue(m_anSofQuantCompId[nCompInd],0,255,_T("Component ID <Ci>"),true,0)) return DECMARK_ERR; anSofSampFact[nCompIdent] = Buf(m_nPos++); m_anSofQuantTblSel_Tqi[nCompIdent] = Buf(m_nPos++); // Tqi, range 0..3 //if (!ValidateValue(m_anSofQuantTblSel_Tqi[nCompIdent],0,3,_T("Table Destination ID <Tqi>"),true,0)) return DECMARK_ERR; // NOTE: We protect against bad input here as replication ratios are // determined later that depend on dividing by sampling factor (hence // possibility of div by 0). m_anSofHorzSampFact_Hi[nCompIdent] = (anSofSampFact[nCompIdent] & 0xF0) >> 4; // Hi, range 1..4 m_anSofVertSampFact_Vi[nCompIdent] = (anSofSampFact[nCompIdent] & 0x0F); // Vi, range 1..4 //if (!ValidateValue(m_anSofHorzSampFact_Hi[nCompIdent],1,4,_T("Horizontal Sampling Factor <Hi>"),true,1)) return DECMARK_ERR; //if (!ValidateValue(m_anSofVertSampFact_Vi[nCompIdent],1,4,_T("Vertical Sampling Factor <Vi>"),true,1)) return DECMARK_ERR; } // Calculate max sampling factors for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = m_anSofQuantCompId[nCompInd]; // Calculate maximum sampling factor for the SOF. This is only // used for later generation of m_strImgQuantCss an the SOF // reporting below. The CimgDecode block is responsible for // calculating the maximum sampling factor on a per-scan basis. m_nSofHorzSampFactMax_Hmax = max(m_nSofHorzSampFactMax_Hmax,m_anSofHorzSampFact_Hi[nCompIdent]); m_nSofVertSampFactMax_Vmax = max(m_nSofVertSampFactMax_Vmax,m_anSofVertSampFact_Vi[nCompIdent]); } // Report per-component sampling factors and quantization table selectors for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = m_anSofQuantCompId[nCompInd]; // Create subsampling ratio // - Protect against division-by-zero CString strSubsampH = _T("?"); CString strSubsampV = _T("?"); if (m_anSofHorzSampFact_Hi[nCompIdent] > 0) { strSubsampH.Format(_T("%u"),m_nSofHorzSampFactMax_Hmax/m_anSofHorzSampFact_Hi[nCompIdent]); } if (m_anSofVertSampFact_Vi[nCompIdent] > 0) { strSubsampV.Format(_T("%u"),m_nSofVertSampFactMax_Vmax/m_anSofVertSampFact_Vi[nCompIdent]); } strFull.Format(_T(" Component[%u]: "),nCompInd); // Note i in Ci is 1-based //XXX strTmp.Format(_T("ID=0x%02X, Samp Fac <Hi,Vi>=0x%02X (Subsamp %u x %u), Quant Tbl Sel <Tqi>=0x%02X"), strTmp.Format(_T("ID=0x%02X, Samp Fac=0x%02X (Subsamp %s x %s), Quant Tbl Sel=0x%02X"), nCompIdent,anSofSampFact[nCompIdent], (LPCTSTR)strSubsampH,(LPCTSTR)strSubsampV, m_anSofQuantTblSel_Tqi[nCompIdent]); strFull += strTmp; // Mapping from component index (not ID) to colour channel per JFIF if (m_nSofNumComps_Nf == 1) { // Assume grayscale strFull += _T(" (Lum: Y)"); } else if (m_nSofNumComps_Nf == 3) { // Assume YCC if (nCompInd == SCAN_COMP_Y) { strFull += _T(" (Lum: Y)"); } else if (nCompInd == SCAN_COMP_CB) { strFull += _T(" (Chrom: Cb)"); } else if (nCompInd == SCAN_COMP_CR) { strFull += _T(" (Chrom: Cr)"); } } else if (m_nSofNumComps_Nf == 4) { // Assume YCCK if (nCompInd == 1) { strFull += _T(" (Y)"); } else if (nCompInd == 2) { strFull += _T(" (Cb)"); } else if (nCompInd == 3) { strFull += _T(" (Cr)"); } else if (nCompInd == 4) { strFull += _T(" (K)"); } } else { strFull += _T(" (???)"); // Unknown } m_pLog->AddLine(strFull); } // Test for bad input, clean up if bad for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = m_anSofQuantCompId[nCompInd]; if (!ValidateValue(m_anSofQuantCompId[nCompInd],0,255,_T("Component ID <Ci>"),true,0)) return DECMARK_ERR; if (!ValidateValue(m_anSofQuantTblSel_Tqi[nCompIdent],0,3,_T("Table Destination ID <Tqi>"),true,0)) return DECMARK_ERR; if (!ValidateValue(m_anSofHorzSampFact_Hi[nCompIdent],1,4,_T("Horizontal Sampling Factor <Hi>"),true,1)) return DECMARK_ERR; if (!ValidateValue(m_anSofVertSampFact_Vi[nCompIdent],1,4,_T("Vertical Sampling Factor <Vi>"),true,1)) return DECMARK_ERR; } // Finally, assign the cleaned values to the decoder for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = m_anSofQuantCompId[nCompInd]; // Store the DQT Table selection for the Image Decoder // Param values: Nf,Tqi // Param ranges: 1..255,0..3 // Note that the Image Decoder doesn't need to see the Component Identifiers bRet = m_pImgDec->SetDqtTables(nCompInd,m_anSofQuantTblSel_Tqi[nCompIdent]); DecodeErrCheck(bRet); // Store the Precision (to handle 12-bit decode) m_pImgDec->SetPrecision(m_nSofPrecision_P); } if (!m_bStateAbort) { // Set the component sampling factors (chroma subsampling) // FIXME: check ranging for (unsigned nCompInd=1;nCompInd<=m_nSofNumComps_Nf;nCompInd++) { // nCompInd is component index (1...Nf) // nCompIdent is Component Identifier (Ci) // Note that the Image Decoder doesn't need to see the Component Identifiers nCompIdent = m_anSofQuantCompId[nCompInd]; m_pImgDec->SetSofSampFactors(nCompInd,m_anSofHorzSampFact_Hi[nCompIdent],m_anSofVertSampFact_Vi[nCompIdent]); } // Now mark the image as been somewhat OK (ie. should // also be suitable for EmbeddedThumb() and PrepareSignature() m_bImgOK = true; m_bStateSofOk = true; } if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_COM: // COM nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); m_nPos+=2; strTmp.Format(_T(" Comment length = %u"),nLength); m_pLog->AddLine(strTmp); // Check for JPEG COM vulnerability // http://marc.info/?l=bugtraq&m=109524346729948 // Note that the recovery is not very graceful. It will assume that the // field is actually zero-length, which will make the next byte trigger the // "Expected marker 0xFF" error message and probably abort. There is no // obvious way to if ( (nLength == 0) || (nLength == 1) ) { strTmp.Format(_T(" JPEG Comment Field Vulnerability detected!")); m_pLog->AddLineErr(strTmp); strTmp.Format(_T(" Skipping data until next marker...")); m_pLog->AddLineErr(strTmp); nLength = 2; bool bDoneSearch = false; unsigned nSkipStart = m_nPos; while (!bDoneSearch) { if (Buf(m_nPos) != 0xFF) { m_nPos++; } else { bDoneSearch = true; } if (m_nPos >= m_pWBuf->GetPosEof()) { bDoneSearch = true; } } strTmp.Format(_T(" Skipped %u bytes"),m_nPos - nSkipStart); m_pLog->AddLineErr(strTmp); // Break out of case statement break; } // Assume COM field valid length (ie. >= 2) strFull = _T(" Comment="); m_strComment = _T(""); for (unsigned ind=0;ind<nLength-2;ind++) { nTmpVal = Buf(m_nPos++); if (_istprint(nTmpVal)) { strTmp.Format(_T("%c"),nTmpVal); m_strComment += strTmp; } else { m_strComment += _T("."); } } strFull += m_strComment; m_pLog->AddLine(strFull); break; case JFIF_DHT: // DHT m_bStateDht = true; DecodeDHT(false); m_bStateDhtOk = true; break; case JFIF_SOS: // SOS unsigned long nPosScanStart; // Byte count at start of scan data segment m_bStateSos = true; // NOTE: Only want to capture position of first SOS // This should make other function such as AVI frame extract // more robust in case we get multiple SOS segments. // We assume that this value is reset when we start a new decode if (m_nPosSos == 0) { m_nPosSos = m_nPos-2; // Used for Extract. Want to include actual marker } nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); m_nPos+=2; // Ensure that we have seen proper markers before we try this one! if (!m_bStateSofOk) { strTmp.Format(_T(" ERROR: SOS before valid SOF defined")); m_pLog->AddLineErr(strTmp); return DECMARK_ERR; } strTmp.Format(_T(" Scan header length = %u"),nLength); m_pLog->AddLine(strTmp); m_nSosNumCompScan_Ns = Buf(m_nPos++); // Ns, range 1..4 //XXX strTmp.Format(_T(" Number of image components <Ns> = %u"),m_nSosNumCompScan_Ns); strTmp.Format(_T(" Number of img components = %u"),m_nSosNumCompScan_Ns); m_pLog->AddLine(strTmp); // Just in case something got corrupted, don't want to get out // of range here. Note that this will be a hard abort, and // will not resume decoding. if (m_nSosNumCompScan_Ns > MAX_SOS_COMP_NS) { strTmp.Format(_T(" ERROR: Scan decode does not support > %u components"),MAX_SOS_COMP_NS); m_pLog->AddLineErr(strTmp); return DECMARK_ERR; } unsigned nSosCompSel_Cs; unsigned nSosHuffTblSel; unsigned nSosHuffTblSelDc_Td; unsigned nSosHuffTblSelAc_Ta; // Max range of components indices is between 1..4 for (unsigned int nScanCompInd=1;((nScanCompInd<=m_nSosNumCompScan_Ns) && (!m_bStateAbort));nScanCompInd++) { strFull.Format(_T(" Component[%u]: "),nScanCompInd); nSosCompSel_Cs = Buf(m_nPos++); // Cs, range 0..255 nSosHuffTblSel = Buf(m_nPos++); nSosHuffTblSelDc_Td = (nSosHuffTblSel & 0xf0)>>4; // Td, range 0..3 nSosHuffTblSelAc_Ta = (nSosHuffTblSel & 0x0f); // Ta, range 0..3 strTmp.Format(_T("selector=0x%02X, table=%u(DC),%u(AC)"),nSosCompSel_Cs,nSosHuffTblSelDc_Td,nSosHuffTblSelAc_Ta); strFull += strTmp; m_pLog->AddLine(strFull); bRet = m_pImgDec->SetDhtTables(nScanCompInd,nSosHuffTblSelDc_Td,nSosHuffTblSelAc_Ta); DecodeErrCheck(bRet); } m_nSosSpectralStart_Ss = Buf(m_nPos++); m_nSosSpectralEnd_Se = Buf(m_nPos++); m_nSosSuccApprox_A = Buf(m_nPos++); strTmp.Format(_T(" Spectral selection = %u .. %u"),m_nSosSpectralStart_Ss,m_nSosSpectralEnd_Se); m_pLog->AddLine(strTmp); strTmp.Format(_T(" Successive approximation = 0x%02X"),m_nSosSuccApprox_A); m_pLog->AddLine(strTmp); if (m_pAppConfig->bOutputScanDump) { m_pLog->AddLine(_T("")); m_pLog->AddLine(_T(" Scan Data: (after bitstuff removed)")); } // Save the scan data segment position nPosScanStart = m_nPos; // Skip over the Scan Data segment // Pass 1) Quick, allowing for bOutputScanDump to dump first 640B. // Pass 2) If bDecodeScanImg, we redo the process but in detail decoding. // FIXME: Not sure why, but if I skip over Pass 1 (eg if I leave in the // following line uncommented), then I get an error at the end of the // pass 2 decode (indicating that EOI marker not seen, and expecting // marker). // if (m_pAppConfig->bOutputScanDump) { // --- PASS 1 --- bool bSkipDone; unsigned nSkipCount; unsigned nSkipData; unsigned nSkipPos; bool bScanDumpTrunc; bSkipDone = false; nSkipCount = 0; nSkipPos = 0; bScanDumpTrunc = FALSE; strFull = _T(""); while (!bSkipDone) { nSkipCount++; nSkipPos++; nSkipData = Buf(m_nPos++); if (nSkipData == 0xFF) { // this could either be a marker or a byte stuff nSkipData = Buf(m_nPos++); nSkipCount++; if (nSkipData == 0x00) { // Byte stuff nSkipData = 0xFF; } else if ((nSkipData >= JFIF_RST0) && (nSkipData <= JFIF_RST7)) { // Skip over } else { // Marker bSkipDone = true; m_nPos -= 2; } } if (m_pAppConfig->bOutputScanDump && (!bSkipDone) ) { // Only display 20 lines of scan data if (nSkipPos > 640) { if (!bScanDumpTrunc) { m_pLog->AddLineWarn(_T(" WARNING: Dump truncated.")); bScanDumpTrunc = TRUE; } } else { if ( ((nSkipPos-1) == 0) || (((nSkipPos-1) % 32) == 0) ) { strFull = _T(" "); } strTmp.Format(_T("%02x "),nSkipData); strFull += strTmp; if (((nSkipPos-1) % 32) == 31) { m_pLog->AddLine(strFull); strFull = _T(""); } } } // Did we run out of bytes? // FIXME: // NOTE: This line here doesn't allow us to attempt to // decode images that are missing EOI. Maybe this is // not the best solution here? Instead, we should be // checking m_nPos against file length? .. and not // return but "break". if (!m_pWBuf->GetBufOk()) { strTmp.Format(_T("ERROR: Ran out of buffer before EOI during phase 1 of Scan decode @ 0x%08X"),m_nPos); m_pLog->AddLineErr(strTmp); break; } } m_pLog->AddLine(strFull); // } // --- PASS 2 --- // If the option is set, start parsing! if (m_pAppConfig->bDecodeScanImg && m_bImgSofUnsupported) { // SOF marker was of type we don't support, so skip decoding m_pLog->AddLineWarn(_T(" NOTE: Scan parsing doesn't support this SOF mode.")); #ifndef DEBUG_YCCK } else if (m_pAppConfig->bDecodeScanImg && (m_nSofNumComps_Nf == 4)) { m_pLog->AddLineWarn(_T(" NOTE: Scan parsing doesn't support CMYK files yet.")); #endif } else if (m_pAppConfig->bDecodeScanImg && !m_bImgSofUnsupported) { if (!m_bStateSofOk) { m_pLog->AddLineWarn(_T(" NOTE: Scan decode disabled as SOF not decoded.")); } else if (!m_bStateDqtOk) { m_pLog->AddLineWarn(_T(" NOTE: Scan decode disabled as DQT not decoded.")); } else if (!m_bStateDhtOk) { m_pLog->AddLineWarn(_T(" NOTE: Scan decode disabled as DHT not decoded.")); } else { m_pLog->AddLine(_T("")); // Set the primary image details m_pImgDec->SetImageDetails(m_nSofSampsPerLine_X,m_nSofNumLines_Y, m_nSofNumComps_Nf,m_nSosNumCompScan_Ns,m_nImgRstEn,m_nImgRstInterval); // Only recalculate the scan decoding if we need to (i.e. file // changed, offset changed, scan option changed) // TODO: In order to decode multiple scans, we will need to alter the // way that m_pImgSrcDirty is set if (m_pImgSrcDirty) { m_pImgDec->DecodeScanImg(nPosScanStart,true,false); m_pImgSrcDirty = false; } } } m_bStateSosOk = true; break; case JFIF_DRI: unsigned nVal; nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); strTmp.Format(_T(" Length = %u"),nLength); m_pLog->AddLine(strTmp); nVal = Buf(m_nPos+2)*256 + Buf(m_nPos+3); // According to ITU-T spec B.2.4.4, we only expect // restart markers if DRI value is non-zero! m_nImgRstInterval = nVal; if (nVal != 0) { m_nImgRstEn = true; } else { m_nImgRstEn = false; } strTmp.Format(_T(" interval = %u"),m_nImgRstInterval); m_pLog->AddLine(strTmp); m_nPos += 4; if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_EOI: // EOI m_pLog->AddLine(_T("")); // Save the EOI file position // NOTE: If the file is missing the EOI, then this variable will be // set to mark the end of file. m_nPosEmbedEnd = m_nPos; m_nPosEoi = m_nPos; m_bStateEoi = true; return DECMARK_EOI; break; // Markers that are not yet supported in JPEGsnoop case JFIF_DHP: // Markers defined for future use / extensions case JFIF_JPG: case JFIF_JPG0: case JFIF_JPG1: case JFIF_JPG2: case JFIF_JPG3: case JFIF_JPG4: case JFIF_JPG5: case JFIF_JPG6: case JFIF_JPG7: case JFIF_JPG8: case JFIF_JPG9: case JFIF_JPG10: case JFIF_JPG11: case JFIF_JPG12: case JFIF_JPG13: case JFIF_TEM: // Unsupported marker // - Provide generic decode based on length nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Length strTmp.Format(_T(" Header length = %u"),nLength); m_pLog->AddLine(strTmp); m_pLog->AddLineWarn(_T(" Skipping unsupported marker")); m_nPos += nLength; break; case JFIF_RST0: case JFIF_RST1: case JFIF_RST2: case JFIF_RST3: case JFIF_RST4: case JFIF_RST5: case JFIF_RST6: case JFIF_RST7: // We don't expect to see restart markers outside the entropy coded segment. // NOTE: RST# are standalone markers, so no length indicator exists // But for the sake of robustness, we can check here to see if treating // as a standalone marker will arrive at another marker (ie. OK). If not, // proceed to assume there is a length indicator. strTmp.Format(_T(" WARNING: Restart marker [0xFF%02X] detected outside scan"),nCode); m_pLog->AddLineWarn(strTmp); if (!m_pAppConfig->bRelaxedParsing) { // Abort m_pLog->AddLineErr(_T(" Stopping decode")); m_pLog->AddLine(_T(" Use [Img Search Fwd/Rev] to locate other valid embedded JPEGs")); return DECMARK_ERR; } else { // Ignore // Check to see if standalone marker treatment looks OK if (Buf(m_nPos+2) == 0xFF) { // Looks like standalone m_pLog->AddLineWarn(_T(" Ignoring standalone marker. Proceeding with decode.")); m_nPos += 2; } else { // Looks like marker with length nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); strTmp.Format(_T(" Header length = %u"),nLength); m_pLog->AddLine(strTmp); m_pLog->AddLineWarn(_T(" Skipping marker")); m_nPos += nLength; } } break; default: strTmp.Format(_T(" WARNING: Unknown marker [0xFF%02X]"),nCode); m_pLog->AddLineWarn(strTmp); if (!m_pAppConfig->bRelaxedParsing) { // Abort m_pLog->AddLineErr(_T(" Stopping decode")); m_pLog->AddLine(_T(" Use [Img Search Fwd/Rev] to locate other valid embedded JPEGs")); return DECMARK_ERR; } else { // Skip nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); strTmp.Format(_T(" Header length = %u"),nLength); m_pLog->AddLine(strTmp); m_pLog->AddLineWarn(_T(" Skipping marker")); m_nPos += nLength; } } // Add white-space between each marker m_pLog->AddLine(_T(" ")); // If we decided to abort for any reason, make sure we trap it now. // This will stop the ProcessFile() while loop. We can set m_bStateAbort // if user says that they want to stop. if (m_bStateAbort) { return DECMARK_ERR; } return DECMARK_OK; }
209,975,869,287,019,700,000,000,000,000,000,000,000
None
null
[ "CWE-369" ]
CVE-2017-1000414
ImpulseAdventure JPEGsnoop version 1.7.5 is vulnerable to a division by zero in the JFIF decode handling resulting denial of service.
https://nvd.nist.gov/vuln/detail/CVE-2017-1000414
518,319
JPEGsnoop
b4e458612d4294e0cfe01dbf1c0b09a07a8133a4
https://github.com/ImpulseAdventure/JPEGsnoop
https://github.com/ImpulseAdventure/JPEGsnoop/commit/b4e458612d4294e0cfe01dbf1c0b09a07a8133a4#diff-cf9182aecc9d630e8db2e0e35f1eec65
Fixed div0 vulnerability in SampFact
0
unsigned CjfifDecode::DecodeMarker() { TCHAR acIdentifier[MAX_IDENTIFIER]; CString strTmp; CString strFull; // Used for concatenation unsigned nLength; // General purpose unsigned nTmpVal; unsigned nCode; unsigned long nPosEnd; unsigned long nPosSaved; // General-purpose saved position in file unsigned long nPosExifStart; unsigned nRet; // General purpose return value bool bRet; unsigned long nPosMarkerStart; // Offset for current marker unsigned nColTransform = 0; // Color Transform from APP14 marker // For DQT CString strDqtPrecision = _T(""); CString strDqtZigZagOrder = _T(""); if (Buf(m_nPos) != 0xFF) { if (m_nPos == 0) { // Don't give error message if we've already alerted them of AVI / PSD if ((!m_bAvi) && (!m_bPsd)) { strTmp.Format(_T("NOTE: File did not start with JPEG marker. Consider using [Tools->Img Search Fwd] to locate embedded JPEG.")); m_pLog->AddLineErr(strTmp); } } else { strTmp.Format(_T("ERROR: Expected marker 0xFF, got 0x%02X @ offset 0x%08X. Consider using [Tools->Img Search Fwd/Rev]."),Buf(m_nPos),m_nPos); m_pLog->AddLineErr(strTmp); } m_nPos++; return DECMARK_ERR; } m_nPos++; // Read the current marker code nCode = Buf(m_nPos++); // Handle Marker Padding // // According to Section B.1.1.2: // "Any marker may optionally be preceded by any number of fill bytes, which are bytes assigned code XFF." // unsigned nSkipMarkerPad = 0; while (nCode == 0xFF) { // Count the pad nSkipMarkerPad++; // Read another byte nCode = Buf(m_nPos++); } // Report out any padding if (nSkipMarkerPad>0) { strTmp.Format(_T("*** Skipped %u marker pad bytes ***"),nSkipMarkerPad); m_pLog->AddLineHdr(strTmp); } // Save the current marker offset nPosMarkerStart = m_nPos; AddHeader(nCode); switch (nCode) { case JFIF_SOI: // SOI m_bStateSoi = true; break; case JFIF_APP12: // Photoshop DUCKY (Save For Web) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); //nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(" Length = %u"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; m_nPos += 2; // Move past length now that we've used it _tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); acIdentifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case strTmp.Format(_T(" Identifier = [%s]"),acIdentifier); m_pLog->AddLine(strTmp); m_nPos += (unsigned)_tcslen(acIdentifier)+1; if (_tcscmp(acIdentifier,_T("Ducky")) != 0) { m_pLog->AddLine(_T(" Not Photoshop DUCKY. Skipping remainder.")); } else // Photoshop { // Please see reference on http://cpan.uwinnipeg.ca/htdocs/Image-ExifTool/Image/ExifTool/APP12.pm.html // A direct indexed approach should be safe m_nImgQualPhotoshopSfw = Buf(m_nPos+6); strTmp.Format(_T(" Photoshop Save For Web Quality = [%d]"),m_nImgQualPhotoshopSfw); m_pLog->AddLine(strTmp); } // Restore original position in file to a point // after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP14: // JPEG Adobe tag nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); strTmp.Format(_T(" Length = %u"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; // Some files had very short segment (eg. nLength=2) if (nLength < 2+12) { m_pLog->AddLine(_T(" Segment too short for Identifier. Skipping remainder.")); m_nPos = nPosSaved+nLength; break; } m_nPos += 2; // Move past length now that we've used it // TODO: Confirm Adobe flag m_nPos += 5; nTmpVal = Buf(m_nPos+0)*256 + Buf(m_nPos+1); strTmp.Format(_T(" DCTEncodeVersion = %u"),nTmpVal); m_pLog->AddLine(strTmp); nTmpVal = Buf(m_nPos+2)*256 + Buf(m_nPos+3); strTmp.Format(_T(" APP14Flags0 = %u"),nTmpVal); m_pLog->AddLine(strTmp); nTmpVal = Buf(m_nPos+4)*256 + Buf(m_nPos+5); strTmp.Format(_T(" APP14Flags1 = %u"),nTmpVal); m_pLog->AddLine(strTmp); nColTransform = Buf(m_nPos+6); switch (nColTransform) { case APP14_COLXFM_UNK_RGB: strTmp.Format(_T(" ColorTransform = %u [Unknown (RGB or CMYK)]"),nColTransform); break; case APP14_COLXFM_YCC: strTmp.Format(_T(" ColorTransform = %u [YCbCr]"),nColTransform); break; case APP14_COLXFM_YCCK: strTmp.Format(_T(" ColorTransform = %u [YCCK]"),nColTransform); break; default: strTmp.Format(_T(" ColorTransform = %u [???]"),nColTransform); break; } m_pLog->AddLine(strTmp); m_nApp14ColTransform = (nColTransform & 0xFF); // Restore original position in file to a point // after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP13: // Photoshop (Save As) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); //nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(" Length = %u"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; // Some files had very short segment (eg. nLength=2) if (nLength < 2+20) { m_pLog->AddLine(_T(" Segment too short for Identifier. Skipping remainder.")); m_nPos = nPosSaved+nLength; break; } m_nPos += 2; // Move past length now that we've used it _tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); acIdentifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case strTmp.Format(_T(" Identifier = [%s]"),acIdentifier); m_pLog->AddLine(strTmp); m_nPos += (unsigned)_tcslen(acIdentifier)+1; if (_tcscmp(acIdentifier,_T("Photoshop 3.0")) != 0) { m_pLog->AddLine(_T(" Not Photoshop. Skipping remainder.")); } else // Photoshop { DecodeApp13Ps(); } // Restore original position in file to a point // after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP1: nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); //nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(" Length = %u"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; m_nPos += 2; // Move past length now that we've used it _tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); acIdentifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case strTmp.Format(_T(" Identifier = [%s]"),acIdentifier); m_pLog->AddLine(strTmp); m_nPos += (unsigned)_tcslen(acIdentifier); if (!_tcsnccmp(acIdentifier,_T("http://ns.adobe.com/xap/1.0/\x00"),29) != 0) { // XMP m_pLog->AddLine(_T(" XMP = ")); m_nPos++; unsigned nPosMarkerEnd = nPosSaved+nLength-1; unsigned sXmpLen = nPosMarkerEnd-m_nPos; char cXmpChar; bool bNonSpace; CString strLine; // Reset state strLine = _T(" |"); bNonSpace = false; for (unsigned nInd=0;nInd<sXmpLen;nInd++) { // Get the next char cXmpChar = (char)m_pWBuf->Buf(m_nPos+nInd); // Detect a non-space in line if ((cXmpChar != 0x20) && (cXmpChar != 0x0A)) { bNonSpace = true; } // Detect Linefeed, print out line if (cXmpChar == 0x0A) { // Only print line if some non-space elements! if (bNonSpace) { m_pLog->AddLine(strLine); } // Reset state strLine = _T(" |"); bNonSpace = false; } else { // Add the char strLine.AppendChar(cXmpChar); } } } else if (!_tcscmp(acIdentifier,_T("Exif")) != 0) { // Only decode it further if it is EXIF format m_nPos += 2; // Skip two 00 bytes nPosExifStart = m_nPos; // Save m_nPos @ start of EXIF used for all IFD offsets // =========== EXIF TIFF Header (Start) =========== // - Defined in Exif 2.2 Standard (JEITA CP-3451) section 4.5.2 // - Contents (8 bytes total) // - Byte order (2 bytes) // - 0x002A (2 bytes) // - Offset of 0th IFD (4 bytes) unsigned char acIdentifierTiff[9]; strFull = _T(""); strTmp = _T(""); strFull = _T(" Identifier TIFF = "); for (unsigned int i=0;i<8;i++) { acIdentifierTiff[i] = (unsigned char)Buf(m_nPos++); } strTmp = PrintAsHexUC(acIdentifierTiff,8); strFull += strTmp; m_pLog->AddLine(strFull); switch (acIdentifierTiff[0]*256+acIdentifierTiff[1]) { case 0x4949: // "II" // Intel alignment m_nImgExifEndian = 0; m_pLog->AddLine(_T(" Endian = Intel (little)")); break; case 0x4D4D: // "MM" // Motorola alignment m_nImgExifEndian = 1; m_pLog->AddLine(_T(" Endian = Motorola (big)")); break; } // We expect the TAG mark of 0x002A (depending on endian mode) unsigned test_002a; test_002a = ByteSwap2(acIdentifierTiff[2],acIdentifierTiff[3]); strTmp.Format(_T(" TAG Mark x002A = 0x%04X"),test_002a); m_pLog->AddLine(strTmp); unsigned nIfdCount; // Current IFD # unsigned nOffsetIfd1; // Mark pointer to EXIF Sub IFD as 0 so that we can // detect if the tag never showed up. m_nImgExifSubIfdPtr = 0; m_nImgExifMakerPtr = 0; m_nImgExifGpsIfdPtr = 0; m_nImgExifInteropIfdPtr = 0; bool exif_done = FALSE; nOffsetIfd1 = ByteSwap4(acIdentifierTiff[4],acIdentifierTiff[5], acIdentifierTiff[6],acIdentifierTiff[7]); // =========== EXIF TIFF Header (End) =========== // =========== EXIF IFD 0 =========== // Do we start the 0th IFD for the "Primary Image Data"? // Even though the nOffsetIfd1 pointer should indicate to // us where the IFD should start (0x0008 if immediately after // EXIF TIFF Header), I have observed JPEG files that // do not contain the IFD. Therefore, we must check for this // condition by comparing against the APP marker length. // Example file: http://img9.imageshack.us/img9/194/90114543.jpg if ((nPosSaved + nLength) <= (nPosExifStart+nOffsetIfd1)) { // We've run out of space for any IFD, so cancel now exif_done = true; m_pLog->AddLine(_T(" NOTE: No IFD entries")); } nIfdCount = 0; while (!exif_done) { m_pLog->AddLine(_T("")); strTmp.Format(_T("IFD%u"),nIfdCount); // Process the IFD nRet = DecodeExifIfd(strTmp,nPosExifStart,nOffsetIfd1); // Now that we have gone through all entries in the IFD directory, // we read the offset to the next IFD nOffsetIfd1 = ByteSwap4(Buf(m_nPos+0),Buf(m_nPos+1),Buf(m_nPos+2),Buf(m_nPos+3)); m_nPos += 4; strTmp.Format(_T(" Offset to Next IFD = 0x%08X"),nOffsetIfd1); m_pLog->AddLine(strTmp); if (nRet != 0) { // Error condition (DecodeExifIfd returned error) nOffsetIfd1 = 0x00000000; } if (nOffsetIfd1 == 0x00000000) { // Either error condition or truly end of IFDs exif_done = TRUE; } else { nIfdCount++; } } // while ! exif_done // If EXIF SubIFD was defined, then handle it now if (m_nImgExifSubIfdPtr != 0) { m_pLog->AddLine(_T("")); DecodeExifIfd(_T("SubIFD"),nPosExifStart,m_nImgExifSubIfdPtr); } if (m_nImgExifMakerPtr != 0) { m_pLog->AddLine(_T("")); DecodeExifIfd(_T("MakerIFD"),nPosExifStart,m_nImgExifMakerPtr); } if (m_nImgExifGpsIfdPtr != 0) { m_pLog->AddLine(_T("")); DecodeExifIfd(_T("GPSIFD"),nPosExifStart,m_nImgExifGpsIfdPtr); } if (m_nImgExifInteropIfdPtr != 0) { m_pLog->AddLine(_T("")); DecodeExifIfd(_T("InteropIFD"),nPosExifStart,m_nImgExifInteropIfdPtr); } } else { strTmp.Format(_T("Identifier [%s] not supported. Skipping remainder."),(LPCTSTR)acIdentifier); m_pLog->AddLine(strTmp); } ////////// // Dump out Makernote area // TODO: Disabled for now #if 0 unsigned ptr_base; if (m_bVerbose) { if (m_nImgExifMakerPtr != 0) { // FIXME: Seems that nPosExifStart is not initialized in VERBOSE mode ptr_base = nPosExifStart+m_nImgExifMakerPtr; m_pLog->AddLine(_T("Exif Maker IFD DUMP")); strFull.Format(_T(" MarkerOffset @ 0x%08X"),ptr_base); m_pLog->AddLine(strFull); } } #endif // End of dump out makernote area // Restore file position m_nPos = nPosSaved; // Restore original position in file to a point // after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP2: // Typically used for Flashpix and possibly ICC profiles // Photoshop (Save As) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); //nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(" Length = %u"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; m_nPos += 2; // Move past length now that we've used it _tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); acIdentifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case strTmp.Format(_T(" Identifier = [%s]"),acIdentifier); m_pLog->AddLine(strTmp); m_nPos += (unsigned)_tcslen(acIdentifier)+1; if (_tcscmp(acIdentifier,_T("FPXR")) == 0) { // Photoshop m_pLog->AddLine(_T(" FlashPix:")); DecodeApp2Flashpix(); } else if (_tcscmp(acIdentifier,_T("ICC_PROFILE")) == 0) { // ICC Profile m_pLog->AddLine(_T(" ICC Profile:")); DecodeApp2IccProfile(nLength); } else { m_pLog->AddLine(_T(" Not supported. Skipping remainder.")); } // Restore original position in file to a point // after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP3: case JFIF_APP4: case JFIF_APP5: case JFIF_APP6: case JFIF_APP7: case JFIF_APP8: case JFIF_APP9: case JFIF_APP10: case JFIF_APP11: //case JFIF_APP12: // Handled separately //case JFIF_APP13: // Handled separately //case JFIF_APP14: // Handled separately case JFIF_APP15: nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); //nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(" Length = %u"),nLength); m_pLog->AddLine(strTmp); if (m_bVerbose) { strFull = _T(""); for (unsigned int i=0;i<nLength;i++) { // Start a new line for every 16 codes if ((i % 16) == 0) { strFull.Format(_T(" MarkerOffset [%04X]: "),i); } else if ((i % 8) == 0) { strFull += _T(" "); } nTmpVal = Buf(m_nPos+i); strTmp.Format(_T("%02X "),nTmpVal); strFull += strTmp; if ((i%16) == 15) { m_pLog->AddLine(strFull); strFull = _T(""); } } m_pLog->AddLine(strFull); strFull = _T(""); for (unsigned int i=0;i<nLength;i++) { // Start a new line for every 16 codes if ((i % 32) == 0) { strFull.Format(_T(" MarkerOffset [%04X]: "),i); } else if ((i % 8) == 0) { strFull += _T(" "); } nTmpVal = Buf(m_nPos+i); if (_istprint(nTmpVal)) { strTmp.Format(_T("%c"),nTmpVal); strFull += strTmp; } else { strFull += _T("."); } if ((i%32)==31) { m_pLog->AddLine(strFull); } } m_pLog->AddLine(strFull); } // nVerbose m_nPos += nLength; break; case JFIF_APP0: // APP0 nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); //nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); m_nPos+=2; strTmp.Format(_T(" Length = %u"),nLength); m_pLog->AddLine(strTmp); _tcscpy_s(m_acApp0Identifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); m_acApp0Identifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case strTmp.Format(_T(" Identifier = [%s]"),m_acApp0Identifier); m_pLog->AddLine(strTmp); if (!_tcscmp(m_acApp0Identifier,_T("JFIF"))) { // Only process remainder if it is JFIF. This marker // is also used for application-specific functions. m_nPos += (unsigned)(_tcslen(m_acApp0Identifier)+1); m_nImgVersionMajor = Buf(m_nPos++); m_nImgVersionMinor = Buf(m_nPos++); strTmp.Format(_T(" version = [%u.%u]"),m_nImgVersionMajor,m_nImgVersionMinor); m_pLog->AddLine(strTmp); m_nImgUnits = Buf(m_nPos++); m_nImgDensityX = Buf(m_nPos)*256 + Buf(m_nPos+1); //m_nImgDensityX = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); m_nPos+=2; m_nImgDensityY = Buf(m_nPos)*256 + Buf(m_nPos+1); //m_nImgDensityY = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); m_nPos+=2; strTmp.Format(_T(" density = %u x %u "),m_nImgDensityX,m_nImgDensityY); strFull = strTmp; switch (m_nImgUnits) { case 0: strFull += _T("(aspect ratio)"); m_pLog->AddLine(strFull); break; case 1: strFull += _T("DPI (dots per inch)"); m_pLog->AddLine(strFull); break; case 2: strFull += _T("DPcm (dots per cm)"); m_pLog->AddLine(strFull); break; default: strTmp.Format(_T("ERROR: Unknown ImgUnits parameter [%u]"),m_nImgUnits); strFull += strTmp; m_pLog->AddLineWarn(strFull); //return DECMARK_ERR; break; } m_nImgThumbSizeX = Buf(m_nPos++); m_nImgThumbSizeY = Buf(m_nPos++); strTmp.Format(_T(" thumbnail = %u x %u"),m_nImgThumbSizeX,m_nImgThumbSizeY); m_pLog->AddLine(strTmp); // Unpack the thumbnail: unsigned thumbnail_r,thumbnail_g,thumbnail_b; if (m_nImgThumbSizeX && m_nImgThumbSizeY) { for (unsigned y=0;y<m_nImgThumbSizeY;y++) { strFull.Format(_T(" Thumb[%03u] = "),y); for (unsigned x=0;x<m_nImgThumbSizeX;x++) { thumbnail_r = Buf(m_nPos++); thumbnail_g = Buf(m_nPos++); thumbnail_b = Buf(m_nPos++); strTmp.Format(_T("(0x%02X,0x%02X,0x%02X) "),thumbnail_r,thumbnail_g,thumbnail_b); strFull += strTmp; m_pLog->AddLine(strFull); } } } // TODO: // - In JPEG-B mode (GeoRaster), we will need to fake out // the DHT & DQT tables here. Unfortunately, we'll have to // rely on the user to put us into this mode as there is nothing // in the file that specifies this mode. /* // TODO: Need to ensure that Faked DHT is correct table AddHeader(JFIF_DHT_FAKE); DecodeDHT(true); // Need to mark DHT tables as OK m_bStateDht = true; m_bStateDhtFake = true; m_bStateDhtOk = true; // ... same for DQT */ } else if (!_tcsnccmp(m_acApp0Identifier,_T("AVI1"),4)) { // AVI MJPEG type // Need to fill in predefined DHT table from spec: // OpenDML file format for AVI, section "Proposed Data Chunk Format" // Described in MMREG.H m_pLog->AddLine(_T(" Detected MotionJPEG")); m_pLog->AddLine(_T(" Importing standard Huffman table...")); m_pLog->AddLine(_T("")); AddHeader(JFIF_DHT_FAKE); DecodeDHT(true); // Need to mark DHT tables as OK m_bStateDht = true; m_bStateDhtFake = true; m_bStateDhtOk = true; m_nPos += nLength-2; // Skip over, and undo length short read } else { // Not JFIF or AVI1 m_pLog->AddLine(_T(" Not known APP0 type. Skipping remainder.")); m_nPos += nLength-2; } if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_DQT: // Define quantization tables m_bStateDqt = true; unsigned nDqtPrecision_Pq; unsigned nDqtQuantDestId_Tq; nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Lq nPosEnd = m_nPos+nLength; m_nPos+=2; //XXX strTmp.Format(_T(" Table length <Lq> = %u"),nLength); strTmp.Format(_T(" Table length = %u"),nLength); m_pLog->AddLine(strTmp); while (nPosEnd > m_nPos) { strTmp.Format(_T(" ----")); m_pLog->AddLine(strTmp); nTmpVal = Buf(m_nPos++); // Pq | Tq nDqtPrecision_Pq = (nTmpVal & 0xF0) >> 4; // Pq, range 0-1 nDqtQuantDestId_Tq = nTmpVal & 0x0F; // Tq, range 0-3 // Decode per ITU-T.81 standard #if 1 if (nDqtPrecision_Pq == 0) { strDqtPrecision = _T("8 bits"); } else if (nDqtPrecision_Pq == 1) { strDqtPrecision = _T("16 bits"); } else { strTmp.Format(_T(" Unsupported precision value [%u]"),nDqtPrecision_Pq); m_pLog->AddLineWarn(strTmp); strDqtPrecision = _T("???"); // FIXME: Consider terminating marker parsing early } if (!ValidateValue(nDqtPrecision_Pq,0,1,_T("DQT Precision <Pq>"),true,0)) return DECMARK_ERR; if (!ValidateValue(nDqtQuantDestId_Tq,0,3,_T("DQT Destination ID <Tq>"),true,0)) return DECMARK_ERR; strTmp.Format(_T(" Precision=%s"),(LPCTSTR)strDqtPrecision); m_pLog->AddLine(strTmp); #else // Decode with additional DQT extension (ITU-T-JPEG-Plus-Proposal_R3.doc) if ((nDqtPrecision_Pq & 0xE) == 0) { // Per ITU-T.81 Standard if (nDqtPrecision_Pq == 0) { strDqtPrecision = _T("8 bits"); } else if (nDqtPrecision_Pq == 1) { strDqtPrecision = _T("16 bits"); } strTmp.Format(_T(" Precision=%s"),strDqtPrecision); m_pLog->AddLine(strTmp); } else { // Non-standard // JPEG-Plus-Proposal-R3: // - Alternative sub-block-wise sequence strTmp.Format(_T(" Non-Standard DQT Extension detected")); m_pLog->AddLineWarn(strTmp); // FIXME: Should prevent attempt to decode until this is implemented if (nDqtPrecision_Pq == 0) { strDqtPrecision = _T("8 bits"); } else if (nDqtPrecision_Pq == 1) { strDqtPrecision = _T("16 bits"); } strTmp.Format(_T(" Precision=%s"),strDqtPrecision); m_pLog->AddLine(strTmp); if ((nDqtPrecision_Pq & 0x2) == 0) { strDqtZigZagOrder = _T("Diagonal zig-zag coeff scan seqeunce"); } else if ((nDqtPrecision_Pq & 0x2) == 1) { strDqtZigZagOrder = _T("Alternate coeff scan seqeunce"); } strTmp.Format(_T(" Coeff Scan Sequence=%s"),strDqtZigZagOrder); m_pLog->AddLine(strTmp); if ((nDqtPrecision_Pq & 0x4) == 1) { strTmp.Format(_T(" Custom coeff scan sequence")); m_pLog->AddLine(strTmp); // Now expect sequence of 64 coefficient entries CString strSequence = _T(""); for (unsigned nInd=0;nInd<64;nInd++) { nTmpVal = Buf(m_nPos++); strTmp.Format(_T("%u"),nTmpVal); strSequence += strTmp; if (nInd!=63) { strSequence += _T(", "); } } strTmp.Format(_T(" Custom sequence = [ %s ]"),strSequence); m_pLog->AddLine(strTmp); } } #endif strTmp.Format(_T(" Destination ID=%u"),nDqtQuantDestId_Tq); if (nDqtQuantDestId_Tq == 0) { strTmp += _T(" (Luminance)"); } else if (nDqtQuantDestId_Tq == 1) { strTmp += _T(" (Chrominance)"); } else if (nDqtQuantDestId_Tq == 2) { strTmp += _T(" (Chrominance)"); } else { strTmp += _T(" (???)"); } m_pLog->AddLine(strTmp); // FIXME: The following is somewhat superseded by ValidateValue() above // with the exception of skipping remainder if (nDqtQuantDestId_Tq >= MAX_DQT_DEST_ID) { strTmp.Format(_T("ERROR: Destination ID <Tq> = %u, >= %u"),nDqtQuantDestId_Tq,MAX_DQT_DEST_ID); m_pLog->AddLineErr(strTmp); if (!m_pAppConfig->bRelaxedParsing) { m_pLog->AddLineErr(_T(" Stopping decode")); return DECMARK_ERR; } else { // Now skip remainder of DQT // FIXME strTmp.Format(_T(" Skipping remainder of marker [%u bytes]"),nPosMarkerStart + nLength - m_nPos); m_pLog->AddLineWarn(strTmp); m_pLog->AddLine(_T("")); m_nPos = nPosMarkerStart + nLength; return DECMARK_OK; } } bool bQuantAllOnes = true; double dComparePercent; double dSumPercent=0; double dSumPercentSqr=0; for (unsigned nCoeffInd=0;nCoeffInd<MAX_DQT_COEFF;nCoeffInd++) { nTmpVal = Buf(m_nPos++); if (nDqtPrecision_Pq == 1) { // 16-bit DQT entries! nTmpVal <<= 8; nTmpVal += Buf(m_nPos++); } m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]] = nTmpVal; /* scaling factor in percent */ // Now calculate the comparison with the Annex sample // FIXME: Should probably use check for landscape orientation and // rotate comparison matrix accordingly if (nDqtQuantDestId_Tq == 0) { if (m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]] != 0) { m_afStdQuantLumCompare[glb_anZigZag[nCoeffInd]] = (float)(glb_anStdQuantLum[glb_anZigZag[nCoeffInd]]) / (float)(m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]]); dComparePercent = 100.0 * (double)(m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]]) / (double)(glb_anStdQuantLum[glb_anZigZag[nCoeffInd]]); } else { m_afStdQuantLumCompare[glb_anZigZag[nCoeffInd]] = (float)999.99; dComparePercent = 999.99; } } else { if (m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]] != 0) { m_afStdQuantChrCompare[glb_anZigZag[nCoeffInd]] = (float)(glb_anStdQuantChr[glb_anZigZag[nCoeffInd]]) / (float)(m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]]); dComparePercent = 100.0 * (double)(m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]]) / (double)(glb_anStdQuantChr[glb_anZigZag[nCoeffInd]]); } else { m_afStdQuantChrCompare[glb_anZigZag[nCoeffInd]] = (float)999.99; } } dSumPercent += dComparePercent; dSumPercentSqr += dComparePercent * dComparePercent; // Check just in case entire table are ones (Quality 100) if (m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]] != 1) bQuantAllOnes = 0; } // 0..63 // Note that the DQT table that we are saving is already // after doing zigzag reordering: // From high freq -> low freq // To X,Y, left-to-right, top-to-bottom // Flag this DQT table as being set! m_abImgDqtSet[nDqtQuantDestId_Tq] = true; unsigned nCoeffInd; // Now display the table for (unsigned nDqtY=0;nDqtY<8;nDqtY++) { strFull.Format(_T(" DQT, Row #%u: "),nDqtY); for (unsigned nDqtX=0;nDqtX<8;nDqtX++) { nCoeffInd = nDqtY*8+nDqtX; strTmp.Format(_T("%3u "),m_anImgDqtTbl[nDqtQuantDestId_Tq][nCoeffInd]); strFull += strTmp; // Store the DQT entry into the Image Decoder bRet = m_pImgDec->SetDqtEntry(nDqtQuantDestId_Tq,nCoeffInd,glb_anUnZigZag[nCoeffInd], m_anImgDqtTbl[nDqtQuantDestId_Tq][nCoeffInd]); DecodeErrCheck(bRet); } // Now add the compare with Annex K // Decided to disable this as it was confusing users /* strFull += _T(" AnnexRatio: <"); for (unsigned nDqtX=0;nDqtX<8;nDqtX++) { nCoeffInd = nDqtY*8+nDqtX; if (nDqtQuantDestId_Tq == 0) { strTmp.Format(_T("%5.1f "),m_afStdQuantLumCompare[nCoeffInd]); } else { strTmp.Format(_T("%5.1f "),m_afStdQuantChrCompare[nCoeffInd]); } strFull += strTmp; } strFull += _T(">"); */ m_pLog->AddLine(strFull); } // Perform some statistical analysis of the quality factor // to determine the likelihood of the current quantization // table being a scaled version of the "standard" tables. // If the variance is high, it is unlikely to be the case. double dQuality; double dVariance; dSumPercent /= 64.0; /* mean scale factor */ dSumPercentSqr /= 64.0; dVariance = dSumPercentSqr - (dSumPercent * dSumPercent); /* variance */ // Generate the equivalent IJQ "quality" factor if (bQuantAllOnes) /* special case for all-ones table */ dQuality = 100.0; else if (dSumPercent <= 100.0) dQuality = (200.0 - dSumPercent) / 2.0; else dQuality = 5000.0 / dSumPercent; // Save the quality rating for later m_adImgDqtQual[nDqtQuantDestId_Tq] = dQuality; strTmp.Format(_T(" Approx quality factor = %.2f (scaling=%.2f variance=%.2f)"), dQuality,dSumPercent,dVariance); m_pLog->AddLine(strTmp); } m_bStateDqtOk = true; if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_DAC: // DAC (Arithmetic Coding) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // La m_nPos+=2; //XXX strTmp.Format(_T(" Arithmetic coding header length <La> = %u"),nLength); strTmp.Format(_T(" Arithmetic coding header length = %u"),nLength); m_pLog->AddLine(strTmp); unsigned nDAC_n; unsigned nDAC_Tc,nDAC_Tb; unsigned nDAC_Cs; nDAC_n = (nLength>2)?(nLength-2)/2:0; for (unsigned nInd=0;nInd<nDAC_n;nInd++) { nTmpVal = Buf(m_nPos++); // Tc,Tb nDAC_Tc = (nTmpVal & 0xF0) >> 4; nDAC_Tb = (nTmpVal & 0x0F); //XXX strTmp.Format(_T(" #%02u: Table class <Tc> = %u"),nInd+1,nDAC_Tc); strTmp.Format(_T(" #%02u: Table class = %u"),nInd+1,nDAC_Tc); m_pLog->AddLine(strTmp); //XXX strTmp.Format(_T(" #%02u: Table destination identifier <Tb> = %u"),nInd+1,nDAC_Tb); strTmp.Format(_T(" #%02u: Table destination identifier = %u"),nInd+1,nDAC_Tb); m_pLog->AddLine(strTmp); nDAC_Cs = Buf(m_nPos++); // Cs //XXX strTmp.Format(_T(" #%02u: Conditioning table value <Cs> = %u"),nInd+1,nDAC_Cs); strTmp.Format(_T(" #%02u: Conditioning table value = %u"),nInd+1,nDAC_Cs); m_pLog->AddLine(strTmp); if (!ValidateValue(nDAC_Tc,0,1,_T("Table class <Tc>"),true,0)) return DECMARK_ERR; if (!ValidateValue(nDAC_Tb,0,3,_T("Table destination ID <Tb>"),true,0)) return DECMARK_ERR; // Parameter range constraints per Table B.6: // ------------|-------------------------|-------------------|------------ // | Sequential DCT | Progressive DCT | Lossless // Parameter | Baseline Extended | | // ------------|-----------|-------------|-------------------|------------ // Cs | Undef | Tc=0: 0-255 | Tc=0: 0-255 | 0-255 // | | Tc=1: 1-63 | Tc=1: 1-63 | // ------------|-----------|-------------|-------------------|------------ // However, to keep it simple (and not depend on lossless mode), // we will only check the maximal range if (!ValidateValue(nDAC_Cs,0,255,_T("Conditioning table value <Cs>"),true,0)) return DECMARK_ERR; } if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_DNL: // DNL (Define number of lines) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Ld m_nPos+=2; //XXX strTmp.Format(_T(" Header length <Ld> = %u"),nLength); strTmp.Format(_T(" Header length = %u"),nLength); m_pLog->AddLine(strTmp); nTmpVal = Buf(m_nPos)*256 + Buf(m_nPos+1); // NL m_nPos+=2; //XXX strTmp.Format(_T(" Number of lines <NL> = %u"),nTmpVal); strTmp.Format(_T(" Number of lines = %u"),nTmpVal); m_pLog->AddLine(strTmp); if (!ValidateValue(nTmpVal,1,65535,_T("Number of lines <NL>"),true,1)) return DECMARK_ERR; if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_EXP: nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Le m_nPos+=2; //XXX strTmp.Format(_T(" Header length <Le> = %u"),nLength); strTmp.Format(_T(" Header length = %u"),nLength); m_pLog->AddLine(strTmp); unsigned nEXP_Eh,nEXP_Ev; nTmpVal = Buf(m_nPos)*256 + Buf(m_nPos+1); // Eh,Ev nEXP_Eh = (nTmpVal & 0xF0) >> 4; nEXP_Ev = (nTmpVal & 0x0F); m_nPos+=2; //XXX strTmp.Format(_T(" Expand horizontally <Eh> = %u"),nEXP_Eh); strTmp.Format(_T(" Expand horizontally = %u"),nEXP_Eh); m_pLog->AddLine(strTmp); //XXX strTmp.Format(_T(" Expand vertically <Ev> = %u"),nEXP_Ev); strTmp.Format(_T(" Expand vertically = %u"),nEXP_Ev); m_pLog->AddLine(strTmp); if (!ValidateValue(nEXP_Eh,0,1,_T("Expand horizontally <Eh>"),true,0)) return DECMARK_ERR; if (!ValidateValue(nEXP_Ev,0,1,_T("Expand vertically <Ev>"),true,0)) return DECMARK_ERR; if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_SOF0: // SOF0 (Baseline DCT) case JFIF_SOF1: // SOF1 (Extended sequential) case JFIF_SOF2: // SOF2 (Progressive) case JFIF_SOF3: case JFIF_SOF5: case JFIF_SOF6: case JFIF_SOF7: case JFIF_SOF9: case JFIF_SOF10: case JFIF_SOF11: case JFIF_SOF13: case JFIF_SOF14: case JFIF_SOF15: // TODO: // - JFIF_DHP should be able to reuse the JFIF_SOF marker parsing // however as we don't support hierarchical image decode, we // would want to skip the update of class members. m_bStateSof = true; // Determine if this is a SOF mode that we support // At this time, we only support Baseline DCT & Extended Sequential Baseline DCT // (non-differential) with Huffman coding. Progressive, Lossless, // Differential and Arithmetic coded modes are not supported. m_bImgSofUnsupported = true; if (nCode == JFIF_SOF0) { m_bImgSofUnsupported = false; } if (nCode == JFIF_SOF1) { m_bImgSofUnsupported = false; } // For reference, note progressive scan files even though // we don't currently support their decode if (nCode == JFIF_SOF2) { m_bImgProgressive = true; } nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Lf m_nPos+=2; //XXX strTmp.Format(_T(" Frame header length <Lf> = %u"),nLength); strTmp.Format(_T(" Frame header length = %u"),nLength); m_pLog->AddLine(strTmp); m_nSofPrecision_P = Buf(m_nPos++); // P //XXX strTmp.Format(_T(" Precision <P> = %u"),m_nSofPrecision_P); strTmp.Format(_T(" Precision = %u"),m_nSofPrecision_P); m_pLog->AddLine(strTmp); if (!ValidateValue(m_nSofPrecision_P,2,16,_T("Precision <P>"),true,8)) return DECMARK_ERR; m_nSofNumLines_Y = Buf(m_nPos)*256 + Buf(m_nPos+1); // Y m_nPos += 2; //XXX strTmp.Format(_T(" Number of Lines <Y> = %u"),m_nSofNumLines_Y); strTmp.Format(_T(" Number of Lines = %u"),m_nSofNumLines_Y); m_pLog->AddLine(strTmp); if (!ValidateValue(m_nSofNumLines_Y,0,65535,_T("Number of Lines <Y>"),true,0)) return DECMARK_ERR; m_nSofSampsPerLine_X = Buf(m_nPos)*256 + Buf(m_nPos+1); // X m_nPos += 2; //XXX strTmp.Format(_T(" Samples per Line <X> = %u"),m_nSofSampsPerLine_X); strTmp.Format(_T(" Samples per Line = %u"),m_nSofSampsPerLine_X); m_pLog->AddLine(strTmp); if (!ValidateValue(m_nSofSampsPerLine_X,1,65535,_T("Samples per Line <X>"),true,1)) return DECMARK_ERR; strTmp.Format(_T(" Image Size = %u x %u"),m_nSofSampsPerLine_X,m_nSofNumLines_Y); m_pLog->AddLine(strTmp); // Determine orientation // m_nSofSampsPerLine_X = X // m_nSofNumLines_Y = Y m_eImgLandscape = ENUM_LANDSCAPE_YES; if (m_nSofNumLines_Y > m_nSofSampsPerLine_X) m_eImgLandscape = ENUM_LANDSCAPE_NO; strTmp.Format(_T(" Raw Image Orientation = %s"),(m_eImgLandscape==ENUM_LANDSCAPE_YES)?_T("Landscape"):_T("Portrait")); m_pLog->AddLine(strTmp); m_nSofNumComps_Nf = Buf(m_nPos++); // Nf, range 1..255 //XXX strTmp.Format(_T(" Number of Img components <Nf> = %u"),m_nSofNumComps_Nf); strTmp.Format(_T(" Number of Img components = %u"),m_nSofNumComps_Nf); m_pLog->AddLine(strTmp); if (!ValidateValue(m_nSofNumComps_Nf,1,255,_T("Number of Img components <Nf>"),true,1)) return DECMARK_ERR; unsigned nCompIdent; unsigned anSofSampFact[MAX_SOF_COMP_NF]; m_nSofHorzSampFactMax_Hmax = 0; m_nSofVertSampFactMax_Vmax = 0; // Now clear the output image content (all components) // TODO: Migrate some of the bitmap allocation / clearing from // DecodeScanImg() into ResetImageContent() and call here //m_pImgDec->ResetImageContent(); // Per JFIF v1.02: // - Nf = 1 or 3 // - C1 = Y // - C2 = Cb // - C3 = Cr for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = Buf(m_nPos++); // Ci, range 0..255 m_anSofQuantCompId[nCompInd] = nCompIdent; //if (!ValidateValue(m_anSofQuantCompId[nCompInd],0,255,_T("Component ID <Ci>"),true,0)) return DECMARK_ERR; anSofSampFact[nCompIdent] = Buf(m_nPos++); m_anSofQuantTblSel_Tqi[nCompIdent] = Buf(m_nPos++); // Tqi, range 0..3 //if (!ValidateValue(m_anSofQuantTblSel_Tqi[nCompIdent],0,3,_T("Table Destination ID <Tqi>"),true,0)) return DECMARK_ERR; // NOTE: We protect against bad input here as replication ratios are // determined later that depend on dividing by sampling factor (hence // possibility of div by 0). m_anSofHorzSampFact_Hi[nCompIdent] = (anSofSampFact[nCompIdent] & 0xF0) >> 4; // Hi, range 1..4 m_anSofVertSampFact_Vi[nCompIdent] = (anSofSampFact[nCompIdent] & 0x0F); // Vi, range 1..4 if (!ValidateValue(m_anSofHorzSampFact_Hi[nCompIdent],1,4,_T("Horizontal Sampling Factor <Hi>"),true,1)) return DECMARK_ERR; if (!ValidateValue(m_anSofVertSampFact_Vi[nCompIdent],1,4,_T("Vertical Sampling Factor <Vi>"),true,1)) return DECMARK_ERR; } // Calculate max sampling factors for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = m_anSofQuantCompId[nCompInd]; // Calculate maximum sampling factor for the SOF. This is only // used for later generation of m_strImgQuantCss an the SOF // reporting below. The CimgDecode block is responsible for // calculating the maximum sampling factor on a per-scan basis. m_nSofHorzSampFactMax_Hmax = max(m_nSofHorzSampFactMax_Hmax,m_anSofHorzSampFact_Hi[nCompIdent]); m_nSofVertSampFactMax_Vmax = max(m_nSofVertSampFactMax_Vmax,m_anSofVertSampFact_Vi[nCompIdent]); } // Report per-component sampling factors and quantization table selectors for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = m_anSofQuantCompId[nCompInd]; // Create subsampling ratio // - Protect against division-by-zero CString strSubsampH = _T("?"); CString strSubsampV = _T("?"); if (m_anSofHorzSampFact_Hi[nCompIdent] > 0) { strSubsampH.Format(_T("%u"),m_nSofHorzSampFactMax_Hmax/m_anSofHorzSampFact_Hi[nCompIdent]); } if (m_anSofVertSampFact_Vi[nCompIdent] > 0) { strSubsampV.Format(_T("%u"),m_nSofVertSampFactMax_Vmax/m_anSofVertSampFact_Vi[nCompIdent]); } strFull.Format(_T(" Component[%u]: "),nCompInd); // Note i in Ci is 1-based //XXX strTmp.Format(_T("ID=0x%02X, Samp Fac <Hi,Vi>=0x%02X (Subsamp %u x %u), Quant Tbl Sel <Tqi>=0x%02X"), strTmp.Format(_T("ID=0x%02X, Samp Fac=0x%02X (Subsamp %s x %s), Quant Tbl Sel=0x%02X"), nCompIdent,anSofSampFact[nCompIdent], (LPCTSTR)strSubsampH,(LPCTSTR)strSubsampV, m_anSofQuantTblSel_Tqi[nCompIdent]); strFull += strTmp; // Mapping from component index (not ID) to colour channel per JFIF if (m_nSofNumComps_Nf == 1) { // Assume grayscale strFull += _T(" (Lum: Y)"); } else if (m_nSofNumComps_Nf == 3) { // Assume YCC if (nCompInd == SCAN_COMP_Y) { strFull += _T(" (Lum: Y)"); } else if (nCompInd == SCAN_COMP_CB) { strFull += _T(" (Chrom: Cb)"); } else if (nCompInd == SCAN_COMP_CR) { strFull += _T(" (Chrom: Cr)"); } } else if (m_nSofNumComps_Nf == 4) { // Assume YCCK if (nCompInd == 1) { strFull += _T(" (Y)"); } else if (nCompInd == 2) { strFull += _T(" (Cb)"); } else if (nCompInd == 3) { strFull += _T(" (Cr)"); } else if (nCompInd == 4) { strFull += _T(" (K)"); } } else { strFull += _T(" (???)"); // Unknown } m_pLog->AddLine(strFull); } // Test for bad input, clean up if bad for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = m_anSofQuantCompId[nCompInd]; if (!ValidateValue(m_anSofQuantCompId[nCompInd],0,255,_T("Component ID <Ci>"),true,0)) return DECMARK_ERR; if (!ValidateValue(m_anSofQuantTblSel_Tqi[nCompIdent],0,3,_T("Table Destination ID <Tqi>"),true,0)) return DECMARK_ERR; if (!ValidateValue(m_anSofHorzSampFact_Hi[nCompIdent],1,4,_T("Horizontal Sampling Factor <Hi>"),true,1)) return DECMARK_ERR; if (!ValidateValue(m_anSofVertSampFact_Vi[nCompIdent],1,4,_T("Vertical Sampling Factor <Vi>"),true,1)) return DECMARK_ERR; } // Finally, assign the cleaned values to the decoder for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = m_anSofQuantCompId[nCompInd]; // Store the DQT Table selection for the Image Decoder // Param values: Nf,Tqi // Param ranges: 1..255,0..3 // Note that the Image Decoder doesn't need to see the Component Identifiers bRet = m_pImgDec->SetDqtTables(nCompInd,m_anSofQuantTblSel_Tqi[nCompIdent]); DecodeErrCheck(bRet); // Store the Precision (to handle 12-bit decode) m_pImgDec->SetPrecision(m_nSofPrecision_P); } if (!m_bStateAbort) { // Set the component sampling factors (chroma subsampling) // FIXME: check ranging for (unsigned nCompInd=1;nCompInd<=m_nSofNumComps_Nf;nCompInd++) { // nCompInd is component index (1...Nf) // nCompIdent is Component Identifier (Ci) // Note that the Image Decoder doesn't need to see the Component Identifiers nCompIdent = m_anSofQuantCompId[nCompInd]; m_pImgDec->SetSofSampFactors(nCompInd,m_anSofHorzSampFact_Hi[nCompIdent],m_anSofVertSampFact_Vi[nCompIdent]); } // Now mark the image as been somewhat OK (ie. should // also be suitable for EmbeddedThumb() and PrepareSignature() m_bImgOK = true; m_bStateSofOk = true; } if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_COM: // COM nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); m_nPos+=2; strTmp.Format(_T(" Comment length = %u"),nLength); m_pLog->AddLine(strTmp); // Check for JPEG COM vulnerability // http://marc.info/?l=bugtraq&m=109524346729948 // Note that the recovery is not very graceful. It will assume that the // field is actually zero-length, which will make the next byte trigger the // "Expected marker 0xFF" error message and probably abort. There is no // obvious way to if ( (nLength == 0) || (nLength == 1) ) { strTmp.Format(_T(" JPEG Comment Field Vulnerability detected!")); m_pLog->AddLineErr(strTmp); strTmp.Format(_T(" Skipping data until next marker...")); m_pLog->AddLineErr(strTmp); nLength = 2; bool bDoneSearch = false; unsigned nSkipStart = m_nPos; while (!bDoneSearch) { if (Buf(m_nPos) != 0xFF) { m_nPos++; } else { bDoneSearch = true; } if (m_nPos >= m_pWBuf->GetPosEof()) { bDoneSearch = true; } } strTmp.Format(_T(" Skipped %u bytes"),m_nPos - nSkipStart); m_pLog->AddLineErr(strTmp); // Break out of case statement break; } // Assume COM field valid length (ie. >= 2) strFull = _T(" Comment="); m_strComment = _T(""); for (unsigned ind=0;ind<nLength-2;ind++) { nTmpVal = Buf(m_nPos++); if (_istprint(nTmpVal)) { strTmp.Format(_T("%c"),nTmpVal); m_strComment += strTmp; } else { m_strComment += _T("."); } } strFull += m_strComment; m_pLog->AddLine(strFull); break; case JFIF_DHT: // DHT m_bStateDht = true; DecodeDHT(false); m_bStateDhtOk = true; break; case JFIF_SOS: // SOS unsigned long nPosScanStart; // Byte count at start of scan data segment m_bStateSos = true; // NOTE: Only want to capture position of first SOS // This should make other function such as AVI frame extract // more robust in case we get multiple SOS segments. // We assume that this value is reset when we start a new decode if (m_nPosSos == 0) { m_nPosSos = m_nPos-2; // Used for Extract. Want to include actual marker } nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); m_nPos+=2; // Ensure that we have seen proper markers before we try this one! if (!m_bStateSofOk) { strTmp.Format(_T(" ERROR: SOS before valid SOF defined")); m_pLog->AddLineErr(strTmp); return DECMARK_ERR; } strTmp.Format(_T(" Scan header length = %u"),nLength); m_pLog->AddLine(strTmp); m_nSosNumCompScan_Ns = Buf(m_nPos++); // Ns, range 1..4 //XXX strTmp.Format(_T(" Number of image components <Ns> = %u"),m_nSosNumCompScan_Ns); strTmp.Format(_T(" Number of img components = %u"),m_nSosNumCompScan_Ns); m_pLog->AddLine(strTmp); // Just in case something got corrupted, don't want to get out // of range here. Note that this will be a hard abort, and // will not resume decoding. if (m_nSosNumCompScan_Ns > MAX_SOS_COMP_NS) { strTmp.Format(_T(" ERROR: Scan decode does not support > %u components"),MAX_SOS_COMP_NS); m_pLog->AddLineErr(strTmp); return DECMARK_ERR; } unsigned nSosCompSel_Cs; unsigned nSosHuffTblSel; unsigned nSosHuffTblSelDc_Td; unsigned nSosHuffTblSelAc_Ta; // Max range of components indices is between 1..4 for (unsigned int nScanCompInd=1;((nScanCompInd<=m_nSosNumCompScan_Ns) && (!m_bStateAbort));nScanCompInd++) { strFull.Format(_T(" Component[%u]: "),nScanCompInd); nSosCompSel_Cs = Buf(m_nPos++); // Cs, range 0..255 nSosHuffTblSel = Buf(m_nPos++); nSosHuffTblSelDc_Td = (nSosHuffTblSel & 0xf0)>>4; // Td, range 0..3 nSosHuffTblSelAc_Ta = (nSosHuffTblSel & 0x0f); // Ta, range 0..3 strTmp.Format(_T("selector=0x%02X, table=%u(DC),%u(AC)"),nSosCompSel_Cs,nSosHuffTblSelDc_Td,nSosHuffTblSelAc_Ta); strFull += strTmp; m_pLog->AddLine(strFull); bRet = m_pImgDec->SetDhtTables(nScanCompInd,nSosHuffTblSelDc_Td,nSosHuffTblSelAc_Ta); DecodeErrCheck(bRet); } m_nSosSpectralStart_Ss = Buf(m_nPos++); m_nSosSpectralEnd_Se = Buf(m_nPos++); m_nSosSuccApprox_A = Buf(m_nPos++); strTmp.Format(_T(" Spectral selection = %u .. %u"),m_nSosSpectralStart_Ss,m_nSosSpectralEnd_Se); m_pLog->AddLine(strTmp); strTmp.Format(_T(" Successive approximation = 0x%02X"),m_nSosSuccApprox_A); m_pLog->AddLine(strTmp); if (m_pAppConfig->bOutputScanDump) { m_pLog->AddLine(_T("")); m_pLog->AddLine(_T(" Scan Data: (after bitstuff removed)")); } // Save the scan data segment position nPosScanStart = m_nPos; // Skip over the Scan Data segment // Pass 1) Quick, allowing for bOutputScanDump to dump first 640B. // Pass 2) If bDecodeScanImg, we redo the process but in detail decoding. // FIXME: Not sure why, but if I skip over Pass 1 (eg if I leave in the // following line uncommented), then I get an error at the end of the // pass 2 decode (indicating that EOI marker not seen, and expecting // marker). // if (m_pAppConfig->bOutputScanDump) { // --- PASS 1 --- bool bSkipDone; unsigned nSkipCount; unsigned nSkipData; unsigned nSkipPos; bool bScanDumpTrunc; bSkipDone = false; nSkipCount = 0; nSkipPos = 0; bScanDumpTrunc = FALSE; strFull = _T(""); while (!bSkipDone) { nSkipCount++; nSkipPos++; nSkipData = Buf(m_nPos++); if (nSkipData == 0xFF) { // this could either be a marker or a byte stuff nSkipData = Buf(m_nPos++); nSkipCount++; if (nSkipData == 0x00) { // Byte stuff nSkipData = 0xFF; } else if ((nSkipData >= JFIF_RST0) && (nSkipData <= JFIF_RST7)) { // Skip over } else { // Marker bSkipDone = true; m_nPos -= 2; } } if (m_pAppConfig->bOutputScanDump && (!bSkipDone) ) { // Only display 20 lines of scan data if (nSkipPos > 640) { if (!bScanDumpTrunc) { m_pLog->AddLineWarn(_T(" WARNING: Dump truncated.")); bScanDumpTrunc = TRUE; } } else { if ( ((nSkipPos-1) == 0) || (((nSkipPos-1) % 32) == 0) ) { strFull = _T(" "); } strTmp.Format(_T("%02x "),nSkipData); strFull += strTmp; if (((nSkipPos-1) % 32) == 31) { m_pLog->AddLine(strFull); strFull = _T(""); } } } // Did we run out of bytes? // FIXME: // NOTE: This line here doesn't allow us to attempt to // decode images that are missing EOI. Maybe this is // not the best solution here? Instead, we should be // checking m_nPos against file length? .. and not // return but "break". if (!m_pWBuf->GetBufOk()) { strTmp.Format(_T("ERROR: Ran out of buffer before EOI during phase 1 of Scan decode @ 0x%08X"),m_nPos); m_pLog->AddLineErr(strTmp); break; } } m_pLog->AddLine(strFull); // } // --- PASS 2 --- // If the option is set, start parsing! if (m_pAppConfig->bDecodeScanImg && m_bImgSofUnsupported) { // SOF marker was of type we don't support, so skip decoding m_pLog->AddLineWarn(_T(" NOTE: Scan parsing doesn't support this SOF mode.")); #ifndef DEBUG_YCCK } else if (m_pAppConfig->bDecodeScanImg && (m_nSofNumComps_Nf == 4)) { m_pLog->AddLineWarn(_T(" NOTE: Scan parsing doesn't support CMYK files yet.")); #endif } else if (m_pAppConfig->bDecodeScanImg && !m_bImgSofUnsupported) { if (!m_bStateSofOk) { m_pLog->AddLineWarn(_T(" NOTE: Scan decode disabled as SOF not decoded.")); } else if (!m_bStateDqtOk) { m_pLog->AddLineWarn(_T(" NOTE: Scan decode disabled as DQT not decoded.")); } else if (!m_bStateDhtOk) { m_pLog->AddLineWarn(_T(" NOTE: Scan decode disabled as DHT not decoded.")); } else { m_pLog->AddLine(_T("")); // Set the primary image details m_pImgDec->SetImageDetails(m_nSofSampsPerLine_X,m_nSofNumLines_Y, m_nSofNumComps_Nf,m_nSosNumCompScan_Ns,m_nImgRstEn,m_nImgRstInterval); // Only recalculate the scan decoding if we need to (i.e. file // changed, offset changed, scan option changed) // TODO: In order to decode multiple scans, we will need to alter the // way that m_pImgSrcDirty is set if (m_pImgSrcDirty) { m_pImgDec->DecodeScanImg(nPosScanStart,true,false); m_pImgSrcDirty = false; } } } m_bStateSosOk = true; break; case JFIF_DRI: unsigned nVal; nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); strTmp.Format(_T(" Length = %u"),nLength); m_pLog->AddLine(strTmp); nVal = Buf(m_nPos+2)*256 + Buf(m_nPos+3); // According to ITU-T spec B.2.4.4, we only expect // restart markers if DRI value is non-zero! m_nImgRstInterval = nVal; if (nVal != 0) { m_nImgRstEn = true; } else { m_nImgRstEn = false; } strTmp.Format(_T(" interval = %u"),m_nImgRstInterval); m_pLog->AddLine(strTmp); m_nPos += 4; if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_EOI: // EOI m_pLog->AddLine(_T("")); // Save the EOI file position // NOTE: If the file is missing the EOI, then this variable will be // set to mark the end of file. m_nPosEmbedEnd = m_nPos; m_nPosEoi = m_nPos; m_bStateEoi = true; return DECMARK_EOI; break; // Markers that are not yet supported in JPEGsnoop case JFIF_DHP: // Markers defined for future use / extensions case JFIF_JPG: case JFIF_JPG0: case JFIF_JPG1: case JFIF_JPG2: case JFIF_JPG3: case JFIF_JPG4: case JFIF_JPG5: case JFIF_JPG6: case JFIF_JPG7: case JFIF_JPG8: case JFIF_JPG9: case JFIF_JPG10: case JFIF_JPG11: case JFIF_JPG12: case JFIF_JPG13: case JFIF_TEM: // Unsupported marker // - Provide generic decode based on length nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Length strTmp.Format(_T(" Header length = %u"),nLength); m_pLog->AddLine(strTmp); m_pLog->AddLineWarn(_T(" Skipping unsupported marker")); m_nPos += nLength; break; case JFIF_RST0: case JFIF_RST1: case JFIF_RST2: case JFIF_RST3: case JFIF_RST4: case JFIF_RST5: case JFIF_RST6: case JFIF_RST7: // We don't expect to see restart markers outside the entropy coded segment. // NOTE: RST# are standalone markers, so no length indicator exists // But for the sake of robustness, we can check here to see if treating // as a standalone marker will arrive at another marker (ie. OK). If not, // proceed to assume there is a length indicator. strTmp.Format(_T(" WARNING: Restart marker [0xFF%02X] detected outside scan"),nCode); m_pLog->AddLineWarn(strTmp); if (!m_pAppConfig->bRelaxedParsing) { // Abort m_pLog->AddLineErr(_T(" Stopping decode")); m_pLog->AddLine(_T(" Use [Img Search Fwd/Rev] to locate other valid embedded JPEGs")); return DECMARK_ERR; } else { // Ignore // Check to see if standalone marker treatment looks OK if (Buf(m_nPos+2) == 0xFF) { // Looks like standalone m_pLog->AddLineWarn(_T(" Ignoring standalone marker. Proceeding with decode.")); m_nPos += 2; } else { // Looks like marker with length nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); strTmp.Format(_T(" Header length = %u"),nLength); m_pLog->AddLine(strTmp); m_pLog->AddLineWarn(_T(" Skipping marker")); m_nPos += nLength; } } break; default: strTmp.Format(_T(" WARNING: Unknown marker [0xFF%02X]"),nCode); m_pLog->AddLineWarn(strTmp); if (!m_pAppConfig->bRelaxedParsing) { // Abort m_pLog->AddLineErr(_T(" Stopping decode")); m_pLog->AddLine(_T(" Use [Img Search Fwd/Rev] to locate other valid embedded JPEGs")); return DECMARK_ERR; } else { // Skip nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); strTmp.Format(_T(" Header length = %u"),nLength); m_pLog->AddLine(strTmp); m_pLog->AddLineWarn(_T(" Skipping marker")); m_nPos += nLength; } } // Add white-space between each marker m_pLog->AddLine(_T(" ")); // If we decided to abort for any reason, make sure we trap it now. // This will stop the ProcessFile() while loop. We can set m_bStateAbort // if user says that they want to stop. if (m_bStateAbort) { return DECMARK_ERR; } return DECMARK_OK; }
124,451,953,334,289,280,000,000,000,000,000,000,000
None
null
[ "CWE-369" ]
CVE-2017-1000414
ImpulseAdventure JPEGsnoop version 1.7.5 is vulnerable to a division by zero in the JFIF decode handling resulting denial of service.
https://nvd.nist.gov/vuln/detail/CVE-2017-1000414
217,206
libofx
a70934eea95c76a7737b83773bffe8738935082d
https://github.com/libofx/libofx
https://github.com/libofx/libofx/commit/a70934eea95c76a7737b83773bffe8738935082d
Fix a buffer overflow. This is only the minimum workaround to prevent buffer overflow: Stop iterating once the (fixed!) size of the output buffers is reached. In response to https://www.talosintelligence.com/vulnerability_reports/TALOS-2017-0317 However, this code is a huge mess anyway and is in no way anything like up-to-date C++ code. Please, anyone, replace it with something more modern. Thanks.
1
string sanitize_proprietary_tags(string input_string) { unsigned int i; size_t input_string_size; bool strip = false; bool tag_open = false; int tag_open_idx = 0; //Are we within < > ? bool closing_tag_open = false; //Are we within </ > ? int orig_tag_open_idx = 0; bool proprietary_tag = false; //Are we within a proprietary element? bool proprietary_closing_tag = false; int crop_end_idx = 0; char buffer[READ_BUFFER_SIZE] = ""; char tagname[READ_BUFFER_SIZE] = ""; int tagname_idx = 0; char close_tagname[READ_BUFFER_SIZE] = ""; for (i = 0; i < READ_BUFFER_SIZE; i++) { buffer[i] = 0; tagname[i] = 0; close_tagname[i] = 0; } input_string_size = input_string.size(); for (i = 0; i < input_string_size; i++) { if (input_string.c_str()[i] == '<') { tag_open = true; tag_open_idx = i; if (proprietary_tag == true && input_string.c_str()[i+1] == '/') { //We are now in a closing tag closing_tag_open = true; //cout<<"Comparaison: "<<tagname<<"|"<<&(input_string.c_str()[i+2])<<"|"<<strlen(tagname)<<endl; if (strncmp(tagname, &(input_string.c_str()[i+2]), strlen(tagname)) != 0) { //If it is the begining of an other tag //cout<<"DIFFERENT!"<<endl; crop_end_idx = i - 1; strip = true; } else { //Otherwise, it is the start of the closing tag of the proprietary tag proprietary_closing_tag = true; } } else if (proprietary_tag == true) { //It is the start of a new tag, following a proprietary tag crop_end_idx = i - 1; strip = true; } } else if (input_string.c_str()[i] == '>') { tag_open = false; closing_tag_open = false; tagname[tagname_idx] = 0; tagname_idx = 0; if (proprietary_closing_tag == true) { crop_end_idx = i; strip = true; } } else if (tag_open == true && closing_tag_open == false) { if (input_string.c_str()[i] == '.') { if (proprietary_tag != true) { orig_tag_open_idx = tag_open_idx; proprietary_tag = true; } } tagname[tagname_idx] = input_string.c_str()[i]; tagname_idx++; } //cerr <<i<<endl; if (strip == true && orig_tag_open_idx < input_string.size()) { input_string.copy(buffer, (crop_end_idx - orig_tag_open_idx) + 1, orig_tag_open_idx); message_out(INFO, "sanitize_proprietary_tags() (end tag or new tag) removed: " + string(buffer)); input_string.erase(orig_tag_open_idx, (crop_end_idx - orig_tag_open_idx) + 1); i = orig_tag_open_idx - 1; proprietary_tag = false; proprietary_closing_tag = false; closing_tag_open = false; tag_open = false; strip = false; input_string_size = input_string.size(); } }//end for if (proprietary_tag == true && orig_tag_open_idx < input_string.size()) { if (crop_end_idx == 0) //no closing tag { crop_end_idx = input_string.size() - 1; } input_string.copy(buffer, (crop_end_idx - orig_tag_open_idx) + 1, orig_tag_open_idx); message_out(INFO, "sanitize_proprietary_tags() (end of line) removed: " + string(buffer)); input_string.erase(orig_tag_open_idx, (crop_end_idx - orig_tag_open_idx) + 1); input_string_size = input_string.size(); } return input_string; }
170,627,852,305,112,900,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-2920
An memory corruption vulnerability exists in the .SVG parsing functionality of Computerinsel Photoline 20.02. A specially crafted .SVG file can cause a vulnerability resulting in memory corruption, which can potentially lead to arbitrary code execution. An attacker can send a specific .SVG file to trigger this vulnerability.
https://nvd.nist.gov/vuln/detail/CVE-2017-2920
518,533
libofx
a70934eea95c76a7737b83773bffe8738935082d
https://github.com/libofx/libofx
https://github.com/libofx/libofx/commit/a70934eea95c76a7737b83773bffe8738935082d
Fix a buffer overflow. This is only the minimum workaround to prevent buffer overflow: Stop iterating once the (fixed!) size of the output buffers is reached. In response to https://www.talosintelligence.com/vulnerability_reports/TALOS-2017-0317 However, this code is a huge mess anyway and is in no way anything like up-to-date C++ code. Please, anyone, replace it with something more modern. Thanks.
0
string sanitize_proprietary_tags(string input_string) { unsigned int i; bool strip = false; bool tag_open = false; int tag_open_idx = 0; //Are we within < > ? bool closing_tag_open = false; //Are we within </ > ? int orig_tag_open_idx = 0; bool proprietary_tag = false; //Are we within a proprietary element? bool proprietary_closing_tag = false; int crop_end_idx = 0; char buffer[READ_BUFFER_SIZE] = ""; char tagname[READ_BUFFER_SIZE] = ""; int tagname_idx = 0; char close_tagname[READ_BUFFER_SIZE] = ""; for (i = 0; i < READ_BUFFER_SIZE; i++) { buffer[i] = 0; tagname[i] = 0; close_tagname[i] = 0; } size_t input_string_size = input_string.size(); // Minimum workaround to prevent buffer overflow: Stop iterating // once the (fixed!) size of the output buffers is reached. In // response to // https://www.talosintelligence.com/vulnerability_reports/TALOS-2017-0317 // // However, this code is a huge mess anyway and is in no way // anything like up-to-date C++ code. Please, anyone, replace it // with something more modern. Thanks. - cstim, 2017-09-17. for (i = 0; i < std::min(input_string_size, size_t(READ_BUFFER_SIZE)); i++) { if (input_string.c_str()[i] == '<') { tag_open = true; tag_open_idx = i; if (proprietary_tag == true && input_string.c_str()[i+1] == '/') { //We are now in a closing tag closing_tag_open = true; //cout<<"Comparaison: "<<tagname<<"|"<<&(input_string.c_str()[i+2])<<"|"<<strlen(tagname)<<endl; if (strncmp(tagname, &(input_string.c_str()[i+2]), strlen(tagname)) != 0) { //If it is the begining of an other tag //cout<<"DIFFERENT!"<<endl; crop_end_idx = i - 1; strip = true; } else { //Otherwise, it is the start of the closing tag of the proprietary tag proprietary_closing_tag = true; } } else if (proprietary_tag == true) { //It is the start of a new tag, following a proprietary tag crop_end_idx = i - 1; strip = true; } } else if (input_string.c_str()[i] == '>') { tag_open = false; closing_tag_open = false; tagname[tagname_idx] = 0; tagname_idx = 0; if (proprietary_closing_tag == true) { crop_end_idx = i; strip = true; } } else if (tag_open == true && closing_tag_open == false) { if (input_string.c_str()[i] == '.') { if (proprietary_tag != true) { orig_tag_open_idx = tag_open_idx; proprietary_tag = true; } } tagname[tagname_idx] = input_string.c_str()[i]; tagname_idx++; } //cerr <<i<<endl; if (strip == true && orig_tag_open_idx < input_string.size()) { input_string.copy(buffer, (crop_end_idx - orig_tag_open_idx) + 1, orig_tag_open_idx); message_out(INFO, "sanitize_proprietary_tags() (end tag or new tag) removed: " + string(buffer)); input_string.erase(orig_tag_open_idx, (crop_end_idx - orig_tag_open_idx) + 1); i = orig_tag_open_idx - 1; proprietary_tag = false; proprietary_closing_tag = false; closing_tag_open = false; tag_open = false; strip = false; input_string_size = input_string.size(); } }//end for if (proprietary_tag == true && orig_tag_open_idx < input_string.size()) { if (crop_end_idx == 0) //no closing tag { crop_end_idx = input_string.size() - 1; } input_string.copy(buffer, (crop_end_idx - orig_tag_open_idx) + 1, orig_tag_open_idx); message_out(INFO, "sanitize_proprietary_tags() (end of line) removed: " + string(buffer)); input_string.erase(orig_tag_open_idx, (crop_end_idx - orig_tag_open_idx) + 1); input_string_size = input_string.size(); } return input_string; }
296,383,376,717,599,540,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-2920
An memory corruption vulnerability exists in the .SVG parsing functionality of Computerinsel Photoline 20.02. A specially crafted .SVG file can cause a vulnerability resulting in memory corruption, which can potentially lead to arbitrary code execution. An attacker can send a specific .SVG file to trigger this vulnerability.
https://nvd.nist.gov/vuln/detail/CVE-2017-2920
217,217
iortcw
11a83410153756ae350a82ed41b08d128ff7f998
https://github.com/iortcw/iortcw
https://github.com/iortcw/iortcw/commit/11a83410153756ae350a82ed41b08d128ff7f998
All: Merge some file writing extension checks
1
void Con_Dump_f( void ) { int l, x, i; short *line; fileHandle_t f; int bufferlen; char *buffer; char filename[MAX_QPATH]; if ( Cmd_Argc() != 2 ) { Com_Printf( "usage: condump <filename>\n" ); return; } Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) ); COM_DefaultExtension( filename, sizeof( filename ), ".txt" ); f = FS_FOpenFileWrite( filename ); if ( !f ) { Com_Printf ("ERROR: couldn't open %s.\n", filename); return; } Com_Printf ("Dumped console text to %s.\n", filename ); // skip empty lines for ( l = con.current - con.totallines + 1 ; l <= con.current ; l++ ) { line = con.text + ( l % con.totallines ) * con.linewidth; for ( x = 0 ; x < con.linewidth ; x++ ) if ( ( line[x] & 0xff ) != ' ' ) { break; } if ( x != con.linewidth ) { break; } } #ifdef _WIN32 bufferlen = con.linewidth + 3 * sizeof ( char ); #else bufferlen = con.linewidth + 2 * sizeof ( char ); #endif buffer = Hunk_AllocateTempMemory( bufferlen ); // write the remaining lines buffer[bufferlen-1] = 0; for ( ; l <= con.current ; l++ ) { line = con.text + ( l % con.totallines ) * con.linewidth; for ( i = 0; i < con.linewidth; i++ ) buffer[i] = line[i] & 0xff; for ( x = con.linewidth - 1 ; x >= 0 ; x-- ) { if ( buffer[x] == ' ' ) { buffer[x] = 0; } else { break; } } #ifdef _WIN32 Q_strcat(buffer, bufferlen, "\r\n"); #else Q_strcat(buffer, bufferlen, "\n"); #endif FS_Write( buffer, strlen( buffer ), f ); } Hunk_FreeTempMemory( buffer ); FS_FCloseFile( f ); }
128,730,628,186,736,880,000,000,000,000,000,000,000
None
null
[ "CWE-269" ]
CVE-2017-6903
In ioquake3 before 2017-03-14, the auto-downloading feature has insufficient content restrictions. This also affects Quake III Arena, OpenArena, OpenJK, iortcw, and other id Tech 3 (aka Quake 3 engine) forks. A malicious auto-downloaded file can trigger loading of crafted auto-downloaded files as native code DLLs. A malicious auto-downloaded file can contain configuration defaults that override the user's. Executable bytecode in a malicious auto-downloaded file can set configuration variables to values that will result in unwanted native code DLLs being loaded, resulting in sandbox escape.
https://nvd.nist.gov/vuln/detail/CVE-2017-6903
519,025
iortcw
11a83410153756ae350a82ed41b08d128ff7f998
https://github.com/iortcw/iortcw
https://github.com/iortcw/iortcw/commit/11a83410153756ae350a82ed41b08d128ff7f998
All: Merge some file writing extension checks
0
void Con_Dump_f( void ) { int l, x, i; short *line; fileHandle_t f; int bufferlen; char *buffer; char filename[MAX_QPATH]; if ( Cmd_Argc() != 2 ) { Com_Printf( "usage: condump <filename>\n" ); return; } Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) ); COM_DefaultExtension( filename, sizeof( filename ), ".txt" ); if (!COM_CompareExtension(filename, ".txt")) { Com_Printf("Con_Dump_f: Only the \".txt\" extension is supported by this command!\n"); return; } f = FS_FOpenFileWrite( filename ); if ( !f ) { Com_Printf ("ERROR: couldn't open %s.\n", filename); return; } Com_Printf ("Dumped console text to %s.\n", filename ); // skip empty lines for ( l = con.current - con.totallines + 1 ; l <= con.current ; l++ ) { line = con.text + ( l % con.totallines ) * con.linewidth; for ( x = 0 ; x < con.linewidth ; x++ ) if ( ( line[x] & 0xff ) != ' ' ) { break; } if ( x != con.linewidth ) { break; } } #ifdef _WIN32 bufferlen = con.linewidth + 3 * sizeof ( char ); #else bufferlen = con.linewidth + 2 * sizeof ( char ); #endif buffer = Hunk_AllocateTempMemory( bufferlen ); // write the remaining lines buffer[bufferlen-1] = 0; for ( ; l <= con.current ; l++ ) { line = con.text + ( l % con.totallines ) * con.linewidth; for ( i = 0; i < con.linewidth; i++ ) buffer[i] = line[i] & 0xff; for ( x = con.linewidth - 1 ; x >= 0 ; x-- ) { if ( buffer[x] == ' ' ) { buffer[x] = 0; } else { break; } } #ifdef _WIN32 Q_strcat(buffer, bufferlen, "\r\n"); #else Q_strcat(buffer, bufferlen, "\n"); #endif FS_Write( buffer, strlen( buffer ), f ); } Hunk_FreeTempMemory( buffer ); FS_FCloseFile( f ); }
160,930,453,638,616,710,000,000,000,000,000,000,000
None
null
[ "CWE-269" ]
CVE-2017-6903
In ioquake3 before 2017-03-14, the auto-downloading feature has insufficient content restrictions. This also affects Quake III Arena, OpenArena, OpenJK, iortcw, and other id Tech 3 (aka Quake 3 engine) forks. A malicious auto-downloaded file can trigger loading of crafted auto-downloaded files as native code DLLs. A malicious auto-downloaded file can contain configuration defaults that override the user's. Executable bytecode in a malicious auto-downloaded file can set configuration variables to values that will result in unwanted native code DLLs being loaded, resulting in sandbox escape.
https://nvd.nist.gov/vuln/detail/CVE-2017-6903
217,218
ps-lite
4be817e8b03e7e92517e91f2dfcc50865e91c6ea
https://github.com/dmlc/ps-lite
https://github.com/dmlc/ps-lite/commit/4be817e8b03e7e92517e91f2dfcc50865e91c6ea
Avoid listening on all interfaces by default
1
int Bind(const Node& node, int max_retry) override { receiver_ = zmq_socket(context_, ZMQ_ROUTER); CHECK(receiver_ != NULL) << "create receiver socket failed: " << zmq_strerror(errno); int local = GetEnv("DMLC_LOCAL", 0); std::string addr = local ? "ipc:///tmp/" : "tcp://*:"; int port = node.port; unsigned seed = static_cast<unsigned>(time(NULL)+port); for (int i = 0; i < max_retry+1; ++i) { auto address = addr + std::to_string(port); if (zmq_bind(receiver_, address.c_str()) == 0) break; if (i == max_retry) { port = -1; } else { port = 10000 + rand_r(&seed) % 40000; } } return port; }
27,773,348,298,973,745,000,000,000,000,000,000,000
None
null
[ "CWE-200" ]
CVE-2018-1281
The clustered setup of Apache MXNet allows users to specify which IP address and port the scheduler will listen on via the DMLC_PS_ROOT_URI and DMLC_PS_ROOT_PORT env variables. In versions older than 1.0.0, however, the MXNet framework will listen on 0.0.0.0 rather than user specified DMLC_PS_ROOT_URI once a scheduler node is initialized. This exposes the instance running MXNet to any attackers reachable via the interface they didn't expect to be listening on. For example: If a user wants to run a clustered setup locally, they may specify to run on 127.0.0.1. But since MXNet will listen on 0.0.0.0, it makes the port accessible on all network interfaces.
https://nvd.nist.gov/vuln/detail/CVE-2018-1281
519,035
ps-lite
4be817e8b03e7e92517e91f2dfcc50865e91c6ea
https://github.com/dmlc/ps-lite
https://github.com/dmlc/ps-lite/commit/4be817e8b03e7e92517e91f2dfcc50865e91c6ea
Avoid listening on all interfaces by default
0
int Bind(const Node& node, int max_retry) override { receiver_ = zmq_socket(context_, ZMQ_ROUTER); CHECK(receiver_ != NULL) << "create receiver socket failed: " << zmq_strerror(errno); int local = GetEnv("DMLC_LOCAL", 0); std::string hostname = node.hostname.empty() ? "*" : node.hostname; std::string addr = local ? "ipc:///tmp/" : "tcp://" + hostname + ":"; int port = node.port; unsigned seed = static_cast<unsigned>(time(NULL)+port); for (int i = 0; i < max_retry+1; ++i) { auto address = addr + std::to_string(port); if (zmq_bind(receiver_, address.c_str()) == 0) break; if (i == max_retry) { port = -1; } else { port = 10000 + rand_r(&seed) % 40000; } } return port; }
287,329,875,877,248,700,000,000,000,000,000,000,000
None
null
[ "CWE-200" ]
CVE-2018-1281
The clustered setup of Apache MXNet allows users to specify which IP address and port the scheduler will listen on via the DMLC_PS_ROOT_URI and DMLC_PS_ROOT_PORT env variables. In versions older than 1.0.0, however, the MXNet framework will listen on 0.0.0.0 rather than user specified DMLC_PS_ROOT_URI once a scheduler node is initialized. This exposes the instance running MXNet to any attackers reachable via the interface they didn't expect to be listening on. For example: If a user wants to run a clustered setup locally, they may specify to run on 127.0.0.1. But since MXNet will listen on 0.0.0.0, it makes the port accessible on all network interfaces.
https://nvd.nist.gov/vuln/detail/CVE-2018-1281
217,219
WAVM
2de6cf70c5ef31e22ed119a25ac2daeefd3d18a1
https://github.com/WAVM/WAVM
https://github.com/WAVM/WAVM/commit/2de6cf70c5ef31e22ed119a25ac2daeefd3d18a1
Fix out-of-bounds array access when passing a <4 byte input file to wavm or wavm-compile
1
inline bool loadModule(const char* filename, IR::Module& outModule) { // Read the specified file into an array. std::vector<U8> fileBytes; if(!loadFile(filename, fileBytes)) { return false; } // If the file starts with the WASM binary magic number, load it as a binary irModule. if(*(U32*)fileBytes.data() == 0x6d736100) { return loadBinaryModule(fileBytes.data(), fileBytes.size(), outModule); } else { // Make sure the WAST file is null terminated. fileBytes.push_back(0); // Load it as a text irModule. std::vector<WAST::Error> parseErrors; if(!WAST::parseModule( (const char*)fileBytes.data(), fileBytes.size(), outModule, parseErrors)) { Log::printf(Log::error, "Error parsing WebAssembly text file:\n"); reportParseErrors(filename, parseErrors); return false; } return true; } }
247,635,764,926,562,080,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2018-17292
An issue was discovered in WAVM before 2018-09-16. The loadModule function in Include/Inline/CLI.h lacks checking of the file length before a file magic comparison, allowing attackers to cause a Denial of Service (application crash caused by out-of-bounds read) by crafting a file that has fewer than 4 bytes.
https://nvd.nist.gov/vuln/detail/CVE-2018-17292
519,044
WAVM
2de6cf70c5ef31e22ed119a25ac2daeefd3d18a1
https://github.com/WAVM/WAVM
https://github.com/WAVM/WAVM/commit/2de6cf70c5ef31e22ed119a25ac2daeefd3d18a1
Fix out-of-bounds array access when passing a <4 byte input file to wavm or wavm-compile
0
inline bool loadModule(const char* filename, IR::Module& outModule) { // Read the specified file into an array. std::vector<U8> fileBytes; if(!loadFile(filename, fileBytes)) { return false; } // If the file starts with the WASM binary magic number, load it as a binary irModule. if(fileBytes.size() >= 4 && *(U32*)fileBytes.data() == 0x6d736100) { return loadBinaryModule(fileBytes.data(), fileBytes.size(), outModule); } else { // Make sure the WAST file is null terminated. fileBytes.push_back(0); // Load it as a text irModule. std::vector<WAST::Error> parseErrors; if(!WAST::parseModule( (const char*)fileBytes.data(), fileBytes.size(), outModule, parseErrors)) { Log::printf(Log::error, "Error parsing WebAssembly text file:\n"); reportParseErrors(filename, parseErrors); return false; } return true; } }
226,446,143,927,897,680,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2018-17292
An issue was discovered in WAVM before 2018-09-16. The loadModule function in Include/Inline/CLI.h lacks checking of the file length before a file magic comparison, allowing attackers to cause a Denial of Service (application crash caused by out-of-bounds read) by crafting a file that has fewer than 4 bytes.
https://nvd.nist.gov/vuln/detail/CVE-2018-17292
217,220
WAVM
31d670b6489e6d708c3b04b911cdf14ac43d846d
https://github.com/WAVM/WAVM
https://github.com/WAVM/WAVM/commit/31d670b6489e6d708c3b04b911cdf14ac43d846d
Fix dereferencing null pointer when running wavm with WebAssembly main function that takes command-line arguments but no Emscripten memory to write them to
1
static int run(const CommandLineOptions& options) { IR::Module irModule; // Load the module. if(!loadModule(options.filename, irModule)) { return EXIT_FAILURE; } if(options.onlyCheck) { return EXIT_SUCCESS; } // Compile the module. Runtime::Module* module = nullptr; if(!options.precompiled) { module = Runtime::compileModule(irModule); } else { const UserSection* precompiledObjectSection = nullptr; for(const UserSection& userSection : irModule.userSections) { if(userSection.name == "wavm.precompiled_object") { precompiledObjectSection = &userSection; break; } } if(!precompiledObjectSection) { Log::printf(Log::error, "Input file did not contain 'wavm.precompiled_object' section"); return EXIT_FAILURE; } else { module = Runtime::loadPrecompiledModule(irModule, precompiledObjectSection->data); } } // Link the module with the intrinsic modules. Compartment* compartment = Runtime::createCompartment(); Context* context = Runtime::createContext(compartment); RootResolver rootResolver(compartment); Emscripten::Instance* emscriptenInstance = nullptr; if(options.enableEmscripten) { emscriptenInstance = Emscripten::instantiate(compartment, irModule); if(emscriptenInstance) { rootResolver.moduleNameToInstanceMap.set("env", emscriptenInstance->env); rootResolver.moduleNameToInstanceMap.set("asm2wasm", emscriptenInstance->asm2wasm); rootResolver.moduleNameToInstanceMap.set("global", emscriptenInstance->global); } } if(options.enableThreadTest) { ModuleInstance* threadTestInstance = ThreadTest::instantiate(compartment); rootResolver.moduleNameToInstanceMap.set("threadTest", threadTestInstance); } LinkResult linkResult = linkModule(irModule, rootResolver); if(!linkResult.success) { Log::printf(Log::error, "Failed to link module:\n"); for(auto& missingImport : linkResult.missingImports) { Log::printf(Log::error, "Missing import: module=\"%s\" export=\"%s\" type=\"%s\"\n", missingImport.moduleName.c_str(), missingImport.exportName.c_str(), asString(missingImport.type).c_str()); } return EXIT_FAILURE; } // Instantiate the module. ModuleInstance* moduleInstance = instantiateModule( compartment, module, std::move(linkResult.resolvedImports), options.filename); if(!moduleInstance) { return EXIT_FAILURE; } // Call the module start function, if it has one. FunctionInstance* startFunction = getStartFunction(moduleInstance); if(startFunction) { invokeFunctionChecked(context, startFunction, {}); } if(options.enableEmscripten) { // Call the Emscripten global initalizers. Emscripten::initializeGlobals(context, irModule, moduleInstance); } // Look up the function export to call. FunctionInstance* functionInstance; if(!options.functionName) { functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, "main")); if(!functionInstance) { functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, "_main")); } if(!functionInstance) { Log::printf(Log::error, "Module does not export main function\n"); return EXIT_FAILURE; } } else { functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, options.functionName)); if(!functionInstance) { Log::printf(Log::error, "Module does not export '%s'\n", options.functionName); return EXIT_FAILURE; } } FunctionType functionType = getFunctionType(functionInstance); // Set up the arguments for the invoke. std::vector<Value> invokeArgs; if(!options.functionName) { if(functionType.params().size() == 2) { MemoryInstance* defaultMemory = Runtime::getDefaultMemory(moduleInstance); if(!defaultMemory) { Log::printf( Log::error, "Module does not declare a default memory object to put arguments in.\n"); return EXIT_FAILURE; } std::vector<const char*> argStrings; argStrings.push_back(options.filename); char** args = options.args; while(*args) { argStrings.push_back(*args++); }; Emscripten::injectCommandArgs(emscriptenInstance, argStrings, invokeArgs); } else if(functionType.params().size() > 0) { Log::printf(Log::error, "WebAssembly function requires %" PRIu64 " argument(s), but only 0 or 2 can be passed!", functionType.params().size()); return EXIT_FAILURE; } } else { for(U32 i = 0; options.args[i]; ++i) { Value value; switch(functionType.params()[i]) { case ValueType::i32: value = (U32)atoi(options.args[i]); break; case ValueType::i64: value = (U64)atol(options.args[i]); break; case ValueType::f32: value = (F32)atof(options.args[i]); break; case ValueType::f64: value = atof(options.args[i]); break; case ValueType::v128: case ValueType::anyref: case ValueType::anyfunc: Errors::fatalf("Cannot parse command-line argument for %s function parameter", asString(functionType.params()[i])); default: Errors::unreachable(); } invokeArgs.push_back(value); } } // Invoke the function. Timing::Timer executionTimer; IR::ValueTuple functionResults = invokeFunctionChecked(context, functionInstance, invokeArgs); Timing::logTimer("Invoked function", executionTimer); if(options.functionName) { Log::printf(Log::debug, "%s returned: %s\n", options.functionName, asString(functionResults).c_str()); return EXIT_SUCCESS; } else if(functionResults.size() == 1 && functionResults[0].type == ValueType::i32) { return functionResults[0].i32; } else { return EXIT_SUCCESS; } }
232,153,025,347,729,260,000,000,000,000,000,000,000
None
null
[ "CWE-476" ]
CVE-2018-17293
An issue was discovered in WAVM before 2018-09-16. The run function in Programs/wavm/wavm.cpp does not check whether there is Emscripten memory to store the command-line arguments passed by the input WebAssembly file's main function, which allows attackers to cause a denial of service (application crash by NULL pointer dereference) or possibly have unspecified other impact by crafting certain WebAssembly files.
https://nvd.nist.gov/vuln/detail/CVE-2018-17293
519,050
WAVM
31d670b6489e6d708c3b04b911cdf14ac43d846d
https://github.com/WAVM/WAVM
https://github.com/WAVM/WAVM/commit/31d670b6489e6d708c3b04b911cdf14ac43d846d
Fix dereferencing null pointer when running wavm with WebAssembly main function that takes command-line arguments but no Emscripten memory to write them to
0
static int run(const CommandLineOptions& options) { IR::Module irModule; // Load the module. if(!loadModule(options.filename, irModule)) { return EXIT_FAILURE; } if(options.onlyCheck) { return EXIT_SUCCESS; } // Compile the module. Runtime::Module* module = nullptr; if(!options.precompiled) { module = Runtime::compileModule(irModule); } else { const UserSection* precompiledObjectSection = nullptr; for(const UserSection& userSection : irModule.userSections) { if(userSection.name == "wavm.precompiled_object") { precompiledObjectSection = &userSection; break; } } if(!precompiledObjectSection) { Log::printf(Log::error, "Input file did not contain 'wavm.precompiled_object' section"); return EXIT_FAILURE; } else { module = Runtime::loadPrecompiledModule(irModule, precompiledObjectSection->data); } } // Link the module with the intrinsic modules. Compartment* compartment = Runtime::createCompartment(); Context* context = Runtime::createContext(compartment); RootResolver rootResolver(compartment); Emscripten::Instance* emscriptenInstance = nullptr; if(options.enableEmscripten) { emscriptenInstance = Emscripten::instantiate(compartment, irModule); if(emscriptenInstance) { rootResolver.moduleNameToInstanceMap.set("env", emscriptenInstance->env); rootResolver.moduleNameToInstanceMap.set("asm2wasm", emscriptenInstance->asm2wasm); rootResolver.moduleNameToInstanceMap.set("global", emscriptenInstance->global); } } if(options.enableThreadTest) { ModuleInstance* threadTestInstance = ThreadTest::instantiate(compartment); rootResolver.moduleNameToInstanceMap.set("threadTest", threadTestInstance); } LinkResult linkResult = linkModule(irModule, rootResolver); if(!linkResult.success) { Log::printf(Log::error, "Failed to link module:\n"); for(auto& missingImport : linkResult.missingImports) { Log::printf(Log::error, "Missing import: module=\"%s\" export=\"%s\" type=\"%s\"\n", missingImport.moduleName.c_str(), missingImport.exportName.c_str(), asString(missingImport.type).c_str()); } return EXIT_FAILURE; } // Instantiate the module. ModuleInstance* moduleInstance = instantiateModule( compartment, module, std::move(linkResult.resolvedImports), options.filename); if(!moduleInstance) { return EXIT_FAILURE; } // Call the module start function, if it has one. FunctionInstance* startFunction = getStartFunction(moduleInstance); if(startFunction) { invokeFunctionChecked(context, startFunction, {}); } if(options.enableEmscripten) { // Call the Emscripten global initalizers. Emscripten::initializeGlobals(context, irModule, moduleInstance); } // Look up the function export to call. FunctionInstance* functionInstance; if(!options.functionName) { functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, "main")); if(!functionInstance) { functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, "_main")); } if(!functionInstance) { Log::printf(Log::error, "Module does not export main function\n"); return EXIT_FAILURE; } } else { functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, options.functionName)); if(!functionInstance) { Log::printf(Log::error, "Module does not export '%s'\n", options.functionName); return EXIT_FAILURE; } } FunctionType functionType = getFunctionType(functionInstance); // Set up the arguments for the invoke. std::vector<Value> invokeArgs; if(!options.functionName) { if(functionType.params().size() == 2) { if(!emscriptenInstance) { Log::printf( Log::error, "Module does not declare a default memory object to put arguments in.\n"); return EXIT_FAILURE; } else { std::vector<const char*> argStrings; argStrings.push_back(options.filename); char** args = options.args; while(*args) { argStrings.push_back(*args++); }; wavmAssert(emscriptenInstance); Emscripten::injectCommandArgs(emscriptenInstance, argStrings, invokeArgs); } } else if(functionType.params().size() > 0) { Log::printf(Log::error, "WebAssembly function requires %" PRIu64 " argument(s), but only 0 or 2 can be passed!", functionType.params().size()); return EXIT_FAILURE; } } else { for(U32 i = 0; options.args[i]; ++i) { Value value; switch(functionType.params()[i]) { case ValueType::i32: value = (U32)atoi(options.args[i]); break; case ValueType::i64: value = (U64)atol(options.args[i]); break; case ValueType::f32: value = (F32)atof(options.args[i]); break; case ValueType::f64: value = atof(options.args[i]); break; case ValueType::v128: case ValueType::anyref: case ValueType::anyfunc: Errors::fatalf("Cannot parse command-line argument for %s function parameter", asString(functionType.params()[i])); default: Errors::unreachable(); } invokeArgs.push_back(value); } } // Invoke the function. Timing::Timer executionTimer; IR::ValueTuple functionResults = invokeFunctionChecked(context, functionInstance, invokeArgs); Timing::logTimer("Invoked function", executionTimer); if(options.functionName) { Log::printf(Log::debug, "%s returned: %s\n", options.functionName, asString(functionResults).c_str()); return EXIT_SUCCESS; } else if(functionResults.size() == 1 && functionResults[0].type == ValueType::i32) { return functionResults[0].i32; } else { return EXIT_SUCCESS; } }
71,582,623,173,496,280,000,000,000,000,000,000,000
None
null
[ "CWE-476" ]
CVE-2018-17293
An issue was discovered in WAVM before 2018-09-16. The run function in Programs/wavm/wavm.cpp does not check whether there is Emscripten memory to store the command-line arguments passed by the input WebAssembly file's main function, which allows attackers to cause a denial of service (application crash by NULL pointer dereference) or possibly have unspecified other impact by crafting certain WebAssembly files.
https://nvd.nist.gov/vuln/detail/CVE-2018-17293
217,235
abuild
4f90ce92778d0ee302e288def75591b96a397c8b
https://github.com/sroracle/abuild
https://github.com/sroracle/abuild/commit/4f90ce92778d0ee302e288def75591b96a397c8b
abuild-sudo: don't allow --keys-dir Not allowing --allow-untrusted is obviously a good idea, but it can be trivially bypassed if --keys-dir is allowed: $ abuild-apk add foo-1-r0.apk ERROR: foo-1-r0.apk: UNTRUSTED signature $ abuild-apk --allow-untrusted add foo-1-r0.apk abuild-apk: --allow-untrusted: not allowed option $ cp -rp /etc/apk/keys /tmp/keys $ cp untrusted.pub /tmp/keys $ abuild-apk --keys-dir /tmp/keys add foo-1-r0.apk (1/1) Installing foo (1-r0) OK: 4319 MiB in 806 packages If both --allow-untrusted and --keys-dir are not allowed, then it should no longer be possible for an unprivileged member of the abuild group to add an untrusted package. $ abuild-apk --keys-dir /tmp/keys add foo-1-r0.apk abuild-apk: --keys-dir: not allowed option
1
int main(int argc, const char *argv[]) { struct group *grent; const char *cmd; const char *path; int i; struct passwd *pw; grent = getgrnam(ABUILD_GROUP); if (grent == NULL) errx(1, "%s: Group not found", ABUILD_GROUP); char *name = NULL; pw = getpwuid(getuid()); if (pw) name = pw->pw_name; if (!is_in_group(grent->gr_gid)) { errx(1, "User %s is not a member of group %s\n", name ? name : "(unknown)", ABUILD_GROUP); } if (name == NULL) warnx("Could not find username for uid %d\n", getuid()); setenv("USER", name ?: "", 1); cmd = strrchr(argv[0], '/'); if (cmd) cmd++; else cmd = argv[0]; cmd = strchr(cmd, '-'); if (cmd == NULL) errx(1, "Calling command has no '-'"); cmd++; path = get_command_path(cmd); if (path == NULL) errx(1, "%s: Not a valid subcommand", cmd); /* we dont allow --allow-untrusted option */ for (i = 1; i < argc; i++) if (strcmp(argv[i], "--allow-untrusted") == 0) errx(1, "%s: not allowed option", "--allow-untrusted"); argv[0] = path; /* set our uid to root so bbsuid --install works */ setuid(0); /* set our gid to root so apk commit hooks run with the same gid as for "sudo apk add ..." */ setgid(0); execv(path, (char * const*)argv); perror(path); return 1; }
246,817,719,144,674,770,000,000,000,000,000,000,000
None
null
[ "CWE-264" ]
CVE-2019-12875
Alpine Linux abuild through 3.4.0 allows an unprivileged member of the abuild group to add an untrusted package via a --keys-dir option that causes acceptance of an untrusted signing key.
https://nvd.nist.gov/vuln/detail/CVE-2019-12875
519,115
abuild
4f90ce92778d0ee302e288def75591b96a397c8b
https://github.com/sroracle/abuild
https://github.com/sroracle/abuild/commit/4f90ce92778d0ee302e288def75591b96a397c8b
abuild-sudo: don't allow --keys-dir Not allowing --allow-untrusted is obviously a good idea, but it can be trivially bypassed if --keys-dir is allowed: $ abuild-apk add foo-1-r0.apk ERROR: foo-1-r0.apk: UNTRUSTED signature $ abuild-apk --allow-untrusted add foo-1-r0.apk abuild-apk: --allow-untrusted: not allowed option $ cp -rp /etc/apk/keys /tmp/keys $ cp untrusted.pub /tmp/keys $ abuild-apk --keys-dir /tmp/keys add foo-1-r0.apk (1/1) Installing foo (1-r0) OK: 4319 MiB in 806 packages If both --allow-untrusted and --keys-dir are not allowed, then it should no longer be possible for an unprivileged member of the abuild group to add an untrusted package. $ abuild-apk --keys-dir /tmp/keys add foo-1-r0.apk abuild-apk: --keys-dir: not allowed option
0
int main(int argc, const char *argv[]) { struct group *grent; const char *cmd; const char *path; int i; struct passwd *pw; grent = getgrnam(ABUILD_GROUP); if (grent == NULL) errx(1, "%s: Group not found", ABUILD_GROUP); char *name = NULL; pw = getpwuid(getuid()); if (pw) name = pw->pw_name; if (!is_in_group(grent->gr_gid)) { errx(1, "User %s is not a member of group %s\n", name ? name : "(unknown)", ABUILD_GROUP); } if (name == NULL) warnx("Could not find username for uid %d\n", getuid()); setenv("USER", name ?: "", 1); cmd = strrchr(argv[0], '/'); if (cmd) cmd++; else cmd = argv[0]; cmd = strchr(cmd, '-'); if (cmd == NULL) errx(1, "Calling command has no '-'"); cmd++; path = get_command_path(cmd); if (path == NULL) errx(1, "%s: Not a valid subcommand", cmd); for (i = 1; i < argc; i++) check_option(argv[i]); argv[0] = path; /* set our uid to root so bbsuid --install works */ setuid(0); /* set our gid to root so apk commit hooks run with the same gid as for "sudo apk add ..." */ setgid(0); execv(path, (char * const*)argv); perror(path); return 1; }
293,885,072,328,865,660,000,000,000,000,000,000,000
None
null
[ "CWE-264" ]
CVE-2019-12875
Alpine Linux abuild through 3.4.0 allows an unprivileged member of the abuild group to add an untrusted package via a --keys-dir option that causes acceptance of an untrusted signing key.
https://nvd.nist.gov/vuln/detail/CVE-2019-12875
217,243
elog
993bed4923c88593cc6b1186e0d1b9564994a25a
https://bitbucket.org/ritt/elog
https://bitbucket.org/ritt/elog/commits/993bed4923c88593cc6b1186e0d1b9564994a25a
Serve SVG files as attachments only to avoid XSS vulnerabilities
1
void send_file_direct(char *file_name) { int fh, i, length, delta; char str[MAX_PATH_LENGTH], dir[MAX_PATH_LENGTH], charset[80]; getcwd(dir, sizeof(dir)); fh = open(file_name, O_RDONLY | O_BINARY); if (fh > 0) { lseek(fh, 0, SEEK_END); length = TELL(fh); lseek(fh, 0, SEEK_SET); rsprintf("HTTP/1.1 200 Document follows\r\n"); rsprintf("Server: ELOG HTTP %s-%s\r\n", VERSION, git_revision()); rsprintf("Accept-Ranges: bytes\r\n"); /* set expiration time to one day if no thumbnail */ if (isparam("thumb")) { rsprintf("Pragma: no-cache\r\n"); rsprintf("Cache-control: private, max-age=0, no-cache, no-store\r\n"); } else { rsprintf("Cache-control: public, max-age=86400\r\n"); } if (keep_alive) { rsprintf("Connection: Keep-Alive\r\n"); rsprintf("Keep-Alive: timeout=60, max=10\r\n"); } /* return proper header for file type */ for (i = 0; i < (int) strlen(file_name); i++) str[i] = toupper(file_name[i]); str[i] = 0; for (i = 0; filetype[i].ext[0]; i++) if (chkext(str, filetype[i].ext)) break; if (!getcfg("global", "charset", charset, sizeof(charset))) strcpy(charset, DEFAULT_HTTP_CHARSET); if (filetype[i].ext[0]) { if (strncmp(filetype[i].type, "text", 4) == 0) rsprintf("Content-Type: %s;charset=%s\r\n", filetype[i].type, charset); else rsprintf("Content-Type: %s\r\n", filetype[i].type); } else if (is_ascii(file_name)) rsprintf("Content-Type: text/plain;charset=%s\r\n", charset); else rsprintf("Content-Type: application/octet-stream;charset=%s\r\n", charset); rsprintf("Content-Length: %d\r\n\r\n", length); /* increase return buffer size if file too big */ if (length > return_buffer_size - (int) strlen(return_buffer)) { delta = length - (return_buffer_size - strlen(return_buffer)) + 1000; return_buffer = xrealloc(return_buffer, return_buffer_size + delta); memset(return_buffer + return_buffer_size, 0, delta); return_buffer_size += delta; } return_length = strlen(return_buffer) + length; read(fh, return_buffer + strlen(return_buffer), length); close(fh); } else { char encodedname[256]; show_html_header(NULL, FALSE, "404 Not Found", TRUE, FALSE, NULL, FALSE, 0); rsprintf("<body><h1>Not Found</h1>\r\n"); rsprintf("The requested file <b>"); strencode2(encodedname, file_name, sizeof(encodedname)); if (strchr(file_name, DIR_SEPARATOR)) rsprintf("%s", encodedname); else rsprintf("%s%c%s", dir, DIR_SEPARATOR, encodedname); rsprintf("</b> was not found on this server<p>\r\n"); rsprintf("<hr><address>ELOG version %s</address></body></html>\r\n\r\n", VERSION); return_length = strlen_retbuf; keep_alive = FALSE; } }
336,698,074,074,745,940,000,000,000,000,000,000,000
None
null
[ "CWE-79" ]
CVE-2019-20376
A cross-site scripting (XSS) vulnerability in Electronic Logbook (ELOG) 3.1.4 allows remote attackers to inject arbitrary web script or HTML via a crafted SVG document to elogd.c.
https://nvd.nist.gov/vuln/detail/CVE-2019-20376
519,320
elog
993bed4923c88593cc6b1186e0d1b9564994a25a
https://bitbucket.org/ritt/elog
https://bitbucket.org/ritt/elog/commits/993bed4923c88593cc6b1186e0d1b9564994a25a
Serve SVG files as attachments only to avoid XSS vulnerabilities
0
void send_file_direct(char *file_name) { int fh, i, length, delta; char str[MAX_PATH_LENGTH], dir[MAX_PATH_LENGTH], charset[80]; getcwd(dir, sizeof(dir)); fh = open(file_name, O_RDONLY | O_BINARY); if (fh > 0) { lseek(fh, 0, SEEK_END); length = TELL(fh); lseek(fh, 0, SEEK_SET); rsprintf("HTTP/1.1 200 Document follows\r\n"); rsprintf("Server: ELOG HTTP %s-%s\r\n", VERSION, git_revision()); rsprintf("Accept-Ranges: bytes\r\n"); /* set expiration time to one day if no thumbnail */ if (isparam("thumb")) { rsprintf("Pragma: no-cache\r\n"); rsprintf("Cache-control: private, max-age=0, no-cache, no-store\r\n"); } else { rsprintf("Cache-control: public, max-age=86400\r\n"); } if (keep_alive) { rsprintf("Connection: Keep-Alive\r\n"); rsprintf("Keep-Alive: timeout=60, max=10\r\n"); } /* return proper header for file type */ for (i = 0; i < (int) strlen(file_name); i++) str[i] = toupper(file_name[i]); str[i] = 0; for (i = 0; filetype[i].ext[0]; i++) if (chkext(str, filetype[i].ext)) break; if (!getcfg("global", "charset", charset, sizeof(charset))) strcpy(charset, DEFAULT_HTTP_CHARSET); if (filetype[i].ext[0]) { if (strncmp(filetype[i].type, "text", 4) == 0) rsprintf("Content-Type: %s;charset=%s\r\n", filetype[i].type, charset); else if (strcmp(filetype[i].ext, ".SVG") == 0) { rsprintf("Content-Type: %s\r\n", filetype[i].type); if (strrchr(file_name, '/')) strlcpy(str, strrchr(file_name, '/')+1, sizeof(str)); else strlcpy(str, file_name, sizeof(str)); if (str[6] == '_' && str[13] == '_') rsprintf("Content-Disposition: attachment; filename=\"%s\"\r\n", str+14); else rsprintf("Content-Disposition: attachment; filename=\"%s\"\r\n", str); } else rsprintf("Content-Type: %s\r\n", filetype[i].type); } else if (is_ascii(file_name)) rsprintf("Content-Type: text/plain;charset=%s\r\n", charset); else rsprintf("Content-Type: application/octet-stream;charset=%s\r\n", charset); rsprintf("Content-Length: %d\r\n\r\n", length); /* increase return buffer size if file too big */ if (length > return_buffer_size - (int) strlen(return_buffer)) { delta = length - (return_buffer_size - strlen(return_buffer)) + 1000; return_buffer = xrealloc(return_buffer, return_buffer_size + delta); memset(return_buffer + return_buffer_size, 0, delta); return_buffer_size += delta; } return_length = strlen(return_buffer) + length; read(fh, return_buffer + strlen(return_buffer), length); close(fh); } else { char encodedname[256]; show_html_header(NULL, FALSE, "404 Not Found", TRUE, FALSE, NULL, FALSE, 0); rsprintf("<body><h1>Not Found</h1>\r\n"); rsprintf("The requested file <b>"); strencode2(encodedname, file_name, sizeof(encodedname)); if (strchr(file_name, DIR_SEPARATOR)) rsprintf("%s", encodedname); else rsprintf("%s%c%s", dir, DIR_SEPARATOR, encodedname); rsprintf("</b> was not found on this server<p>\r\n"); rsprintf("<hr><address>ELOG version %s</address></body></html>\r\n\r\n", VERSION); return_length = strlen_retbuf; keep_alive = FALSE; } }
325,071,300,405,512,530,000,000,000,000,000,000,000
None
null
[ "CWE-79" ]
CVE-2019-20376
A cross-site scripting (XSS) vulnerability in Electronic Logbook (ELOG) 3.1.4 allows remote attackers to inject arbitrary web script or HTML via a crafted SVG document to elogd.c.
https://nvd.nist.gov/vuln/detail/CVE-2019-20376
217,247
naviserver
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
https://bitbucket.org/naviserver/naviserver
https://bitbucket.org/naviserver/naviserver/commits/a5c3079f1d8996d5f34c9384a440acf3519ca3bb
fix for bug https://sourceforge.net/p/naviserver/bugs/89/ A negative value provided as chunk encoding length led to a potential crash. A test case for this case was added to the regression test.
1
ChunkedDecode(Request *reqPtr, bool update) { const Tcl_DString *bufPtr; const char *end, *chunkStart; bool success = NS_TRUE; NS_NONNULL_ASSERT(reqPtr != NULL); bufPtr = &reqPtr->buffer; end = bufPtr->string + bufPtr->length; chunkStart = bufPtr->string + reqPtr->chunkStartOff; while (reqPtr->chunkStartOff < (size_t)bufPtr->length) { char *p = strstr(chunkStart, "\r\n"); size_t chunk_length; if (p == NULL) { Ns_Log(DriverDebug, "ChunkedDecode: chunk did not find end-of-line"); success = NS_FALSE; break; } *p = '\0'; chunk_length = (size_t)strtol(chunkStart, NULL, 16); *p = '\r'; if (p + 2 + chunk_length > end) { Ns_Log(DriverDebug, "ChunkedDecode: chunk length past end of buffer"); success = NS_FALSE; break; } if (update) { char *writeBuffer = bufPtr->string + reqPtr->chunkWriteOff; memmove(writeBuffer, p + 2, chunk_length); reqPtr->chunkWriteOff += chunk_length; *(writeBuffer + chunk_length) = '\0'; } reqPtr->chunkStartOff += (size_t)(p - chunkStart) + 4u + chunk_length; chunkStart = bufPtr->string + reqPtr->chunkStartOff; } return success; }
210,559,204,718,292,940,000,000,000,000,000,000,000
None
null
[ "CWE-787" ]
CVE-2020-13111
NaviServer 4.99.4 to 4.99.19 allows denial of service due to the nsd/driver.c ChunkedDecode function not properly validating the length of a chunk. A remote attacker can craft a chunked-transfer request that will result in a negative value being passed to memmove via the size parameter, causing the process to crash.
https://nvd.nist.gov/vuln/detail/CVE-2020-13111
519,503
naviserver
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
https://bitbucket.org/naviserver/naviserver
https://bitbucket.org/naviserver/naviserver/commits/a5c3079f1d8996d5f34c9384a440acf3519ca3bb
fix for bug https://sourceforge.net/p/naviserver/bugs/89/ A negative value provided as chunk encoding length led to a potential crash. A test case for this case was added to the regression test.
0
ChunkedDecode(Request *reqPtr, bool update) { const Tcl_DString *bufPtr; const char *end, *chunkStart; SockState result = SOCK_READY; NS_NONNULL_ASSERT(reqPtr != NULL); bufPtr = &reqPtr->buffer; end = bufPtr->string + bufPtr->length; chunkStart = bufPtr->string + reqPtr->chunkStartOff; while (reqPtr->chunkStartOff < (size_t)bufPtr->length) { char *p = strstr(chunkStart, "\r\n"); long chunkLength; if (p == NULL) { Ns_Log(DriverDebug, "ChunkedDecode: chunk did not find end-of-line"); result = SOCK_MORE; break; } *p = '\0'; chunkLength = strtol(chunkStart, NULL, 16); *p = '\r'; if (chunkLength < 0) { Ns_Log(Warning, "ChunkedDecode: negative chunk length"); result = SOCK_BADREQUEST; break; } *p = '\r'; if (p + 2 + chunkLength > end) { Ns_Log(DriverDebug, "ChunkedDecode: chunk length past end of buffer"); result = SOCK_MORE; break; } if (update) { char *writeBuffer = bufPtr->string + reqPtr->chunkWriteOff; memmove(writeBuffer, p + 2, (size_t)chunkLength); reqPtr->chunkWriteOff += (size_t)chunkLength; *(writeBuffer + chunkLength) = '\0'; } reqPtr->chunkStartOff += (size_t)(p - chunkStart) + 4u + (size_t)chunkLength; chunkStart = bufPtr->string + reqPtr->chunkStartOff; } return result; }
52,143,067,939,071,995,000,000,000,000,000,000,000
None
null
[ "CWE-787" ]
CVE-2020-13111
NaviServer 4.99.4 to 4.99.19 allows denial of service due to the nsd/driver.c ChunkedDecode function not properly validating the length of a chunk. A remote attacker can craft a chunked-transfer request that will result in a negative value being passed to memmove via the size parameter, causing the process to crash.
https://nvd.nist.gov/vuln/detail/CVE-2020-13111
217,250
cbang
1c1dba62bd3e6fa9d0d0c0aa21926043b75382c7
https://github.com/CauldronDevelopmentLLC/cbang
https://github.com/CauldronDevelopmentLLC/cbang/commit/1c1dba62bd3e6fa9d0d0c0aa21926043b75382c7
Don't allow extraction of tar files outside of the target directory, added tar tests
1
std::string TarFileReader::extract(const string &_path) { if (_path.empty()) THROW("path cannot be empty"); if (!hasMore()) THROW("No more tar files"); string path = _path; if (SystemUtilities::isDirectory(path)) path += "/" + getFilename(); LOG_DEBUG(5, "Extracting: " << path); return extract(*SystemUtilities::oopen(path)); }
230,347,907,451,407,680,000,000,000,000,000,000,000
None
null
[ "CWE-22" ]
CVE-2020-15908
tar/TarFileReader.cpp in Cauldron cbang (aka C-Bang or C!) before 1.6.0 allows Directory Traversal during extraction from a TAR archive.
https://nvd.nist.gov/vuln/detail/CVE-2020-15908
519,599
cbang
1c1dba62bd3e6fa9d0d0c0aa21926043b75382c7
https://github.com/CauldronDevelopmentLLC/cbang
https://github.com/CauldronDevelopmentLLC/cbang/commit/1c1dba62bd3e6fa9d0d0c0aa21926043b75382c7
Don't allow extraction of tar files outside of the target directory, added tar tests
0
std::string TarFileReader::extract(const string &_path) { if (_path.empty()) THROW("path cannot be empty"); if (!hasMore()) THROW("No more tar files"); string path = _path; if (SystemUtilities::isDirectory(path)) { path += "/" + getFilename(); // Check that path is under the target directory string a = SystemUtilities::getCanonicalPath(_path); string b = SystemUtilities::getCanonicalPath(path); if (!String::startsWith(b, a)) THROW("Tar path points outside of the extraction directory: " << path); } LOG_DEBUG(5, "Extracting: " << path); switch (getType()) { case NORMAL_FILE: case CONTIGUOUS_FILE: return extract(*SystemUtilities::oopen(path)); case DIRECTORY: SystemUtilities::ensureDirectory(path); break; default: THROW("Unsupported tar file type " << getType()); } return getFilename(); }
313,067,532,887,911,780,000,000,000,000,000,000,000
None
null
[ "CWE-22" ]
CVE-2020-15908
tar/TarFileReader.cpp in Cauldron cbang (aka C-Bang or C!) before 1.6.0 allows Directory Traversal during extraction from a TAR archive.
https://nvd.nist.gov/vuln/detail/CVE-2020-15908
217,251
pdf2json
80bf71f16c804108fd933e267fe31692aaa509b4
https://github.com/flexpaper/pdf2json
https://github.com/flexpaper/pdf2json/commit/80bf71f16c804108fd933e267fe31692aaa509b4
Fix for heap vulnerability
1
void CharCodeToUnicode::addMapping(CharCode code, char *uStr, int n, int offset) { CharCode oldLen, i; Unicode u; char uHex[5]; int j; if (code >= mapLen) { oldLen = mapLen; mapLen = (code + 256) & ~255; map = (Unicode *)greallocn(map, mapLen, sizeof(Unicode)); for (i = oldLen; i < mapLen; ++i) { map[i] = 0; } } if (n <= 4) { if (sscanf(uStr, "%x", &u) != 1) { error(-1, "Illegal entry in ToUnicode CMap"); return; } map[code] = u + offset; } else { if (sMapLen >= sMapSize) { sMapSize = sMapSize + 16; sMap = (CharCodeToUnicodeString *) greallocn(sMap, sMapSize, sizeof(CharCodeToUnicodeString)); } map[code] = 0; sMap[sMapLen].c = code; sMap[sMapLen].len = n / 4; for (j = 0; j < sMap[sMapLen].len && j < maxUnicodeString; ++j) { strncpy(uHex, uStr + j*4, 4); uHex[4] = '\0'; if (sscanf(uHex, "%x", &sMap[sMapLen].u[j]) != 1) { error(-1, "Illegal entry in ToUnicode CMap"); } } sMap[sMapLen].u[sMap[sMapLen].len - 1] += offset; ++sMapLen; } }
19,626,458,378,996,310,000,000,000,000,000,000,000
None
null
[ "CWE-120" ]
CVE-2020-18750
Buffer overflow in pdf2json 0.69 allows local users to execute arbitrary code by converting a crafted PDF file.
https://nvd.nist.gov/vuln/detail/CVE-2020-18750
519,625
pdf2json
80bf71f16c804108fd933e267fe31692aaa509b4
https://github.com/flexpaper/pdf2json
https://github.com/flexpaper/pdf2json/commit/80bf71f16c804108fd933e267fe31692aaa509b4
Fix for heap vulnerability
0
void CharCodeToUnicode::addMapping(CharCode code, char *uStr, int n, int offset) { CharCode oldLen, i; Unicode u; char uHex[5]; int j; if (code >= mapLen) { oldLen = mapLen; mapLen = (code + 256) & ~255; if (unlikely(code >= mapLen)) { error(-1, "Illegal code value in CharCodeToUnicode::addMapping"); return; } else { map = (Unicode *)greallocn(map, mapLen, sizeof(Unicode)); for (i = oldLen; i < mapLen; ++i) { map[i] = 0; } } } if (n <= 4) { if (sscanf(uStr, "%x", &u) != 1) { error(-1, "Illegal entry in ToUnicode CMap"); return; } map[code] = u + offset; } else { if (sMapLen >= sMapSize) { sMapSize = sMapSize + 16; sMap = (CharCodeToUnicodeString *) greallocn(sMap, sMapSize, sizeof(CharCodeToUnicodeString)); } map[code] = 0; sMap[sMapLen].c = code; sMap[sMapLen].len = n / 4; for (j = 0; j < sMap[sMapLen].len && j < maxUnicodeString; ++j) { strncpy(uHex, uStr + j*4, 4); uHex[4] = '\0'; if (sscanf(uHex, "%x", &sMap[sMapLen].u[j]) != 1) { error(-1, "Illegal entry in ToUnicode CMap"); } } sMap[sMapLen].u[sMap[sMapLen].len - 1] += offset; ++sMapLen; } }
86,424,053,612,770,930,000,000,000,000,000,000,000
None
null
[ "CWE-120" ]
CVE-2020-18750
Buffer overflow in pdf2json 0.69 allows local users to execute arbitrary code by converting a crafted PDF file.
https://nvd.nist.gov/vuln/detail/CVE-2020-18750
217,252
Platinum
9a4ceaccb1585ec35c45fd8e2585538fff6a865e
https://github.com/plutinosoft/Platinum
https://github.com/plutinosoft/Platinum/commit/9a4ceaccb1585ec35c45fd8e2585538fff6a865e
Fix vulnerability around urls crafter as http://host/../secret.foo (#24)
1
PLT_HttpServer::ServeFile(const NPT_HttpRequest& request, const NPT_HttpRequestContext& context, NPT_HttpResponse& response, NPT_String file_path) { NPT_InputStreamReference stream; NPT_File file(file_path); NPT_FileInfo file_info; // prevent hackers from accessing files outside of our root if ((file_path.Find("/..") >= 0) || (file_path.Find("\\..") >= 0) || NPT_FAILED(NPT_File::GetInfo(file_path, &file_info))) { return NPT_ERROR_NO_SUCH_ITEM; } // check for range requests const NPT_String* range_spec = request.GetHeaders().GetHeaderValue(NPT_HTTP_HEADER_RANGE); // handle potential 304 only if range header not set NPT_DateTime date; NPT_TimeStamp timestamp; if (NPT_SUCCEEDED(PLT_UPnPMessageHelper::GetIfModifiedSince((NPT_HttpMessage&)request, date)) && !range_spec) { date.ToTimeStamp(timestamp); NPT_LOG_INFO_5("File %s timestamps: request=%d (%s) vs file=%d (%s)", (const char*)request.GetUrl().GetPath(), (NPT_UInt32)timestamp.ToSeconds(), (const char*)date.ToString(), (NPT_UInt32)file_info.m_ModificationTime, (const char*)NPT_DateTime(file_info.m_ModificationTime).ToString()); if (timestamp >= file_info.m_ModificationTime) { // it's a match NPT_LOG_FINE_1("Returning 304 for %s", request.GetUrl().GetPath().GetChars()); response.SetStatus(304, "Not Modified", NPT_HTTP_PROTOCOL_1_1); return NPT_SUCCESS; } } // open file if (NPT_FAILED(file.Open(NPT_FILE_OPEN_MODE_READ)) || NPT_FAILED(file.GetInputStream(stream)) || stream.IsNull()) { return NPT_ERROR_NO_SUCH_ITEM; } // set Last-Modified and Cache-Control headers if (file_info.m_ModificationTime) { NPT_DateTime last_modified = NPT_DateTime(file_info.m_ModificationTime); response.GetHeaders().SetHeader("Last-Modified", last_modified.ToString(NPT_DateTime::FORMAT_RFC_1123), true); response.GetHeaders().SetHeader("Cache-Control", "max-age=0,must-revalidate", true); //response.GetHeaders().SetHeader("Cache-Control", "max-age=1800", true); } PLT_HttpRequestContext tmp_context(request, context); return ServeStream(request, context, response, stream, PLT_MimeType::GetMimeType(file_path, &tmp_context)); }
80,959,503,616,478,400,000,000,000,000,000,000,000
None
null
[ "CWE-22" ]
CVE-2020-19858
Platinum Upnp SDK through 1.2.0 has a directory traversal vulnerability. The attack could remote attack victim by sending http://ip:port/../privacy.avi URL to compromise a victim's privacy.
https://nvd.nist.gov/vuln/detail/CVE-2020-19858
519,628
Platinum
9a4ceaccb1585ec35c45fd8e2585538fff6a865e
https://github.com/plutinosoft/Platinum
https://github.com/plutinosoft/Platinum/commit/9a4ceaccb1585ec35c45fd8e2585538fff6a865e
Fix vulnerability around urls crafter as http://host/../secret.foo (#24)
0
PLT_HttpServer::ServeFile(const NPT_HttpRequest& request, const NPT_HttpRequestContext& context, NPT_HttpResponse& response, NPT_String file_path) { NPT_InputStreamReference stream; NPT_File file(file_path); NPT_FileInfo file_info; // prevent hackers from accessing files outside of our root if ((file_path.Find("../") >= 0) || (file_path.Find("..\\") >= 0) || NPT_FAILED(NPT_File::GetInfo(file_path, &file_info))) { return NPT_ERROR_NO_SUCH_ITEM; } // check for range requests const NPT_String* range_spec = request.GetHeaders().GetHeaderValue(NPT_HTTP_HEADER_RANGE); // handle potential 304 only if range header not set NPT_DateTime date; NPT_TimeStamp timestamp; if (NPT_SUCCEEDED(PLT_UPnPMessageHelper::GetIfModifiedSince((NPT_HttpMessage&)request, date)) && !range_spec) { date.ToTimeStamp(timestamp); NPT_LOG_INFO_5("File %s timestamps: request=%d (%s) vs file=%d (%s)", (const char*)request.GetUrl().GetPath(), (NPT_UInt32)timestamp.ToSeconds(), (const char*)date.ToString(), (NPT_UInt32)file_info.m_ModificationTime, (const char*)NPT_DateTime(file_info.m_ModificationTime).ToString()); if (timestamp >= file_info.m_ModificationTime) { // it's a match NPT_LOG_FINE_1("Returning 304 for %s", request.GetUrl().GetPath().GetChars()); response.SetStatus(304, "Not Modified", NPT_HTTP_PROTOCOL_1_1); return NPT_SUCCESS; } } // open file if (NPT_FAILED(file.Open(NPT_FILE_OPEN_MODE_READ)) || NPT_FAILED(file.GetInputStream(stream)) || stream.IsNull()) { return NPT_ERROR_NO_SUCH_ITEM; } // set Last-Modified and Cache-Control headers if (file_info.m_ModificationTime) { NPT_DateTime last_modified = NPT_DateTime(file_info.m_ModificationTime); response.GetHeaders().SetHeader("Last-Modified", last_modified.ToString(NPT_DateTime::FORMAT_RFC_1123), true); response.GetHeaders().SetHeader("Cache-Control", "max-age=0,must-revalidate", true); //response.GetHeaders().SetHeader("Cache-Control", "max-age=1800", true); } PLT_HttpRequestContext tmp_context(request, context); return ServeStream(request, context, response, stream, PLT_MimeType::GetMimeType(file_path, &tmp_context)); }
202,319,851,150,031,300,000,000,000,000,000,000,000
None
null
[ "CWE-22" ]
CVE-2020-19858
Platinum Upnp SDK through 1.2.0 has a directory traversal vulnerability. The attack could remote attack victim by sending http://ip:port/../privacy.avi URL to compromise a victim's privacy.
https://nvd.nist.gov/vuln/detail/CVE-2020-19858
217,285
jsish
430ea27accd4d4ffddc946c9402e7c9064835a18
https://github.com/pcmacdon/jsish
https://github.com/pcmacdon/jsish/commit/430ea27accd4d4ffddc946c9402e7c9064835a18
Release "3.0.7": Fix toPrecision bug "stack overflow #4". FossilOrigin-Name: 6c7f0c37027d7f890b57cb38f776af39b8f81f03e60ceeb0a231a1d21e24b5de
1
static Jsi_RC NumberToPrecisionCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { char buf[100]; int prec = 0, skip = 0; Jsi_Number num; Jsi_Value *v; ChkStringN(_this, funcPtr, v); if (Jsi_GetIntFromValue(interp, Jsi_ValueArrayIndex(interp, args, skip), &prec) != JSI_OK) return JSI_ERROR; if (prec<=0) return JSI_ERROR; Jsi_GetDoubleFromValue(interp, v, &num); snprintf(buf, sizeof(buf),"%.*" JSI_NUMFFMT, prec, num); if (num<0) prec++; buf[prec+1] = 0; if (buf[prec] == '.') buf[prec] = 0; Jsi_ValueMakeStringDup(interp, ret, buf); return JSI_OK; }
25,461,200,118,267,773,000,000,000,000,000,000,000
None
null
[ "CWE-120" ]
CVE-2020-22873
Buffer overflow vulnerability in function NumberToPrecisionCmd in jsish before 3.0.7, allows remote attackers to execute arbitrary code.
https://nvd.nist.gov/vuln/detail/CVE-2020-22873
520,296
jsish
430ea27accd4d4ffddc946c9402e7c9064835a18
https://github.com/pcmacdon/jsish
https://github.com/pcmacdon/jsish/commit/430ea27accd4d4ffddc946c9402e7c9064835a18
Release "3.0.7": Fix toPrecision bug "stack overflow #4". FossilOrigin-Name: 6c7f0c37027d7f890b57cb38f776af39b8f81f03e60ceeb0a231a1d21e24b5de
0
static Jsi_RC NumberToPrecisionCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { char buf[JSI_MAX_NUMBER_STRING*2]; int prec = 0, skip = 0; Jsi_Number num; Jsi_Value *v; ChkStringN(_this, funcPtr, v); if (Jsi_GetIntFromValue(interp, Jsi_ValueArrayIndex(interp, args, skip), &prec) != JSI_OK) return JSI_ERROR; if (prec<=0 || prec>JSI_MAX_NUMBER_STRING) return Jsi_LogError("precision must be between 1 and %d", JSI_MAX_NUMBER_STRING); Jsi_GetDoubleFromValue(interp, v, &num); snprintf(buf, sizeof(buf),"%.*" JSI_NUMFFMT, prec, num); if (num<0) prec++; buf[prec+1] = 0; if (buf[prec] == '.') buf[prec] = 0; Jsi_ValueMakeStringDup(interp, ret, buf); return JSI_OK; }
176,441,123,893,071,800,000,000,000,000,000,000,000
None
null
[ "CWE-120" ]
CVE-2020-22873
Buffer overflow vulnerability in function NumberToPrecisionCmd in jsish before 3.0.7, allows remote attackers to execute arbitrary code.
https://nvd.nist.gov/vuln/detail/CVE-2020-22873
217,327
retdec
517298bafaaff0a8e3dd60dd055a67c41b545807
https://github.com/avast/retdec
https://github.com/avast/retdec/commit/517298bafaaff0a8e3dd60dd055a67c41b545807
Try to fix issue #637 Reference: https://github.com/avast/retdec/issues/637
1
bool Decoder::canSplitFunctionOn( utils::Address addr, llvm::BasicBlock* splitBb, std::set<llvm::BasicBlock*>& newFncStarts) { newFncStarts.insert(splitBb); auto* f = splitBb->getParent(); auto fAddr = getFunctionAddress(f); auto fSzIt = _fnc2sz.find(f); if (fSzIt != _fnc2sz.end()) { if (fAddr <= addr && addr < (fAddr+fSzIt->second)) { LOG << "\t\t\t\t\t" << "!CAN S: addr cond @ " << addr << std::endl; return false; } } std::set<Address> fncStarts; fncStarts.insert(fAddr); fncStarts.insert(addr); LOG << "\t\t\t\t\t" << "CAN S: split @ " << fAddr << std::endl; LOG << "\t\t\t\t\t" << "CAN S: split @ " << addr << std::endl; bool changed = true; while (changed) { changed = false; for (BasicBlock& b : *f) { // Address bAddr = getBasicBlockAddress(&b); Address bAddr; // TODO: shitty BasicBlock* bPrev = &b; while (bAddr.isUndefined() && bPrev) { bAddr = getBasicBlockAddress(bPrev); bPrev = bPrev->getPrevNode(); } if (bAddr.isUndefined()) { continue; } auto up = fncStarts.upper_bound(bAddr); --up; Address bFnc = *up; for (auto* p : predecessors(&b)) { // Address pAddr = getBasicBlockAddress(p); Address pAddr; // TODO: shitty BasicBlock* pPrev = p; while (pAddr.isUndefined() && pPrev) { pAddr = getBasicBlockAddress(pPrev); pPrev = pPrev->getPrevNode(); } if (pAddr.isUndefined()) { continue; } auto up = fncStarts.upper_bound(pAddr); --up; Address pFnc = *up; if (bFnc != pFnc) { if (!canSplitFunctionOn(&b)) { return false; } changed |= newFncStarts.insert(&b).second; changed |= fncStarts.insert(bAddr).second; LOG << "\t\t\t\t\t" << "CAN S: split @ " << bAddr << std::endl; } } } } return true; }
251,333,548,688,546,380,000,000,000,000,000,000,000
None
null
[ "CWE-787" ]
CVE-2020-23907
An issue was discovered in retdec v3.3. In function canSplitFunctionOn() of ir_modifications.cpp, there is a possible out of bounds read due to a heap buffer overflow. The impact is: Deny of Service, Memory Disclosure, and Possible Code Execution.
https://nvd.nist.gov/vuln/detail/CVE-2020-23907
520,976
retdec
517298bafaaff0a8e3dd60dd055a67c41b545807
https://github.com/avast/retdec
https://github.com/avast/retdec/commit/517298bafaaff0a8e3dd60dd055a67c41b545807
Try to fix issue #637 Reference: https://github.com/avast/retdec/issues/637
0
bool Decoder::canSplitFunctionOn( utils::Address addr, llvm::BasicBlock* splitBb, std::set<llvm::BasicBlock*>& newFncStarts) { newFncStarts.insert(splitBb); auto* f = splitBb->getParent(); auto fAddr = getFunctionAddress(f); auto fSzIt = _fnc2sz.find(f); if (fSzIt != _fnc2sz.end()) { if (fAddr <= addr && addr < (fAddr+fSzIt->second)) { LOG << "\t\t\t\t\t" << "!CAN S: addr cond @ " << addr << std::endl; return false; } } std::set<Address> fncStarts; fncStarts.insert(fAddr); fncStarts.insert(addr); LOG << "\t\t\t\t\t" << "CAN S: split @ " << fAddr << std::endl; LOG << "\t\t\t\t\t" << "CAN S: split @ " << addr << std::endl; bool changed = true; while (changed) { changed = false; for (BasicBlock& b : *f) { // Address bAddr = getBasicBlockAddress(&b); Address bAddr; // TODO: shitty BasicBlock* bPrev = &b; while (bAddr.isUndefined() && bPrev) { bAddr = getBasicBlockAddress(bPrev); bPrev = bPrev->getPrevNode(); } if (bAddr.isUndefined()) { continue; } auto up = fncStarts.upper_bound(bAddr); if (up == fncStarts.begin()) { return false; } --up; Address bFnc = *up; for (auto* p : predecessors(&b)) { // Address pAddr = getBasicBlockAddress(p); Address pAddr; // TODO: shitty BasicBlock* pPrev = p; while (pAddr.isUndefined() && pPrev) { pAddr = getBasicBlockAddress(pPrev); pPrev = pPrev->getPrevNode(); } if (pAddr.isUndefined()) { continue; } auto up = fncStarts.upper_bound(pAddr); if (up == fncStarts.begin()) { return false; } --up; Address pFnc = *up; if (bFnc != pFnc) { if (!canSplitFunctionOn(&b)) { return false; } changed |= newFncStarts.insert(&b).second; changed |= fncStarts.insert(bAddr).second; LOG << "\t\t\t\t\t" << "CAN S: split @ " << bAddr << std::endl; } } } } return true; }
52,757,457,497,306,000,000,000,000,000,000,000,000
None
null
[ "CWE-787" ]
CVE-2020-23907
An issue was discovered in retdec v3.3. In function canSplitFunctionOn() of ir_modifications.cpp, there is a possible out of bounds read due to a heap buffer overflow. The impact is: Deny of Service, Memory Disclosure, and Possible Code Execution.
https://nvd.nist.gov/vuln/detail/CVE-2020-23907
217,328
oocborrt
539851c66778f68a244633985f6f8d0df94ea3b3
https://github.com/objsys/oocborrt
https://github.com/objsys/oocborrt/commit/539851c66778f68a244633985f6f8d0df94ea3b3
fixed missing return status test error
1
static int cbor2json (OSCTXT* pCborCtxt, OSCTXT* pJsonCtxt) { int ret = 0; OSOCTET tag, ub; /* Read byte from stream */ ret = rtxReadBytes (pCborCtxt, &ub, 1); if (0 != ret) return LOG_RTERR (pCborCtxt, ret); tag = ub >> 5; /* Switch on tag value */ switch (tag) { case OSRTCBOR_UINT: { OSUINTTYPE value; ret = rtCborDecUInt (pCborCtxt, ub, &value); if (0 != ret) return LOG_RTERR (pCborCtxt, ret); /* Encode JSON */ #ifndef _NO_INT64_SUPPORT ret = rtJsonEncUInt64Value (pJsonCtxt, value); #else ret = rtJsonEncUIntValue (pJsonCtxt, value); #endif if (0 != ret) return LOG_RTERR (pJsonCtxt, ret); break; } case OSRTCBOR_NEGINT: { OSINTTYPE value; ret = rtCborDecInt (pCborCtxt, ub, &value); if (0 != ret) return LOG_RTERR (pCborCtxt, ret); /* Encode JSON */ #ifndef _NO_INT64_SUPPORT ret = rtJsonEncInt64Value (pJsonCtxt, value); #else ret = rtJsonEncIntValue (pJsonCtxt, value); #endif if (0 != ret) return LOG_RTERR (pJsonCtxt, ret); break; } case OSRTCBOR_BYTESTR: { OSDynOctStr64 byteStr; ret = rtCborDecDynByteStr (pCborCtxt, ub, &byteStr); if (0 != ret) return LOG_RTERR (pCborCtxt, ret); /* Encode JSON */ ret = rtJsonEncHexStr (pJsonCtxt, byteStr.numocts, byteStr.data); rtxMemFreePtr (pCborCtxt, byteStr.data); if (0 != ret) return LOG_RTERR (pJsonCtxt, ret); break; } case OSRTCBOR_UTF8STR: { OSUTF8CHAR* utf8str; ret = rtCborDecDynUTF8Str (pCborCtxt, ub, (char**)&utf8str); ret = rtJsonEncStringValue (pJsonCtxt, utf8str); rtxMemFreePtr (pCborCtxt, utf8str); if (0 != ret) return LOG_RTERR (pJsonCtxt, ret); break; } case OSRTCBOR_ARRAY: case OSRTCBOR_MAP: { OSOCTET len = ub & 0x1F; char startChar = (tag == OSRTCBOR_ARRAY) ? '[' : '{'; char endChar = (tag == OSRTCBOR_ARRAY) ? ']' : '}'; OSRTSAFEPUTCHAR (pJsonCtxt, startChar); if (len == OSRTCBOR_INDEF) { OSBOOL first = TRUE; for (;;) { if (OSRTCBOR_MATCHEOC (pCborCtxt)) { pCborCtxt->buffer.byteIndex++; break; } if (!first) OSRTSAFEPUTCHAR (pJsonCtxt, ','); else first = FALSE; /* If map, decode object name */ if (tag == OSRTCBOR_MAP) { ret = cborElemNameToJson (pCborCtxt, pJsonCtxt); } /* Make recursive call */ if (0 == ret) ret = cbor2json (pCborCtxt, pJsonCtxt); if (0 != ret) { OSCTXT* pctxt = (rtxErrGetErrorCnt(pJsonCtxt) > 0) ? pJsonCtxt : pCborCtxt; return LOG_RTERR (pctxt, ret); } } } else { /* definite length */ OSSIZE nitems; /* Decode tag and number of items */ ret = rtCborDecSize (pCborCtxt, len, &nitems); if (0 == ret) { OSSIZE i; /* Loop to decode array items */ for (i = 0; i < nitems; i++) { if (0 != i) OSRTSAFEPUTCHAR (pJsonCtxt, ','); /* If map, decode object name */ if (tag == OSRTCBOR_MAP) { ret = cborElemNameToJson (pCborCtxt, pJsonCtxt); } /* Make recursive call */ if (0 == ret) ret = cbor2json (pCborCtxt, pJsonCtxt); if (0 != ret) { OSCTXT* pctxt = (rtxErrGetErrorCnt(pJsonCtxt) > 0) ? pJsonCtxt : pCborCtxt; return LOG_RTERR (pctxt, ret); } } } } OSRTSAFEPUTCHAR (pJsonCtxt, endChar); break; } case OSRTCBOR_FLOAT: if (tag == OSRTCBOR_FALSEENC || tag == OSRTCBOR_TRUEENC) { OSBOOL boolval = (ub == OSRTCBOR_TRUEENC) ? TRUE : FALSE; ret = rtJsonEncBoolValue (pJsonCtxt, boolval); if (0 != ret) return LOG_RTERR (pJsonCtxt, ret); } else if (tag == OSRTCBOR_FLT16ENC || tag == OSRTCBOR_FLT32ENC || tag == OSRTCBOR_FLT64ENC) { OSDOUBLE fltval; ret = rtCborDecFloat (pCborCtxt, ub, &fltval); if (0 != ret) return LOG_RTERR (pCborCtxt, ret); /* Encode JSON */ ret = rtJsonEncDoubleValue (pJsonCtxt, fltval, 0); if (0 != ret) return LOG_RTERR (pJsonCtxt, ret); } else { ret = cborTagNotSupp (pCborCtxt, tag); } break; default: ret = cborTagNotSupp (pCborCtxt, tag); } return ret; }
127,504,669,515,341,630,000,000,000,000,000,000,000
None
null
[ "CWE-20" ]
CVE-2020-24753
A memory corruption vulnerability in Objective Open CBOR Run-time (oocborrt) in versions before 2020-08-12 could allow an attacker to execute code via crafted Concise Binary Object Representation (CBOR) input to the cbor2json decoder. An uncaught error while decoding CBOR Major Type 3 text strings leads to the use of an attacker-controllable uninitialized stack value. This can be used to modify memory, causing a crash or potentially exploitable heap corruption.
https://nvd.nist.gov/vuln/detail/CVE-2020-24753
520,982
oocborrt
539851c66778f68a244633985f6f8d0df94ea3b3
https://github.com/objsys/oocborrt
https://github.com/objsys/oocborrt/commit/539851c66778f68a244633985f6f8d0df94ea3b3
fixed missing return status test error
0
static int cbor2json (OSCTXT* pCborCtxt, OSCTXT* pJsonCtxt) { int ret = 0; OSOCTET tag, ub; /* Read byte from stream */ ret = rtxReadBytes (pCborCtxt, &ub, 1); if (0 != ret) return LOG_RTERR (pCborCtxt, ret); tag = ub >> 5; /* Switch on tag value */ switch (tag) { case OSRTCBOR_UINT: { OSUINTTYPE value; ret = rtCborDecUInt (pCborCtxt, ub, &value); if (0 != ret) return LOG_RTERR (pCborCtxt, ret); /* Encode JSON */ #ifndef _NO_INT64_SUPPORT ret = rtJsonEncUInt64Value (pJsonCtxt, value); #else ret = rtJsonEncUIntValue (pJsonCtxt, value); #endif if (0 != ret) return LOG_RTERR (pJsonCtxt, ret); break; } case OSRTCBOR_NEGINT: { OSINTTYPE value; ret = rtCborDecInt (pCborCtxt, ub, &value); if (0 != ret) return LOG_RTERR (pCborCtxt, ret); /* Encode JSON */ #ifndef _NO_INT64_SUPPORT ret = rtJsonEncInt64Value (pJsonCtxt, value); #else ret = rtJsonEncIntValue (pJsonCtxt, value); #endif if (0 != ret) return LOG_RTERR (pJsonCtxt, ret); break; } case OSRTCBOR_BYTESTR: { OSDynOctStr64 byteStr; ret = rtCborDecDynByteStr (pCborCtxt, ub, &byteStr); if (0 != ret) return LOG_RTERR (pCborCtxt, ret); /* Encode JSON */ ret = rtJsonEncHexStr (pJsonCtxt, byteStr.numocts, byteStr.data); rtxMemFreePtr (pCborCtxt, byteStr.data); if (0 != ret) return LOG_RTERR (pJsonCtxt, ret); break; } case OSRTCBOR_UTF8STR: { OSUTF8CHAR* utf8str; ret = rtCborDecDynUTF8Str (pCborCtxt, ub, (char**)&utf8str); if (0 != ret) return LOG_RTERR (pCborCtxt, ret); ret = rtJsonEncStringValue (pJsonCtxt, utf8str); rtxMemFreePtr (pCborCtxt, utf8str); if (0 != ret) return LOG_RTERR (pJsonCtxt, ret); break; } case OSRTCBOR_ARRAY: case OSRTCBOR_MAP: { OSOCTET len = ub & 0x1F; char startChar = (tag == OSRTCBOR_ARRAY) ? '[' : '{'; char endChar = (tag == OSRTCBOR_ARRAY) ? ']' : '}'; OSRTSAFEPUTCHAR (pJsonCtxt, startChar); if (len == OSRTCBOR_INDEF) { OSBOOL first = TRUE; for (;;) { if (OSRTCBOR_MATCHEOC (pCborCtxt)) { pCborCtxt->buffer.byteIndex++; break; } if (!first) OSRTSAFEPUTCHAR (pJsonCtxt, ','); else first = FALSE; /* If map, decode object name */ if (tag == OSRTCBOR_MAP) { ret = cborElemNameToJson (pCborCtxt, pJsonCtxt); } /* Make recursive call */ if (0 == ret) ret = cbor2json (pCborCtxt, pJsonCtxt); if (0 != ret) { OSCTXT* pctxt = (rtxErrGetErrorCnt(pJsonCtxt) > 0) ? pJsonCtxt : pCborCtxt; return LOG_RTERR (pctxt, ret); } } } else { /* definite length */ OSSIZE nitems; /* Decode tag and number of items */ ret = rtCborDecSize (pCborCtxt, len, &nitems); if (0 == ret) { OSSIZE i; /* Loop to decode array items */ for (i = 0; i < nitems; i++) { if (0 != i) OSRTSAFEPUTCHAR (pJsonCtxt, ','); /* If map, decode object name */ if (tag == OSRTCBOR_MAP) { ret = cborElemNameToJson (pCborCtxt, pJsonCtxt); } /* Make recursive call */ if (0 == ret) ret = cbor2json (pCborCtxt, pJsonCtxt); if (0 != ret) { OSCTXT* pctxt = (rtxErrGetErrorCnt(pJsonCtxt) > 0) ? pJsonCtxt : pCborCtxt; return LOG_RTERR (pctxt, ret); } } } } OSRTSAFEPUTCHAR (pJsonCtxt, endChar); break; } case OSRTCBOR_FLOAT: if (tag == OSRTCBOR_FALSEENC || tag == OSRTCBOR_TRUEENC) { OSBOOL boolval = (ub == OSRTCBOR_TRUEENC) ? TRUE : FALSE; ret = rtJsonEncBoolValue (pJsonCtxt, boolval); if (0 != ret) return LOG_RTERR (pJsonCtxt, ret); } else if (tag == OSRTCBOR_FLT16ENC || tag == OSRTCBOR_FLT32ENC || tag == OSRTCBOR_FLT64ENC) { OSDOUBLE fltval; ret = rtCborDecFloat (pCborCtxt, ub, &fltval); if (0 != ret) return LOG_RTERR (pCborCtxt, ret); /* Encode JSON */ ret = rtJsonEncDoubleValue (pJsonCtxt, fltval, 0); if (0 != ret) return LOG_RTERR (pJsonCtxt, ret); } else { ret = cborTagNotSupp (pCborCtxt, tag); } break; default: ret = cborTagNotSupp (pCborCtxt, tag); } return ret; }
182,192,642,033,756,700,000,000,000,000,000,000,000
None
null
[ "CWE-20" ]
CVE-2020-24753
A memory corruption vulnerability in Objective Open CBOR Run-time (oocborrt) in versions before 2020-08-12 could allow an attacker to execute code via crafted Concise Binary Object Representation (CBOR) input to the cbor2json decoder. An uncaught error while decoding CBOR Major Type 3 text strings leads to the use of an attacker-controllable uninitialized stack value. This can be used to modify memory, causing a crash or potentially exploitable heap corruption.
https://nvd.nist.gov/vuln/detail/CVE-2020-24753
217,461
sqlcipher
cb71f53e8cea4802509f182fa5bead0ac6ab0e7f
https://github.com/sqlcipher/sqlcipher
https://github.com/sqlcipher/sqlcipher/commit/cb71f53e8cea4802509f182fa5bead0ac6ab0e7f
fix sqlcipher_export handling of NULL parameters
1
void sqlcipher_exportFunc(sqlite3_context *context, int argc, sqlite3_value **argv) { sqlite3 *db = sqlite3_context_db_handle(context); const char* targetDb, *sourceDb; int targetDb_idx = 0; u64 saved_flags = db->flags; /* Saved value of the db->flags */ u32 saved_mDbFlags = db->mDbFlags; /* Saved value of the db->mDbFlags */ int saved_nChange = db->nChange; /* Saved value of db->nChange */ int saved_nTotalChange = db->nTotalChange; /* Saved value of db->nTotalChange */ u8 saved_mTrace = db->mTrace; /* Saved value of db->mTrace */ int rc = SQLITE_OK; /* Return code from service routines */ char *zSql = NULL; /* SQL statements */ char *pzErrMsg = NULL; if(argc != 1 && argc != 2) { rc = SQLITE_ERROR; pzErrMsg = sqlite3_mprintf("invalid number of arguments (%d) passed to sqlcipher_export", argc); goto end_of_export; } targetDb = (const char*) sqlite3_value_text(argv[0]); sourceDb = (argc == 2) ? (char *) sqlite3_value_text(argv[1]) : "main"; /* if the name of the target is not main, but the index returned is zero there is a mismatch and we should not proceed */ targetDb_idx = sqlcipher_find_db_index(db, targetDb); if(targetDb_idx == 0 && sqlite3StrICmp("main", targetDb) != 0) { rc = SQLITE_ERROR; pzErrMsg = sqlite3_mprintf("unknown database %s", targetDb); goto end_of_export; } db->init.iDb = targetDb_idx; db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks; db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum; db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_Defensive | SQLITE_CountRows); db->mTrace = 0; /* Query the schema of the main database. Create a mirror schema ** in the temporary database. */ zSql = sqlite3_mprintf( "SELECT sql " " FROM %s.sqlite_master WHERE type='table' AND name!='sqlite_sequence'" " AND rootpage>0" , sourceDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); zSql = sqlite3_mprintf( "SELECT sql " " FROM %s.sqlite_master WHERE sql LIKE 'CREATE INDEX %%' " , sourceDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); zSql = sqlite3_mprintf( "SELECT sql " " FROM %s.sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %%'" , sourceDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); /* Loop through the tables in the main database. For each, do ** an "INSERT INTO rekey_db.xxx SELECT * FROM main.xxx;" to copy ** the contents to the temporary database. */ zSql = sqlite3_mprintf( "SELECT 'INSERT INTO %s.' || quote(name) " "|| ' SELECT * FROM %s.' || quote(name) || ';'" "FROM %s.sqlite_master " "WHERE type = 'table' AND name!='sqlite_sequence' " " AND rootpage>0" , targetDb, sourceDb, sourceDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); /* Copy over the contents of the sequence table */ zSql = sqlite3_mprintf( "SELECT 'INSERT INTO %s.' || quote(name) " "|| ' SELECT * FROM %s.' || quote(name) || ';' " "FROM %s.sqlite_master WHERE name=='sqlite_sequence';" , targetDb, sourceDb, targetDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); /* Copy the triggers, views, and virtual tables from the main database ** over to the temporary database. None of these objects has any ** associated storage, so all we have to do is copy their entries ** from the SQLITE_MASTER table. */ zSql = sqlite3_mprintf( "INSERT INTO %s.sqlite_master " " SELECT type, name, tbl_name, rootpage, sql" " FROM %s.sqlite_master" " WHERE type='view' OR type='trigger'" " OR (type='table' AND rootpage=0)" , targetDb, sourceDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); zSql = NULL; end_of_export: db->init.iDb = 0; db->flags = saved_flags; db->mDbFlags = saved_mDbFlags; db->nChange = saved_nChange; db->nTotalChange = saved_nTotalChange; db->mTrace = saved_mTrace; if(zSql) sqlite3_free(zSql); if(rc) { if(pzErrMsg != NULL) { sqlite3_result_error(context, pzErrMsg, -1); sqlite3DbFree(db, pzErrMsg); } else { sqlite3_result_error(context, sqlite3ErrStr(rc), -1); } } }
76,223,646,707,037,760,000,000,000,000,000,000,000
None
null
[ "CWE-476" ]
CVE-2021-3119
Zetetic SQLCipher 4.x before 4.4.3 has a NULL pointer dereferencing issue related to sqlcipher_export in crypto.c and sqlite3StrICmp in sqlite3.c. This may allow an attacker to perform a remote denial of service attack. For example, an SQL injection can be used to execute the crafted SQL command sequence, which causes a segmentation fault.
https://nvd.nist.gov/vuln/detail/CVE-2021-3119
521,506
sqlcipher
cb71f53e8cea4802509f182fa5bead0ac6ab0e7f
https://github.com/sqlcipher/sqlcipher
https://github.com/sqlcipher/sqlcipher/commit/cb71f53e8cea4802509f182fa5bead0ac6ab0e7f
fix sqlcipher_export handling of NULL parameters
0
void sqlcipher_exportFunc(sqlite3_context *context, int argc, sqlite3_value **argv) { sqlite3 *db = sqlite3_context_db_handle(context); const char* targetDb, *sourceDb; int targetDb_idx = 0; u64 saved_flags = db->flags; /* Saved value of the db->flags */ u32 saved_mDbFlags = db->mDbFlags; /* Saved value of the db->mDbFlags */ int saved_nChange = db->nChange; /* Saved value of db->nChange */ int saved_nTotalChange = db->nTotalChange; /* Saved value of db->nTotalChange */ u8 saved_mTrace = db->mTrace; /* Saved value of db->mTrace */ int rc = SQLITE_OK; /* Return code from service routines */ char *zSql = NULL; /* SQL statements */ char *pzErrMsg = NULL; if(argc != 1 && argc != 2) { rc = SQLITE_ERROR; pzErrMsg = sqlite3_mprintf("invalid number of arguments (%d) passed to sqlcipher_export", argc); goto end_of_export; } if(sqlite3_value_type(argv[0]) == SQLITE_NULL) { rc = SQLITE_ERROR; pzErrMsg = sqlite3_mprintf("target database can't be NULL"); goto end_of_export; } targetDb = (const char*) sqlite3_value_text(argv[0]); sourceDb = "main"; if(argc == 2) { if(sqlite3_value_type(argv[1]) == SQLITE_NULL) { rc = SQLITE_ERROR; pzErrMsg = sqlite3_mprintf("target database can't be NULL"); goto end_of_export; } sourceDb = (char *) sqlite3_value_text(argv[1]); } /* if the name of the target is not main, but the index returned is zero there is a mismatch and we should not proceed */ targetDb_idx = sqlcipher_find_db_index(db, targetDb); if(targetDb_idx == 0 && targetDb != NULL && sqlite3StrICmp("main", targetDb) != 0) { rc = SQLITE_ERROR; pzErrMsg = sqlite3_mprintf("unknown database %s", targetDb); goto end_of_export; } db->init.iDb = targetDb_idx; db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks; db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum; db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_Defensive | SQLITE_CountRows); db->mTrace = 0; /* Query the schema of the main database. Create a mirror schema ** in the temporary database. */ zSql = sqlite3_mprintf( "SELECT sql " " FROM %s.sqlite_master WHERE type='table' AND name!='sqlite_sequence'" " AND rootpage>0" , sourceDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); zSql = sqlite3_mprintf( "SELECT sql " " FROM %s.sqlite_master WHERE sql LIKE 'CREATE INDEX %%' " , sourceDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); zSql = sqlite3_mprintf( "SELECT sql " " FROM %s.sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %%'" , sourceDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); /* Loop through the tables in the main database. For each, do ** an "INSERT INTO rekey_db.xxx SELECT * FROM main.xxx;" to copy ** the contents to the temporary database. */ zSql = sqlite3_mprintf( "SELECT 'INSERT INTO %s.' || quote(name) " "|| ' SELECT * FROM %s.' || quote(name) || ';'" "FROM %s.sqlite_master " "WHERE type = 'table' AND name!='sqlite_sequence' " " AND rootpage>0" , targetDb, sourceDb, sourceDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); /* Copy over the contents of the sequence table */ zSql = sqlite3_mprintf( "SELECT 'INSERT INTO %s.' || quote(name) " "|| ' SELECT * FROM %s.' || quote(name) || ';' " "FROM %s.sqlite_master WHERE name=='sqlite_sequence';" , targetDb, sourceDb, targetDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); /* Copy the triggers, views, and virtual tables from the main database ** over to the temporary database. None of these objects has any ** associated storage, so all we have to do is copy their entries ** from the SQLITE_MASTER table. */ zSql = sqlite3_mprintf( "INSERT INTO %s.sqlite_master " " SELECT type, name, tbl_name, rootpage, sql" " FROM %s.sqlite_master" " WHERE type='view' OR type='trigger'" " OR (type='table' AND rootpage=0)" , targetDb, sourceDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); zSql = NULL; end_of_export: db->init.iDb = 0; db->flags = saved_flags; db->mDbFlags = saved_mDbFlags; db->nChange = saved_nChange; db->nTotalChange = saved_nTotalChange; db->mTrace = saved_mTrace; if(zSql) sqlite3_free(zSql); if(rc) { if(pzErrMsg != NULL) { sqlite3_result_error(context, pzErrMsg, -1); sqlite3DbFree(db, pzErrMsg); } else { sqlite3_result_error(context, sqlite3ErrStr(rc), -1); } } }
291,673,322,331,677,800,000,000,000,000,000,000,000
None
null
[ "CWE-476" ]
CVE-2021-3119
Zetetic SQLCipher 4.x before 4.4.3 has a NULL pointer dereferencing issue related to sqlcipher_export in crypto.c and sqlite3StrICmp in sqlite3.c. This may allow an attacker to perform a remote denial of service attack. For example, an SQL injection can be used to execute the crafted SQL command sequence, which causes a segmentation fault.
https://nvd.nist.gov/vuln/detail/CVE-2021-3119
217,552
maddy
7ee6a39c6a1939b376545f030a5efd6f90913583
https://github.com/foxcpp/maddy
https://github.com/foxcpp/maddy/commit/7ee6a39c6a1939b376545f030a5efd6f90913583
auth/pam: Check for account/password expiry See GHSA-6cp7-g972-w9m9. Thanks Youssef Rebahi-Gilbert (ysf) for reporting the issue.
1
struct error_obj run_pam_auth(const char *username, char *password) { // PAM frees pam_response for us. struct pam_response *reply = malloc(sizeof(struct pam_response)); if (reply == NULL) { struct error_obj ret_val; ret_val.status = 2; ret_val.func_name = "malloc"; ret_val.error_msg = "Out of memory"; return ret_val; } reply->resp = password; reply->resp_retcode = 0; const struct pam_conv local_conv = { conv_func, reply }; pam_handle_t *local_auth = NULL; int status = pam_start("maddy", username, &local_conv, &local_auth); if (status != PAM_SUCCESS) { struct error_obj ret_val; ret_val.status = 2; ret_val.func_name = "pam_start"; ret_val.error_msg = pam_strerror(local_auth, status); return ret_val; } status = pam_authenticate(local_auth, PAM_SILENT|PAM_DISALLOW_NULL_AUTHTOK); if (status != PAM_SUCCESS) { struct error_obj ret_val; if (status == PAM_AUTH_ERR || status == PAM_USER_UNKNOWN) { ret_val.status = 1; } else { ret_val.status = 2; } ret_val.func_name = "pam_authenticate"; ret_val.error_msg = pam_strerror(local_auth, status); return ret_val; } status = pam_end(local_auth, status); if (status != PAM_SUCCESS) { struct error_obj ret_val; ret_val.status = 2; ret_val.func_name = "pam_end"; ret_val.error_msg = pam_strerror(local_auth, status); return ret_val; } struct error_obj ret_val; ret_val.status = 0; ret_val.func_name = NULL; ret_val.error_msg = NULL; return ret_val; }
65,001,628,105,258,760,000,000,000,000,000,000,000
None
null
[ "CWE-613" ]
CVE-2022-24732
Maddy Mail Server is an open source SMTP compatible email server. Versions of maddy prior to 0.5.4 do not implement password expiry or account expiry checking when authenticating using PAM. Users are advised to upgrade. Users unable to upgrade should manually remove expired accounts via existing filtering mechanisms.
https://nvd.nist.gov/vuln/detail/CVE-2022-24732
522,443
maddy
7ee6a39c6a1939b376545f030a5efd6f90913583
https://github.com/foxcpp/maddy
https://github.com/foxcpp/maddy/commit/7ee6a39c6a1939b376545f030a5efd6f90913583
auth/pam: Check for account/password expiry See GHSA-6cp7-g972-w9m9. Thanks Youssef Rebahi-Gilbert (ysf) for reporting the issue.
0
struct error_obj run_pam_auth(const char *username, char *password) { // PAM frees pam_response for us. struct pam_response *reply = malloc(sizeof(struct pam_response)); if (reply == NULL) { struct error_obj ret_val; ret_val.status = 2; ret_val.func_name = "malloc"; ret_val.error_msg = "Out of memory"; return ret_val; } reply->resp = password; reply->resp_retcode = 0; const struct pam_conv local_conv = { conv_func, reply }; pam_handle_t *local_auth = NULL; int status = pam_start("maddy", username, &local_conv, &local_auth); if (status != PAM_SUCCESS) { struct error_obj ret_val; ret_val.status = 2; ret_val.func_name = "pam_start"; ret_val.error_msg = pam_strerror(local_auth, status); return ret_val; } status = pam_authenticate(local_auth, PAM_SILENT|PAM_DISALLOW_NULL_AUTHTOK); if (status != PAM_SUCCESS) { struct error_obj ret_val; if (status == PAM_AUTH_ERR || status == PAM_USER_UNKNOWN) { ret_val.status = 1; } else { ret_val.status = 2; } ret_val.func_name = "pam_authenticate"; ret_val.error_msg = pam_strerror(local_auth, status); return ret_val; } status = pam_acct_mgmt(local_auth, PAM_SILENT|PAM_DISALLOW_NULL_AUTHTOK); if (status != PAM_SUCCESS) { struct error_obj ret_val; if (status == PAM_AUTH_ERR || status == PAM_USER_UNKNOWN || status == PAM_NEW_AUTHTOK_REQD) { ret_val.status = 1; } else { ret_val.status = 2; } ret_val.func_name = "pam_acct_mgmt"; ret_val.error_msg = pam_strerror(local_auth, status); return ret_val; } status = pam_end(local_auth, status); if (status != PAM_SUCCESS) { struct error_obj ret_val; ret_val.status = 2; ret_val.func_name = "pam_end"; ret_val.error_msg = pam_strerror(local_auth, status); return ret_val; } struct error_obj ret_val; ret_val.status = 0; ret_val.func_name = NULL; ret_val.error_msg = NULL; return ret_val; }
311,322,554,352,065,030,000,000,000,000,000,000,000
None
null
[ "CWE-613" ]
CVE-2022-24732
Maddy Mail Server is an open source SMTP compatible email server. Versions of maddy prior to 0.5.4 do not implement password expiry or account expiry checking when authenticating using PAM. Users are advised to upgrade. Users unable to upgrade should manually remove expired accounts via existing filtering mechanisms.
https://nvd.nist.gov/vuln/detail/CVE-2022-24732