whack uses optionsfrom from libstrongswan
[strongswan.git] / src / scepclient / scepclient.c
1 /*
2 * Copyright (C) 2005 Jan Hutter, Martin Willi
3 * Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 /**
17 * @file main.c
18 * @brief scepclient main program
19 */
20
21 /**
22 * @mainpage SCEP for Linux strongSwan
23 *
24 * Documentation of SCEP for Linux StrongSwan
25 */
26
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <getopt.h>
32 #include <ctype.h>
33 #include <unistd.h>
34 #include <time.h>
35 #include <gmp.h>
36
37 #include <freeswan.h>
38
39 #include <library.h>
40 #include <debug.h>
41 #include <asn1/asn1.h>
42 #include <asn1/oid.h>
43 #include <utils/optionsfrom.h>
44 #include <utils/enumerator.h>
45
46 #include "../pluto/constants.h"
47 #include "../pluto/defs.h"
48 #include "../pluto/log.h"
49 #include "../pluto/pkcs1.h"
50 #include "../pluto/pkcs7.h"
51 #include "../pluto/certs.h"
52
53 #include "rsakey.h"
54 #include "pkcs10.h"
55 #include "scep.h"
56
57 /*
58 * definition of some defaults
59 */
60
61 /* default name of DER-encoded PKCS#1 private key file */
62 #define DEFAULT_FILENAME_PKCS1 "myKey.der"
63
64 /* default name of DER-encoded PKCS#10 certificate request file */
65 #define DEFAULT_FILENAME_PKCS10 "myReq.der"
66
67 /* default name of DER-encoded PKCS#7 file */
68 #define DEFAULT_FILENAME_PKCS7 "pkcs7.der"
69
70 /* default name of DER-encoded self-signed X.509 certificate file */
71 #define DEFAULT_FILENAME_CERT_SELF "selfCert.der"
72
73 /* default name of DER-encoded X.509 certificate file */
74 #define DEFAULT_FILENAME_CERT "myCert.der"
75
76 /* default name of DER-encoded CA cert file used for key encipherment */
77 #define DEFAULT_FILENAME_CACERT_ENC "caCert.der"
78
79 /* default name of the der encoded CA cert file used for signature verification */
80 #define DEFAULT_FILENAME_CACERT_SIG "caCert.der"
81
82 /* default prefix of the der encoded CA certificates received from the SCEP server */
83 #define DEFAULT_FILENAME_PREFIX_CACERT "caCert.der"
84
85 /* default certificate validity */
86 #define DEFAULT_CERT_VALIDITY 5 * 3600 * 24 * 365 /* seconds */
87
88 /* default polling time interval in SCEP manual mode */
89 #define DEFAULT_POLL_INTERVAL 20 /* seconds */
90
91 /* default key length for self-generated RSA keys */
92 #define DEFAULT_RSA_KEY_LENGTH 2048 /* bits */
93
94 /* default distinguished name */
95 #define DEFAULT_DN "C=CH, O=Linux strongSwan, CN="
96
97 /* challenge password buffer size */
98 #define MAX_PASSWORD_LENGTH 256
99
100 /* Max length of filename for tempfile */
101 #define MAX_TEMP_FILENAME_LENGTH 256
102
103
104 /* current scepclient version */
105 static const char *scepclient_version = "1.0";
106
107 /* by default the CRL policy is lenient */
108 bool strict_crl_policy = FALSE;
109
110 /* by default pluto does not check crls dynamically */
111 long crl_check_interval = 0;
112
113 /* by default pluto logs out after every smartcard use */
114 bool pkcs11_keep_state = FALSE;
115
116 /* options read by optionsfrom */
117 options_t *options;
118
119 /*
120 * Global variables
121 */
122
123 RSA_private_key_t *private_key = NULL;
124
125 chunk_t pkcs1;
126 chunk_t pkcs7;
127 chunk_t subject;
128 chunk_t challengePassword;
129 chunk_t serialNumber;
130 chunk_t transID;
131 chunk_t fingerprint;
132 chunk_t issuerAndSubject;
133 chunk_t getCertInitial;
134 chunk_t scep_response;
135 cert_t cert;
136
137 x509cert_t *x509_signer = NULL;
138 x509cert_t *x509_ca_enc = NULL;
139 x509cert_t *x509_ca_sig = NULL;
140 generalName_t *subjectAltNames = NULL;
141 pkcs10_t *pkcs10 = NULL;
142
143 /**
144 * @brief exit scepclient
145 *
146 * @param status 0 = OK, 1 = general discomfort
147 */
148 static void
149 exit_scepclient(err_t message, ...)
150 {
151 int status = 0;
152
153 if (private_key != NULL)
154 {
155 free_RSA_private_content(private_key);
156 free(private_key);
157 }
158 free(pkcs1.ptr);
159 free(pkcs7.ptr);
160 free(subject.ptr);
161 free(serialNumber.ptr);
162 free(transID.ptr);
163 free(fingerprint.ptr);
164 free(issuerAndSubject.ptr);
165 free(getCertInitial.ptr);
166 free(scep_response.ptr);
167
168 free_generalNames(subjectAltNames, TRUE);
169 if (x509_signer != NULL)
170 {
171 x509_signer->subjectAltName = NULL;
172 }
173 free_x509cert(x509_signer);
174 free_x509cert(x509_ca_enc);
175 free_x509cert(x509_ca_sig);
176 pkcs10_free(pkcs10);
177 options->destroy(options);
178
179 /* print any error message to stderr */
180 if (message != NULL && *message != '\0')
181 {
182 va_list args;
183 char m[LOG_WIDTH]; /* longer messages will be truncated */
184
185 va_start(args, message);
186 vsnprintf(m, sizeof(m), message, args);
187 va_end(args);
188
189 fprintf(stderr, "error: %s\n", m);
190 status = -1;
191 }
192 library_deinit();
193 close_log();
194 exit(status);
195 }
196
197 /**
198 * @brief prints the program version and exits
199 *
200 */
201 static void
202 version(void)
203 {
204 printf("scepclient %s\n", scepclient_version);
205 exit_scepclient(NULL);
206 }
207
208 /**
209 * @brief prints the usage of the program to the stderr output
210 *
211 * If message is set, program is exitet with 1 (error)
212 * @param message message in case of an error
213 */
214 static void
215 usage(const char *message)
216 {
217 fprintf(stderr,
218 "Usage: scepclient\n"
219 " --help (-h) show usage and exit\n"
220 " --version (-v) show version and exit\n"
221 " --quiet (-q) do not write log output to stderr\n"
222 " --in (-i) <type>[=<filename>] use <filename> of <type> for input \n"
223 " <type> = pkcs1 | cacert-enc | cacert-sig\n"
224 " - if no pkcs1 input is defined, a \n"
225 " RSA key will be generated\n"
226 " - if no filename is given, default is used\n"
227 " --out (-o) <type>[=<filename>] write output of <type> to <filename>\n"
228 " multiple outputs are allowed\n"
229 " <type> = pkcs1 | pkcs10 | pkcs7 | cert-self | cert | cacert\n"
230 " - type cacert defines filename prefix of\n"
231 " received CA certificate(s)\n"
232 " - if no filename is given, default is used\n"
233 " --optionsfrom (-+) <filename> reads additional options from given file\n"
234 " --force (-f) force existing file(s)\n"
235 "\n"
236 "Options for key generation (pkcs1):\n"
237 " --keylength (-k) <bits> key length for RSA key generation\n"
238 "(default: 2048 bits)\n"
239 "\n"
240 "Options for validity:\n"
241 " --days (-D) <days> validity in days\n"
242 " --startdate (-S) <YYMMDDHHMMSS>Z not valid before date\n"
243 " --enddate (-E) <YYMMDDHHMMSS>Z not valid after date\n"
244 "\n"
245 "Options for request generation (pkcs10):\n"
246 " --dn (-d) <dn> comma separated list of distinguished names\n"
247 " --subjectAltName (-s) <t>=<v> include subjectAltName in certificate request\n"
248 " <t> = email | dns | ip \n"
249 " --password (-p) <pw> challenge password\n"
250 " - if pw is '%%prompt', password gets prompted for\n"
251 " --algorithm (-a) <algo> use specified algorithm for PKCS#7 encryption\n"
252 " <algo> = des-cbc | 3des-cbc | aes128-cbc |\n"
253 " aes192-cbc | aes256-cbc (default: 3des-cbc)\n"
254 "\n"
255 "Options for enrollment (cert):\n"
256 " --url (-u) <url> url of the SCEP server\n"
257 " --method (-m) post | get http request type\n"
258 " --interval (-t) <seconds> manual mode poll interval in seconds (default 20s)\n"
259 " --maxpolltime (-x) <seconds> max poll time in seconds when in manual mode\n"
260 " (default: unlimited)\n"
261 #ifdef DEBUG
262 "\n"
263 "Debugging output:\n"
264 " --debug-all (-A) show everything except private\n"
265 " --debug-parsing (-P) show parsing relevant stuff\n"
266 " --debug-raw (-R) show raw hex dumps\n"
267 " --debug-control (-C) show control flow output\n"
268 " --debug-controlmore (-M) show more control flow\n"
269 " --debug-private (-X) show sensitive data (private keys, etc.)\n"
270 #endif
271 );
272 exit_scepclient(message);
273 }
274
275 /**
276 * Log loaded plugins
277 */
278 static void print_plugins()
279 {
280 char buf[BUF_LEN], *plugin;
281 int len = 0;
282 enumerator_t *enumerator;
283
284 enumerator = lib->plugins->create_plugin_enumerator(lib->plugins);
285 while (len < BUF_LEN && enumerator->enumerate(enumerator, &plugin))
286 {
287 len += snprintf(&buf[len], BUF_LEN-len, "%s ", plugin);
288 }
289 enumerator->destroy(enumerator);
290 DBG1(" loaded plugins: %s", buf);
291 }
292
293 /**
294 * @brief main of scepclient
295 *
296 * @param argc number of arguments
297 * @param argv pointer to the argument values
298 */
299 int main(int argc, char **argv)
300 {
301 /* external values */
302 extern char * optarg;
303 extern int optind;
304
305 /* type of input and output files */
306 typedef enum {
307 PKCS1 = 0x01,
308 PKCS10 = 0x02,
309 PKCS7 = 0x04,
310 CERT_SELF = 0x08,
311 CERT = 0x10,
312 CACERT_ENC = 0x20,
313 CACERT_SIG = 0x40
314 } scep_filetype_t;
315
316 /* filetype to read from, defaults to "generate a key" */
317 scep_filetype_t filetype_in = 0;
318
319 /* filetype to write to, no default here */
320 scep_filetype_t filetype_out = 0;
321
322 /* input files */
323 char *file_in_pkcs1 = DEFAULT_FILENAME_PKCS1;
324 char *file_in_cacert_enc = DEFAULT_FILENAME_CACERT_ENC;
325 char *file_in_cacert_sig = DEFAULT_FILENAME_CACERT_SIG;
326
327 /* output files */
328 char *file_out_pkcs1 = DEFAULT_FILENAME_PKCS1;
329 char *file_out_pkcs10 = DEFAULT_FILENAME_PKCS10;
330 char *file_out_pkcs7 = DEFAULT_FILENAME_PKCS7;
331 char *file_out_cert_self = DEFAULT_FILENAME_CERT_SELF;
332 char *file_out_cert = DEFAULT_FILENAME_CERT;
333 char *file_out_prefix_cacert = DEFAULT_FILENAME_PREFIX_CACERT;
334
335 /* by default user certificate is requested */
336 bool request_ca_certificate = FALSE;
337
338 /* by default existing files are not overwritten */
339 bool force = FALSE;
340
341 /* length of RSA key in bits */
342 u_int rsa_keylength = DEFAULT_RSA_KEY_LENGTH;
343
344 /* validity of self-signed certificate */
345 time_t validity = DEFAULT_CERT_VALIDITY;
346 time_t notBefore = 0;
347 time_t notAfter = 0;
348
349 /* distinguished name for requested certificate, ASCII format */
350 char *distinguishedName = NULL;
351
352 /* challenge password */
353 char challenge_password_buffer[MAX_PASSWORD_LENGTH];
354
355 /* symmetric encryption algorithm used by pkcs7, default is 3DES */
356 int pkcs7_symmetric_cipher = OID_3DES_EDE_CBC;
357
358 /* digest algorithm used by pkcs7, default is SHA-1 */
359 int pkcs7_digest_alg = OID_SHA1;
360
361 /* signature algorithm used by pkcs10, default is SHA-1 with RSA encryption */
362 int pkcs10_signature_alg = OID_SHA1;
363
364 /* URL of the SCEP-Server */
365 char *scep_url = NULL;
366
367 /* http request method, default is GET */
368 bool http_get_request = TRUE;
369
370 /* poll interval time in manual mode in seconds */
371 u_int poll_interval = DEFAULT_POLL_INTERVAL;
372
373 /* maximum poll time */
374 u_int max_poll_time = 0;
375
376 err_t ugh = NULL;
377
378 /* initialize global variables */
379 pkcs1 = chunk_empty;
380 pkcs7 = chunk_empty;
381 serialNumber = chunk_empty;
382 transID = chunk_empty;
383 fingerprint = chunk_empty;
384 issuerAndSubject = chunk_empty;
385 challengePassword = chunk_empty;
386 getCertInitial = chunk_empty;
387 scep_response = chunk_empty;
388 log_to_stderr = TRUE;
389
390 /* initialize library and optionsfrom */
391 library_init(STRONGSWAN_CONF);
392 options = options_create();
393
394 for (;;)
395 {
396 static const struct option long_opts[] = {
397 /* name, has_arg, flag, val */
398 { "help", no_argument, NULL, 'h' },
399 { "version", no_argument, NULL, 'v' },
400 { "optionsfrom", required_argument, NULL, '+' },
401 { "quiet", no_argument, NULL, 'q' },
402 { "in", required_argument, NULL, 'i' },
403 { "out", required_argument, NULL, 'o' },
404 { "force", no_argument, NULL, 'f' },
405 { "keylength", required_argument, NULL, 'k' },
406 { "dn", required_argument, NULL, 'd' },
407 { "days", required_argument, NULL, 'D' },
408 { "startdate", required_argument, NULL, 'S' },
409 { "enddate", required_argument, NULL, 'E' },
410 { "subjectAltName", required_argument, NULL, 's' },
411 { "password", required_argument, NULL, 'p' },
412 { "algorithm", required_argument, NULL, 'a' },
413 { "url", required_argument, NULL, 'u' },
414 { "method", required_argument, NULL, 'm' },
415 { "interval", required_argument, NULL, 't' },
416 { "maxpolltime", required_argument, NULL, 'x' },
417 #ifdef DEBUG
418 { "debug-all", no_argument, NULL, 'A' },
419 { "debug-parsing", no_argument, NULL, 'P'},
420 { "debug-raw", no_argument, NULL, 'R'},
421 { "debug-control", no_argument, NULL, 'C'},
422 { "debug-controlmore", no_argument, NULL, 'M'},
423 { "debug-private", no_argument, NULL, 'X'},
424 #endif
425 { 0,0,0,0 }
426 };
427
428 /* parse next option */
429 int c = getopt_long(argc, argv, "hv+:qi:o:fk:d:s:p:a:u:m:t:x:APRCMS", long_opts, NULL);
430
431 switch (c)
432 {
433 case EOF: /* end of flags */
434 break;
435
436 case 'h': /* --help */
437 usage(NULL);
438
439 case 'v': /* --version */
440 version();
441
442 case 'q': /* --quiet */
443 log_to_stderr = FALSE;
444 continue;
445
446 case 'i': /* --in <type> [= <filename>] */
447 {
448 char *filename = strstr(optarg, "=");
449
450 if (filename)
451 {
452 /* replace '=' by '\0' */
453 *filename = '\0';
454 /* set pointer to start of filename */
455 filename++;
456 }
457 if (strcaseeq("pkcs1", optarg))
458 {
459 filetype_in |= PKCS1;
460 if (filename)
461 file_in_pkcs1 = filename;
462 }
463 else if (strcaseeq("cacert-enc", optarg))
464 {
465 filetype_in |= CACERT_ENC;
466 if (filename)
467 file_in_cacert_enc = filename;
468 }
469 else if (strcaseeq("cacert-sig", optarg))
470 {
471 filetype_in |= CACERT_SIG;
472 if (filename)
473 file_in_cacert_sig = filename;
474 }
475 else
476 {
477 usage("invalid --in file type");
478 }
479 continue;
480 }
481
482 case 'o': /* --out <type> [= <filename>] */
483 {
484 char *filename = strstr(optarg, "=");
485
486 if (filename)
487 {
488 /* replace '=' by '\0' */
489 *filename = '\0';
490 /* set pointer to start of filename */
491 filename++;
492 }
493 if (strcaseeq("pkcs1", optarg))
494 {
495 filetype_out |= PKCS1;
496 if (filename)
497 file_out_pkcs1 = filename;
498 }
499 else if (strcaseeq("pkcs10", optarg))
500 {
501 filetype_out |= PKCS10;
502 if (filename)
503 file_out_pkcs10 = filename;
504 }
505 else if (strcaseeq("pkcs7", optarg))
506 {
507 filetype_out |= PKCS7;
508 if (filename)
509 file_out_pkcs7 = filename;
510 }
511 else if (strcaseeq("cert-self", optarg))
512 {
513 filetype_out |= CERT_SELF;
514 if (filename)
515 file_out_cert_self = filename;
516 }
517 else if (strcaseeq("cert", optarg))
518 {
519 filetype_out |= CERT;
520 if (filename)
521 file_out_cert = filename;
522 }
523 else if (strcaseeq("cacert", optarg))
524 {
525 request_ca_certificate = TRUE;
526 if (filename)
527 file_out_prefix_cacert = filename;
528 }
529 else
530 {
531 usage("invalid --out file type");
532 }
533 continue;
534 }
535
536 case 'f': /* --force */
537 force = TRUE;
538 continue;
539
540 case '+': /* --optionsfrom <filename> */
541 if (!options->from(options, optarg, &argc, &argv, optind))
542 {
543 exit_scepclient("optionsfrom failed");
544 }
545 continue;
546
547 case 'k': /* --keylength <length> */
548 {
549 div_t q;
550
551 rsa_keylength = atoi(optarg);
552 if (rsa_keylength == 0)
553 usage("invalid keylength");
554
555 /* check if key length is a multiple of 8 bits */
556 q = div(rsa_keylength, 2*BITS_PER_BYTE);
557 if (q.rem != 0)
558 {
559 exit_scepclient("keylength is not a multiple of %d bits!"
560 , 2*BITS_PER_BYTE);
561 }
562 continue;
563 }
564
565 case 'D': /* --days */
566 if (optarg == NULL || !isdigit(optarg[0]))
567 usage("missing number of days");
568 {
569 char *endptr;
570 long days = strtol(optarg, &endptr, 0);
571
572 if (*endptr != '\0' || endptr == optarg
573 || days <= 0)
574 usage("<days> must be a positive number");
575 validity = 24*3600*days;
576 }
577 continue;
578
579 case 'S': /* --startdate */
580 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
581 usage("date format must be YYMMDDHHMMSSZ");
582 {
583 chunk_t date = { optarg, 13 };
584 notBefore = asn1_to_time(&date, ASN1_UTCTIME);
585 }
586 continue;
587
588 case 'E': /* --enddate */
589 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
590 usage("date format must be YYMMDDHHMMSSZ");
591 {
592 chunk_t date = { optarg, 13 };
593 notAfter = asn1_to_time(&date, ASN1_UTCTIME);
594 }
595 continue;
596
597 case 'd': /* --dn */
598 if (distinguishedName)
599 usage("only one distinguished name allowed");
600 distinguishedName = optarg;
601 continue;
602
603 case 's': /* --subjectAltName */
604 {
605 generalNames_t kind;
606 char *value = strstr(optarg, "=");
607
608 if (value)
609 {
610 /* replace '=' by '\0' */
611 *value = '\0';
612 /* set pointer to start of value */
613 value++;
614 }
615
616 if (strcaseeq("email", optarg))
617 {
618 kind = GN_RFC822_NAME;
619 }
620 else if (strcaseeq("dns", optarg))
621 {
622 kind = GN_DNS_NAME;
623 }
624 else if (strcaseeq("ip", optarg))
625 {
626 kind = GN_IP_ADDRESS;
627 }
628 else
629 {
630 usage("invalid --subjectAltName type");
631 continue;
632 }
633 pkcs10_add_subjectAltName(&subjectAltNames, kind, value);
634 continue;
635 }
636
637 case 'p': /* --password */
638 if (challengePassword.len > 0)
639 {
640 usage("only one challenge password allowed");
641 }
642 if (strcaseeq("%prompt", optarg))
643 {
644 printf("Challenge password: ");
645 if (fgets(challenge_password_buffer, sizeof(challenge_password_buffer)-1, stdin))
646 {
647 challengePassword.ptr = challenge_password_buffer;
648 /* discard the terminating '\n' from the input */
649 challengePassword.len = strlen(challenge_password_buffer) - 1;
650 }
651 else
652 {
653 usage("challenge password could not be read");
654 }
655 }
656 else
657 {
658 challengePassword.ptr = optarg;
659 challengePassword.len = strlen(optarg);
660 }
661 continue;
662
663 case 'u': /* -- url */
664 if (scep_url)
665 {
666 usage("only one URL argument allowed");
667 }
668 scep_url = optarg;
669 continue;
670
671 case 'm': /* --method */
672 if (strcaseeq("get", optarg))
673 {
674 http_get_request = TRUE;
675 }
676 else if (strcaseeq("post", optarg))
677 {
678 http_get_request = FALSE;
679 }
680 else
681 {
682 usage("invalid http request method specified");
683 }
684 continue;
685
686 case 't': /* --interval */
687 poll_interval = atoi(optarg);
688 if (poll_interval <= 0)
689 {
690 usage("invalid interval specified");
691 }
692 continue;
693
694 case 'x': /* --maxpolltime */
695 max_poll_time = atoi(optarg);
696 if (max_poll_time < 0)
697 {
698 usage("invalid maxpolltime specified");
699 }
700 continue;
701
702 case 'a': /*--algorithm */
703 if (strcaseeq("des-cbc", optarg))
704 {
705 pkcs7_symmetric_cipher = OID_DES_CBC;
706 }
707 else if (strcaseeq("3des-cbc", optarg))
708 {
709 pkcs7_symmetric_cipher = OID_3DES_EDE_CBC;
710 }
711 else if (strcaseeq("aes128-cbc", optarg))
712 {
713 pkcs7_symmetric_cipher = OID_AES128_CBC;
714 }
715 else if (strcaseeq("aes192-cbc", optarg))
716 {
717 pkcs7_symmetric_cipher = OID_AES192_CBC;
718 }
719 else if (strcaseeq("aes256-cbc", optarg))
720 {
721 pkcs7_symmetric_cipher = OID_AES256_CBC;
722 }
723 else
724 {
725 usage("invalid encryption algorithm specified");
726 }
727 continue;
728 #ifdef DEBUG
729 case 'A': /* --debug-all */
730 base_debugging |= DBG_ALL;
731 continue;
732 case 'P': /* debug parsing */
733 base_debugging |= DBG_PARSING;
734 continue;
735 case 'R': /* debug raw */
736 base_debugging |= DBG_RAW;
737 continue;
738 case 'C': /* debug control */
739 base_debugging |= DBG_CONTROL;
740 continue;
741 case 'M': /* debug control more */
742 base_debugging |= DBG_CONTROLMORE;
743 continue;
744 case 'X': /* debug private */
745 base_debugging |= DBG_PRIVATE;
746 continue;
747 #endif
748 default:
749 usage("unknown option");
750 }
751 /* break from loop */
752 break;
753 }
754 cur_debugging = base_debugging;
755
756 init_log("scepclient");
757
758 /* load plugins, further infrastructure may need it */
759 lib->plugins->load(lib->plugins, IPSEC_PLUGINDIR,
760 lib->settings->get_str(lib->settings, "scepclient.load", PLUGINS));
761 print_plugins();
762
763 if ((filetype_out == 0) && (!request_ca_certificate))
764 {
765 usage ("--out filetype required");
766 }
767 if (request_ca_certificate && (filetype_out > 0 || filetype_in > 0))
768 {
769 usage("in CA certificate request, no other --in or --out option allowed");
770 }
771
772 /* check if url is given, if cert output defined */
773 if (((filetype_out & CERT) || request_ca_certificate) && !scep_url)
774 {
775 usage("URL of SCEP server required");
776 }
777
778 /* check for sanity of --in/--out */
779 if (!filetype_in && (filetype_in > filetype_out))
780 {
781 usage("cannot generate --out of given --in!");
782 }
783
784 /*
785 * input of PKCS#1 file
786 */
787 private_key = malloc_thing(RSA_private_key_t);
788
789 if (filetype_in & PKCS1) /* load an RSA key pair from file */
790 {
791 prompt_pass_t pass = { "", FALSE, STDIN_FILENO };
792 char *path = concatenate_paths(PRIVATE_KEY_PATH, file_in_pkcs1);
793
794 ugh = load_rsa_private_key(path, &pass, private_key);
795 }
796 else /* generate an RSA key pair */
797 {
798 ugh = generate_rsa_private_key(rsa_keylength, private_key);
799 }
800 if (ugh != NULL)
801 exit_scepclient(ugh);
802
803 /* check for minimum key length */
804 if ((private_key->pub.k) < RSA_MIN_OCTETS)
805 {
806 exit_scepclient("length of RSA key has to be at least %d bits"
807 ,RSA_MIN_OCTETS * BITS_PER_BYTE);
808 }
809
810 /*
811 * input of PKCS#10 file
812 */
813 if (filetype_in & PKCS10)
814 {
815 /* user wants to load a pkcs10 request
816 * operation is not yet supported
817 * would require a PKCS#10 parsing function
818
819 pkcs10 = pkcs10_read_from_file(file_in_pkcs10);
820
821 */
822 }
823 else
824 {
825 char buf[IDTOA_BUF];
826 chunk_t dn = chunk_empty;
827
828 dn.ptr = buf;
829
830 if (distinguishedName == NULL)
831 {
832 char buf[BUF_LEN];
833 int n = sprintf(buf, DEFAULT_DN);
834
835 /* set the common name to the hostname */
836 if (gethostname(buf + n, BUF_LEN - n) || strlen(buf) == n)
837 {
838 exit_scepclient("no hostname defined, use "
839 "--dn <distinguished name> option");
840 }
841 distinguishedName = buf;
842 }
843
844 DBG(DBG_CONTROL,
845 DBG_log("dn: '%s'", distinguishedName);
846 )
847 ugh = atodn(distinguishedName, &dn);
848 if (ugh != NULL)
849 {
850 exit_scepclient(ugh);
851 }
852
853 subject = chunk_clone(dn);
854
855 DBG(DBG_CONTROL,
856 DBG_log("building pkcs10 object:")
857 )
858 pkcs10 = pkcs10_build(private_key, subject, challengePassword
859 , subjectAltNames, pkcs10_signature_alg);
860 scep_generate_pkcs10_fingerprint(pkcs10->request, &fingerprint);
861 plog(" fingerprint: %.*s", (int)fingerprint.len, fingerprint.ptr);
862 }
863
864 /*
865 * output of PKCS#10 file
866 */
867 if (filetype_out & PKCS10)
868 {
869 char *path = concatenate_paths(REQ_PATH, file_out_pkcs10);
870
871 if (!chunk_write(pkcs10->request, path, "pkcs10", 0022, force))
872 exit_scepclient("could not write pkcs10 file '%s'", path);
873
874 filetype_out &= ~PKCS10; /* delete PKCS10 flag */
875 }
876
877 if (!filetype_out)
878 {
879 exit_scepclient(NULL); /* no further output required */
880 }
881
882 /*
883 * output of PKCS#1 file
884 */
885 if (filetype_out & PKCS1)
886 {
887 char *path = concatenate_paths(PRIVATE_KEY_PATH, file_out_pkcs1);
888
889 DBG(DBG_CONTROL,
890 DBG_log("building pkcs1 object:")
891 )
892 pkcs1 = pkcs1_build_private_key(private_key);
893
894 if (!chunk_write(pkcs1, path, "pkcs1", 0066, force))
895 exit_scepclient("could not write pkcs1 file '%s'", path);
896
897 filetype_out &= ~PKCS1; /* delete PKCS1 flag */
898 }
899
900 if (!filetype_out)
901 {
902 exit_scepclient(NULL); /* no further output required */
903 }
904
905 scep_generate_transaction_id((const RSA_public_key_t *)private_key
906 , &transID, &serialNumber);
907 plog(" transaction ID: %.*s", (int)transID.len, transID.ptr);
908
909 /* generate a self-signed X.509 certificate */
910 x509_signer = malloc_thing(x509cert_t);
911 *x509_signer = empty_x509cert;
912 x509_signer->serialNumber = serialNumber;
913 x509_signer->sigAlg = OID_SHA1_WITH_RSA;
914 x509_signer->issuer = subject;
915 x509_signer->notBefore = (notBefore)? notBefore
916 : time(NULL);
917 x509_signer->notAfter = (notAfter)? notAfter
918 : x509_signer->notBefore + validity;
919 x509_signer->subject = subject;
920 x509_signer->subjectAltName = subjectAltNames;
921
922 build_x509cert(x509_signer, (const RSA_public_key_t *)private_key
923 , private_key);
924
925 /*
926 * output of self-signed X.509 certificate file
927 */
928 if (filetype_out & CERT_SELF)
929 {
930 char *path = concatenate_paths(HOST_CERT_PATH, file_out_cert_self);
931
932 if (!chunk_write(x509_signer->certificate, path, "self-signed cert", 0022, force))
933 exit_scepclient("could not write self-signed cert file '%s'", path);
934 ;
935 filetype_out &= ~CERT_SELF; /* delete CERT_SELF flag */
936 }
937
938 if (!filetype_out)
939 {
940 exit_scepclient(NULL); /* no further output required */
941 }
942
943 /*
944 * load ca encryption certificate
945 */
946 {
947 char *path = concatenate_paths(CA_CERT_PATH, file_in_cacert_enc);
948 cert_t cert;
949
950 if (!load_cert(path, "encryption cacert", &cert))
951 {
952 exit_scepclient("could not load encryption cacert file '%s'", path);
953 }
954 x509_ca_enc = cert.u.x509;
955 }
956
957 /*
958 * input of PKCS#7 file
959 */
960 if (filetype_in & PKCS7)
961 {
962 /* user wants to load a pkcs7 encrypted request
963 * operation is not yet supported!
964 * would require additional parsing of transaction-id
965
966 pkcs7 = pkcs7_read_from_file(file_in_pkcs7);
967
968 */
969 }
970 else
971 {
972 DBG(DBG_CONTROL,
973 DBG_log("building pkcs7 request")
974 )
975 pkcs7 = scep_build_request(pkcs10->request
976 , transID, SCEP_PKCSReq_MSG
977 , x509_ca_enc, pkcs7_symmetric_cipher
978 , x509_signer, pkcs7_digest_alg, private_key);
979 }
980
981 /*
982 * output pkcs7 encrypted and signed certificate request
983 */
984 if (filetype_out & PKCS7)
985 {
986 char *path = concatenate_paths(REQ_PATH, file_out_pkcs7);
987
988 if (!chunk_write(pkcs7, path, "pkcs7 encrypted request", 0022, force))
989 exit_scepclient("could not write pkcs7 file '%s'", path);
990 ;
991 filetype_out &= ~PKCS7; /* delete PKCS7 flag */
992 }
993
994 if (!filetype_out)
995 {
996 exit_scepclient(NULL); /* no further output required */
997 }
998
999 /*
1000 * output certificate fetch from SCEP server
1001 */
1002 if (filetype_out & CERT)
1003 {
1004 char *path = concatenate_paths(CA_CERT_PATH, file_in_cacert_sig);
1005 cert_t cert;
1006 time_t poll_start;
1007
1008 x509cert_t *certs = NULL;
1009 chunk_t envelopedData = chunk_empty;
1010 chunk_t certData = chunk_empty;
1011 contentInfo_t data = empty_contentInfo;
1012 scep_attributes_t attrs = empty_scep_attributes;
1013
1014 if (!load_cert(path, "signature cacert", &cert))
1015 exit_scepclient("could not load signature cacert file '%s'", path);
1016 x509_ca_sig = cert.u.x509;
1017
1018 if (!scep_http_request(scep_url, pkcs7, SCEP_PKI_OPERATION,
1019 http_get_request, &scep_response))
1020 {
1021 exit_scepclient("did not receive a valid scep response");
1022 }
1023 ugh = scep_parse_response(scep_response, transID, &data, &attrs
1024 , x509_ca_sig);
1025 if (ugh != NULL)
1026 {
1027 exit_scepclient(ugh);
1028 }
1029
1030 /* in case of manual mode, we are going into a polling loop */
1031 if (attrs.pkiStatus == SCEP_PENDING)
1032 {
1033 plog(" scep request pending, polling every %d seconds"
1034 , poll_interval);
1035 time(&poll_start);
1036 issuerAndSubject = asn1_wrap(ASN1_SEQUENCE, "cc"
1037 , x509_ca_sig->subject
1038 , subject);
1039 }
1040 while (attrs.pkiStatus == SCEP_PENDING)
1041 {
1042 if (max_poll_time > 0
1043 && (time(NULL) - poll_start >= max_poll_time))
1044 {
1045 exit_scepclient("maximum poll time reached: %d seconds"
1046 , max_poll_time);
1047 }
1048 DBG(DBG_CONTROL,
1049 DBG_log("going to sleep for %d seconds", poll_interval)
1050 )
1051 sleep(poll_interval);
1052 free(scep_response.ptr);
1053
1054 DBG(DBG_CONTROL,
1055 DBG_log("fingerprint: %.*s", (int)fingerprint.len, fingerprint.ptr);
1056 DBG_log("transaction ID: %.*s", (int)transID.len, transID.ptr)
1057 )
1058
1059 chunk_free(&getCertInitial);
1060 getCertInitial = scep_build_request(issuerAndSubject
1061 , transID, SCEP_GetCertInitial_MSG
1062 , x509_ca_enc, pkcs7_symmetric_cipher
1063 , x509_signer, pkcs7_digest_alg, private_key);
1064
1065 if (!scep_http_request(scep_url, getCertInitial, SCEP_PKI_OPERATION,
1066 http_get_request, &scep_response))
1067 {
1068 exit_scepclient("did not receive a valid scep response");
1069 }
1070 ugh = scep_parse_response(scep_response, transID, &data, &attrs
1071 , x509_ca_sig);
1072 if (ugh != NULL)
1073 {
1074 exit_scepclient(ugh);
1075 }
1076 }
1077
1078 if (attrs.pkiStatus != SCEP_SUCCESS)
1079 {
1080 exit_scepclient("reply status is not 'SUCCESS'");
1081 }
1082
1083 envelopedData = data.content;
1084
1085 if (data.type != OID_PKCS7_DATA
1086 || !asn1_parse_simple_object(&envelopedData, ASN1_OCTET_STRING, 0, "data"))
1087 {
1088 exit_scepclient("contentInfo is not of type 'data'");
1089 }
1090 if (!pkcs7_parse_envelopedData(envelopedData, &certData
1091 , serialNumber, private_key))
1092 {
1093 exit_scepclient("could not decrypt envelopedData");
1094 }
1095 if (!pkcs7_parse_signedData(certData, NULL, &certs, NULL, NULL))
1096 {
1097 exit_scepclient("error parsing the scep response");
1098 }
1099 chunk_free(&certData);
1100
1101 /* store the end entity certificate */
1102 path = concatenate_paths(HOST_CERT_PATH, file_out_cert);
1103 while (certs != NULL)
1104 {
1105 bool stored = FALSE;
1106 x509cert_t *cert = certs;
1107
1108 if (!cert->isCA)
1109 {
1110 if (stored)
1111 exit_scepclient("multiple certs received, only first stored");
1112 if (!chunk_write(cert->certificate, path, "requested cert", 0022, force))
1113 exit_scepclient("could not write cert file '%s'", path);
1114 stored = TRUE;
1115 }
1116 certs = certs->next;
1117 free_x509cert(cert);
1118 }
1119 filetype_out &= ~CERT; /* delete CERT flag */
1120 }
1121
1122 exit_scepclient(NULL);
1123 return -1; /* should never be reached */
1124 }
1125
1126