pkcs1-conv.c 14.9 KB
Newer Older
Niels Möller's avatar
Niels Möller committed
1
2
/* pkcs1-conv.c
 *
3
 * Converting pkcs#1 and similar keys to sexp format. */
Niels Möller's avatar
Niels Möller committed
4
5
6

/* nettle, low-level cryptographics library
 *
Niels Möller's avatar
Niels Möller committed
7
 * Copyright (C) 2005, 2009 Niels Möller, Magnus Holmgren
Niels Möller's avatar
Niels Möller committed
8
9
10
11
12
13
14
15
16
17
18
19
20
 *  
 * The nettle library 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.
 * 
 * The nettle library 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 the nettle library; see the file COPYING.LIB.  If not, write to
21
22
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02111-1301, USA.
Niels Möller's avatar
Niels Möller committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 */

#if HAVE_CONFIG_H
# include "config.h"
#endif

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

#include "asn1.h"
#include "base64.h"
#include "buffer.h"
#include "rsa.h"
38
#include "dsa.h"
Niels Möller's avatar
Niels Möller committed
39
40
41
42
43
44

#include "getopt.h"
#include "misc.h"

enum object_type
  {
45
    /* Use a range of values which also work as option id:s */
Niels Möller's avatar
Niels Möller committed
46
47
    RSA_PRIVATE_KEY = 0x200,
    RSA_PUBLIC_KEY,
48
49
50
    DSA_PRIVATE_KEY,
    /* DSA public keys only supported as part of a
       SubjectPublicKeyInfo, i.e., the GENERAL_PUBLIC_KEY case. */
Niels Möller's avatar
Niels Möller committed
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
    GENERAL_PUBLIC_KEY,
  };

static int
write_file(struct nettle_buffer *buffer, FILE *f)
{
  size_t res = fwrite(buffer->contents, 1, buffer->size, f);
  if (res < buffer->size)
    {
      werror("Write failed: %s.\n", strerror(errno));
      return 0;
    }
  else
    return 1;
}

/* Return 1 on success, 0 on error, -1 on eof */
static int
read_line(struct nettle_buffer *buffer, FILE *f)
{
  int c;
  
  while ((c = getc(f)) != EOF)
    {
      if (!NETTLE_BUFFER_PUTC(buffer, c))
	return 0;

      if (c == '\n')
	return 1;
    }
  if (ferror(f))
    {
      werror("Read failed: %s\n", strerror(errno));
      return 0;
    }
  
  else 
    return -1;
}

static int
read_file(struct nettle_buffer *buffer, FILE *f)
{
  int c;
  
  while ((c = getc(f)) != EOF)
    if (!NETTLE_BUFFER_PUTC(buffer, c))
      return 0;

  if (ferror(f))
    {
      werror("Read failed: %s\n", strerror(errno));
      return 0;
    }
  else
    return 1;
}

static const uint8_t
pem_start_pattern[11] = "-----BEGIN ";

static const uint8_t
pem_end_pattern[9] = "-----END ";

static const uint8_t
pem_trailer_pattern[5] = "-----";

static const char
pem_ws[33] = {
  0, 0, 0, 0, 0, 0, 0, 0,
  0, 1, 1, 1, 1, 1, 0, 0, /* \t, \n, \v, \f, \r */
  0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,
  1 /* SPC */
};

#define PEM_IS_SPACE(c) ((c) < sizeof(pem_ws) && pem_ws[(c)]) 

/* Returns 1 on match, otherwise 0. */ 
static int
match_pem_start(unsigned length, const uint8_t *line,
		unsigned *marker_start,
		unsigned *marker_length)
{
  while (length > 0 && PEM_IS_SPACE(line[length - 1]))
    length--;

  if (length > (sizeof(pem_start_pattern) + sizeof(pem_trailer_pattern))
      && memcmp(line, pem_start_pattern, sizeof(pem_start_pattern)) == 0
      && memcmp(line + length - sizeof(pem_trailer_pattern),
		pem_trailer_pattern, sizeof(pem_trailer_pattern)) == 0)
    {
      *marker_start = 11;
      *marker_length = length - (sizeof(pem_start_pattern) + sizeof(pem_trailer_pattern));

      return 1;
    }
  else
    return 0;
}

