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