summaryrefslogtreecommitdiff
path: root/tests/run-genkey.c
blob: fd9b42a7d92b76ea590db1a2ee140717b9b31ac9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
/* run-genkey.c  - Test tool to perform key generation
 * Copyright (C) 2016 g10 Code GmbH
 *
 * This file is part of GPGME.
 *
 * GPGME is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * GPGME is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, see <https://gnu.org/licenses/>.
 * SPDX-License-Identifier: LGPL-2.1-or-later
 */

/* We need to include config.h so that we know whether we are building
   with large file system (LFS) support. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>

#include <gpgme.h>

#define PGM "run-genkey"

#include "run-support.h"


static int verbose;


/* Tokenize STRING using the set of delimiters in DELIM.  Leading
 * spaces and tabs are removed from all tokens.  The caller must free
 * the result.
 *
 * Returns: A malloced and NULL delimited array with the tokens.  On
 *          memory error NULL is returned and ERRNO is set.
 */
static char **
strtokenize (const char *string, const char *delim)
{
  const char *s;
  size_t fields;
  size_t bytes, n;
  char *buffer;
  char *p, *px, *pend;
  char **result;

  /* Count the number of fields.  */
  for (fields = 1, s = strpbrk (string, delim); s; s = strpbrk (s + 1, delim))
    fields++;
  fields++; /* Add one for the terminating NULL.  */

  /* Allocate an array for all fields, a terminating NULL, and space
     for a copy of the string.  */
  bytes = fields * sizeof *result;
  if (bytes / sizeof *result != fields)
    {
      gpg_err_set_errno (ENOMEM);
      return NULL;
    }
  n = strlen (string) + 1;
  bytes += n;
  if (bytes < n)
    {
      gpg_err_set_errno (ENOMEM);
      return NULL;
    }
  result = malloc (bytes);
  if (!result)
    return NULL;
  buffer = (char*)(result + fields);

  /* Copy and parse the string.  */
  strcpy (buffer, string);
  for (n = 0, p = buffer; (pend = strpbrk (p, delim)); p = pend + 1)
    {
      *pend = 0;
      while (*p == ' ' || *p == '\t')
        p++;
      for (px = pend - 1; px >= p && (*px == ' ' || *px == '\t'); px--)
        *px = 0;
      result[n++] = p;
    }
  while (*p == ' ' || *p == '\t')
    p++;
  for (px = p + strlen (p) - 1; px >= p && (*px == ' ' || *px == '\t'); px--)
    *px = 0;
  result[n++] = p;
  result[n] = NULL;

  assert ((char*)(result + n + 1) == buffer);

  return result;
}


static gpg_error_t
status_cb (void *opaque, const char *keyword, const char *value)
{
  (void)opaque;
  fprintf (stderr, "status_cb: %s %s\n", nonnull(keyword), nonnull(value));
  return 0;
}


static void
progress_cb (void *opaque, const char *what, int type, int current, int total)
{
  (void)opaque;
  (void)type;

  if (total)
    fprintf (stderr, "progress for '%s' %u%% (%d of %d)\n",
             nonnull (what),
             (unsigned)(((double)current / total) * 100), current, total);
  else
    fprintf (stderr, "progress for '%s' %d\n", nonnull(what), current);
  fflush (stderr);
}


static unsigned long
parse_expire_string (const char *string)
{
  unsigned long seconds;

  if (!string || !*string || !strcmp (string, "none")
      || !strcmp (string, "never") || !strcmp (string, "-"))
    seconds = 0;
  else if (strspn (string, "01234567890") == strlen (string))
    seconds = strtoul (string, NULL, 10);
  else
    {
      fprintf (stderr, PGM ": invalid value '%s'\n", string);
      exit (1);
    }

  return seconds;
}


