1 /* misc.c -  miscellaneous functions
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
3  *               2008 Free Software Foundation, Inc.
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 <http://www.gnu.org/licenses/>.
19  */
20 
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #if defined(__linux__) && defined(__alpha__) && __GLIBC__ < 2
28 #include <asm/sysinfo.h>
29 #include <asm/unistd.h>
30 #endif
31 #ifdef HAVE_SETRLIMIT
32 #include <time.h>
33 #include <sys/time.h>
34 #include <sys/resource.h>
35 #endif
36 #ifdef ENABLE_SELINUX_HACKS
37 #include <sys/stat.h>
38 #endif
39 #ifdef _WIN32
40 #include <time.h>
41 #include <process.h>
42 #include <windows.h>
43 #include <shlobj.h>
44 #ifndef CSIDL_APPDATA
45 #define CSIDL_APPDATA 0x001a
46 #endif
47 #ifndef CSIDL_LOCAL_APPDATA
48 #define CSIDL_LOCAL_APPDATA 0x001c
49 #endif
50 #ifndef CSIDL_FLAG_CREATE
51 #define CSIDL_FLAG_CREATE 0x8000
52 #endif
53 #include "errors.h"
54 #include "dynload.h"
55 #endif /*_WIN32*/
56 
57 #ifdef __VMS
58 # include <time.h>
59 #endif /* def __VMS */
60 
61 #include "util.h"
62 #include "main.h"
63 #include "photoid.h"
64 #include "options.h"
65 #include "i18n.h"
66 #include "cardglue.h"
67 
68 
69 
70 
71 #ifdef ENABLE_SELINUX_HACKS
72 /* A object and a global variable to keep track of files marked as
73    secured. */
74 struct secured_file_item
75 {
76   struct secured_file_item *next;
77   ino_t ino;
78   dev_t dev;
79 };
80 static struct secured_file_item *secured_files;
81 #endif /*ENABLE_SELINUX_HACKS*/
82 
83 
84 
85 #if defined(__linux__) && defined(__alpha__) && __GLIBC__ < 2
86 static int
setsysinfo(unsigned long op,void * buffer,unsigned long size,int * start,void * arg,unsigned long flag)87 setsysinfo(unsigned long op, void *buffer, unsigned long size,
88 		     int *start, void *arg, unsigned long flag)
89 {
90     return syscall(__NR_osf_setsysinfo, op, buffer, size, start, arg, flag);
91 }
92 
93 void
trap_unaligned(void)94 trap_unaligned(void)
95 {
96     unsigned int buf[2];
97 
98     buf[0] = SSIN_UACPROC;
99     buf[1] = UAC_SIGBUS | UAC_NOPRINT;
100     setsysinfo(SSI_NVPAIRS, buf, 1, 0, 0, 0);
101 }
102 #else
103 void
trap_unaligned(void)104 trap_unaligned(void)
105 {  /* dummy */
106 }
107 #endif
108 
109 
110 int
disable_core_dumps()111 disable_core_dumps()
112 {
113 #if defined(HAVE_DOSISH_SYSTEM) || defined(__VMS)
114     return 0;
115 #else
116 #ifdef HAVE_SETRLIMIT
117     struct rlimit limit;
118 
119     limit.rlim_cur = 0;
120     limit.rlim_max = 0;
121     if( !setrlimit( RLIMIT_CORE, &limit ) )
122 	return 0;
123     if( errno != EINVAL && errno != ENOSYS )
124 	log_fatal(_("can't disable core dumps: %s\n"), strerror(errno) );
125 #endif
126     return 1;
127 #endif
128 }
129 
130 
131 /* For the sake of SELinux we want to restrict access through gpg to
132    certain files we keep under our own control.  This function
133    registers such a file and is_secured_file may then be used to
134    check whether a file has ben registered as secured. */
135 void
register_secured_file(const char * fname)136 register_secured_file (const char *fname)
137 {
138 #ifdef ENABLE_SELINUX_HACKS
139   struct stat buf;
140   struct secured_file_item *sf;
141 
142   /* Note that we stop immediatley if something goes wrong here. */
143   if (stat (fname, &buf))
144     log_fatal (_("fstat of `%s' failed in %s: %s\n"), fname,
145                "register_secured_file", strerror (errno));
146 /*   log_debug ("registering `%s' i=%lu.%lu\n", fname, */
147 /*              (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
148   for (sf=secured_files; sf; sf = sf->next)
149     {
150       if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
151         return; /* Already registered.  */
152     }
153 
154   sf = xmalloc (sizeof *sf);
155   sf->ino = buf.st_ino;
156   sf->dev = buf.st_dev;
157   sf->next = secured_files;
158   secured_files = sf;
159 #endif /*ENABLE_SELINUX_HACKS*/
160 }
161 
162 /* Remove a file registerd as secure. */
163 void
unregister_secured_file(const char * fname)164 unregister_secured_file (const char *fname)
165 {
166 #ifdef ENABLE_SELINUX_HACKS
167   struct stat buf;
168   struct secured_file_item *sf, *sfprev;
169 
170   if (stat (fname, &buf))
171     {
172       log_error (_("fstat of `%s' failed in %s: %s\n"), fname,
173                  "unregister_secured_file", strerror (errno));
174       return;
175     }
176 /*   log_debug ("unregistering `%s' i=%lu.%lu\n", fname,  */
177 /*              (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
178   for (sfprev=NULL,sf=secured_files; sf; sfprev=sf, sf = sf->next)
179     {
180       if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
181         {
182           if (sfprev)
183             sfprev->next = sf->next;
184           else
185             secured_files = sf->next;
186           xfree (sf);
187           return;
188         }
189     }
190 #endif /*ENABLE_SELINUX_HACKS*/
191 }
192 
193 /* Return true if FD is corresponds to a secured file.  Using -1 for
194    FS is allowed and will return false. */
195 int
is_secured_file(int fd)196 is_secured_file (int fd)
197 {
198 #ifdef ENABLE_SELINUX_HACKS
199   struct stat buf;
200   struct secured_file_item *sf;
201 
202   if (fd == -1)
203     return 0; /* No file descriptor so it can't be secured either.  */
204 
205   /* Note that we print out a error here and claim that a file is
206      secure if something went wrong. */
207   if (fstat (fd, &buf))
208     {
209       log_error (_("fstat(%d) failed in %s: %s\n"), fd,
210                  "is_secured_file", strerror (errno));
211       return 1;
212     }
213 /*   log_debug ("is_secured_file (%d) i=%lu.%lu\n", fd, */
214 /*              (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
215   for (sf=secured_files; sf; sf = sf->next)
216     {
217       if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
218         return 1; /* Yes.  */
219     }
220 #endif /*ENABLE_SELINUX_HACKS*/
221   return 0; /* No. */
222 }
223 
224 /* Return true if FNAME is corresponds to a secured file.  Using NULL,
225    "" or "-" for FS is allowed and will return false. This function is
226    used before creating a file, thus it won't fail if the file does
227    not exist. */
228 int
is_secured_filename(const char * fname)229 is_secured_filename (const char *fname)
230 {
231 #ifdef ENABLE_SELINUX_HACKS
232   struct stat buf;
233   struct secured_file_item *sf;
234 
235   if (iobuf_is_pipe_filename (fname) || !*fname)
236     return 0;
237 
238   /* Note that we print out a error here and claim that a file is
239      secure if something went wrong. */
240   if (stat (fname, &buf))
241     {
242       if (errno == ENOENT || errno == EPERM || errno == EACCES)
243         return 0;
244       log_error (_("fstat of `%s' failed in %s: %s\n"), fname,
245                  "is_secured_filename", strerror (errno));
246       return 1;
247     }
248 /*   log_debug ("is_secured_filename (%s) i=%lu.%lu\n", fname, */
249 /*              (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
250   for (sf=secured_files; sf; sf = sf->next)
251     {
252       if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
253         return 1; /* Yes.  */
254     }
255 #endif /*ENABLE_SELINUX_HACKS*/
256   return 0; /* No. */
257 }
258 
259 
260 
261 u16
checksum_u16(unsigned n)262 checksum_u16( unsigned n )
263 {
264     u16 a;
265 
266     a  = (n >> 8) & 0xff;
267     a += n & 0xff;
268     return a;
269 }
270 
271 
272 u16
checksum(byte * p,unsigned n)273 checksum( byte *p, unsigned n )
274 {
275     u16 a;
276 
277     for(a=0; n; n-- )
278 	a += *p++;
279     return a;
280 }
281 
282 u16
checksum_mpi(MPI a)283 checksum_mpi( MPI a )
284 {
285     u16 csum;
286     byte *buffer;
287     unsigned nbytes;
288     unsigned nbits;
289 
290     buffer = mpi_get_buffer( a, &nbytes, NULL );
291     nbits = mpi_get_nbits(a);
292     csum = checksum_u16( nbits );
293     csum += checksum( buffer, nbytes );
294     xfree( buffer );
295     return csum;
296 }
297 
298 void
print_pubkey_algo_note(int algo)299 print_pubkey_algo_note( int algo )
300 {
301   if(algo >= 100 && algo <= 110)
302     {
303       static int warn=0;
304       if(!warn)
305 	{
306 	  warn=1;
307 	  log_info(_("WARNING: using experimental public key algorithm %s\n"),
308 		   pubkey_algo_to_string(algo));
309 	}
310     }
311   else if (algo == 20)
312     {
313       log_info (_("WARNING: Elgamal sign+encrypt keys are deprecated\n"));
314     }
315 }
316 
317 void
print_cipher_algo_note(int algo)318 print_cipher_algo_note( int algo )
319 {
320   if(algo >= 100 && algo <= 110)
321     {
322       static int warn=0;
323       if(!warn)
324 	{
325 	  warn=1;
326 	  log_info(_("WARNING: using experimental cipher algorithm %s\n"),
327 		   cipher_algo_to_string(algo));
328 	}
329     }
330 }
331 
332 void
print_digest_algo_note(int algo)333 print_digest_algo_note( int algo )
334 {
335   const struct weakhash *weak;
336 
337   if(algo >= 100 && algo <= 110)
338     {
339       static int warn=0;
340       if(!warn)
341 	{
342 	  warn=1;
343 	  log_info(_("WARNING: using experimental digest algorithm %s\n"),
344 		   digest_algo_to_string(algo));
345 	}
346     }
347   else
348       for (weak = opt.weak_digests; weak; weak = weak->next)
349         if (weak->algo == algo)
350           log_info (_("WARNING: digest algorithm %s is deprecated\n"),
351                     digest_algo_to_string(algo));
352 }
353 
354 /* Return a string which is used as a kind of process ID */
355 const byte *
get_session_marker(size_t * rlen)356 get_session_marker( size_t *rlen )
357 {
358     static byte marker[SIZEOF_UNSIGNED_LONG*2];
359     static int initialized;
360 
361     if ( !initialized ) {
362         volatile ulong aa, bb; /* we really want the uninitialized value */
363         ulong a, b;
364 
365         initialized = 1;
366         /* also this marker is guessable it is not easy to use this
367          * for a faked control packet because an attacker does not
368          * have enough control about the time the verification does
369          * take place.  Of course, we can add just more random but
370          * than we need the random generator even for verification
371          * tasks - which does not make sense. */
372         a = aa ^ (ulong)getpid();
373         b = bb ^ (ulong)time(NULL);
374         memcpy( marker, &a, SIZEOF_UNSIGNED_LONG );
375         memcpy( marker+SIZEOF_UNSIGNED_LONG, &b, SIZEOF_UNSIGNED_LONG );
376     }
377     *rlen = sizeof(marker);
378     return marker;
379 }
380 
381 /****************
382  * Wrapper around the libgcrypt function with addional checks on
383  * openPGP contraints for the algo ID.
384  */
385 int
openpgp_cipher_test_algo(int algo)386 openpgp_cipher_test_algo( int algo )
387 {
388     if( algo < 0 || algo > 110 )
389         return G10ERR_CIPHER_ALGO;
390     return check_cipher_algo(algo);
391 }
392 
393 int
openpgp_pk_test_algo(int algo,unsigned int usage_flags)394 openpgp_pk_test_algo( int algo, unsigned int usage_flags )
395 {
396     /* Dont't allow type 20 keys unless in rfc2440 mode.  */
397     if (!RFC2440 && algo == 20)
398         return G10ERR_PUBKEY_ALGO;
399     if( algo < 0 || algo > 110 )
400 	return G10ERR_PUBKEY_ALGO;
401     return check_pubkey_algo2( algo, usage_flags );
402 }
403 
404 int
openpgp_pk_algo_usage(int algo)405 openpgp_pk_algo_usage ( int algo )
406 {
407     int use = 0;
408 
409     /* they are hardwired in gpg 1.0 */
410     switch ( algo ) {
411       case PUBKEY_ALGO_RSA:
412           use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG | PUBKEY_USAGE_ENC | PUBKEY_USAGE_AUTH;
413           break;
414       case PUBKEY_ALGO_RSA_E:
415           use = PUBKEY_USAGE_ENC;
416           break;
417       case PUBKEY_ALGO_RSA_S:
418           use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG;
419           break;
420       case PUBKEY_ALGO_ELGAMAL:
421           /* Allow encryption with type 20 keys if RFC-2440 compliance
422              has been selected.  Signing is broken thus we won't allow
423              this.  */
424           if (RFC2440)
425             use = PUBKEY_USAGE_ENC;
426           break;
427       case PUBKEY_ALGO_ELGAMAL_E:
428           use = PUBKEY_USAGE_ENC;
429           break;
430       case PUBKEY_ALGO_DSA:
431           use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG | PUBKEY_USAGE_AUTH;
432           break;
433       default:
434           break;
435     }
436     return use;
437 }
438 
439 int
openpgp_md_test_algo(int algo)440 openpgp_md_test_algo( int algo )
441 {
442     if( algo < 0 || algo > 110 )
443         return G10ERR_DIGEST_ALGO;
444     return check_digest_algo(algo);
445 }
446 
447 /* Print a warning if the md5 digest algorithm has been used.  This
448    warning is printed only once unless SHOW is used. */
449 void
md5_digest_warn(int show)450 md5_digest_warn (int show)
451 {
452   static int warned = 0;
453 
454   if (!warned || show)
455     {
456       log_info (_("WARNING: digest algorithm %s is deprecated\n"),
457                 digest_algo_to_string (DIGEST_ALGO_MD5));
458       log_info (_("please see %s for more information\n"),
459                 "https://gnupg.org/faq/weak-digest-algos.html");
460       warned = 1;
461     }
462 }
463 
464 
465 void
not_in_gpg1_notice(void)466 not_in_gpg1_notice (void)
467 {
468   static int warned = 0;
469 
470   if (!warned)
471     {
472       log_info (_("NOTE: This feature is not available in %s\n"), "GnuPG 1.x");
473       log_info (_("please see %s for more information\n"),
474                 "https://gnupg.org/faq/features-not-in-gnupg-1.html");
475       warned = 1;
476     }
477 }
478 
479 
480 static unsigned long
get_signature_count(PKT_secret_key * sk)481 get_signature_count(PKT_secret_key *sk)
482 {
483 #ifdef ENABLE_CARD_SUPPORT
484   if(sk && sk->is_protected && sk->protect.s2k.mode==1002)
485     {
486       struct agent_card_info_s info;
487       if(agent_scd_getattr("SIG-COUNTER",&info)==0)
488 	return info.sig_counter;
489     }
490 #endif
491 
492   /* How to do this without a card? */
493 
494   return 0;
495 }
496 
497 /* Expand %-strings.  Returns a string which must be xfreed.  Returns
498    NULL if the string cannot be expanded (too large). */
499 char *
pct_expando(const char * string,struct expando_args * args)500 pct_expando(const char *string,struct expando_args *args)
501 {
502   const char *ch=string;
503   int idx=0,maxlen=0,done=0;
504   u32 pk_keyid[2]={0,0},sk_keyid[2]={0,0};
505   char *ret=NULL;
506 
507   if(args->pk)
508     keyid_from_pk(args->pk,pk_keyid);
509 
510   if(args->sk)
511     keyid_from_sk(args->sk,sk_keyid);
512 
513   /* This is used so that %k works in photoid command strings in
514      --list-secret-keys (which of course has a sk, but no pk). */
515   if(!args->pk && args->sk)
516     keyid_from_sk(args->sk,pk_keyid);
517 
518   while(*ch!='\0')
519     {
520       if(!done)
521 	{
522 	  /* 8192 is way bigger than we'll need here */
523 	  if(maxlen>=8192)
524 	    goto fail;
525 
526 	  maxlen+=1024;
527 	  ret=xrealloc(ret,maxlen);
528 	}
529 
530       done=0;
531 
532       if(*ch=='%')
533 	{
534 	  switch(*(ch+1))
535 	    {
536 	    case 's': /* short key id */
537 	      if(idx+8<maxlen)
538 		{
539 		  sprintf(&ret[idx],"%08lX",(ulong)sk_keyid[1]);
540 		  idx+=8;
541 		  done=1;
542 		}
543 	      break;
544 
545 	    case 'S': /* long key id */
546 	      if(idx+16<maxlen)
547 		{
548 		  sprintf(&ret[idx],"%08lX%08lX",
549 			  (ulong)sk_keyid[0],(ulong)sk_keyid[1]);
550 		  idx+=16;
551 		  done=1;
552 		}
553 	      break;
554 
555 	    case 'k': /* short key id */
556 	      if(idx+8<maxlen)
557 		{
558 		  sprintf(&ret[idx],"%08lX",(ulong)pk_keyid[1]);
559 		  idx+=8;
560 		  done=1;
561 		}
562 	      break;
563 
564 	    case 'K': /* long key id */
565 	      if(idx+16<maxlen)
566 		{
567 		  sprintf(&ret[idx],"%08lX%08lX",
568 			  (ulong)pk_keyid[0],(ulong)pk_keyid[1]);
569 		  idx+=16;
570 		  done=1;
571 		}
572 	      break;
573 
574 	    case 'c': /* signature count from card, if any. */
575 	      if(idx+10<maxlen)
576 		{
577 		  sprintf(&ret[idx],"%lu",get_signature_count(args->sk));
578 		  idx+=strlen(&ret[idx]);
579 		  done=1;
580 		}
581 	      break;
582 
583 	    case 'p': /* primary pk fingerprint of a sk */
584 	    case 'f': /* pk fingerprint */
585 	    case 'g': /* sk fingerprint */
586 	      {
587 		byte array[MAX_FINGERPRINT_LEN];
588 		size_t len;
589 		int i;
590 
591 		if((*(ch+1))=='p' && args->sk)
592 		  {
593 		    if(args->sk->is_primary)
594 		      fingerprint_from_sk(args->sk,array,&len);
595 		    else if(args->sk->main_keyid[0] || args->sk->main_keyid[1])
596 		      {
597 			PKT_public_key *pk=
598 			  xmalloc_clear(sizeof(PKT_public_key));
599 
600 			if(get_pubkey_fast(pk,args->sk->main_keyid)==0)
601 			  fingerprint_from_pk(pk,array,&len);
602 			else
603 			  memset(array,0,(len=MAX_FINGERPRINT_LEN));
604 			free_public_key(pk);
605 		      }
606 		    else
607 		      memset(array,0,(len=MAX_FINGERPRINT_LEN));
608 		  }
609 		else if((*(ch+1))=='f' && args->pk)
610 		  fingerprint_from_pk(args->pk,array,&len);
611 		else if((*(ch+1))=='g' && args->sk)
612 		  fingerprint_from_sk(args->sk,array,&len);
613 		else
614 		  memset(array,0,(len=MAX_FINGERPRINT_LEN));
615 
616 		if(idx+(len*2)<maxlen)
617 		  {
618 		    for(i=0;i<len;i++)
619 		      {
620 			sprintf(&ret[idx],"%02X",array[i]);
621 			idx+=2;
622 		      }
623 		    done=1;
624 		  }
625 	      }
626 	      break;
627 
628 	    case 'v': /* validity letters */
629 	      if(args->validity_info && idx+1<maxlen)
630 		{
631 		  ret[idx++]=args->validity_info;
632 		  ret[idx]='\0';
633 		  done=1;
634 		}
635 	      break;
636 
637 	      /* The text string types */
638 	    case 't':
639 	    case 'T':
640 	    case 'V':
641 	      {
642 		const char *str=NULL;
643 
644 		switch(*(ch+1))
645 		  {
646 		  case 't': /* e.g. "jpg" */
647 		    str=image_type_to_string(args->imagetype,0);
648 		    break;
649 
650 		  case 'T': /* e.g. "image/jpeg" */
651 		    str=image_type_to_string(args->imagetype,2);
652 		    break;
653 
654 		  case 'V': /* e.g. "full", "expired", etc. */
655 		    str=args->validity_string;
656 		    break;
657 		  }
658 
659 		if(str && idx+strlen(str)<maxlen)
660 		  {
661 		    strcpy(&ret[idx],str);
662 		    idx+=strlen(str);
663 		    done=1;
664 		  }
665 	      }
666 	      break;
667 
668 	    case '%':
669 	      if(idx+1<maxlen)
670 		{
671 		  ret[idx++]='%';
672 		  ret[idx]='\0';
673 		  done=1;
674 		}
675 	      break;
676 
677 	      /* Any unknown %-keys (like %i, %o, %I, and %O) are
678 		 passed through for later expansion.  Note this also
679 		 handles the case where the last character in the
680 		 string is a '%' - the terminating \0 will end up here
681 		 and properly terminate the string. */
682 	    default:
683 	      if(idx+2<maxlen)
684 		{
685 		  ret[idx++]='%';
686 		  ret[idx++]=*(ch+1);
687 		  ret[idx]='\0';
688 		  done=1;
689 		}
690 	      break;
691 	      }
692 
693 	  if(done)
694 	    ch++;
695 	}
696       else
697 	{
698 	  if(idx+1<maxlen)
699 	    {
700 	      ret[idx++]=*ch;
701 	      ret[idx]='\0';
702 	      done=1;
703 	    }
704 	}
705 
706       if(done)
707 	ch++;
708     }
709 
710   return ret;
711 
712  fail:
713   xfree(ret);
714   return NULL;
715 }
716 
717 void
deprecated_warning(const char * configname,unsigned int configlineno,const char * option,const char * repl1,const char * repl2)718 deprecated_warning(const char *configname,unsigned int configlineno,
719 		   const char *option,const char *repl1,const char *repl2)
720 {
721   if(configname)
722     {
723       if(strncmp("--",option,2)==0)
724 	option+=2;
725 
726       if(strncmp("--",repl1,2)==0)
727 	repl1+=2;
728 
729       log_info(_("%s:%d: deprecated option \"%s\"\n"),
730 	       configname,configlineno,option);
731     }
732   else
733     log_info(_("WARNING: \"%s\" is a deprecated option\n"),option);
734 
735   log_info(_("please use \"%s%s\" instead\n"),repl1,repl2);
736 }
737 
738 
739 void
deprecated_command(const char * name)740 deprecated_command (const char *name)
741 {
742   log_info(_("WARNING: \"%s\" is a deprecated command - do not use it\n"),
743            name);
744 }
745 
746 
747 const char *
compress_algo_to_string(int algo)748 compress_algo_to_string(int algo)
749 {
750   const char *s=NULL;
751 
752   switch(algo)
753     {
754     case COMPRESS_ALGO_NONE:
755       s=_("Uncompressed");
756       break;
757 
758     case COMPRESS_ALGO_ZIP:
759       s="ZIP";
760       break;
761 
762     case COMPRESS_ALGO_ZLIB:
763       s="ZLIB";
764       break;
765 
766 #ifdef HAVE_BZIP2
767     case COMPRESS_ALGO_BZIP2:
768       s="BZIP2";
769       break;
770 #endif
771     }
772 
773   return s;
774 }
775 
776 int
string_to_compress_algo(const char * string)777 string_to_compress_algo(const char *string)
778 {
779   /* TRANSLATORS: See doc/TRANSLATE about this string. */
780   if(match_multistr(_("uncompressed|none"),string))
781     return 0;
782   else if(ascii_strcasecmp(string,"uncompressed")==0)
783     return 0;
784   else if(ascii_strcasecmp(string,"none")==0)
785     return 0;
786   else if(ascii_strcasecmp(string,"zip")==0)
787     return 1;
788   else if(ascii_strcasecmp(string,"zlib")==0)
789     return 2;
790 #ifdef HAVE_BZIP2
791   else if(ascii_strcasecmp(string,"bzip2")==0)
792     return 3;
793 #endif
794   else if(ascii_strcasecmp(string,"z0")==0)
795     return 0;
796   else if(ascii_strcasecmp(string,"z1")==0)
797     return 1;
798   else if(ascii_strcasecmp(string,"z2")==0)
799     return 2;
800 #ifdef HAVE_BZIP2
801   else if(ascii_strcasecmp(string,"z3")==0)
802     return 3;
803 #endif
804   else
805     return -1;
806 }
807 
808 int
check_compress_algo(int algo)809 check_compress_algo(int algo)
810 {
811 #ifdef HAVE_BZIP2
812   if(algo>=0 && algo<=3)
813     return 0;
814 #else
815   if(algo>=0 && algo<=2)
816     return 0;
817 #endif
818 
819   return G10ERR_COMPR_ALGO;
820 }
821 
822 int
default_cipher_algo(void)823 default_cipher_algo(void)
824 {
825   if(opt.def_cipher_algo)
826     return opt.def_cipher_algo;
827   else if(opt.personal_cipher_prefs)
828     return opt.personal_cipher_prefs[0].value;
829   else
830     return opt.s2k_cipher_algo;
831 }
832 
833 /* There is no default_digest_algo function, but see
834    sign.c:hash_for() */
835 
836 int
default_compress_algo(void)837 default_compress_algo(void)
838 {
839   if(opt.compress_algo!=-1)
840     return opt.compress_algo;
841   else if(opt.personal_compress_prefs)
842     return opt.personal_compress_prefs[0].value;
843   else
844     return DEFAULT_COMPRESS_ALGO;
845 }
846 
847 const char *
compliance_option_string(void)848 compliance_option_string(void)
849 {
850   char *ver="???";
851 
852   switch(opt.compliance)
853     {
854     case CO_GNUPG:   return "--gnupg";
855     case CO_RFC4880: return "--openpgp";
856     case CO_RFC2440: return "--rfc2440";
857     case CO_RFC1991: return "--rfc1991";
858     case CO_PGP2:    return "--pgp2";
859     case CO_PGP6:    return "--pgp6";
860     case CO_PGP7:    return "--pgp7";
861     case CO_PGP8:    return "--pgp8";
862     }
863 
864   return ver;
865 }
866 
867 void
compliance_failure(void)868 compliance_failure(void)
869 {
870   char *ver="???";
871 
872   switch(opt.compliance)
873     {
874     case CO_GNUPG:
875       ver="GnuPG";
876       break;
877 
878     case CO_RFC4880:
879       ver="OpenPGP";
880       break;
881 
882     case CO_RFC2440:
883       ver="OpenPGP (older)";
884       break;
885 
886     case CO_RFC1991:
887       ver="old PGP";
888       break;
889 
890     case CO_PGP2:
891       ver="PGP 2.x";
892       break;
893 
894     case CO_PGP6:
895       ver="PGP 6.x";
896       break;
897 
898     case CO_PGP7:
899       ver="PGP 7.x";
900       break;
901 
902     case CO_PGP8:
903       ver="PGP 8.x";
904       break;
905     }
906 
907   log_info(_("this message may not be usable by %s\n"),ver);
908   opt.compliance=CO_GNUPG;
909 }
910 
911 /* Break a string into successive option pieces.  Accepts single word
912    options and key=value argument options. */
913 char *
optsep(char ** stringp)914 optsep(char **stringp)
915 {
916   char *tok,*end;
917 
918   tok=*stringp;
919   if(tok)
920     {
921       end=strpbrk(tok," ,=");
922       if(end)
923 	{
924 	  int sawequals=0;
925 	  char *ptr=end;
926 
927 	  /* what we need to do now is scan along starting with *end,
928 	     If the next character we see (ignoring spaces) is an =
929 	     sign, then there is an argument. */
930 
931 	  while(*ptr)
932 	    {
933 	      if(*ptr=='=')
934 		sawequals=1;
935 	      else if(*ptr!=' ')
936 		break;
937 	      ptr++;
938 	    }
939 
940 	  /* There is an argument, so grab that too.  At this point,
941 	     ptr points to the first character of the argument. */
942 	  if(sawequals)
943 	    {
944 	      /* Is it a quoted argument? */
945 	      if(*ptr=='"')
946 		{
947 		  ptr++;
948 		  end=strchr(ptr,'"');
949 		  if(end)
950 		    end++;
951 		}
952 	      else
953 		end=strpbrk(ptr," ,");
954 	    }
955 
956 	  if(end && *end)
957 	    {
958 	      *end='\0';
959 	      *stringp=end+1;
960 	    }
961 	  else
962 	    *stringp=NULL;
963 	}
964       else
965 	*stringp=NULL;
966     }
967 
968   return tok;
969 }
970 
971 /* Breaks an option value into key and value.  Returns NULL if there
972    is no value.  Note that "string" is modified to remove the =value
973    part. */
974 char *
argsplit(char * string)975 argsplit(char *string)
976 {
977   char *equals,*arg=NULL;
978 
979   equals=strchr(string,'=');
980   if(equals)
981     {
982       char *quote,*space;
983 
984       *equals='\0';
985       arg=equals+1;
986 
987       /* Quoted arg? */
988       quote=strchr(arg,'"');
989       if(quote)
990 	{
991 	  arg=quote+1;
992 
993 	  quote=strchr(arg,'"');
994 	  if(quote)
995 	    *quote='\0';
996 	}
997       else
998 	{
999 	  size_t spaces;
1000 
1001 	  /* Trim leading spaces off of the arg */
1002 	  spaces=strspn(arg," ");
1003 	  arg+=spaces;
1004 	}
1005 
1006       /* Trim tailing spaces off of the tag */
1007       space=strchr(string,' ');
1008       if(space)
1009 	*space='\0';
1010     }
1011 
1012   return arg;
1013 }
1014 
1015 /* Return the length of the initial token, leaving off any
1016    argument. */
1017 static size_t
optlen(const char * s)1018 optlen(const char *s)
1019 {
1020   char *end=strpbrk(s," =");
1021 
1022   if(end)
1023     return end-s;
1024   else
1025     return strlen(s);
1026 }
1027 
1028 int
parse_options(char * str,unsigned int * options,struct parse_options * opts,int noisy)1029 parse_options(char *str,unsigned int *options,
1030 	      struct parse_options *opts,int noisy)
1031 {
1032   char *tok;
1033 
1034   if (str && !strcmp (str, "help"))
1035     {
1036       int i,maxlen=0;
1037 
1038       /* Figure out the longest option name so we can line these up
1039 	 neatly. */
1040       for(i=0;opts[i].name;i++)
1041 	if(opts[i].help && maxlen<strlen(opts[i].name))
1042 	  maxlen=strlen(opts[i].name);
1043 
1044       for(i=0;opts[i].name;i++)
1045         if(opts[i].help)
1046 	  printf("%s%*s%s\n",opts[i].name,
1047 		 maxlen+2-(int)strlen(opts[i].name),"",_(opts[i].help));
1048 
1049       g10_exit(0);
1050     }
1051 
1052   while((tok=optsep(&str)))
1053     {
1054       int i,rev=0;
1055       char *otok=tok;
1056 
1057       if(tok[0]=='\0')
1058 	continue;
1059 
1060       if(ascii_strncasecmp("no-",tok,3)==0)
1061 	{
1062 	  rev=1;
1063 	  tok+=3;
1064 	}
1065 
1066       for(i=0;opts[i].name;i++)
1067 	{
1068 	  size_t toklen=optlen(tok);
1069 
1070 	  if(ascii_strncasecmp(opts[i].name,tok,toklen)==0)
1071 	    {
1072 	      /* We have a match, but it might be incomplete */
1073 	      if(toklen!=strlen(opts[i].name))
1074 		{
1075 		  int j;
1076 
1077 		  for(j=i+1;opts[j].name;j++)
1078 		    {
1079 		      if(ascii_strncasecmp(opts[j].name,tok,toklen)==0)
1080 			{
1081 			  if(noisy)
1082 			    log_info(_("ambiguous option `%s'\n"),otok);
1083 			  return 0;
1084 			}
1085 		    }
1086 		}
1087 
1088 	      if(rev)
1089 		{
1090 		  *options&=~opts[i].bit;
1091 		  if(opts[i].value)
1092 		    *opts[i].value=NULL;
1093 		}
1094 	      else
1095 		{
1096 		  *options|=opts[i].bit;
1097 		  if(opts[i].value)
1098 		    *opts[i].value=argsplit(tok);
1099 		}
1100 	      break;
1101 	    }
1102 	}
1103 
1104       if(!opts[i].name)
1105 	{
1106 	  if(noisy)
1107 	    log_info(_("unknown option `%s'\n"),otok);
1108 	  return 0;
1109 	}
1110     }
1111 
1112   return 1;
1113 }
1114 
1115 
1116 /* Return a new malloced string by unescaping the string S.  Escaping
1117    is percent escaping and '+'/space mapping.  A binary nul will
1118    silently be replaced by a 0xFF. */
1119 char *
unescape_percent_string(const unsigned char * s)1120 unescape_percent_string (const unsigned char *s)
1121 {
1122   char *buffer, *d;
1123 
1124   buffer = d = xmalloc (strlen (s)+1);
1125   while (*s)
1126     {
1127       if (*s == '%' && s[1] && s[2])
1128         {
1129           s++;
1130           *d = xtoi_2 (s);
1131           if (!*d)
1132             *d = '\xff';
1133           d++;
1134           s += 2;
1135         }
1136       else if (*s == '+')
1137         {
1138           *d++ = ' ';
1139           s++;
1140         }
1141       else
1142         *d++ = *s++;
1143     }
1144   *d = 0;
1145   return buffer;
1146 }
1147 
1148 
1149 /* This is a helper function to load a Windows function from either of
1150    one DLLs. */
1151 #ifdef HAVE_W32_SYSTEM
1152 static HRESULT
w32_shgetfolderpath(HWND a,int b,HANDLE c,DWORD d,LPSTR e)1153 w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d, LPSTR e)
1154 {
1155   static int initialized;
1156   static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPSTR);
1157 
1158   if (!initialized)
1159     {
1160       static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL };
1161       void *handle;
1162       int i;
1163 
1164       initialized = 1;
1165 
1166       for (i=0, handle = NULL; !handle && dllnames[i]; i++)
1167         {
1168           handle = dlopen (dllnames[i], RTLD_LAZY);
1169           if (handle)
1170             {
1171               func = dlsym (handle, "SHGetFolderPathA");
1172               if (!func)
1173                 {
1174                   dlclose (handle);
1175                   handle = NULL;
1176                 }
1177             }
1178         }
1179     }
1180 
1181   if (func)
1182     return func (a,b,c,d,e);
1183   else
1184     return -1;
1185 }
1186 #endif /*HAVE_W32_SYSTEM*/
1187 
1188 
1189 /* Set up the default home directory.  The usual --homedir option
1190    should be parsed later. */
1191 char *
default_homedir(void)1192 default_homedir (void)
1193 {
1194   char *dir;
1195 
1196   dir = getenv("GNUPGHOME");
1197 #ifdef HAVE_W32_SYSTEM
1198   if (!dir || !*dir)
1199     dir = read_w32_registry_string (NULL, "Software\\GNU\\GnuPG", "HomeDir");
1200   if (!dir || !*dir)
1201     {
1202       char path[MAX_PATH];
1203 
1204       /* It might be better to use LOCAL_APPDATA because this is
1205          defined as "non roaming" and thus more likely to be kept
1206          locally.  For private keys this is desired.  However, given
1207          that many users copy private keys anyway forth and back,
1208          using a system roaming serives might be better than to let
1209          them do it manually.  A security conscious user will anyway
1210          use the registry entry to have better control.  */
1211       if (w32_shgetfolderpath (NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE,
1212                                NULL, 0, path) >= 0)
1213         {
1214           char *tmp = xmalloc (strlen (path) + 6 +1);
1215           strcpy (stpcpy (tmp, path), "\\gnupg");
1216           dir = tmp;
1217 
1218           /* Try to create the directory if it does not yet
1219              exists.  */
1220           if (access (dir, F_OK))
1221             CreateDirectory (dir, NULL);
1222         }
1223     }
1224 #endif /*HAVE_W32_SYSTEM*/
1225   if (!dir || !*dir)
1226     dir = GNUPG_HOMEDIR;
1227 
1228   return dir;
1229 }
1230 
1231 
1232 /* Return the name of the libexec directory.  The name is allocated in
1233    a static area on the first use.  This function won't fail. */
1234 const char *
get_libexecdir(void)1235 get_libexecdir (void)
1236 {
1237 #ifdef HAVE_W32_SYSTEM
1238   static int got_dir;
1239   static char dir[MAX_PATH+5];
1240 
1241   if (!got_dir)
1242     {
1243       char *p;
1244 
1245       if ( !GetModuleFileName ( NULL, dir, MAX_PATH) )
1246         {
1247           log_debug ("GetModuleFileName failed: %s\n", w32_strerror (0));
1248           *dir = 0;
1249         }
1250       got_dir = 1;
1251       p = strrchr (dir, DIRSEP_C);
1252       if (p)
1253         *p = 0;
1254       else
1255         {
1256           log_debug ("bad filename `%s' returned for this process\n", dir);
1257           *dir = 0;
1258         }
1259     }
1260 
1261   if (*dir)
1262     return dir;
1263   /* Fallback to the hardwired value. */
1264 #endif /*HAVE_W32_SYSTEM*/
1265 
1266   return GNUPG_LIBEXECDIR;
1267 }
1268 
1269 /* Similar to access(2), but uses PATH to find the file.
1270 
1271    (2006-07-08 SMS: See "vmslib/vms.c" for a VMS-specific replacement
1272    function) */
1273 #ifndef __VMS
1274 int
path_access(const char * file,int mode)1275 path_access(const char *file,int mode)
1276 {
1277   char *envpath;
1278   int ret=-1;
1279 
1280   envpath=getenv("PATH");
1281 
1282   if(!envpath
1283 #ifdef HAVE_DRIVE_LETTERS
1284      || (((file[0]>='A' && file[0]<='Z')
1285 	  || (file[0]>='a' && file[0]<='z'))
1286 	 && file[1]==':')
1287 #else
1288      || file[0]=='/'
1289 #endif
1290      )
1291     return access(file,mode);
1292   else
1293     {
1294       /* At least as large as, but most often larger than we need. */
1295       char *buffer=xmalloc(strlen(envpath)+1+strlen(file)+1);
1296       char *split,*item,*path=xstrdup(envpath);
1297 
1298       split=path;
1299 
1300       while((item=strsep(&split,PATHSEP_S)))
1301 	{
1302 	  strcpy(buffer,item);
1303 	  strcat(buffer,"/");
1304 	  strcat(buffer,file);
1305 	  ret=access(buffer,mode);
1306 	  if(ret==0)
1307 	    break;
1308 	}
1309 
1310       xfree(path);
1311       xfree(buffer);
1312     }
1313 
1314   return ret;
1315 }
1316 #endif /*ndef __VMS*/
1317 
1318 
1319 /* Ignore signatures and certifications made over certain digest
1320  * algorithms.  This allows users to deprecate support for algorithms
1321  * they are not willing to rely on.
1322  */
1323 void
additional_weak_digest(const char * digestname)1324 additional_weak_digest (const char* digestname)
1325 {
1326   struct weakhash *weak = NULL;
1327   const int algo = string_to_digest_algo(digestname);
1328 
1329   if (algo == 0)
1330     {
1331       log_error(_("Unknown weak digest '%s'\n"), digestname);
1332       return;
1333     }
1334 
1335   /* Check to ensure it's not already present.  */
1336   for (weak = opt.weak_digests; weak != NULL; weak = weak->next)
1337     if (algo == weak->algo)
1338       return;
1339 
1340   /* Add it to the head of the list.  */
1341   weak = xmalloc(sizeof(*weak));
1342   weak->algo = algo;
1343   weak->rejection_shown = 0;
1344   weak->next = opt.weak_digests;
1345   opt.weak_digests = weak;
1346 }
1347