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