88dd28521202fee78fe48a56cded001f3134186d
[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
36 #include <freeswan.h>
37
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 #include <crypto/crypters/crypter.h>
45 #include <crypto/proposal/proposal_keywords.h>
46 #include <credentials/keys/private_key.h>
47 #include <credentials/keys/public_key.h>
48
49 #include "../pluto/constants.h"
50 #include "../pluto/defs.h"
51 #include "../pluto/log.h"
52 #include "../pluto/pkcs7.h"
53 #include "../pluto/certs.h"
54
55 #include "pkcs10.h"
56 #include "scep.h"
57
58 /*
59 * definition of some defaults
60 */
61
62 /* default name of DER-encoded PKCS#1 private key file */
63 #define DEFAULT_FILENAME_PKCS1 "myKey.der"
64
65 /* default name of DER-encoded PKCS#10 certificate request file */
66 #define DEFAULT_FILENAME_PKCS10 "myReq.der"
67
68 /* default name of DER-encoded PKCS#7 file */
69 #define DEFAULT_FILENAME_PKCS7 "pkcs7.der"
70
71 /* default name of DER-encoded self-signed X.509 certificate file */
72 #define DEFAULT_FILENAME_CERT_SELF "selfCert.der"
73
74 /* default name of DER-encoded X.509 certificate file */
75 #define DEFAULT_FILENAME_CERT "myCert.der"
76
77 /* default name of DER-encoded CA cert file used for key encipherment */
78 #define DEFAULT_FILENAME_CACERT_ENC "caCert.der"
79
80 /* default name of the der encoded CA cert file used for signature verification */
81 #define DEFAULT_FILENAME_CACERT_SIG "caCert.der"
82
83 /* default prefix of the der encoded CA certificates received from the SCEP server */
84 #define DEFAULT_FILENAME_PREFIX_CACERT "caCert.der"
85
86 /* default certificate validity */
87 #define DEFAULT_CERT_VALIDITY 5 * 3600 * 24 * 365 /* seconds */
88
89 /* default polling time interval in SCEP manual mode */
90 #define DEFAULT_POLL_INTERVAL 20 /* seconds */
91
92 /* default key length for self-generated RSA keys */
93 #define DEFAULT_RSA_KEY_LENGTH 2048 /* bits */
94
95 /* default distinguished name */
96 #define DEFAULT_DN "C=CH, O=Linux strongSwan, CN="
97
98 /* challenge password buffer size */
99 #define MAX_PASSWORD_LENGTH 256
100
101 /* Max length of filename for tempfile */
102 #define MAX_TEMP_FILENAME_LENGTH 256
103
104
105 /* current scepclient version */
106 static const char *scepclient_version = "1.0";
107
108 /* by default the CRL policy is lenient */
109 bool strict_crl_policy = FALSE;
110
111 /* by default pluto does not check crls dynamically */
112 long crl_check_interval = 0;
113
114 /* by default pluto logs out after every smartcard use */
115 bool pkcs11_keep_state = FALSE;
116
117 /* options read by optionsfrom */
118 options_t *options;
119
120 /*
121 * Global variables
122 */
123
124 private_key_t *private_key = NULL;
125 public_key_t *public_key = NULL;
126
127 chunk_t pkcs1;
128 chunk_t pkcs7;
129 chunk_t subject;
130 chunk_t challengePassword;
131 chunk_t serialNumber;
132 chunk_t transID;
133 chunk_t fingerprint;
134 chunk_t issuerAndSubject;
135 chunk_t getCertInitial;
136 chunk_t scep_response;
137 cert_t cert;
138
139 x509cert_t *x509_signer = NULL;
140 x509cert_t *x509_ca_enc = NULL;
141 x509cert_t *x509_ca_sig = NULL;
142 generalName_t *subjectAltNames = NULL;
143 pkcs10_t *pkcs10 = NULL;
144
145 /**
146 * @brief exit scepclient
147 *
148 * @param status 0 = OK, 1 = general discomfort
149 */
150 static void
151 exit_scepclient(err_t message, ...)
152 {
153 int status = 0;
154
155 DESTROY_IF(private_key);
156 DESTROY_IF(public_key);
157 free(pkcs1.ptr);
158 free(pkcs7.ptr);
159 free(subject.ptr);
160 free(serialNumber.ptr);
161 free(transID.ptr);
162 free(fingerprint.ptr);
163 free(issuerAndSubject.ptr);
164 free(getCertInitial.ptr);
165 free(scep_response.ptr);
166
167 free_generalNames(subjectAltNames, TRUE);
168 if (x509_signer != NULL)
169 {
170 x509_signer->subjectAltName = NULL;
171 }
172 free_x509cert(x509_signer);
173 free_x509cert(x509_ca_enc);
174 free_x509cert(x509_ca_sig);
175 pkcs10_free(pkcs10);
176 options->destroy(options);
177
178 /* print any error message to stderr */
179 if (message != NULL && *message != '\0')
180 {
181 va_list args;
182 char m[LOG_WIDTH]; /* longer messages will be truncated */
183
184 va_start(args, message);
185 vsnprintf(m, sizeof(m), message, args);
186 va_end(args);
187
188 fprintf(stderr, "error: %s\n", m);
189 status = -1;
190 }
191 library_deinit();
192 close_log();
193 exit(status);
194 }
195
196 /**
197 * @brief prints the program version and exits
198 *
199 */
200 static void
201 version(void)
202 {
203 printf("scepclient %s\n", scepclient_version);
204 exit_scepclient(NULL);
205 }
206
207 /**
208 * @brief prints the usage of the program to the stderr output
209 *
210 * If message is set, program is exitet with 1 (error)
211 * @param message message in case of an error
212 */
213 static void
214 usage(const char *message)
215 {
216 fprintf(stderr,
217 "Usage: scepclient\n"
218 " --help (-h) show usage and exit\n"
219 " --version (-v) show version and exit\n"
220 " --quiet (-q) do not write log output to stderr\n"
221 " --in (-i) <type>[=<filename>] use <filename> of <type> for input \n"
222 " <type> = pkcs1 | cacert-enc | cacert-sig\n"
223 " - if no pkcs1 input is defined, a \n"
224 " RSA key will be generated\n"
225 " - if no filename is given, default is used\n"
226 " --out (-o) <type>[=<filename>] write output of <type> to <filename>\n"
227 " multiple outputs are allowed\n"
228 " <type> = pkcs1 | pkcs10 | pkcs7 | cert-self | cert | cacert\n"
229 " - type cacert defines filename prefix of\n"
230 " received CA certificate(s)\n"
231 " - if no filename is given, default is used\n"
232 " --optionsfrom (-+) <filename> reads additional options from given file\n"
233 " --force (-f) force existing file(s)\n"
234 "\n"
235 "Options for key generation (pkcs1):\n"
236 " --keylength (-k) <bits> key length for RSA key generation\n"
237 "(default: 2048 bits)\n"
238 "\n"
239 "Options for validity:\n"
240 " --days (-D) <days> validity in days\n"
241 " --startdate (-S) <YYMMDDHHMMSS>Z not valid before date\n"
242 " --enddate (-E) <YYMMDDHHMMSS>Z not valid after date\n"
243 "\n"
244 "Options for request generation (pkcs10):\n"
245 " --dn (-d) <dn> comma separated list of distinguished names\n"
246 " --subjectAltName (-s) <t>=<v> include subjectAltName in certificate request\n"
247 " <t> = email | dns | ip \n"
248 " --password (-p) <pw> challenge password\n"
249 " - if pw is '%%prompt', password gets prompted for\n"
250 " --algorithm (-a) <algo> use specified algorithm for PKCS#7 encryption\n"
251 " <algo> = des | 3des (default) | aes128| aes192 | \n"
252 " aes256 | camellia128 | camellia192 | camellia256\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 */
390 if (!library_init(STRONGSWAN_CONF))
391 {
392 library_deinit();
393 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
394 }
395
396 /* initialize optionsfrom */
397 options = options_create();
398
399 for (;;)
400 {
401 static const struct option long_opts[] = {
402 /* name, has_arg, flag, val */
403 { "help", no_argument, NULL, 'h' },
404 { "version", no_argument, NULL, 'v' },
405 { "optionsfrom", required_argument, NULL, '+' },
406 { "quiet", no_argument, NULL, 'q' },
407 { "in", required_argument, NULL, 'i' },
408 { "out", required_argument, NULL, 'o' },
409 { "force", no_argument, NULL, 'f' },
410 { "keylength", required_argument, NULL, 'k' },
411 { "dn", required_argument, NULL, 'd' },
412 { "days", required_argument, NULL, 'D' },
413 { "startdate", required_argument, NULL, 'S' },
414 { "enddate", required_argument, NULL, 'E' },
415 { "subjectAltName", required_argument, NULL, 's' },
416 { "password", required_argument, NULL, 'p' },
417 { "algorithm", required_argument, NULL, 'a' },
418 { "url", required_argument, NULL, 'u' },
419 { "method", required_argument, NULL, 'm' },
420 { "interval", required_argument, NULL, 't' },
421 { "maxpolltime", required_argument, NULL, 'x' },
422 #ifdef DEBUG
423 { "debug-all", no_argument, NULL, 'A' },
424 { "debug-parsing", no_argument, NULL, 'P'},
425 { "debug-raw", no_argument, NULL, 'R'},
426 { "debug-control", no_argument, NULL, 'C'},
427 { "debug-controlmore", no_argument, NULL, 'M'},
428 { "debug-private", no_argument, NULL, 'X'},
429 #endif
430 { 0,0,0,0 }
431 };
432
433 /* parse next option */
434 int c = getopt_long(argc, argv, "hv+:qi:o:fk:d:s:p:a:u:m:t:x:APRCMS", long_opts, NULL);
435
436 switch (c)
437 {
438 case EOF: /* end of flags */
439 break;
440
441 case 'h': /* --help */
442 usage(NULL);
443
444 case 'v': /* --version */
445 version();
446
447 case 'q': /* --quiet */
448 log_to_stderr = FALSE;
449 continue;
450
451 case 'i': /* --in <type> [= <filename>] */
452 {
453 char *filename = strstr(optarg, "=");
454
455 if (filename)
456 {
457 /* replace '=' by '\0' */
458 *filename = '\0';
459 /* set pointer to start of filename */
460 filename++;
461 }
462 if (strcaseeq("pkcs1", optarg))
463 {
464 filetype_in |= PKCS1;
465 if (filename)
466 file_in_pkcs1 = filename;
467 }
468 else if (strcaseeq("cacert-enc", optarg))
469 {
470 filetype_in |= CACERT_ENC;
471 if (filename)
472 file_in_cacert_enc = filename;
473 }
474 else if (strcaseeq("cacert-sig", optarg))
475 {
476 filetype_in |= CACERT_SIG;
477 if (filename)
478 file_in_cacert_sig = filename;
479 }
480 else
481 {
482 usage("invalid --in file type");
483 }
484 continue;
485 }
486
487 case 'o': /* --out <type> [= <filename>] */
488 {
489 char *filename = strstr(optarg, "=");
490
491 if (filename)
492 {
493 /* replace '=' by '\0' */
494 *filename = '\0';
495 /* set pointer to start of filename */
496 filename++;
497 }
498 if (strcaseeq("pkcs1", optarg))
499 {
500 filetype_out |= PKCS1;
501 if (filename)
502 file_out_pkcs1 = filename;
503 }
504 else if (strcaseeq("pkcs10", optarg))
505 {
506 filetype_out |= PKCS10;
507 if (filename)
508 file_out_pkcs10 = filename;
509 }
510 else if (strcaseeq("pkcs7", optarg))
511 {
512 filetype_out |= PKCS7;
513 if (filename)
514 file_out_pkcs7 = filename;
515 }
516 else if (strcaseeq("cert-self", optarg))
517 {
518 filetype_out |= CERT_SELF;
519 if (filename)
520 file_out_cert_self = filename;
521 }
522 else if (strcaseeq("cert", optarg))
523 {
524 filetype_out |= CERT;
525 if (filename)
526 file_out_cert = filename;
527 }
528 else if (strcaseeq("cacert", optarg))
529 {
530 request_ca_certificate = TRUE;
531 if (filename)
532 file_out_prefix_cacert = filename;
533 }
534 else
535 {
536 usage("invalid --out file type");
537 }
538 continue;
539 }
540
541 case 'f': /* --force */
542 force = TRUE;
543 continue;
544
545 case '+': /* --optionsfrom <filename> */
546 if (!options->from(options, optarg, &argc, &argv, optind))
547 {
548 exit_scepclient("optionsfrom failed");
549 }
550 continue;
551
552 case 'k': /* --keylength <length> */
553 {
554 div_t q;
555
556 rsa_keylength = atoi(optarg);
557 if (rsa_keylength == 0)
558 usage("invalid keylength");
559
560 /* check if key length is a multiple of 8 bits */
561 q = div(rsa_keylength, 2*BITS_PER_BYTE);
562 if (q.rem != 0)
563 {
564 exit_scepclient("keylength is not a multiple of %d bits!"
565 , 2*BITS_PER_BYTE);
566 }
567 continue;
568 }
569
570 case 'D': /* --days */
571 if (optarg == NULL || !isdigit(optarg[0]))
572 usage("missing number of days");
573 {
574 char *endptr;
575 long days = strtol(optarg, &endptr, 0);
576
577 if (*endptr != '\0' || endptr == optarg
578 || days <= 0)
579 usage("<days> must be a positive number");
580 validity = 24*3600*days;
581 }
582 continue;
583
584 case 'S': /* --startdate */
585 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
586 usage("date format must be YYMMDDHHMMSSZ");
587 {
588 chunk_t date = { optarg, 13 };
589 notBefore = asn1_to_time(&date, ASN1_UTCTIME);
590 }
591 continue;
592
593 case 'E': /* --enddate */
594 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
595 usage("date format must be YYMMDDHHMMSSZ");
596 {
597 chunk_t date = { optarg, 13 };
598 notAfter = asn1_to_time(&date, ASN1_UTCTIME);
599 }
600 continue;
601
602 case 'd': /* --dn */
603 if (distinguishedName)
604 usage("only one distinguished name allowed");
605 distinguishedName = optarg;
606 continue;
607
608 case 's': /* --subjectAltName */
609 {
610 generalNames_t kind;
611 char *value = strstr(optarg, "=");
612
613 if (value)
614 {
615 /* replace '=' by '\0' */
616 *value = '\0';
617 /* set pointer to start of value */
618 value++;
619 }
620
621 if (strcaseeq("email", optarg))
622 {
623 kind = GN_RFC822_NAME;
624 }
625 else if (strcaseeq("dns", optarg))
626 {
627 kind = GN_DNS_NAME;
628 }
629 else if (strcaseeq("ip", optarg))
630 {
631 kind = GN_IP_ADDRESS;
632 }
633 else
634 {
635 usage("invalid --subjectAltName type");
636 continue;
637 }
638 pkcs10_add_subjectAltName(&subjectAltNames, kind, value);
639 continue;
640 }
641
642 case 'p': /* --password */
643 if (challengePassword.len > 0)
644 {
645 usage("only one challenge password allowed");
646 }
647 if (strcaseeq("%prompt", optarg))
648 {
649 printf("Challenge password: ");
650 if (fgets(challenge_password_buffer, sizeof(challenge_password_buffer)-1, stdin))
651 {
652 challengePassword.ptr = challenge_password_buffer;
653 /* discard the terminating '\n' from the input */
654 challengePassword.len = strlen(challenge_password_buffer) - 1;
655 }
656 else
657 {
658 usage("challenge password could not be read");
659 }
660 }
661 else
662 {
663 challengePassword.ptr = optarg;
664 challengePassword.len = strlen(optarg);
665 }
666 continue;
667
668 case 'u': /* -- url */
669 if (scep_url)
670 {
671 usage("only one URL argument allowed");
672 }
673 scep_url = optarg;
674 continue;
675
676 case 'm': /* --method */
677 if (strcaseeq("get", optarg))
678 {
679 http_get_request = TRUE;
680 }
681 else if (strcaseeq("post", optarg))
682 {
683 http_get_request = FALSE;
684 }
685 else
686 {
687 usage("invalid http request method specified");
688 }
689 continue;
690
691 case 't': /* --interval */
692 poll_interval = atoi(optarg);
693 if (poll_interval <= 0)
694 {
695 usage("invalid interval specified");
696 }
697 continue;
698
699 case 'x': /* --maxpolltime */
700 max_poll_time = atoi(optarg);
701 if (max_poll_time < 0)
702 {
703 usage("invalid maxpolltime specified");
704 }
705 continue;
706
707 case 'a': /*--algorithm */
708 {
709 const proposal_token_t *token;
710
711 token = proposal_get_token(optarg, strlen(optarg));
712 if (token == NULL || token->type != ENCRYPTION_ALGORITHM)
713 {
714 usage("invalid algorithm specified");
715 }
716 pkcs7_symmetric_cipher = encryption_algorithm_to_oid(
717 token->algorithm, token->keysize);
718 if (pkcs7_symmetric_cipher == OID_UNKNOWN)
719 {
720 usage("unsupported encryption algorithm specified");
721 }
722 continue;
723 }
724 #ifdef DEBUG
725 case 'A': /* --debug-all */
726 base_debugging |= DBG_ALL;
727 continue;
728 case 'P': /* debug parsing */
729 base_debugging |= DBG_PARSING;
730 continue;
731 case 'R': /* debug raw */
732 base_debugging |= DBG_RAW;
733 continue;
734 case 'C': /* debug control */
735 base_debugging |= DBG_CONTROL;
736 continue;
737 case 'M': /* debug control more */
738 base_debugging |= DBG_CONTROLMORE;
739 continue;
740 case 'X': /* debug private */
741 base_debugging |= DBG_PRIVATE;
742 continue;
743 #endif
744 default:
745 usage("unknown option");
746 }
747 /* break from loop */
748 break;
749 }
750 cur_debugging = base_debugging;
751
752 init_log("scepclient");
753
754 /* load plugins, further infrastructure may need it */
755 lib->plugins->load(lib->plugins, IPSEC_PLUGINDIR,
756 lib->settings->get_str(lib->settings, "scepclient.load", PLUGINS));
757 print_plugins();
758
759 if ((filetype_out == 0) && (!request_ca_certificate))
760 {
761 usage ("--out filetype required");
762 }
763 if (request_ca_certificate && (filetype_out > 0 || filetype_in > 0))
764 {
765 usage("in CA certificate request, no other --in or --out option allowed");
766 }
767
768 /* check if url is given, if cert output defined */
769 if (((filetype_out & CERT) || request_ca_certificate) && !scep_url)
770 {
771 usage("URL of SCEP server required");
772 }
773
774 /* check for sanity of --in/--out */
775 if (!filetype_in && (filetype_in > filetype_out))
776 {
777 usage("cannot generate --out of given --in!");
778 }
779
780 /*
781 * input of PKCS#1 file
782 */
783 if (filetype_in & PKCS1) /* load an RSA key pair from file */
784 {
785 prompt_pass_t pass = { "", FALSE, STDIN_FILENO };
786 char *path = concatenate_paths(PRIVATE_KEY_PATH, file_in_pkcs1);
787
788 private_key = load_private_key(path, &pass, KEY_RSA);
789 }
790 else /* generate an RSA key pair */
791 {
792 private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
793 BUILD_KEY_SIZE, rsa_keylength,
794 BUILD_END);
795 }
796 if (private_key == NULL)
797 {
798 exit_scepclient("no RSA private key available");
799 }
800 public_key = private_key->get_public_key(private_key);
801
802 /* check for minimum key length */
803 if (private_key->get_keysize(private_key) < RSA_MIN_OCTETS)
804 {
805 exit_scepclient("length of RSA key has to be at least %d bits"
806 ,RSA_MIN_OCTETS * BITS_PER_BYTE);
807 }
808
809 /*
810 * input of PKCS#10 file
811 */
812 if (filetype_in & PKCS10)
813 {
814 /* user wants to load a pkcs10 request
815 * operation is not yet supported
816 * would require a PKCS#10 parsing function
817
818 pkcs10 = pkcs10_read_from_file(file_in_pkcs10);
819
820 */
821 }
822 else
823 {
824 char buf[IDTOA_BUF];
825 chunk_t dn = chunk_empty;
826
827 dn.ptr = buf;
828
829 if (distinguishedName == NULL)
830 {
831 char buf[BUF_LEN];
832 int n = sprintf(buf, DEFAULT_DN);
833
834 /* set the common name to the hostname */
835 if (gethostname(buf + n, BUF_LEN - n) || strlen(buf) == n)
836 {
837 exit_scepclient("no hostname defined, use "
838 "--dn <distinguished name> option");
839 }
840 distinguishedName = buf;
841 }
842
843 DBG(DBG_CONTROL,
844 DBG_log("dn: '%s'", distinguishedName);
845 )
846 ugh = atodn(distinguishedName, &dn);
847 if (ugh != NULL)
848 {
849 exit_scepclient(ugh);
850 }
851
852 subject = chunk_clone(dn);
853
854 DBG(DBG_CONTROL,
855 DBG_log("building pkcs10 object:")
856 )
857 pkcs10 = pkcs10_build(private_key, public_key, subject,
858 challengePassword, subjectAltNames,
859 pkcs10_signature_alg);
860 fingerprint = scep_generate_pkcs10_fingerprint(pkcs10->request);
861 plog(" fingerprint: %s", 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 = private_key->get_encoding(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(public_key, &transID, &serialNumber);
906 plog(" transaction ID: %.*s", (int)transID.len, transID.ptr);
907
908 /* generate a self-signed X.509 certificate */
909 x509_signer = malloc_thing(x509cert_t);
910 *x509_signer = empty_x509cert;
911 x509_signer->serialNumber = serialNumber;
912 x509_signer->sigAlg = OID_SHA1_WITH_RSA;
913 x509_signer->issuer = subject;
914 x509_signer->notBefore = (notBefore)? notBefore
915 : time(NULL);
916 x509_signer->notAfter = (notAfter)? notAfter
917 : x509_signer->notBefore + validity;
918 x509_signer->subject = subject;
919 x509_signer->subjectAltName = subjectAltNames;
920 build_x509cert(x509_signer, public_key, private_key);
921
922 /*
923 * output of self-signed X.509 certificate file
924 */
925 if (filetype_out & CERT_SELF)
926 {
927 char *path = concatenate_paths(HOST_CERT_PATH, file_out_cert_self);
928
929 if (!chunk_write(x509_signer->certificate, path, "self-signed cert", 0022, force))
930 exit_scepclient("could not write self-signed cert file '%s'", path);
931 ;
932 filetype_out &= ~CERT_SELF; /* delete CERT_SELF flag */
933 }
934
935 if (!filetype_out)
936 {
937 exit_scepclient(NULL); /* no further output required */
938 }
939
940 /*
941 * load ca encryption certificate
942 */
943 {
944 char *path = concatenate_paths(CA_CERT_PATH, file_in_cacert_enc);
945 cert_t cert;
946
947 if (!load_cert(path, "encryption cacert", &cert))
948 {
949 exit_scepclient("could not load encryption cacert file '%s'", path);
950 }
951 x509_ca_enc = cert.u.x509;
952 }
953
954 /*
955 * input of PKCS#7 file
956 */
957 if (filetype_in & PKCS7)
958 {
959 /* user wants to load a pkcs7 encrypted request
960 * operation is not yet supported!
961 * would require additional parsing of transaction-id
962
963 pkcs7 = pkcs7_read_from_file(file_in_pkcs7);
964
965 */
966 }
967 else
968 {
969 DBG(DBG_CONTROL,
970 DBG_log("building pkcs7 request")
971 )
972 pkcs7 = scep_build_request(pkcs10->request
973 , transID, SCEP_PKCSReq_MSG
974 , x509_ca_enc, pkcs7_symmetric_cipher
975 , x509_signer, pkcs7_digest_alg, private_key);
976 }
977
978 /*
979 * output pkcs7 encrypted and signed certificate request
980 */
981 if (filetype_out & PKCS7)
982 {
983 char *path = concatenate_paths(REQ_PATH, file_out_pkcs7);
984
985 if (!chunk_write(pkcs7, path, "pkcs7 encrypted request", 0022, force))
986 exit_scepclient("could not write pkcs7 file '%s'", path);
987 ;
988 filetype_out &= ~PKCS7; /* delete PKCS7 flag */
989 }
990
991 if (!filetype_out)
992 {
993 exit_scepclient(NULL); /* no further output required */
994 }
995
996 /*
997 * output certificate fetch from SCEP server
998 */
999 if (filetype_out & CERT)
1000 {
1001 char *path = concatenate_paths(CA_CERT_PATH, file_in_cacert_sig);
1002 cert_t cert;
1003 time_t poll_start;
1004
1005 x509cert_t *certs = NULL;
1006 chunk_t envelopedData = chunk_empty;
1007 chunk_t certData = chunk_empty;
1008 contentInfo_t data = empty_contentInfo;
1009 scep_attributes_t attrs = empty_scep_attributes;
1010
1011 if (!load_cert(path, "signature cacert", &cert))
1012 exit_scepclient("could not load signature cacert file '%s'", path);
1013 x509_ca_sig = cert.u.x509;
1014
1015 if (!scep_http_request(scep_url, pkcs7, SCEP_PKI_OPERATION,
1016 http_get_request, &scep_response))
1017 {
1018 exit_scepclient("did not receive a valid scep response");
1019 }
1020 ugh = scep_parse_response(scep_response, transID, &data, &attrs
1021 , x509_ca_sig);
1022 if (ugh != NULL)
1023 {
1024 exit_scepclient(ugh);
1025 }
1026
1027 /* in case of manual mode, we are going into a polling loop */
1028 if (attrs.pkiStatus == SCEP_PENDING)
1029 {
1030 plog(" scep request pending, polling every %d seconds"
1031 , poll_interval);
1032 time(&poll_start);
1033 issuerAndSubject = asn1_wrap(ASN1_SEQUENCE, "cc"
1034 , x509_ca_sig->subject
1035 , subject);
1036 }
1037 while (attrs.pkiStatus == SCEP_PENDING)
1038 {
1039 if (max_poll_time > 0
1040 && (time(NULL) - poll_start >= max_poll_time))
1041 {
1042 exit_scepclient("maximum poll time reached: %d seconds"
1043 , max_poll_time);
1044 }
1045 DBG(DBG_CONTROL,
1046 DBG_log("going to sleep for %d seconds", poll_interval)
1047 )
1048 sleep(poll_interval);
1049 free(scep_response.ptr);
1050
1051 DBG(DBG_CONTROL,
1052 DBG_log("fingerprint: %.*s", (int)fingerprint.len, fingerprint.ptr);
1053 DBG_log("transaction ID: %.*s", (int)transID.len, transID.ptr)
1054 )
1055
1056 chunk_free(&getCertInitial);
1057 getCertInitial = scep_build_request(issuerAndSubject
1058 , transID, SCEP_GetCertInitial_MSG
1059 , x509_ca_enc, pkcs7_symmetric_cipher
1060 , x509_signer, pkcs7_digest_alg, private_key);
1061
1062 if (!scep_http_request(scep_url, getCertInitial, SCEP_PKI_OPERATION,
1063 http_get_request, &scep_response))
1064 {
1065 exit_scepclient("did not receive a valid scep response");
1066 }
1067 ugh = scep_parse_response(scep_response, transID, &data, &attrs
1068 , x509_ca_sig);
1069 if (ugh != NULL)
1070 {
1071 exit_scepclient(ugh);
1072 }
1073 }
1074
1075 if (attrs.pkiStatus != SCEP_SUCCESS)
1076 {
1077 exit_scepclient("reply status is not 'SUCCESS'");
1078 }
1079
1080 envelopedData = data.content;
1081
1082 if (data.type != OID_PKCS7_DATA
1083 || !asn1_parse_simple_object(&envelopedData, ASN1_OCTET_STRING, 0, "data"))
1084 {
1085 exit_scepclient("contentInfo is not of type 'data'");
1086 }
1087 if (!pkcs7_parse_envelopedData(envelopedData, &certData
1088 , serialNumber, private_key))
1089 {
1090 exit_scepclient("could not decrypt envelopedData");
1091 }
1092 if (!pkcs7_parse_signedData(certData, NULL, &certs, NULL, NULL))
1093 {
1094 exit_scepclient("error parsing the scep response");
1095 }
1096 chunk_free(&certData);
1097
1098 /* store the end entity certificate */
1099 path = concatenate_paths(HOST_CERT_PATH, file_out_cert);
1100 while (certs != NULL)
1101 {
1102 bool stored = FALSE;
1103 x509cert_t *cert = certs;
1104
1105 if (!cert->isCA)
1106 {
1107 if (stored)
1108 exit_scepclient("multiple certs received, only first stored");
1109 if (!chunk_write(cert->certificate, path, "requested cert", 0022, force))
1110 exit_scepclient("could not write cert file '%s'", path);
1111 stored = TRUE;
1112 }
1113 certs = certs->next;
1114 free_x509cert(cert);
1115 }
1116 filetype_out &= ~CERT; /* delete CERT flag */
1117 }
1118
1119 exit_scepclient(NULL);
1120 return -1; /* should never be reached */
1121 }
1122
1123