2 * Copyright (c) 2005 - 2007 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the Institute nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 RCSID("$Id: ks_file.c 20776 2007-06-01 22:02:01Z lha $");
49 add_headers(struct header **headers, const char *header, const char *value)
52 h = calloc(1, sizeof(*h));
55 h->header = strdup(header);
56 if (h->header == NULL) {
60 h->value = strdup(value);
61 if (h->value == NULL) {
74 free_headers(struct header *headers)
79 headers = headers->next;
87 find_header(const struct header *headers, const char *header)
90 if (strcmp(header, headers->header) == 0)
91 return headers->value;
92 headers = headers->next;
102 parse_certificate(hx509_context context, const char *fn,
103 struct hx509_collector *c,
104 const struct header *headers,
105 const void *data, size_t len)
112 ret = decode_Certificate(data, len, &t, &size);
114 hx509_set_error_string(context, 0, ret,
115 "Failed to parse certificate in %s",
120 ret = hx509_cert_init(context, &t, &cert);
121 free_Certificate(&t);
125 ret = _hx509_collector_certs_add(context, c, cert);
126 hx509_cert_free(cert);
131 try_decrypt(hx509_context context,
132 struct hx509_collector *collector,
133 const AlgorithmIdentifier *alg,
136 const void *password,
141 heim_octet_string clear;
146 keylen = EVP_CIPHER_key_length(c);
148 key = malloc(keylen);
150 hx509_clear_error_string(context);
154 ret = EVP_BytesToKey(c, EVP_md5(), ivdata,
155 password, passwordlen,
158 hx509_set_error_string(context, 0, HX509_CRYPTO_INTERNAL_ERROR,
159 "Failed to do string2key for private key");
160 return HX509_CRYPTO_INTERNAL_ERROR;
163 clear.data = malloc(len);
164 if (clear.data == NULL) {
165 hx509_set_error_string(context, 0, ENOMEM,
166 "Out of memory to decrypt for private key");
174 EVP_CIPHER_CTX_init(&ctx);
175 EVP_CipherInit_ex(&ctx, c, NULL, key, ivdata, 0);
176 EVP_Cipher(&ctx, clear.data, cipher, len);
177 EVP_CIPHER_CTX_cleanup(&ctx);
180 ret = _hx509_collector_private_key_add(context,
187 memset(clear.data, 0, clear.length);
190 memset(key, 0, keylen);
196 parse_rsa_private_key(hx509_context context, const char *fn,
197 struct hx509_collector *c,
198 const struct header *headers,
199 const void *data, size_t len)
204 enc = find_header(headers, "Proc-Type");
210 const EVP_CIPHER *cipher;
211 const struct _hx509_password *pw;
213 int i, decrypted = 0;
215 lock = _hx509_collector_get_lock(c);
217 hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
218 "Failed to get password for "
219 "password protected file %s", fn);
220 return HX509_ALG_NOT_SUPP;
223 if (strcmp(enc, "4,ENCRYPTED") != 0) {
224 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
225 "RSA key encrypted in unknown method %s "
228 hx509_clear_error_string(context);
229 return HX509_PARSING_KEY_FAILED;
232 dek = find_header(headers, "DEK-Info");
234 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
235 "Encrypted RSA missing DEK-Info");
236 return HX509_PARSING_KEY_FAILED;
241 hx509_clear_error_string(context);
245 iv = strchr(type, ',');
250 ivdata = malloc(size);
251 if (ivdata == NULL) {
252 hx509_clear_error_string(context);
257 cipher = EVP_get_cipherbyname(type);
258 if (cipher == NULL) {
260 hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
261 "RSA key encrypted with "
262 "unsupported cipher: %s",
265 return HX509_ALG_NOT_SUPP;
268 #define PKCS5_SALT_LEN 8
270 ssize = hex_decode(iv, ivdata, size);
275 if (ssize < 0 || ssize < PKCS5_SALT_LEN || ssize < EVP_CIPHER_iv_length(cipher)) {
277 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
278 "Salt have wrong length in RSA key file");
279 return HX509_PARSING_KEY_FAILED;
282 pw = _hx509_lock_get_passwords(lock);
284 const void *password;
287 for (i = 0; i < pw->len; i++) {
288 password = pw->val[i];
289 passwordlen = strlen(password);
291 ret = try_decrypt(context, c, hx509_signature_rsa(),
292 cipher, ivdata, password, passwordlen,
304 memset(&prompt, 0, sizeof(prompt));
306 prompt.prompt = "Password for keyfile: ";
307 prompt.type = HX509_PROMPT_TYPE_PASSWORD;
308 prompt.reply.data = password;
309 prompt.reply.length = sizeof(password);
311 ret = hx509_lock_prompt(lock, &prompt);
313 ret = try_decrypt(context, c, hx509_signature_rsa(),
314 cipher, ivdata, password, strlen(password),
316 /* XXX add password to lock password collection ? */
317 memset(password, 0, sizeof(password));
322 heim_octet_string keydata;
324 keydata.data = rk_UNCONST(data);
325 keydata.length = len;
327 ret = _hx509_collector_private_key_add(context,
329 hx509_signature_rsa(),
341 int (*func)(hx509_context, const char *, struct hx509_collector *,
342 const struct header *, const void *, size_t);
344 { "CERTIFICATE", parse_certificate },
345 { "RSA PRIVATE KEY", parse_rsa_private_key }
350 parse_pem_file(hx509_context context,
352 struct hx509_collector *c,
355 struct header *headers = NULL;
364 enum { BEFORE, SEARCHHEADER, INHEADER, INDATA, DONE } where;
369 if ((f = fopen(fn, "r")) == NULL) {
370 hx509_set_error_string(context, 0, ENOENT,
371 "Failed to open PEM file \"%s\": %s",
372 fn, strerror(errno));
377 while (fgets(buf, sizeof(buf), f) != NULL) {
381 i = strcspn(buf, "\n");
382 if (buf[i] == '\n') {
387 if (buf[i] == '\r') {
395 if (strncmp("-----BEGIN ", buf, 11) == 0) {
396 type = strdup(buf + 11);
399 p = strchr(type, '-');
403 where = SEARCHHEADER;
407 p = strchr(buf, ':');
414 if (buf[0] == '\0') {
418 p = strchr(buf, ':');
421 while (isspace((int)*p))
423 add_headers(&headers, buf, p);
429 if (strncmp("-----END ", buf, 9) == 0) {
435 i = base64_decode(buf, p);
441 data = erealloc(data, len + i);
442 memcpy(((char *)data) + len, p, i);
453 for (j = 0; j < sizeof(formats)/sizeof(formats[0]); j++) {
454 const char *q = formats[j].name;
455 if (strcasecmp(type, q) == 0) {
456 ret = (*formats[j].func)(context, fn, c,
461 if (j == sizeof(formats)/sizeof(formats[0])) {
462 ret = HX509_UNSUPPORTED_OPERATION;
463 hx509_set_error_string(context, 0, ret,
464 "Found no matching PEM format for %s",
474 free_headers(headers);
483 if (where != BEFORE) {
484 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
485 "File ends before end of PEM end tag");
486 ret = HX509_PARSING_KEY_FAILED;
493 free_headers(headers);
503 file_init(hx509_context context,
504 hx509_certs certs, void **data, int flags,
505 const char *residue, hx509_lock lock)
508 struct ks_file *f = NULL;
509 struct hx509_collector *c = NULL;
510 hx509_private_key *keys = NULL;
516 lock = _hx509_empty_lock;
518 f = calloc(1, sizeof(*f));
520 hx509_clear_error_string(context);
524 f->fn = strdup(residue);
526 hx509_clear_error_string(context);
532 * XXX this is broken, the function should parse the file before
536 if (flags & HX509_CERTS_CREATE) {
537 ret = hx509_certs_init(context, "MEMORY:ks-file-create",
545 ret = _hx509_collector_alloc(context, lock, &c);
549 for (p = f->fn; p != NULL; p = pnext) {
552 pnext = strchr(p, ',');
556 ret = parse_pem_file(context, p, c, &found_data);
565 ret = _hx509_map_file(p, &ptr, &length, NULL);
567 hx509_clear_error_string(context);
571 for (i = 0; i < sizeof(formats)/sizeof(formats[0]); i++) {
572 ret = (*formats[i].func)(context, p, c, NULL, ptr, length);
576 _hx509_unmap_file(ptr, length);
582 ret = _hx509_collector_collect_certs(context, c, &f->certs);
586 ret = _hx509_collector_collect_private_keys(context, c, &keys);
590 for (i = 0; keys[i]; i++)
591 _hx509_certs_keys_add(context, f->certs, keys[i]);
592 _hx509_certs_keys_free(context, keys);
604 _hx509_collector_free(c);
609 file_free(hx509_certs certs, void *data)
611 struct ks_file *f = data;
612 hx509_certs_free(&f->certs);
619 pem_header(FILE *f, const char *type, const char *str)
621 fprintf(f, "-----%s %s-----\n", type, str);
625 dump_pem_file(hx509_context context, const char *header,
626 FILE *f, const void *data, size_t size)
628 const char *p = data;
632 #define ENCODE_LINE_LENGTH 54
634 pem_header(f, "BEGIN", header);
640 if (length > ENCODE_LINE_LENGTH)
641 length = ENCODE_LINE_LENGTH;
643 l = base64_encode(p, length, &line);
645 hx509_set_error_string(context, 0, ENOMEM,
646 "malloc - out of memory");
650 fprintf(f, "%s\n", line);
655 pem_header(f, "END", header);
661 store_private_key(hx509_context context, FILE *f, hx509_private_key key)
663 heim_octet_string data;
666 ret = _hx509_private_key_export(context, key, &data);
668 dump_pem_file(context, _hx509_private_pem_name(key), f,
669 data.data, data.length);
675 store_func(hx509_context context, void *ctx, hx509_cert c)
677 FILE *f = (FILE *)ctx;
678 heim_octet_string data;
681 ret = hx509_cert_binary(context, c, &data);
685 dump_pem_file(context, "CERTIFICATE", f, data.data, data.length);
688 if (_hx509_cert_private_key_exportable(c))
689 store_private_key(context, f, _hx509_cert_private_key(c));
695 file_store(hx509_context context,
696 hx509_certs certs, void *data, int flags, hx509_lock lock)
698 struct ks_file *f = data;
702 fh = fopen(f->fn, "w");
704 hx509_set_error_string(context, 0, ENOENT,
705 "Failed to open file %s for writing");
709 ret = hx509_certs_iter(context, f->certs, store_func, fh);
715 file_add(hx509_context context, hx509_certs certs, void *data, hx509_cert c)
717 struct ks_file *f = data;
718 return hx509_certs_add(context, f->certs, c);
722 file_iter_start(hx509_context context,
723 hx509_certs certs, void *data, void **cursor)
725 struct ks_file *f = data;
726 return hx509_certs_start_seq(context, f->certs, cursor);
730 file_iter(hx509_context context,
731 hx509_certs certs, void *data, void *iter, hx509_cert *cert)
733 struct ks_file *f = data;
734 return hx509_certs_next_cert(context, f->certs, iter, cert);
738 file_iter_end(hx509_context context,
743 struct ks_file *f = data;
744 return hx509_certs_end_seq(context, f->certs, cursor);
748 file_getkeys(hx509_context context,
751 hx509_private_key **keys)
753 struct ks_file *f = data;
754 return _hx509_certs_keys_get(context, f->certs, keys);
758 file_addkey(hx509_context context,
761 hx509_private_key key)
763 struct ks_file *f = data;
764 return _hx509_certs_keys_add(context, f->certs, key);
767 static struct hx509_keyset_ops keyset_file = {
784 _hx509_ks_file_register(hx509_context context)
786 _hx509_ks_register(context, &keyset_file);