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