/* Parse a usage string and return flags for gpgme_op_createkey.  */
static unsigned int
parse_usage_string (const char *string)
{
  gpg_error_t err;
  char **tokens = NULL;
  const char *s;
  int i;
  unsigned int flags = 0;

  tokens = strtokenize (string, " \t,");
  if (!tokens)
    {
      err = gpg_error_from_syserror ();
      fprintf (stderr, PGM": strtokenize failed: %s\n", gpg_strerror (err));
      exit (1);
    }

  for (i=0; (s = tokens[i]); i++)
    {
      if (!*s)
        ;
      else if (!strcmp (s, "default"))
        ;
      else if (!strcmp (s, "sign"))
        flags |= GPGME_CREATE_SIGN;
      else if (!strcmp (s, "encr"))
        flags |= GPGME_CREATE_ENCR;
      else if (!strcmp (s, "cert"))
        flags |= GPGME_CREATE_CERT;
      else if (!strcmp (s, "auth"))
        flags |= GPGME_CREATE_AUTH;
      else
        {
          free (tokens);
          fprintf (stderr, PGM": invalid value '%s': %s\n",
                   string, "bad usage");
          exit (1);
        }
    }

  free (tokens);
  return flags;
}



static int
show_usage (int ex)
{
  fputs ("usage: " PGM " [options] ARGS\n"
         "         args: USERID [ALGO [USAGE [EXPIRESECONDS]]]\n"
         "   for addkey: FPR    [ALGO [USAGE [EXPIRESECONDS]]]\n"
         "   for adduid: FPR    USERID\n"
         "   for revuid: FPR    USERID\n"
         "   for set-primary: FPR    USERID\n"
         "Options:\n"
         "  --addkey         add a subkey to the key with FPR\n"
         "  --adduid         add a user id to the key with FPR\n"
         "  --revuid         revoke a user id from the key with FPR\n"
         "  --set-primary    set the primary key flag on USERID\n"
         "  --verbose        run in verbose mode\n"
         "  --status         print status lines from the backend\n"
         "  --progress       print progress info\n"
         "  --openpgp        use the OpenPGP protocol (default)\n"
         "  --cms            use the CMS protocol\n"
         "  --loopback       use a loopback pinentry\n"
         "  --unprotected    do not use a passphrase\n"
         "  --force          do not check for a duplicated user id\n"
         , stderr);
  exit (ex);
}


