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