/* Returns 1 on match, -1 if the line is of the right form except for
   the marker, otherwise 0. */ 
static int
match_pem_end(unsigned length, const uint8_t *line,
	      unsigned marker_length,
	      const uint8_t *marker)
{
  while (length > 0 && PEM_IS_SPACE(line[length - 1]))
    length--;

  if (length > (sizeof(pem_end_pattern) + sizeof(pem_trailer_pattern))
      && memcmp(line, pem_end_pattern, sizeof(pem_end_pattern)) == 0
      && memcmp(line + length - sizeof(pem_trailer_pattern),
		pem_trailer_pattern, sizeof(pem_trailer_pattern)) == 0)
    {
      /* Right form. Check marker */
      if (length == marker_length + (sizeof(pem_end_pattern) + sizeof(pem_trailer_pattern))
	  && memcmp(line + sizeof(pem_end_pattern), marker, marker_length) == 0)
	return 1;
      else
	return -1;
    }
  else
    return 0;  
}

struct pem_info
{
  /* The FOO part in "-----BEGIN FOO-----" */
  unsigned marker_start;
  unsigned marker_length;
  unsigned data_start;
  unsigned data_length;
};

static int
read_pem(struct nettle_buffer *buffer, FILE *f,
	 struct pem_info *info)
{  
  /* Find start line */
  for (;;)
    {
194
195
      int res;

Niels Möller's avatar
Niels Möller committed
196
197
      nettle_buffer_reset(buffer);

198
      res = read_line(buffer, f);
Niels Möller's avatar
Niels Möller committed
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
      if (res != 1)
	return res;

      if (match_pem_start(buffer->size, buffer->contents,
			  &info->marker_start, &info->marker_length))
	break;
    }

  /* NUL-terminate the marker. Don't care to check for embedded NULs. */
  buffer->contents[info->marker_start + info->marker_length] = 0;

  info->data_start = buffer->size;

  for (;;)
    {
      unsigned line_start = buffer->size;

      if (read_line(buffer, f) != 1)
	return 0;

      switch (match_pem_end(buffer->size - line_start,
			    buffer->contents + line_start,
			    info->marker_length,
			    buffer->contents + info->marker_start))
	{
	case 0:
	  break;
	case -1:
	  werror("PEM END line doesn't match BEGIN.\n");
	  return 0;
	case 1:
	  /* Return base 64 data; let caller do the decoding */ 
	  info->data_length = line_start - info->data_start;
	  return 1;
	}
    }
}

static int
decode_base64(struct nettle_buffer *buffer,
	      unsigned start, unsigned *length)
{
  struct base64_decode_ctx ctx;
  
  base64_decode_init(&ctx);

  /* Decode in place */
  if (base64_decode_update(&ctx,
			   length, buffer->contents + start,
			   *length, buffer->contents + start)
      && base64_decode_final(&ctx))
    return 1;
  
  else
    {
      werror("Invalid base64 date.\n");
      return 0;
    }
}

static int
convert_rsa_public_key(struct nettle_buffer *buffer, unsigned length, const uint8_t *data)
{
  struct rsa_public_key pub;
  int res;
  
  rsa_public_key_init(&pub);

  if (rsa_keypair_from_der(&pub, NULL, 0,
			   length, data))
    {
      /* Reuses the buffer */
      nettle_buffer_reset(buffer);
      res = rsa_keypair_to_sexp(buffer, NULL, &pub, NULL);
    }
  else
    {
      werror("Invalid PKCS#1 public key.\n");
      res = 0;
    }
  rsa_public_key_clear(&pub);
  return res;
}

static int
convert_rsa_private_key(struct nettle_buffer *buffer, unsigned length, const uint8_t *data)
{
  struct rsa_public_key pub;
  struct rsa_private_key priv;
  int res;
  
  rsa_public_key_init(&pub);
  rsa_private_key_init(&priv);

  if (rsa_keypair_from_der(&pub, &priv, 0,
			   length, data))
    {
      /* Reuses the buffer */
      nettle_buffer_reset(buffer);
      res = rsa_keypair_to_sexp(buffer, NULL, &pub, &priv);
    }
  else
    {
      werror("Invalid PKCS#1 private key.\n");
      res = 0;
    }
  rsa_public_key_clear(&pub);
  rsa_private_key_clear(&priv);

  return res;
}

