2 * Copyright (C) 2012 Tobias Brunner
3 * Copyright (C) 2005 Jan Hutter, Martin Willi
4 * Hochschule fuer Technik Rapperswil
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
30 #include <utils/debug.h>
31 #include <asn1/asn1.h>
33 #include <utils/optionsfrom.h>
34 #include <collections/enumerator.h>
35 #include <collections/linked_list.h>
36 #include <crypto/hashers/hasher.h>
37 #include <crypto/crypters/crypter.h>
38 #include <crypto/proposal/proposal_keywords.h>
39 #include <credentials/keys/private_key.h>
40 #include <credentials/keys/public_key.h>
41 #include <credentials/certificates/certificate.h>
42 #include <credentials/certificates/x509.h>
43 #include <credentials/certificates/pkcs10.h>
44 #include <credentials/sets/mem_cred.h>
45 #include <plugins/plugin.h>
50 * definition of some defaults
54 #define REQ_PATH IPSEC_CONFDIR "/ipsec.d/reqs"
55 #define HOST_CERT_PATH IPSEC_CONFDIR "/ipsec.d/certs"
56 #define CA_CERT_PATH IPSEC_CONFDIR "/ipsec.d/cacerts"
57 #define PRIVATE_KEY_PATH IPSEC_CONFDIR "/ipsec.d/private"
59 /* default name of DER-encoded PKCS#1 private key file */
60 #define DEFAULT_FILENAME_PKCS1 "myKey.der"
62 /* default name of DER-encoded PKCS#10 certificate request file */
63 #define DEFAULT_FILENAME_PKCS10 "myReq.der"
65 /* default name of DER-encoded PKCS#7 file */
66 #define DEFAULT_FILENAME_PKCS7 "pkcs7.der"
68 /* default name of DER-encoded self-signed X.509 certificate file */
69 #define DEFAULT_FILENAME_CERT_SELF "selfCert.der"
71 /* default name of DER-encoded X.509 certificate file */
72 #define DEFAULT_FILENAME_CERT "myCert.der"
74 /* default name of DER-encoded CA cert file used for key encipherment */
75 #define DEFAULT_FILENAME_CACERT_ENC "caCert.der"
77 /* default name of the der encoded CA cert file used for signature verification */
78 #define DEFAULT_FILENAME_CACERT_SIG "caCert.der"
80 /* default prefix of the der encoded CA certificates received from the SCEP server */
81 #define DEFAULT_FILENAME_PREFIX_CACERT "caCert.der"
83 /* default certificate validity */
84 #define DEFAULT_CERT_VALIDITY 5 * 3600 * 24 * 365 /* seconds */
86 /* default polling time interval in SCEP manual mode */
87 #define DEFAULT_POLL_INTERVAL 20 /* seconds */
89 /* default key length for self-generated RSA keys */
90 #define DEFAULT_RSA_KEY_LENGTH 2048 /* bits */
92 /* default distinguished name */
93 #define DEFAULT_DN "C=CH, O=Linux strongSwan, CN="
95 /* minimum RSA key size */
96 #define RSA_MIN_OCTETS (512 / BITS_PER_BYTE)
98 /* challenge password buffer size */
99 #define MAX_PASSWORD_LENGTH 256
101 /* Max length of filename for tempfile */
102 #define MAX_TEMP_FILENAME_LENGTH 256
105 /* current scepclient version */
106 static const char *scepclient_version
= "1.0";
108 /* by default the CRL policy is lenient */
109 bool strict_crl_policy
= FALSE
;
111 /* by default pluto does not check crls dynamically */
112 long crl_check_interval
= 0;
114 /* by default pluto logs out after every smartcard use */
115 bool pkcs11_keep_state
= FALSE
;
117 /* by default HTTP fetch timeout is 30s */
118 static u_int http_timeout
= 30;
120 /* address to bind for HTTP fetches */
121 static char* http_bind
= NULL
;
123 /* options read by optionsfrom */
131 chunk_t challengePassword
;
132 chunk_t serialNumber
;
136 chunk_t pkcs10_encoding
;
137 chunk_t issuerAndSubject
;
138 chunk_t getCertInitial
;
139 chunk_t scep_response
;
141 linked_list_t
*subjectAltNames
;
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
;
151 mem_cred_t
*creds
= NULL
;
154 static bool log_to_stderr
= TRUE
;
155 static bool log_to_syslog
= TRUE
;
156 static level_t default_loglevel
= 1;
159 * logging function for scepclient
161 static void scepclient_dbg(debug_t group
, level_t level
, char *fmt
, ...)
164 char *current
= buffer
, *next
;
167 if (level
<= default_loglevel
)
172 vfprintf(stderr
, fmt
, args
);
174 fprintf(stderr
, "\n");
178 /* write in memory buffer first */
180 vsnprintf(buffer
, sizeof(buffer
), fmt
, args
);
183 /* do a syslog with every line */
186 next
= strchr(current
, '\n');
191 syslog(LOG_INFO
, "%s\n", current
);
199 * Initialize logging to stderr/syslog
201 static void init_log(const char *program
)
203 dbg
= scepclient_dbg
;
207 setbuf(stderr
, NULL
);
211 openlog(program
, LOG_CONS
| LOG_NDELAY
| LOG_PID
, LOG_AUTHPRIV
);
216 * join two paths if filename is not absolute
218 static void join_paths(char *target
, size_t target_size
, char *parent
,
221 if (*filename
== '/' || *filename
== '.')
223 snprintf(target
, target_size
, "%s", filename
);
227 snprintf(target
, target_size
, "%s/%s", parent
, filename
);
232 * add a suffix to a given filename, properly handling extensions like '.der'
234 static void add_path_suffix(char *target
, size_t target_size
, char *filename
,
235 char *suffix_fmt
, ...)
237 char suffix
[PATH_MAX
], *start
, *dot
;
240 va_start(args
, suffix_fmt
);
241 vsnprintf(suffix
, sizeof(suffix
), suffix_fmt
, args
);
244 start
= strrchr(filename
, '/');
245 start
= start
?: filename
;
246 dot
= strrchr(start
, '.');
248 if (!dot
|| dot
== start
|| dot
[1] == '\0')
249 { /* no extension add suffix at the end */
250 snprintf(target
, target_size
, "%s%s", filename
, suffix
);
253 { /* add the suffix between the filename and the extension */
254 snprintf(target
, target_size
, "%.*s%s%s", (int)(dot
- filename
),
255 filename
, suffix
, dot
);
260 * @brief exit scepclient
262 * @param status 0 = OK, 1 = general discomfort
264 static void exit_scepclient(err_t message
, ...)
270 lib
->credmgr
->remove_set(lib
->credmgr
, &creds
->set
);
271 creds
->destroy(creds
);
275 DESTROY_IF(private_key
);
276 DESTROY_IF(public_key
);
277 DESTROY_IF(x509_signer
);
278 DESTROY_IF(x509_ca_enc
);
279 DESTROY_IF(x509_ca_sig
);
280 DESTROY_IF(pkcs10_req
);
281 subjectAltNames
->destroy_offset(subjectAltNames
,
282 offsetof(identification_t
, destroy
));
285 free(serialNumber
.ptr
);
287 free(fingerprint
.ptr
);
289 free(pkcs10_encoding
.ptr
);
290 free(issuerAndSubject
.ptr
);
291 free(getCertInitial
.ptr
);
292 free(scep_response
.ptr
);
293 options
->destroy(options
);
295 /* print any error message to stderr */
296 if (message
!= NULL
&& *message
!= '\0')
301 va_start(args
, message
);
302 vsnprintf(m
, sizeof(m
), message
, args
);
305 fprintf(stderr
, "error: %s\n", m
);
313 * @brief prints the program version and exits
316 static void version(void)
318 printf("scepclient %s\n", scepclient_version
);
319 exit_scepclient(NULL
);
323 * @brief prints the usage of the program to the stderr output
325 * If message is set, program is exitet with 1 (error)
326 * @param message message in case of an error
328 static void usage(const char *message
)
331 "Usage: scepclient\n"
332 " --help (-h) show usage and exit\n"
333 " --version (-v) show version and exit\n"
334 " --quiet (-q) do not write log output to stderr\n"
335 " --in (-i) <type>[=<filename>] use <filename> of <type> for input\n"
336 " <type> = pkcs1 | pkcs10 | cert-self\n"
337 " cacert-enc | cacert-sig\n"
338 " - if no pkcs1 input is defined, an RSA\n"
339 " key will be generated\n"
340 " - if no pkcs10 input is defined, a\n"
341 " PKCS#10 request will be generated\n"
342 " - if no cert-self input is defined, a\n"
343 " self-signed certificate will be generated\n"
344 " - if no filename is given, default is used\n"
345 " --out (-o) <type>[=<filename>] write output of <type> to <filename>\n"
346 " multiple outputs are allowed\n"
347 " <type> = pkcs1 | pkcs10 | pkcs7 | cert-self |\n"
349 " - type cacert defines filename prefix of\n"
350 " received CA certificate(s)\n"
351 " - if no filename is given, default is used\n"
352 " --optionsfrom (-+) <filename> reads additional options from given file\n"
353 " --force (-f) force existing file(s)\n"
354 " --httptimeout (-T) timeout for HTTP operations (default: 30s)\n"
355 " --bind (-b) source address to bind for HTTP operations\n"
357 "Options for key generation (pkcs1):\n"
358 " --keylength (-k) <bits> key length for RSA key generation\n"
359 " (default: 2048 bits)\n"
361 "Options for validity:\n"
362 " --days (-D) <days> validity in days\n"
363 " --startdate (-S) <YYMMDDHHMMSS>Z not valid before date\n"
364 " --enddate (-E) <YYMMDDHHMMSS>Z not valid after date\n"
366 "Options for request generation (pkcs10):\n"
367 " --dn (-d) <dn> comma separated list of distinguished names\n"
368 " --subjectAltName (-s) <t>=<v> include subjectAltName in certificate request\n"
369 " <t> = email | dns | ip \n"
370 " --password (-p) <pw> challenge password\n"
371 " - use '%%prompt' as pw for a password prompt\n"
372 " --algorithm (-a) [<type>=]<algo> algorithm to be used for PKCS#7 encryption,\n"
373 " PKCS#7 digest or PKCS#10 signature\n"
374 " <type> = enc | dgst | sig\n"
375 " - if no type is given enc is assumed\n"
376 " <algo> = des (default) | 3des | aes128 |\n"
377 " aes192 | aes256 | camellia128 |\n"
378 " camellia192 | camellia256\n"
379 " <algo> = md5 (default) | sha1 | sha256 |\n"
382 "Options for CA certificate acquisition:\n"
383 " --caname (-c) <name> name of CA to fetch CA certificate(s)\n"
384 " (default: CAIdentifier)\n"
385 "Options for enrollment (cert):\n"
386 " --url (-u) <url> url of the SCEP server\n"
387 " --method (-m) post | get http request type\n"
388 " --interval (-t) <seconds> poll interval in seconds (default 20s)\n"
389 " --maxpolltime (-x) <seconds> max poll time in seconds when in manual mode\n"
390 " (default: unlimited)\n"
392 "Debugging output:\n"
393 " --debug (-l) <level> changes the log level (-1..4, default: 1)\n"
395 exit_scepclient(message
);
399 * @brief main of scepclient
401 * @param argc number of arguments
402 * @param argv pointer to the argument values
404 int main(int argc
, char **argv
)
406 /* external values */
407 extern char * optarg
;
410 /* type of input and output files */
421 /* filetype to read from, defaults to "generate a key" */
422 scep_filetype_t filetype_in
= 0;
424 /* filetype to write to, no default here */
425 scep_filetype_t filetype_out
= 0;
428 char *file_in_pkcs1
= DEFAULT_FILENAME_PKCS1
;
429 char *file_in_pkcs10
= DEFAULT_FILENAME_PKCS10
;
430 char *file_in_cert_self
= DEFAULT_FILENAME_CERT_SELF
;
431 char *file_in_cacert_enc
= DEFAULT_FILENAME_CACERT_ENC
;
432 char *file_in_cacert_sig
= DEFAULT_FILENAME_CACERT_SIG
;
435 char *file_out_pkcs1
= DEFAULT_FILENAME_PKCS1
;
436 char *file_out_pkcs10
= DEFAULT_FILENAME_PKCS10
;
437 char *file_out_pkcs7
= DEFAULT_FILENAME_PKCS7
;
438 char *file_out_cert_self
= DEFAULT_FILENAME_CERT_SELF
;
439 char *file_out_cert
= DEFAULT_FILENAME_CERT
;
440 char *file_out_ca_cert
= DEFAULT_FILENAME_CACERT_ENC
;
442 /* by default user certificate is requested */
443 bool request_ca_certificate
= FALSE
;
445 /* by default existing files are not overwritten */
448 /* length of RSA key in bits */
449 u_int rsa_keylength
= DEFAULT_RSA_KEY_LENGTH
;
451 /* validity of self-signed certificate */
452 time_t validity
= DEFAULT_CERT_VALIDITY
;
453 time_t notBefore
= 0;
456 /* distinguished name for requested certificate, ASCII format */
457 char *distinguishedName
= NULL
;
459 /* challenge password */
460 char challenge_password_buffer
[MAX_PASSWORD_LENGTH
];
462 /* symmetric encryption algorithm used by pkcs7, default is DES */
463 encryption_algorithm_t pkcs7_symmetric_cipher
= ENCR_DES
;
464 size_t pkcs7_key_size
= 0;
466 /* digest algorithm used by pkcs7, default is MD5 */
467 hash_algorithm_t pkcs7_digest_alg
= HASH_MD5
;
469 /* signature algorithm used by pkcs10, default is MD5 */
470 hash_algorithm_t pkcs10_signature_alg
= HASH_MD5
;
472 /* URL of the SCEP-Server */
473 char *scep_url
= NULL
;
475 /* Name of CA to fetch CA certs for */
476 char *ca_name
= "CAIdentifier";
478 /* http request method, default is GET */
479 bool http_get_request
= TRUE
;
481 /* poll interval time in manual mode in seconds */
482 u_int poll_interval
= DEFAULT_POLL_INTERVAL
;
484 /* maximum poll time */
485 u_int max_poll_time
= 0;
489 /* initialize library */
490 if (!library_init(NULL
))
493 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY
);
495 if (lib
->integrity
&&
496 !lib
->integrity
->check_file(lib
->integrity
, "scepclient", argv
[0]))
498 fprintf(stderr
, "integrity check of scepclient failed\n");
500 exit(SS_RC_DAEMON_INTEGRITY
);
503 /* initialize global variables */
506 serialNumber
= chunk_empty
;
507 transID
= chunk_empty
;
508 fingerprint
= chunk_empty
;
509 encoding
= chunk_empty
;
510 pkcs10_encoding
= chunk_empty
;
511 issuerAndSubject
= chunk_empty
;
512 challengePassword
= chunk_empty
;
513 getCertInitial
= chunk_empty
;
514 scep_response
= chunk_empty
;
515 subjectAltNames
= linked_list_create();
516 options
= options_create();
520 static const struct option long_opts
[] = {
521 /* name, has_arg, flag, val */
522 { "help", no_argument
, NULL
, 'h' },
523 { "version", no_argument
, NULL
, 'v' },
524 { "optionsfrom", required_argument
, NULL
, '+' },
525 { "quiet", no_argument
, NULL
, 'q' },
526 { "debug", required_argument
, NULL
, 'l' },
527 { "in", required_argument
, NULL
, 'i' },
528 { "out", required_argument
, NULL
, 'o' },
529 { "force", no_argument
, NULL
, 'f' },
530 { "httptimeout", required_argument
, NULL
, 'T' },
531 { "bind", required_argument
, NULL
, 'b' },
532 { "keylength", required_argument
, NULL
, 'k' },
533 { "dn", required_argument
, NULL
, 'd' },
534 { "days", required_argument
, NULL
, 'D' },
535 { "startdate", required_argument
, NULL
, 'S' },
536 { "enddate", required_argument
, NULL
, 'E' },
537 { "subjectAltName", required_argument
, NULL
, 's' },
538 { "password", required_argument
, NULL
, 'p' },
539 { "algorithm", required_argument
, NULL
, 'a' },
540 { "url", required_argument
, NULL
, 'u' },
541 { "caname", required_argument
, NULL
, 'c'},
542 { "method", required_argument
, NULL
, 'm' },
543 { "interval", required_argument
, NULL
, 't' },
544 { "maxpolltime", required_argument
, NULL
, 'x' },
548 /* parse next option */
549 int c
= getopt_long(argc
, argv
, "hv+:qi:o:fk:d:s:p:a:u:c:m:t:x:APRCMS", long_opts
, NULL
);
553 case EOF
: /* end of flags */
556 case 'h': /* --help */
559 case 'v': /* --version */
562 case 'q': /* --quiet */
563 log_to_stderr
= FALSE
;
566 case 'l': /* --debug <level> */
567 default_loglevel
= atoi(optarg
);
570 case 'i': /* --in <type> [= <filename>] */
572 char *filename
= strstr(optarg
, "=");
576 /* replace '=' by '\0' */
578 /* set pointer to start of filename */
581 if (strcaseeq("pkcs1", optarg
))
583 filetype_in
|= PKCS1
;
585 file_in_pkcs1
= filename
;
587 else if (strcaseeq("pkcs10", optarg
))
589 filetype_in
|= PKCS10
;
591 file_in_pkcs10
= filename
;
593 else if (strcaseeq("cacert-enc", optarg
))
595 filetype_in
|= CACERT_ENC
;
597 file_in_cacert_enc
= filename
;
599 else if (strcaseeq("cacert-sig", optarg
))
601 filetype_in
|= CACERT_SIG
;
603 file_in_cacert_sig
= filename
;
605 else if (strcaseeq("cert-self", optarg
))
607 filetype_in
|= CERT_SELF
;
609 file_in_cert_self
= filename
;
613 usage("invalid --in file type");
618 case 'o': /* --out <type> [= <filename>] */
620 char *filename
= strstr(optarg
, "=");
624 /* replace '=' by '\0' */
626 /* set pointer to start of filename */
629 if (strcaseeq("pkcs1", optarg
))
631 filetype_out
|= PKCS1
;
633 file_out_pkcs1
= filename
;
635 else if (strcaseeq("pkcs10", optarg
))
637 filetype_out
|= PKCS10
;
639 file_out_pkcs10
= filename
;
641 else if (strcaseeq("pkcs7", optarg
))
643 filetype_out
|= PKCS7
;
645 file_out_pkcs7
= filename
;
647 else if (strcaseeq("cert-self", optarg
))
649 filetype_out
|= CERT_SELF
;
651 file_out_cert_self
= filename
;
653 else if (strcaseeq("cert", optarg
))
655 filetype_out
|= CERT
;
657 file_out_cert
= filename
;
659 else if (strcaseeq("cacert", optarg
))
661 request_ca_certificate
= TRUE
;
663 file_out_ca_cert
= filename
;
667 usage("invalid --out file type");
672 case 'f': /* --force */
676 case 'T': /* --httptimeout */
677 http_timeout
= atoi(optarg
);
678 if (http_timeout
<= 0)
680 usage("invalid httptimeout specified");
684 case 'b': /* --bind */
688 case '+': /* --optionsfrom <filename> */
689 if (!options
->from(options
, optarg
, &argc
, &argv
, optind
))
691 exit_scepclient("optionsfrom failed");
695 case 'k': /* --keylength <length> */
699 rsa_keylength
= atoi(optarg
);
700 if (rsa_keylength
== 0)
701 usage("invalid keylength");
703 /* check if key length is a multiple of 8 bits */
704 q
= div(rsa_keylength
, 2*BITS_PER_BYTE
);
707 exit_scepclient("keylength is not a multiple of %d bits!"
713 case 'D': /* --days */
714 if (optarg
== NULL
|| !isdigit(optarg
[0]))
716 usage("missing number of days");
721 long days
= strtol(optarg
, &endptr
, 0);
723 if (*endptr
!= '\0' || endptr
== optarg
725 usage("<days> must be a positive number");
726 validity
= 24*3600*days
;
730 case 'S': /* --startdate */
731 if (optarg
== NULL
|| strlen(optarg
) != 13 || optarg
[12] != 'Z')
733 usage("date format must be YYMMDDHHMMSSZ");
737 chunk_t date
= { optarg
, 13 };
738 notBefore
= asn1_to_time(&date
, ASN1_UTCTIME
);
742 case 'E': /* --enddate */
743 if (optarg
== NULL
|| strlen(optarg
) != 13 || optarg
[12] != 'Z')
745 usage("date format must be YYMMDDHHMMSSZ");
749 chunk_t date
= { optarg
, 13 };
750 notAfter
= asn1_to_time(&date
, ASN1_UTCTIME
);
755 if (distinguishedName
)
757 usage("only one distinguished name allowed");
759 distinguishedName
= optarg
;
762 case 's': /* --subjectAltName */
764 char *value
= strstr(optarg
, "=");
768 /* replace '=' by '\0' */
770 /* set pointer to start of value */
774 if (strcaseeq("email", optarg
) ||
775 strcaseeq("dns", optarg
) ||
776 strcaseeq("ip", optarg
))
778 subjectAltNames
->insert_last(subjectAltNames
,
779 identification_create_from_string(value
));
784 usage("invalid --subjectAltName type");
789 case 'p': /* --password */
790 if (challengePassword
.len
> 0)
792 usage("only one challenge password allowed");
794 if (strcaseeq("%prompt", optarg
))
796 printf("Challenge password: ");
797 if (fgets(challenge_password_buffer
,
798 sizeof(challenge_password_buffer
) - 1, stdin
))
800 challengePassword
.ptr
= challenge_password_buffer
;
801 /* discard the terminating '\n' from the input */
802 challengePassword
.len
= strlen(challenge_password_buffer
) - 1;
806 usage("challenge password could not be read");
811 challengePassword
.ptr
= optarg
;
812 challengePassword
.len
= strlen(optarg
);
816 case 'u': /* -- url */
819 usage("only one URL argument allowed");
824 case 'c': /* -- caname */
828 case 'm': /* --method */
829 if (strcaseeq("get", optarg
))
831 http_get_request
= TRUE
;
833 else if (strcaseeq("post", optarg
))
835 http_get_request
= FALSE
;
839 usage("invalid http request method specified");
843 case 't': /* --interval */
844 poll_interval
= atoi(optarg
);
845 if (poll_interval
<= 0)
847 usage("invalid interval specified");
851 case 'x': /* --maxpolltime */
852 max_poll_time
= atoi(optarg
);
855 case 'a': /*--algorithm [<type>=]algo */
857 const proposal_token_t
*token
;
859 char *algo
= strstr(optarg
, "=");
872 if (strcaseeq("enc", type
))
874 token
= lib
->proposal
->get_token(lib
->proposal
, algo
);
875 if (token
== NULL
|| token
->type
!= ENCRYPTION_ALGORITHM
)
877 usage("invalid algorithm specified");
879 pkcs7_symmetric_cipher
= token
->algorithm
;
880 pkcs7_key_size
= token
->keysize
;
881 if (encryption_algorithm_to_oid(token
->algorithm
,
882 token
->keysize
) == OID_UNKNOWN
)
884 usage("unsupported encryption algorithm specified");
887 else if (strcaseeq("dgst", type
) ||
888 strcaseeq("sig", type
))
890 hash_algorithm_t hash
;
892 token
= lib
->proposal
->get_token(lib
->proposal
, algo
);
893 if (token
== NULL
|| token
->type
!= INTEGRITY_ALGORITHM
)
895 usage("invalid algorithm specified");
897 hash
= hasher_algorithm_from_integrity(token
->algorithm
,
899 if (hash
== OID_UNKNOWN
)
901 usage("invalid algorithm specified");
903 if (strcaseeq("dgst", type
))
905 pkcs7_digest_alg
= hash
;
909 pkcs10_signature_alg
= hash
;
914 usage("invalid --algorithm type");
919 usage("unknown option");
921 /* break from loop */
925 init_log("scepclient");
927 /* load plugins, further infrastructure may need it */
928 if (!lib
->plugins
->load(lib
->plugins
,
929 lib
->settings
->get_str(lib
->settings
, "scepclient.load", PLUGINS
)))
931 exit_scepclient("plugin loading failed");
933 lib
->plugins
->status(lib
->plugins
, LEVEL_DIAG
);
935 if ((filetype_out
== 0) && (!request_ca_certificate
))
937 usage("--out filetype required");
939 if (request_ca_certificate
&& (filetype_out
> 0 || filetype_in
> 0))
941 usage("in CA certificate request, no other --in or --out option allowed");
944 /* check if url is given, if cert output defined */
945 if (((filetype_out
& CERT
) || request_ca_certificate
) && !scep_url
)
947 usage("URL of SCEP server required");
950 /* check for sanity of --in/--out */
951 if (!filetype_in
&& (filetype_in
> filetype_out
))
953 usage("cannot generate --out of given --in!");
957 if (request_ca_certificate
)
959 char ca_path
[PATH_MAX
];
960 container_t
*container
;
963 if (!scep_http_request(scep_url
, chunk_create(ca_name
, strlen(ca_name
)),
964 SCEP_GET_CA_CERT
, http_get_request
,
965 http_timeout
, http_bind
, &scep_response
))
967 exit_scepclient("did not receive a valid scep response");
970 join_paths(ca_path
, sizeof(ca_path
), CA_CERT_PATH
, file_out_ca_cert
);
972 pkcs7
= lib
->creds
->create(lib
->creds
, CRED_CONTAINER
, CONTAINER_PKCS7
,
973 BUILD_BLOB_ASN1_DER
, scep_response
, BUILD_END
);
976 { /* no PKCS#7 encoded CA+RA certificates, assume simple CA cert */
978 DBG1(DBG_APP
, "unable to parse PKCS#7, assuming plain CA cert");
979 if (!chunk_write(scep_response
, ca_path
, 0022, force
))
981 exit_scepclient("could not write ca cert file '%s': %s",
982 ca_path
, strerror(errno
));
987 enumerator_t
*enumerator
;
989 int ra_certs
= 0, ca_certs
= 0;
990 int ra_index
= 1, ca_index
= 1;
992 enumerator
= pkcs7
->create_cert_enumerator(pkcs7
);
993 while (enumerator
->enumerate(enumerator
, &cert
))
995 x509_t
*x509
= (x509_t
*)cert
;
996 if (x509
->get_flags(x509
) & X509_CA
)
1005 enumerator
->destroy(enumerator
);
1007 enumerator
= pkcs7
->create_cert_enumerator(pkcs7
);
1008 while (enumerator
->enumerate(enumerator
, &cert
))
1010 x509_t
*x509
= (x509_t
*)cert
;
1011 bool ca_cert
= x509
->get_flags(x509
) & X509_CA
;
1012 char cert_path
[PATH_MAX
], *path
= ca_path
;
1014 if (ca_cert
&& ca_certs
> 1)
1016 add_path_suffix(cert_path
, sizeof(cert_path
), ca_path
,
1017 "-%.1d", ca_index
++);
1021 { /* use CA name as base for RA certs */
1024 add_path_suffix(cert_path
, sizeof(cert_path
), ca_path
,
1025 "-ra-%.1d", ra_index
++);
1029 add_path_suffix(cert_path
, sizeof(cert_path
), ca_path
,
1035 if (!cert
->get_encoding(cert
, CERT_ASN1_DER
, &encoding
) ||
1036 !chunk_write(encoding
, path
, 0022, force
))
1038 exit_scepclient("could not write cert file '%s': %s",
1039 path
, strerror(errno
));
1041 chunk_free(&encoding
);
1043 enumerator
->destroy(enumerator
);
1044 container
= &pkcs7
->container
;
1045 container
->destroy(container
);
1047 exit_scepclient(NULL
); /* no further output required */
1050 creds
= mem_cred_create();
1051 lib
->credmgr
->add_set(lib
->credmgr
, &creds
->set
);
1054 * input of PKCS#1 file
1056 if (filetype_in
& PKCS1
) /* load an RSA key pair from file */
1058 char path
[PATH_MAX
];
1060 join_paths(path
, sizeof(path
), PRIVATE_KEY_PATH
, file_in_pkcs1
);
1062 private_key
= lib
->creds
->create(lib
->creds
, CRED_PRIVATE_KEY
, KEY_RSA
,
1063 BUILD_FROM_FILE
, path
, BUILD_END
);
1065 else /* generate an RSA key pair */
1067 private_key
= lib
->creds
->create(lib
->creds
, CRED_PRIVATE_KEY
, KEY_RSA
,
1068 BUILD_KEY_SIZE
, rsa_keylength
,
1071 if (private_key
== NULL
)
1073 exit_scepclient("no RSA private key available");
1075 creds
->add_key(creds
, private_key
->get_ref(private_key
));
1076 public_key
= private_key
->get_public_key(private_key
);
1078 /* check for minimum key length */
1079 if (private_key
->get_keysize(private_key
) < RSA_MIN_OCTETS
/ BITS_PER_BYTE
)
1081 exit_scepclient("length of RSA key has to be at least %d bits",
1082 RSA_MIN_OCTETS
* BITS_PER_BYTE
);
1086 * input of PKCS#10 file
1088 if (filetype_in
& PKCS10
)
1090 char path
[PATH_MAX
];
1092 join_paths(path
, sizeof(path
), REQ_PATH
, file_in_pkcs10
);
1094 pkcs10_req
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
,
1095 CERT_PKCS10_REQUEST
, BUILD_FROM_FILE
,
1099 exit_scepclient("could not read certificate request '%s'", path
);
1101 subject
= pkcs10_req
->get_subject(pkcs10_req
);
1102 subject
= subject
->clone(subject
);
1106 if (distinguishedName
== NULL
)
1109 int n
= sprintf(buf
, DEFAULT_DN
);
1111 /* set the common name to the hostname */
1112 if (gethostname(buf
+ n
, BUF_LEN
- n
) || strlen(buf
) == n
)
1114 exit_scepclient("no hostname defined, use "
1115 "--dn <distinguished name> option");
1117 distinguishedName
= buf
;
1120 DBG2(DBG_APP
, "dn: '%s'", distinguishedName
);
1121 subject
= identification_create_from_string(distinguishedName
);
1122 if (subject
->get_type(subject
) != ID_DER_ASN1_DN
)
1124 exit_scepclient("parsing of distinguished name failed");
1127 DBG2(DBG_APP
, "building pkcs10 object:");
1128 pkcs10_req
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
,
1129 CERT_PKCS10_REQUEST
,
1130 BUILD_SIGNING_KEY
, private_key
,
1131 BUILD_SUBJECT
, subject
,
1132 BUILD_SUBJECT_ALTNAMES
, subjectAltNames
,
1133 BUILD_CHALLENGE_PWD
, challengePassword
,
1134 BUILD_DIGEST_ALG
, pkcs10_signature_alg
,
1138 exit_scepclient("generating pkcs10 request failed");
1141 pkcs10_req
->get_encoding(pkcs10_req
, CERT_ASN1_DER
, &pkcs10_encoding
);
1142 fingerprint
= scep_generate_pkcs10_fingerprint(pkcs10_encoding
);
1143 DBG1(DBG_APP
, " fingerprint: %s", fingerprint
.ptr
);
1146 * output of PKCS#10 file
1148 if (filetype_out
& PKCS10
)
1150 char path
[PATH_MAX
];
1152 join_paths(path
, sizeof(path
), REQ_PATH
, file_out_pkcs10
);
1154 if (!chunk_write(pkcs10_encoding
, path
, 0022, force
))
1156 exit_scepclient("could not write pkcs10 file '%s': %s",
1157 path
, strerror(errno
));
1159 filetype_out
&= ~PKCS10
; /* delete PKCS10 flag */
1164 exit_scepclient(NULL
); /* no further output required */
1168 * output of PKCS#1 file
1170 if (filetype_out
& PKCS1
)
1172 char path
[PATH_MAX
];
1174 join_paths(path
, sizeof(path
), PRIVATE_KEY_PATH
, file_out_pkcs1
);
1176 DBG2(DBG_APP
, "building pkcs1 object:");
1177 if (!private_key
->get_encoding(private_key
, PRIVKEY_ASN1_DER
, &pkcs1
) ||
1178 !chunk_write(pkcs1
, path
, 0066, force
))
1180 exit_scepclient("could not write pkcs1 file '%s': %s",
1181 path
, strerror(errno
));
1183 filetype_out
&= ~PKCS1
; /* delete PKCS1 flag */
1188 exit_scepclient(NULL
); /* no further output required */
1191 scep_generate_transaction_id(public_key
, &transID
, &serialNumber
);
1192 DBG1(DBG_APP
, " transaction ID: %.*s", (int)transID
.len
, transID
.ptr
);
1195 * read or generate self-signed X.509 certificate
1197 if (filetype_in
& CERT_SELF
)
1199 char path
[PATH_MAX
];
1201 join_paths(path
, sizeof(path
), HOST_CERT_PATH
, file_in_cert_self
);
1203 x509_signer
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
, CERT_X509
,
1204 BUILD_FROM_FILE
, path
, BUILD_END
);
1207 exit_scepclient("could not read certificate file '%s'", path
);
1212 notBefore
= notBefore
? notBefore
: time(NULL
);
1213 notAfter
= notAfter
? notAfter
: (notBefore
+ validity
);
1214 x509_signer
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
, CERT_X509
,
1215 BUILD_SIGNING_KEY
, private_key
,
1216 BUILD_PUBLIC_KEY
, public_key
,
1217 BUILD_SUBJECT
, subject
,
1218 BUILD_NOT_BEFORE_TIME
, notBefore
,
1219 BUILD_NOT_AFTER_TIME
, notAfter
,
1220 BUILD_SERIAL
, serialNumber
,
1221 BUILD_SUBJECT_ALTNAMES
, subjectAltNames
,
1225 exit_scepclient("generating certificate failed");
1228 creds
->add_cert(creds
, TRUE
, x509_signer
->get_ref(x509_signer
));
1231 * output of self-signed X.509 certificate file
1233 if (filetype_out
& CERT_SELF
)
1235 char path
[PATH_MAX
];
1237 join_paths(path
, sizeof(path
), HOST_CERT_PATH
, file_out_cert_self
);
1239 if (!x509_signer
->get_encoding(x509_signer
, CERT_ASN1_DER
, &encoding
))
1241 exit_scepclient("encoding certificate failed");
1243 if (!chunk_write(encoding
, path
, 0022, force
))
1245 exit_scepclient("could not write self-signed cert file '%s': %s",
1246 path
, strerror(errno
));
1248 chunk_free(&encoding
);
1249 filetype_out
&= ~CERT_SELF
; /* delete CERT_SELF flag */
1254 exit_scepclient(NULL
); /* no further output required */
1258 * load ca encryption certificate
1261 char path
[PATH_MAX
];
1263 join_paths(path
, sizeof(path
), CA_CERT_PATH
, file_in_cacert_enc
);
1265 x509_ca_enc
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
, CERT_X509
,
1266 BUILD_FROM_FILE
, path
, BUILD_END
);
1269 exit_scepclient("could not load encryption cacert file '%s'", path
);
1274 * input of PKCS#7 file
1276 if (filetype_in
& PKCS7
)
1278 /* user wants to load a pkcs7 encrypted request
1279 * operation is not yet supported!
1280 * would require additional parsing of transaction-id
1282 pkcs7 = pkcs7_read_from_file(file_in_pkcs7);
1288 DBG2(DBG_APP
, "building pkcs7 request");
1289 pkcs7
= scep_build_request(pkcs10_encoding
,
1290 transID
, SCEP_PKCSReq_MSG
, x509_ca_enc
,
1291 pkcs7_symmetric_cipher
, pkcs7_key_size
,
1292 x509_signer
, pkcs7_digest_alg
, private_key
);
1295 exit_scepclient("failed to build pkcs7 request");
1300 * output pkcs7 encrypted and signed certificate request
1302 if (filetype_out
& PKCS7
)
1304 char path
[PATH_MAX
];
1306 join_paths(path
, sizeof(path
), REQ_PATH
, file_out_pkcs7
);
1308 if (!chunk_write(pkcs7
, path
, 0022, force
))
1310 exit_scepclient("could not write pkcs7 file '%s': %s",
1311 path
, strerror(errno
));
1313 filetype_out
&= ~PKCS7
; /* delete PKCS7 flag */
1318 exit_scepclient(NULL
); /* no further output required */
1322 * output certificate fetch from SCEP server
1324 if (filetype_out
& CERT
)
1326 bool stored
= FALSE
;
1327 certificate_t
*cert
;
1328 enumerator_t
*enumerator
;
1329 char path
[PATH_MAX
];
1330 time_t poll_start
= 0;
1332 container_t
*container
= NULL
;
1334 scep_attributes_t attrs
= empty_scep_attributes
;
1336 join_paths(path
, sizeof(path
), CA_CERT_PATH
, file_in_cacert_sig
);
1338 x509_ca_sig
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
, CERT_X509
,
1339 BUILD_FROM_FILE
, path
, BUILD_END
);
1342 exit_scepclient("could not load signature cacert file '%s'", path
);
1345 creds
->add_cert(creds
, TRUE
, x509_ca_sig
->get_ref(x509_ca_sig
));
1347 if (!scep_http_request(scep_url
, pkcs7
, SCEP_PKI_OPERATION
,
1348 http_get_request
, http_timeout
, http_bind
, &scep_response
))
1350 exit_scepclient("did not receive a valid scep response");
1352 ugh
= scep_parse_response(scep_response
, transID
, &container
, &attrs
);
1355 exit_scepclient(ugh
);
1358 /* in case of manual mode, we are going into a polling loop */
1359 if (attrs
.pkiStatus
== SCEP_PENDING
)
1361 identification_t
*issuer
= x509_ca_sig
->get_subject(x509_ca_sig
);
1363 DBG1(DBG_APP
, " scep request pending, polling every %d seconds",
1365 poll_start
= time_monotonic(NULL
);
1366 issuerAndSubject
= asn1_wrap(ASN1_SEQUENCE
, "cc",
1367 issuer
->get_encoding(issuer
),
1368 subject
->get_encoding(subject
));
1370 while (attrs
.pkiStatus
== SCEP_PENDING
)
1372 if (max_poll_time
> 0 &&
1373 (time_monotonic(NULL
) - poll_start
>= max_poll_time
))
1375 exit_scepclient("maximum poll time reached: %d seconds"
1378 DBG2(DBG_APP
, "going to sleep for %d seconds", poll_interval
);
1379 sleep(poll_interval
);
1380 free(scep_response
.ptr
);
1381 container
->destroy(container
);
1383 DBG2(DBG_APP
, "fingerprint: %.*s",
1384 (int)fingerprint
.len
, fingerprint
.ptr
);
1385 DBG2(DBG_APP
, "transaction ID: %.*s",
1386 (int)transID
.len
, transID
.ptr
);
1388 chunk_free(&getCertInitial
);
1389 getCertInitial
= scep_build_request(issuerAndSubject
,
1390 transID
, SCEP_GetCertInitial_MSG
, x509_ca_enc
,
1391 pkcs7_symmetric_cipher
, pkcs7_key_size
,
1392 x509_signer
, pkcs7_digest_alg
, private_key
);
1393 if (!getCertInitial
.ptr
)
1395 exit_scepclient("failed to build scep request");
1397 if (!scep_http_request(scep_url
, getCertInitial
, SCEP_PKI_OPERATION
,
1398 http_get_request
, http_timeout
, http_bind
, &scep_response
))
1400 exit_scepclient("did not receive a valid scep response");
1402 ugh
= scep_parse_response(scep_response
, transID
, &container
, &attrs
);
1405 exit_scepclient(ugh
);
1409 if (attrs
.pkiStatus
!= SCEP_SUCCESS
)
1411 container
->destroy(container
);
1412 exit_scepclient("reply status is not 'SUCCESS'");
1415 if (!container
->get_data(container
, &chunk
))
1417 container
->destroy(container
);
1418 exit_scepclient("extracting signed-data failed");
1420 container
->destroy(container
);
1422 /* decrypt enveloped-data container */
1423 container
= lib
->creds
->create(lib
->creds
,
1424 CRED_CONTAINER
, CONTAINER_PKCS7
,
1425 BUILD_BLOB_ASN1_DER
, chunk
,
1430 exit_scepclient("could not decrypt envelopedData");
1433 if (!container
->get_data(container
, &chunk
))
1435 container
->destroy(container
);
1436 exit_scepclient("extracting encrypted-data failed");
1438 container
->destroy(container
);
1440 /* parse signed-data container */
1441 container
= lib
->creds
->create(lib
->creds
,
1442 CRED_CONTAINER
, CONTAINER_PKCS7
,
1443 BUILD_BLOB_ASN1_DER
, chunk
,
1448 exit_scepclient("could not parse singed-data");
1450 /* no need to verify the signed-data container, the signature does NOT
1451 * cover the contained certificates */
1453 /* store the end entity certificate */
1454 join_paths(path
, sizeof(path
), HOST_CERT_PATH
, file_out_cert
);
1456 p7
= (pkcs7_t
*)container
;
1457 enumerator
= p7
->create_cert_enumerator(p7
);
1458 while (enumerator
->enumerate(enumerator
, &cert
))
1460 x509_t
*x509
= (x509_t
*)cert
;
1462 if (!(x509
->get_flags(x509
) & X509_CA
))
1466 exit_scepclient("multiple certs received, only first stored");
1468 if (!cert
->get_encoding(cert
, CERT_ASN1_DER
, &encoding
) ||
1469 !chunk_write(encoding
, path
, 0022, force
))
1471 exit_scepclient("could not write cert file '%s': %s",
1472 path
, strerror(errno
));
1474 chunk_free(&encoding
);
1478 enumerator
->destroy(enumerator
);
1479 container
->destroy(container
);
1480 chunk_free(&attrs
.transID
);
1481 chunk_free(&attrs
.senderNonce
);
1482 chunk_free(&attrs
.recipientNonce
);
1484 filetype_out
&= ~CERT
; /* delete CERT flag */
1487 exit_scepclient(NULL
);
1488 return -1; /* should never be reached */