Imported Upstream version 2.4.3
[platform/upstream/gpg2.git] / g10 / misc.c
1 /* misc.c - miscellaneous functions
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
3  *               2008, 2009, 2010 Free Software Foundation, Inc.
4  * Copyright (C) 2014 Werner Koch
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <https://www.gnu.org/licenses/>.
20  */
21
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #if defined(__linux__) && defined(__alpha__) && __GLIBC__ < 2
29 #include <asm/sysinfo.h>
30 #include <asm/unistd.h>
31 #endif
32 #ifdef HAVE_SETRLIMIT
33 #include <time.h>
34 #include <sys/time.h>
35 #include <sys/resource.h>
36 #endif
37 #ifdef ENABLE_SELINUX_HACKS
38 #include <sys/stat.h>
39 #endif
40
41 #ifdef HAVE_W32_SYSTEM
42 #include <time.h>
43 #include <process.h>
44 #ifdef HAVE_WINSOCK2_H
45 # define WIN32_LEAN_AND_MEAN 1
46 # include <winsock2.h>
47 #endif
48 #include <windows.h>
49 #include <shlobj.h>
50 #ifndef CSIDL_APPDATA
51 #define CSIDL_APPDATA 0x001a
52 #endif
53 #ifndef CSIDL_LOCAL_APPDATA
54 #define CSIDL_LOCAL_APPDATA 0x001c
55 #endif
56 #ifndef CSIDL_FLAG_CREATE
57 #define CSIDL_FLAG_CREATE 0x8000
58 #endif
59 #endif /*HAVE_W32_SYSTEM*/
60
61 #include "gpg.h"
62 #ifdef HAVE_W32_SYSTEM
63 # include "../common/status.h"
64 #endif /*HAVE_W32_SYSTEM*/
65 #include "../common/util.h"
66 #include "main.h"
67 #include "photoid.h"
68 #include "options.h"
69 #include "call-agent.h"
70 #include "../common/i18n.h"
71 #include "../common/zb32.h"
72
73
74 /* FIXME: Libgcrypt 1.9 will support EAX.  Until we name this a
75  * requirement we hardwire the enum used for EAX.  */
76 #define MY_GCRY_CIPHER_MODE_EAX 14
77
78
79 #ifdef ENABLE_SELINUX_HACKS
80 /* A object and a global variable to keep track of files marked as
81    secured. */
82 struct secured_file_item
83 {
84   struct secured_file_item *next;
85   ino_t ino;
86   dev_t dev;
87 };
88 static struct secured_file_item *secured_files;
89 #endif /*ENABLE_SELINUX_HACKS*/
90
91
92
93
94 /* For the sake of SELinux we want to restrict access through gpg to
95    certain files we keep under our own control.  This function
96    registers such a file and is_secured_file may then be used to
97    check whether a file has ben registered as secured. */
98 void
99 register_secured_file (const char *fname)
100 {
101 #ifdef ENABLE_SELINUX_HACKS
102   struct stat buf;
103   struct secured_file_item *sf;
104
105   /* Note that we stop immediately if something goes wrong here. */
106   if (gnupg_stat (fname, &buf))
107     log_fatal (_("fstat of '%s' failed in %s: %s\n"), fname,
108                "register_secured_file", strerror (errno));
109 /*   log_debug ("registering '%s' i=%lu.%lu\n", fname, */
110 /*              (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
111   for (sf=secured_files; sf; sf = sf->next)
112     {
113       if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
114         return; /* Already registered.  */
115     }
116
117   sf = xmalloc (sizeof *sf);
118   sf->ino = buf.st_ino;
119   sf->dev = buf.st_dev;
120   sf->next = secured_files;
121   secured_files = sf;
122 #else /*!ENABLE_SELINUX_HACKS*/
123   (void)fname;
124 #endif /*!ENABLE_SELINUX_HACKS*/
125 }
126
127 /* Remove a file registered as secure. */
128 void
129 unregister_secured_file (const char *fname)
130 {
131 #ifdef ENABLE_SELINUX_HACKS
132   struct stat buf;
133   struct secured_file_item *sf, *sfprev;
134
135   if (gnupg_stat (fname, &buf))
136     {
137       log_error (_("fstat of '%s' failed in %s: %s\n"), fname,
138                  "unregister_secured_file", strerror (errno));
139       return;
140     }
141 /*   log_debug ("unregistering '%s' i=%lu.%lu\n", fname,  */
142 /*              (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
143   for (sfprev=NULL,sf=secured_files; sf; sfprev=sf, sf = sf->next)
144     {
145       if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
146         {
147           if (sfprev)
148             sfprev->next = sf->next;
149           else
150             secured_files = sf->next;
151           xfree (sf);
152           return;
153         }
154     }
155 #else /*!ENABLE_SELINUX_HACKS*/
156   (void)fname;
157 #endif /*!ENABLE_SELINUX_HACKS*/
158 }
159
160 /* Return true if FD is corresponds to a secured file.  Using -1 for
161    FS is allowed and will return false. */
162 int
163 is_secured_file (int fd)
164 {
165 #ifdef ENABLE_SELINUX_HACKS
166   struct stat buf;
167   struct secured_file_item *sf;
168
169   if (fd == -1)
170     return 0; /* No file descriptor so it can't be secured either.  */
171
172   /* Note that we print out a error here and claim that a file is
173      secure if something went wrong. */
174   if (fstat (fd, &buf))
175     {
176       log_error (_("fstat(%d) failed in %s: %s\n"), fd,
177                  "is_secured_file", strerror (errno));
178       return 1;
179     }
180 /*   log_debug ("is_secured_file (%d) i=%lu.%lu\n", fd, */
181 /*              (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
182   for (sf=secured_files; sf; sf = sf->next)
183     {
184       if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
185         return 1; /* Yes.  */
186     }
187 #else /*!ENABLE_SELINUX_HACKS*/
188   (void)fd;
189 #endif /*!ENABLE_SELINUX_HACKS*/
190   return 0; /* No. */
191 }
192
193 /* Return true if FNAME is corresponds to a secured file.  Using NULL,
194    "" or "-" for FS is allowed and will return false. This function is
195    used before creating a file, thus it won't fail if the file does
196    not exist. */
197 int
198 is_secured_filename (const char *fname)
199 {
200 #ifdef ENABLE_SELINUX_HACKS
201   struct stat buf;
202   struct secured_file_item *sf;
203
204   if (iobuf_is_pipe_filename (fname) || !*fname)
205     return 0;
206
207   /* Note that we print out a error here and claim that a file is
208      secure if something went wrong. */
209   if (gnupg_stat (fname, &buf))
210     {
211       if (errno == ENOENT || errno == EPERM || errno == EACCES)
212         return 0;
213       log_error (_("fstat of '%s' failed in %s: %s\n"), fname,
214                  "is_secured_filename", strerror (errno));
215       return 1;
216     }
217 /*   log_debug ("is_secured_filename (%s) i=%lu.%lu\n", fname, */
218 /*              (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
219   for (sf=secured_files; sf; sf = sf->next)
220     {
221       if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
222         return 1; /* Yes.  */
223     }
224 #else /*!ENABLE_SELINUX_HACKS*/
225   (void)fname;
226 #endif /*!ENABLE_SELINUX_HACKS*/
227   return 0; /* No. */
228 }
229
230
231
232 u16
233 checksum_u16( unsigned n )
234 {
235     u16 a;
236
237     a  = (n >> 8) & 0xff;
238     a += n & 0xff;
239     return a;
240 }
241
242
243 u16
244 checksum (const byte *p, unsigned n)
245 {
246     u16 a;
247
248     for(a=0; n; n-- )
249         a += *p++;
250     return a;
251 }
252
253 u16
254 checksum_mpi (gcry_mpi_t a)
255 {
256   u16 csum;
257   byte *buffer;
258   size_t nbytes;
259
260   /*
261    * This code can be skipped when gcry_mpi_print
262    * supports opaque MPI.
263    */
264   if (gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
265     {
266       const byte *p;
267       unsigned int nbits;
268
269       p = gcry_mpi_get_opaque (a, &nbits);
270       if (!p)
271         return 0;
272
273       csum = nbits >> 8;
274       csum += (nbits & 0xff);
275       csum += checksum (p, (nbits+7)/8);
276       return csum;
277     }
278
279   if ( gcry_mpi_print (GCRYMPI_FMT_PGP, NULL, 0, &nbytes, a) )
280     BUG ();
281   /* Fixme: For numbers not in secure memory we should use a stack
282    * based buffer and only allocate a larger one if mpi_print returns
283    * an error. */
284   buffer = (gcry_is_secure(a)?
285             gcry_xmalloc_secure (nbytes) : gcry_xmalloc (nbytes));
286   if ( gcry_mpi_print (GCRYMPI_FMT_PGP, buffer, nbytes, NULL, a) )
287     BUG ();
288   csum = checksum (buffer, nbytes);
289   xfree (buffer);
290   return csum;
291 }
292
293
294 void
295 print_pubkey_algo_note (pubkey_algo_t algo)
296 {
297   if(algo >= 100 && algo <= 110)
298     {
299       static int warn=0;
300       if(!warn)
301         {
302           warn=1;
303           es_fflush (es_stdout);
304           log_info (_("WARNING: using experimental public key algorithm %s\n"),
305                     openpgp_pk_algo_name (algo));
306         }
307     }
308   else if (algo == PUBKEY_ALGO_ELGAMAL)
309     {
310       es_fflush (es_stdout);
311       log_info (_("WARNING: Elgamal sign+encrypt keys are deprecated\n"));
312     }
313 }
314
315 void
316 print_cipher_algo_note (cipher_algo_t algo)
317 {
318   if(algo >= 100 && algo <= 110)
319     {
320       static int warn=0;
321       if(!warn)
322         {
323           warn=1;
324           es_fflush (es_stdout);
325           log_info (_("WARNING: using experimental cipher algorithm %s\n"),
326                     openpgp_cipher_algo_name (algo));
327         }
328     }
329 }
330
331 void
332 print_digest_algo_note (digest_algo_t algo)
333 {
334   if(algo >= 100 && algo <= 110)
335     {
336       static int warn=0;
337       const enum gcry_md_algos galgo = map_md_openpgp_to_gcry (algo);
338
339       if(!warn)
340         {
341           warn=1;
342           es_fflush (es_stdout);
343           log_info (_("WARNING: using experimental digest algorithm %s\n"),
344                     gcry_md_algo_name (galgo));
345         }
346     }
347   else if (is_weak_digest (algo))
348     {
349       const enum gcry_md_algos galgo = map_md_openpgp_to_gcry (algo);
350       es_fflush (es_stdout);
351       log_info (_("WARNING: digest algorithm %s is deprecated\n"),
352                 gcry_md_algo_name (galgo));
353     }
354 }
355
356
357 void
358 print_digest_rejected_note (enum gcry_md_algos algo)
359 {
360   struct weakhash* weak;
361   int show = 1;
362
363   if (opt.quiet)
364     return;
365
366   for (weak = opt.weak_digests; weak; weak = weak->next)
367     if (weak->algo == algo)
368       {
369         if (weak->rejection_shown)
370           show = 0;
371         else
372           weak->rejection_shown = 1;
373         break;
374       }
375
376   if (show)
377     {
378       es_fflush (es_stdout);
379       log_info
380         (_("Note: signatures using the %s algorithm are rejected\n"),
381          gcry_md_algo_name(algo));
382     }
383 }
384
385
386 void
387 print_sha1_keysig_rejected_note (void)
388 {
389   static int shown;
390
391   if (shown || opt.quiet)
392     return;
393
394   shown = 1;
395   es_fflush (es_stdout);
396   log_info (_("Note: third-party key signatures using"
397               " the %s algorithm are rejected\n"),
398             gcry_md_algo_name (GCRY_MD_SHA1));
399   if (!opt.quiet)
400     log_info (_("(use option \"%s\" to override)\n"),
401               "--allow-weak-key-signatures");
402 }
403
404
405 /* Print a message
406  *  "(reported error: %s)\n
407  * in verbose mode to further explain an error.  If the error code has
408  * the value IGNORE_EC no message is printed.  A message is also not
409  * printed if ERR is 0.  */
410 void
411 print_reported_error (gpg_error_t err, gpg_err_code_t ignore_ec)
412 {
413   if (!opt.verbose)
414     return;
415
416   if (!gpg_err_code (err))
417     ;
418   else if (gpg_err_code (err) == ignore_ec)
419     ;
420   else if (gpg_err_source (err) == GPG_ERR_SOURCE_DEFAULT)
421     log_info (_("(reported error: %s)\n"),
422               gpg_strerror (err));
423   else
424     log_info (_("(reported error: %s <%s>)\n"),
425               gpg_strerror (err), gpg_strsource (err));
426
427 }
428
429
430 /* Print a message
431  *   "(further info: %s)\n
432  * in verbose mode to further explain an error.  That message is
433  * intended to help debug a problem and should not be translated.
434  */
435 void
436 print_further_info (const char *format, ...)
437 {
438   va_list arg_ptr;
439
440   if (!opt.verbose)
441     return;
442
443   log_info (_("(further info: "));
444   va_start (arg_ptr, format);
445   log_logv (GPGRT_LOGLVL_CONT, format, arg_ptr);
446   va_end (arg_ptr);
447   log_printf (")\n");
448 }
449
450
451 /* Map OpenPGP algo numbers to those used by Libgcrypt.  We need to do
452    this for algorithms we implemented in Libgcrypt after they become
453    part of OpenPGP.  */
454 enum gcry_cipher_algos
455 map_cipher_openpgp_to_gcry (cipher_algo_t algo)
456 {
457   switch (algo)
458     {
459     case CIPHER_ALGO_NONE:        return GCRY_CIPHER_NONE;
460
461 #ifdef GPG_USE_IDEA
462     case CIPHER_ALGO_IDEA:        return GCRY_CIPHER_IDEA;
463 #else
464     case CIPHER_ALGO_IDEA:        return 0;
465 #endif
466
467     case CIPHER_ALGO_3DES:        return GCRY_CIPHER_3DES;
468
469 #ifdef GPG_USE_CAST5
470     case CIPHER_ALGO_CAST5:       return GCRY_CIPHER_CAST5;
471 #else
472     case CIPHER_ALGO_CAST5:       return 0;
473 #endif
474
475 #ifdef GPG_USE_BLOWFISH
476     case CIPHER_ALGO_BLOWFISH:    return GCRY_CIPHER_BLOWFISH;
477 #else
478     case CIPHER_ALGO_BLOWFISH:    return 0;
479 #endif
480
481 #ifdef GPG_USE_AES128
482     case CIPHER_ALGO_AES:         return GCRY_CIPHER_AES;
483 #else
484     case CIPHER_ALGO_AES:         return 0;
485 #endif
486
487 #ifdef GPG_USE_AES192
488     case CIPHER_ALGO_AES192:      return GCRY_CIPHER_AES192;
489 #else
490     case CIPHER_ALGO_AES192:      return 0;
491 #endif
492
493 #ifdef GPG_USE_AES256
494     case CIPHER_ALGO_AES256:      return GCRY_CIPHER_AES256;
495 #else
496     case CIPHER_ALGO_AES256:      return 0;
497 #endif
498
499 #ifdef GPG_USE_TWOFISH
500     case CIPHER_ALGO_TWOFISH:     return GCRY_CIPHER_TWOFISH;
501 #else
502     case CIPHER_ALGO_TWOFISH:     return 0;
503 #endif
504
505 #ifdef GPG_USE_CAMELLIA128
506     case CIPHER_ALGO_CAMELLIA128: return GCRY_CIPHER_CAMELLIA128;
507 #else
508     case CIPHER_ALGO_CAMELLIA128: return 0;
509 #endif
510
511 #ifdef GPG_USE_CAMELLIA192
512     case CIPHER_ALGO_CAMELLIA192: return GCRY_CIPHER_CAMELLIA192;
513 #else
514     case CIPHER_ALGO_CAMELLIA192: return 0;
515 #endif
516
517 #ifdef GPG_USE_CAMELLIA256
518     case CIPHER_ALGO_CAMELLIA256: return GCRY_CIPHER_CAMELLIA256;
519 #else
520     case CIPHER_ALGO_CAMELLIA256: return 0;
521 #endif
522     default: return 0;
523     }
524 }
525
526 /* The inverse function of above.  */
527 static cipher_algo_t
528 map_cipher_gcry_to_openpgp (enum gcry_cipher_algos algo)
529 {
530   switch (algo)
531     {
532     case GCRY_CIPHER_NONE:        return CIPHER_ALGO_NONE;
533     case GCRY_CIPHER_IDEA:        return CIPHER_ALGO_IDEA;
534     case GCRY_CIPHER_3DES:        return CIPHER_ALGO_3DES;
535     case GCRY_CIPHER_CAST5:       return CIPHER_ALGO_CAST5;
536     case GCRY_CIPHER_BLOWFISH:    return CIPHER_ALGO_BLOWFISH;
537     case GCRY_CIPHER_AES:         return CIPHER_ALGO_AES;
538     case GCRY_CIPHER_AES192:      return CIPHER_ALGO_AES192;
539     case GCRY_CIPHER_AES256:      return CIPHER_ALGO_AES256;
540     case GCRY_CIPHER_TWOFISH:     return CIPHER_ALGO_TWOFISH;
541     case GCRY_CIPHER_CAMELLIA128: return CIPHER_ALGO_CAMELLIA128;
542     case GCRY_CIPHER_CAMELLIA192: return CIPHER_ALGO_CAMELLIA192;
543     case GCRY_CIPHER_CAMELLIA256: return CIPHER_ALGO_CAMELLIA256;
544     default: return 0;
545     }
546 }
547
548
549 /* Return the block length of an OpenPGP cipher algorithm.  */
550 int
551 openpgp_cipher_blocklen (cipher_algo_t algo)
552 {
553   /* We use the numbers from OpenPGP to be sure that we get the right
554      block length.  This is so that the packet parsing code works even
555      for unknown algorithms (for which we assume 8 due to tradition).
556
557      NOTE: If you change the returned blocklen above 16, check
558      the callers because they may use a fixed size buffer of that
559      size. */
560   switch (algo)
561     {
562     case CIPHER_ALGO_AES:
563     case CIPHER_ALGO_AES192:
564     case CIPHER_ALGO_AES256:
565     case CIPHER_ALGO_TWOFISH:
566     case CIPHER_ALGO_CAMELLIA128:
567     case CIPHER_ALGO_CAMELLIA192:
568     case CIPHER_ALGO_CAMELLIA256:
569       return 16;
570
571     default:
572       return 8;
573     }
574 }
575
576 /****************
577  * Wrapper around the libgcrypt function with additional checks on
578  * the OpenPGP constraints for the algo ID.
579  */
580 int
581 openpgp_cipher_test_algo (cipher_algo_t algo)
582 {
583   enum gcry_cipher_algos ga;
584
585   ga = map_cipher_openpgp_to_gcry (algo);
586   if (!ga)
587     return gpg_error (GPG_ERR_CIPHER_ALGO);
588
589   return gcry_cipher_test_algo (ga);
590 }
591
592 /* Map the OpenPGP cipher algorithm whose ID is contained in ALGORITHM to a
593    string representation of the algorithm name.  For unknown algorithm
594    IDs this function returns "?".  */
595 const char *
596 openpgp_cipher_algo_name (cipher_algo_t algo)
597 {
598   switch (algo)
599     {
600     case CIPHER_ALGO_IDEA:        return "IDEA";
601     case CIPHER_ALGO_3DES:        return "3DES";
602     case CIPHER_ALGO_CAST5:       return "CAST5";
603     case CIPHER_ALGO_BLOWFISH:    return "BLOWFISH";
604     case CIPHER_ALGO_AES:         return "AES";
605     case CIPHER_ALGO_AES192:      return "AES192";
606     case CIPHER_ALGO_AES256:      return "AES256";
607     case CIPHER_ALGO_TWOFISH:     return "TWOFISH";
608     case CIPHER_ALGO_CAMELLIA128: return "CAMELLIA128";
609     case CIPHER_ALGO_CAMELLIA192: return "CAMELLIA192";
610     case CIPHER_ALGO_CAMELLIA256: return "CAMELLIA256";
611     case CIPHER_ALGO_NONE:
612     default: return "?";
613     }
614 }
615
616
617 /* Same as openpgp_cipher_algo_name but returns a string in the form
618  * "ALGO.MODE".  If AEAD is 0 "CFB" is used for the mode.  */
619 const char *
620 openpgp_cipher_algo_mode_name (cipher_algo_t algo, aead_algo_t aead)
621 {
622   return map_static_strings ("openpgp_cipher_algo_mode_name", algo, aead,
623                              openpgp_cipher_algo_name (algo),
624                              ".",
625                              aead? openpgp_aead_algo_name (aead) : "CFB",
626                              NULL);
627 }
628
629
630 /* Return 0 if ALGO is supported.  Return an error if not. */
631 gpg_error_t
632 openpgp_aead_test_algo (aead_algo_t algo)
633 {
634   /* FIXME: We currently have no easy way to test whether libgcrypt
635    * implements a mode.  The only way we can do this is to open a
636    * cipher context with that mode and close it immediately.  That is
637    * a bit costly.  Thus in case we add another algo we need to look
638    * at the libgcrypt version and assume nothing has been patched out.  */
639   switch (algo)
640     {
641     case AEAD_ALGO_NONE:
642       break;
643
644     case AEAD_ALGO_EAX:
645     case AEAD_ALGO_OCB:
646       return 0;
647     }
648
649   return gpg_error (GPG_ERR_INV_CIPHER_MODE);
650 }
651
652
653 /* Map the OpenPGP AEAD algorithm with ID ALGO to a string
654  * representation of the algorithm name.  For unknown algorithm IDs
655  * this function returns "?".  */
656 const char *
657 openpgp_aead_algo_name (aead_algo_t algo)
658 {
659   switch (algo)
660     {
661     case AEAD_ALGO_NONE:  break;
662     case AEAD_ALGO_EAX:   return "EAX";
663     case AEAD_ALGO_OCB:   return "OCB";
664     }
665
666   return "?";
667 }
668
669
670 /* Return information for the AEAD algorithm ALGO.  The corresponding
671  * Libgcrypt ciphermode is stored at R_MODE and the required number of
672  * octets for the nonce at R_NONCELEN.  On error and error code is
673  * returned.  Note that the taglen is always 128 bits.  */
674 gpg_error_t
675 openpgp_aead_algo_info (aead_algo_t algo, enum gcry_cipher_modes *r_mode,
676                         unsigned int *r_noncelen)
677 {
678   switch (algo)
679     {
680     case AEAD_ALGO_OCB:
681       *r_mode = GCRY_CIPHER_MODE_OCB;
682       *r_noncelen = 15;
683       break;
684
685     case AEAD_ALGO_EAX:
686       *r_mode = MY_GCRY_CIPHER_MODE_EAX;
687       *r_noncelen = 16;
688       break;
689
690     default:
691       log_error ("unsupported AEAD algo %d\n", algo);
692       return gpg_error (GPG_ERR_INV_CIPHER_MODE);
693     }
694   return 0;
695 }
696
697
698 /* Return 0 if ALGO is a supported OpenPGP public key algorithm.  */
699 int
700 openpgp_pk_test_algo (pubkey_algo_t algo)
701 {
702   return openpgp_pk_test_algo2 (algo, 0);
703 }
704
705
706 /* Return 0 if ALGO is a supported OpenPGP public key algorithm and
707    allows the usage USE.  */
708 int
709 openpgp_pk_test_algo2 (pubkey_algo_t algo, unsigned int use)
710 {
711   enum gcry_pk_algos ga = 0;
712   size_t use_buf = use;
713
714   switch (algo)
715     {
716 #ifdef GPG_USE_RSA
717     case PUBKEY_ALGO_RSA:       ga = GCRY_PK_RSA;   break;
718     case PUBKEY_ALGO_RSA_E:     ga = GCRY_PK_RSA_E; break;
719     case PUBKEY_ALGO_RSA_S:     ga = GCRY_PK_RSA_S; break;
720 #else
721     case PUBKEY_ALGO_RSA:       break;
722     case PUBKEY_ALGO_RSA_E:     break;
723     case PUBKEY_ALGO_RSA_S:     break;
724 #endif
725
726     case PUBKEY_ALGO_ELGAMAL_E: ga = GCRY_PK_ELG;   break;
727     case PUBKEY_ALGO_DSA:       ga = GCRY_PK_DSA;   break;
728
729 #ifdef GPG_USE_ECDH
730     case PUBKEY_ALGO_ECDH:      ga = GCRY_PK_ECC;   break;
731 #else
732     case PUBKEY_ALGO_ECDH:      break;
733 #endif
734
735 #ifdef GPG_USE_ECDSA
736     case PUBKEY_ALGO_ECDSA:     ga = GCRY_PK_ECC;   break;
737 #else
738     case PUBKEY_ALGO_ECDSA:     break;
739 #endif
740
741 #ifdef GPG_USE_EDDSA
742     case PUBKEY_ALGO_EDDSA:     ga = GCRY_PK_ECC;   break;
743 #else
744     case PUBKEY_ALGO_EDDSA:     break;
745 #endif
746
747     case PUBKEY_ALGO_ELGAMAL:
748       /* Don't allow type 20 keys unless in rfc2440 mode.  */
749       if (RFC2440)
750         ga = GCRY_PK_ELG;
751       break;
752
753     default:
754       break;
755     }
756   if (!ga)
757     return gpg_error (GPG_ERR_PUBKEY_ALGO);
758
759   /* Elgamal in OpenPGP used to support signing and Libgcrypt still
760    * does.  However, we removed the signing capability from gpg ages
761    * ago.  This function should reflect this so that errors are thrown
762    * early and not only when we try to sign using Elgamal.  */
763   if (ga == GCRY_PK_ELG && (use & (PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG)))
764     return gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
765
766   /* Now check whether Libgcrypt has support for the algorithm.  */
767   return gcry_pk_algo_info (ga, GCRYCTL_TEST_ALGO, NULL, &use_buf);
768 }
769
770
771 int
772 openpgp_pk_algo_usage ( int algo )
773 {
774     int use = 0;
775
776     /* They are hardwired in gpg 1.0. */
777     switch ( algo ) {
778       case PUBKEY_ALGO_RSA:
779           use = (PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG
780                  | PUBKEY_USAGE_ENC | PUBKEY_USAGE_RENC | PUBKEY_USAGE_AUTH);
781           break;
782       case PUBKEY_ALGO_RSA_E:
783       case PUBKEY_ALGO_ECDH:
784           use = PUBKEY_USAGE_ENC | PUBKEY_USAGE_RENC;
785           break;
786       case PUBKEY_ALGO_RSA_S:
787           use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG;
788           break;
789       case PUBKEY_ALGO_ELGAMAL:
790           if (RFC2440)
791              use = PUBKEY_USAGE_ENC | PUBKEY_USAGE_RENC;
792           break;
793       case PUBKEY_ALGO_ELGAMAL_E:
794           use = PUBKEY_USAGE_ENC | PUBKEY_USAGE_RENC;
795           break;
796       case PUBKEY_ALGO_DSA:
797           use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG | PUBKEY_USAGE_AUTH;
798           break;
799       case PUBKEY_ALGO_ECDSA:
800       case PUBKEY_ALGO_EDDSA:
801           use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG | PUBKEY_USAGE_AUTH;
802       default:
803           break;
804     }
805     return use;
806 }
807
808 /* Map the OpenPGP pubkey algorithm whose ID is contained in ALGO to a
809    string representation of the algorithm name.  For unknown algorithm
810    IDs this function returns "?".  */
811 const char *
812 openpgp_pk_algo_name (pubkey_algo_t algo)
813 {
814   switch (algo)
815     {
816     case PUBKEY_ALGO_RSA:
817     case PUBKEY_ALGO_RSA_E:
818     case PUBKEY_ALGO_RSA_S:     return "RSA";
819     case PUBKEY_ALGO_ELGAMAL:
820     case PUBKEY_ALGO_ELGAMAL_E: return "ELG";
821     case PUBKEY_ALGO_DSA:       return "DSA";
822     case PUBKEY_ALGO_ECDH:      return "ECDH";
823     case PUBKEY_ALGO_ECDSA:     return "ECDSA";
824     case PUBKEY_ALGO_EDDSA:     return "EDDSA";
825     default: return "?";
826     }
827 }
828
829
830 /* Explicit mapping of OpenPGP digest algos to Libgcrypt.  */
831 /* FIXME: We do not yes use it everywhere.  */
832 enum gcry_md_algos
833 map_md_openpgp_to_gcry (digest_algo_t algo)
834 {
835   switch (algo)
836     {
837 #ifdef GPG_USE_MD5
838     case DIGEST_ALGO_MD5:    return GCRY_MD_MD5;
839 #else
840     case DIGEST_ALGO_MD5:    return 0;
841 #endif
842
843     case DIGEST_ALGO_SHA1:   return GCRY_MD_SHA1;
844
845 #ifdef GPG_USE_RMD160
846     case DIGEST_ALGO_RMD160: return GCRY_MD_RMD160;
847 #else
848     case DIGEST_ALGO_RMD160: return 0;
849 #endif
850
851 #ifdef GPG_USE_SHA224
852     case DIGEST_ALGO_SHA224: return GCRY_MD_SHA224;
853 #else
854     case DIGEST_ALGO_SHA224: return 0;
855 #endif
856
857     case DIGEST_ALGO_SHA256: return GCRY_MD_SHA256;
858
859 #ifdef GPG_USE_SHA384
860     case DIGEST_ALGO_SHA384: return GCRY_MD_SHA384;
861 #else
862     case DIGEST_ALGO_SHA384: return 0;
863 #endif
864
865 #ifdef GPG_USE_SHA512
866     case DIGEST_ALGO_SHA512: return GCRY_MD_SHA512;
867 #else
868     case DIGEST_ALGO_SHA512: return 0;
869 #endif
870     default: return 0;
871     }
872 }
873
874
875 /* Return 0 if ALGO is suitable and implemented OpenPGP hash
876    algorithm.  */
877 int
878 openpgp_md_test_algo (digest_algo_t algo)
879 {
880   enum gcry_md_algos ga;
881
882   ga = map_md_openpgp_to_gcry (algo);
883   if (!ga)
884     return gpg_error (GPG_ERR_DIGEST_ALGO);
885
886   return gcry_md_test_algo (ga);
887 }
888
889
890 /* Map the OpenPGP digest algorithm whose ID is contained in ALGO to a
891    string representation of the algorithm name.  For unknown algorithm
892    IDs this function returns "?".  */
893 const char *
894 openpgp_md_algo_name (int algo)
895 {
896   switch (algo)
897     {
898     case DIGEST_ALGO_MD5:    return "MD5";
899     case DIGEST_ALGO_SHA1:   return "SHA1";
900     case DIGEST_ALGO_RMD160: return "RIPEMD160";
901     case DIGEST_ALGO_SHA256: return "SHA256";
902     case DIGEST_ALGO_SHA384: return "SHA384";
903     case DIGEST_ALGO_SHA512: return "SHA512";
904     case DIGEST_ALGO_SHA224: return "SHA224";
905     }
906   return "?";
907 }
908
909
910 static unsigned long
911 get_signature_count (PKT_public_key *pk)
912 {
913 #ifdef ENABLE_CARD_SUPPORT
914   struct agent_card_info_s info;
915
916   (void)pk;
917   if (!agent_scd_getattr ("SIG-COUNTER",&info))
918     return info.sig_counter;
919   else
920     return 0;
921 #else
922   (void)pk;
923   return 0;
924 #endif
925 }
926
927 /* Expand %-strings.  Returns a string which must be xfreed.  Returns
928    NULL if the string cannot be expanded (too large). */
929 char *
930 pct_expando (ctrl_t ctrl, const char *string,struct expando_args *args)
931 {
932   const char *ch=string;
933   int idx=0,maxlen=0,done=0;
934   u32 pk_keyid[2]={0,0},sk_keyid[2]={0,0};
935   char *ret=NULL;
936
937   /* The parser below would return NULL for an empty string, thus we
938    * catch it here.  Also catch NULL here. */
939   if (!string || !*string)
940     return xstrdup ("");
941
942   if(args->pk)
943     keyid_from_pk(args->pk,pk_keyid);
944
945   if(args->pksk)
946     keyid_from_pk (args->pksk, sk_keyid);
947
948   /* This is used so that %k works in photoid command strings in
949      --list-secret-keys (which of course has a sk, but no pk). */
950   if(!args->pk && args->pksk)
951     keyid_from_pk (args->pksk, pk_keyid);
952
953   while(*ch!='\0')
954     {
955       if(!done)
956         {
957           /* 8192 is way bigger than we'll need here */
958           if(maxlen>=8192)
959             goto fail;
960
961           maxlen+=1024;
962           ret=xrealloc(ret,maxlen);
963         }
964
965       done=0;
966
967       if(*ch=='%')
968         {
969           switch(*(ch+1))
970             {
971             case 's': /* short key id */
972               if(idx+8<maxlen)
973                 {
974                   sprintf(&ret[idx],"%08lX",(ulong)sk_keyid[1]);
975                   idx+=8;
976                   done=1;
977                 }
978               break;
979
980             case 'S': /* long key id */
981               if(idx+16<maxlen)
982                 {
983                   sprintf(&ret[idx],"%08lX%08lX",
984                           (ulong)sk_keyid[0],(ulong)sk_keyid[1]);
985                   idx+=16;
986                   done=1;
987                 }
988               break;
989
990             case 'k': /* short key id */
991               if(idx+8<maxlen)
992                 {
993                   sprintf(&ret[idx],"%08lX",(ulong)pk_keyid[1]);
994                   idx+=8;
995                   done=1;
996                 }
997               break;
998
999             case 'K': /* long key id */
1000               if(idx+16<maxlen)
1001                 {
1002                   sprintf(&ret[idx],"%08lX%08lX",
1003                           (ulong)pk_keyid[0],(ulong)pk_keyid[1]);
1004                   idx+=16;
1005                   done=1;
1006                 }
1007               break;
1008
1009             case 'U': /* z-base-32 encoded user id hash. */
1010               if (args->namehash)
1011                 {
1012                   char *tmp = zb32_encode (args->namehash, 8*20);
1013                   if (tmp)
1014                     {
1015                       if (idx + strlen (tmp) < maxlen)
1016                         {
1017                           strcpy (ret+idx, tmp);
1018                           idx += strlen (tmp);
1019                         }
1020                       xfree (tmp);
1021                       done = 1;
1022                     }
1023                 }
1024               break;
1025
1026             case 'c': /* signature count from card, if any. */
1027               if(idx+10<maxlen)
1028                 {
1029                   sprintf (&ret[idx],"%lu", get_signature_count (args->pksk));
1030                   idx+=strlen(&ret[idx]);
1031                   done=1;
1032                 }
1033               break;
1034
1035             case 'f': /* Fingerprint of key being signed */
1036             case 'p': /* Fingerprint of the primary key making the signature. */
1037             case 'g': /* Fingerprint of the key making the signature.  */
1038               {
1039                 byte array[MAX_FINGERPRINT_LEN];
1040                 size_t len;
1041                 int i;
1042
1043                 if ((*(ch+1))=='f' && args->pk)
1044                   fingerprint_from_pk (args->pk, array, &len);
1045                 else if ((*(ch+1))=='p' && args->pksk)
1046                   {
1047                     if(args->pksk->flags.primary)
1048                       fingerprint_from_pk (args->pksk, array, &len);
1049                     else if (args->pksk->main_keyid[0]
1050                              || args->pksk->main_keyid[1])
1051                       {
1052                         /* Not the primary key: Find the fingerprint
1053                            of the primary key.  */
1054                         PKT_public_key *pk=
1055                           xmalloc_clear(sizeof(PKT_public_key));
1056
1057                         if (!get_pubkey_fast (ctrl, pk,args->pksk->main_keyid))
1058                           fingerprint_from_pk (pk, array, &len);
1059                         else
1060                           memset (array, 0, (len=MAX_FINGERPRINT_LEN));
1061                         free_public_key (pk);
1062                       }
1063                     else /* Oops: info about the primary key missing.  */
1064                       memset(array,0,(len=MAX_FINGERPRINT_LEN));
1065                   }
1066                 else if((*(ch+1))=='g' && args->pksk)
1067                   fingerprint_from_pk (args->pksk, array, &len);
1068                 else
1069                   memset(array,0,(len=MAX_FINGERPRINT_LEN));
1070
1071                 if(idx+(len*2)<maxlen)
1072                   {
1073                     for(i=0;i<len;i++)
1074                       {
1075                         sprintf(&ret[idx],"%02X",array[i]);
1076                         idx+=2;
1077                       }
1078                     done=1;
1079                   }
1080               }
1081               break;
1082
1083             case 'v': /* validity letters */
1084               if(args->validity_info && idx+1<maxlen)
1085                 {
1086                   ret[idx++]=args->validity_info;
1087                   ret[idx]='\0';
1088                   done=1;
1089                 }
1090               break;
1091
1092               /* The text string types */
1093             case 't':
1094             case 'T':
1095             case 'V':
1096               {
1097                 const char *str=NULL;
1098
1099                 switch(*(ch+1))
1100                   {
1101                   case 't': /* e.g. "jpg" */
1102                     str=image_type_to_string(args->imagetype,0);
1103                     break;
1104
1105                   case 'T': /* e.g. "image/jpeg" */
1106                     str=image_type_to_string(args->imagetype,2);
1107                     break;
1108
1109                   case 'V': /* e.g. "full", "expired", etc. */
1110                     str=args->validity_string;
1111                     break;
1112                   }
1113
1114                 if(str && idx+strlen(str)<maxlen)
1115                   {
1116                     strcpy(&ret[idx],str);
1117                     idx+=strlen(str);
1118                     done=1;
1119                   }
1120               }
1121               break;
1122
1123             case '%':
1124               if(idx+1<maxlen)
1125                 {
1126                   ret[idx++]='%';
1127                   ret[idx]='\0';
1128                   done=1;
1129                 }
1130               break;
1131
1132               /* Any unknown %-keys (like %i, %o, %I, and %O) are
1133                  passed through for later expansion.  Note this also
1134                  handles the case where the last character in the
1135                  string is a '%' - the terminating \0 will end up here
1136                  and properly terminate the string. */
1137             default:
1138               if(idx+2<maxlen)
1139                 {
1140                   ret[idx++]='%';
1141                   ret[idx++]=*(ch+1);
1142                   ret[idx]='\0';
1143                   done=1;
1144                 }
1145               break;
1146               }
1147
1148           if(done)
1149             ch++;
1150         }
1151       else
1152         {
1153           if(idx+1<maxlen)
1154             {
1155               ret[idx++]=*ch;
1156               ret[idx]='\0';
1157               done=1;
1158             }
1159         }
1160
1161       if(done)
1162         ch++;
1163     }
1164
1165   return ret;
1166
1167  fail:
1168   xfree(ret);
1169   return NULL;
1170 }
1171
1172 void
1173 deprecated_warning(const char *configname,unsigned int configlineno,
1174                    const char *option,const char *repl1,const char *repl2)
1175 {
1176   if(configname)
1177     {
1178       if(strncmp("--",option,2)==0)
1179         option+=2;
1180
1181       if(strncmp("--",repl1,2)==0)
1182         repl1+=2;
1183
1184       log_info(_("%s:%d: deprecated option \"%s\"\n"),
1185                configname,configlineno,option);
1186     }
1187   else
1188     log_info(_("WARNING: \"%s\" is a deprecated option\n"),option);
1189
1190   log_info(_("please use \"%s%s\" instead\n"),repl1,repl2);
1191 }
1192
1193
1194 void
1195 deprecated_command (const char *name)
1196 {
1197   log_info(_("WARNING: \"%s\" is a deprecated command - do not use it\n"),
1198            name);
1199 }
1200
1201
1202 void
1203 obsolete_scdaemon_option (const char *configname, unsigned int configlineno,
1204                           const char *name)
1205 {
1206   if (configname)
1207     log_info (_("%s:%u: \"%s\" is obsolete in this file"
1208                 " - it only has effect in %s\n"),
1209               configname, configlineno, name, SCDAEMON_NAME EXTSEP_S "conf");
1210   else
1211     log_info (_("WARNING: \"%s%s\" is an obsolete option"
1212                 " - it has no effect except on %s\n"),
1213               "--", name, SCDAEMON_NAME);
1214 }
1215
1216
1217 /*
1218  * Wrapper around gcry_cipher_map_name to provide a fallback using the
1219  * "Sn" syntax as used by the preference strings.
1220  */
1221 int
1222 string_to_cipher_algo (const char *string)
1223 {
1224   int val;
1225
1226   val = map_cipher_gcry_to_openpgp (gcry_cipher_map_name (string));
1227   if (!val && string && (string[0]=='S' || string[0]=='s'))
1228     {
1229       char *endptr;
1230
1231       string++;
1232       val = strtol (string, &endptr, 10);
1233       if (!*string || *endptr || openpgp_cipher_test_algo (val))
1234         val = 0;
1235     }
1236
1237   return val;
1238 }
1239
1240
1241 /*
1242  * Map an AEAD mode string to a an AEAD algorithm number as defined by
1243  * rfc4880bis.  Also support the "An" syntax as used by the preference
1244  * strings.
1245  */
1246 aead_algo_t
1247 string_to_aead_algo (const char *string)
1248 {
1249   int result;
1250
1251   if (!string)
1252     result = 0;
1253   else if (!ascii_strcasecmp (string, "EAX"))
1254     result = 1;
1255   else if (!ascii_strcasecmp (string, "OCB"))
1256     result = 2;
1257   else if ((string[0]=='A' || string[0]=='a'))
1258     {
1259       char *endptr;
1260
1261       string++;
1262       result = strtol (string, &endptr, 10);
1263       if (!*string || *endptr || result < 1 || result > 2)
1264         result = 0;
1265     }
1266   else
1267     result = 0;
1268
1269   return result;
1270 }
1271
1272
1273 /*
1274  * Wrapper around gcry_md_map_name to provide a fallback using the
1275  * "Hn" syntax as used by the preference strings.
1276  */
1277 int
1278 string_to_digest_algo (const char *string)
1279 {
1280   int val;
1281
1282   /* FIXME: We should make use of our wrapper function and not assume
1283      that there is a 1 to 1 mapping between OpenPGP and Libgcrypt.  */
1284   val = gcry_md_map_name (string);
1285   if (!val && string && (string[0]=='H' || string[0]=='h'))
1286     {
1287       char *endptr;
1288
1289       string++;
1290       val = strtol (string, &endptr, 10);
1291       if (!*string || *endptr || openpgp_md_test_algo (val))
1292         val = 0;
1293     }
1294
1295   return val;
1296 }
1297
1298
1299
1300 const char *
1301 compress_algo_to_string(int algo)
1302 {
1303   const char *s=NULL;
1304
1305   switch(algo)
1306     {
1307     case COMPRESS_ALGO_NONE:
1308       s=_("Uncompressed");
1309       break;
1310
1311     case COMPRESS_ALGO_ZIP:
1312       s="ZIP";
1313       break;
1314
1315     case COMPRESS_ALGO_ZLIB:
1316       s="ZLIB";
1317       break;
1318
1319 #ifdef HAVE_BZIP2
1320     case COMPRESS_ALGO_BZIP2:
1321       s="BZIP2";
1322       break;
1323 #endif
1324     }
1325
1326   return s;
1327 }
1328
1329 int
1330 string_to_compress_algo(const char *string)
1331 {
1332   /* TRANSLATORS: See doc/TRANSLATE about this string. */
1333   if(match_multistr(_("uncompressed|none"),string))
1334     return 0;
1335   else if(ascii_strcasecmp(string,"uncompressed")==0)
1336     return 0;
1337   else if(ascii_strcasecmp(string,"none")==0)
1338     return 0;
1339   else if(ascii_strcasecmp(string,"zip")==0)
1340     return 1;
1341   else if(ascii_strcasecmp(string,"zlib")==0)
1342     return 2;
1343 #ifdef HAVE_BZIP2
1344   else if(ascii_strcasecmp(string,"bzip2")==0)
1345     return 3;
1346 #endif
1347   else if(ascii_strcasecmp(string,"z0")==0)
1348     return 0;
1349   else if(ascii_strcasecmp(string,"z1")==0)
1350     return 1;
1351   else if(ascii_strcasecmp(string,"z2")==0)
1352     return 2;
1353 #ifdef HAVE_BZIP2
1354   else if(ascii_strcasecmp(string,"z3")==0)
1355     return 3;
1356 #endif
1357   else
1358     return -1;
1359 }
1360
1361 int
1362 check_compress_algo(int algo)
1363 {
1364   switch (algo)
1365     {
1366     case 0: return 0;
1367 #ifdef HAVE_ZIP
1368     case 1:
1369     case 2: return 0;
1370 #endif
1371 #ifdef HAVE_BZIP2
1372     case 3: return 0;
1373 #endif
1374     default: return GPG_ERR_COMPR_ALGO;
1375     }
1376 }
1377
1378 int
1379 default_cipher_algo(void)
1380 {
1381   if(opt.def_cipher_algo)
1382     return opt.def_cipher_algo;
1383   else if(opt.personal_cipher_prefs)
1384     return opt.personal_cipher_prefs[0].value;
1385   else
1386     return opt.s2k_cipher_algo;
1387 }
1388
1389
1390 /* There is no default_digest_algo function, but see
1391    sign.c:hash_for() */
1392
1393 int
1394 default_compress_algo(void)
1395 {
1396   if(opt.compress_algo!=-1)
1397     return opt.compress_algo;
1398   else if(opt.personal_compress_prefs)
1399     return opt.personal_compress_prefs[0].value;
1400   else
1401     return DEFAULT_COMPRESS_ALGO;
1402 }
1403
1404
1405 void
1406 compliance_failure(void)
1407 {
1408   char *ver="???";
1409
1410   switch(opt.compliance)
1411     {
1412     case CO_GNUPG:
1413       ver="GnuPG";
1414       break;
1415
1416     case CO_RFC4880:
1417       ver="OpenPGP";
1418       break;
1419
1420     case CO_RFC2440:
1421       ver="OpenPGP (older)";
1422       break;
1423
1424     case CO_PGP7:
1425       ver="PGP 7.x";
1426       break;
1427
1428     case CO_PGP8:
1429       ver="PGP 8.x";
1430       break;
1431
1432     case CO_DE_VS:
1433       ver="DE-VS applications";
1434       break;
1435     }
1436
1437   log_info(_("this message may not be usable by %s\n"),ver);
1438   opt.compliance=CO_GNUPG;
1439 }
1440
1441 /* Break a string into successive option pieces.  Accepts single word
1442    options and key=value argument options. */
1443 char *
1444 optsep(char **stringp)
1445 {
1446   char *tok,*end;
1447
1448   tok=*stringp;
1449   if(tok)
1450     {
1451       end=strpbrk(tok," ,=");
1452       if(end)
1453         {
1454           int sawequals=0;
1455           char *ptr=end;
1456
1457           /* what we need to do now is scan along starting with *end,
1458              If the next character we see (ignoring spaces) is an =
1459              sign, then there is an argument. */
1460
1461           while(*ptr)
1462             {
1463               if(*ptr=='=')
1464                 sawequals=1;
1465               else if(*ptr!=' ')
1466                 break;
1467               ptr++;
1468             }
1469
1470           /* There is an argument, so grab that too.  At this point,
1471              ptr points to the first character of the argument. */
1472           if(sawequals)
1473             {
1474               /* Is it a quoted argument? */
1475               if(*ptr=='"')
1476                 {
1477                   ptr++;
1478                   end=strchr(ptr,'"');
1479                   if(end)
1480                     end++;
1481                 }
1482               else
1483                 end=strpbrk(ptr," ,");
1484             }
1485
1486           if(end && *end)
1487             {
1488               *end='\0';
1489               *stringp=end+1;
1490             }
1491           else
1492             *stringp=NULL;
1493         }
1494       else
1495         *stringp=NULL;
1496     }
1497
1498   return tok;
1499 }
1500
1501 /* Breaks an option value into key and value.  Returns NULL if there
1502    is no value.  Note that "string" is modified to remove the =value
1503    part. */
1504 char *
1505 argsplit(char *string)
1506 {
1507   char *equals,*arg=NULL;
1508
1509   equals=strchr(string,'=');
1510   if(equals)
1511     {
1512       char *quote,*space;
1513
1514       *equals='\0';
1515       arg=equals+1;
1516
1517       /* Quoted arg? */
1518       quote=strchr(arg,'"');
1519       if(quote)
1520         {
1521           arg=quote+1;
1522
1523           quote=strchr(arg,'"');
1524           if(quote)
1525             *quote='\0';
1526         }
1527       else
1528         {
1529           size_t spaces;
1530
1531           /* Trim leading spaces off of the arg */
1532           spaces=strspn(arg," ");
1533           arg+=spaces;
1534         }
1535
1536       /* Trim tailing spaces off of the tag */
1537       space=strchr(string,' ');
1538       if(space)
1539         *space='\0';
1540     }
1541
1542   return arg;
1543 }
1544
1545 /* Return the length of the initial token, leaving off any
1546    argument. */
1547 static size_t
1548 optlen(const char *s)
1549 {
1550   char *end=strpbrk(s," =");
1551
1552   if(end)
1553     return end-s;
1554   else
1555     return strlen(s);
1556 }
1557
1558
1559 /* Note: This function returns true on success.  */
1560 int
1561 parse_options(char *str,unsigned int *options,
1562               struct parse_options *opts,int noisy)
1563 {
1564   char *tok;
1565
1566   if (str && (!strcmp (str, "help") || !strcmp (str, "full-help")))
1567     {
1568       int i,maxlen=0;
1569       int full = *str == 'f';
1570
1571       /* Figure out the longest option name so we can line these up
1572          neatly. */
1573       for(i=0;opts[i].name;i++)
1574         if(opts[i].help && maxlen<strlen(opts[i].name))
1575           maxlen=strlen(opts[i].name);
1576
1577       for(i=0;opts[i].name;i++)
1578         if(opts[i].help)
1579           es_printf("%s%*s%s\n",opts[i].name,
1580                     maxlen+2-(int)strlen(opts[i].name),"",_(opts[i].help));
1581       if (full)
1582         for (i=0; opts[i].name; i++)
1583           if(!opts[i].help)
1584             es_printf("%s\n",opts[i].name);
1585
1586       g10_exit(0);
1587     }
1588
1589   while((tok=optsep(&str)))
1590     {
1591       int i,rev=0;
1592       char *otok=tok;
1593
1594       if(tok[0]=='\0')
1595         continue;
1596
1597       if(ascii_strncasecmp("no-",tok,3)==0)
1598         {
1599           rev=1;
1600           tok+=3;
1601         }
1602
1603       for(i=0;opts[i].name;i++)
1604         {
1605           size_t toklen=optlen(tok);
1606
1607           if(ascii_strncasecmp(opts[i].name,tok,toklen)==0)
1608             {
1609               /* We have a match, but it might be incomplete */
1610               if(toklen!=strlen(opts[i].name))
1611                 {
1612                   int j;
1613
1614                   for(j=i+1;opts[j].name;j++)
1615                     {
1616                       if(ascii_strncasecmp(opts[j].name,tok,toklen)==0)
1617                         {
1618                           if(noisy)
1619                             log_info(_("ambiguous option '%s'\n"),otok);
1620                           return 0;
1621                         }
1622                     }
1623                 }
1624
1625               if(rev)
1626                 {
1627                   *options&=~opts[i].bit;
1628                   if(opts[i].value)
1629                     *opts[i].value=NULL;
1630                 }
1631               else
1632                 {
1633                   *options|=opts[i].bit;
1634                   if(opts[i].value)
1635                     *opts[i].value=argsplit(tok);
1636                 }
1637               break;
1638             }
1639         }
1640
1641       if(!opts[i].name)
1642         {
1643           if(noisy)
1644             log_info(_("unknown option '%s'\n"),otok);
1645           return 0;
1646         }
1647     }
1648
1649   return 1;
1650 }
1651
1652
1653 /* Similar to access(2), but uses PATH to find the file. */
1654 int
1655 path_access(const char *file,int mode)
1656 {
1657   char *envpath;
1658   int ret=-1;
1659
1660   envpath=getenv("PATH");
1661
1662   if(!envpath
1663 #ifdef HAVE_DRIVE_LETTERS
1664      || (((file[0]>='A' && file[0]<='Z')
1665           || (file[0]>='a' && file[0]<='z'))
1666          && file[1]==':')
1667 #else
1668      || file[0]=='/'
1669 #endif
1670      )
1671     return access(file,mode);
1672   else
1673     {
1674       /* At least as large as, but most often larger than we need. */
1675       char *buffer=xmalloc(strlen(envpath)+1+strlen(file)+1);
1676       char *split,*item,*path=xstrdup(envpath);
1677
1678       split=path;
1679
1680       while((item=strsep(&split,PATHSEP_S)))
1681         {
1682           strcpy(buffer,item);
1683           strcat(buffer,"/");
1684           strcat(buffer,file);
1685           ret=access(buffer,mode);
1686           if(ret==0)
1687             break;
1688         }
1689
1690       xfree(path);
1691       xfree(buffer);
1692     }
1693
1694   return ret;
1695 }
1696
1697
1698 \f
1699 /* Return the number of public key parameters as used by OpenPGP.  */
1700 int
1701 pubkey_get_npkey (pubkey_algo_t algo)
1702 {
1703   switch (algo)
1704     {
1705     case PUBKEY_ALGO_RSA:
1706     case PUBKEY_ALGO_RSA_E:
1707     case PUBKEY_ALGO_RSA_S:     return 2;
1708     case PUBKEY_ALGO_ELGAMAL_E: return 3;
1709     case PUBKEY_ALGO_DSA:       return 4;
1710     case PUBKEY_ALGO_ECDH:      return 3;
1711     case PUBKEY_ALGO_ECDSA:     return 2;
1712     case PUBKEY_ALGO_ELGAMAL:   return 3;
1713     case PUBKEY_ALGO_EDDSA:     return 2;
1714     default: return 0;
1715     }
1716 }
1717
1718
1719 /* Return the number of secret key parameters as used by OpenPGP.  */
1720 int
1721 pubkey_get_nskey (pubkey_algo_t algo)
1722 {
1723   switch (algo)
1724     {
1725     case PUBKEY_ALGO_RSA:
1726     case PUBKEY_ALGO_RSA_E:
1727     case PUBKEY_ALGO_RSA_S:     return 6;
1728     case PUBKEY_ALGO_ELGAMAL_E: return 4;
1729     case PUBKEY_ALGO_DSA:       return 5;
1730     case PUBKEY_ALGO_ECDH:      return 4;
1731     case PUBKEY_ALGO_ECDSA:     return 3;
1732     case PUBKEY_ALGO_ELGAMAL:   return 4;
1733     case PUBKEY_ALGO_EDDSA:     return 3;
1734     default: return 0;
1735     }
1736 }
1737
1738 /* Temporary helper. */
1739 int
1740 pubkey_get_nsig (pubkey_algo_t algo)
1741 {
1742   switch (algo)
1743     {
1744     case PUBKEY_ALGO_RSA:
1745     case PUBKEY_ALGO_RSA_E:
1746     case PUBKEY_ALGO_RSA_S:     return 1;
1747     case PUBKEY_ALGO_ELGAMAL_E: return 0;
1748     case PUBKEY_ALGO_DSA:       return 2;
1749     case PUBKEY_ALGO_ECDH:      return 0;
1750     case PUBKEY_ALGO_ECDSA:     return 2;
1751     case PUBKEY_ALGO_ELGAMAL:   return 2;
1752     case PUBKEY_ALGO_EDDSA:     return 2;
1753     default: return 0;
1754     }
1755 }
1756
1757
1758 /* Temporary helper. */
1759 int
1760 pubkey_get_nenc (pubkey_algo_t algo)
1761 {
1762   switch (algo)
1763     {
1764     case PUBKEY_ALGO_RSA:
1765     case PUBKEY_ALGO_RSA_E:
1766     case PUBKEY_ALGO_RSA_S:     return 1;
1767     case PUBKEY_ALGO_ELGAMAL_E: return 2;
1768     case PUBKEY_ALGO_DSA:       return 0;
1769     case PUBKEY_ALGO_ECDH:      return 2;
1770     case PUBKEY_ALGO_ECDSA:     return 0;
1771     case PUBKEY_ALGO_ELGAMAL:   return 2;
1772     case PUBKEY_ALGO_EDDSA:     return 0;
1773     default: return 0;
1774     }
1775 }
1776
1777
1778 /* Temporary helper. */
1779 unsigned int
1780 pubkey_nbits( int algo, gcry_mpi_t *key )
1781 {
1782   int rc, nbits;
1783   gcry_sexp_t sexp;
1784
1785   if (algo == PUBKEY_ALGO_DSA
1786       && key[0] && key[1] && key[2] && key[3])
1787     {
1788       rc = gcry_sexp_build (&sexp, NULL,
1789                             "(public-key(dsa(p%m)(q%m)(g%m)(y%m)))",
1790                             key[0], key[1], key[2], key[3] );
1791     }
1792   else if ((algo == PUBKEY_ALGO_ELGAMAL || algo == PUBKEY_ALGO_ELGAMAL_E)
1793            && key[0] && key[1] && key[2])
1794     {
1795       rc = gcry_sexp_build (&sexp, NULL,
1796                             "(public-key(elg(p%m)(g%m)(y%m)))",
1797                             key[0], key[1], key[2] );
1798     }
1799   else if (is_RSA (algo)
1800            && key[0] && key[1])
1801     {
1802       rc = gcry_sexp_build (&sexp, NULL,
1803                             "(public-key(rsa(n%m)(e%m)))",
1804                             key[0], key[1] );
1805     }
1806   else if ((algo == PUBKEY_ALGO_ECDSA || algo == PUBKEY_ALGO_ECDH
1807             || algo == PUBKEY_ALGO_EDDSA)
1808            && key[0] && key[1])
1809     {
1810       char *curve = openpgp_oid_to_str (key[0]);
1811       if (!curve)
1812         rc = gpg_error_from_syserror ();
1813       else
1814         {
1815           rc = gcry_sexp_build (&sexp, NULL,
1816                                 "(public-key(ecc(curve%s)(q%m)))",
1817                                 curve, key[1]);
1818           xfree (curve);
1819         }
1820     }
1821   else
1822     return 0;
1823
1824   if (rc)
1825     BUG ();
1826
1827   nbits = gcry_pk_get_nbits (sexp);
1828   gcry_sexp_release (sexp);
1829   return nbits;
1830 }
1831
1832
1833
1834 int
1835 mpi_print (estream_t fp, gcry_mpi_t a, int mode)
1836 {
1837   int n = 0;
1838   size_t nwritten;
1839
1840   if (!a)
1841     return es_fprintf (fp, "[MPI_NULL]");
1842   if (!mode)
1843     {
1844       unsigned int n1;
1845       n1 = gcry_mpi_get_nbits(a);
1846       n += es_fprintf (fp, "[%u bits]", n1);
1847     }
1848   else if (gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
1849     {
1850       unsigned int nbits;
1851       unsigned char *p = gcry_mpi_get_opaque (a, &nbits);
1852       if (!p)
1853         n += es_fprintf (fp, "[invalid opaque value]");
1854       else
1855         {
1856           if (!es_write_hexstring (fp, p, (nbits + 7)/8, 0, &nwritten))
1857             n += nwritten;
1858         }
1859     }
1860   else
1861     {
1862       unsigned char *buffer;
1863       size_t buflen;
1864
1865       if (gcry_mpi_aprint (GCRYMPI_FMT_USG, &buffer, &buflen, a))
1866         BUG ();
1867       if (!es_write_hexstring (fp, buffer, buflen, 0, &nwritten))
1868         n += nwritten;
1869       gcry_free (buffer);
1870     }
1871   return n;
1872 }
1873
1874
1875 /* pkey[1] or skey[1] is Q for ECDSA, which is an uncompressed point,
1876    i.e.  04 <x> <y> */
1877 unsigned int
1878 ecdsa_qbits_from_Q (unsigned int qbits)
1879 {
1880   if ((qbits%8) > 3)
1881     {
1882       log_error (_("ECDSA public key is expected to be in SEC encoding "
1883                    "multiple of 8 bits\n"));
1884       return 0;
1885     }
1886   qbits -= qbits%8;
1887   qbits /= 2;
1888   return qbits;
1889 }
1890
1891
1892 /* Ignore signatures and certifications made over certain digest
1893  * algorithms by default, MD5 is considered weak.  This allows users
1894  * to deprecate support for other algorithms as well.
1895  */
1896 void
1897 additional_weak_digest (const char* digestname)
1898 {
1899   struct weakhash *weak = NULL;
1900   const enum gcry_md_algos algo = string_to_digest_algo(digestname);
1901
1902   if (algo == GCRY_MD_NONE)
1903     {
1904       log_error (_("unknown weak digest '%s'\n"), digestname);
1905       return;
1906     }
1907
1908   /* Check to ensure it's not already present.  */
1909   for (weak = opt.weak_digests; weak; weak = weak->next)
1910     if (algo == weak->algo)
1911       return;
1912
1913   /* Add it to the head of the list.  */
1914   weak = xmalloc(sizeof(*weak));
1915   weak->algo = algo;
1916   weak->rejection_shown = 0;
1917   weak->next = opt.weak_digests;
1918   opt.weak_digests = weak;
1919 }
1920
1921
1922 /* Return true if ALGO is in the list of weak digests.  */
1923 int
1924 is_weak_digest (digest_algo_t algo)
1925 {
1926   const enum gcry_md_algos galgo = map_md_openpgp_to_gcry (algo);
1927   const struct weakhash *weak;
1928
1929   for (weak = opt.weak_digests; weak; weak = weak->next)
1930     if (weak->algo == galgo)
1931       return 1;
1932   return 0;
1933 }