1 /* pksign.c - public key signing (well, actually using a secret key)
2 * Copyright (C) 2001-2004, 2010 Free Software Foundation, Inc.
3 * Copyright (C) 2001-2004, 2010, 2013 Werner Koch
4 *
5 * This file is part of GnuPG.
6 *
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <https://www.gnu.org/licenses/>.
19 */
20
21 #include <config.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <ctype.h>
27 #include <sys/stat.h>
28
29 #include "agent.h"
30 #include "../common/i18n.h"
31
32
33 static int
do_encode_md(const byte * md,size_t mdlen,int algo,gcry_sexp_t * r_hash,int raw_value)34 do_encode_md (const byte * md, size_t mdlen, int algo, gcry_sexp_t * r_hash,
35 int raw_value)
36 {
37 gcry_sexp_t hash;
38 int rc;
39
40 if (!raw_value)
41 {
42 const char *s;
43 char tmp[16+1];
44 int i;
45
46 s = gcry_md_algo_name (algo);
47 if (!s || strlen (s) >= 16)
48 {
49 hash = NULL;
50 rc = gpg_error (GPG_ERR_DIGEST_ALGO);
51 }
52 else
53 {
54 for (i=0; s[i]; i++)
55 tmp[i] = ascii_tolower (s[i]);
56 tmp[i] = '\0';
57
58 rc = gcry_sexp_build (&hash, NULL,
59 "(data (flags pkcs1) (hash %s %b))",
60 tmp, (int)mdlen, md);
61 }
62 }
63 else
64 {
65 rc = gcry_sexp_build (&hash, NULL,
66 "(data (flags raw) (value %b))",
67 (int)mdlen, md);
68 }
69
70 *r_hash = hash;
71 return rc;
72 }
73
74
75 /* Return the number of bits of the Q parameter from the DSA key
76 KEY. */
77 static unsigned int
get_dsa_qbits(gcry_sexp_t key)78 get_dsa_qbits (gcry_sexp_t key)
79 {
80 gcry_sexp_t l1, l2;
81 gcry_mpi_t q;
82 unsigned int nbits;
83
84 l1 = gcry_sexp_find_token (key, "private-key", 0);
85 if (!l1)
86 l1 = gcry_sexp_find_token (key, "protected-private-key", 0);
87 if (!l1)
88 l1 = gcry_sexp_find_token (key, "shadowed-private-key", 0);
89 if (!l1)
90 l1 = gcry_sexp_find_token (key, "public-key", 0);
91 if (!l1)
92 return 0; /* Does not contain a key object. */
93 l2 = gcry_sexp_cadr (l1);
94 gcry_sexp_release (l1);
95 l1 = gcry_sexp_find_token (l2, "q", 1);
96 gcry_sexp_release (l2);
97 if (!l1)
98 return 0; /* Invalid object. */
99 q = gcry_sexp_nth_mpi (l1, 1, GCRYMPI_FMT_USG);
100 gcry_sexp_release (l1);
101 if (!q)
102 return 0; /* Missing value. */
103 nbits = gcry_mpi_get_nbits (q);
104 gcry_mpi_release (q);
105
106 return nbits;
107 }
108
109
110 /* Return an appropriate hash algorithm to be used with RFC-6979 for a
111 message digest of length MDLEN. Although a fallback of SHA-256 is
112 used the current implementation in Libgcrypt will reject a hash
113 algorithm which does not match the length of the message. */
114 static const char *
rfc6979_hash_algo_string(size_t mdlen)115 rfc6979_hash_algo_string (size_t mdlen)
116 {
117 switch (mdlen)
118 {
119 case 20: return "sha1";
120 case 28: return "sha224";
121 case 32: return "sha256";
122 case 48: return "sha384";
123 case 64: return "sha512";
124 default: return "sha256";
125 }
126 }
127
128
129 /* Encode a message digest for use with the EdDSA algorithm
130 (i.e. curve Ed25519). */
131 static gpg_error_t
do_encode_eddsa(size_t nbits,const byte * md,size_t mdlen,gcry_sexp_t * r_hash)132 do_encode_eddsa (size_t nbits, const byte *md, size_t mdlen,
133 gcry_sexp_t *r_hash)
134 {
135 gpg_error_t err;
136 gcry_sexp_t hash;
137 const char *fmt;
138
139 if (nbits == 448)
140 fmt = "(data(value %b))";
141 else
142 fmt = "(data(flags eddsa)(hash-algo sha512)(value %b))";
143
144 *r_hash = NULL;
145 err = gcry_sexp_build (&hash, NULL, fmt, (int)mdlen, md);
146 if (!err)
147 *r_hash = hash;
148 return err;
149 }
150
151
152 /* Encode a message digest for use with an DSA algorithm. */
153 static gpg_error_t
do_encode_dsa(const byte * md,size_t mdlen,int pkalgo,gcry_sexp_t pkey,gcry_sexp_t * r_hash)154 do_encode_dsa (const byte *md, size_t mdlen, int pkalgo, gcry_sexp_t pkey,
155 gcry_sexp_t *r_hash)
156 {
157 gpg_error_t err;
158 gcry_sexp_t hash;
159 unsigned int qbits;
160
161 *r_hash = NULL;
162
163 if (pkalgo == GCRY_PK_ECC)
164 qbits = gcry_pk_get_nbits (pkey);
165 else if (pkalgo == GCRY_PK_DSA)
166 qbits = get_dsa_qbits (pkey);
167 else
168 return gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
169
170 if (pkalgo == GCRY_PK_DSA && (qbits%8))
171 {
172 /* FIXME: We check the QBITS but print a message about the hash
173 length. */
174 log_error (_("DSA requires the hash length to be a"
175 " multiple of 8 bits\n"));
176 return gpg_error (GPG_ERR_INV_LENGTH);
177 }
178
179 /* Don't allow any Q smaller than 160 bits. We don't want someone
180 to issue signatures from a key with a 16-bit Q or something like
181 that, which would look correct but allow trivial forgeries. Yes,
182 I know this rules out using MD5 with DSA. ;) */
183 if (qbits < 160)
184 {
185 log_error (_("%s key uses an unsafe (%u bit) hash\n"),
186 gcry_pk_algo_name (pkalgo), qbits);
187 return gpg_error (GPG_ERR_INV_LENGTH);
188 }
189
190 /* ECDSA 521 is special as it is larger than the largest hash
191 we have (SHA-512). Thus we change the size for further
192 processing to 512. */
193 if (pkalgo == GCRY_PK_ECC && qbits > 512)
194 qbits = 512;
195
196 /* Check if we're too short. Too long is safe as we'll
197 automatically left-truncate. */
198 if (mdlen < qbits/8)
199 {
200 log_error (_("a %zu bit hash is not valid for a %u bit %s key\n"),
201 mdlen*8,
202 gcry_pk_get_nbits (pkey),
203 gcry_pk_algo_name (pkalgo));
204 return gpg_error (GPG_ERR_INV_LENGTH);
205 }
206
207 /* Truncate. */
208 if (mdlen > qbits/8)
209 mdlen = qbits/8;
210
211 /* Create the S-expression. */
212 err = gcry_sexp_build (&hash, NULL,
213 "(data (flags rfc6979) (hash %s %b))",
214 rfc6979_hash_algo_string (mdlen),
215 (int)mdlen, md);
216 if (!err)
217 *r_hash = hash;
218 return err;
219 }
220
221
222 /* Special version of do_encode_md to take care of pkcs#1 padding.
223 For TLS-MD5SHA1 we need to do the padding ourself as Libgrypt does
224 not know about this special scheme. Fixme: We should have a
225 pkcs1-only-padding flag for Libgcrypt. */
226 static int
do_encode_raw_pkcs1(const byte * md,size_t mdlen,unsigned int nbits,gcry_sexp_t * r_hash)227 do_encode_raw_pkcs1 (const byte *md, size_t mdlen, unsigned int nbits,
228 gcry_sexp_t *r_hash)
229 {
230 int rc;
231 gcry_sexp_t hash;
232 unsigned char *frame;
233 size_t i, n, nframe;
234
235 nframe = (nbits+7) / 8;
236 if ( !mdlen || mdlen + 8 + 4 > nframe )
237 {
238 /* Can't encode this hash into a frame of size NFRAME. */
239 return gpg_error (GPG_ERR_TOO_SHORT);
240 }
241
242 frame = xtrymalloc (nframe);
243 if (!frame)
244 return gpg_error_from_syserror ();
245
246 /* Assemble the pkcs#1 block type 1. */
247 n = 0;
248 frame[n++] = 0;
249 frame[n++] = 1; /* Block type. */
250 i = nframe - mdlen - 3 ;
251 log_assert (i >= 8); /* At least 8 bytes of padding. */
252 memset (frame+n, 0xff, i );
253 n += i;
254 frame[n++] = 0;
255 memcpy (frame+n, md, mdlen );
256 n += mdlen;
257 log_assert (n == nframe);
258
259 /* Create the S-expression. */
260 rc = gcry_sexp_build (&hash, NULL,
261 "(data (flags raw) (value %b))",
262 (int)nframe, frame);
263 xfree (frame);
264
265 *r_hash = hash;
266 return rc;
267 }
268
269
270
271 /* SIGN whatever information we have accumulated in CTRL and return
272 * the signature S-expression. LOOKUP is an optional function to
273 * provide a way for lower layers to ask for the caching TTL. If a
274 * CACHE_NONCE is given that cache item is first tried to get a
275 * passphrase. If OVERRIDEDATA is not NULL, OVERRIDEDATALEN bytes
276 * from this buffer are used instead of the data in CTRL. The
277 * override feature is required to allow the use of Ed25519 with ssh
278 * because Ed25519 does the hashing itself. */
279 gpg_error_t
agent_pksign_do(ctrl_t ctrl,const char * cache_nonce,const char * desc_text,gcry_sexp_t * signature_sexp,cache_mode_t cache_mode,lookup_ttl_t lookup_ttl,const void * overridedata,size_t overridedatalen)280 agent_pksign_do (ctrl_t ctrl, const char *cache_nonce,
281 const char *desc_text,
282 gcry_sexp_t *signature_sexp,
283 cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
284 const void *overridedata, size_t overridedatalen)
285 {
286 gpg_error_t err = 0;
287 gcry_sexp_t s_skey = NULL;
288 gcry_sexp_t s_sig = NULL;
289 gcry_sexp_t s_hash = NULL;
290 gcry_sexp_t s_pkey = NULL;
291 unsigned char *shadow_info = NULL;
292 int no_shadow_info = 0;
293 const unsigned char *data;
294 int datalen;
295 int check_signature = 0;
296 int algo;
297
298 if (overridedata)
299 {
300 data = overridedata;
301 datalen = overridedatalen;
302 }
303 else if (ctrl->digest.data)
304 {
305 data = ctrl->digest.data;
306 datalen = ctrl->digest.valuelen;
307 }
308 else
309 {
310 data = ctrl->digest.value;
311 datalen = ctrl->digest.valuelen;
312 }
313
314 if (!ctrl->have_keygrip)
315 return gpg_error (GPG_ERR_NO_SECKEY);
316
317 err = agent_key_from_file (ctrl, cache_nonce, desc_text, ctrl->keygrip,
318 &shadow_info, cache_mode, lookup_ttl,
319 &s_skey, NULL);
320 if (gpg_err_code (err) == GPG_ERR_NO_SECKEY)
321 no_shadow_info = 1;
322 else if (err)
323 {
324 log_error ("failed to read the secret key\n");
325 goto leave;
326 }
327 else
328 algo = get_pk_algo_from_key (s_skey);
329
330 if (shadow_info || no_shadow_info)
331 {
332 /* Divert operation to the smartcard. With NO_SHADOW_INFO set
333 * we don't have the keystub but we want to see whether the key
334 * is on the active card. */
335 size_t len;
336 unsigned char *buf = NULL;
337
338 if (no_shadow_info)
339 {
340 /* Try to get the public key from the card or fail with the
341 * original NO_SECKEY error. We also write a stub file (we
342 * are here only because no stub exists). */
343 char *serialno;
344 unsigned char *pkbuf = NULL;
345 size_t pkbuflen;
346 char hexgrip[2*KEYGRIP_LEN+1];
347 char *keyref;
348
349 if (agent_card_serialno (ctrl, &serialno, NULL))
350 {
351 /* No card available or error reading the card. */
352 err = gpg_error (GPG_ERR_NO_SECKEY);
353 goto leave;
354 }
355 bin2hex (ctrl->keygrip, KEYGRIP_LEN, hexgrip);
356 if (agent_card_readkey (ctrl, hexgrip, &pkbuf, &keyref))
357 {
358 /* No such key on the card. */
359 xfree (serialno);
360 err = gpg_error (GPG_ERR_NO_SECKEY);
361 goto leave;
362 }
363 pkbuflen = gcry_sexp_canon_len (pkbuf, 0, NULL, NULL);
364 err = gcry_sexp_sscan (&s_pkey, NULL, (char*)pkbuf, pkbuflen);
365 if (err)
366 {
367 xfree (serialno);
368 xfree (pkbuf);
369 xfree (keyref);
370 log_error ("%s: corrupted key returned by scdaemon\n", __func__);
371 goto leave;
372 }
373
374 if (keyref)
375 agent_write_shadow_key (ctrl->keygrip, serialno, keyref, pkbuf, 0);
376
377 algo = get_pk_algo_from_key (s_pkey);
378
379 xfree (serialno);
380 xfree (pkbuf);
381 xfree (keyref);
382 }
383 else
384 {
385 /* Get the public key from the stub file. */
386 err = agent_public_key_from_file (ctrl, ctrl->keygrip, &s_pkey);
387 if (err)
388 {
389 log_error ("failed to read the public key\n");
390 goto leave;
391 }
392 }
393
394 {
395 char *desc2 = NULL;
396
397 if (desc_text)
398 agent_modify_description (desc_text, NULL, s_pkey, &desc2);
399
400 if (agent_is_tpm2_key (s_skey))
401 err = divert_tpm2_pksign (ctrl, desc2? desc2 : desc_text,
402 data, datalen,
403 ctrl->digest.algo,
404 shadow_info, &buf, &len);
405 else
406 err = divert_pksign (ctrl, desc2? desc2 : desc_text,
407 ctrl->keygrip,
408 data, datalen,
409 ctrl->digest.algo,
410 shadow_info, &buf, &len);
411 xfree (desc2);
412 }
413 if (err)
414 {
415 log_error ("smartcard signing failed: %s\n", gpg_strerror (err));
416 goto leave;
417 }
418
419 if (algo == GCRY_PK_RSA)
420 {
421 unsigned char *p = buf;
422
423 check_signature = 1;
424
425 /*
426 * Smartcard returns fixed-size data, which is good for
427 * PKCS1. If variable-size unsigned MPI is needed, remove
428 * zeros.
429 */
430 if (ctrl->digest.algo == MD_USER_TLS_MD5SHA1
431 || ctrl->digest.raw_value)
432 {
433 int i;
434
435 for (i = 0; i < len - 1; i++)
436 if (p[i])
437 break;
438 p += i;
439 len -= i;
440 }
441
442 err = gcry_sexp_build (&s_sig, NULL, "(sig-val(rsa(s%b)))",
443 (int)len, p);
444 }
445 else if (algo == GCRY_PK_EDDSA)
446 {
447 err = gcry_sexp_build (&s_sig, NULL, "(sig-val(eddsa(r%b)(s%b)))",
448 (int)len/2, buf, (int)len/2, buf + len/2);
449 }
450 else if (algo == GCRY_PK_ECC)
451 {
452 unsigned char *r_buf, *s_buf;
453 int r_buflen, s_buflen;
454 int i;
455
456 r_buflen = s_buflen = len/2;
457
458 /*
459 * Smartcard returns fixed-size data. For ECDSA signature,
460 * variable-size unsigned MPI is assumed, thus, remove
461 * zeros.
462 */
463 r_buf = buf;
464 for (i = 0; i < r_buflen - 1; i++)
465 if (r_buf[i])
466 break;
467 r_buf += i;
468 r_buflen -= i;
469
470 s_buf = buf + len/2;
471 for (i = 0; i < s_buflen - 1; i++)
472 if (s_buf[i])
473 break;
474 s_buf += i;
475 s_buflen -= i;
476
477 err = gcry_sexp_build (&s_sig, NULL, "(sig-val(ecdsa(r%b)(s%b)))",
478 r_buflen, r_buf,
479 s_buflen, s_buf);
480 }
481 else
482 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
483
484 xfree (buf);
485 if (err)
486 {
487 log_error ("failed to convert sigbuf returned by divert_pksign "
488 "into S-Exp: %s", gpg_strerror (err));
489 goto leave;
490 }
491 }
492 else
493 {
494 /* No smartcard, but a private key (in S_SKEY). */
495
496 /* Put the hash into a sexp */
497 if (algo == GCRY_PK_EDDSA)
498 err = do_encode_eddsa (gcry_pk_get_nbits (s_skey), data, datalen,
499 &s_hash);
500 else if (ctrl->digest.algo == MD_USER_TLS_MD5SHA1)
501 err = do_encode_raw_pkcs1 (data, datalen,
502 gcry_pk_get_nbits (s_skey),
503 &s_hash);
504 else if (algo == GCRY_PK_DSA || algo == GCRY_PK_ECC)
505 err = do_encode_dsa (data, datalen,
506 algo, s_skey,
507 &s_hash);
508 else if (ctrl->digest.is_pss)
509 {
510 log_info ("signing with rsaPSS is currently only supported"
511 " for (some) smartcards\n");
512 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
513 }
514 else
515 err = do_encode_md (data, datalen,
516 ctrl->digest.algo,
517 &s_hash,
518 ctrl->digest.raw_value);
519 if (err)
520 goto leave;
521
522 if (DBG_CRYPTO)
523 {
524 gcry_log_debugsxp ("skey", s_skey);
525 gcry_log_debugsxp ("hash", s_hash);
526 }
527
528 /* sign */
529 err = gcry_pk_sign (&s_sig, s_hash, s_skey);
530 if (err)
531 {
532 log_error ("signing failed: %s\n", gpg_strerror (err));
533 goto leave;
534 }
535
536 if (DBG_CRYPTO)
537 gcry_log_debugsxp ("rslt", s_sig);
538 }
539
540 /* Check that the signature verification worked and nothing is
541 * fooling us e.g. by a bug in the signature create code or by
542 * deliberately introduced faults. Because Libgcrypt 1.7 does this
543 * for RSA internally there is no need to do it here again. We do
544 * this always for card based RSA keys, though. */
545 if (check_signature)
546 {
547 gcry_sexp_t sexp_key = s_pkey? s_pkey: s_skey;
548
549 if (s_hash == NULL)
550 {
551 if (ctrl->digest.is_pss)
552 {
553 err = gcry_sexp_build (&s_hash, NULL,
554 "(data (flags raw) (value %b))",
555 (int)datalen, data);
556 }
557 else if (algo == GCRY_PK_DSA || algo == GCRY_PK_ECC)
558 err = do_encode_dsa (data, datalen, algo, sexp_key, &s_hash);
559 else if (ctrl->digest.algo == MD_USER_TLS_MD5SHA1)
560 err = do_encode_raw_pkcs1 (data, datalen,
561 gcry_pk_get_nbits (sexp_key), &s_hash);
562 else
563 err = do_encode_md (data, datalen, ctrl->digest.algo, &s_hash,
564 ctrl->digest.raw_value);
565 }
566
567 if (!err)
568 err = gcry_pk_verify (s_sig, s_hash, sexp_key);
569
570 if (err)
571 {
572 log_error (_("checking created signature failed: %s\n"),
573 gpg_strerror (err));
574 if (DBG_CRYPTO)
575 {
576 gcry_log_debugsxp ("verify s_hsh", s_hash);
577 gcry_log_debugsxp ("verify s_sig", s_sig);
578 gcry_log_debugsxp ("verify s_key", sexp_key);
579 }
580 gcry_sexp_release (s_sig);
581 s_sig = NULL;
582 }
583 }
584
585 leave:
586
587 *signature_sexp = s_sig;
588
589 gcry_sexp_release (s_pkey);
590 gcry_sexp_release (s_skey);
591 gcry_sexp_release (s_hash);
592 xfree (shadow_info);
593
594 return err;
595 }
596
597
598 /* SIGN whatever information we have accumulated in CTRL and write it
599 * back to OUTFP. If a CACHE_NONCE is given that cache item is first
600 * tried to get a passphrase. */
601 gpg_error_t
agent_pksign(ctrl_t ctrl,const char * cache_nonce,const char * desc_text,membuf_t * outbuf,cache_mode_t cache_mode)602 agent_pksign (ctrl_t ctrl, const char *cache_nonce, const char *desc_text,
603 membuf_t *outbuf, cache_mode_t cache_mode)
604 {
605 gpg_error_t err;
606 gcry_sexp_t s_sig = NULL;
607 char *buf = NULL;
608 size_t len = 0;
609
610 err = agent_pksign_do (ctrl, cache_nonce, desc_text, &s_sig, cache_mode,
611 NULL, NULL, 0);
612 if (err)
613 goto leave;
614
615 len = gcry_sexp_sprint (s_sig, GCRYSEXP_FMT_CANON, NULL, 0);
616 log_assert (len);
617 buf = xtrymalloc (len);
618 if (!buf)
619 {
620 err = gpg_error_from_syserror ();
621 goto leave;
622 }
623 len = gcry_sexp_sprint (s_sig, GCRYSEXP_FMT_CANON, buf, len);
624 log_assert (len);
625 put_membuf (outbuf, buf, len);
626
627 leave:
628 gcry_sexp_release (s_sig);
629 xfree (buf);
630
631 return err;
632 }
633