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.
5 * This file is part of GnuPG.
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.
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.
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/>.
27 #if defined(__linux__) && defined(__alpha__) && __GLIBC__ < 2
28 #include <asm/sysinfo.h>
29 #include <asm/unistd.h>
34 #include <sys/resource.h>
36 #ifdef ENABLE_SELINUX_HACKS
40 #ifdef HAVE_W32_SYSTEM
46 #define CSIDL_APPDATA 0x001a
48 #ifndef CSIDL_LOCAL_APPDATA
49 #define CSIDL_LOCAL_APPDATA 0x001c
51 #ifndef CSIDL_FLAG_CREATE
52 #define CSIDL_FLAG_CREATE 0x8000
54 #endif /*HAVE_W32_SYSTEM*/
57 #ifdef HAVE_W32_SYSTEM
59 #endif /*HAVE_W32_SYSTEM*/
64 #include "call-agent.h"
70 string_count_chr (const char *string, int c)
74 for (count=0; *string; string++ )
82 #ifdef ENABLE_SELINUX_HACKS
83 /* A object and a global variable to keep track of files marked as
85 struct secured_file_item
87 struct secured_file_item *next;
91 static struct secured_file_item *secured_files;
92 #endif /*ENABLE_SELINUX_HACKS*/
97 /* For the sake of SELinux we want to restrict access through gpg to
98 certain files we keep under our own control. This function
99 registers such a file and is_secured_file may then be used to
100 check whether a file has ben registered as secured. */
102 register_secured_file (const char *fname)
104 #ifdef ENABLE_SELINUX_HACKS
106 struct secured_file_item *sf;
108 /* Note that we stop immediatley if something goes wrong here. */
109 if (stat (fname, &buf))
110 log_fatal (_("fstat of '%s' failed in %s: %s\n"), fname,
111 "register_secured_file", strerror (errno));
112 /* log_debug ("registering '%s' i=%lu.%lu\n", fname, */
113 /* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
114 for (sf=secured_files; sf; sf = sf->next)
116 if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
117 return; /* Already registered. */
120 sf = xmalloc (sizeof *sf);
121 sf->ino = buf.st_ino;
122 sf->dev = buf.st_dev;
123 sf->next = secured_files;
125 #else /*!ENABLE_SELINUX_HACKS*/
127 #endif /*!ENABLE_SELINUX_HACKS*/
130 /* Remove a file registered as secure. */
132 unregister_secured_file (const char *fname)
134 #ifdef ENABLE_SELINUX_HACKS
136 struct secured_file_item *sf, *sfprev;
138 if (stat (fname, &buf))
140 log_error (_("fstat of '%s' failed in %s: %s\n"), fname,
141 "unregister_secured_file", strerror (errno));
144 /* log_debug ("unregistering '%s' i=%lu.%lu\n", fname, */
145 /* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
146 for (sfprev=NULL,sf=secured_files; sf; sfprev=sf, sf = sf->next)
148 if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
151 sfprev->next = sf->next;
153 secured_files = sf->next;
158 #else /*!ENABLE_SELINUX_HACKS*/
160 #endif /*!ENABLE_SELINUX_HACKS*/
163 /* Return true if FD is corresponds to a secured file. Using -1 for
164 FS is allowed and will return false. */
166 is_secured_file (int fd)
168 #ifdef ENABLE_SELINUX_HACKS
170 struct secured_file_item *sf;
173 return 0; /* No file descriptor so it can't be secured either. */
175 /* Note that we print out a error here and claim that a file is
176 secure if something went wrong. */
177 if (fstat (fd, &buf))
179 log_error (_("fstat(%d) failed in %s: %s\n"), fd,
180 "is_secured_file", strerror (errno));
183 /* log_debug ("is_secured_file (%d) i=%lu.%lu\n", fd, */
184 /* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
185 for (sf=secured_files; sf; sf = sf->next)
187 if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
190 #else /*!ENABLE_SELINUX_HACKS*/
192 #endif /*!ENABLE_SELINUX_HACKS*/
196 /* Return true if FNAME is corresponds to a secured file. Using NULL,
197 "" or "-" for FS is allowed and will return false. This function is
198 used before creating a file, thus it won't fail if the file does
201 is_secured_filename (const char *fname)
203 #ifdef ENABLE_SELINUX_HACKS
205 struct secured_file_item *sf;
207 if (iobuf_is_pipe_filename (fname) || !*fname)
210 /* Note that we print out a error here and claim that a file is
211 secure if something went wrong. */
212 if (stat (fname, &buf))
214 if (errno == ENOENT || errno == EPERM || errno == EACCES)
216 log_error (_("fstat of '%s' failed in %s: %s\n"), fname,
217 "is_secured_filename", strerror (errno));
220 /* log_debug ("is_secured_filename (%s) i=%lu.%lu\n", fname, */
221 /* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
222 for (sf=secured_files; sf; sf = sf->next)
224 if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
227 #else /*!ENABLE_SELINUX_HACKS*/
229 #endif /*!ENABLE_SELINUX_HACKS*/
236 checksum_u16( unsigned n )
247 checksum( byte *p, unsigned n )
257 checksum_mpi (gcry_mpi_t a)
263 if ( gcry_mpi_print (GCRYMPI_FMT_PGP, NULL, 0, &nbytes, a) )
265 /* Fixme: For numbers not in secure memory we should use a stack
266 * based buffer and only allocate a larger one if mpi_print returns
268 buffer = (gcry_is_secure(a)?
269 gcry_xmalloc_secure (nbytes) : gcry_xmalloc (nbytes));
270 if ( gcry_mpi_print (GCRYMPI_FMT_PGP, buffer, nbytes, NULL, a) )
272 csum = checksum (buffer, nbytes);
278 buffer_to_u32( const byte *buffer )
282 a |= buffer[1] << 16;
289 print_pubkey_algo_note( int algo )
291 if(algo >= 100 && algo <= 110)
297 log_info (_("WARNING: using experimental public key algorithm %s\n"),
298 openpgp_cipher_algo_name (algo));
303 log_info (_("WARNING: Elgamal sign+encrypt keys are deprecated\n"));
308 print_cipher_algo_note( int algo )
310 if(algo >= 100 && algo <= 110)
316 log_info (_("WARNING: using experimental cipher algorithm %s\n"),
317 openpgp_cipher_algo_name (algo));
323 print_digest_algo_note( int algo )
325 if(algo >= 100 && algo <= 110)
331 log_info (_("WARNING: using experimental digest algorithm %s\n"),
332 gcry_md_algo_name (algo));
335 else if(algo==DIGEST_ALGO_MD5)
336 log_info (_("WARNING: digest algorithm %s is deprecated\n"),
337 gcry_md_algo_name (algo));
341 /* Map OpenPGP algo numbers to those used by Libgcrypt. We need to do
342 this for algorithms we implemented in Libgcrypt after they become
345 map_cipher_openpgp_to_gcry (int algo)
349 case CIPHER_ALGO_CAMELLIA128: return 310;
350 case CIPHER_ALGO_CAMELLIA192: return 311;
351 case CIPHER_ALGO_CAMELLIA256: return 312;
352 default: return algo;
356 /* The inverse fucntion of above. */
358 map_cipher_gcry_to_openpgp (int algo)
362 case 310: return CIPHER_ALGO_CAMELLIA128;
363 case 311: return CIPHER_ALGO_CAMELLIA192;
364 case 312: return CIPHER_ALGO_CAMELLIA256;
365 default: return algo;
369 /* Map OpenPGP public key algorithm numbers to those used by
372 map_pk_openpgp_to_gcry (int algo)
376 case PUBKEY_ALGO_ECDSA: return GCRY_PK_ECDSA;
377 case PUBKEY_ALGO_ECDH: return GCRY_PK_ECDH;
378 default: return algo;
382 /* Map Gcrypt public key algorithm numbers to those used by
385 map_pk_gcry_to_openpgp (enum gcry_pk_algos algo)
389 case GCRY_PK_ECDSA: return PUBKEY_ALGO_ECDSA;
390 case GCRY_PK_ECDH: return PUBKEY_ALGO_ECDH;
391 default: return algo < 110 ? algo : 0;
396 /* Return the block length of an OpenPGP cipher algorithm. */
398 openpgp_cipher_blocklen (int algo)
400 /* We use the numbers from OpenPGP to be sure that we get the right
401 block length. This is so that the packet parsing code works even
402 for unknown algorithms (for which we assume 8 due to tradition).
404 NOTE: If you change the the returned blocklen above 16, check
405 the callers because they may use a fixed size buffer of that
409 case 7: case 8: case 9: /* AES */
410 case 10: /* Twofish */
411 case 11: case 12: case 13: /* Camellia */
420 * Wrapper around the libgcrypt function with additonal checks on
421 * the OpenPGP contraints for the algo ID.
424 openpgp_cipher_test_algo( int algo )
426 /* (5 and 6 are marked reserved by rfc4880.) */
427 if ( algo < 0 || algo > 110 || algo == 5 || algo == 6 )
428 return gpg_error (GPG_ERR_CIPHER_ALGO);
430 return gcry_cipher_test_algo (map_cipher_openpgp_to_gcry (algo));
433 /* Map the OpenPGP cipher algorithm whose ID is contained in ALGORITHM to a
434 string representation of the algorithm name. For unknown algorithm
435 IDs this function returns "?". */
437 openpgp_cipher_algo_name (int algo)
439 return gnupg_cipher_algo_name (map_cipher_openpgp_to_gcry (algo));
443 openpgp_pk_test_algo( int algo )
445 /* Dont't allow type 20 keys unless in rfc2440 mode. */
446 if (!RFC2440 && algo == 20)
447 return gpg_error (GPG_ERR_PUBKEY_ALGO);
449 if (algo == GCRY_PK_ELG_E)
452 if (algo < 0 || algo > 110)
453 return gpg_error (GPG_ERR_PUBKEY_ALGO);
455 return gcry_pk_test_algo (map_pk_openpgp_to_gcry (algo));
459 openpgp_pk_test_algo2( int algo, unsigned int use )
461 size_t use_buf = use;
463 /* Dont't allow type 20 keys unless in rfc2440 mode. */
464 if (!RFC2440 && algo == 20)
465 return gpg_error (GPG_ERR_PUBKEY_ALGO);
467 if (algo == GCRY_PK_ELG_E)
470 if (algo < 0 || algo > 110)
471 return gpg_error (GPG_ERR_PUBKEY_ALGO);
473 return gcry_pk_algo_info (map_pk_openpgp_to_gcry (algo),
474 GCRYCTL_TEST_ALGO, NULL, &use_buf);
478 openpgp_pk_algo_usage ( int algo )
482 /* They are hardwired in gpg 1.0. */
484 case PUBKEY_ALGO_RSA:
485 use = (PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG
486 | PUBKEY_USAGE_ENC | PUBKEY_USAGE_AUTH);
488 case PUBKEY_ALGO_RSA_E:
489 case PUBKEY_ALGO_ECDH:
490 use = PUBKEY_USAGE_ENC;
492 case PUBKEY_ALGO_RSA_S:
493 use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG;
495 case PUBKEY_ALGO_ELGAMAL:
497 use = PUBKEY_USAGE_ENC;
499 case PUBKEY_ALGO_ELGAMAL_E:
500 use = PUBKEY_USAGE_ENC;
502 case PUBKEY_ALGO_DSA:
503 use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG | PUBKEY_USAGE_AUTH;
505 case PUBKEY_ALGO_ECDSA:
506 use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG | PUBKEY_USAGE_AUTH;
513 /* Map the OpenPGP pubkey algorithm whose ID is contained in ALGO to a
514 string representation of the algorithm name. For unknown algorithm
515 IDs this function returns "?". */
517 openpgp_pk_algo_name (int algo)
519 return gcry_pk_algo_name (map_pk_openpgp_to_gcry (algo));
524 openpgp_md_test_algo( int algo )
526 /* Note: If the list of actual supported OpenPGP algorithms changes,
527 make sure that our hard coded values at
528 print_status_begin_signing() gets updated. */
529 /* 4, 5, 6, 7 are defined by rfc2440 but will be removed from the
530 next revision of the standard. */
531 if (algo < 0 || algo > 110 || (algo >= 4 && algo <= 7))
532 return gpg_error (GPG_ERR_DIGEST_ALGO);
533 return gcry_md_test_algo (algo);
537 /* Map the OpenPGP digest algorithm whose ID is contained in ALGO to a
538 string representation of the algorithm name. For unknown algorithm
539 IDs this function returns "?". */
541 openpgp_md_algo_name (int algo)
543 if (algo < 0 || algo > 110)
545 return gcry_md_algo_name (algo);
550 get_signature_count (PKT_public_key *pk)
552 #ifdef ENABLE_CARD_SUPPORT
553 struct agent_card_info_s info;
556 if (!agent_scd_getattr ("SIG-COUNTER",&info))
557 return info.sig_counter;
566 /* Expand %-strings. Returns a string which must be xfreed. Returns
567 NULL if the string cannot be expanded (too large). */
569 pct_expando(const char *string,struct expando_args *args)
571 const char *ch=string;
572 int idx=0,maxlen=0,done=0;
573 u32 pk_keyid[2]={0,0},sk_keyid[2]={0,0};
577 keyid_from_pk(args->pk,pk_keyid);
580 keyid_from_pk (args->pksk, sk_keyid);
582 /* This is used so that %k works in photoid command strings in
583 --list-secret-keys (which of course has a sk, but no pk). */
584 if(!args->pk && args->pksk)
585 keyid_from_pk (args->pksk, pk_keyid);
591 /* 8192 is way bigger than we'll need here */
596 ret=xrealloc(ret,maxlen);
605 case 's': /* short key id */
608 sprintf(&ret[idx],"%08lX",(ulong)sk_keyid[1]);
614 case 'S': /* long key id */
617 sprintf(&ret[idx],"%08lX%08lX",
618 (ulong)sk_keyid[0],(ulong)sk_keyid[1]);
624 case 'k': /* short key id */
627 sprintf(&ret[idx],"%08lX",(ulong)pk_keyid[1]);
633 case 'K': /* long key id */
636 sprintf(&ret[idx],"%08lX%08lX",
637 (ulong)pk_keyid[0],(ulong)pk_keyid[1]);
643 case 'c': /* signature count from card, if any. */
646 sprintf (&ret[idx],"%lu", get_signature_count (args->pksk));
647 idx+=strlen(&ret[idx]);
652 case 'p': /* primary pk fingerprint of a sk */
653 case 'f': /* pk fingerprint */
654 case 'g': /* sk fingerprint */
656 byte array[MAX_FINGERPRINT_LEN];
660 if((*(ch+1))=='p' && args->pksk)
662 if(args->pksk->flags.primary)
663 fingerprint_from_pk (args->pksk, array, &len);
664 else if (args->pksk->main_keyid[0]
665 || args->pksk->main_keyid[1])
667 /* FIXME: Document teh code and check whether
668 it is still needed. */
670 xmalloc_clear(sizeof(PKT_public_key));
672 if (!get_pubkey_fast (pk,args->pksk->main_keyid))
673 fingerprint_from_pk (pk, array, &len);
675 memset (array, 0, (len=MAX_FINGERPRINT_LEN));
676 free_public_key (pk);
679 memset(array,0,(len=MAX_FINGERPRINT_LEN));
681 else if((*(ch+1))=='f' && args->pk)
682 fingerprint_from_pk (args->pk, array, &len);
683 else if((*(ch+1))=='g' && args->pksk)
684 fingerprint_from_pk (args->pksk, array, &len);
686 memset(array,0,(len=MAX_FINGERPRINT_LEN));
688 if(idx+(len*2)<maxlen)
692 sprintf(&ret[idx],"%02X",array[i]);
700 case 'v': /* validity letters */
701 if(args->validity_info && idx+1<maxlen)
703 ret[idx++]=args->validity_info;
709 /* The text string types */
714 const char *str=NULL;
718 case 't': /* e.g. "jpg" */
719 str=image_type_to_string(args->imagetype,0);
722 case 'T': /* e.g. "image/jpeg" */
723 str=image_type_to_string(args->imagetype,2);
726 case 'V': /* e.g. "full", "expired", etc. */
727 str=args->validity_string;
731 if(str && idx+strlen(str)<maxlen)
733 strcpy(&ret[idx],str);
749 /* Any unknown %-keys (like %i, %o, %I, and %O) are
750 passed through for later expansion. Note this also
751 handles the case where the last character in the
752 string is a '%' - the terminating \0 will end up here
753 and properly terminate the string. */
790 deprecated_warning(const char *configname,unsigned int configlineno,
791 const char *option,const char *repl1,const char *repl2)
795 if(strncmp("--",option,2)==0)
798 if(strncmp("--",repl1,2)==0)
801 log_info(_("%s:%d: deprecated option \"%s\"\n"),
802 configname,configlineno,option);
805 log_info(_("WARNING: \"%s\" is a deprecated option\n"),option);
807 log_info(_("please use \"%s%s\" instead\n"),repl1,repl2);
812 deprecated_command (const char *name)
814 log_info(_("WARNING: \"%s\" is a deprecated command - do not use it\n"),
820 obsolete_option (const char *configname, unsigned int configlineno,
824 log_info (_("%s:%u: obsolete option \"%s\" - it has no effect\n"),
825 configname, configlineno, name);
827 log_info (_("WARNING: \"%s\" is an obsolete option - it has no effect\n"),
833 * Wrapper around gcry_cipher_map_name to provide a fallback using the
834 * "Sn" syntax as used by the preference strings.
837 string_to_cipher_algo (const char *string)
841 val = map_cipher_gcry_to_openpgp (gcry_cipher_map_name (string));
842 if (!val && string && (string[0]=='S' || string[0]=='s'))
847 val = strtol (string, &endptr, 10);
848 if (!*string || *endptr || openpgp_cipher_test_algo (val))
856 * Wrapper around gcry_md_map_name to provide a fallback using the
857 * "Hn" syntax as used by the preference strings.
860 string_to_digest_algo (const char *string)
864 val = gcry_md_map_name (string);
865 if (!val && string && (string[0]=='H' || string[0]=='h'))
870 val = strtol (string, &endptr, 10);
871 if (!*string || *endptr || openpgp_md_test_algo (val))
881 compress_algo_to_string(int algo)
887 case COMPRESS_ALGO_NONE:
891 case COMPRESS_ALGO_ZIP:
895 case COMPRESS_ALGO_ZLIB:
900 case COMPRESS_ALGO_BZIP2:
910 string_to_compress_algo(const char *string)
912 /* TRANSLATORS: See doc/TRANSLATE about this string. */
913 if(match_multistr(_("uncompressed|none"),string))
915 else if(ascii_strcasecmp(string,"uncompressed")==0)
917 else if(ascii_strcasecmp(string,"none")==0)
919 else if(ascii_strcasecmp(string,"zip")==0)
921 else if(ascii_strcasecmp(string,"zlib")==0)
924 else if(ascii_strcasecmp(string,"bzip2")==0)
927 else if(ascii_strcasecmp(string,"z0")==0)
929 else if(ascii_strcasecmp(string,"z1")==0)
931 else if(ascii_strcasecmp(string,"z2")==0)
934 else if(ascii_strcasecmp(string,"z3")==0)
942 check_compress_algo(int algo)
954 default: return G10ERR_COMPR_ALGO;
959 default_cipher_algo(void)
961 if(opt.def_cipher_algo)
962 return opt.def_cipher_algo;
963 else if(opt.personal_cipher_prefs)
964 return opt.personal_cipher_prefs[0].value;
966 return opt.s2k_cipher_algo;
969 /* There is no default_digest_algo function, but see
973 default_compress_algo(void)
975 if(opt.compress_algo!=-1)
976 return opt.compress_algo;
977 else if(opt.personal_compress_prefs)
978 return opt.personal_compress_prefs[0].value;
980 return DEFAULT_COMPRESS_ALGO;
984 compliance_option_string(void)
988 switch(opt.compliance)
990 case CO_GNUPG: return "--gnupg";
991 case CO_RFC4880: return "--openpgp";
992 case CO_RFC2440: return "--rfc2440";
993 case CO_RFC1991: return "--rfc1991";
994 case CO_PGP2: return "--pgp2";
995 case CO_PGP6: return "--pgp6";
996 case CO_PGP7: return "--pgp7";
997 case CO_PGP8: return "--pgp8";
1004 compliance_failure(void)
1008 switch(opt.compliance)
1019 ver="OpenPGP (older)";
1043 log_info(_("this message may not be usable by %s\n"),ver);
1044 opt.compliance=CO_GNUPG;
1047 /* Break a string into successive option pieces. Accepts single word
1048 options and key=value argument options. */
1050 optsep(char **stringp)
1057 end=strpbrk(tok," ,=");
1063 /* what we need to do now is scan along starting with *end,
1064 If the next character we see (ignoring spaces) is an =
1065 sign, then there is an argument. */
1076 /* There is an argument, so grab that too. At this point,
1077 ptr points to the first character of the argument. */
1080 /* Is it a quoted argument? */
1084 end=strchr(ptr,'"');
1089 end=strpbrk(ptr," ,");
1107 /* Breaks an option value into key and value. Returns NULL if there
1108 is no value. Note that "string" is modified to remove the =value
1111 argsplit(char *string)
1113 char *equals,*arg=NULL;
1115 equals=strchr(string,'=');
1124 quote=strchr(arg,'"');
1129 quote=strchr(arg,'"');
1137 /* Trim leading spaces off of the arg */
1138 spaces=strspn(arg," ");
1142 /* Trim tailing spaces off of the tag */
1143 space=strchr(string,' ');
1151 /* Return the length of the initial token, leaving off any
1154 optlen(const char *s)
1156 char *end=strpbrk(s," =");
1165 parse_options(char *str,unsigned int *options,
1166 struct parse_options *opts,int noisy)
1170 if (str && !strcmp (str, "help"))
1174 /* Figure out the longest option name so we can line these up
1176 for(i=0;opts[i].name;i++)
1177 if(opts[i].help && maxlen<strlen(opts[i].name))
1178 maxlen=strlen(opts[i].name);
1180 for(i=0;opts[i].name;i++)
1182 printf("%s%*s%s\n",opts[i].name,
1183 maxlen+2-(int)strlen(opts[i].name),"",_(opts[i].help));
1188 while((tok=optsep(&str)))
1196 if(ascii_strncasecmp("no-",tok,3)==0)
1202 for(i=0;opts[i].name;i++)
1204 size_t toklen=optlen(tok);
1206 if(ascii_strncasecmp(opts[i].name,tok,toklen)==0)
1208 /* We have a match, but it might be incomplete */
1209 if(toklen!=strlen(opts[i].name))
1213 for(j=i+1;opts[j].name;j++)
1215 if(ascii_strncasecmp(opts[j].name,tok,toklen)==0)
1218 log_info(_("ambiguous option '%s'\n"),otok);
1226 *options&=~opts[i].bit;
1228 *opts[i].value=NULL;
1232 *options|=opts[i].bit;
1234 *opts[i].value=argsplit(tok);
1243 log_info(_("unknown option '%s'\n"),otok);
1252 /* Check whether the string has characters not valid in an RFC-822
1253 address. To cope with OpenPGP we ignore non-ascii characters
1254 so that for example umlauts are legal in an email address. An
1255 OpenPGP user ID must be utf-8 encoded but there is no strict
1256 requirement for RFC-822. Thus to avoid IDNA encoding we put the
1257 address verbatim as utf-8 into the user ID under the assumption
1258 that mail programs handle IDNA at a lower level and take OpenPGP
1259 user IDs as utf-8. Note that we can't do an utf-8 encoding
1260 checking here because in keygen.c this function is called with the
1261 native encoding and native to utf-8 encoding is only done later. */
1263 has_invalid_email_chars (const char *s)
1266 const char *valid_chars=
1267 "01234567890_-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1272 continue; /* We only care about ASCII. */
1275 else if ( !at_seen && !(strchr (valid_chars, *s)
1276 || strchr ("!#$%&'*+/=?^`{|}~", *s)))
1278 else if ( at_seen && !strchr( valid_chars, *s ) )
1285 /* Check whether NAME represents a valid mailbox according to
1286 RFC822. Returns true if so. */
1288 is_valid_mailbox (const char *name)
1292 || has_invalid_email_chars (name)
1293 || string_count_chr (name,'@') != 1
1295 || name[strlen(name)-1] == '@'
1296 || name[strlen(name)-1] == '.'
1297 || strstr (name, "..") );
1301 /* Similar to access(2), but uses PATH to find the file. */
1303 path_access(const char *file,int mode)
1308 envpath=getenv("PATH");
1311 #ifdef HAVE_DRIVE_LETTERS
1312 || (((file[0]>='A' && file[0]<='Z')
1313 || (file[0]>='a' && file[0]<='z'))
1319 return access(file,mode);
1322 /* At least as large as, but most often larger than we need. */
1323 char *buffer=xmalloc(strlen(envpath)+1+strlen(file)+1);
1324 char *split,*item,*path=xstrdup(envpath);
1328 while((item=strsep(&split,PATHSEP_S)))
1330 strcpy(buffer,item);
1332 strcat(buffer,file);
1333 ret=access(buffer,mode);
1347 /* Return the number of public key parameters as used by OpenPGP. */
1349 pubkey_get_npkey (int algo)
1353 /* ECC is special. */
1354 if (algo == PUBKEY_ALGO_ECDSA)
1356 else if (algo == PUBKEY_ALGO_ECDH)
1359 /* All other algorithms match those of Libgcrypt. */
1360 if (algo == GCRY_PK_ELG_E)
1362 else if (is_RSA (algo))
1365 if (gcry_pk_algo_info (algo, GCRYCTL_GET_ALGO_NPKEY, NULL, &n))
1371 /* Return the number of secret key parameters as used by OpenPGP. */
1373 pubkey_get_nskey (int algo)
1377 /* ECC is special. */
1378 if (algo == PUBKEY_ALGO_ECDSA)
1380 else if (algo == PUBKEY_ALGO_ECDH)
1383 /* All other algorithms match those of Libgcrypt. */
1384 if (algo == GCRY_PK_ELG_E)
1386 else if (is_RSA (algo))
1389 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NSKEY, NULL, &n ))
1394 /* Temporary helper. */
1396 pubkey_get_nsig (int algo)
1400 /* ECC is special. */
1401 if (algo == PUBKEY_ALGO_ECDSA)
1403 else if (algo == PUBKEY_ALGO_ECDH)
1406 if (algo == GCRY_PK_ELG_E)
1408 else if (is_RSA (algo))
1411 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NSIGN, NULL, &n))
1417 /* Temporary helper. */
1419 pubkey_get_nenc (int algo)
1423 /* ECC is special. */
1424 if (algo == PUBKEY_ALGO_ECDSA)
1426 else if (algo == PUBKEY_ALGO_ECDH)
1429 if (algo == GCRY_PK_ELG_E)
1431 else if (is_RSA (algo))
1434 if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NENCR, NULL, &n ))
1440 /* Temporary helper. */
1442 pubkey_nbits( int algo, gcry_mpi_t *key )
1447 if( algo == PUBKEY_ALGO_DSA ) {
1448 rc = gcry_sexp_build ( &sexp, NULL,
1449 "(public-key(dsa(p%m)(q%m)(g%m)(y%m)))",
1450 key[0], key[1], key[2], key[3] );
1452 else if( algo == PUBKEY_ALGO_ELGAMAL || algo == PUBKEY_ALGO_ELGAMAL_E ) {
1453 rc = gcry_sexp_build ( &sexp, NULL,
1454 "(public-key(elg(p%m)(g%m)(y%m)))",
1455 key[0], key[1], key[2] );
1457 else if( is_RSA (algo) ) {
1458 rc = gcry_sexp_build ( &sexp, NULL,
1459 "(public-key(rsa(n%m)(e%m)))",
1462 else if( algo == PUBKEY_ALGO_ECDSA || algo == PUBKEY_ALGO_ECDH ) {
1463 char *curve = openpgp_oid_to_str (key[0]);
1465 rc = gpg_error_from_syserror ();
1468 rc = gcry_sexp_build (&sexp, NULL,
1469 "(public-key(ecc(curve%s)(q%m)))",
1480 nbits = gcry_pk_get_nbits( sexp );
1481 gcry_sexp_release( sexp );
1488 mpi_print (estream_t fp, gcry_mpi_t a, int mode)
1493 return es_fprintf (fp, "[MPI_NULL]");
1497 n1 = gcry_mpi_get_nbits(a);
1498 n += es_fprintf (fp, "[%u bits]", n1);
1500 else if (gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
1503 unsigned char *p = gcry_mpi_get_opaque (a, &nbits);
1505 n += es_fprintf (fp, "[invalid opaque value]");
1508 nbits = (nbits + 7)/8;
1509 for (; nbits; nbits--, p++)
1510 n += es_fprintf (fp, "%02X", *p);
1515 unsigned char *buffer;
1517 if (gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buffer, NULL, a))
1519 es_fputs (buffer, fp);
1520 n += strlen (buffer);
1527 /* pkey[1] or skey[1] is Q for ECDSA, which is an uncompressed point,
1530 ecdsa_qbits_from_Q (unsigned int qbits)
1534 log_error (_("ECDSA public key is expected to be in SEC encoding "
1535 "multiple of 8 bits\n"));