1 /* keyid.c - key ID and fingerprint handling
2  * Copyright (C) 1998, 1999, 2000, 2001, 2003,
3  *               2004, 2006, 2010 Free Software Foundation, Inc.
4  * Copyright (C) 2014 Werner Koch
5  * Copyright (C) 2016 g10 Code GmbH
6  *
7  * This file is part of GnuPG.
8  *
9  * GnuPG is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * GnuPG is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, see <https://www.gnu.org/licenses/>.
21  */
22 
23 #include <config.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <time.h>
29 
30 #include "gpg.h"
31 #include "../common/util.h"
32 #include "main.h"
33 #include "packet.h"
34 #include "options.h"
35 #include "keydb.h"
36 #include "../common/i18n.h"
37 #include "rmd160.h"
38 #include "../common/host2net.h"
39 
40 
41 #define KEYID_STR_SIZE 19
42 
43 #ifdef HAVE_UNSIGNED_TIME_T
44 # define IS_INVALID_TIME_T(a) ((a) == (time_t)(-1))
45 #else
46   /* Error or 32 bit time_t and value after 2038-01-19.  */
47 # define IS_INVALID_TIME_T(a) ((a) < 0)
48 #endif
49 
50 
51 /* Return a letter describing the public key algorithms.  */
52 int
pubkey_letter(int algo)53 pubkey_letter( int algo )
54 {
55   switch (algo)
56     {
57     case PUBKEY_ALGO_RSA:	return 'R' ;
58     case PUBKEY_ALGO_RSA_E:	return 'r' ;
59     case PUBKEY_ALGO_RSA_S:	return 's' ;
60     case PUBKEY_ALGO_ELGAMAL_E: return 'g' ;
61     case PUBKEY_ALGO_ELGAMAL:   return 'G' ;
62     case PUBKEY_ALGO_DSA:	return 'D' ;
63     case PUBKEY_ALGO_ECDH:	return 'e' ;	/* ECC DH (encrypt only) */
64     case PUBKEY_ALGO_ECDSA:	return 'E' ;	/* ECC DSA (sign only)   */
65     case PUBKEY_ALGO_EDDSA:	return 'E' ;	/* ECC EdDSA (sign only) */
66     default: return '?';
67     }
68 }
69 
70 /* Return a string describing the public key algorithm and the
71    keysize.  For elliptic curves the function prints the name of the
72    curve because the keysize is a property of the curve.  The string
73    is copied to the supplied buffer up a length of BUFSIZE-1.
74    Examples for the output are:
75 
76    "rsa3072"  - RSA with 3072 bit
77    "elg1024"  - Elgamal with 1024 bit
78    "ed25519"  - ECC using the curve Ed25519.
79    "E_1.2.3.4"  - ECC using the unsupported curve with OID "1.2.3.4".
80    "E_1.3.6.1.4.1.11591.2.12242973" ECC with a bogus OID.
81    "unknown_N"  - Unknown OpenPGP algorithm N.
82 
83    If the option --legacy-list-mode is active, the output use the
84    legacy format:
85 
86    "3072R" - RSA with 3072 bit
87    "1024g" - Elgamal with 1024 bit
88    "256E"  - ECDSA using a curve with 256 bit
89 
90    The macro PUBKEY_STRING_SIZE may be used to allocate a buffer with
91    a suitable size.  Note that a more general version of this function
92    exists as get_keyalgo_string.  However, that has no special
93    treatment for the old and unsupported Elgamal which we here print as
94    xxxNNNN.  */
95 char *
pubkey_string(PKT_public_key * pk,char * buffer,size_t bufsize)96 pubkey_string (PKT_public_key *pk, char *buffer, size_t bufsize)
97 {
98   const char *prefix = NULL;
99 
100   if (opt.legacy_list_mode)
101     {
102       snprintf (buffer, bufsize, "%4u%c",
103                 nbits_from_pk (pk), pubkey_letter (pk->pubkey_algo));
104       return buffer;
105     }
106 
107   switch (pk->pubkey_algo)
108     {
109     case PUBKEY_ALGO_RSA:
110     case PUBKEY_ALGO_RSA_E:
111     case PUBKEY_ALGO_RSA_S:	prefix = "rsa"; break;
112     case PUBKEY_ALGO_ELGAMAL_E: prefix = "elg"; break;
113     case PUBKEY_ALGO_DSA:	prefix = "dsa"; break;
114     case PUBKEY_ALGO_ELGAMAL:   prefix = "xxx"; break;
115     case PUBKEY_ALGO_ECDH:
116     case PUBKEY_ALGO_ECDSA:
117     case PUBKEY_ALGO_EDDSA:     prefix = "";    break;
118     }
119 
120   if (prefix && *prefix)
121     snprintf (buffer, bufsize, "%s%u", prefix, nbits_from_pk (pk));
122   else if (prefix)
123     {
124       char *curve = openpgp_oid_to_str (pk->pkey[0]);
125       const char *name = openpgp_oid_to_curve (curve, 0);
126 
127       if (name)
128         snprintf (buffer, bufsize, "%s", name);
129       else if (curve)
130         snprintf (buffer, bufsize, "E_%s", curve);
131       else
132         snprintf (buffer, bufsize, "E_error");
133       xfree (curve);
134     }
135   else
136     snprintf (buffer, bufsize, "unknown_%u", (unsigned int)pk->pubkey_algo);
137 
138   return buffer;
139 }
140 
141 
142 /* Hash a public key.  This function is useful for v4 and v5
143  * fingerprints and for v3 or v4 key signing. */
144 void
hash_public_key(gcry_md_hd_t md,PKT_public_key * pk)145 hash_public_key (gcry_md_hd_t md, PKT_public_key *pk)
146 {
147   unsigned int n;
148   unsigned int nn[PUBKEY_MAX_NPKEY];
149   byte *pp[PUBKEY_MAX_NPKEY];
150   int i;
151   unsigned int nbits;
152   size_t nbytes;
153   int npkey = pubkey_get_npkey (pk->pubkey_algo);
154   int is_v5 = pk->version == 5;
155 
156   n = is_v5? 10 : 6;
157   /* FIXME: We can avoid the extra malloc by calling only the first
158      mpi_print here which computes the required length and calling the
159      real mpi_print only at the end.  The speed advantage would only be
160      for ECC (opaque MPIs) or if we could implement an mpi_print
161      variant with a callback handler to do the hashing.  */
162   if (npkey==0 && pk->pkey[0]
163       && gcry_mpi_get_flag (pk->pkey[0], GCRYMPI_FLAG_OPAQUE))
164     {
165       pp[0] = gcry_mpi_get_opaque (pk->pkey[0], &nbits);
166       nn[0] = (nbits+7)/8;
167       n+=nn[0];
168     }
169   else
170     {
171       for (i=0; i < npkey; i++ )
172         {
173           if (!pk->pkey[i])
174             {
175               /* This case may only happen if the parsing of the MPI
176                  failed but the key was anyway created.  May happen
177                  during "gpg KEYFILE".  */
178               pp[i] = NULL;
179               nn[i] = 0;
180             }
181           else if (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_OPAQUE))
182             {
183               const char *p;
184               int is_sos = 0;
185 
186               if (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_USER2))
187                 is_sos = 2;
188 
189               p = gcry_mpi_get_opaque (pk->pkey[i], &nbits);
190               pp[i] = xmalloc ((nbits+7)/8 + is_sos);
191               if (p)
192                 memcpy (pp[i] + is_sos, p, (nbits+7)/8);
193               else
194                 pp[i] = NULL;
195               if (is_sos)
196                 {
197                   if (*p)
198                     {
199                       nbits = ((nbits + 7) / 8) * 8;
200 
201                       if (nbits >= 8 && !(*p & 0x80))
202                         if (--nbits >= 7 && !(*p & 0x40))
203                           if (--nbits >= 6 && !(*p & 0x20))
204                             if (--nbits >= 5 && !(*p & 0x10))
205                               if (--nbits >= 4 && !(*p & 0x08))
206                                 if (--nbits >= 3 && !(*p & 0x04))
207                                   if (--nbits >= 2 && !(*p & 0x02))
208                                     if (--nbits >= 1 && !(*p & 0x01))
209                                       --nbits;
210                     }
211 
212                   pp[i][0] = (nbits >> 8);
213                   pp[i][1] = nbits;
214                 }
215               nn[i] = (nbits+7)/8 + is_sos;
216               n += nn[i];
217             }
218           else
219             {
220               if (gcry_mpi_print (GCRYMPI_FMT_PGP, NULL, 0,
221                                   &nbytes, pk->pkey[i]))
222                 BUG ();
223               pp[i] = xmalloc (nbytes);
224               if (gcry_mpi_print (GCRYMPI_FMT_PGP, pp[i], nbytes,
225                                   &nbytes, pk->pkey[i]))
226                 BUG ();
227               nn[i] = nbytes;
228               n += nn[i];
229             }
230         }
231     }
232 
233   if (is_v5)
234     {
235       gcry_md_putc ( md, 0x9a );     /* ctb */
236       gcry_md_putc ( md, n >> 24 );  /* 4 byte length header */
237       gcry_md_putc ( md, n >> 16 );
238       gcry_md_putc ( md, n >>  8 );
239       gcry_md_putc ( md, n       );
240       gcry_md_putc ( md, pk->version );
241     }
242   else
243     {
244       gcry_md_putc ( md, 0x99 );     /* ctb */
245       gcry_md_putc ( md, n >> 8 );   /* 2 byte length header */
246       gcry_md_putc ( md, n );
247       gcry_md_putc ( md, pk->version );
248     }
249   gcry_md_putc ( md, pk->timestamp >> 24 );
250   gcry_md_putc ( md, pk->timestamp >> 16 );
251   gcry_md_putc ( md, pk->timestamp >>  8 );
252   gcry_md_putc ( md, pk->timestamp       );
253 
254   gcry_md_putc ( md, pk->pubkey_algo );
255 
256   if (is_v5)
257     {
258       n -= 10;
259       gcry_md_putc ( md, n >> 24 );
260       gcry_md_putc ( md, n >> 16 );
261       gcry_md_putc ( md, n >>  8 );
262       gcry_md_putc ( md, n       );
263     }
264 
265   if(npkey==0 && pk->pkey[0]
266      && gcry_mpi_get_flag (pk->pkey[0], GCRYMPI_FLAG_OPAQUE))
267     {
268       if (pp[0])
269         gcry_md_write (md, pp[0], nn[0]);
270     }
271   else
272     {
273       for(i=0; i < npkey; i++ )
274         {
275           if (pp[i])
276             gcry_md_write ( md, pp[i], nn[i] );
277           xfree(pp[i]);
278         }
279     }
280 }
281 
282 
283 /* fixme: Check whether we can replace this function or if not
284    describe why we need it.  */
285 u32
v3_keyid(gcry_mpi_t a,u32 * ki)286 v3_keyid (gcry_mpi_t a, u32 *ki)
287 {
288   byte *buffer, *p;
289   size_t nbytes;
290 
291   if (gcry_mpi_print (GCRYMPI_FMT_USG, NULL, 0, &nbytes, a ))
292     BUG ();
293   /* fixme: allocate it on the stack */
294   buffer = xmalloc (nbytes);
295   if (gcry_mpi_print( GCRYMPI_FMT_USG, buffer, nbytes, NULL, a ))
296     BUG ();
297   if (nbytes < 8) /* oops */
298     ki[0] = ki[1] = 0;
299   else
300     {
301       p = buffer + nbytes - 8;
302       ki[0] = buf32_to_u32 (p);
303       p += 4;
304       ki[1] = buf32_to_u32 (p);
305     }
306   xfree (buffer);
307   return ki[1];
308 }
309 
310 
311 /* Return PK's keyid.  The memory is owned by PK.  */
312 u32 *
pk_keyid(PKT_public_key * pk)313 pk_keyid (PKT_public_key *pk)
314 {
315   keyid_from_pk (pk, NULL);
316 
317   /* Uncomment this for help tracking down bugs related to keyid or
318      main_keyid not being set correctly.  */
319 #if 0
320   if (! (pk->main_keyid[0] || pk->main_keyid[1]))
321     log_bug ("pk->main_keyid not set!\n");
322   if (keyid_cmp (pk->keyid, pk->main_keyid) == 0
323       && ! pk->flags.primary)
324     log_bug ("keyid and main_keyid are the same, but primary flag not set!\n");
325   if (keyid_cmp (pk->keyid, pk->main_keyid) != 0
326       && pk->flags.primary)
327     log_bug ("keyid and main_keyid are different, but primary flag set!\n");
328 #endif
329 
330   return pk->keyid;
331 }
332 
333 /* Return the keyid of the primary key associated with PK.  The memory
334    is owned by PK.  */
335 u32 *
pk_main_keyid(PKT_public_key * pk)336 pk_main_keyid (PKT_public_key *pk)
337 {
338   /* Uncomment this for help tracking down bugs related to keyid or
339      main_keyid not being set correctly.  */
340 #if 0
341   if (! (pk->main_keyid[0] || pk->main_keyid[1]))
342     log_bug ("pk->main_keyid not set!\n");
343 #endif
344 
345   return pk->main_keyid;
346 }
347 
348 /* Copy the keyid in SRC to DEST and return DEST.  */
349 u32 *
keyid_copy(u32 * dest,const u32 * src)350 keyid_copy (u32 *dest, const u32 *src)
351 {
352   dest[0] = src[0];
353   dest[1] = src[1];
354   return dest;
355 }
356 
357 char *
format_keyid(u32 * keyid,int format,char * buffer,int len)358 format_keyid (u32 *keyid, int format, char *buffer, int len)
359 {
360   char tmp[KEYID_STR_SIZE];
361   if (! buffer)
362     {
363       buffer = tmp;
364       len = sizeof (tmp);
365     }
366 
367   if (format == KF_DEFAULT)
368     format = opt.keyid_format;
369   if (format == KF_DEFAULT)
370     format = KF_NONE;
371 
372   switch (format)
373     {
374     case KF_NONE:
375       if (len)
376         *buffer = 0;
377       break;
378 
379     case KF_SHORT:
380       snprintf (buffer, len, "%08lX", (ulong)keyid[1]);
381       break;
382 
383     case KF_LONG:
384       snprintf (buffer, len, "%08lX%08lX", (ulong)keyid[0], (ulong)keyid[1]);
385       break;
386 
387     case KF_0xSHORT:
388       snprintf (buffer, len, "0x%08lX", (ulong)keyid[1]);
389       break;
390 
391     case KF_0xLONG:
392       snprintf (buffer, len, "0x%08lX%08lX", (ulong)keyid[0],(ulong)keyid[1]);
393       break;
394 
395     default:
396       BUG();
397     }
398 
399   if (buffer == tmp)
400     return xstrdup (buffer);
401   return buffer;
402 }
403 
404 size_t
keystrlen(void)405 keystrlen(void)
406 {
407   int format = opt.keyid_format;
408   if (format == KF_DEFAULT)
409     format = KF_NONE;
410 
411   switch(format)
412     {
413     case KF_NONE:
414       return 0;
415 
416     case KF_SHORT:
417       return 8;
418 
419     case KF_LONG:
420       return 16;
421 
422     case KF_0xSHORT:
423       return 10;
424 
425     case KF_0xLONG:
426       return 18;
427 
428     default:
429       BUG();
430     }
431 }
432 
433 
434 const char *
keystr(u32 * keyid)435 keystr (u32 *keyid)
436 {
437   static char keyid_str[KEYID_STR_SIZE];
438   int format = opt.keyid_format;
439 
440   if (format == KF_DEFAULT)
441     format = KF_NONE;
442   if (format == KF_NONE)
443     format = KF_LONG;
444 
445   return format_keyid (keyid, format, keyid_str, sizeof (keyid_str));
446 }
447 
448 /* This function returns the key id of the main and possible the
449  * subkey as one string.  It is used by error messages.  */
450 const char *
keystr_with_sub(u32 * main_kid,u32 * sub_kid)451 keystr_with_sub (u32 *main_kid, u32 *sub_kid)
452 {
453   static char buffer[KEYID_STR_SIZE+1+KEYID_STR_SIZE];
454   char *p;
455   int format = opt.keyid_format;
456 
457   if (format == KF_NONE)
458     format = KF_LONG;
459 
460   format_keyid (main_kid, format, buffer, KEYID_STR_SIZE);
461   if (sub_kid)
462     {
463       p = buffer + strlen (buffer);
464       *p++ = '/';
465       format_keyid (sub_kid, format, p, KEYID_STR_SIZE);
466     }
467   return buffer;
468 }
469 
470 
471 const char *
keystr_from_pk(PKT_public_key * pk)472 keystr_from_pk(PKT_public_key *pk)
473 {
474   keyid_from_pk(pk,NULL);
475 
476   return keystr(pk->keyid);
477 }
478 
479 
480 const char *
keystr_from_pk_with_sub(PKT_public_key * main_pk,PKT_public_key * sub_pk)481 keystr_from_pk_with_sub (PKT_public_key *main_pk, PKT_public_key *sub_pk)
482 {
483   keyid_from_pk (main_pk, NULL);
484   if (sub_pk)
485     keyid_from_pk (sub_pk, NULL);
486 
487   return keystr_with_sub (main_pk->keyid, sub_pk? sub_pk->keyid:NULL);
488 }
489 
490 
491 /* Return PK's key id as a string using the default format.  PK owns
492    the storage.  */
493 const char *
pk_keyid_str(PKT_public_key * pk)494 pk_keyid_str (PKT_public_key *pk)
495 {
496   return keystr (pk_keyid (pk));
497 }
498 
499 
500 const char *
keystr_from_desc(KEYDB_SEARCH_DESC * desc)501 keystr_from_desc(KEYDB_SEARCH_DESC *desc)
502 {
503   switch(desc->mode)
504     {
505     case KEYDB_SEARCH_MODE_LONG_KID:
506     case KEYDB_SEARCH_MODE_SHORT_KID:
507       return keystr(desc->u.kid);
508 
509     case KEYDB_SEARCH_MODE_FPR:
510       {
511 	u32 keyid[2];
512 
513         if (desc->fprlen == 32)
514           {
515             keyid[0] = buf32_to_u32 (desc->u.fpr);
516             keyid[1] = buf32_to_u32 (desc->u.fpr+4);
517           }
518         else if (desc->fprlen == 20)
519           {
520             keyid[0] = buf32_to_u32 (desc->u.fpr+12);
521             keyid[1] = buf32_to_u32 (desc->u.fpr+16);
522           }
523         else if (desc->fprlen == 16)
524           return "?v3 fpr?";
525         else /* oops */
526           return "?vx fpr?";
527 	return keystr(keyid);
528       }
529 
530     default:
531       BUG();
532     }
533 }
534 
535 
536 /* Compute the fingerprint and keyid and store it in PK.  */
537 static void
compute_fingerprint(PKT_public_key * pk)538 compute_fingerprint (PKT_public_key *pk)
539 {
540   const byte *dp;
541   gcry_md_hd_t md;
542   size_t len;
543 
544   if (gcry_md_open (&md, pk->version == 5 ? GCRY_MD_SHA256 : GCRY_MD_SHA1, 0))
545     BUG ();
546   hash_public_key (md, pk);
547   gcry_md_final (md);
548   dp = gcry_md_read (md, 0);
549   len = gcry_md_get_algo_dlen (gcry_md_get_algo (md));
550   log_assert (len <= MAX_FINGERPRINT_LEN);
551   memcpy (pk->fpr, dp, len);
552   pk->fprlen = len;
553   if (pk->version == 5)
554     {
555       pk->keyid[0] = buf32_to_u32 (dp);
556       pk->keyid[1] = buf32_to_u32 (dp+4);
557     }
558   else
559     {
560       pk->keyid[0] = buf32_to_u32 (dp+12);
561       pk->keyid[1] = buf32_to_u32 (dp+16);
562     }
563   gcry_md_close( md);
564 }
565 
566 
567 /*
568  * Get the keyid from the public key PK and store it at KEYID unless
569  * this is NULL.  Returns the 32 bit short keyid.
570  */
571 u32
keyid_from_pk(PKT_public_key * pk,u32 * keyid)572 keyid_from_pk (PKT_public_key *pk, u32 *keyid)
573 {
574   u32 dummy_keyid[2];
575 
576   if (!keyid)
577     keyid = dummy_keyid;
578 
579   if (!pk->fprlen)
580     compute_fingerprint (pk);
581 
582   keyid[0] = pk->keyid[0];
583   keyid[1] = pk->keyid[1];
584 
585   if (pk->fprlen == 32)
586     return keyid[0];
587   else
588     return keyid[1];
589 }
590 
591 
592 /*
593  * Get the keyid from the fingerprint.  This function is simple for
594  * most keys, but has to do a key lookup for old v3 keys where the
595  * keyid is not part of the fingerprint.
596  */
597 u32
keyid_from_fingerprint(ctrl_t ctrl,const byte * fprint,size_t fprint_len,u32 * keyid)598 keyid_from_fingerprint (ctrl_t ctrl, const byte *fprint,
599                         size_t fprint_len, u32 *keyid)
600 {
601   u32 dummy_keyid[2];
602 
603   if( !keyid )
604     keyid = dummy_keyid;
605 
606   if (fprint_len != 20 && fprint_len != 32)
607     {
608       /* This is special as we have to lookup the key first.  */
609       PKT_public_key pk;
610       int rc;
611 
612       memset (&pk, 0, sizeof pk);
613       rc = get_pubkey_byfprint (ctrl, &pk, NULL, fprint, fprint_len);
614       if( rc )
615         {
616           log_printhex (fprint, fprint_len,
617                         "Oops: keyid_from_fingerprint: no pubkey; fpr:");
618           keyid[0] = 0;
619           keyid[1] = 0;
620         }
621       else
622         keyid_from_pk (&pk, keyid);
623     }
624   else
625     {
626       const byte *dp = fprint;
627       if (fprint_len == 20)  /* v4 key */
628         {
629           keyid[0] = buf32_to_u32 (dp+12);
630           keyid[1] = buf32_to_u32 (dp+16);
631         }
632       else  /* v5 key */
633         {
634           keyid[0] = buf32_to_u32 (dp);
635           keyid[1] = buf32_to_u32 (dp+4);
636         }
637     }
638 
639   return keyid[1];
640 }
641 
642 
643 u32
keyid_from_sig(PKT_signature * sig,u32 * keyid)644 keyid_from_sig (PKT_signature *sig, u32 *keyid)
645 {
646   if( keyid )
647     {
648       keyid[0] = sig->keyid[0];
649       keyid[1] = sig->keyid[1];
650     }
651   return sig->keyid[1];  /*FIXME:shortkeyid*/
652 }
653 
654 
655 byte *
namehash_from_uid(PKT_user_id * uid)656 namehash_from_uid (PKT_user_id *uid)
657 {
658   if (!uid->namehash)
659     {
660       uid->namehash = xmalloc (20);
661 
662       if (uid->attrib_data)
663 	rmd160_hash_buffer (uid->namehash, uid->attrib_data, uid->attrib_len);
664       else
665 	rmd160_hash_buffer (uid->namehash, uid->name, uid->len);
666     }
667 
668   return uid->namehash;
669 }
670 
671 
672 /*
673  * Return the number of bits used in PK.
674  */
675 unsigned int
nbits_from_pk(PKT_public_key * pk)676 nbits_from_pk (PKT_public_key *pk)
677 {
678     return pubkey_nbits (pk->pubkey_algo, pk->pkey);
679 }
680 
681 
682 /* Convert an UTC TIMESTAMP into an UTC yyyy-mm-dd string.  Return
683  * that string.  The caller should pass a buffer with at least a size
684  * of MK_DATESTR_SIZE.  */
685 char *
mk_datestr(char * buffer,size_t bufsize,u32 timestamp)686 mk_datestr (char *buffer, size_t bufsize, u32 timestamp)
687 {
688   time_t atime = timestamp;
689   struct tm *tp;
690 
691   if (IS_INVALID_TIME_T (atime))
692     strcpy (buffer, "????" "-??" "-??"); /* Mark this as invalid. */
693   else
694     {
695       tp = gmtime (&atime);
696       snprintf (buffer, bufsize, "%04d-%02d-%02d",
697                 1900+tp->tm_year, tp->tm_mon+1, tp->tm_mday );
698     }
699   return buffer;
700 }
701 
702 
703 /*
704  * return a string with the creation date of the pk
705  * Note: this is alloced in a static buffer.
706  *    Format is: yyyy-mm-dd
707  */
708 const char *
dateonlystr_from_pk(PKT_public_key * pk)709 dateonlystr_from_pk (PKT_public_key *pk)
710 {
711   static char buffer[MK_DATESTR_SIZE];
712 
713   return mk_datestr (buffer, sizeof buffer, pk->timestamp);
714 }
715 
716 
717 /* Same as dateonlystr_from_pk but with a global option a full iso
718  * timestamp is returned.  In this case it shares a static buffer with
719  * isotimestamp(). */
720 const char *
datestr_from_pk(PKT_public_key * pk)721 datestr_from_pk (PKT_public_key *pk)
722 {
723   if (opt.flags.full_timestrings)
724     return isotimestamp (pk->timestamp);
725   else
726     return dateonlystr_from_pk (pk);
727 }
728 
729 
730 const char *
dateonlystr_from_sig(PKT_signature * sig)731 dateonlystr_from_sig (PKT_signature *sig )
732 {
733   static char buffer[MK_DATESTR_SIZE];
734 
735   return mk_datestr (buffer, sizeof buffer, sig->timestamp);
736 }
737 
738 const char *
datestr_from_sig(PKT_signature * sig)739 datestr_from_sig (PKT_signature *sig )
740 {
741   if (opt.flags.full_timestrings)
742     return isotimestamp (sig->timestamp);
743   else
744     return dateonlystr_from_sig (sig);
745 }
746 
747 
748 const char *
expirestr_from_pk(PKT_public_key * pk)749 expirestr_from_pk (PKT_public_key *pk)
750 {
751   static char buffer[MK_DATESTR_SIZE];
752 
753   if (!pk->expiredate)
754     return _("never     ");
755 
756   if (opt.flags.full_timestrings)
757     return isotimestamp (pk->expiredate);
758 
759   return mk_datestr (buffer, sizeof buffer, pk->expiredate);
760 }
761 
762 
763 const char *
expirestr_from_sig(PKT_signature * sig)764 expirestr_from_sig (PKT_signature *sig)
765 {
766   static char buffer[MK_DATESTR_SIZE];
767 
768   if (!sig->expiredate)
769     return _("never     ");
770 
771   if (opt.flags.full_timestrings)
772     return isotimestamp (sig->expiredate);
773 
774   return mk_datestr (buffer, sizeof buffer, sig->expiredate);
775 }
776 
777 
778 const char *
revokestr_from_pk(PKT_public_key * pk)779 revokestr_from_pk( PKT_public_key *pk )
780 {
781   static char buffer[MK_DATESTR_SIZE];
782 
783   if(!pk->revoked.date)
784     return _("never     ");
785 
786   if (opt.flags.full_timestrings)
787     return isotimestamp (pk->revoked.date);
788 
789   return mk_datestr (buffer, sizeof buffer, pk->revoked.date);
790 }
791 
792 
793 const char *
usagestr_from_pk(PKT_public_key * pk,int fill)794 usagestr_from_pk (PKT_public_key *pk, int fill)
795 {
796   static char buffer[10];
797   int i = 0;
798   unsigned int use = pk->pubkey_usage;
799 
800   if ( use & PUBKEY_USAGE_SIG )
801     buffer[i++] = 'S';
802 
803   if ( use & PUBKEY_USAGE_CERT )
804     buffer[i++] = 'C';
805 
806   if ( use & PUBKEY_USAGE_ENC )
807     buffer[i++] = 'E';
808 
809   if ( (use & PUBKEY_USAGE_AUTH) )
810     buffer[i++] = 'A';
811 
812   while (fill && i < 4)
813     buffer[i++] = ' ';
814 
815   buffer[i] = 0;
816   return buffer;
817 }
818 
819 
820 const char *
colon_strtime(u32 t)821 colon_strtime (u32 t)
822 {
823   static char buf[20];
824 
825   if (!t)
826     return "";
827   snprintf (buf, sizeof buf, "%lu", (ulong)t);
828   return buf;
829 }
830 
831 const char *
colon_datestr_from_pk(PKT_public_key * pk)832 colon_datestr_from_pk (PKT_public_key *pk)
833 {
834   static char buf[20];
835 
836   snprintf (buf, sizeof buf, "%lu", (ulong)pk->timestamp);
837   return buf;
838 }
839 
840 
841 const char *
colon_datestr_from_sig(PKT_signature * sig)842 colon_datestr_from_sig (PKT_signature *sig)
843 {
844   static char buf[20];
845 
846   snprintf (buf, sizeof buf, "%lu", (ulong)sig->timestamp);
847   return buf;
848 }
849 
850 const char *
colon_expirestr_from_sig(PKT_signature * sig)851 colon_expirestr_from_sig (PKT_signature *sig)
852 {
853   static char buf[20];
854 
855   if (!sig->expiredate)
856     return "";
857 
858   snprintf (buf, sizeof buf,"%lu", (ulong)sig->expiredate);
859   return buf;
860 }
861 
862 
863 
864 /*
865  * Return a byte array with the fingerprint for the given PK/SK
866  * The length of the array is returned in ret_len. Caller must free
867  * the array or provide an array of length MAX_FINGERPRINT_LEN.
868  */
869 byte *
fingerprint_from_pk(PKT_public_key * pk,byte * array,size_t * ret_len)870 fingerprint_from_pk (PKT_public_key *pk, byte *array, size_t *ret_len)
871 {
872   if (!pk->fprlen)
873     compute_fingerprint (pk);
874 
875   if (!array)
876     array = xmalloc (pk->fprlen);
877   memcpy (array, pk->fpr, pk->fprlen);
878 
879   if (ret_len)
880     *ret_len = pk->fprlen;
881   return array;
882 }
883 
884 
885 /*
886  * Get FPR20 for the given PK/SK into ARRAY.
887  *
888  * FPR20 is special form of fingerprint of length 20 for the record of
889  * trustdb.  For v4key, having fingerprint with SHA-1, FPR20 is the
890  * same one.  For v5key, FPR20 is constructed from its fingerprint
891  * with SHA-2, so that its kid of last 8-byte can be as same as
892  * kid of v5key fingerprint.
893  *
894  */
895 void
fpr20_from_pk(PKT_public_key * pk,byte array[20])896 fpr20_from_pk (PKT_public_key *pk, byte array[20])
897 {
898   if (!pk->fprlen)
899     compute_fingerprint (pk);
900 
901   if (!array)
902     array = xmalloc (pk->fprlen);
903 
904   if (pk->fprlen == 32)         /* v5 fingerprint */
905     {
906       memcpy (array +  0, pk->fpr + 20, 4);
907       memcpy (array +  4, pk->fpr + 24, 4);
908       memcpy (array +  8, pk->fpr + 28, 4);
909       memcpy (array + 12, pk->fpr +  0, 4); /* kid[0] */
910       memcpy (array + 16, pk->fpr +  4, 4); /* kid[1] */
911     }
912   else                          /* v4 fingerprint */
913     memcpy (array, pk->fpr, 20);
914 }
915 
916 
917 /* Return an allocated buffer with the fingerprint of PK formatted as
918  * a plain hexstring.  If BUFFER is NULL the result is a malloc'd
919  * string.  If BUFFER is not NULL the result will be copied into this
920  * buffer.  In the latter case BUFLEN describes the length of the
921  * buffer; if this is too short the function terminates the process.
922  * Returns a malloc'ed string or BUFFER.  A suitable length for BUFFER
923  * is (2*MAX_FINGERPRINT_LEN + 1). */
924 char *
hexfingerprint(PKT_public_key * pk,char * buffer,size_t buflen)925 hexfingerprint (PKT_public_key *pk, char *buffer, size_t buflen)
926 {
927   if (!pk->fprlen)
928     compute_fingerprint (pk);
929 
930   if (!buffer)
931     {
932       buffer = xtrymalloc (2 * pk->fprlen + 1);
933       if (!buffer)
934         return NULL;
935     }
936   else if (buflen < 2 * pk->fprlen + 1)
937     log_fatal ("%s: buffer too short (%zu)\n", __func__, buflen);
938 
939   bin2hex (pk->fpr, pk->fprlen, buffer);
940   return buffer;
941 }
942 
943 
944 /* Pretty print a hex fingerprint.  If BUFFER is NULL the result is a
945    malloc'd string.  If BUFFER is not NULL the result will be copied
946    into this buffer.  In the latter case BUFLEN describes the length
947    of the buffer; if this is too short the function terminates the
948    process.  Returns a malloc'ed string or BUFFER.  A suitable length
949    for BUFFER is (MAX_FORMATTED_FINGERPRINT_LEN + 1).  */
950 char *
format_hexfingerprint(const char * fingerprint,char * buffer,size_t buflen)951 format_hexfingerprint (const char *fingerprint, char *buffer, size_t buflen)
952 {
953   int hexlen = strlen (fingerprint);
954   int space;
955   int i, j;
956 
957   if (hexlen == 40)  /* v4 fingerprint */
958     {
959       space = (/* The characters and the NUL.  */
960 	       40 + 1
961 	       /* After every fourth character, we add a space (except
962 		  the last).  */
963 	       + 40 / 4 - 1
964 	       /* Half way through we add a second space.  */
965 	       + 1);
966     }
967   else if (hexlen == 64 || hexlen == 50)  /* v5 fingerprint */
968     {
969       /* The v5 fingerprint is commonly printed truncated to 25
970        * octets.  We accept the truncated as well as the full hex
971        * version here and format it like this:
972        * 19347 BC987 24640 25F99 DF3EC 2E000 0ED98 84892 E1F7B 3EA4C
973        */
974       hexlen = 50;
975       space = 10 * 5 + 9 + 1;
976     }
977   else  /* Other fingerprint versions - print as is.  */
978     {
979       /* We truncated here so that we do not need to provide a buffer
980        * of a length which is in reality never used.  */
981       if (hexlen > MAX_FORMATTED_FINGERPRINT_LEN - 1)
982         hexlen = MAX_FORMATTED_FINGERPRINT_LEN - 1;
983       space = hexlen + 1;
984     }
985 
986   if (!buffer)
987     buffer = xmalloc (space);
988   else if (buflen < space)
989     log_fatal ("%s: buffer too short (%zu)\n", __func__, buflen);
990 
991   if (hexlen == 40)  /* v4 fingerprint */
992     {
993       for (i = 0, j = 0; i < 40; i ++)
994         {
995           if (i && !(i % 4))
996             buffer[j ++] = ' ';
997           if (i == 40 / 2)
998             buffer[j ++] = ' ';
999 
1000           buffer[j ++] = fingerprint[i];
1001         }
1002       buffer[j ++] = 0;
1003       log_assert (j == space);
1004     }
1005   else if (hexlen == 50)  /* v5 fingerprint */
1006     {
1007       for (i=j=0; i < 50; i++)
1008         {
1009           if (i && !(i % 5))
1010             buffer[j++] = ' ';
1011           buffer[j++] = fingerprint[i];
1012         }
1013       buffer[j++] = 0;
1014       log_assert (j == space);
1015     }
1016   else
1017     {
1018       mem2str (buffer, fingerprint, space);
1019     }
1020 
1021   return buffer;
1022 }
1023 
1024 
1025 
1026 /* Return the so called KEYGRIP which is the SHA-1 hash of the public
1027    key parameters expressed as an canonical encoded S-Exp.  ARRAY must
1028    be 20 bytes long.  Returns 0 on success or an error code.  */
1029 gpg_error_t
keygrip_from_pk(PKT_public_key * pk,unsigned char * array)1030 keygrip_from_pk (PKT_public_key *pk, unsigned char *array)
1031 {
1032   gpg_error_t err;
1033   gcry_sexp_t s_pkey;
1034 
1035   if (DBG_PACKET)
1036     log_debug ("get_keygrip for public key\n");
1037 
1038   switch (pk->pubkey_algo)
1039     {
1040     case GCRY_PK_DSA:
1041       err = gcry_sexp_build (&s_pkey, NULL,
1042                              "(public-key(dsa(p%m)(q%m)(g%m)(y%m)))",
1043                              pk->pkey[0], pk->pkey[1],
1044                              pk->pkey[2], pk->pkey[3]);
1045       break;
1046 
1047     case GCRY_PK_ELG:
1048     case GCRY_PK_ELG_E:
1049       err = gcry_sexp_build (&s_pkey, NULL,
1050                              "(public-key(elg(p%m)(g%m)(y%m)))",
1051                              pk->pkey[0], pk->pkey[1], pk->pkey[2]);
1052       break;
1053 
1054     case GCRY_PK_RSA:
1055     case GCRY_PK_RSA_S:
1056     case GCRY_PK_RSA_E:
1057       err = gcry_sexp_build (&s_pkey, NULL,
1058                              "(public-key(rsa(n%m)(e%m)))",
1059                              pk->pkey[0], pk->pkey[1]);
1060       break;
1061 
1062     case PUBKEY_ALGO_EDDSA:
1063     case PUBKEY_ALGO_ECDSA:
1064     case PUBKEY_ALGO_ECDH:
1065       {
1066         char *curve = openpgp_oid_to_str (pk->pkey[0]);
1067         if (!curve)
1068           err = gpg_error_from_syserror ();
1069         else
1070           {
1071             err = gcry_sexp_build (&s_pkey, NULL,
1072                                    pk->pubkey_algo == PUBKEY_ALGO_EDDSA?
1073                                    "(public-key(ecc(curve%s)(flags eddsa)(q%m)))":
1074                                    (pk->pubkey_algo == PUBKEY_ALGO_ECDH
1075                                     && openpgp_oid_is_cv25519 (pk->pkey[0]))?
1076                                    "(public-key(ecc(curve%s)(flags djb-tweak)(q%m)))":
1077                                    "(public-key(ecc(curve%s)(q%m)))",
1078                                    curve, pk->pkey[1]);
1079             xfree (curve);
1080           }
1081       }
1082       break;
1083 
1084     default:
1085       err = gpg_error (GPG_ERR_PUBKEY_ALGO);
1086       break;
1087     }
1088 
1089   if (err)
1090     return err;
1091 
1092   if (!gcry_pk_get_keygrip (s_pkey, array))
1093     {
1094       char *hexfpr;
1095 
1096       hexfpr = hexfingerprint (pk, NULL, 0);
1097       log_info ("error computing keygrip (fpr=%s)\n", hexfpr);
1098       xfree (hexfpr);
1099 
1100       memset (array, 0, 20);
1101       err = gpg_error (GPG_ERR_GENERAL);
1102     }
1103   else
1104     {
1105       if (DBG_PACKET)
1106         log_printhex (array, 20, "keygrip=");
1107       /* FIXME: Save the keygrip in PK.  */
1108     }
1109   gcry_sexp_release (s_pkey);
1110 
1111   return err;
1112 }
1113 
1114 
1115 /* Store an allocated buffer with the keygrip of PK encoded as a
1116    hexstring at r_GRIP.  Returns 0 on success.  */
1117 gpg_error_t
hexkeygrip_from_pk(PKT_public_key * pk,char ** r_grip)1118 hexkeygrip_from_pk (PKT_public_key *pk, char **r_grip)
1119 {
1120   gpg_error_t err;
1121   unsigned char grip[KEYGRIP_LEN];
1122 
1123   *r_grip = NULL;
1124   err = keygrip_from_pk (pk, grip);
1125   if (!err)
1126     {
1127       char * buf = xtrymalloc (KEYGRIP_LEN * 2 + 1);
1128       if (!buf)
1129         err = gpg_error_from_syserror ();
1130       else
1131         {
1132           bin2hex (grip, KEYGRIP_LEN, buf);
1133           *r_grip = buf;
1134         }
1135     }
1136   return err;
1137 }
1138