int
main (int argc, char **argv)
{
  int last_argc = -1;
  gpgme_error_t err;
  gpgme_ctx_t ctx;
  gpgme_protocol_t protocol = GPGME_PROTOCOL_OpenPGP;
  int print_status = 0;
  int print_progress = 0;
  int use_loopback = 0;
  int addkey = 0;
  int adduid = 0;
  int revuid = 0;
  int setpri = 0;
  const char *userid;
  const char *algo = NULL;
  const char *newuserid = NULL;
  unsigned int flags = 0;
  unsigned long expire = 0;
  gpgme_genkey_result_t result;

  if (argc)
    { argc--; argv++; }

  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--help"))
        show_usage (0);
      else if (!strcmp (*argv, "--addkey"))
        {
          addkey = 1;
          adduid = 0;
          revuid = 0;
          setpri = 0;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--adduid"))
        {
          addkey = 0;
          adduid = 1;
          revuid = 0;
          setpri = 0;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--revuid"))
        {
          addkey = 0;
          adduid = 0;
          revuid = 1;
          setpri = 0;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--set-primary"))
        {
          addkey = 0;
          adduid = 0;
          revuid = 0;
          setpri = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--verbose"))
        {
          verbose = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--status"))
        {
          print_status = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--progress"))
        {
          print_progress = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--openpgp"))
        {
          protocol = GPGME_PROTOCOL_OpenPGP;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--cms"))
        {
          protocol = GPGME_PROTOCOL_CMS;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--loopback"))
        {
          use_loopback = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--unprotected"))
        {
          flags |= GPGME_CREATE_NOPASSWD;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--force"))
        {
          flags |= GPGME_CREATE_FORCE;
          argc--; argv++;
        }
      else if (!strncmp (*argv, "--", 2))
        show_usage (1);
    }

  if (adduid || revuid || setpri)
    {
      if (argc != 2)
        show_usage (1);
      userid = argv[0];
      newuserid = argv[1];
    }
  else
    {
      if (!argc || argc > 4)
        show_usage (1);
      userid = argv[0];
      if (argc > 1)
        algo = argv[1];
      if (argc > 2)
        flags |= parse_usage_string (argv[2]);
      if (argc > 3)
        expire = parse_expire_string (argv[3]);
    }

  init_gpgme (protocol);

  err = gpgme_new (&ctx);
  fail_if_err (err);
  gpgme_set_protocol (ctx, protocol);
  gpgme_set_armor (ctx, 1);
  if (print_status)
    {
      gpgme_set_status_cb (ctx, status_cb, NULL);
      gpgme_set_ctx_flag (ctx, "full-status", "1");
    }
  if (print_progress)
    gpgme_set_progress_cb (ctx, progress_cb, NULL);
  if (use_loopback)
    {
      gpgme_set_pinentry_mode (ctx, GPGME_PINENTRY_MODE_LOOPBACK);
      gpgme_set_passphrase_cb (ctx, passphrase_cb, NULL);
    }

  if (addkey || adduid || revuid || setpri)
    {
      gpgme_key_t akey;

      err = gpgme_get_key (ctx, userid, &akey, 1);
      if (err)
        {
          fprintf (stderr, PGM ": error getting secret key for '%s': %s\n",
                   userid, gpg_strerror (err));
          exit (1);
        }

      if (addkey)
        {
          err = gpgme_op_createsubkey (ctx, akey, algo, 0, expire, flags);
          if (err)
            {
              fprintf (stderr, PGM ": gpgme_op_createsubkey failed: %s\n",
                       gpg_strerror (err));
              exit (1);
            }
        }
      else if (adduid)
        {
          err = gpgme_op_adduid (ctx, akey, newuserid, flags);
          if (err)
            {
              fprintf (stderr, PGM ": gpgme_op_adduid failed: %s\n",
                       gpg_strerror (err));
              exit (1);
            }
        }
      else if (revuid)
        {
          err = gpgme_op_revuid (ctx, akey, newuserid, flags);
          if (err)
            {
              fprintf (stderr, PGM ": gpgme_op_revuid failed: %s\n",
                       gpg_strerror (err));
              exit (1);
            }
        }
      else if (setpri)
        {
          err = gpgme_op_set_uid_flag (ctx, akey, newuserid, "primary", NULL);
          if (err)
            {
              fprintf (stderr, PGM ": gpgme_op_set_uid_flag failed: %s\n",
                       gpg_strerror (err));
              exit (1);
            }
        }
      gpgme_key_unref (akey);
    }
  else
    {
      err = gpgme_op_createkey (ctx, userid, algo, 0, expire, NULL, flags);
      if (err)
        {
          fprintf (stderr, PGM ": gpgme_op_createkey failed: %s\n",
                   gpg_strerror (err));
          exit (1);
        }
    }

  if (!setpri)
    {
      result = gpgme_op_genkey_result (ctx);
      if (!result)
        {
          fprintf (stderr, PGM": gpgme_op_genkey_result returned NULL\n");
          exit (1);
        }

      printf ("Generated key: %s (%s)\n",
              result->fpr ? result->fpr : "none",
              result->primary ? (result->sub ? "primary, sub" : "primary")
              /**/            : (result->sub ? "sub" : "none"));

      if (result->fpr && strlen (result->fpr) < 40)
        fprintf (stderr, PGM": generated key has unexpected fingerprint\n");
      if (!result->primary)
        fprintf (stderr, PGM": primary key was not generated\n");
      if (!result->sub)
        fprintf (stderr, PGM": sub key was not generated\n");
      if (!result->uid)
        fprintf (stderr, PGM": uid was not generated\n");
    }

  gpgme_release (ctx);
  return 0;
}