hx509: create files with safe mode_t
[heimdal.git] / lib / hx509 / ks_file.c
blob6e8f5b1aa7a8fb5f7b632a495df78d80ed4bf291
1 /*
2 * Copyright (c) 2005 - 2007 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
4 * All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
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
31 * SUCH DAMAGE.
34 #include "hx_locl.h"
36 typedef enum { USE_PEM, USE_DER } outformat;
38 struct ks_file {
39 hx509_certs certs;
40 char *fn;
41 outformat format;
48 static int
49 parse_certificate(hx509_context context, const char *fn,
50 struct hx509_collector *c,
51 const hx509_pem_header *headers,
52 const void *data, size_t len,
53 const AlgorithmIdentifier *ai)
55 heim_error_t error = NULL;
56 hx509_cert cert;
57 int ret;
59 cert = hx509_cert_init_data(context, data, len, &error);
60 if (cert == NULL) {
61 ret = heim_error_get_code(error);
62 heim_release(error);
63 return ret;
66 ret = _hx509_collector_certs_add(context, c, cert);
67 hx509_cert_free(cert);
68 return ret;
71 static int
72 try_decrypt(hx509_context context,
73 struct hx509_collector *collector,
74 const AlgorithmIdentifier *alg,
75 const EVP_CIPHER *c,
76 const void *ivdata,
77 const void *password,
78 size_t passwordlen,
79 const void *cipher,
80 size_t len)
82 heim_octet_string clear;
83 size_t keylen;
84 void *key;
85 int ret;
87 keylen = EVP_CIPHER_key_length(c);
89 key = malloc(keylen);
90 if (key == NULL) {
91 hx509_clear_error_string(context);
92 return ENOMEM;
95 ret = EVP_BytesToKey(c, EVP_md5(), ivdata,
96 password, passwordlen,
97 1, key, NULL);
98 if (ret <= 0) {
99 ret = HX509_CRYPTO_INTERNAL_ERROR;
100 hx509_set_error_string(context, 0, ret,
101 "Failed to do string2key for private key");
102 goto out;
105 clear.data = malloc(len);
106 if (clear.data == NULL) {
107 hx509_set_error_string(context, 0, ENOMEM,
108 "Out of memory to decrypt for private key");
109 ret = ENOMEM;
110 goto out;
112 clear.length = len;
115 EVP_CIPHER_CTX ctx;
116 EVP_CIPHER_CTX_init(&ctx);
117 EVP_CipherInit_ex(&ctx, c, NULL, key, ivdata, 0);
118 EVP_Cipher(&ctx, clear.data, cipher, len);
119 EVP_CIPHER_CTX_cleanup(&ctx);
122 ret = _hx509_collector_private_key_add(context,
123 collector,
124 alg,
125 NULL,
126 &clear,
127 NULL);
129 memset_s(clear.data, clear.length, 0, clear.length);
130 free(clear.data);
131 out:
132 memset_s(key, keylen, 0, keylen);
133 free(key);
134 return ret;
137 static int
138 parse_pkcs8_private_key(hx509_context context, const char *fn,
139 struct hx509_collector *c,
140 const hx509_pem_header *headers,
141 const void *data, size_t length,
142 const AlgorithmIdentifier *ai)
144 PKCS8PrivateKeyInfo ki;
145 heim_octet_string keydata;
147 int ret;
149 ret = decode_PKCS8PrivateKeyInfo(data, length, &ki, NULL);
150 if (ret)
151 return ret;
153 keydata.data = rk_UNCONST(data);
154 keydata.length = length;
156 ret = _hx509_collector_private_key_add(context,
158 &ki.privateKeyAlgorithm,
159 NULL,
160 &ki.privateKey,
161 &keydata);
162 free_PKCS8PrivateKeyInfo(&ki);
163 return ret;
166 static int
167 parse_pem_private_key(hx509_context context, const char *fn,
168 struct hx509_collector *c,
169 const hx509_pem_header *headers,
170 const void *data, size_t len,
171 const AlgorithmIdentifier *ai)
173 int ret = 0;
174 const char *enc;
176 enc = hx509_pem_find_header(headers, "Proc-Type");
177 if (enc) {
178 const char *dek;
179 char *type, *iv;
180 ssize_t ssize, size;
181 void *ivdata;
182 const EVP_CIPHER *cipher;
183 const struct _hx509_password *pw;
184 hx509_lock lock;
185 int decrypted = 0;
186 size_t i;
188 lock = _hx509_collector_get_lock(c);
189 if (lock == NULL) {
190 hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
191 "Failed to get password for "
192 "password protected file %s", fn);
193 return HX509_ALG_NOT_SUPP;
196 if (strcmp(enc, "4,ENCRYPTED") != 0) {
197 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
198 "Private key encrypted in unknown method %s "
199 "in file",
200 enc, fn);
201 hx509_clear_error_string(context);
202 return HX509_PARSING_KEY_FAILED;
205 dek = hx509_pem_find_header(headers, "DEK-Info");
206 if (dek == NULL) {
207 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
208 "Encrypted private key missing DEK-Info");
209 return HX509_PARSING_KEY_FAILED;
212 type = strdup(dek);
213 if (type == NULL) {
214 hx509_clear_error_string(context);
215 return ENOMEM;
218 iv = strchr(type, ',');
219 if (iv == NULL) {
220 free(type);
221 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
222 "IV missing");
223 return HX509_PARSING_KEY_FAILED;
226 *iv++ = '\0';
228 size = strlen(iv);
229 ivdata = malloc(size);
230 if (ivdata == NULL) {
231 hx509_clear_error_string(context);
232 free(type);
233 return ENOMEM;
236 cipher = EVP_get_cipherbyname(type);
237 if (cipher == NULL) {
238 free(ivdata);
239 hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
240 "Private key encrypted with "
241 "unsupported cipher: %s",
242 type);
243 free(type);
244 return HX509_ALG_NOT_SUPP;
247 #define PKCS5_SALT_LEN 8
249 ssize = hex_decode(iv, ivdata, size);
250 free(type);
251 type = NULL;
252 iv = NULL;
254 if (ssize < 0 || ssize < PKCS5_SALT_LEN || ssize < EVP_CIPHER_iv_length(cipher)) {
255 free(ivdata);
256 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
257 "Salt have wrong length in "
258 "private key file");
259 return HX509_PARSING_KEY_FAILED;
262 pw = _hx509_lock_get_passwords(lock);
263 if (pw != NULL) {
264 const void *password;
265 size_t passwordlen;
267 for (i = 0; i < pw->len; i++) {
268 password = pw->val[i];
269 passwordlen = strlen(password);
271 ret = try_decrypt(context, c, ai, cipher, ivdata,
272 password, passwordlen, data, len);
273 if (ret == 0) {
274 decrypted = 1;
275 break;
279 if (!decrypted) {
280 hx509_prompt prompt;
281 char password[128];
283 memset(&prompt, 0, sizeof(prompt));
285 prompt.prompt = "Password for keyfile: ";
286 prompt.type = HX509_PROMPT_TYPE_PASSWORD;
287 prompt.reply.data = password;
288 prompt.reply.length = sizeof(password);
290 ret = hx509_lock_prompt(lock, &prompt);
291 if (ret == 0)
292 ret = try_decrypt(context, c, ai, cipher, ivdata, password,
293 strlen(password), data, len);
294 /* XXX add password to lock password collection ? */
295 memset_s(password, sizeof(password), 0, sizeof(password));
297 free(ivdata);
299 } else {
300 heim_octet_string keydata;
302 keydata.data = rk_UNCONST(data);
303 keydata.length = len;
305 ret = _hx509_collector_private_key_add(context, c, ai, NULL,
306 &keydata, NULL);
309 return ret;
313 struct pem_formats {
314 const char *name;
315 int (*func)(hx509_context, const char *, struct hx509_collector *,
316 const hx509_pem_header *, const void *, size_t,
317 const AlgorithmIdentifier *);
318 const AlgorithmIdentifier *(*ai)(void);
319 } formats[] = {
320 { "CERTIFICATE", parse_certificate, NULL },
321 { "PRIVATE KEY", parse_pkcs8_private_key, NULL },
322 { "RSA PRIVATE KEY", parse_pem_private_key, hx509_signature_rsa },
323 #ifdef HAVE_HCRYPTO_W_OPENSSL
324 { "EC PRIVATE KEY", parse_pem_private_key, hx509_signature_ecPublicKey }
325 #endif
329 struct pem_ctx {
330 int flags;
331 struct hx509_collector *c;
334 static int
335 pem_func(hx509_context context, const char *type,
336 const hx509_pem_header *header,
337 const void *data, size_t len, void *ctx)
339 struct pem_ctx *pem_ctx = (struct pem_ctx*)ctx;
340 int ret = 0;
341 size_t j;
343 for (j = 0; j < sizeof(formats)/sizeof(formats[0]); j++) {
344 const char *q = formats[j].name;
345 if (strcasecmp(type, q) == 0) {
346 const AlgorithmIdentifier *ai = NULL;
347 if (formats[j].ai != NULL)
348 ai = (*formats[j].ai)();
350 ret = (*formats[j].func)(context, NULL, pem_ctx->c,
351 header, data, len, ai);
352 if (ret && (pem_ctx->flags & HX509_CERTS_UNPROTECT_ALL)) {
353 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
354 "Failed parseing PEM format %s", type);
355 return ret;
357 break;
360 if (j == sizeof(formats)/sizeof(formats[0])) {
361 ret = HX509_UNSUPPORTED_OPERATION;
362 hx509_set_error_string(context, 0, ret,
363 "Found no matching PEM format for %s", type);
364 return ret;
366 return 0;
373 static int
374 file_init_common(hx509_context context,
375 hx509_certs certs, void **data, int flags,
376 const char *residue, hx509_lock lock, outformat format)
378 char *p, *pnext;
379 struct ks_file *ksf = NULL;
380 hx509_private_key *keys = NULL;
381 int ret;
382 struct pem_ctx pem_ctx;
384 pem_ctx.flags = flags;
385 pem_ctx.c = NULL;
387 if (residue == NULL || residue[0] == '\0') {
388 hx509_set_error_string(context, 0, EINVAL,
389 "PEM file name not specified");
390 return EINVAL;
393 *data = NULL;
395 if (lock == NULL)
396 lock = _hx509_empty_lock;
398 ksf = calloc(1, sizeof(*ksf));
399 if (ksf == NULL) {
400 hx509_clear_error_string(context);
401 return ENOMEM;
403 ksf->format = format;
405 ksf->fn = strdup(residue);
406 if (ksf->fn == NULL) {
407 hx509_clear_error_string(context);
408 ret = ENOMEM;
409 goto out;
413 * XXX this is broken, the function should parse the file before
414 * overwriting it
417 if (flags & HX509_CERTS_CREATE) {
419 * Note that the file creation is deferred until file_store() is
420 * called.
422 ret = hx509_certs_init(context, "MEMORY:ks-file-create",
423 0, lock, &ksf->certs);
424 if (ret)
425 goto out;
426 *data = ksf;
427 return 0;
430 ret = _hx509_collector_alloc(context, lock, &pem_ctx.c);
431 if (ret)
432 goto out;
434 for (p = ksf->fn; p != NULL; p = pnext) {
435 FILE *f;
437 pnext = strchr(p, ',');
438 if (pnext)
439 *pnext++ = '\0';
442 if ((f = fopen(p, "r")) == NULL) {
443 ret = ENOENT;
444 hx509_set_error_string(context, 0, ret,
445 "Failed to open PEM file \"%s\": %s",
446 p, strerror(errno));
447 goto out;
449 rk_cloexec_file(f);
451 ret = hx509_pem_read(context, f, pem_func, &pem_ctx);
452 fclose(f);
453 if (ret != 0 && ret != HX509_PARSING_KEY_FAILED)
454 goto out;
455 else if (ret == HX509_PARSING_KEY_FAILED) {
456 size_t length;
457 void *ptr;
458 size_t i;
460 ret = rk_undumpdata(p, &ptr, &length);
461 if (ret) {
462 hx509_clear_error_string(context);
463 goto out;
466 for (i = 0; i < sizeof(formats)/sizeof(formats[0]); i++) {
467 const AlgorithmIdentifier *ai = NULL;
468 if (formats[i].ai != NULL)
469 ai = (*formats[i].ai)();
471 ret = (*formats[i].func)(context, p, pem_ctx.c, NULL, ptr, length, ai);
472 if (ret == 0)
473 break;
475 rk_xfree(ptr);
476 if (ret) {
477 hx509_clear_error_string(context);
478 goto out;
483 ret = _hx509_collector_collect_certs(context, pem_ctx.c, &ksf->certs);
484 if (ret)
485 goto out;
487 ret = _hx509_collector_collect_private_keys(context, pem_ctx.c, &keys);
488 if (ret == 0) {
489 int i;
491 for (i = 0; keys[i]; i++)
492 _hx509_certs_keys_add(context, ksf->certs, keys[i]);
493 _hx509_certs_keys_free(context, keys);
496 out:
497 if (ret == 0)
498 *data = ksf;
499 else {
500 if (ksf->fn)
501 free(ksf->fn);
502 free(ksf);
504 if (pem_ctx.c)
505 _hx509_collector_free(pem_ctx.c);
507 return ret;
510 static int
511 file_init_pem(hx509_context context,
512 hx509_certs certs, void **data, int flags,
513 const char *residue, hx509_lock lock)
515 return file_init_common(context, certs, data, flags, residue, lock, USE_PEM);
518 static int
519 file_init_der(hx509_context context,
520 hx509_certs certs, void **data, int flags,
521 const char *residue, hx509_lock lock)
523 return file_init_common(context, certs, data, flags, residue, lock, USE_DER);
526 static int
527 file_free(hx509_certs certs, void *data)
529 struct ks_file *ksf = data;
530 hx509_certs_free(&ksf->certs);
531 free(ksf->fn);
532 free(ksf);
533 return 0;
536 struct store_ctx {
537 FILE *f;
538 outformat format;
541 static int HX509_LIB_CALL
542 store_func(hx509_context context, void *ctx, hx509_cert c)
544 struct store_ctx *sc = ctx;
545 heim_octet_string data;
546 int ret;
548 if (hx509_cert_have_private_key_only(c)) {
549 data.length = 0;
550 data.data = NULL;
551 } else {
552 ret = hx509_cert_binary(context, c, &data);
553 if (ret)
554 return ret;
557 switch (sc->format) {
558 case USE_DER:
559 if (data.data) {
560 fwrite(data.data, data.length, 1, sc->f);
561 free(data.data);
562 } /* XXX else write private key instead */
563 break;
564 case USE_PEM:
565 if (data.data) {
566 hx509_pem_write(context, "CERTIFICATE", NULL, sc->f,
567 data.data, data.length);
568 free(data.data);
570 if (_hx509_cert_private_key_exportable(c)) {
571 hx509_private_key key = _hx509_cert_private_key(c);
572 ret = _hx509_private_key_export(context, key,
573 HX509_KEY_FORMAT_DER, &data);
574 if (ret)
575 break;
576 hx509_pem_write(context, _hx509_private_pem_name(key), NULL, sc->f,
577 data.data, data.length);
578 free(data.data);
580 break;
583 return 0;
586 static int
587 file_store(hx509_context context,
588 hx509_certs certs, void *data, int flags, hx509_lock lock)
590 struct ks_file *ksf = data;
591 struct store_ctx sc;
592 int ret;
593 int fd;
595 sc.f = NULL;
596 fd = open(ksf->fn, O_CREAT | O_WRONLY, 0600);
597 if (fd > -1)
598 sc.f = fdopen(fd, "w");
599 if (sc.f == NULL) {
600 hx509_set_error_string(context, 0, ret = errno,
601 "Failed to open file %s for writing", ksf->fn);
602 if (fd > -1)
603 (void) close(fd);
604 return ret;
606 rk_cloexec_file(sc.f);
607 sc.format = ksf->format;
609 ret = hx509_certs_iter_f(context, ksf->certs, store_func, &sc);
610 fclose(sc.f);
611 return ret;
614 static int
615 file_add(hx509_context context, hx509_certs certs, void *data, hx509_cert c)
617 struct ks_file *ksf = data;
618 return hx509_certs_add(context, ksf->certs, c);
621 static int
622 file_iter_start(hx509_context context,
623 hx509_certs certs, void *data, void **cursor)
625 struct ks_file *ksf = data;
626 return hx509_certs_start_seq(context, ksf->certs, cursor);
629 static int
630 file_iter(hx509_context context,
631 hx509_certs certs, void *data, void *iter, hx509_cert *cert)
633 struct ks_file *ksf = data;
634 return hx509_certs_next_cert(context, ksf->certs, iter, cert);
637 static int
638 file_iter_end(hx509_context context,
639 hx509_certs certs,
640 void *data,
641 void *cursor)
643 struct ks_file *ksf = data;
644 return hx509_certs_end_seq(context, ksf->certs, cursor);
647 static int
648 file_getkeys(hx509_context context,
649 hx509_certs certs,
650 void *data,
651 hx509_private_key **keys)
653 struct ks_file *ksf = data;
654 return _hx509_certs_keys_get(context, ksf->certs, keys);
657 static int
658 file_addkey(hx509_context context,
659 hx509_certs certs,
660 void *data,
661 hx509_private_key key)
663 struct ks_file *ksf = data;
664 return _hx509_certs_keys_add(context, ksf->certs, key);
667 static struct hx509_keyset_ops keyset_file = {
668 "FILE",
670 file_init_pem,
671 file_store,
672 file_free,
673 file_add,
674 NULL,
675 file_iter_start,
676 file_iter,
677 file_iter_end,
678 NULL,
679 file_getkeys,
680 file_addkey
683 static struct hx509_keyset_ops keyset_pemfile = {
684 "PEM-FILE",
686 file_init_pem,
687 file_store,
688 file_free,
689 file_add,
690 NULL,
691 file_iter_start,
692 file_iter,
693 file_iter_end,
694 NULL,
695 file_getkeys,
696 file_addkey
699 static struct hx509_keyset_ops keyset_derfile = {
700 "DER-FILE",
702 file_init_der,
703 file_store,
704 file_free,
705 file_add,
706 NULL,
707 file_iter_start,
708 file_iter,
709 file_iter_end,
710 NULL,
711 file_getkeys,
712 file_addkey
716 HX509_LIB_FUNCTION void HX509_LIB_CALL
717 _hx509_ks_file_register(hx509_context context)
719 _hx509_ks_register(context, &keyset_file);
720 _hx509_ks_register(context, &keyset_pemfile);
721 _hx509_ks_register(context, &keyset_derfile);