311
312
313
314
315
316
317
318
319
320
static int
convert_dsa_private_key(struct nettle_buffer *buffer, unsigned length, const uint8_t *data)
{
  struct dsa_public_key pub;
  struct dsa_private_key priv;
  int res;
  
  dsa_public_key_init(&pub);
  dsa_private_key_init(&priv);

321
322
  if (dsa_openssl_private_key_from_der(&pub, &priv, 0,
				       length, data))
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
    {
      /* Reuses the buffer */
      nettle_buffer_reset(buffer);
      res = dsa_keypair_to_sexp(buffer, NULL, &pub, &priv);
    }
  else
    {
      werror("Invalid OpenSSL private key.\n");
      res = 0;
    }
  dsa_public_key_clear(&pub);
  dsa_private_key_clear(&priv);

  return res;
}

Niels Möller's avatar
Niels Möller committed
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
/* Returns 1 on success, 0 on error, and -1 for unsupported algorithms. */
static int
convert_public_key(struct nettle_buffer *buffer, unsigned length, const uint8_t *data)
{
  /* SubjectPublicKeyInfo ::= SEQUENCE {
         algorithm		AlgorithmIdentifier,
	 subjectPublicKey 	BIT STRING
     }

     AlgorithmIdentifier ::= SEQUENCE {
         algorithm  	OBJECT IDENTIFIER,
	 parameters 	OPTIONAL
     }
  */
  struct asn1_der_iterator i;
  struct asn1_der_iterator j;
  int res = 0;

  if (asn1_der_iterator_first(&i, length, data) == ASN1_ITERATOR_CONSTRUCTED
      && i.type == ASN1_SEQUENCE
      && asn1_der_decode_constructed_last(&i) == ASN1_ITERATOR_CONSTRUCTED
      && i.type == ASN1_SEQUENCE

      /* Use the j iterator to parse the algorithm identifier */
      && asn1_der_decode_constructed(&i, &j) == ASN1_ITERATOR_PRIMITIVE
      && j.type == ASN1_IDENTIFIER
      && asn1_der_iterator_next(&i) == ASN1_ITERATOR_PRIMITIVE
      && i.type == ASN1_BITSTRING

368
369
      /* Use i to parse the object wrapped in the bit string.*/
      && asn1_der_decode_bitstring_last(&i))
Niels Möller's avatar
Niels Möller committed
370
371
372
373
374
375
376
377
378
379
380
381
382
383
    {
      /* pkcs-1 {
	     iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs-1(1)
	     modules(0) pkcs-1(1)
	 }

	 --
	 -- When rsaEncryption is used in an AlgorithmIdentifier the
	 -- parameters MUST be present and MUST be NULL.
	 --
	 rsaEncryption    OBJECT IDENTIFIER ::= { pkcs-1 1 }
      */
      static const uint8_t id_rsaEncryption[9] =
	{ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 };
384
385
386
387
388
389
390
391
392
393
      /*
	 --
	 -- When dsa is used in an AlgorithmIdentifier the
	 -- parameters MUST be present and MUST NOT be NULL.
	 --
	 dsa    OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) x9-57(10040) x9algorithm(4) 1 }
      */
      static const uint8_t id_dsa[7] =
	{ 0x2A, 0x86, 0x48, 0xCE, 0x38, 0x04, 0x01 };

Niels Möller's avatar
Niels Möller committed
394
395
396
397
398
399
400
401
      switch (j.length)
	{
	unknown:
	default:
	  werror("SubjectPublicKeyInfo: Unsupported algorithm.\n");
	  res = -1;
	  break;
	  
402
403
404
405
406
407
408
409
410
411
	case 7:
	  if (memcmp(j.data, id_dsa, 7) == 0)
	    {
	      if (asn1_der_iterator_next(&j) == ASN1_ITERATOR_CONSTRUCTED
		  && asn1_der_decode_constructed_last(&j) == ASN1_ITERATOR_PRIMITIVE)
		{
		  struct dsa_public_key pub;

		  dsa_public_key_init(&pub);

412
413
		  if (dsa_params_from_der_iterator(&pub, 0, &i)
		      && dsa_public_key_from_der_iterator(&pub, 0, &j))
414
415
416
417
		    {
		      nettle_buffer_reset(buffer);
		      res = dsa_keypair_to_sexp(buffer, NULL, &pub, NULL) > 0;
		    }
418
		  dsa_public_key_clear(&pub);
419
420
421
422
423
424
		}
	      if (!res)
		werror("SubjectPublicKeyInfo: Invalid DSA key.\n");
	      break;
	    }
	  else goto unknown;
Niels Möller's avatar
Niels Möller committed
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
	case 9:
	  if (memcmp(j.data, id_rsaEncryption, 9) == 0)
	    {
	      if (asn1_der_iterator_next(&j) == ASN1_ITERATOR_PRIMITIVE
		  && j.type == ASN1_NULL
		  && j.length == 0
		  && asn1_der_iterator_next(&j) == ASN1_ITERATOR_END)
		{
		  struct rsa_public_key pub;

		  rsa_public_key_init(&pub);

		  if (rsa_public_key_from_der_iterator(&pub, 0, &i))
		    {
		      nettle_buffer_reset(buffer);
		      res = rsa_keypair_to_sexp(buffer, NULL, &pub, NULL) > 0;
		    }
442
		  rsa_public_key_clear(&pub);
Niels Möller's avatar
Niels Möller committed
443
444
445
446
447
448
449
450
451
452
		}
	      if (!res)
		werror("SubjectPublicKeyInfo: Invalid RSA key.\n");
	      break;
	    }
	  else goto unknown;
	}
    }
  else
    werror("SubjectPublicKeyInfo: Invalid object.\n");
453

Niels Möller's avatar
Niels Möller committed
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
  return res;
}

