diff --git a/common/sexputil.c b/common/sexputil.c index 3c5abbe16..68388e146 100644 --- a/common/sexputil.c +++ b/common/sexputil.c @@ -1,1172 +1,1188 @@ /* sexputil.c - Utility functions for S-expressions. * Copyright (C) 2005, 2007, 2009 Free Software Foundation, Inc. * Copyright (C) 2013 Werner Koch * * This file is part of GnuPG. * * This file is free software; you can redistribute it and/or modify * it under the terms of either * * - the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at * your option) any later version. * * or * * - the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at * your option) any later version. * * or both in parallel, as here. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ /* This file implements a few utility functions useful when working with canonical encrypted S-expressions (i.e. not the S-exprssion objects from libgcrypt). */ #include #include #include #include #include #include #ifdef HAVE_LOCALE_H #include #endif #include "util.h" #include "tlv.h" #include "sexp-parse.h" #include "openpgpdefs.h" /* for pubkey_algo_t */ /* Return a malloced string with the S-expression CANON in advanced format. Returns NULL on error. */ static char * sexp_to_string (gcry_sexp_t sexp) { size_t n; char *result; if (!sexp) return NULL; n = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_ADVANCED, NULL, 0); if (!n) return NULL; result = xtrymalloc (n); if (!result) return NULL; n = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_ADVANCED, result, n); if (!n) BUG (); return result; } /* Return a malloced string with the S-expression CANON in advanced format. Returns NULL on error. */ char * canon_sexp_to_string (const unsigned char *canon, size_t canonlen) { size_t n; gcry_sexp_t sexp; char *result; n = gcry_sexp_canon_len (canon, canonlen, NULL, NULL); if (!n) return NULL; if (gcry_sexp_sscan (&sexp, NULL, canon, n)) return NULL; result = sexp_to_string (sexp); gcry_sexp_release (sexp); return result; } /* Print the canonical encoded S-expression in SEXP in advanced format. SEXPLEN may be passed as 0 is SEXP is known to be valid. With TEXT of NULL print just the raw S-expression, with TEXT just an empty string, print a trailing linefeed, otherwise print an entire debug line. */ void log_printcanon (const char *text, const unsigned char *sexp, size_t sexplen) { if (text && *text) log_debug ("%s ", text); if (sexp) { char *buf = canon_sexp_to_string (sexp, sexplen); log_printf ("%s", buf? buf : "[invalid S-expression]"); xfree (buf); } if (text) log_printf ("\n"); } /* Print the gcryp S-expression in SEXP in advanced format. With TEXT of NULL print just the raw S-expression, with TEXT just an empty string, print a trailing linefeed, otherwise print an entire debug line. */ void log_printsexp (const char *text, gcry_sexp_t sexp) { if (text && *text) log_debug ("%s ", text); if (sexp) { char *buf = sexp_to_string (sexp); log_printf ("%s", buf? buf : "[invalid S-expression]"); xfree (buf); } if (text) log_printf ("\n"); } /* Helper function to create a canonical encoded S-expression from a Libgcrypt S-expression object. The function returns 0 on success and the malloced canonical S-expression is stored at R_BUFFER and the allocated length at R_BUFLEN. On error an error code is returned and (NULL, 0) stored at R_BUFFER and R_BUFLEN. If the allocated buffer length is not required, NULL by be used for R_BUFLEN. */ gpg_error_t make_canon_sexp (gcry_sexp_t sexp, unsigned char **r_buffer, size_t *r_buflen) { size_t len; unsigned char *buf; *r_buffer = NULL; if (r_buflen) *r_buflen = 0;; len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_CANON, NULL, 0); if (!len) return gpg_error (GPG_ERR_BUG); buf = xtrymalloc (len); if (!buf) return gpg_error_from_syserror (); len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_CANON, buf, len); if (!len) return gpg_error (GPG_ERR_BUG); *r_buffer = buf; if (r_buflen) *r_buflen = len; return 0; } /* Same as make_canon_sexp but pad the buffer to multiple of 64 bits. If SECURE is set, secure memory will be allocated. */ gpg_error_t make_canon_sexp_pad (gcry_sexp_t sexp, int secure, unsigned char **r_buffer, size_t *r_buflen) { size_t len; unsigned char *buf; *r_buffer = NULL; if (r_buflen) *r_buflen = 0;; len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_CANON, NULL, 0); if (!len) return gpg_error (GPG_ERR_BUG); len += (8 - len % 8) % 8; buf = secure? xtrycalloc_secure (1, len) : xtrycalloc (1, len); if (!buf) return gpg_error_from_syserror (); if (!gcry_sexp_sprint (sexp, GCRYSEXP_FMT_CANON, buf, len)) return gpg_error (GPG_ERR_BUG); *r_buffer = buf; if (r_buflen) *r_buflen = len; return 0; } /* Return the so called "keygrip" which is the SHA-1 hash of the public key parameters expressed in a way depended on the algorithm. KEY is expected to be an canonical encoded S-expression with a public or private key. KEYLEN is the length of that buffer. GRIP must be at least 20 bytes long. On success 0 is returned, on error an error code. */ gpg_error_t keygrip_from_canon_sexp (const unsigned char *key, size_t keylen, unsigned char *grip) { gpg_error_t err; gcry_sexp_t sexp; if (!grip) return gpg_error (GPG_ERR_INV_VALUE); err = gcry_sexp_sscan (&sexp, NULL, (const char *)key, keylen); if (err) return err; if (!gcry_pk_get_keygrip (sexp, grip)) err = gpg_error (GPG_ERR_INTERNAL); gcry_sexp_release (sexp); return err; } /* Compare two simple S-expressions like "(3:foo)". Returns 0 if they are identical or !0 if they are not. Note that this function can't be used for sorting. */ int cmp_simple_canon_sexp (const unsigned char *a_orig, const unsigned char *b_orig) { const char *a = (const char *)a_orig; const char *b = (const char *)b_orig; unsigned long n1, n2; char *endp; if (!a && !b) return 0; /* Both are NULL, they are identical. */ if (!a || !b) return 1; /* One is NULL, they are not identical. */ if (*a != '(' || *b != '(') log_bug ("invalid S-exp in cmp_simple_canon_sexp\n"); a++; n1 = strtoul (a, &endp, 10); a = endp; b++; n2 = strtoul (b, &endp, 10); b = endp; if (*a != ':' || *b != ':' ) log_bug ("invalid S-exp in cmp_simple_canon_sexp\n"); if (n1 != n2) return 1; /* Not the same. */ for (a++, b++; n1; n1--, a++, b++) if (*a != *b) return 1; /* Not the same. */ return 0; } /* Helper for cmp_canon_sexp. */ static int cmp_canon_sexp_def_tcmp (void *ctx, int depth, const unsigned char *aval, size_t alen, const unsigned char *bval, size_t blen) { (void)ctx; (void)depth; if (alen > blen) return 1; else if (alen < blen) return -1; else return memcmp (aval, bval, alen); } /* Compare the two canonical encoded s-expressions A with maximum * length ALEN and B with maximum length BLEN. * * Returns 0 if they match. * * If TCMP is NULL, this is not different really different from a * memcmp but does not consider any garbage after the last closing * parentheses. * * If TCMP is not NULL, it is expected to be a function to compare the * values of each token. TCMP is called for each token while parsing * the s-expressions until TCMP return a non-zero value. Here the CTX * receives the provided value TCMPCTX, DEPTH is the number of * currently open parentheses and (AVAL,ALEN) and (BVAL,BLEN) the * values of the current token. TCMP needs to return zero to indicate * that the tokens match. */ int cmp_canon_sexp (const unsigned char *a, size_t alen, const unsigned char *b, size_t blen, int (*tcmp)(void *ctx, int depth, const unsigned char *aval, size_t avallen, const unsigned char *bval, size_t bvallen), void *tcmpctx) { const unsigned char *a_buf, *a_tok; const unsigned char *b_buf, *b_tok; size_t a_buflen, a_toklen; size_t b_buflen, b_toklen; int a_depth, b_depth, ret; if ((!a && !b) || (!alen && !blen)) return 0; /* Both are NULL, they are identical. */ if (!a || !b) return !!a - !!b; /* One is NULL, they are not identical. */ if (*a != '(' || *b != '(') log_bug ("invalid S-exp in %s\n", __func__); if (!tcmp) tcmp = cmp_canon_sexp_def_tcmp; a_depth = 0; a_buf = a; a_buflen = alen; b_depth = 0; b_buf = b; b_buflen = blen; for (;;) { if (parse_sexp (&a_buf, &a_buflen, &a_depth, &a_tok, &a_toklen)) return -1; /* A is invalid. */ if (parse_sexp (&b_buf, &b_buflen, &b_depth, &b_tok, &b_toklen)) return -1; /* B is invalid. */ if (!a_depth && !b_depth) return 0; /* End of both expressions - they match. */ if (a_depth != b_depth) return a_depth - b_depth; /* Not the same structure */ if (!a_tok && !b_tok) ; /* parens */ else if (a_tok && b_tok) { ret = tcmp (tcmpctx, a_depth, a_tok, a_toklen, b_tok, b_toklen); if (ret) return ret; /* Mismatch */ } else /* One has a paren other has not. */ return !!a_tok - !!b_tok; } } /* Create a simple S-expression from the hex string at LINE. Returns a newly allocated buffer with that canonical encoded S-expression or NULL in case of an error. On return the number of characters scanned in LINE will be stored at NSCANNED. This functions stops converting at the first character not representing a hexdigit. Odd numbers of hex digits are allowed; a leading zero is then assumed. If no characters have been found, NULL is returned.*/ unsigned char * make_simple_sexp_from_hexstr (const char *line, size_t *nscanned) { size_t n, len; const char *s; unsigned char *buf; unsigned char *p; char numbuf[50], *numbufp; size_t numbuflen; for (n=0, s=line; hexdigitp (s); s++, n++) ; if (nscanned) *nscanned = n; if (!n) return NULL; len = ((n+1) & ~0x01)/2; numbufp = smklen (numbuf, sizeof numbuf, len, &numbuflen); buf = xtrymalloc (1 + numbuflen + len + 1 + 1); if (!buf) return NULL; buf[0] = '('; p = (unsigned char *)stpcpy ((char *)buf+1, numbufp); s = line; if ((n&1)) { *p++ = xtoi_1 (s); s++; n--; } for (; n > 1; n -=2, s += 2) *p++ = xtoi_2 (s); *p++ = ')'; *p = 0; /* (Not really neaded.) */ return buf; } /* Return the hash algorithm from a KSBA sig-val. SIGVAL is a canonical encoded S-expression. Return 0 if the hash algorithm is not encoded in SIG-VAL or it is not supported by libgcrypt. */ int hash_algo_from_sigval (const unsigned char *sigval) { const unsigned char *s = sigval; size_t n; int depth; char buffer[50]; if (!s || *s != '(') return 0; /* Invalid S-expression. */ s++; n = snext (&s); if (!n) return 0; /* Invalid S-expression. */ if (!smatch (&s, n, "sig-val")) return 0; /* Not a sig-val. */ if (*s != '(') return 0; /* Invalid S-expression. */ s++; /* Skip over the algo+parameter list. */ depth = 1; if (sskip (&s, &depth) || depth) return 0; /* Invalid S-expression. */ if (*s != '(') return 0; /* No further list. */ /* Check whether this is (hash ALGO). */ s++; n = snext (&s); if (!n) return 0; /* Invalid S-expression. */ if (!smatch (&s, n, "hash")) return 0; /* Not a "hash" keyword. */ n = snext (&s); if (!n || n+1 >= sizeof (buffer)) return 0; /* Algorithm string is missing or too long. */ memcpy (buffer, s, n); buffer[n] = 0; return gcry_md_map_name (buffer); } /* Create a public key S-expression for an RSA public key from the modulus M with length MLEN and the public exponent E with length ELEN. Returns a newly allocated buffer of NULL in case of a memory allocation problem. If R_LEN is not NULL, the length of the canonical S-expression is stored there. */ unsigned char * make_canon_sexp_from_rsa_pk (const void *m_arg, size_t mlen, const void *e_arg, size_t elen, size_t *r_len) { const unsigned char *m = m_arg; const unsigned char *e = e_arg; int m_extra = 0; int e_extra = 0; char mlen_str[35]; char elen_str[35]; unsigned char *keybuf, *p; const char part1[] = "(10:public-key(3:rsa(1:n"; const char part2[] = ")(1:e"; const char part3[] = ")))"; /* Remove leading zeroes. */ for (; mlen && !*m; mlen--, m++) ; for (; elen && !*e; elen--, e++) ; /* Insert a leading zero if the number would be zero or interpreted as negative. */ if (!mlen || (m[0] & 0x80)) m_extra = 1; if (!elen || (e[0] & 0x80)) e_extra = 1; /* Build the S-expression. */ snprintf (mlen_str, sizeof mlen_str, "%u:", (unsigned int)mlen+m_extra); snprintf (elen_str, sizeof elen_str, "%u:", (unsigned int)elen+e_extra); keybuf = xtrymalloc (strlen (part1) + strlen (mlen_str) + mlen + m_extra + strlen (part2) + strlen (elen_str) + elen + e_extra + strlen (part3) + 1); if (!keybuf) return NULL; p = stpcpy (keybuf, part1); p = stpcpy (p, mlen_str); if (m_extra) *p++ = 0; memcpy (p, m, mlen); p += mlen; p = stpcpy (p, part2); p = stpcpy (p, elen_str); if (e_extra) *p++ = 0; memcpy (p, e, elen); p += elen; p = stpcpy (p, part3); if (r_len) *r_len = p - keybuf; return keybuf; } /* Return the parameters of a public RSA key expressed as an canonical encoded S-expression. */ gpg_error_t get_rsa_pk_from_canon_sexp (const unsigned char *keydata, size_t keydatalen, unsigned char const **r_n, size_t *r_nlen, unsigned char const **r_e, size_t *r_elen) { gpg_error_t err; const unsigned char *buf, *tok; size_t buflen, toklen; int depth, last_depth1, last_depth2; const unsigned char *rsa_n = NULL; const unsigned char *rsa_e = NULL; size_t rsa_n_len, rsa_e_len; *r_n = NULL; *r_nlen = 0; *r_e = NULL; *r_elen = 0; buf = keydata; buflen = keydatalen; depth = 0; if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if (!tok || toklen != 10 || memcmp ("public-key", tok, toklen)) return gpg_error (GPG_ERR_BAD_PUBKEY); if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if (!tok || toklen != 3 || memcmp ("rsa", tok, toklen)) return gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO); last_depth1 = depth; while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)) && depth && depth >= last_depth1) { if (tok) return gpg_error (GPG_ERR_UNKNOWN_SEXP); if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if (tok && toklen == 1) { const unsigned char **mpi; size_t *mpi_len; switch (*tok) { case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break; case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break; default: mpi = NULL; mpi_len = NULL; break; } if (mpi && *mpi) return gpg_error (GPG_ERR_DUP_VALUE); if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if (tok && mpi) { /* Strip off leading zero bytes and save. */ for (;toklen && !*tok; toklen--, tok++) ; *mpi = tok; *mpi_len = toklen; } } /* Skip to the end of the list. */ last_depth2 = depth; while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)) && depth && depth >= last_depth2) ; if (err) return err; } if (err) return err; if (!rsa_n || !rsa_n_len || !rsa_e || !rsa_e_len) return gpg_error (GPG_ERR_BAD_PUBKEY); *r_n = rsa_n; *r_nlen = rsa_n_len; *r_e = rsa_e; *r_elen = rsa_e_len; return 0; } /* Return the public key parameter Q of a public RSA or ECC key * expressed as an canonical encoded S-expression. */ gpg_error_t get_ecc_q_from_canon_sexp (const unsigned char *keydata, size_t keydatalen, unsigned char const **r_q, size_t *r_qlen) { gpg_error_t err; const unsigned char *buf, *tok; size_t buflen, toklen; int depth, last_depth1, last_depth2; const unsigned char *ecc_q = NULL; size_t ecc_q_len; *r_q = NULL; *r_qlen = 0; buf = keydata; buflen = keydatalen; depth = 0; if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if (!tok || toklen != 10 || memcmp ("public-key", tok, toklen)) return gpg_error (GPG_ERR_BAD_PUBKEY); if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if (tok && toklen == 3 && !memcmp ("ecc", tok, toklen)) ; else if (tok && toklen == 5 && (!memcmp ("ecdsa", tok, toklen) || !memcmp ("eddsa", tok, toklen))) ; else return gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO); last_depth1 = depth; while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)) && depth && depth >= last_depth1) { if (tok) return gpg_error (GPG_ERR_UNKNOWN_SEXP); if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if (tok && toklen == 1) { const unsigned char **mpi; size_t *mpi_len; switch (*tok) { case 'q': mpi = &ecc_q; mpi_len = &ecc_q_len; break; default: mpi = NULL; mpi_len = NULL; break; } if (mpi && *mpi) return gpg_error (GPG_ERR_DUP_VALUE); if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if (tok && mpi) { *mpi = tok; *mpi_len = toklen; } } /* Skip to the end of the list. */ last_depth2 = depth; while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)) && depth && depth >= last_depth2) ; if (err) return err; } if (err) return err; if (!ecc_q || !ecc_q_len) return gpg_error (GPG_ERR_BAD_PUBKEY); *r_q = ecc_q; *r_qlen = ecc_q_len; return 0; } /* Return an uncompressed point (X,Y) in P at R_BUF as a malloced * buffer with its byte length stored at R_BUFLEN. May not be used * for sensitive data. */ static gpg_error_t ec2os (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t p, unsigned char **r_buf, unsigned int *r_buflen) { gpg_error_t err; int pbytes = (mpi_get_nbits (p)+7)/8; size_t n; unsigned char *buf, *ptr; *r_buf = NULL; *r_buflen = 0; buf = xtrymalloc (1 + 2*pbytes); if (!buf) return gpg_error_from_syserror (); *buf = 04; /* Uncompressed point. */ ptr = buf+1; err = gcry_mpi_print (GCRYMPI_FMT_USG, ptr, pbytes, &n, x); if (err) { xfree (buf); return err; } if (n < pbytes) { memmove (ptr+(pbytes-n), ptr, n); memset (ptr, 0, (pbytes-n)); } ptr += pbytes; err = gcry_mpi_print (GCRYMPI_FMT_USG, ptr, pbytes, &n, y); if (err) { xfree (buf); return err; } if (n < pbytes) { memmove (ptr+(pbytes-n), ptr, n); memset (ptr, 0, (pbytes-n)); } *r_buf = buf; *r_buflen = 1 + 2*pbytes; return 0; } /* Convert the ECC parameter Q in the canonical s-expression * (KEYDATA,KEYDATALEN) to uncompressed form. On success and if a * conversion was done, the new canonical encoded s-expression is * returned at (R_NEWKEYDAT,R_NEWKEYDATALEN); if a conversion was not * required (NULL,0) is stored there. On error an error code is * returned. The function may take any kind of key but will only do * the conversion for ECC curves where compression is supported. */ gpg_error_t uncompress_ecc_q_in_canon_sexp (const unsigned char *keydata, size_t keydatalen, unsigned char **r_newkeydata, size_t *r_newkeydatalen) { gpg_error_t err; const unsigned char *buf, *tok; size_t buflen, toklen, n; int depth, last_depth1, last_depth2; const unsigned char *q_ptr; /* Points to the value of "q". */ size_t q_ptrlen; /* Remaining length in KEYDATA. */ size_t q_toklen; /* Q's length including prefix. */ const unsigned char *curve_ptr; /* Points to the value of "curve". */ size_t curve_ptrlen; /* Remaining length in KEYDATA. */ gcry_mpi_t x, y; /* Point Q */ gcry_mpi_t p, a, b; /* Curve parameters. */ gcry_mpi_t x3, t, p1_4; /* Helper */ int y_bit; unsigned char *qvalue; /* Q in uncompressed form. */ unsigned int qvaluelen; unsigned char *dst; /* Helper */ char lenstr[35]; /* Helper for a length prefix. */ *r_newkeydata = NULL; *r_newkeydatalen = 0; buf = keydata; buflen = keydatalen; depth = 0; if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if (!tok) return gpg_error (GPG_ERR_BAD_PUBKEY); else if (toklen == 10 || !memcmp ("public-key", tok, toklen)) ; else if (toklen == 11 || !memcmp ("private-key", tok, toklen)) ; else if (toklen == 20 || !memcmp ("shadowed-private-key", tok, toklen)) ; else return gpg_error (GPG_ERR_BAD_PUBKEY); if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if (tok && toklen == 3 && !memcmp ("ecc", tok, toklen)) ; else if (tok && toklen == 5 && !memcmp ("ecdsa", tok, toklen)) ; else return 0; /* Other algo - no need for conversion. */ last_depth1 = depth; q_ptr = curve_ptr = NULL; q_ptrlen = 0; /*(silence cc warning)*/ while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)) && depth && depth >= last_depth1) { if (tok) return gpg_error (GPG_ERR_UNKNOWN_SEXP); if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if (tok && toklen == 1 && *tok == 'q' && !q_ptr) { q_ptr = buf; q_ptrlen = buflen; } else if (tok && toklen == 5 && !memcmp (tok, "curve", 5) && !curve_ptr) { curve_ptr = buf; curve_ptrlen = buflen; } if (q_ptr && curve_ptr) break; /* We got all what we need. */ /* Skip to the end of the list. */ last_depth2 = depth; while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)) && depth && depth >= last_depth2) ; if (err) return err; } if (err) return err; if (!q_ptr) return 0; /* No Q - nothing to do. */ /* Get Q's value and check whether uncompressing is at all required. */ buf = q_ptr; buflen = q_ptrlen; if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) return err; if (toklen < 2 || !(*tok == 0x02 || *tok == 0x03)) return 0; /* Invalid length or not compressed. */ q_toklen = buf - q_ptr; /* We want the length with the prefix. */ /* Put the x-coordinate of q into X and remember the y bit */ y_bit = (*tok == 0x03); err = gcry_mpi_scan (&x, GCRYMPI_FMT_USG, tok+1, toklen-1, NULL); if (err) return err; /* For uncompressing we need to know the curve. */ if (!curve_ptr) { gcry_mpi_release (x); return gpg_error (GPG_ERR_INV_CURVE); } buf = curve_ptr; buflen = curve_ptrlen; if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))) { gcry_mpi_release (x); return err; } { char name[50]; gcry_sexp_t curveparam; if (toklen + 1 > sizeof name) { gcry_mpi_release (x); return gpg_error (GPG_ERR_TOO_LARGE); } mem2str (name, tok, toklen+1); curveparam = gcry_pk_get_param (GCRY_PK_ECC, name); if (!curveparam) { gcry_mpi_release (x); return gpg_error (GPG_ERR_UNKNOWN_CURVE); } err = gcry_sexp_extract_param (curveparam, NULL, "pab", &p, &a, &b, NULL); gcry_sexp_release (curveparam); if (err) { gcry_mpi_release (x); return gpg_error (GPG_ERR_INTERNAL); } } if (!mpi_test_bit (p, 1)) { /* No support for point compression for this curve. */ gcry_mpi_release (x); gcry_mpi_release (p); gcry_mpi_release (a); gcry_mpi_release (b); return gpg_error (GPG_ERR_NOT_IMPLEMENTED); } /* * Recover Y. The Weierstrass curve: y^2 = x^3 + a*x + b */ x3 = mpi_new (0); t = mpi_new (0); p1_4 = mpi_new (0); y = mpi_new (0); /* Compute right hand side. */ mpi_powm (x3, x, GCRYMPI_CONST_THREE, p); mpi_mul (t, a, x); mpi_mod (t, t, p); mpi_add (t, t, b); mpi_mod (t, t, p); mpi_add (t, t, x3); mpi_mod (t, t, p); /* * When p mod 4 = 3, modular square root of A can be computed by * A^((p+1)/4) mod p */ /* Compute (p+1)/4 into p1_4 */ mpi_rshift (p1_4, p, 2); mpi_add_ui (p1_4, p1_4, 1); mpi_powm (y, t, p1_4, p); if (y_bit != mpi_test_bit (y, 0)) mpi_sub (y, p, y); gcry_mpi_release (p1_4); gcry_mpi_release (t); gcry_mpi_release (x3); gcry_mpi_release (a); gcry_mpi_release (b); err = ec2os (x, y, p, &qvalue, &qvaluelen); gcry_mpi_release (x); gcry_mpi_release (y); gcry_mpi_release (p); if (err) return err; snprintf (lenstr, sizeof lenstr, "%u:", (unsigned int)qvaluelen); /* Note that for simplicity we do not subtract the old length of Q * for the new buffer. */ *r_newkeydata = xtrymalloc (qvaluelen + strlen(lenstr) + qvaluelen); if (!*r_newkeydata) return gpg_error_from_syserror (); dst = *r_newkeydata; n = q_ptr - keydata; memcpy (dst, keydata, n); /* Copy first part of original data. */ dst += n; n = strlen (lenstr); memcpy (dst, lenstr, n); /* Copy new prefix of Q's value. */ dst += n; memcpy (dst, qvalue, qvaluelen); /* Copy new value of Q. */ dst += qvaluelen; log_assert (q_toklen < q_ptrlen); n = q_ptrlen - q_toklen; memcpy (dst, q_ptr + q_toklen, n);/* Copy rest of original data. */ dst += n; *r_newkeydatalen = dst - *r_newkeydata; xfree (qvalue); return 0; } /* Return the algo of a public KEY of SEXP. */ int get_pk_algo_from_key (gcry_sexp_t key) { gcry_sexp_t list; const char *s; size_t n; char algoname[6]; int algo = 0; list = gcry_sexp_nth (key, 1); if (!list) goto out; s = gcry_sexp_nth_data (list, 0, &n); if (!s) goto out; if (n >= sizeof (algoname)) goto out; memcpy (algoname, s, n); algoname[n] = 0; algo = gcry_pk_map_name (algoname); if (algo == GCRY_PK_ECC) { gcry_sexp_t l1 = gcry_sexp_find_token (list, "flags", 0); int i; for (i = l1 ? gcry_sexp_length (l1)-1 : 0; i > 0; i--) { s = gcry_sexp_nth_data (l1, i, &n); if (!s) continue; /* Not a data element. */ if (n == 5 && !memcmp (s, "eddsa", 5)) { algo = GCRY_PK_EDDSA; break; } } gcry_sexp_release (l1); } out: gcry_sexp_release (list); return algo; } /* This is a variant of get_pk_algo_from_key but takes an canonical * encoded S-expression as input. Returns a GCRYPT public key * identiier or 0 on error. */ int get_pk_algo_from_canon_sexp (const unsigned char *keydata, size_t keydatalen) { gcry_sexp_t sexp; int algo; if (gcry_sexp_sscan (&sexp, NULL, keydata, keydatalen)) return 0; algo = get_pk_algo_from_key (sexp); gcry_sexp_release (sexp); return algo; } /* Given the public key S_PKEY, return a new buffer with a descriptive * string for its algorithm. This function may return NULL on memory * error. If R_ALGOID is not NULL the gcrypt algo id is stored there. */ char * pubkey_algo_string (gcry_sexp_t s_pkey, enum gcry_pk_algos *r_algoid) { const char *prefix; gcry_sexp_t l1; char *algoname; int algo; char *result; if (r_algoid) *r_algoid = 0; l1 = gcry_sexp_find_token (s_pkey, "public-key", 0); if (!l1) return xtrystrdup ("E_no_key"); { gcry_sexp_t l_tmp = gcry_sexp_cadr (l1); gcry_sexp_release (l1); l1 = l_tmp; } algoname = gcry_sexp_nth_string (l1, 0); gcry_sexp_release (l1); if (!algoname) return xtrystrdup ("E_no_algo"); algo = gcry_pk_map_name (algoname); switch (algo) { case GCRY_PK_RSA: prefix = "rsa"; break; case GCRY_PK_ELG: prefix = "elg"; break; case GCRY_PK_DSA: prefix = "dsa"; break; case GCRY_PK_ECC: prefix = ""; break; default: prefix = NULL; break; } if (prefix && *prefix) result = xtryasprintf ("%s%u", prefix, gcry_pk_get_nbits (s_pkey)); else if (prefix) { const char *curve = gcry_pk_get_curve (s_pkey, 0, NULL); const char *name = openpgp_oid_to_curve (openpgp_curve_to_oid (curve, NULL, NULL), 0); if (name) result = xtrystrdup (name); else if (curve) result = xtryasprintf ("X_%s", curve); else result = xtrystrdup ("E_unknown"); } else result = xtryasprintf ("X_algo_%d", algo); if (r_algoid) *r_algoid = algo; xfree (algoname); return result; } /* Map a pubkey algo id from gcrypt to a string. This is the same as * gcry_pk_algo_name but makes sure that the ECC algo identifiers are * not all mapped to "ECC". */ const char * pubkey_algo_to_string (int algo) { if (algo == GCRY_PK_ECDSA) return "ECDSA"; else if (algo == GCRY_PK_ECDH) return "ECDH"; else if (algo == GCRY_PK_EDDSA) return "EdDSA"; else return gcry_pk_algo_name (algo); } /* Map a hash algo id from gcrypt to a string. This is the same as * gcry_md_algo_name but the returned string is lower case, as * expected by libksba and it avoids some overhead. */ const char * hash_algo_to_string (int algo) { static const struct { const char *name; int algo; } hashnames[] = { { "sha256", GCRY_MD_SHA256 }, { "sha512", GCRY_MD_SHA512 }, { "sha1", GCRY_MD_SHA1 }, { "sha384", GCRY_MD_SHA384 }, { "sha224", GCRY_MD_SHA224 }, { "sha3-224", GCRY_MD_SHA3_224 }, { "sha3-256", GCRY_MD_SHA3_256 }, { "sha3-384", GCRY_MD_SHA3_384 }, { "sha3-512", GCRY_MD_SHA3_512 }, { "ripemd160", GCRY_MD_RMD160 }, { "rmd160", GCRY_MD_RMD160 }, { "md2", GCRY_MD_MD2 }, { "md4", GCRY_MD_MD4 }, { "tiger", GCRY_MD_TIGER }, { "haval", GCRY_MD_HAVAL }, #if GCRYPT_VERSION_NUMBER >= 0x010900 { "sm3", GCRY_MD_SM3 }, #endif { "md5", GCRY_MD_MD5 } }; int i; for (i=0; i < DIM (hashnames); i++) if (algo == hashnames[i].algo) return hashnames[i].name; return "?"; } + + +/* Map cipher modes to a string. */ +const char * +cipher_mode_to_string (int mode) +{ + switch (mode) + { + case GCRY_CIPHER_MODE_CFB: return "CFB"; + case GCRY_CIPHER_MODE_CBC: return "CBC"; + case GCRY_CIPHER_MODE_GCM: return "GCM"; + case GCRY_CIPHER_MODE_OCB: return "OCB"; + case 14: return "EAX"; /* Only in gcrypt 1.9 */ + default: return "[?]"; + } +} diff --git a/common/util.h b/common/util.h index f0933888d..cd2feab67 100644 --- a/common/util.h +++ b/common/util.h @@ -1,407 +1,408 @@ /* util.h - Utility functions for GnuPG * Copyright (C) 2001, 2002, 2003, 2004, 2009 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute and/or modify this * part of GnuPG under the terms of either * * - the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at * your option) any later version. * * or * * - the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at * your option) any later version. * * or both in parallel, as here. * * GnuPG is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copies of the GNU General Public License * and the GNU Lesser General Public License along with this program; * if not, see . */ #ifndef GNUPG_COMMON_UTIL_H #define GNUPG_COMMON_UTIL_H #include /* We need this for the memory function protos. */ #include /* We need errno. */ #include /* We need gpg_error_t and estream. */ /* These error codes might be used but not defined in the required * libgpg-error version. Define them here. * Example: (#if GPG_ERROR_VERSION_NUMBER < 0x011500 // 1.21) */ #if GPG_ERROR_VERSION_NUMBER < 0x012400 /* 1.36 */ # define GPG_ERR_NO_AUTH 314 # define GPG_ERR_BAD_AUTH 315 #endif #ifndef EXTERN_UNLESS_MAIN_MODULE # if !defined (INCLUDED_BY_MAIN_MODULE) # define EXTERN_UNLESS_MAIN_MODULE extern # else # define EXTERN_UNLESS_MAIN_MODULE # endif #endif /* Hash function used with libksba. */ #define HASH_FNC ((void (*)(void *, const void*,size_t))gcry_md_write) /* The length of the keygrip. This is a SHA-1 hash of the key * parameters as generated by gcry_pk_get_keygrip. */ #define KEYGRIP_LEN 20 /* Get all the stuff from jnlib. */ #include "../common/logging.h" #include "../common/argparse.h" #include "../common/stringhelp.h" #include "../common/mischelp.h" #include "../common/strlist.h" #include "../common/dotlock.h" #include "../common/utf8conv.h" #include "../common/dynload.h" #include "../common/fwddecl.h" #include "../common/utilproto.h" #include "gettime.h" /* Redefine asprintf by our estream version which uses our own memory allocator.. */ #define asprintf gpgrt_asprintf #define vasprintf gpgrt_vasprintf /* Due to a bug in mingw32's snprintf related to the 'l' modifier and for increased portability we use our snprintf on all systems. */ #undef snprintf #define snprintf gpgrt_snprintf /* Replacements for macros not available with libgpg-error < 1.20. */ /* We need this type even if we are not using libreadline and or we did not include libreadline in the current file. */ #ifndef GNUPG_LIBREADLINE_H_INCLUDED typedef char **rl_completion_func_t (const char *, int, int); #endif /*!GNUPG_LIBREADLINE_H_INCLUDED*/ /* Handy malloc macros - please use only them. */ #define xtrymalloc(a) gcry_malloc ((a)) #define xtrymalloc_secure(a) gcry_malloc_secure ((a)) #define xtrycalloc(a,b) gcry_calloc ((a),(b)) #define xtrycalloc_secure(a,b) gcry_calloc_secure ((a),(b)) #define xtryrealloc(a,b) gcry_realloc ((a),(b)) #define xtrystrdup(a) gcry_strdup ((a)) #define xfree(a) gcry_free ((a)) #define xfree_fnc gcry_free #define xmalloc(a) gcry_xmalloc ((a)) #define xmalloc_secure(a) gcry_xmalloc_secure ((a)) #define xcalloc(a,b) gcry_xcalloc ((a),(b)) #define xcalloc_secure(a,b) gcry_xcalloc_secure ((a),(b)) #define xrealloc(a,b) gcry_xrealloc ((a),(b)) #define xstrdup(a) gcry_xstrdup ((a)) /* For compatibility with gpg 1.4 we also define these: */ #define xmalloc_clear(a) gcry_xcalloc (1, (a)) #define xmalloc_secure_clear(a) gcry_xcalloc_secure (1, (a)) /* The default error source of the application. This is different from GPG_ERR_SOURCE_DEFAULT in that it does not depend on the source file and thus is usable in code shared by applications. Defined by init.c. */ extern gpg_err_source_t default_errsource; /* Convenience function to return a gpg-error code for memory allocation failures. This function makes sure that an error will be returned even if accidentally ERRNO is not set. */ static inline gpg_error_t out_of_core (void) { return gpg_error_from_syserror (); } /*-- yesno.c --*/ int answer_is_yes (const char *s); int answer_is_yes_no_default (const char *s, int def_answer); int answer_is_yes_no_quit (const char *s); int answer_is_okay_cancel (const char *s, int def_answer); /*-- xreadline.c --*/ ssize_t read_line (FILE *fp, char **addr_of_buffer, size_t *length_of_buffer, size_t *max_length); /*-- b64enc.c and b64dec.c --*/ struct b64state { unsigned int flags; int idx; int quad_count; FILE *fp; estream_t stream; char *title; unsigned char radbuf[4]; u32 crc; int stop_seen:1; int invalid_encoding:1; gpg_error_t lasterr; }; gpg_error_t b64enc_start (struct b64state *state, FILE *fp, const char *title); gpg_error_t b64enc_start_es (struct b64state *state, estream_t fp, const char *title); gpg_error_t b64enc_write (struct b64state *state, const void *buffer, size_t nbytes); gpg_error_t b64enc_finish (struct b64state *state); gpg_error_t b64dec_start (struct b64state *state, const char *title); gpg_error_t b64dec_proc (struct b64state *state, void *buffer, size_t length, size_t *r_nbytes); gpg_error_t b64dec_finish (struct b64state *state); /*-- sexputil.c */ char *canon_sexp_to_string (const unsigned char *canon, size_t canonlen); void log_printcanon (const char *text, const unsigned char *sexp, size_t sexplen); void log_printsexp (const char *text, gcry_sexp_t sexp); gpg_error_t make_canon_sexp (gcry_sexp_t sexp, unsigned char **r_buffer, size_t *r_buflen); gpg_error_t make_canon_sexp_pad (gcry_sexp_t sexp, int secure, unsigned char **r_buffer, size_t *r_buflen); gpg_error_t keygrip_from_canon_sexp (const unsigned char *key, size_t keylen, unsigned char *grip); int cmp_simple_canon_sexp (const unsigned char *a, const unsigned char *b); int cmp_canon_sexp (const unsigned char *a, size_t alen, const unsigned char *b, size_t blen, int (*tcmp)(void *ctx, int depth, const unsigned char *aval, size_t avallen, const unsigned char *bval, size_t bvallen), void *tcmpctx); unsigned char *make_simple_sexp_from_hexstr (const char *line, size_t *nscanned); int hash_algo_from_sigval (const unsigned char *sigval); unsigned char *make_canon_sexp_from_rsa_pk (const void *m, size_t mlen, const void *e, size_t elen, size_t *r_len); gpg_error_t get_rsa_pk_from_canon_sexp (const unsigned char *keydata, size_t keydatalen, unsigned char const **r_n, size_t *r_nlen, unsigned char const **r_e, size_t *r_elen); gpg_error_t get_ecc_q_from_canon_sexp (const unsigned char *keydata, size_t keydatalen, unsigned char const **r_q, size_t *r_qlen); gpg_error_t uncompress_ecc_q_in_canon_sexp (const unsigned char *keydata, size_t keydatalen, unsigned char **r_newkeydata, size_t *r_newkeydatalen); int get_pk_algo_from_key (gcry_sexp_t key); int get_pk_algo_from_canon_sexp (const unsigned char *keydata, size_t keydatalen); char *pubkey_algo_string (gcry_sexp_t s_pkey, enum gcry_pk_algos *r_algoid); const char *pubkey_algo_to_string (int algo); const char *hash_algo_to_string (int algo); +const char *cipher_mode_to_string (int mode); /*-- convert.c --*/ int hex2bin (const char *string, void *buffer, size_t length); int hexcolon2bin (const char *string, void *buffer, size_t length); char *bin2hex (const void *buffer, size_t length, char *stringbuf); char *bin2hexcolon (const void *buffer, size_t length, char *stringbuf); const char *hex2str (const char *hexstring, char *buffer, size_t bufsize, size_t *buflen); char *hex2str_alloc (const char *hexstring, size_t *r_count); /*-- percent.c --*/ char *percent_plus_escape (const char *string); char *percent_data_escape (int plus_escape, const char *prefix, const void *data, size_t datalen); char *percent_plus_unescape (const char *string, int nulrepl); char *percent_unescape (const char *string, int nulrepl); size_t percent_plus_unescape_inplace (char *string, int nulrepl); size_t percent_unescape_inplace (char *string, int nulrepl); /*-- openpgp-oid.c --*/ gpg_error_t openpgp_oid_from_str (const char *string, gcry_mpi_t *r_mpi); char *openpgp_oidbuf_to_str (const unsigned char *buf, size_t len); char *openpgp_oid_to_str (gcry_mpi_t a); int openpgp_oidbuf_is_ed25519 (const void *buf, size_t len); int openpgp_oid_is_ed25519 (gcry_mpi_t a); int openpgp_oidbuf_is_cv25519 (const void *buf, size_t len); int openpgp_oid_is_cv25519 (gcry_mpi_t a); const char *openpgp_curve_to_oid (const char *name, unsigned int *r_nbits, int *r_algo); const char *openpgp_oid_to_curve (const char *oid, int canon); const char *openpgp_enum_curves (int *idxp); const char *openpgp_is_curve_supported (const char *name, int *r_algo, unsigned int *r_nbits); /*-- homedir.c --*/ const char *standard_homedir (void); const char *default_homedir (void); void gnupg_set_homedir (const char *newdir); void gnupg_maybe_make_homedir (const char *fname, int quiet); const char *gnupg_homedir (void); int gnupg_default_homedir_p (void); const char *gnupg_daemon_rootdir (void); const char *gnupg_socketdir (void); const char *gnupg_sysconfdir (void); const char *gnupg_bindir (void); const char *gnupg_libexecdir (void); const char *gnupg_libdir (void); const char *gnupg_datadir (void); const char *gnupg_localedir (void); const char *gnupg_cachedir (void); const char *dirmngr_socket_name (void); char *_gnupg_socketdir_internal (int skip_checks, unsigned *r_info); /* All module names. We also include gpg and gpgsm for the sake for gpgconf. */ #define GNUPG_MODULE_NAME_AGENT 1 #define GNUPG_MODULE_NAME_PINENTRY 2 #define GNUPG_MODULE_NAME_SCDAEMON 3 #define GNUPG_MODULE_NAME_DIRMNGR 4 #define GNUPG_MODULE_NAME_PROTECT_TOOL 5 #define GNUPG_MODULE_NAME_CHECK_PATTERN 6 #define GNUPG_MODULE_NAME_GPGSM 7 #define GNUPG_MODULE_NAME_GPG 8 #define GNUPG_MODULE_NAME_CONNECT_AGENT 9 #define GNUPG_MODULE_NAME_GPGCONF 10 #define GNUPG_MODULE_NAME_DIRMNGR_LDAP 11 #define GNUPG_MODULE_NAME_GPGV 12 const char *gnupg_module_name (int which); void gnupg_module_name_flush_some (void); void gnupg_set_builddir (const char *newdir); /*-- gpgrlhelp.c --*/ void gnupg_rl_initialize (void); /*-- helpfile.c --*/ char *gnupg_get_help_string (const char *key, int only_current_locale); /*-- localename.c --*/ const char *gnupg_messages_locale_name (void); /*-- sysutils.c --*/ FILE *gnupg_fopen (const char *fname, const char *mode); /*-- miscellaneous.c --*/ /* This function is called at startup to tell libgcrypt to use our own logging subsystem. */ void setup_libgcrypt_logging (void); /* Print an out of core message and die. */ void xoutofcore (void); /* Same as estream_asprintf but die on memory failure. */ char *xasprintf (const char *fmt, ...) GPGRT_ATTR_PRINTF(1,2); /* This is now an alias to estream_asprintf. */ char *xtryasprintf (const char *fmt, ...) GPGRT_ATTR_PRINTF(1,2); /* Replacement for gcry_cipher_algo_name. */ const char *gnupg_cipher_algo_name (int algo); void obsolete_option (const char *configname, unsigned int configlineno, const char *name); const char *print_fname_stdout (const char *s); const char *print_fname_stdin (const char *s); void print_utf8_buffer3 (estream_t fp, const void *p, size_t n, const char *delim); void print_utf8_buffer2 (estream_t fp, const void *p, size_t n, int delim); void print_utf8_buffer (estream_t fp, const void *p, size_t n); void print_utf8_string (estream_t stream, const char *p); void print_hexstring (FILE *fp, const void *buffer, size_t length, int reserved); char *try_make_printable_string (const void *p, size_t n, int delim); char *make_printable_string (const void *p, size_t n, int delim); int is_file_compressed (const char *s, int *ret_rc); int match_multistr (const char *multistr,const char *match); int gnupg_compare_version (const char *a, const char *b); struct debug_flags_s { unsigned int flag; const char *name; }; int parse_debug_flag (const char *string, unsigned int *debugvar, const struct debug_flags_s *flags); /*-- Simple replacement functions. */ /* We use the gnupg_ttyname macro to be safe not to run into conflicts which an extisting but broken ttyname. */ #if !defined(HAVE_TTYNAME) || defined(HAVE_BROKEN_TTYNAME) # define gnupg_ttyname(n) _gnupg_ttyname ((n)) /* Systems without ttyname (W32) will merely return NULL. */ static inline char * _gnupg_ttyname (int fd) { (void)fd; return NULL; } #else /*HAVE_TTYNAME*/ # define gnupg_ttyname(n) ttyname ((n)) #endif /*HAVE_TTYNAME */ #ifdef HAVE_W32CE_SYSTEM #define getpid() GetCurrentProcessId () char *_gnupg_getenv (const char *name); /* See sysutils.c */ #define getenv(a) _gnupg_getenv ((a)) char *_gnupg_setenv (const char *name); /* See sysutils.c */ #define setenv(a,b,c) _gnupg_setenv ((a),(b),(c)) int _gnupg_isatty (int fd); #define gnupg_isatty(a) _gnupg_isatty ((a)) #else #define gnupg_isatty(a) isatty ((a)) #endif /*-- Macros to replace ctype ones to avoid locale problems. --*/ #define spacep(p) (*(p) == ' ' || *(p) == '\t') #define digitp(p) (*(p) >= '0' && *(p) <= '9') #define alphap(p) ((*(p) >= 'A' && *(p) <= 'Z') \ || (*(p) >= 'a' && *(p) <= 'z')) #define alnump(p) (alphap (p) || digitp (p)) #define hexdigitp(a) (digitp (a) \ || (*(a) >= 'A' && *(a) <= 'F') \ || (*(a) >= 'a' && *(a) <= 'f')) /* Note this isn't identical to a C locale isspace() without \f and \v, but works for the purposes used here. */ #define ascii_isspace(a) ((a)==' ' || (a)=='\n' || (a)=='\r' || (a)=='\t') /* The atoi macros assume that the buffer has only valid digits. */ #define atoi_1(p) (*(p) - '0' ) #define atoi_2(p) ((atoi_1(p) * 10) + atoi_1((p)+1)) #define atoi_4(p) ((atoi_2(p) * 100) + atoi_2((p)+2)) #define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \ *(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10)) #define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1)) #define xtoi_4(p) ((xtoi_2(p) * 256) + xtoi_2((p)+2)) #endif /*GNUPG_COMMON_UTIL_H*/ diff --git a/sm/decrypt.c b/sm/decrypt.c index 93be59b33..aba01cb6b 100644 --- a/sm/decrypt.c +++ b/sm/decrypt.c @@ -1,648 +1,1067 @@ /* decrypt.c - Decrypt a message * Copyright (C) 2001, 2003, 2010 Free Software Foundation, Inc. + * Copyright (C) 2001-2019 Werner Koch + * Copyright (C) 2015-2021 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . + * SPDX-License-Identifier: GPL-3.0-or-later */ #include #include #include #include #include #include #include #include #include "gpgsm.h" #include #include #include "keydb.h" #include "../common/i18n.h" #include "../common/compliance.h" +#include "../common/tlv.h" struct decrypt_filter_parm_s { int algo; int mode; int blklen; gcry_cipher_hd_t hd; char iv[16]; size_t ivlen; int any_data; /* did we push anything through the filter at all? */ unsigned char lastblock[16]; /* to strip the padding we have to keep this one */ char helpblock[16]; /* needed because there is no block buffering in libgcrypt (yet) */ int helpblocklen; + int is_de_vs; /* Helper to track CO_DE_VS state. */ }; +/* Return the hash algorithm's algo id from its name given in the + * non-null termnated string in (buffer,buflen). Returns 0 on failure + * or if the algo is not known. */ +static char * +string_from_gcry_buffer (gcry_buffer_t *buffer) +{ + char *string; + + string = xtrymalloc (buffer->len + 1); + if (!string) + return NULL; + memcpy (string, buffer->data, buffer->len); + string[buffer->len] = 0; + return string; +} + + +/* Helper for pwri_decrypt to parse the derive info. + * Example data for (DER,DERLEN): + * SEQUENCE { + * OCTET STRING + * 60 76 4B E9 5E DF 3C F8 B2 F9 B6 C2 7D 5A FB 90 + * 23 B6 47 DF + * INTEGER 10000 + * SEQUENCE { + * OBJECT IDENTIFIER + * hmacWithSHA512 (1 2 840 113549 2 11) + * NULL + * } + * } + */ +static gpg_error_t +pwri_parse_pbkdf2 (const unsigned char *der, size_t derlen, + unsigned char const **r_salt, unsigned int *r_saltlen, + unsigned long *r_iterations, + enum gcry_md_algos *r_digest) +{ + gpg_error_t err; + size_t objlen, hdrlen; + int class, tag, constructed, ndef; + char *oidstr; + + err = parse_ber_header (&der, &derlen, &class, &tag, &constructed, + &ndef, &objlen, &hdrlen); + if (!err && (objlen > derlen || tag != TAG_SEQUENCE + || !constructed || ndef)) + err = gpg_error (GPG_ERR_INV_OBJ); + if (err) + return err; + derlen = objlen; + + err = parse_ber_header (&der, &derlen, &class, &tag, &constructed, + &ndef, &objlen, &hdrlen); + if (!err && (objlen > derlen || tag != TAG_OCTET_STRING + || constructed || ndef)) + err = gpg_error (GPG_ERR_INV_OBJ); + if (err) + return err; + *r_salt = der; + *r_saltlen = objlen; + der += objlen; + derlen -= objlen; + + err = parse_ber_header (&der, &derlen, &class, &tag, &constructed, + &ndef, &objlen, &hdrlen); + if (!err && (objlen > derlen || tag != TAG_INTEGER + || constructed || ndef)) + err = gpg_error (GPG_ERR_INV_OBJ); + if (err) + return err; + *r_iterations = 0; + for (; objlen; objlen--) + { + *r_iterations <<= 8; + *r_iterations |= (*der++) & 0xff; + derlen--; + } + + err = parse_ber_header (&der, &derlen, &class, &tag, &constructed, + &ndef, &objlen, &hdrlen); + if (!err && (objlen > derlen || tag != TAG_SEQUENCE + || !constructed || ndef)) + err = gpg_error (GPG_ERR_INV_OBJ); + if (err) + return err; + derlen = objlen; + + err = parse_ber_header (&der, &derlen, &class, &tag, &constructed, + &ndef, &objlen, &hdrlen); + if (!err && (objlen > derlen || tag != TAG_OBJECT_ID + || constructed || ndef)) + err = gpg_error (GPG_ERR_INV_OBJ); + if (err) + return err; + + oidstr = ksba_oid_to_str (der, objlen); + if (!oidstr) + return gpg_error_from_syserror (); + *r_digest = gcry_md_map_name (oidstr); + if (*r_digest) + ; + else if (!strcmp (oidstr, "1.2.840.113549.2.7")) + *r_digest = GCRY_MD_SHA1; + else if (!strcmp (oidstr, "1.2.840.113549.2.8")) + *r_digest = GCRY_MD_SHA224; + else if (!strcmp (oidstr, "1.2.840.113549.2.9")) + *r_digest = GCRY_MD_SHA256; + else if (!strcmp (oidstr, "1.2.840.113549.2.10")) + *r_digest = GCRY_MD_SHA384; + else if (!strcmp (oidstr, "1.2.840.113549.2.11")) + *r_digest = GCRY_MD_SHA512; + else + err = gpg_error (GPG_ERR_DIGEST_ALGO); + ksba_free (oidstr); + + return err; +} + + +/* Password based decryption. + * ENC_VAL has the form: + * (enc-val + * (pwri + * (derive-algo ) --| both are optional + * (derive-parm ) --| + * (encr-algo ) + * (encr-parm ) + * (encr-key ))) -- this is the encrypted session key + * + */ +static gpg_error_t +pwri_decrypt (gcry_sexp_t enc_val, + unsigned char **r_result, unsigned int *r_resultlen, + struct decrypt_filter_parm_s *parm) +{ + gpg_error_t err; + gcry_buffer_t ioarray[5] = { {0} }; + char *derive_algo_str = NULL; + char *encr_algo_str = NULL; + const unsigned char *dparm; /* Alias for ioarray[1]. */ + unsigned int dparmlen; + const unsigned char *eparm; /* Alias for ioarray[3]. */ + unsigned int eparmlen; + const unsigned char *ekey; /* Alias for ioarray[4]. */ + unsigned int ekeylen; + unsigned char kek[32]; + unsigned int keklen; + enum gcry_cipher_algos encr_algo; + enum gcry_cipher_modes encr_mode; + gcry_cipher_hd_t encr_hd = NULL; + unsigned char *result = NULL; + unsigned int resultlen; + unsigned int blklen; + const unsigned char *salt; /* Points int dparm. */ + unsigned int saltlen; + unsigned long iterations; + enum gcry_md_algos digest_algo; + + + *r_resultlen = 0; + *r_result = NULL; + + err = gcry_sexp_extract_param (enc_val, "enc-val!pwri", + "&'derive-algo'?'derive-parm'?" + "'encr-algo''encr-parm''encr-key'", + ioarray+0, ioarray+1, + ioarray+2, ioarray+3, ioarray+4, NULL); + if (err) + { + /* If this is not pwri element, it is likly a kekri element + * which we do not yet support. Change the error back to the + * original as returned by ksba_cms_get_issuer. */ + if (gpg_err_code (err) == GPG_ERR_NOT_FOUND) + err = gpg_error (GPG_ERR_UNSUPPORTED_CMS_OBJ); + else + log_error ("extracting PWRI parameter failed: %s\n", + gpg_strerror (err)); + goto leave; + } + + if (ioarray[0].data) + { + derive_algo_str = string_from_gcry_buffer (ioarray+0); + if (!derive_algo_str) + { + err = gpg_error_from_syserror (); + goto leave; + } + } + dparm = ioarray[1].data; + dparmlen = ioarray[1].len; + encr_algo_str = string_from_gcry_buffer (ioarray+2); + if (!encr_algo_str) + { + err = gpg_error_from_syserror (); + goto leave; + } + eparm = ioarray[3].data; + eparmlen = ioarray[3].len; + ekey = ioarray[4].data; + ekeylen = ioarray[4].len; + + /* Check parameters. */ + if (DBG_CRYPTO) + { + if (derive_algo_str) + { + log_debug ("derive algo: %s\n", derive_algo_str); + log_printhex (dparm, dparmlen, "derive parm:"); + } + log_debug ("encr algo .: %s\n", encr_algo_str); + log_printhex (eparm, eparmlen, "encr parm .:"); + log_printhex (ekey, ekeylen, "encr key .:"); + } + + if (!derive_algo_str) + { + err = gpg_error (GPG_ERR_NOT_SUPPORTED); + log_info ("PWRI with no key derivation detected\n"); + goto leave; + } + if (strcmp (derive_algo_str, "1.2.840.113549.1.5.12")) + { + err = gpg_error (GPG_ERR_NOT_SUPPORTED); + log_info ("PWRI does not use PBKDF2 (but %s)\n", derive_algo_str); + goto leave; + } + + digest_algo = 0; /*(silence cc warning)*/ + err = pwri_parse_pbkdf2 (dparm, dparmlen, + &salt, &saltlen, &iterations, &digest_algo); + if (err) + { + log_error ("parsing PWRI parameter failed: %s\n", gpg_strerror (err)); + goto leave; + } + + parm->is_de_vs = (parm->is_de_vs + && gnupg_digest_is_compliant (CO_DE_VS, digest_algo)); + + + encr_algo = gcry_cipher_map_name (encr_algo_str); + encr_mode = gcry_cipher_mode_from_oid (encr_algo_str); + if (!encr_algo || !encr_mode) + { + log_error ("PWRI uses unknown algorithm %s\n", encr_algo_str); + err = gpg_error (GPG_ERR_CIPHER_ALGO); + goto leave; + } + + parm->is_de_vs = + (parm->is_de_vs + && gnupg_cipher_is_compliant (CO_DE_VS, encr_algo, encr_mode)); + + keklen = gcry_cipher_get_algo_keylen (encr_algo); + blklen = gcry_cipher_get_algo_blklen (encr_algo); + if (!keklen || keklen > sizeof kek || blklen != 16 ) + { + log_error ("PWRI algorithm %s cannot be used\n", encr_algo_str); + err = gpg_error (GPG_ERR_INV_KEYLEN); + goto leave; + } + if ((ekeylen % blklen) || (ekeylen / blklen < 2)) + { + /* Note that we need at least two full blocks. */ + log_error ("PWRI uses a wrong length of encrypted key\n"); + err = gpg_error (GPG_ERR_INV_KEYLEN); + goto leave; + } + + err = gcry_kdf_derive ("abc", 3, + GCRY_KDF_PBKDF2, digest_algo, + salt, saltlen, iterations, + keklen, kek); + if (err) + { + log_error ("deriving key from passphrase failed: %s\n", + gpg_strerror (err)); + goto leave; + } + + if (DBG_CRYPTO) + log_printhex (kek, keklen, "KEK .......:"); + + /* Unwrap the key. */ + resultlen = ekeylen; + result = xtrymalloc_secure (resultlen); + if (!result) + { + err = gpg_error_from_syserror (); + goto leave; + } + + err = gcry_cipher_open (&encr_hd, encr_algo, encr_mode, 0); + if (err) + { + log_error ("PWRI failed to open cipher: %s\n", gpg_strerror (err)); + goto leave; + } + + err = gcry_cipher_setkey (encr_hd, kek, keklen); + wipememory (kek, sizeof kek); + if (!err) + err = gcry_cipher_setiv (encr_hd, ekey + ekeylen - 2 * blklen, blklen); + if (!err) + err = gcry_cipher_decrypt (encr_hd, result + ekeylen - blklen, blklen, + ekey + ekeylen - blklen, blklen); + if (!err) + err = gcry_cipher_setiv (encr_hd, result + ekeylen - blklen, blklen); + if (!err) + err = gcry_cipher_decrypt (encr_hd, result, ekeylen - blklen, + ekey, ekeylen - blklen); + /* (We assume that that eparm is the octet string with the IV) */ + if (!err) + err = gcry_cipher_setiv (encr_hd, eparm, eparmlen); + if (!err) + err = gcry_cipher_decrypt (encr_hd, result, resultlen, NULL, 0); + + if (err) + { + log_error ("KEK decryption failed for PWRI: %s\n", gpg_strerror (err)); + goto leave; + } + + if (DBG_CRYPTO) + log_printhex (result, resultlen, "Frame .....:"); + + if (result[0] < 8 /* At least 64 bits */ + || (result[0] % 8) /* Multiple of 64 bits */ + || result[0] > resultlen - 4 /* Not more than the size of the input */ + || ( (result[1] ^ result[4]) /* Matching check bytes. */ + & (result[2] ^ result[5]) + & (result[3] ^ result[6]) ) != 0xff) + { + err = gpg_error (GPG_ERR_BAD_PASSPHRASE); + goto leave; + } + + *r_resultlen = result[0]; + *r_result = memmove (result, result + 4, result[0]); + result = NULL; + + leave: + if (result) + { + wipememory (result, resultlen); + xfree (result); + } + gcry_cipher_close (encr_hd); + xfree (derive_algo_str); + xfree (encr_algo_str); + xfree (ioarray[0].data); + xfree (ioarray[1].data); + xfree (ioarray[2].data); + xfree (ioarray[3].data); + xfree (ioarray[4].data); + return err; +} + /* Decrypt the session key and fill in the parm structure. The algo and the IV is expected to be already in PARM. */ static int prepare_decryption (ctrl_t ctrl, const char *hexkeygrip, const char *desc, ksba_const_sexp_t enc_val, struct decrypt_filter_parm_s *parm) { char *seskey = NULL; size_t n, seskeylen; + int pwri = !hexkeygrip; int rc; - rc = gpgsm_agent_pkdecrypt (ctrl, hexkeygrip, desc, enc_val, - &seskey, &seskeylen); - if (rc) + if (DBG_CRYPTO) + log_printcanon ("decrypting:", enc_val, 0); + + if (!pwri) { - log_error ("error decrypting session key: %s\n", gpg_strerror (rc)); - goto leave; + rc = gpgsm_agent_pkdecrypt (ctrl, hexkeygrip, desc, enc_val, + &seskey, &seskeylen); + if (rc) + { + log_error ("error decrypting session key: %s\n", gpg_strerror (rc)); + goto leave; + } } - if (DBG_CRYPTO) - log_printhex (seskey, seskeylen, "pkcs1 encoded session key:"); - n=0; - if (seskeylen == 32 || seskeylen == 24 || seskeylen == 16) + if (pwri) /* Password based encryption. */ + { + gcry_sexp_t s_enc_val; + unsigned char *decrypted; + unsigned int decryptedlen; + + rc = gcry_sexp_sscan (&s_enc_val, NULL, enc_val, + gcry_sexp_canon_len (enc_val, 0, NULL, NULL)); + if (rc) + goto leave; + + rc = pwri_decrypt (s_enc_val, &decrypted, &decryptedlen, parm); + gcry_sexp_release (s_enc_val); + if (rc) + goto leave; + xfree (seskey); + seskey = decrypted; + seskeylen = decryptedlen; + } + else if (seskeylen == 32 || seskeylen == 24 || seskeylen == 16) { /* Smells like an AES-128, 3-DES, or AES-256 key. This might * happen because a SC has already done the unpacking. A better * solution would be to test for this only after we triggered * the GPG_ERR_INV_SESSION_KEY. */ } else { if (n + 7 > seskeylen ) { rc = gpg_error (GPG_ERR_INV_SESSION_KEY); goto leave; } /* FIXME: Actually the leading zero is required but due to the way we encode the output in libgcrypt as an MPI we are not able to encode that leading zero. However, when using a Smartcard we are doing it the right way and therefore we have to skip the zero. This should be fixed in gpg-agent of course. */ if (!seskey[n]) n++; if (seskey[n] != 2 ) /* Wrong block type version. */ { rc = gpg_error (GPG_ERR_INV_SESSION_KEY); goto leave; } for (n++; n < seskeylen && seskey[n]; n++) /* Skip the random bytes. */ ; n++; /* and the zero byte */ if (n >= seskeylen ) { rc = gpg_error (GPG_ERR_INV_SESSION_KEY); goto leave; } } if (DBG_CRYPTO) log_printhex (seskey+n, seskeylen-n, "session key:"); + if (opt.verbose) + log_info (_("%s.%s encrypted data\n"), + gcry_cipher_algo_name (parm->algo), + cipher_mode_to_string (parm->mode)); + rc = gcry_cipher_open (&parm->hd, parm->algo, parm->mode, 0); if (rc) { log_error ("error creating decryptor: %s\n", gpg_strerror (rc)); goto leave; } rc = gcry_cipher_setkey (parm->hd, seskey+n, seskeylen-n); if (gpg_err_code (rc) == GPG_ERR_WEAK_KEY) { log_info (_("WARNING: message was encrypted with " "a weak key in the symmetric cipher.\n")); rc = 0; } if (rc) { log_error("key setup failed: %s\n", gpg_strerror(rc) ); goto leave; } - gcry_cipher_setiv (parm->hd, parm->iv, parm->ivlen); + rc = gcry_cipher_setiv (parm->hd, parm->iv, parm->ivlen); + if (rc) + { + log_error("IV setup failed: %s\n", gpg_strerror(rc) ); + goto leave; + } leave: xfree (seskey); return rc; } /* This function is called by the KSBA writer just before the actual write is done. The function must take INLEN bytes from INBUF, decrypt it and store it inoutbuf which has a maximum size of maxoutlen. The valid bytes in outbuf should be return in outlen. Due to different buffer sizes or different length of input and output, it may happen that fewer bytes are processed or fewer bytes are written. */ static gpg_error_t decrypt_filter (void *arg, const void *inbuf, size_t inlen, size_t *inused, void *outbuf, size_t maxoutlen, size_t *outlen) { struct decrypt_filter_parm_s *parm = arg; int blklen = parm->blklen; size_t orig_inlen = inlen; /* fixme: Should we issue an error when we have not seen one full block? */ if (!inlen) return gpg_error (GPG_ERR_BUG); if (maxoutlen < 2*parm->blklen) return gpg_error (GPG_ERR_BUG); /* Make some space because we will later need an extra block at the end. */ maxoutlen -= blklen; if (parm->helpblocklen) { int i, j; for (i=parm->helpblocklen,j=0; i < blklen && j < inlen; i++, j++) parm->helpblock[i] = ((const char*)inbuf)[j]; inlen -= j; if (blklen > maxoutlen) return gpg_error (GPG_ERR_BUG); if (i < blklen) { parm->helpblocklen = i; *outlen = 0; } else { parm->helpblocklen = 0; if (parm->any_data) { memcpy (outbuf, parm->lastblock, blklen); *outlen =blklen; } else *outlen = 0; gcry_cipher_decrypt (parm->hd, parm->lastblock, blklen, parm->helpblock, blklen); parm->any_data = 1; } *inused = orig_inlen - inlen; return 0; } if (inlen > maxoutlen) inlen = maxoutlen; if (inlen % blklen) { /* store the remainder away */ parm->helpblocklen = inlen%blklen; inlen = inlen/blklen*blklen; memcpy (parm->helpblock, (const char*)inbuf+inlen, parm->helpblocklen); } *inused = inlen + parm->helpblocklen; if (inlen) { assert (inlen >= blklen); if (parm->any_data) { gcry_cipher_decrypt (parm->hd, (char*)outbuf+blklen, inlen, inbuf, inlen); memcpy (outbuf, parm->lastblock, blklen); memcpy (parm->lastblock,(char*)outbuf+inlen, blklen); *outlen = inlen; } else { gcry_cipher_decrypt (parm->hd, outbuf, inlen, inbuf, inlen); memcpy (parm->lastblock, (char*)outbuf+inlen-blklen, blklen); *outlen = inlen - blklen; parm->any_data = 1; } } else *outlen = 0; return 0; } /* Perform a decrypt operation. */ int gpgsm_decrypt (ctrl_t ctrl, int in_fd, estream_t out_fp) { int rc; gnupg_ksba_io_t b64reader = NULL; gnupg_ksba_io_t b64writer = NULL; ksba_reader_t reader; ksba_writer_t writer; ksba_cms_t cms = NULL; ksba_stop_reason_t stopreason; KEYDB_HANDLE kh; int recp; estream_t in_fp = NULL; struct decrypt_filter_parm_s dfparm; memset (&dfparm, 0, sizeof dfparm); audit_set_type (ctrl->audit, AUDIT_TYPE_DECRYPT); kh = keydb_new (); if (!kh) { log_error (_("failed to allocate keyDB handle\n")); rc = gpg_error (GPG_ERR_GENERAL); goto leave; } in_fp = es_fdopen_nc (in_fd, "rb"); if (!in_fp) { rc = gpg_error_from_syserror (); log_error ("fdopen() failed: %s\n", strerror (errno)); goto leave; } rc = gnupg_ksba_create_reader (&b64reader, ((ctrl->is_pem? GNUPG_KSBA_IO_PEM : 0) | (ctrl->is_base64? GNUPG_KSBA_IO_BASE64 : 0) | (ctrl->autodetect_encoding? GNUPG_KSBA_IO_AUTODETECT : 0)), in_fp, &reader); if (rc) { log_error ("can't create reader: %s\n", gpg_strerror (rc)); goto leave; } rc = gnupg_ksba_create_writer (&b64writer, ((ctrl->create_pem? GNUPG_KSBA_IO_PEM : 0) | (ctrl->create_base64? GNUPG_KSBA_IO_BASE64 : 0)), ctrl->pem_name, out_fp, &writer); if (rc) { log_error ("can't create writer: %s\n", gpg_strerror (rc)); goto leave; } rc = ksba_cms_new (&cms); if (rc) goto leave; rc = ksba_cms_set_reader_writer (cms, reader, writer); if (rc) { log_debug ("ksba_cms_set_reader_writer failed: %s\n", gpg_strerror (rc)); goto leave; } audit_log (ctrl->audit, AUDIT_SETUP_READY); /* Parser loop. */ do { rc = ksba_cms_parse (cms, &stopreason); if (rc) { log_debug ("ksba_cms_parse failed: %s\n", gpg_strerror (rc)); goto leave; } if (stopreason == KSBA_SR_BEGIN_DATA || stopreason == KSBA_SR_DETACHED_DATA) { int algo, mode; const char *algoid; int any_key = 0; - int is_de_vs; /* Computed compliance with CO_DE_VS. */ audit_log (ctrl->audit, AUDIT_GOT_DATA); algoid = ksba_cms_get_content_oid (cms, 2/* encryption algo*/); algo = gcry_cipher_map_name (algoid); mode = gcry_cipher_mode_from_oid (algoid); if (!algo || !mode) { rc = gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM); log_error ("unsupported algorithm '%s'\n", algoid? algoid:"?"); if (algoid && !strcmp (algoid, "1.2.840.113549.3.2")) log_info (_("(this is the RC2 algorithm)\n")); else if (!algoid) log_info (_("(this does not seem to be an encrypted" " message)\n")); { char numbuf[50]; sprintf (numbuf, "%d", rc); gpgsm_status2 (ctrl, STATUS_ERROR, "decrypt.algorithm", numbuf, algoid?algoid:"?", NULL); audit_log_s (ctrl->audit, AUDIT_BAD_DATA_CIPHER_ALGO, algoid); } /* If it seems that this is not an encrypted message we return a more sensible error code. */ if (!algoid) rc = gpg_error (GPG_ERR_NO_DATA); goto leave; } /* Check compliance. */ if (! gnupg_cipher_is_allowed (opt.compliance, 0, algo, mode)) { log_error (_("cipher algorithm '%s'" " may not be used in %s mode\n"), gcry_cipher_algo_name (algo), gnupg_compliance_option_string (opt.compliance)); rc = gpg_error (GPG_ERR_CIPHER_ALGO); goto leave; } /* For CMS, CO_DE_VS demands CBC mode. */ - is_de_vs = gnupg_cipher_is_compliant (CO_DE_VS, algo, mode); + dfparm.is_de_vs = gnupg_cipher_is_compliant (CO_DE_VS, algo, mode); audit_log_i (ctrl->audit, AUDIT_DATA_CIPHER_ALGO, algo); dfparm.algo = algo; dfparm.mode = mode; dfparm.blklen = gcry_cipher_get_algo_blklen (algo); if (dfparm.blklen > sizeof (dfparm.helpblock)) return gpg_error (GPG_ERR_BUG); rc = ksba_cms_get_content_enc_iv (cms, dfparm.iv, sizeof (dfparm.iv), &dfparm.ivlen); if (rc) { log_error ("error getting IV: %s\n", gpg_strerror (rc)); goto leave; } for (recp=0; !any_key; recp++) { char *issuer; ksba_sexp_t serial; ksba_sexp_t enc_val; char *hexkeygrip = NULL; + char *pkalgostr = NULL; + char *pkfpr = NULL; char *desc = NULL; char kidbuf[16+1]; + int tmp_rc; + ksba_cert_t cert = NULL; + unsigned int nbits; + int pk_algo = 0; + int maybe_pwri = 0; *kidbuf = 0; - rc = ksba_cms_get_issuer_serial (cms, recp, &issuer, &serial); - if (rc == -1 && recp) + tmp_rc = ksba_cms_get_issuer_serial (cms, recp, &issuer, &serial); + if (tmp_rc == -1 && recp) break; /* no more recipients */ audit_log_i (ctrl->audit, AUDIT_NEW_RECP, recp); - if (rc) - log_error ("recp %d - error getting info: %s\n", - recp, gpg_strerror (rc)); + if (gpg_err_code (tmp_rc) == GPG_ERR_UNSUPPORTED_CMS_OBJ) + { + maybe_pwri = 1; + } + else if (tmp_rc) + { + log_error ("recp %d - error getting info: %s\n", + recp, gpg_strerror (tmp_rc)); + } else { - ksba_cert_t cert = NULL; - - log_debug ("recp %d - issuer: '%s'\n", - recp, issuer? issuer:"[NONE]"); - log_debug ("recp %d - serial: ", recp); - gpgsm_dump_serial (serial); - log_printf ("\n"); + if (opt.verbose) + { + log_debug ("recp %d - issuer: '%s'\n", + recp, issuer? issuer:"[NONE]"); + log_debug ("recp %d - serial: ", recp); + gpgsm_dump_serial (serial); + log_printf ("\n"); + } if (ctrl->audit) { char *tmpstr = gpgsm_format_sn_issuer (serial, issuer); audit_log_s (ctrl->audit, AUDIT_RECP_NAME, tmpstr); xfree (tmpstr); } keydb_search_reset (kh); rc = keydb_search_issuer_sn (ctrl, kh, issuer, serial); if (rc) { log_error ("failed to find the certificate: %s\n", gpg_strerror(rc)); goto oops; } rc = keydb_get_cert (kh, &cert); if (rc) { log_error ("failed to get cert: %s\n", gpg_strerror (rc)); goto oops; } /* Print the ENC_TO status line. Note that we can do so only if we have the certificate. This is in contrast to gpg where the keyID is commonly included in the encrypted messages. It is too cumbersome to retrieve the used algorithm, thus we don't print it for now. We also record the keyid for later use. */ { unsigned long kid[2]; kid[0] = gpgsm_get_short_fingerprint (cert, kid+1); snprintf (kidbuf, sizeof kidbuf, "%08lX%08lX", kid[1], kid[0]); gpgsm_status2 (ctrl, STATUS_ENC_TO, kidbuf, "0", "0", NULL); } /* Put the certificate into the audit log. */ audit_log_cert (ctrl->audit, AUDIT_SAVE_CERT, cert, 0); /* Just in case there is a problem with the own certificate we print this message - should never happen of course */ rc = gpgsm_cert_use_decrypt_p (cert); if (rc) { char numbuf[50]; sprintf (numbuf, "%d", rc); gpgsm_status2 (ctrl, STATUS_ERROR, "decrypt.keyusage", numbuf, NULL); rc = 0; } hexkeygrip = gpgsm_get_keygrip_hexstring (cert); desc = gpgsm_format_keydesc (cert); + pkfpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1); + pkalgostr = gpgsm_pubkey_algo_string (cert, NULL); + pk_algo = gpgsm_get_key_algo_info (cert, &nbits); + if (!opt.quiet) + log_info (_("encrypted to %s key %s\n"), pkalgostr, pkfpr); + + /* Check compliance. */ + if (!gnupg_pk_is_allowed (opt.compliance, + PK_USE_DECRYPTION, + pk_algo, 0, NULL, nbits, NULL)) + { + char kidstr[10+1]; + + snprintf (kidstr, sizeof kidstr, "0x%08lX", + gpgsm_get_short_fingerprint (cert, NULL)); + log_info (_("key %s is not suitable for decryption" + " in %s mode\n"), + kidstr, + gnupg_compliance_option_string(opt.compliance)); + rc = gpg_error (GPG_ERR_PUBKEY_ALGO); + goto oops; + } - { - unsigned int nbits; - int pk_algo = gpgsm_get_key_algo_info (cert, &nbits); - - /* Check compliance. */ - if (!gnupg_pk_is_allowed (opt.compliance, - PK_USE_DECRYPTION, - pk_algo, 0, NULL, nbits, NULL)) - { - char kidstr[10+1]; - - snprintf (kidstr, sizeof kidstr, "0x%08lX", - gpgsm_get_short_fingerprint (cert, NULL)); - log_info - (_("key %s is not suitable for decryption" - " in %s mode\n"), - kidstr, - gnupg_compliance_option_string (opt.compliance)); - rc = gpg_error (GPG_ERR_PUBKEY_ALGO); - goto oops; - } - - /* Check that all certs are compliant with CO_DE_VS. */ - is_de_vs = - (is_de_vs - && gnupg_pk_is_compliant (CO_DE_VS, pk_algo, 0, NULL, - nbits, NULL)); - } + /* Check that all certs are compliant with CO_DE_VS. */ + dfparm.is_de_vs = + (dfparm.is_de_vs + && gnupg_pk_is_compliant (CO_DE_VS, pk_algo, 0, + NULL, nbits, NULL)); oops: if (rc) { /* We cannot check compliance of certs that we * don't have. */ - is_de_vs = 0; + dfparm.is_de_vs = 0; } xfree (issuer); xfree (serial); ksba_cert_release (cert); } - if (!hexkeygrip) + if ((!hexkeygrip || !pk_algo) && !maybe_pwri) ; else if (!(enc_val = ksba_cms_get_enc_val (cms, recp))) - log_error ("recp %d - error getting encrypted session key\n", - recp); + { + log_error ("recp %d - error getting encrypted session key\n", + recp); + if (maybe_pwri) + log_info ("(possibly unsupported KEK info)\n"); + } else { - rc = prepare_decryption (ctrl, - hexkeygrip, desc, enc_val, &dfparm); + if (maybe_pwri && opt.verbose) + log_info ("recp %d - KEKRI or PWRI\n", recp); + + rc = prepare_decryption (ctrl, hexkeygrip, + desc, enc_val, &dfparm); xfree (enc_val); if (rc) { log_info ("decrypting session key failed: %s\n", gpg_strerror (rc)); if (gpg_err_code (rc) == GPG_ERR_NO_SECKEY && *kidbuf) gpgsm_status2 (ctrl, STATUS_NO_SECKEY, kidbuf, NULL); } else { /* setup the bulk decrypter */ any_key = 1; ksba_writer_set_filter (writer, decrypt_filter, &dfparm); - if (is_de_vs && gnupg_gcrypt_is_compliant (CO_DE_VS)) + if (dfparm.is_de_vs + && gnupg_gcrypt_is_compliant (CO_DE_VS)) gpgsm_status (ctrl, STATUS_DECRYPTION_COMPLIANCE_MODE, gnupg_status_compliance_flag (CO_DE_VS)); } audit_log_ok (ctrl->audit, AUDIT_RECP_RESULT, rc); } + xfree (pkalgostr); + xfree (pkfpr); xfree (hexkeygrip); xfree (desc); } /* If we write an audit log add the unused recipients to the log as well. */ if (ctrl->audit && any_key) { for (;; recp++) { char *issuer; ksba_sexp_t serial; int tmp_rc; tmp_rc = ksba_cms_get_issuer_serial (cms, recp, &issuer, &serial); if (tmp_rc == -1) break; /* no more recipients */ audit_log_i (ctrl->audit, AUDIT_NEW_RECP, recp); if (tmp_rc) log_error ("recp %d - error getting info: %s\n", recp, gpg_strerror (rc)); else { char *tmpstr = gpgsm_format_sn_issuer (serial, issuer); audit_log_s (ctrl->audit, AUDIT_RECP_NAME, tmpstr); xfree (tmpstr); xfree (issuer); xfree (serial); } } } if (!any_key) { rc = gpg_error (GPG_ERR_NO_SECKEY); goto leave; } } else if (stopreason == KSBA_SR_END_DATA) { ksba_writer_set_filter (writer, NULL, NULL); if (dfparm.any_data) { /* write the last block with padding removed */ int i, npadding = dfparm.lastblock[dfparm.blklen-1]; if (!npadding || npadding > dfparm.blklen) { log_error ("invalid padding with value %d\n", npadding); rc = gpg_error (GPG_ERR_INV_DATA); goto leave; } rc = ksba_writer_write (writer, dfparm.lastblock, dfparm.blklen - npadding); if (rc) goto leave; for (i=dfparm.blklen - npadding; i < dfparm.blklen; i++) { if (dfparm.lastblock[i] != npadding) { log_error ("inconsistent padding\n"); rc = gpg_error (GPG_ERR_INV_DATA); goto leave; } } } } } while (stopreason != KSBA_SR_READY); rc = gnupg_ksba_finish_writer (b64writer); if (rc) { log_error ("write failed: %s\n", gpg_strerror (rc)); goto leave; } gpgsm_status (ctrl, STATUS_DECRYPTION_OKAY, NULL); leave: audit_log_ok (ctrl->audit, AUDIT_DECRYPTION_RESULT, rc); if (rc) { gpgsm_status (ctrl, STATUS_DECRYPTION_FAILED, NULL); log_error ("message decryption failed: %s <%s>\n", gpg_strerror (rc), gpg_strsource (rc)); } ksba_cms_release (cms); gnupg_ksba_destroy_reader (b64reader); gnupg_ksba_destroy_writer (b64writer); keydb_release (kh); es_fclose (in_fp); if (dfparm.hd) gcry_cipher_close (dfparm.hd); return rc; }