Bump to 2.4.3
[platform/upstream/gpg2.git] / agent / genkey.c
1 /* genkey.c - Generate a keypair
2  * Copyright (C) 2002, 2003, 2004, 2007, 2010 Free Software Foundation, Inc.
3  * Copyright (C) 2015 g10 Code GmbH.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <ctype.h>
27
28 #include "agent.h"
29 #include "../common/i18n.h"
30 #include "../common/exechelp.h"
31 #include "../common/sysutils.h"
32
33 static int
34 store_key (gcry_sexp_t private, const char *passphrase, int force,
35            unsigned long s2k_count, time_t timestamp)
36 {
37   int rc;
38   unsigned char *buf;
39   size_t len;
40   unsigned char grip[20];
41
42   if ( !gcry_pk_get_keygrip (private, grip) )
43     {
44       log_error ("can't calculate keygrip\n");
45       return gpg_error (GPG_ERR_GENERAL);
46     }
47
48   len = gcry_sexp_sprint (private, GCRYSEXP_FMT_CANON, NULL, 0);
49   log_assert (len);
50   buf = gcry_malloc_secure (len);
51   if (!buf)
52       return out_of_core ();
53   len = gcry_sexp_sprint (private, GCRYSEXP_FMT_CANON, buf, len);
54   log_assert (len);
55
56   if (passphrase)
57     {
58       unsigned char *p;
59
60       rc = agent_protect (buf, passphrase, &p, &len, s2k_count);
61       if (rc)
62         {
63           xfree (buf);
64           return rc;
65         }
66       xfree (buf);
67       buf = p;
68     }
69
70   rc = agent_write_private_key (grip, buf, len, force,
71                                 NULL, NULL, NULL, timestamp);
72   xfree (buf);
73   return rc;
74 }
75
76
77 /* Count the number of non-alpha characters in S.  Control characters
78    and non-ascii characters are not considered.  */
79 static size_t
80 nonalpha_count (const char *s)
81 {
82   size_t n;
83
84   for (n=0; *s; s++)
85     if (isascii (*s) && ( isdigit (*s) || ispunct (*s) ))
86       n++;
87
88   return n;
89 }
90
91
92 /* Check PW against a list of pattern.  Return 0 if PW does not match
93    these pattern.  If CHECK_CONSTRAINTS_NEW_SYMKEY is set in flags and
94    --check-sym-passphrase-pattern has been configured, use the pattern
95    file from that option.  */
96 static int
97 do_check_passphrase_pattern (ctrl_t ctrl, const char *pw, unsigned int flags)
98 {
99   gpg_error_t err = 0;
100   const char *pgmname = gnupg_module_name (GNUPG_MODULE_NAME_CHECK_PATTERN);
101   estream_t stream_to_check_pattern = NULL;
102   const char *argv[10];
103   pid_t pid;
104   int result, i;
105   const char *pattern;
106   char *patternfname;
107
108   (void)ctrl;
109
110   pattern = opt.check_passphrase_pattern;
111   if ((flags & CHECK_CONSTRAINTS_NEW_SYMKEY)
112       && opt.check_sym_passphrase_pattern)
113     pattern = opt.check_sym_passphrase_pattern;
114   if (!pattern)
115     return 1; /* Oops - Assume password should not be used  */
116
117   if (strchr (pattern, '/') || strchr (pattern, '\\')
118       || (*pattern == '~' && pattern[1] == '/'))
119     patternfname = make_absfilename_try (pattern, NULL);
120   else
121     patternfname = make_filename_try (gnupg_sysconfdir (), pattern, NULL);
122   if (!patternfname)
123     {
124       log_error ("error making filename from '%s': %s\n",
125                  pattern, gpg_strerror (gpg_error_from_syserror ()));
126       return 1; /* Do not pass the check.  */
127     }
128
129   /* Make debugging a broken config easier by printing a useful error
130    * message.  */
131   if (gnupg_access (patternfname, F_OK))
132     {
133       log_error ("error accessing '%s': %s\n",
134                  patternfname, gpg_strerror (gpg_error_from_syserror ()));
135       xfree (patternfname);
136       return 1; /* Do not pass the check.  */
137     }
138
139   i = 0;
140   argv[i++] = "--null";
141   argv[i++] = "--",
142   argv[i++] = patternfname,
143   argv[i] = NULL;
144   log_assert (i < sizeof argv);
145
146   if (gnupg_spawn_process (pgmname, argv, NULL, 0,
147                            &stream_to_check_pattern, NULL, NULL, &pid))
148     result = 1; /* Execute error - assume password should no be used.  */
149   else
150     {
151       es_set_binary (stream_to_check_pattern);
152       if (es_fwrite (pw, strlen (pw), 1, stream_to_check_pattern) != 1)
153         {
154           err = gpg_error_from_syserror ();
155           log_error (_("error writing to pipe: %s\n"), gpg_strerror (err));
156           result = 1; /* Error - assume password should not be used.  */
157         }
158       else
159         es_fflush (stream_to_check_pattern);
160       es_fclose (stream_to_check_pattern);
161       if (gnupg_wait_process (pgmname, pid, 1, NULL))
162         result = 1; /* Helper returned an error - probably a match.  */
163       else
164         result = 0; /* Success; i.e. no match.  */
165       gnupg_release_process (pid);
166     }
167
168   xfree (patternfname);
169   return result;
170 }
171
172
173 static int
174 take_this_one_anyway (ctrl_t ctrl, const char *desc, const char *anyway_btn)
175 {
176   return agent_get_confirmation (ctrl, desc,
177                                  anyway_btn, L_("Enter new passphrase"), 0);
178 }
179
180
181 /* Check whether the passphrase PW is suitable. Returns 0 if the
182  * passphrase is suitable and true if it is not and the user should be
183  * asked to provide a different one.  If FAILED_CONSTRAINT is set, a
184  * message describing the problem is returned at FAILED_CONSTRAINT.
185  * The FLAGS are:
186  *   CHECK_CONSTRAINTS_NOT_EMPTY
187  *       Do not allow an empty passphrase
188  *   CHECK_CONSTRAINTS_NEW_SYMKEY
189  *       Hint that the passphrase is used for a new symmetric key.
190  */
191 int
192 check_passphrase_constraints (ctrl_t ctrl, const char *pw, unsigned int flags,
193                               char **failed_constraint)
194 {
195   gpg_error_t err = 0;
196   unsigned int minlen = opt.min_passphrase_len;
197   unsigned int minnonalpha = opt.min_passphrase_nonalpha;
198   char *msg1 = NULL;
199   char *msg2 = NULL;
200   char *msg3 = NULL;
201   int no_empty = !!(flags & CHECK_CONSTRAINTS_NOT_EMPTY);
202
203   if (ctrl && ctrl->pinentry_mode == PINENTRY_MODE_LOOPBACK)
204     return 0;
205
206   if (!pw)
207     pw = "";
208
209   /* The first check is to warn about an empty passphrase. */
210   if (!*pw)
211     {
212       const char *desc = (opt.enforce_passphrase_constraints || no_empty?
213                           L_("You have not entered a passphrase!%0A"
214                              "An empty passphrase is not allowed.") :
215                           L_("You have not entered a passphrase - "
216                              "this is in general a bad idea!%0A"
217                              "Please confirm that you do not want to "
218                              "have any protection on your key."));
219
220       err = 1;
221       if (failed_constraint)
222         {
223           if (opt.enforce_passphrase_constraints || no_empty)
224             *failed_constraint = xstrdup (desc);
225           else
226             err = take_this_one_anyway (ctrl, desc,
227                                         L_("Yes, protection is not needed"));
228         }
229
230       goto leave;
231     }
232
233   /* Now check the constraints and collect the error messages unless
234      in silent mode which returns immediately.  */
235   if (utf8_charcount (pw, -1) < minlen )
236     {
237       if (!failed_constraint)
238         {
239           err = gpg_error (GPG_ERR_INV_PASSPHRASE);
240           goto leave;
241         }
242
243       msg1 = xtryasprintf
244         ( ngettext ("A passphrase should be at least %u character long.",
245                     "A passphrase should be at least %u characters long.",
246                     minlen), minlen );
247       if (!msg1)
248         {
249           err = gpg_error_from_syserror ();
250           goto leave;
251         }
252     }
253
254   if (nonalpha_count (pw) < minnonalpha )
255     {
256       if (!failed_constraint)
257         {
258           err = gpg_error (GPG_ERR_INV_PASSPHRASE);
259           goto leave;
260         }
261
262       msg2 = xtryasprintf
263         ( ngettext ("A passphrase should contain at least %u digit or%%0A"
264                     "special character.",
265                     "A passphrase should contain at least %u digits or%%0A"
266                     "special characters.",
267                     minnonalpha), minnonalpha );
268       if (!msg2)
269         {
270           err = gpg_error_from_syserror ();
271           goto leave;
272         }
273     }
274
275   /* If configured check the passphrase against a list of known words
276      and pattern.  The actual test is done by an external program.
277      The warning message is generic to give the user no hint on how to
278      circumvent this list.  */
279   if (*pw
280       && (opt.check_passphrase_pattern || opt.check_sym_passphrase_pattern)
281       && do_check_passphrase_pattern (ctrl, pw, flags))
282     {
283       if (!failed_constraint)
284         {
285           err = gpg_error (GPG_ERR_INV_PASSPHRASE);
286           goto leave;
287         }
288
289       msg3 = xtryasprintf
290         (L_("A passphrase may not be a known term or match%%0A"
291             "certain pattern."));
292       if (!msg3)
293         {
294           err = gpg_error_from_syserror ();
295           goto leave;
296         }
297     }
298
299   if (failed_constraint && (msg1 || msg2 || msg3))
300     {
301       char *msg;
302       size_t n;
303
304       msg = strconcat
305         (L_("Warning: You have entered an insecure passphrase."),
306          "%0A%0A",
307          msg1? msg1 : "", msg1? "%0A" : "",
308          msg2? msg2 : "", msg2? "%0A" : "",
309          msg3? msg3 : "", msg3? "%0A" : "",
310          NULL);
311       if (!msg)
312         {
313           err = gpg_error_from_syserror ();
314           goto leave;
315         }
316       /* Strip a trailing "%0A".  */
317       n = strlen (msg);
318       if (n > 3 && !strcmp (msg + n - 3, "%0A"))
319         msg[n-3] = 0;
320
321       err = 1;
322       if (opt.enforce_passphrase_constraints)
323         *failed_constraint = msg;
324       else
325         {
326           err = take_this_one_anyway (ctrl, msg, L_("Take this one anyway"));
327           xfree (msg);
328         }
329     }
330
331  leave:
332   xfree (msg1);
333   xfree (msg2);
334   xfree (msg3);
335   return err;
336 }
337
338
339 /* Callback function to compare the first entered PIN with the one
340    currently being entered. */
341 static gpg_error_t
342 reenter_compare_cb (struct pin_entry_info_s *pi)
343 {
344   const char *pin1 = pi->check_cb_arg;
345
346   if (!strcmp (pin1, pi->pin))
347     return 0; /* okay */
348   return gpg_error (GPG_ERR_BAD_PASSPHRASE);
349 }
350
351
352 /* Ask the user for a new passphrase using PROMPT.  On success the
353    function returns 0 and store the passphrase at R_PASSPHRASE; if the
354    user opted not to use a passphrase NULL will be stored there.  The
355    user needs to free the returned string.  In case of an error and
356    error code is returned and NULL stored at R_PASSPHRASE.  */
357 gpg_error_t
358 agent_ask_new_passphrase (ctrl_t ctrl, const char *prompt,
359                           char **r_passphrase)
360 {
361   gpg_error_t err;
362   const char *text1 = prompt;
363   const char *text2 = L_("Please re-enter this passphrase");
364   char *initial_errtext = NULL;
365   struct pin_entry_info_s *pi, *pi2;
366
367   *r_passphrase = NULL;
368
369   if (ctrl->pinentry_mode == PINENTRY_MODE_LOOPBACK)
370     {
371         size_t size;
372         unsigned char *buffer;
373
374         err = pinentry_loopback (ctrl, "NEW_PASSPHRASE", &buffer, &size,
375                                  MAX_PASSPHRASE_LEN);
376         if (!err)
377           {
378             if (size)
379               {
380                 buffer[size] = 0;
381                 *r_passphrase = buffer;
382               }
383             else
384                 *r_passphrase = NULL;
385           }
386         return err;
387     }
388
389   pi = gcry_calloc_secure (1, sizeof (*pi) + MAX_PASSPHRASE_LEN + 1);
390   if (!pi)
391     return gpg_error_from_syserror ();
392   pi2 = gcry_calloc_secure (1, sizeof (*pi2) + MAX_PASSPHRASE_LEN + 1);
393   if (!pi2)
394     {
395       err = gpg_error_from_syserror ();
396       xfree (pi);
397       return err;
398     }
399   pi->max_length = MAX_PASSPHRASE_LEN + 1;
400   pi->max_tries = 3;
401   pi->with_qualitybar = 0;
402   pi->with_repeat = 1;
403   pi2->max_length = MAX_PASSPHRASE_LEN + 1;
404   pi2->max_tries = 3;
405   pi2->check_cb = reenter_compare_cb;
406   pi2->check_cb_arg = pi->pin;
407
408  next_try:
409   err = agent_askpin (ctrl, text1, NULL, initial_errtext, pi, NULL, 0);
410   xfree (initial_errtext);
411   initial_errtext = NULL;
412   if (!err)
413     {
414       if (check_passphrase_constraints (ctrl, pi->pin, 0, &initial_errtext))
415         {
416           pi->failed_tries = 0;
417           pi2->failed_tries = 0;
418           goto next_try;
419         }
420       /* Unless the passphrase is empty or the pinentry told us that
421          it already did the repetition check, ask to confirm it.  */
422       if (*pi->pin && !pi->repeat_okay)
423         {
424           err = agent_askpin (ctrl, text2, NULL, NULL, pi2, NULL, 0);
425           if (gpg_err_code (err) == GPG_ERR_BAD_PASSPHRASE)
426             { /* The re-entered one did not match and the user did not
427                  hit cancel. */
428               initial_errtext = xtrystrdup (L_("does not match - try again"));
429               if (initial_errtext)
430                 goto next_try;
431               err = gpg_error_from_syserror ();
432             }
433         }
434     }
435
436   if (!err && *pi->pin)
437     {
438       /* User wants a passphrase. */
439       *r_passphrase = xtrystrdup (pi->pin);
440       if (!*r_passphrase)
441         err = gpg_error_from_syserror ();
442     }
443
444   xfree (initial_errtext);
445   xfree (pi2);
446   xfree (pi);
447   return err;
448 }
449
450
451
452 /* Generate a new keypair according to the parameters given in
453    KEYPARAM.  If CACHE_NONCE is given first try to lookup a passphrase
454    using the cache nonce.  If NO_PROTECTION is true the key will not
455    be protected by a passphrase.  If OVERRIDE_PASSPHRASE is true that
456    passphrase will be used for the new key.  If TIMESTAMP is not zero
457    it will be recorded as creation date of the key (unless extended
458    format is disabled) . */
459 int
460 agent_genkey (ctrl_t ctrl, const char *cache_nonce, time_t timestamp,
461               const char *keyparam, size_t keyparamlen, int no_protection,
462               const char *override_passphrase, int preset, membuf_t *outbuf)
463 {
464   gcry_sexp_t s_keyparam, s_key, s_private, s_public;
465   char *passphrase_buffer = NULL;
466   const char *passphrase;
467   int rc;
468   size_t len;
469   char *buf;
470
471   rc = gcry_sexp_sscan (&s_keyparam, NULL, keyparam, keyparamlen);
472   if (rc)
473     {
474       log_error ("failed to convert keyparam: %s\n", gpg_strerror (rc));
475       return gpg_error (GPG_ERR_INV_DATA);
476     }
477
478   /* Get the passphrase now, cause key generation may take a while. */
479   if (override_passphrase)
480     passphrase = override_passphrase;
481   else if (no_protection || !cache_nonce)
482     passphrase = NULL;
483   else
484     {
485       passphrase_buffer = agent_get_cache (ctrl, cache_nonce, CACHE_MODE_NONCE);
486       passphrase = passphrase_buffer;
487     }
488
489   if (passphrase || no_protection)
490     ;
491   else
492     {
493       rc = agent_ask_new_passphrase (ctrl,
494                                      L_("Please enter the passphrase to%0A"
495                                         "protect your new key"),
496                                      &passphrase_buffer);
497       if (rc)
498         {
499           gcry_sexp_release (s_keyparam);
500           return rc;
501         }
502       passphrase = passphrase_buffer;
503     }
504
505   rc = gcry_pk_genkey (&s_key, s_keyparam );
506   gcry_sexp_release (s_keyparam);
507   if (rc)
508     {
509       log_error ("key generation failed: %s\n", gpg_strerror (rc));
510       xfree (passphrase_buffer);
511       return rc;
512     }
513
514   /* break out the parts */
515   s_private = gcry_sexp_find_token (s_key, "private-key", 0);
516   if (!s_private)
517     {
518       log_error ("key generation failed: invalid return value\n");
519       gcry_sexp_release (s_key);
520       xfree (passphrase_buffer);
521       return gpg_error (GPG_ERR_INV_DATA);
522     }
523   s_public = gcry_sexp_find_token (s_key, "public-key", 0);
524   if (!s_public)
525     {
526       log_error ("key generation failed: invalid return value\n");
527       gcry_sexp_release (s_private);
528       gcry_sexp_release (s_key);
529       xfree (passphrase_buffer);
530       return gpg_error (GPG_ERR_INV_DATA);
531     }
532   gcry_sexp_release (s_key); s_key = NULL;
533
534   /* store the secret key */
535   if (DBG_CRYPTO)
536     log_debug ("storing private key\n");
537   rc = store_key (s_private, passphrase, 0, ctrl->s2k_count, timestamp);
538   if (!rc)
539     {
540       if (!cache_nonce)
541         {
542           char tmpbuf[12];
543           gcry_create_nonce (tmpbuf, 12);
544           cache_nonce = bin2hex (tmpbuf, 12, NULL);
545         }
546       if (cache_nonce
547           && !no_protection
548           && !agent_put_cache (ctrl, cache_nonce, CACHE_MODE_NONCE,
549                                passphrase, ctrl->cache_ttl_opt_preset))
550         agent_write_status (ctrl, "CACHE_NONCE", cache_nonce, NULL);
551       if (preset && !no_protection)
552         {
553           unsigned char grip[20];
554           char hexgrip[40+1];
555           if (gcry_pk_get_keygrip (s_private, grip))
556             {
557               bin2hex(grip, 20, hexgrip);
558               rc = agent_put_cache (ctrl, hexgrip, CACHE_MODE_ANY, passphrase,
559                                     ctrl->cache_ttl_opt_preset);
560             }
561         }
562     }
563   xfree (passphrase_buffer);
564   passphrase_buffer = NULL;
565   passphrase = NULL;
566   gcry_sexp_release (s_private);
567   if (rc)
568     {
569       gcry_sexp_release (s_public);
570       return rc;
571     }
572
573   /* return the public key */
574   if (DBG_CRYPTO)
575     log_debug ("returning public key\n");
576   len = gcry_sexp_sprint (s_public, GCRYSEXP_FMT_CANON, NULL, 0);
577   log_assert (len);
578   buf = xtrymalloc (len);
579   if (!buf)
580     {
581       gpg_error_t tmperr = out_of_core ();
582       gcry_sexp_release (s_private);
583       gcry_sexp_release (s_public);
584       return tmperr;
585     }
586   len = gcry_sexp_sprint (s_public, GCRYSEXP_FMT_CANON, buf, len);
587   log_assert (len);
588   put_membuf (outbuf, buf, len);
589   gcry_sexp_release (s_public);
590   xfree (buf);
591
592   return 0;
593 }
594
595
596 \f
597 /* Apply a new passphrase to the key S_SKEY and store it.  If
598    PASSPHRASE_ADDR and *PASSPHRASE_ADDR are not NULL, use that
599    passphrase.  If PASSPHRASE_ADDR is not NULL store a newly entered
600    passphrase at that address. */
601 gpg_error_t
602 agent_protect_and_store (ctrl_t ctrl, gcry_sexp_t s_skey,
603                          char **passphrase_addr)
604 {
605   gpg_error_t err;
606
607   if (passphrase_addr && *passphrase_addr)
608     {
609       /* Take an empty string as request not to protect the key.  */
610       err = store_key (s_skey, **passphrase_addr? *passphrase_addr:NULL, 1,
611                        ctrl->s2k_count, 0);
612     }
613   else
614     {
615       char *pass = NULL;
616
617       if (passphrase_addr)
618         {
619           xfree (*passphrase_addr);
620           *passphrase_addr = NULL;
621         }
622       err = agent_ask_new_passphrase (ctrl,
623                                       L_("Please enter the new passphrase"),
624                                       &pass);
625       if (!err)
626         err = store_key (s_skey, pass, 1, ctrl->s2k_count, 0);
627       if (!err && passphrase_addr)
628         *passphrase_addr = pass;
629       else
630         xfree (pass);
631     }
632
633   return err;
634 }