/* NOTE: Destroys contents of buffer */
/* Returns 1 on success, 0 on error, and -1 for unsupported algorithms. */
static int
convert_type(struct nettle_buffer *buffer,
	     enum object_type type,
	     unsigned length, const uint8_t *data)
{
  int res;
  
  switch(type)
    {
    default:
      abort();

    case GENERAL_PUBLIC_KEY:
      res = convert_public_key(buffer, length, data);
      break;

    case RSA_PUBLIC_KEY:
      res = convert_rsa_public_key(buffer, length, data);
      break;

    case RSA_PRIVATE_KEY:
      res = convert_rsa_private_key(buffer, length, data);
      break;
482
483
484
485

    case DSA_PRIVATE_KEY:
      res = convert_dsa_private_key(buffer, length, data);
      break;
Niels Möller's avatar
Niels Möller committed
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
    }

  if (res > 0)
    res = write_file(buffer, stdout);

  return res;
}

static int
convert_file(struct nettle_buffer *buffer,
	     FILE *f,
	     enum object_type type,
	     int base64)
{
  if (type)
    {
      read_file(buffer, f);
      if (base64 && !decode_base64(buffer, 0, &buffer->size))
	return 0;
      
      if (convert_type(buffer, type,
		       buffer->size, buffer->contents) != 1)
	return 0;

      return 1;
    }
  else
    {
      /* PEM processing */
      for (;;)
	{
	  struct pem_info info;
	  const uint8_t *marker;
	  
	  nettle_buffer_reset(buffer);
	  switch (read_pem(buffer, f, &info))
	    {
	    default:
	      return 0;
	    case 1:
	      break;
	    case -1:
	      /* EOF */
	      return 1;
	    }

	  if (!decode_base64(buffer, info.data_start, &info.data_length))
	    return 0;

	  marker = buffer->contents + info.marker_start;

	  type = 0;
	  switch (info.marker_length)
	    {
	    case 10:
	      if (memcmp(marker, "PUBLIC KEY", 10) == 0)
		{
		  type = GENERAL_PUBLIC_KEY;
		  break;
		}
	    case 14:
	      if (memcmp(marker, "RSA PUBLIC KEY", 14) == 0)
		{
		  type = RSA_PUBLIC_KEY;
		  break;
		}

	    case 15:
	      if (memcmp(marker, "RSA PRIVATE KEY", 15) == 0)
		{
		  type = RSA_PRIVATE_KEY;
		  break;
		}
559
560
561
562
563
	      if (memcmp(marker, "DSA PRIVATE KEY", 15) == 0)
		{
		  type = DSA_PRIVATE_KEY;
		  break;
		}
Niels Möller's avatar
Niels Möller committed
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
	    }
	  
	  if (!type)
	    werror("Ignoring unsupported object type `%s'.\n", marker);

	  else if (convert_type(buffer, type,
				info.data_length,
				buffer->contents + info.data_start) != 1)
	    return 0;
	}
    }
}

