pluto and scepclient use the curl and ldap fetcher plugins
[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 #include <library.h>
39 #include <debug.h>
40 #include <asn1/asn1.h>
41 #include <asn1/oid.h>
42 #include <utils/optionsfrom.h>
43 #include <utils/enumerator.h>
44
45 #include "../pluto/constants.h"
46 #include "../pluto/defs.h"
47 #include "../pluto/log.h"
48 #include "../pluto/pkcs1.h"
49 #include "../pluto/pkcs7.h"
50 #include "../pluto/certs.h"
51 #include "../pluto/rnd.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 (default: 3des-cbc)\n"
253 "\n"
254 "Options for enrollment (cert):\n"
255 " --url (-u) <url> url of the SCEP server\n"
256 " --method (-m) post | get http request type\n"
257 " --interval (-t) <seconds> manual mode poll interval in seconds (default 20s)\n"
258 " --maxpolltime (-x) <seconds> max poll time in seconds when in manual mode\n"
259 " (default: unlimited)\n"
260 #ifdef DEBUG
261 "\n"
262 "Debugging output:\n"
263 " --debug-all (-A) show everything except private\n"
264 " --debug-parsing (-P) show parsing relevant stuff\n"
265 " --debug-raw (-R) show raw hex dumps\n"
266 " --debug-control (-C) show control flow output\n"
267 " --debug-controlmore (-M) show more control flow\n"
268 " --debug-private (-X) show sensitive data (private keys, etc.)\n"
269 #endif
270 );
271 exit_scepclient(message);
272 }
273
274 /**
275 * Log loaded plugins
276 */
277 static void print_plugins()
278 {
279 char buf[BUF_LEN], *plugin;
280 int len = 0;
281 enumerator_t *enumerator;
282
283 enumerator = lib->plugins->create_plugin_enumerator(lib->plugins);
284 while (len < BUF_LEN && enumerator->enumerate(enumerator, &plugin))
285 {
286 len += snprintf(&buf[len], BUF_LEN-len, "%s ", plugin);
287 }
288 enumerator->destroy(enumerator);
289 DBG1(" loaded plugins: %s", buf);
290 }
291
292 /**
293 * @brief main of scepclient
294 *
295 * @param argc number of arguments
296 * @param argv pointer to the argument values
297 */
298 int main(int argc, char **argv)
299 {
300 /* external values */
301 extern char * optarg;
302 extern int optind;
303
304 /* type of input and output files */
305 typedef enum {
306 PKCS1 = 0x01,
307 PKCS10 = 0x02,
308 PKCS7 = 0x04,
309 CERT_SELF = 0x08,
310 CERT = 0x10,
311 CACERT_ENC = 0x20,
312 CACERT_SIG = 0x40
313 } scep_filetype_t;
314
315 /* filetype to read from, defaults to "generate a key" */
316 scep_filetype_t filetype_in = 0;
317
318 /* filetype to write to, no default here */
319 scep_filetype_t filetype_out = 0;
320
321 /* input files */
322 char *file_in_pkcs1 = DEFAULT_FILENAME_PKCS1;
323 char *file_in_cacert_enc = DEFAULT_FILENAME_CACERT_ENC;
324 char *file_in_cacert_sig = DEFAULT_FILENAME_CACERT_SIG;
325
326 /* output files */
327 char *file_out_pkcs1 = DEFAULT_FILENAME_PKCS1;
328 char *file_out_pkcs10 = DEFAULT_FILENAME_PKCS10;
329 char *file_out_pkcs7 = DEFAULT_FILENAME_PKCS7;
330 char *file_out_cert_self = DEFAULT_FILENAME_CERT_SELF;
331 char *file_out_cert = DEFAULT_FILENAME_CERT;
332 char *file_out_prefix_cacert = DEFAULT_FILENAME_PREFIX_CACERT;
333
334 /* by default user certificate is requested */
335 bool request_ca_certificate = FALSE;
336
337 /* by default existing files are not overwritten */
338 bool force = FALSE;
339
340 /* length of RSA key in bits */
341 u_int rsa_keylength = DEFAULT_RSA_KEY_LENGTH;
342
343 /* validity of self-signed certificate */
344 time_t validity = DEFAULT_CERT_VALIDITY;
345 time_t notBefore = 0;
346 time_t notAfter = 0;
347
348 /* distinguished name for requested certificate, ASCII format */
349 char *distinguishedName = NULL;
350
351 /* challenge password */
352 char challenge_password_buffer[MAX_PASSWORD_LENGTH];
353
354 /* symmetric encryption algorithm used by pkcs7, default is 3DES */
355 int pkcs7_symmetric_cipher = OID_3DES_EDE_CBC;
356
357 /* digest algorithm used by pkcs7, default is SHA-1 */
358 int pkcs7_digest_alg = OID_SHA1;
359
360 /* signature algorithm used by pkcs10, default is SHA-1 with RSA encryption */
361 int pkcs10_signature_alg = OID_SHA1;
362
363 /* URL of the SCEP-Server */
364 char *scep_url = NULL;
365
366 /* http request method, default is GET */
367 bool http_get_request = TRUE;
368
369 /* poll interval time in manual mode in seconds */
370 u_int poll_interval = DEFAULT_POLL_INTERVAL;
371
372 /* maximum poll time */
373 u_int max_poll_time = 0;
374
375 err_t ugh = NULL;
376
377 /* initialize global variables */
378 pkcs1 = chunk_empty;
379 pkcs7 = chunk_empty;
380 serialNumber = chunk_empty;
381 transID = chunk_empty;
382 fingerprint = chunk_empty;
383 issuerAndSubject = chunk_empty;
384 challengePassword = chunk_empty;
385 getCertInitial = chunk_empty;
386 scep_response = chunk_empty;
387 log_to_stderr = TRUE;
388
389 /* initialize library and optionsfrom */
390 library_init(STRONGSWAN_CONF);
391 options = options_create();
392
393 for (;;)
394 {
395 static const struct option long_opts[] = {
396 /* name, has_arg, flag, val */
397 { "help", no_argument, NULL, 'h' },
398 { "version", no_argument, NULL, 'v' },
399 { "optionsfrom", required_argument, NULL, '+' },
400 { "quiet", no_argument, NULL, 'q' },
401 { "in", required_argument, NULL, 'i' },
402 { "out", required_argument, NULL, 'o' },
403 { "force", no_argument, NULL, 'f' },
404 { "keylength", required_argument, NULL, 'k' },
405 { "dn", required_argument, NULL, 'd' },
406 { "days", required_argument, NULL, 'D' },
407 { "startdate", required_argument, NULL, 'S' },
408 { "enddate", required_argument, NULL, 'E' },
409 { "subjectAltName", required_argument, NULL, 's' },
410 { "password", required_argument, NULL, 'p' },
411 { "algorithm", required_argument, NULL, 'a' },
412 { "url", required_argument, NULL, 'u' },
413 { "method", required_argument, NULL, 'm' },
414 { "interval", required_argument, NULL, 't' },
415 { "maxpolltime", required_argument, NULL, 'x' },
416 #ifdef DEBUG
417 { "debug-all", no_argument, NULL, 'A' },
418 { "debug-parsing", no_argument, NULL, 'P'},
419 { "debug-raw", no_argument, NULL, 'R'},
420 { "debug-control", no_argument, NULL, 'C'},
421 { "debug-controlmore", no_argument, NULL, 'M'},
422 { "debug-private", no_argument, NULL, 'X'},
423 #endif
424 { 0,0,0,0 }
425 };
426
427 /* parse next option */
428 int c = getopt_long(argc, argv, "hv+:qi:o:fk:d:s:p:a:u:m:t:x:APRCMS", long_opts, NULL);
429
430 switch (c)
431 {
432 case EOF: /* end of flags */
433 break;
434
435 case 'h': /* --help */
436 usage(NULL);
437
438 case 'v': /* --version */
439 version();
440
441 case 'q': /* --quiet */
442 log_to_stderr = FALSE;
443 continue;
444
445 case 'i': /* --in <type> [= <filename>] */
446 {
447 char *filename = strstr(optarg, "=");
448
449 if (filename)
450 {
451 /* replace '=' by '\0' */
452 *filename = '\0';
453 /* set pointer to start of filename */
454 filename++;
455 }
456 if (strcaseeq("pkcs1", optarg))
457 {
458 filetype_in |= PKCS1;
459 if (filename)
460 file_in_pkcs1 = filename;
461 }
462 else if (strcaseeq("cacert-enc", optarg))
463 {
464 filetype_in |= CACERT_ENC;
465 if (filename)
466 file_in_cacert_enc = filename;
467 }
468 else if (strcaseeq("cacert-sig", optarg))
469 {
470 filetype_in |= CACERT_SIG;
471 if (filename)
472 file_in_cacert_sig = filename;
473 }
474 else
475 {
476 usage("invalid --in file type");
477 }
478 continue;
479 }
480
481 case 'o': /* --out <type> [= <filename>] */
482 {
483 char *filename = strstr(optarg, "=");
484
485 if (filename)
486 {
487 /* replace '=' by '\0' */
488 *filename = '\0';
489 /* set pointer to start of filename */
490 filename++;
491 }
492 if (strcaseeq("pkcs1", optarg))
493 {
494 filetype_out |= PKCS1;
495 if (filename)
496 file_out_pkcs1 = filename;
497 }
498 else if (strcaseeq("pkcs10", optarg))
499 {
500 filetype_out |= PKCS10;
501 if (filename)
502 file_out_pkcs10 = filename;
503 }
504 else if (strcaseeq("pkcs7", optarg))
505 {
506 filetype_out |= PKCS7;
507 if (filename)
508 file_out_pkcs7 = filename;
509 }
510 else if (strcaseeq("cert-self", optarg))
511 {
512 filetype_out |= CERT_SELF;
513 if (filename)
514 file_out_cert_self = filename;
515 }
516 else if (strcaseeq("cert", optarg))
517 {
518 filetype_out |= CERT;
519 if (filename)
520 file_out_cert = filename;
521 }
522 else if (strcaseeq("cacert", optarg))
523 {
524 request_ca_certificate = TRUE;
525 if (filename)
526 file_out_prefix_cacert = filename;
527 }
528 else
529 {
530 usage("invalid --out file type");
531 }
532 continue;
533 }
534
535 case 'f': /* --force */
536 force = TRUE;
537 continue;
538
539 case '+': /* --optionsfrom <filename> */
540 if (!options->from(options, optarg, &argc, &argv, optind))
541 {
542 exit_scepclient("optionsfrom failed");
543 }
544 continue;
545
546 case 'k': /* --keylength <length> */
547 {
548 div_t q;
549
550 rsa_keylength = atoi(optarg);
551 if (rsa_keylength == 0)
552 usage("invalid keylength");
553
554 /* check if key length is a multiple of 8 bits */
555 q = div(rsa_keylength, 2*BITS_PER_BYTE);
556 if (q.rem != 0)
557 {
558 exit_scepclient("keylength is not a multiple of %d bits!"
559 , 2*BITS_PER_BYTE);
560 }
561 continue;
562 }
563
564 case 'D': /* --days */
565 if (optarg == NULL || !isdigit(optarg[0]))
566 usage("missing number of days");
567 {
568 char *endptr;
569 long days = strtol(optarg, &endptr, 0);
570
571 if (*endptr != '\0' || endptr == optarg
572 || days <= 0)
573 usage("<days> must be a positive number");
574 validity = 24*3600*days;
575 }
576 continue;
577
578 case 'S': /* --startdate */
579 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
580 usage("date format must be YYMMDDHHMMSSZ");
581 {
582 chunk_t date = { optarg, 13 };
583 notBefore = asn1_to_time(&date, ASN1_UTCTIME);
584 }
585 continue;
586
587 case 'E': /* --enddate */
588 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
589 usage("date format must be YYMMDDHHMMSSZ");
590 {
591 chunk_t date = { optarg, 13 };
592 notAfter = asn1_to_time(&date, ASN1_UTCTIME);
593 }
594 continue;
595
596 case 'd': /* --dn */
597 if (distinguishedName)
598 usage("only one distinguished name allowed");
599 distinguishedName = optarg;
600 continue;
601
602 case 's': /* --subjectAltName */
603 {
604 generalNames_t kind;
605 char *value = strstr(optarg, "=");
606
607 if (value)
608 {
609 /* replace '=' by '\0' */
610 *value = '\0';
611 /* set pointer to start of value */
612 value++;
613 }
614
615 if (strcaseeq("email", optarg))
616 {
617 kind = GN_RFC822_NAME;
618 }
619 else if (strcaseeq("dns", optarg))
620 {
621 kind = GN_DNS_NAME;
622 }
623 else if (strcaseeq("ip", optarg))
624 {
625 kind = GN_IP_ADDRESS;
626 }
627 else
628 {
629 usage("invalid --subjectAltName type");
630 continue;
631 }
632 pkcs10_add_subjectAltName(&subjectAltNames, kind, value);
633 continue;
634 }
635
636 case 'p': /* --password */
637 if (challengePassword.len > 0)
638 {
639 usage("only one challenge password allowed");
640 }
641 if (strcaseeq("%prompt", optarg))
642 {
643 printf("Challenge password: ");
644 if (fgets(challenge_password_buffer, sizeof(challenge_password_buffer)-1, stdin))
645 {
646 challengePassword.ptr = challenge_password_buffer;
647 /* discard the terminating '\n' from the input */
648 challengePassword.len = strlen(challenge_password_buffer) - 1;
649 }
650 else
651 {
652 usage("challenge password could not be read");
653 }
654 }
655 else
656 {
657 challengePassword.ptr = optarg;
658 challengePassword.len = strlen(optarg);
659 }
660 continue;
661
662 case 'u': /* -- url */
663 if (scep_url)
664 {
665 usage("only one URL argument allowed");
666 }
667 scep_url = optarg;
668 continue;
669
670 case 'm': /* --method */
671 if (strcaseeq("get", optarg))
672 {
673 http_get_request = TRUE;
674 }
675 else if (strcaseeq("post", optarg))
676 {
677 http_get_request = FALSE;
678 }
679 else
680 {
681 usage("invalid http request method specified");
682 }
683 continue;
684
685 case 't': /* --interval */
686 poll_interval = atoi(optarg);
687 if (poll_interval <= 0)
688 {
689 usage("invalid interval specified");
690 }
691 continue;
692
693 case 'x': /* --maxpolltime */
694 max_poll_time = atoi(optarg);
695 if (max_poll_time < 0)
696 {
697 usage("invalid maxpolltime specified");
698 }
699 continue;
700
701 case 'a': /*--algorithm */
702 if (strcaseeq("des-cbc", optarg))
703 {
704 pkcs7_symmetric_cipher = OID_DES_CBC;
705 }
706 else if (strcaseeq("3des-cbc", optarg))
707 {
708 pkcs7_symmetric_cipher = OID_3DES_EDE_CBC;
709 }
710 else
711 {
712 usage("invalid encryption algorithm specified");
713 }
714 continue;
715 #ifdef DEBUG
716 case 'A': /* --debug-all */
717 base_debugging |= DBG_ALL;
718 continue;
719 case 'P': /* debug parsing */
720 base_debugging |= DBG_PARSING;
721 continue;
722 case 'R': /* debug raw */
723 base_debugging |= DBG_RAW;
724 continue;
725 case 'C': /* debug control */
726 base_debugging |= DBG_CONTROL;
727 continue;
728 case 'M': /* debug control more */
729 base_debugging |= DBG_CONTROLMORE;
730 continue;
731 case 'X': /* debug private */
732 base_debugging |= DBG_PRIVATE;
733 continue;
734 #endif
735 default:
736 usage("unknown option");
737 }
738 /* break from loop */
739 break;
740 }
741 cur_debugging = base_debugging;
742
743 init_log("scepclient");
744
745 /* load plugins, further infrastructure may need it */
746 lib->plugins->load(lib->plugins, IPSEC_PLUGINDIR,
747 lib->settings->get_str(lib->settings, "scepclient.load", PLUGINS));
748 print_plugins();
749
750 init_rnd_pool();
751 init_fetch();
752
753 if ((filetype_out == 0) && (!request_ca_certificate))
754 {
755 usage ("--out filetype required");
756 }
757 if (request_ca_certificate && (filetype_out > 0 || filetype_in > 0))
758 {
759 usage("in CA certificate request, no other --in or --out option allowed");
760 }
761
762 /* check if url is given, if cert output defined */
763 if (((filetype_out & CERT) || request_ca_certificate) && !scep_url)
764 {
765 usage("URL of SCEP server required");
766 }
767
768 /* check for sanity of --in/--out */
769 if (!filetype_in && (filetype_in > filetype_out))
770 {
771 usage("cannot generate --out of given --in!");
772 }
773
774 /*
775 * input of PKCS#1 file
776 */
777 private_key = malloc_thing(RSA_private_key_t);
778
779 if (filetype_in & PKCS1) /* load an RSA key pair from file */
780 {
781 prompt_pass_t pass = { "", FALSE, STDIN_FILENO };
782 char *path = concatenate_paths(PRIVATE_KEY_PATH, file_in_pkcs1);
783
784 ugh = load_rsa_private_key(path, &pass, private_key);
785 }
786 else /* generate an RSA key pair */
787 {
788 ugh = generate_rsa_private_key(rsa_keylength, private_key);
789 }
790 if (ugh != NULL)
791 exit_scepclient(ugh);
792
793 /* check for minimum key length */
794 if ((private_key->pub.k) < RSA_MIN_OCTETS)
795 {
796 exit_scepclient("length of RSA key has to be at least %d bits"
797 ,RSA_MIN_OCTETS * BITS_PER_BYTE);
798 }
799
800 /*
801 * input of PKCS#10 file
802 */
803 if (filetype_in & PKCS10)
804 {
805 /* user wants to load a pkcs10 request
806 * operation is not yet supported
807 * would require a PKCS#10 parsing function
808
809 pkcs10 = pkcs10_read_from_file(file_in_pkcs10);
810
811 */
812 }
813 else
814 {
815 char buf[IDTOA_BUF];
816 chunk_t dn = chunk_empty;
817
818 dn.ptr = buf;
819
820 if (distinguishedName == NULL)
821 {
822 char buf[BUF_LEN];
823 int n = sprintf(buf, DEFAULT_DN);
824
825 /* set the common name to the hostname */
826 if (gethostname(buf + n, BUF_LEN - n) || strlen(buf) == n)
827 {
828 exit_scepclient("no hostname defined, use "
829 "--dn <distinguished name> option");
830 }
831 distinguishedName = buf;
832 }
833
834 DBG(DBG_CONTROL,
835 DBG_log("dn: '%s'", distinguishedName);
836 )
837 ugh = atodn(distinguishedName, &dn);
838 if (ugh != NULL)
839 {
840 exit_scepclient(ugh);
841 }
842
843 subject = chunk_clone(dn);
844
845 DBG(DBG_CONTROL,
846 DBG_log("building pkcs10 object:")
847 )
848 pkcs10 = pkcs10_build(private_key, subject, challengePassword
849 , subjectAltNames, pkcs10_signature_alg);
850 scep_generate_pkcs10_fingerprint(pkcs10->request, &fingerprint);
851 plog(" fingerprint: %.*s", (int)fingerprint.len, fingerprint.ptr);
852 }
853
854 /*
855 * output of PKCS#10 file
856 */
857 if (filetype_out & PKCS10)
858 {
859 char *path = concatenate_paths(REQ_PATH, file_out_pkcs10);
860
861 if (!chunk_write(pkcs10->request, path, "pkcs10", 0022, force))
862 exit_scepclient("could not write pkcs10 file '%s'", path);
863
864 filetype_out &= ~PKCS10; /* delete PKCS10 flag */
865 }
866
867 if (!filetype_out)
868 {
869 exit_scepclient(NULL); /* no further output required */
870 }
871
872 /*
873 * output of PKCS#1 file
874 */
875 if (filetype_out & PKCS1)
876 {
877 char *path = concatenate_paths(PRIVATE_KEY_PATH, file_out_pkcs1);
878
879 DBG(DBG_CONTROL,
880 DBG_log("building pkcs1 object:")
881 )
882 pkcs1 = pkcs1_build_private_key(private_key);
883
884 if (!chunk_write(pkcs1, path, "pkcs1", 0066, force))
885 exit_scepclient("could not write pkcs1 file '%s'", path);
886
887 filetype_out &= ~PKCS1; /* delete PKCS1 flag */
888 }
889
890 if (!filetype_out)
891 {
892 exit_scepclient(NULL); /* no further output required */
893 }
894
895 scep_generate_transaction_id((const RSA_public_key_t *)private_key
896 , &transID, &serialNumber);
897 plog(" transaction ID: %.*s", (int)transID.len, transID.ptr);
898
899 /* generate a self-signed X.509 certificate */
900 x509_signer = malloc_thing(x509cert_t);
901 *x509_signer = empty_x509cert;
902 x509_signer->serialNumber = serialNumber;
903 x509_signer->sigAlg = OID_SHA1_WITH_RSA;
904 x509_signer->issuer = subject;
905 x509_signer->notBefore = (notBefore)? notBefore
906 : time(NULL);
907 x509_signer->notAfter = (notAfter)? notAfter
908 : x509_signer->notBefore + validity;
909 x509_signer->subject = subject;
910 x509_signer->subjectAltName = subjectAltNames;
911
912 build_x509cert(x509_signer, (const RSA_public_key_t *)private_key
913 , private_key);
914
915 /*
916 * output of self-signed X.509 certificate file
917 */
918 if (filetype_out & CERT_SELF)
919 {
920 char *path = concatenate_paths(HOST_CERT_PATH, file_out_cert_self);
921
922 if (!chunk_write(x509_signer->certificate, path, "self-signed cert", 0022, force))
923 exit_scepclient("could not write self-signed cert file '%s'", path);
924 ;
925 filetype_out &= ~CERT_SELF; /* delete CERT_SELF flag */
926 }
927
928 if (!filetype_out)
929 {
930 exit_scepclient(NULL); /* no further output required */
931 }
932
933 /*
934 * load ca encryption certificate
935 */
936 {
937 char *path = concatenate_paths(CA_CERT_PATH, file_in_cacert_enc);
938 cert_t cert;
939
940 if (!load_cert(path, "encryption cacert", &cert))
941 {
942 exit_scepclient("could not load encryption cacert file '%s'", path);
943 }
944 x509_ca_enc = cert.u.x509;
945 }
946
947 /*
948 * input of PKCS#7 file
949 */
950 if (filetype_in & PKCS7)
951 {
952 /* user wants to load a pkcs7 encrypted request
953 * operation is not yet supported!
954 * would require additional parsing of transaction-id
955
956 pkcs7 = pkcs7_read_from_file(file_in_pkcs7);
957
958 */
959 }
960 else
961 {
962 DBG(DBG_CONTROL,
963 DBG_log("building pkcs7 request")
964 )
965 pkcs7 = scep_build_request(pkcs10->request
966 , transID, SCEP_PKCSReq_MSG
967 , x509_ca_enc, pkcs7_symmetric_cipher
968 , x509_signer, pkcs7_digest_alg, private_key);
969 }
970
971 /*
972 * output pkcs7 encrypted and signed certificate request
973 */
974 if (filetype_out & PKCS7)
975 {
976 char *path = concatenate_paths(REQ_PATH, file_out_pkcs7);
977
978 if (!chunk_write(pkcs7, path, "pkcs7 encrypted request", 0022, force))
979 exit_scepclient("could not write pkcs7 file '%s'", path);
980 ;
981 filetype_out &= ~PKCS7; /* delete PKCS7 flag */
982 }
983
984 if (!filetype_out)
985 {
986 exit_scepclient(NULL); /* no further output required */
987 }
988
989 /*
990 * output certificate fetch from SCEP server
991 */
992 if (filetype_out & CERT)
993 {
994 char *path = concatenate_paths(CA_CERT_PATH, file_in_cacert_sig);
995 cert_t cert;
996 time_t poll_start;
997
998 x509cert_t *certs = NULL;
999 chunk_t envelopedData = chunk_empty;
1000 chunk_t certData = chunk_empty;
1001 contentInfo_t data = empty_contentInfo;
1002 scep_attributes_t attrs = empty_scep_attributes;
1003
1004 if (!load_cert(path, "signature cacert", &cert))
1005 exit_scepclient("could not load signature cacert file '%s'", path);
1006 x509_ca_sig = cert.u.x509;
1007
1008 if (!scep_http_request(scep_url, pkcs7, SCEP_PKI_OPERATION,
1009 http_get_request, &scep_response))
1010 {
1011 exit_scepclient("did not receive a valid scep response");
1012 }
1013 ugh = scep_parse_response(scep_response, transID, &data, &attrs
1014 , x509_ca_sig);
1015 if (ugh != NULL)
1016 {
1017 exit_scepclient(ugh);
1018 }
1019
1020 /* in case of manual mode, we are going into a polling loop */
1021 if (attrs.pkiStatus == SCEP_PENDING)
1022 {
1023 plog(" scep request pending, polling every %d seconds"
1024 , poll_interval);
1025 time(&poll_start);
1026 issuerAndSubject = asn1_wrap(ASN1_SEQUENCE, "cc"
1027 , x509_ca_sig->subject
1028 , subject);
1029 }
1030 while (attrs.pkiStatus == SCEP_PENDING)
1031 {
1032 if (max_poll_time > 0
1033 && (time(NULL) - poll_start >= max_poll_time))
1034 {
1035 exit_scepclient("maximum poll time reached: %d seconds"
1036 , max_poll_time);
1037 }
1038 DBG(DBG_CONTROL,
1039 DBG_log("going to sleep for %d seconds", poll_interval)
1040 )
1041 sleep(poll_interval);
1042 free(scep_response.ptr);
1043
1044 DBG(DBG_CONTROL,
1045 DBG_log("fingerprint: %.*s", (int)fingerprint.len, fingerprint.ptr);
1046 DBG_log("transaction ID: %.*s", (int)transID.len, transID.ptr)
1047 )
1048
1049 chunk_free(&getCertInitial);
1050 getCertInitial = scep_build_request(issuerAndSubject
1051 , transID, SCEP_GetCertInitial_MSG
1052 , x509_ca_enc, pkcs7_symmetric_cipher
1053 , x509_signer, pkcs7_digest_alg, private_key);
1054
1055 if (!scep_http_request(scep_url, getCertInitial, SCEP_PKI_OPERATION,
1056 http_get_request, &scep_response))
1057 {
1058 exit_scepclient("did not receive a valid scep response");
1059 }
1060 ugh = scep_parse_response(scep_response, transID, &data, &attrs
1061 , x509_ca_sig);
1062 if (ugh != NULL)
1063 {
1064 exit_scepclient(ugh);
1065 }
1066 }
1067
1068 if (attrs.pkiStatus != SCEP_SUCCESS)
1069 {
1070 exit_scepclient("reply status is not 'SUCCESS'");
1071 }
1072
1073 envelopedData = data.content;
1074
1075 if (data.type != OID_PKCS7_DATA
1076 || !asn1_parse_simple_object(&envelopedData, ASN1_OCTET_STRING, 0, "data"))
1077 {
1078 exit_scepclient("contentInfo is not of type 'data'");
1079 }
1080 if (!pkcs7_parse_envelopedData(envelopedData, &certData
1081 , serialNumber, private_key))
1082 {
1083 exit_scepclient("could not decrypt envelopedData");
1084 }
1085 if (!pkcs7_parse_signedData(certData, NULL, &certs, NULL, NULL))
1086 {
1087 exit_scepclient("error parsing the scep response");
1088 }
1089 chunk_free(&certData);
1090
1091 /* store the end entity certificate */
1092 path = concatenate_paths(HOST_CERT_PATH, file_out_cert);
1093 while (certs != NULL)
1094 {
1095 bool stored = FALSE;
1096 x509cert_t *cert = certs;
1097
1098 if (!cert->isCA)
1099 {
1100 if (stored)
1101 exit_scepclient("multiple certs received, only first stored");
1102 if (!chunk_write(cert->certificate, path, "requested cert", 0022, force))
1103 exit_scepclient("could not write cert file '%s'", path);
1104 stored = TRUE;
1105 }
1106 certs = certs->next;
1107 free_x509cert(cert);
1108 }
1109 filetype_out &= ~CERT; /* delete CERT flag */
1110 }
1111
1112 exit_scepclient(NULL);
1113 return -1; /* should never be reached */
1114 }
1115
1116