int
main(int argc, char **argv)
{
  struct nettle_buffer buffer;
  enum object_type type = 0;
  int base64 = 0;
  int c;
584
585
586
587
588
589
590
591

  enum {
    OPT_HELP = 0x300,
    OPT_PRIVATE_RSA = RSA_PRIVATE_KEY,
    OPT_PUBLIC_RSA = RSA_PUBLIC_KEY,
    OPT_PRIVATE_DSA = DSA_PRIVATE_KEY,
    OPT_PUBLIC_KEY = GENERAL_PUBLIC_KEY,
  };
Niels Möller's avatar
Niels Möller committed
592
593
594
595
  
  static const struct option options[] =
    {
      /* Name, args, flag, val */
596
      { "help", no_argument, NULL, OPT_HELP },
Niels Möller's avatar
Niels Möller committed
597
      { "version", no_argument, NULL, 'V' },
598
599
600
601
      { "private-rsa-key", no_argument, NULL, OPT_PRIVATE_RSA },
      { "public-rsa-key", no_argument, NULL, OPT_PUBLIC_RSA },
      { "private-dsa-key", no_argument, NULL, OPT_PRIVATE_DSA },
      { "public-key-info", no_argument, NULL, OPT_PUBLIC_KEY },
Niels Möller's avatar
Niels Möller committed
602
603
604
605
      { "base-64", no_argument, NULL, 'b' },
      { NULL, 0, NULL, 0 }
    };

606
  while ( (c = getopt_long(argc, argv, "Vb", options, NULL)) != -1)
Niels Möller's avatar
Niels Möller committed
607
608
609
610
611
612
613
614
615
616
    {
      switch (c)
	{
	default:
	  abort();

	case 'b':
	  base64 = 1;
	  break;

617
618
619
620
621
	case OPT_PRIVATE_RSA:
	case OPT_PUBLIC_RSA:
	case OPT_PRIVATE_DSA:
	case OPT_PUBLIC_KEY:
	  /* Same values as the type codes. */
Niels Möller's avatar
Niels Möller committed
622
623
624
	  type = c;
	  break;

625
	case OPT_HELP:
Niels Möller's avatar
Niels Möller committed
626
627
	  printf("FIXME: Usage information.\n");
	  return EXIT_SUCCESS;
628
629
	case '?':
	  return EXIT_FAILURE;
Niels Möller's avatar
Niels Möller committed
630
631
632

	case 'V':
	  printf("pkcs1-conv (" PACKAGE_STRING ")\n");
633
	  return EXIT_SUCCESS;
Niels Möller's avatar
Niels Möller committed
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
	}
    }

  nettle_buffer_init_realloc(&buffer, NULL, nettle_xrealloc);  

  if (optind == argc)
    {
      if (!convert_file(&buffer, stdin, type, base64))
	return EXIT_FAILURE;
    }
  else
    {
      int i;
      const char *mode = (type || base64) ? "r" : "rb";
      
      for (i = optind; i < argc; i++)
	{
	  FILE *f = fopen(argv[i], mode);
	  if (!f)
	    die("Failed to open `%s': %s.\n", argv[i], strerror(errno));

	  if (!convert_file(&buffer, f, type, base64))
	    return EXIT_FAILURE;

	  fclose(f);
	}
    }
661
662
  nettle_buffer_clear (&buffer);

Niels Möller's avatar
Niels Möller committed
663
664
  return EXIT_SUCCESS;
}