* Update configure script to remove the search for a linking tcl
[alpine.git] / pith / smkeys.c
blob5fd7f97ccc03d6753980deca48cf4e67def63ecb
1 #if !defined(lint) && !defined(DOS)
2 static char rcsid[] = "$Id: smkeys.c 1266 2009-07-14 18:39:12Z hubert@u.washington.edu $";
3 #endif
5 /*
6 * ========================================================================
7 * Copyright 2013-2018 Eduardo Chappa
8 * Copyright 2008 University of Washington
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
14 * http://www.apache.org/licenses/LICENSE-2.0
16 * ========================================================================
20 * This is based on a contribution from Jonathan Paisley, see smime.c
24 #include "../pith/headers.h"
26 #ifdef SMIME
28 #include "../pith/status.h"
29 #include "../pith/conf.h"
30 #include "../pith/remote.h"
31 #include "../pith/tempfile.h"
32 #include "../pith/busy.h"
33 #include "../pith/osdep/lstcmpnt.h"
34 #include "../pith/util.h"
35 #include "../pith/mailindx.h"
36 #include "../pith/readfile.h"
37 #include "smkeys.h"
39 #ifdef APPLEKEYCHAIN
40 #include <Security/SecKeychain.h>
41 #include <Security/SecKeychainItem.h>
42 #include <Security/SecKeychainSearch.h>
43 #include <Security/SecCertificate.h>
44 #endif /* APPLEKEYCHAIN */
47 /* internal prototypes */
48 static char *emailstrclean(char *string);
49 static int mem_add_extra_cacerts(char *contents, X509_LOOKUP *lookup);
50 int compare_certs_by_name(const void *data1, const void *data2);
51 int password_policy_check(char *);
53 int (*pith_smime_enter_password)(char *, char *, size_t);
55 /* test if password passes a predetermined policy.
56 * return value: 0 - does not pass; 1 - it passes
58 int
59 password_policy_check(char *password)
61 int rv = 1;
62 char *error;
63 char tmp[1024];
65 if(password == NULL || password[0] == '\0'){
66 error = _("Password cannot be blank");
67 rv = 0;
68 } else if(strlen(password) < 8){
69 error = _("Password is too short");
70 rv = 0;
72 if(rv == 0){
73 snprintf(tmp, sizeof(tmp), "%s%s", error, _(". Enter password again"));
74 tmp[sizeof(tmp) - 1] = '\0';
75 q_status_message(SM_ORDER, 3, 3, tmp);
77 return rv;
81 int
82 create_master_password(char *pass, size_t passlen, int first_time)
84 #define MAXTRIAL 3
85 int rv, trial;
86 char prompt[MAILTMPLEN];
87 char passbackup[MAILTMPLEN];
89 if(first_time)
90 q_status_message(SM_ORDER, 3, 3,
91 _(" Creating a Master Password for your Password file "));
92 else
93 q_status_message(SM_ORDER, 3, 3,
94 _(" Retrying to create a Master Password for your Password file "));
96 for(trial = 0; trial < MAXTRIAL; trial++){
97 snprintf(prompt, sizeof(prompt),
98 _("Create master password (attempt %d of %d): "), trial+1, MAXTRIAL);
99 prompt[sizeof(prompt)- 1] = '\0';
100 pass[0] = '\0';
101 do {
102 /* rv == 1 means cancel */
103 rv = (pith_smime_enter_password)(prompt, pass, passlen);
104 if(rv == 1 || password_policy_check(pass) == 0)
105 pass[0] = '\0';
106 if(rv == 1) return 0;
107 } while ((rv != 0 && rv != 1) || (rv == 0 && pass[0] == '\0'));
109 snprintf(prompt, sizeof(prompt),
110 _("Confirm master password (attempt %d of %d): "), trial+1, MAXTRIAL);
111 prompt[sizeof(prompt)- 1] = '\0';
112 passbackup[0] = '\0';
113 do {
114 rv = (pith_smime_enter_password)(prompt, passbackup, sizeof(passbackup));
115 } while ((rv !=0 && rv !=1 && rv > 0) || passbackup[0] == '\0');
116 if(!strcmp(pass, passbackup))
117 break;
118 if(trial + 1 < MAXTRIAL)
119 q_status_message(SM_ORDER, 2, 2, _("Passwords do not match, try again."));
120 else{
121 q_status_message(SM_ORDER, 2, 2, _("Passwords do not match, too many failures."));
122 pass[0] = '\0';
125 return (trial < MAXTRIAL) ? 1 : 0;
129 * Create a self signed certificate with root name _fname_, in directory
130 * _pathdir_. If _version_ is 3, we use the _template_ file as configuration
131 * file for openssl. At this moment, we only call this function with template = NULL
132 * and version = 0, but a sensible call is
133 * ALPINE_self_signed_certificate("/etc/ssl/openssl.cnf", 2, pathdir, fname, first_time);
134 * or so.
135 * _pathdir_ is the directory to save the file,
136 * _fname_ is the root of the name to use. Append ".key" and ".crt" to this name
137 * _first_time_ is an indicator to tell us if this is the first time we call this function
139 PERSONAL_CERT *
140 ALPINE_self_signed_certificate(char *template, int version, char *pathdir, char *fname)
142 BIGNUM *b = NULL;
143 X509_NAME *name = NULL;
144 X509_REQ *req = NULL;
145 EVP_PKEY_CTX *pkctx;
146 BIO *out = NULL;
147 char tmp[MAXPATH+1], password[1024];
148 char *keyfile = NULL, *certfile = NULL;
149 char *extensions = NULL;
150 FILE *fp;
151 long errline = -1L;
152 PERSONAL_CERT *pc = NULL;
153 EVP_PKEY *pkey = NULL;
154 X509 *pcert = NULL;
155 CONF *req_conf = NULL;
156 static int first_time = 1;
158 if(pathdir == NULL)
159 return NULL;
161 if(template){
162 if((out = BIO_new_file(template, "r")) == NULL){
163 q_status_message(SM_ORDER, 2, 2, _("Problem reading configuration file"));
164 return pc;
167 if((req_conf = NCONF_new(NULL)) != NULL
168 && NCONF_load_bio(req_conf, out, &errline) > 0){
169 if((extensions = NCONF_get_string(req_conf, "req", "x509_extensions")) != NULL){
170 X509V3_CTX ctx;
171 X509V3_set_ctx_test(&ctx);
172 X509V3_set_nconf(&ctx, req_conf);
173 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
174 q_status_message(SM_ORDER, 2, 2, _("Problem loading openssl configuration"));
175 NCONF_free(req_conf);
176 return pc;
180 BIO_free(out);
181 out = NULL;
184 if(create_master_password(password, sizeof(password), first_time)
185 && (pkctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL)) != NULL
186 && EVP_PKEY_keygen_init(pkctx) > 0
187 && EVP_PKEY_CTX_set_rsa_keygen_bits(pkctx, 2048) > 0 /* RSA:2048 */
188 && EVP_PKEY_keygen(pkctx, &pkey) > 0){
189 snprintf(tmp, sizeof(tmp), "%s.key", fname);
190 tmp[sizeof(tmp)-1] = '\0';
191 keyfile = cpystr(tmp);
192 build_path(tmp, pathdir, keyfile, sizeof(tmp));
193 keyfile[strlen(keyfile)-4] = '\0'; /* keyfile does not have .key extension */
194 if((fp = fopen(tmp, "w")) != NULL
195 && (out = BIO_new_fp(fp, BIO_CLOSE | BIO_FP_TEXT)) != NULL
196 && PEM_write_bio_PrivateKey(out, pkey, EVP_des_ede3_cbc(),
197 NULL, 0, NULL, password)){
198 BIO_free(out);
199 out = NULL;
201 memset((void *)password, 0, sizeof(password));
202 if((req = X509_REQ_new()) != NULL
203 && X509_REQ_set_version(req, 0L)){
204 name = X509_REQ_get_subject_name(req);
205 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, "Password File Certificate and Key Pair", -1, -1, 0);
206 if(X509_REQ_set_pubkey(req, pkey)
207 && (pcert = X509_new()) != NULL){
208 if(X509_set_version(pcert, version)
209 && (b = BN_new()) != NULL
210 && BN_set_word(b, 65537)
211 && BN_pseudo_rand(b, 64, 0, 0)
212 && X509_get_serialNumber(pcert)
213 && BN_to_ASN1_INTEGER(b, X509_get_serialNumber(pcert)) /* set serial */
214 && X509_set_issuer_name(pcert, X509_REQ_get_subject_name(req))
215 && X509_set_subject_name(pcert, X509_REQ_get_subject_name(req))){
216 X509V3_CTX ext_ctx;
217 EVP_PKEY *tmppkey;
219 X509_gmtime_adj(X509_getm_notBefore(pcert), 0);
220 X509_time_adj_ex(X509_getm_notAfter(pcert), 1095, 0, NULL);
222 if((tmppkey = X509_REQ_get0_pubkey(req)) != NULL
223 && X509_set_pubkey(pcert, tmppkey)){
224 if(extensions != NULL && version == 2){
225 X509V3_set_ctx(&ext_ctx, pcert, pcert, NULL, NULL, 0);
226 if(req_conf){ /* only if template is not null */
227 X509V3_set_nconf(&ext_ctx, req_conf);
228 X509V3_EXT_add_nconf(req_conf, &ext_ctx, extensions, pcert);
231 EVP_PKEY_free(tmppkey);
232 X509_sign(pcert, pkey, NULL);
234 BN_free(b);
239 snprintf(tmp, sizeof(tmp), "%s.crt", fname);
240 tmp[sizeof(tmp)-1] = '\0';
241 certfile = cpystr(tmp);
242 build_path(tmp, pathdir, certfile, sizeof(tmp));
243 if((fp = fopen(tmp, "w")) != NULL
244 &&(out = BIO_new_fp(fp, BIO_FP_TEXT)) != NULL){
245 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
246 PEM_write_bio_X509(out, pcert);
247 BIO_flush(out);
248 BIO_free(out);
249 out = NULL;
251 if(req_conf)
252 NCONF_free(req_conf);
254 if(keyfile && certfile && pkey && pcert){
255 pc = (PERSONAL_CERT *) fs_get(sizeof(PERSONAL_CERT));
256 memset((void *)pc, 0, sizeof(PERSONAL_CERT));
257 pc->name = keyfile;
258 pc->key = pkey;
259 pc->cert = pcert;
260 pc->cname = certfile;
262 first_time = 0;
263 return pc;
266 CertList *
267 smime_X509_to_cert_info(X509 *x, char *name)
269 CertList *cert;
270 char buf[MAXPATH+1];
272 if(x == NULL) return NULL;
274 cert = fs_get(sizeof(CertList));
275 memset((void *)cert, 0, sizeof(CertList));
276 cert->x509_cert = x;
277 cert->name = name ? cpystr(name) : NULL;
278 cert->data.date_from = smime_get_date(X509_get0_notBefore(x));
279 cert->data.date_to = smime_get_date(X509_get0_notAfter(x));
280 cert->cn = smime_get_cn(x);
281 get_fingerprint(x, EVP_md5(), buf, sizeof(buf), NULL);
282 cert->data.md5 = cpystr(buf);
284 return cert;
287 #define SMIME_BACKUP_DIR ".backup"
288 #define MAX_TRY_BACKUP 100
290 /* return value: 0 - success, -1 error
291 * Call this function after setting up paths in ps_global->smime
292 * and reading certificates names in certlist.
295 setup_certs_backup_by_type(WhichCerts ctype)
297 int rv = 0; /* assume success */
298 int len;
299 int i, done;
300 char *d, *fname;
301 char p[MAXPATH+1]; /* path to where the backup is */
302 char buf[MAXPATH+1], buf2[MAXPATH+1];
303 struct stat sbuf;
304 CertList *data, *cl;
305 #ifndef _WINDOWS
306 DIR *dirp;
307 struct dirent *df; /* file in the directory */
308 #else /* _WINDOWS */
309 struct _finddata_t dbuf;
310 char bufn[_MAX_PATH + 4];
311 long findrv;
312 #endif /* !_WINDOWS */
313 CertList *cert, *cl2;
314 X509 *x;
315 BIO *in;
317 return rv; /* remove when this function is complete */
319 if(SMHOLDERTYPE(ctype) == Directory){
320 d = PATHCERTDIR(ctype);
321 if(d != NULL){
322 len = strlen(d) + strlen(S_FILESEP) + strlen(SMIME_BACKUP_DIR) + 1;
323 snprintf(p, MAXPATH, "%s%s%s", d, S_FILESEP, SMIME_BACKUP_DIR);
324 p[MAXPATH] = '\0';
325 if(our_stat(p, &sbuf) < 0){
326 if(our_mkpath(p, 0700) != 0)
327 return -1;
328 } else if((sbuf.st_mode & S_IFMT) != S_IFDIR){
329 for(i = 0, done = 0; done == 0 && i < MAX_TRY_BACKUP; i++){
330 snprintf(buf2, len+2, "%s%d", p, i);
331 if(our_stat(buf2, &sbuf) < 0){
332 if(our_mkpath(buf2, 0700) == 0)
333 done++;
335 else if((sbuf.st_mode & S_IFMT) == S_IFDIR)
336 done++;
337 if(done){
338 strncpy(p, buf2, MAXPATH);
339 p[MAXPATH] = '\0';
342 if(done == 0)
343 return -1;
345 /* if we are here, we have a backup directory where to
346 * backup certificates/keys, so now we will go
347 * through the list of certificates and back them up
348 * if we need to.
350 data = BACKUPDATACERT(ctype);
351 for(cl = DATACERT(ctype); cl; cl = cl->next){
352 char clname[MAXPATH+1];
354 snprintf(clname, MAXPATH, "%s%s", cl->name, ctype == Private ? ".key" : "");
355 clname[MAXPATH] = '\0';
356 len = strlen(d) + strlen(clname) + 2;
357 if(len < MAXPATH){
358 snprintf(buf, len, "%s%s%s", d, S_FILESEP, clname);
359 buf[sizeof(buf)-1] = '\0';
360 len = strlen(p) + strlen(clname) + strlen(cl->data.md5) + 3;
361 if(len < MAXPATH){
362 snprintf(buf2, len, "%s%s%s.%s", p, S_FILESEP, clname, cl->data.md5);
363 buf2[sizeof(buf2)-1] = '\0';
364 done = 0; /* recycle done: it means we have a file that may be a certifificate*/
365 if(stat(buf2, &sbuf) < 0){
366 if (our_copy(buf2, buf) == 0)
367 done++;
368 } else if((sbuf.st_mode & S_IFMT) == S_IFREG)
369 done++;
371 if(done){
372 switch(ctype){
373 case Public:
374 case CACert:
375 if((in = BIO_new_file(buf2, "r"))!=0){
376 cert = fs_get(sizeof(CertList));
377 memset((void *)cert, 0, sizeof(CertList));
378 cert->x509_cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
379 if(cl->data.date_from != NULL)
380 cert->data.date_from = cpystr(cl->data.date_from);
381 if(cl->data.date_to != NULL)
382 cert->data.date_to = cpystr(cl->data.date_to);
383 if(cl->data.md5 != NULL)
384 cert->data.md5 = cpystr(cl->data.md5);
385 if(cl->cn != NULL)
386 cert->cn = cpystr(cl->cn);
387 snprintf(buf2, len, "%s.%s", cl->name, cl->data.md5);
388 buf2[sizeof(buf2)-1] = '\0';
389 cert->name = cpystr(buf2);
390 if(data == NULL)
391 data = cert;
392 else{
393 for (cl2 = data; cl2 && cl2->next; cl2 = cl2->next);
394 cl2->next = cert;
396 BIO_free(in);
398 break;
400 case Private: break;
401 default: alpine_panic("Bad ctype (0)");
407 /* if we are here, it means we just loaded the backup variable with
408 * a copy of the data that comes from the certlist not coming from
409 * backup. Now we are going to load the contents of the .backup
410 * directory.
413 /* Here is the plan: read the backup directory (in the variable "p")
414 * and attempt to add it. If already there, skip it; otherwise continue
416 #ifndef _WINDOWS
417 if ((dirp = opendir(p)) != NULL) {
418 while ((df = readdir(dirp)) != NULL) {
419 fname = df->d_name;
421 if (fname && *fname == '.') /* no hidden files here */
422 continue;
423 #else
424 snprintf(bufn, sizeof(bufn), "%s%s*.*", p, (p[strlen(p) - 1] == '\\') ? "" : "\\");
425 bufn[sizeof(bufn) - 1] = '\0';
426 if ((findrv = _findfirst(bufn, &dbuf)) >= 0) {
427 do {
428 fname = fname_to_utf8(dbuf.name);
429 #endif /* ! _WINDOWS */
430 /* make sure that we have a file */
431 snprintf(buf2, sizeof(buf2), "%s%s%s", p, S_FILESEP, fname);
432 buf2[sizeof(buf2) - 1] = '\0';
433 if (our_stat(buf2, &sbuf) == 0
434 && (sbuf.st_mode & S_IFMT) != S_IFREG)
435 continue;
437 /* make sure it is not already in the list */
438 for (cl = data; cl; cl = cl->next)
439 if (strcmp(cl->name, fname) == 0)
440 break;
441 if (cl != NULL)
442 continue;
444 /* ok, if it is not in the list, and it is a certificate. Add it */
445 switch (ctype) {
446 case Public:
447 case CACert:
448 if ((in = BIO_new_file(buf2, "r")) != 0) {
449 x = PEM_read_bio_X509(in, NULL, NULL, NULL);
450 if (x) { /* for now copy this information */
451 cert = smime_X509_to_cert_info(x, fname);
452 /* we will use the cert->data.md5 variable to find a backup
453 certificate, not the name */
454 cert->next = data;
455 data = cert;
457 BIO_free(in);
459 break;
461 case Private:
462 /* here we must check it is a key of some cert....*/
463 break;
465 default: alpine_panic("Bad ctype (1)");
466 } /* end switch */
467 #ifndef _WINDOWS
469 closedir(dirp);
470 #else /* _WINDOWS */
471 } while (_findnext(findrv, &dbuf) == 0);
472 _findclose(findrv);
473 #endif /* ! _WINDOWS */
475 /* Now that we are here, we have all the information in the backup
476 * directory
479 switch (ctype) {
480 case Public: ps_global->smime->backuppubliccertlist = data; break;
481 case Private: ps_global->smime->backupprivatecertlist = data; break;
482 case CACert: ps_global->smime->backupcacertlist = data; break;
483 default: alpine_panic("Bad ctype (n)");
486 } else if(SMHOLDERTYPE(ctype) == Container){
488 } /* else APPLEKEYCHAIN */
489 return rv;
492 char *
493 smime_get_cn(X509 *x)
495 X509_NAME_ENTRY *e;
496 X509_NAME *subject;
497 char buf[256];
498 char *rv = NULL;
500 subject = X509_get_subject_name(x);
501 if((e = X509_NAME_get_entry(subject, X509_NAME_entry_count(subject)-1)) != NULL){
502 X509_NAME_get_text_by_OBJ(subject, X509_NAME_ENTRY_get_object(e), buf, sizeof(buf));
503 rv = cpystr(buf);
506 return rv;
510 compare_certs_by_name(const void *data1, const void *data2)
512 int rv, i, j;
513 char *s;
515 CertList *cl1 = *(CertList **) data1;
516 CertList *cl2 = *(CertList **) data2;
518 i = j = -1;
519 if((s = strchr(cl1->name, '@')) != NULL){
520 i = s - cl1->name;
521 *s = '\0';
524 if((s = strchr(cl2->name, '@')) != NULL){
525 j = s - cl2->name;
526 *s = '\0';
529 if((rv = strucmp(cl1->name, cl2->name)) == 0)
530 rv = strucmp(cl1->name + i + 1, cl2->name + j + 1);
531 if(i >= 0) cl1->name[i] = '@';
532 if(j >= 0) cl2->name[j] = '@';
533 return rv;
536 void
537 resort_certificates(CertList **data, WhichCerts ctype)
539 int i, j;
540 CertList *cl = *data;
541 CertList **cll;
542 char *s, *t;
544 if(cl == NULL)
545 return;
547 for(i = 0; cl; cl = cl->next, i++)
548 if(SMHOLDERTYPE(ctype) == Directory && ctype != Private){
549 for(t = s = cl->name; (t = strstr(s, ".crt")) != NULL; s = t+1);
550 if (s) *(s-1) = '\0';
552 j = i;
553 cll = fs_get(i*sizeof(CertList *));
554 for(cl = *data, i = 0; cl; cl = cl->next, i++)
555 cll[i] = cl;
556 qsort((void *)cll, j, sizeof(CertList *), compare_certs_by_name);
557 for(i = 0; i < j - 1; i++){
558 cll[i]->next = cll[i+1];
559 if(SMHOLDERTYPE(ctype) == Directory && ctype != Private)
560 cll[i]->name[strlen(cll[i]->name)]= '.'; /* restore ".crt" part */
562 if(SMHOLDERTYPE(ctype) == Directory && ctype != Private)
563 cll[j-1]->name[strlen(cll[j-1]->name)]= '.'; /* restore ".crt" part */
564 cll[j-1]->next = NULL;
565 *data = cll[0];
569 void
570 get_fingerprint(X509 *cert, const EVP_MD *type, char *buf, size_t maxLen, char *s)
572 unsigned char md[128];
573 char *b;
574 unsigned int len, i;
576 len = sizeof(md);
578 X509_digest(cert, type, md, &len);
580 b = buf;
581 *b = 0;
582 for(i=0; i<len; i++){
583 if(b-buf+3>=maxLen)
584 break;
586 if(i != 0 && s && *s)
587 *b++ = *s;
589 snprintf(b, maxLen - (b-buf), "%02x", md[i]);
590 b+=2;
596 * Remove leading whitespace, trailing whitespace and convert
597 * to lowercase. Also remove slash characters
599 * Args: s, -- The string to clean
601 * Result: the cleaned string
603 static char *
604 emailstrclean(char *string)
606 char *s = string, *sc = NULL, *p = NULL;
608 for(; *s; s++){ /* single pass */
609 if(!isspace((unsigned char) (*s))){
610 p = NULL; /* not start of blanks */
611 if(!sc) /* first non-blank? */
612 sc = string; /* start copying */
614 else if(!p) /* it's OK if sc == NULL */
615 p = sc; /* start of blanks? */
617 if(sc && *s!='/' && *s!='\\') /* if copying, copy */
618 *sc++ = isupper((unsigned char) (*s))
619 ? (unsigned char) tolower((unsigned char) (*s))
620 : (unsigned char) (*s);
623 if(p) /* if ending blanks */
624 *p = '\0'; /* tie off beginning */
625 else if(!sc) /* never saw a non-blank */
626 *string = '\0'; /* so tie whole thing off */
628 return(string);
632 char *
633 smime_get_date(const ASN1_TIME *tm)
635 BIO *mb = BIO_new(BIO_s_mem());
636 char iobuf[4096];
637 char date[MAILTMPLEN];
638 char buf[MAILTMPLEN];
639 char *m, *d, *t, *y, *z;
640 int len;
641 struct date smd;
642 struct tm smtm;
644 (void) BIO_reset(mb);
645 if(ASN1_TIME_print(mb, tm) == 0)
646 return cpystr(_("Invalid"));
648 (void) BIO_flush(mb);
649 len = BIO_read(mb, iobuf, sizeof(iobuf));
650 iobuf[len-1] = '\0';
652 /* openssl returns the date in the format:
653 * "MONTH (as name) DAY (as number) TIME(hh:mm:ss) YEAR GMT"
655 m = iobuf;
656 d = strchr(iobuf, ' ');
657 *d++ = '\0';
658 while(*d == ' ') d++;
659 t = strchr(d+1, ' ');
660 *t++ = '\0';
661 while(*t == ' ') t++;
662 y = strchr(t+1, ' ');
663 *y++ = '\0';
664 while(*y == ' ') y++;
665 z = strchr(y+1, ' ');
666 *z++ = '\0';
667 while(*z == ' ') z++;
669 snprintf(date, sizeof(date), "%s %s %s %s (%s)", d, m, y, t, z);
670 date[sizeof(date)-1] = '\0';
671 if(F_ON(F_DATES_TO_LOCAL,ps_global)){
672 parse_date(convert_date_to_local(date), &smd);
673 memset(&smtm, 0, sizeof(smtm));
674 smtm.tm_year = smd.year - 1900;
675 smtm.tm_mon = MIN(MAX(smd.month-1, 0), 11);
676 smtm.tm_mday = MIN(MAX(smd.day, 1), 31);
677 our_strftime(buf, sizeof(buf), "%x", &smtm);
679 else
680 snprintf(buf, sizeof(buf), "%s/%s/%s", m, d, y + strlen(y) - 2);
681 buf[sizeof(buf)-1] = '\0';
683 BIO_free(mb);
684 return cpystr(buf);
688 * Add a lookup for each "*.crt*" file in the given directory.
691 add_certs_in_dir(X509_LOOKUP *lookup, char *path, char *ext, CertList **cdata)
693 char buf[MAXPATH], *fname;
694 #ifndef _WINDOWS
695 struct direct *d;
696 DIR *dirp;
697 #else /* _WINDOWS */
698 struct _finddata_t dbuf;
699 char bufn[_MAX_PATH + 4];
700 long findrv;
701 #endif /* !_WINDOWS */
702 CertList *cert, *cl;
703 int ret = 0, nfiles = 0, nerr = 0;
705 #ifndef _WINDOWS
706 if((dirp = opendir(path)) != NULL){
707 while(!ret && (d=readdir(dirp)) != NULL){
708 fname = d->d_name;
709 #else /* _WINDOWS */
710 snprintf(bufn, sizeof(bufn), "%s%s*.*", path, (path[strlen(path)-1] == '\\') ? "" : "\\");
711 bufn[sizeof(bufn)-1] = '\0';
712 if((findrv = _findfirst(bufn, &dbuf)) >= 0){
714 fname = fname_to_utf8(dbuf.name);
715 #endif /* ! _WINDOWS */
716 if(srchrstr(fname, ext)){
717 nfiles++;
718 build_path(buf, path, fname, sizeof(buf));
720 if(!X509_LOOKUP_load_file(lookup, buf, X509_FILETYPE_PEM)){
721 q_status_message1(SM_ORDER, 3, 3, _("Error loading file %s"), buf);
722 nerr++;
723 } else {
724 if(cdata){
725 BIO *in;
726 X509 *x;
728 cert = fs_get(sizeof(CertList));
729 memset((void *)cert, 0, sizeof(CertList));
730 cert->name = cpystr(fname);
731 /* read buf into a bio and fill the CertData structure */
732 if((in = BIO_new_file(buf, "r"))!=0){
733 if((x = PEM_read_bio_X509(in, NULL, NULL, NULL)) != NULL){
734 cert->data.date_from = smime_get_date(X509_get0_notBefore(x));
735 cert->data.date_to = smime_get_date(X509_get0_notAfter(x));
736 get_fingerprint(x, EVP_md5(), buf, sizeof(buf), NULL);
737 cert->data.md5 = cpystr(buf);
738 cert->cn = smime_get_cn(x);
739 X509_free(x);
741 BIO_free(in);
743 if(*cdata == NULL)
744 *cdata = cert;
745 else{
746 for (cl = *cdata; cl && cl->next; cl = cl->next);
747 cl->next = cert;
754 #ifndef _WINDOWS
756 closedir(dirp);
757 #else /* _WINDOWS */
758 } while(_findnext(findrv, &dbuf) == 0);
759 _findclose(findrv);
760 #endif /* ! _WINDOWS */
763 /* if all certificates fail to load */
764 if(nerr > 0 && nerr == nfiles) ret = -1;
765 return ret;
770 * Get an X509_STORE. This consists of the system
771 * certs directory and any certificates in the user's
772 * ~/.alpine-smime/ca directory.
774 X509_STORE *
775 get_ca_store(void)
777 X509_LOOKUP *lookup;
778 X509_STORE *store = NULL;
780 dprint((9, "get_ca_store()"));
782 if(!(store=X509_STORE_new())){
783 dprint((9, "X509_STORE_new() failed"));
784 return store;
787 if(!(lookup=X509_STORE_add_lookup(store, X509_LOOKUP_file()))){
788 dprint((9, "X509_STORE_add_lookup() failed"));
789 X509_STORE_free(store);
790 return NULL;
793 if(ps_global->smime && ps_global->smime->catype == Container
794 && ps_global->smime->cacontent){
796 if(!mem_add_extra_cacerts(ps_global->smime->cacontent, lookup)){
797 X509_STORE_free(store);
798 return NULL;
801 else if(ps_global->smime && ps_global->smime->catype == Directory
802 && ps_global->smime->capath){
803 if(add_certs_in_dir(lookup, ps_global->smime->capath, ".crt", &ps_global->smime->cacertlist) < 0){
804 X509_STORE_free(store);
805 return NULL;
807 resort_certificates(&ps_global->smime->cacertlist, CACert);
810 if(!(lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()))){
811 X509_STORE_free(store);
812 return NULL;
815 #ifdef SMIME_SSLCERTS
816 dprint((9, "get_ca_store(): adding cacerts from %s", SMIME_SSLCERTS));
817 X509_LOOKUP_add_dir(lookup, SMIME_SSLCERTS, X509_FILETYPE_PEM);
818 #endif
820 return store;
824 EVP_PKEY *
825 load_key(PERSONAL_CERT *pc, char *pass, int flag)
827 BIO *in;
828 EVP_PKEY *key = NULL;
829 char buf[MAXPATH], file[MAXPATH];
831 if(!(ps_global->smime && pc && pc->name))
832 return key;
834 if(ps_global->smime->privatetype == Container){
835 char *q;
837 if(pc->keytext && (q = strstr(pc->keytext, "-----END")) != NULL){
838 while(*q && *q != '\n')
839 q++;
841 if(*q == '\n')
842 q++;
844 if((in = BIO_new_mem_buf(pc->keytext, q-pc->keytext)) != NULL){
845 key = PEM_read_bio_PrivateKey(in, NULL, NULL, pass);
846 BIO_free(in);
850 else if(ps_global->smime->privatetype == Directory){
851 /* filename is path/name.key */
852 strncpy(buf, pc->name, sizeof(buf)-5);
853 buf[sizeof(buf)-5] = '\0';
854 strncat(buf, ".key", 5);
855 build_path(file, ps_global->smime->privatepath, buf, sizeof(file));
857 if(!(in = BIO_new_file(file, "r")))
858 return NULL;
860 key = PEM_read_bio_PrivateKey(in, NULL, NULL, pass);
861 BIO_free(in);
864 return key;
868 #include <openssl/x509v3.h>
870 * This newer version is from Adrian Vogel. It looks for the email
871 * address not only in the email address field, but also in an
872 * X509v3 extension field, Subject Altenative Name.
874 char **
875 get_x509_subject_email(X509 *x)
877 char **result = NULL;
878 int i, n;
879 STACK_OF(OPENSSL_STRING) *emails = X509_get1_email(x);
880 if ((n = sk_OPENSSL_STRING_num(emails)) > 0) {
881 result = fs_get((n+1)*sizeof(char *));
882 for(i = 0; i < n; i++)
883 result[i] = cpystr(sk_OPENSSL_STRING_value(emails, i));
884 result[i] = NULL;
886 X509_email_free(emails);
887 return result;
892 * Save the certificate for the given email address in
893 * ~/.alpine-smime/public.
895 * Should consider the security hazards in making a file with
896 * the email address that has come from the certificate.
898 * The argument email is destroyed.
900 * args: ctype says where the user wants to save the certificate
902 void
903 save_cert_for(char *email, X509 *cert, WhichCerts ctype)
905 if(!ps_global->smime || ctype == Private)
906 return;
908 dprint((9, "save_cert_for(%s, %s)", email ? email : "?", ctype == Public ? _("Public") : ctype == Private ? _("Private") : "CACert"));
909 emailstrclean(email);
911 if(ps_global->smime->publictype == Keychain){
912 #ifdef APPLEKEYCHAIN
914 OSStatus rc;
915 SecCertificateRef secCertificateRef;
916 CSSM_DATA certData;
918 memset((void *) &certData, 0, sizeof(certData));
919 memset((void *) &secCertificateRef, 0, sizeof(secCertificateRef));
921 /* convert OpenSSL X509 cert data to MacOS certData */
922 if((certData.Length = i2d_X509(cert, &(certData.Data))) > 0){
925 * Put that certData into a SecCertificateRef.
926 * Version 3 should work for versions 1-3.
928 if(!(rc=SecCertificateCreateFromData(&certData,
929 CSSM_CERT_X_509v3,
930 CSSM_CERT_ENCODING_DER,
931 &secCertificateRef))){
933 /* add it to the default keychain */
934 if(!(rc=SecCertificateAddToKeychain(secCertificateRef, NULL))){
935 /* ok */
937 else if(rc == errSecDuplicateItem){
938 dprint((9, "save_cert_for: certificate for %s already in keychain", email));
940 else{
941 dprint((9, "SecCertificateAddToKeychain failed"));
944 else{
945 dprint((9, "SecCertificateCreateFromData failed"));
948 else{
949 dprint((9, "i2d_X509 failed"));
952 #endif /* APPLEKEYCHAIN */
954 else if(SMHOLDERTYPE(ctype) == Container){
955 REMDATA_S *rd = NULL;
956 char *ret_dir = NULL;
957 char path[MAXPATH];
958 char fpath[MAXPATH];
959 char *upath = PATHCERTDIR(ctype);
960 char *tempfile = NULL;
961 int err = 0;
962 CertList *clist = DATACERT(ctype);
964 add_to_end_of_certlist(&clist, email, X509_dup(cert));
966 switch(ctype){
967 case Private: ps_global->smime->privatecertlist = clist; break;
968 case Public : ps_global->smime->publiccertlist = clist; break;
969 case CACert : ps_global->smime->cacertlist = clist; break;
970 default: break;
973 if(!upath)
974 return;
976 if(IS_REMOTE(upath)){
977 rd = rd_create_remote(RemImap, upath, REMOTE_SMIME_SUBTYPE,
978 NULL, "Error: ",
979 _("Can't access remote smime configuration."));
980 if(!rd){
981 return;
984 (void) rd_read_metadata(rd);
986 if(rd->access == MaybeRorW){
987 if(rd->read_status == 'R')
988 rd->access = ReadOnly;
989 else
990 rd->access = ReadWrite;
993 if(rd->access != NoExists){
995 rd_check_remvalid(rd, 1L);
998 * If the cached info says it is readonly but
999 * it looks like it's been fixed now, change it to readwrite.
1001 if(rd->read_status == 'R'){
1002 rd_check_readonly_access(rd);
1003 if(rd->read_status == 'W'){
1004 rd->access = ReadWrite;
1005 rd->flags |= REM_OUTOFDATE;
1007 else
1008 rd->access = ReadOnly;
1012 if(rd->flags & REM_OUTOFDATE){
1013 if(rd_update_local(rd) != 0){
1015 dprint((1, "save_cert_for: rd_update_local failed\n"));
1016 rd_close_remdata(&rd);
1017 return;
1020 else
1021 rd_open_remote(rd);
1023 if(rd->access != ReadWrite || rd_remote_is_readonly(rd)){
1024 rd_close_remdata(&rd);
1025 return;
1028 rd->flags |= DO_REMTRIM;
1030 strncpy(path, rd->lf, sizeof(path)-1);
1031 path[sizeof(path)-1] = '\0';
1033 else{
1034 strncpy(path, upath, sizeof(path)-1);
1035 path[sizeof(path)-1] = '\0';
1038 tempfile = tempfile_in_same_dir(path, "az", &ret_dir);
1039 if(tempfile){
1040 if(certlist_to_file(tempfile, DATACERT(ctype)))
1041 err++;
1043 if(!err && ret_dir){
1044 if(IS_REMOTE(upath)){
1045 strncpy(fpath, rd->lf, sizeof(fpath));
1046 fpath[sizeof(fpath)-1] = '\0';
1048 else{
1049 if(strlen(path) + strlen(tempfile) - strlen(ret_dir) + 1 < sizeof(path))
1050 snprintf(fpath, sizeof(fpath), "%s%c%s",
1051 path, tempfile[strlen(ret_dir)], tempfile + strlen(ret_dir) + 1);
1052 else
1053 err++;
1056 else err++;
1058 fs_give((void **)&ret_dir);
1060 if(!err){
1061 if(rename_file(tempfile, fpath) < 0){
1062 q_status_message2(SM_ORDER, 3, 3,
1063 _("Can't rename %s to %s"), tempfile, fpath);
1064 err++;
1068 if(!err && IS_REMOTE(upath)){
1069 int e, we_cancel;
1070 char datebuf[200];
1072 datebuf[0] = '\0';
1074 we_cancel = busy_cue(_("Copying to remote smime container"), NULL, 1);
1075 if((e = rd_update_remote(rd, datebuf)) != 0){
1076 if(e == -1){
1077 q_status_message2(SM_ORDER | SM_DING, 3, 5,
1078 _("Error opening temporary smime file %s: %s"),
1079 rd->lf, error_description(errno));
1080 dprint((1,
1081 "write_remote_smime: error opening temp file %s\n",
1082 rd->lf ? rd->lf : "?"));
1084 else{
1085 q_status_message2(SM_ORDER | SM_DING, 3, 5,
1086 _("Error copying to %s: %s"),
1087 rd->rn, error_description(errno));
1088 dprint((1,
1089 "write_remote_smime: error copying from %s to %s\n",
1090 rd->lf ? rd->lf : "?", rd->rn ? rd->rn : "?"));
1093 q_status_message(SM_ORDER | SM_DING, 5, 5,
1094 _("Copy of smime cert to remote folder failed, changes NOT saved remotely"));
1096 else{
1097 rd_update_metadata(rd, datebuf);
1098 rd->read_status = 'W';
1101 rd_close_remdata(&rd);
1103 if(we_cancel)
1104 cancel_busy_cue(-1);
1107 fs_give((void **) &tempfile);
1110 else if(SMHOLDERTYPE(ctype) == Directory){
1111 char *path = PATHCERTDIR(ctype);
1112 char certfilename[MAXPATH];
1113 BIO *bio_out;
1115 build_path(certfilename, path, email, sizeof(certfilename));
1116 strncat(certfilename, ".crt", sizeof(certfilename)-1-strlen(certfilename));
1117 certfilename[sizeof(certfilename)-1] = 0;
1119 bio_out = BIO_new_file(certfilename, "w");
1120 if(bio_out){
1121 PEM_write_bio_X509(bio_out, cert);
1122 BIO_free(bio_out);
1123 q_status_message1(SM_ORDER, 1, 1, _("Saved certificate for <%s>"), email);
1125 else{
1126 q_status_message1(SM_ORDER, 1, 1, _("Couldn't save certificate for <%s>"), email);
1133 * Try to retrieve the certificate for the given email address.
1134 * The caller should free the cert.
1136 X509 *
1137 get_cert_for(char *email, WhichCerts ctype, int tolower)
1139 char certfilename[MAXPATH];
1140 char emailaddr[MAXPATH];
1141 X509 *cert = NULL;
1142 BIO *in;
1144 if(ctype == Password){
1145 build_path(certfilename, PATHCERTDIR(ctype), email, sizeof(certfilename));
1146 strncat(certfilename, EXTCERT(Public), sizeof(certfilename)-1-strlen(certfilename));
1147 certfilename[sizeof(certfilename)-1] = 0;
1149 if((in = BIO_new_file(certfilename, "r"))!=0){
1151 cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
1153 if(cert){
1154 /* could check email addr in cert matches */
1157 BIO_free(in);
1160 return cert;
1163 if(!ps_global->smime)
1164 return cert;
1166 dprint((9, "get_cert_for(%s, %s)", email ? email : "?", "none yet"));
1168 if(ctype == Private) /* there is no private certificate info */
1169 ctype = Public; /* return public information instead */
1170 strncpy(emailaddr, email, sizeof(emailaddr)-1);
1171 emailaddr[sizeof(emailaddr)-1] = 0;
1173 /* clean it up (lowercase, space removal) */
1174 if(tolower)
1175 emailstrclean(emailaddr);
1177 if(ps_global->smime->publictype == Keychain){
1178 #ifdef APPLEKEYCHAIN
1180 OSStatus rc;
1181 SecKeychainItemRef itemRef = nil;
1182 SecKeychainAttributeList attrList;
1183 SecKeychainAttribute attrib;
1184 SecKeychainSearchRef searchRef = nil;
1185 CSSM_DATA certData;
1187 /* low-level form of MacOS data */
1188 memset((void *) &certData, 0, sizeof(certData));
1190 attrList.count = 1;
1191 attrList.attr = &attrib;
1193 /* kSecAlias means email address for a certificate */
1194 attrib.tag = kSecAlias;
1195 attrib.data = emailaddr;
1196 attrib.length = strlen(attrib.data);
1198 /* Find the certificate in the default keychain */
1199 if(!(rc=SecKeychainSearchCreateFromAttributes(NULL,
1200 kSecCertificateItemClass,
1201 &attrList,
1202 &searchRef))){
1204 if(!(rc=SecKeychainSearchCopyNext(searchRef, &itemRef))){
1206 /* extract the data portion of the certificate */
1207 if(!(rc=SecCertificateGetData((SecCertificateRef) itemRef, &certData))){
1210 * Convert it from MacOS form to OpenSSL form.
1211 * The input is certData from above and the output
1212 * is the X509 *cert.
1214 if(!d2i_X509(&cert, &(certData.Data), certData.Length)){
1215 dprint((9, "d2i_X509 failed"));
1218 else{
1219 dprint((9, "SecCertificateGetData failed"));
1222 else if(rc == errSecItemNotFound){
1223 dprint((9, "get_cert_for: Public cert for %s not found", emailaddr));
1225 else{
1226 dprint((9, "SecKeychainSearchCopyNext failed"));
1229 else{
1230 dprint((9, "SecKeychainSearchCreateFromAttributes failed"));
1233 if(searchRef)
1234 CFRelease(searchRef);
1236 #endif /* APPLEKEYCHAIN */
1238 else if(SMHOLDERTYPE(ctype) == Container){
1239 CertList *cl;
1241 for(cl = DATACERT(ctype); cl; cl = cl->next){
1242 if(cl->name && !strucmp(emailaddr, cl->name))
1243 break;
1246 if(cl)
1247 cert = X509_dup((X509 *) cl->x509_cert);
1249 else if(SMHOLDERTYPE(ctype) == Directory){
1250 build_path(certfilename, PATHCERTDIR(ctype), emailaddr, sizeof(certfilename));
1251 strncat(certfilename, EXTCERT(ctype), sizeof(certfilename)-1-strlen(certfilename));
1252 certfilename[sizeof(certfilename)-1] = 0;
1254 if((in = BIO_new_file(certfilename, "r"))!=0){
1256 cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
1258 if(cert){
1259 /* could check email addr in cert matches */
1262 BIO_free(in);
1267 return cert;
1271 * load_cert_for_key finds a certificate in pathdir that matches a private key
1272 * pkey. It returns its name in certfile, and the certificate in *pcert.
1273 * return value: success: different from zero, failure 0. If both certfile
1274 * and pcert are NULL, this function returns if there is certificate that
1275 * matches the given key.
1278 load_cert_for_key(char *pathdir, EVP_PKEY *pkey, char **certfile, X509 **pcert)
1280 #ifndef _WINDOWS
1281 DIR *dirp;
1282 struct dirent *d;
1283 #else /* _WINDOWS */
1284 struct _finddata_t dbuf;
1285 char bufn[_MAX_PATH + 4];
1286 long findrv;
1287 #endif /* ! _WINDOWS */
1288 size_t ll;
1289 int rv = 0;
1290 BIO *in;
1291 X509 *x;
1292 char buf[MAXPATH+1], pathcert[MAXPATH+1], *fname;
1294 if(pathdir == NULL || pkey == NULL)
1295 return 0;
1297 if(certfile) *certfile = NULL;
1298 if(pcert) *pcert = NULL;
1300 #ifndef _WINDOWS
1301 if((dirp = opendir(pathdir)) != NULL){
1302 while(rv == 0 && (d=readdir(dirp)) != NULL){
1303 fname = d->d_name;
1304 #else
1305 snprintf(bufn, sizeof(bufn), "%s%s*.*", pathdir, (pathdir[strlen(pathdir)-1] == '\\') ? "" : "\\");
1306 bufn[sizeof(bufn)-1] = '\0';
1307 if((findrv = _findfirst(bufn, &dbuf)) >= 0){
1309 fname = fname_to_utf8(dbuf.name);
1310 #endif /* ! _WINDOWS */
1311 if((ll=strlen(fname)) && ll > 4){
1312 if(!strcmp(fname+ll-4, ".crt")){
1313 strncpy(buf, fname, sizeof(buf));
1314 buf[sizeof(buf)-1] = '\0';
1315 build_path(pathcert, pathdir, buf, sizeof(pathcert));
1316 if((in = BIO_new_file(pathcert, "r")) != NULL){
1317 if((x = PEM_read_bio_X509(in, NULL, NULL, NULL)) != NULL){
1318 if(X509_check_private_key(x, pkey) > 0){
1319 rv = 1;
1320 if(certfile) *certfile = cpystr(buf);
1321 if(pcert) *pcert = x;
1323 else
1324 X509_free(x);
1326 BIO_free(in);
1330 #ifndef _WINDOWS
1332 closedir(dirp);
1333 #else /* _WINDOWS */
1334 } while(_findnext(findrv, &dbuf) == 0);
1335 _findclose(findrv);
1336 #endif
1338 return rv;
1342 PERSONAL_CERT *
1343 mem_to_personal_certs(char *contents)
1345 PERSONAL_CERT *result = NULL;
1346 char *p, *q, *line, *name, *keytext, *save_p;
1347 X509 *cert = NULL;
1349 if(contents && *contents){
1350 for(p = contents; *p != '\0';){
1351 line = p;
1353 while(*p && *p != '\n')
1354 p++;
1356 save_p = NULL;
1357 if(*p == '\n'){
1358 save_p = p;
1359 *p++ = '\0';
1362 if(strncmp(EMAILADDRLEADER, line, strlen(EMAILADDRLEADER)) == 0){
1363 name = line + strlen(EMAILADDRLEADER);
1364 cert = get_cert_for(name, Public, 1);
1365 keytext = p;
1367 /* advance p past this record */
1368 if((q = strstr(keytext, "-----END")) != NULL){
1369 while(*q && *q != '\n')
1370 q++;
1372 if(*q == '\n')
1373 q++;
1375 p = q;
1377 else{
1378 p = p + strlen(p);
1379 q_status_message(SM_ORDER | SM_DING, 3, 3, _("Error in privatekey container, missing END"));
1382 if(cert){
1383 PERSONAL_CERT *pc;
1385 pc = (PERSONAL_CERT *) fs_get(sizeof(*pc));
1386 pc->cert = cert;
1387 pc->name = cpystr(name);
1388 pc->cname = NULL;
1389 pc->keytext = keytext; /* a pointer into contents */
1391 pc->key = load_key(pc, "", SM_NORMALCERT);
1393 pc->next = result;
1394 result = pc;
1398 if(save_p)
1399 *save_p = '\n';
1403 return result;
1407 CertList *
1408 mem_to_certlist(char *contents, WhichCerts ctype)
1410 CertList *ret = NULL;
1411 char *p, *q, *line, *name, *certtext, *save_p;
1412 X509 *cert = NULL;
1413 BIO *in;
1414 char *sep = (ctype == Public || ctype == Private)
1415 ? EMAILADDRLEADER : CACERTSTORELEADER;
1417 if(contents && *contents){
1418 for(p = contents; *p != '\0';){
1419 line = p;
1421 while(*p && *p != '\n')
1422 p++;
1424 save_p = NULL;
1425 if(*p == '\n'){
1426 save_p = p;
1427 *p++ = '\0';
1430 if(strncmp(sep, line, strlen(sep)) == 0){
1431 name = line + strlen(sep);
1432 cert = NULL;
1433 certtext = strstr(p, "-----BEGIN");
1434 if(certtext != NULL){
1435 if((q = strstr(certtext, sep)) != NULL)
1436 p = q;
1437 else
1438 p = q = certtext+strlen(certtext);
1440 if((in = BIO_new_mem_buf(certtext, q-certtext)) != 0){
1441 cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
1442 BIO_free(in);
1445 else{
1446 q_status_message2(SM_ORDER | SM_DING, 3, 3, _("Error in %scert container, missing BEGIN, certtext=%s"), ctype == Public ? _("public") : _("ca"), p);
1447 p = p + strlen(p);
1450 if(name && cert)
1451 add_to_end_of_certlist(&ret, name, cert);
1454 if(save_p)
1455 *save_p = '\n';
1458 if(ret != NULL)
1459 resort_certificates(&ret, ctype);
1461 return ret;
1466 * Add the CACert Container contents into the CACert store.
1468 * Returns > 0 for success, 0 for failure
1471 mem_add_extra_cacerts(char *contents, X509_LOOKUP *lookup)
1473 char *p, *q, *line, *certtext, *save_p;
1474 BIO *in, *out;
1475 int len, failed = 0;
1476 char *tempfile;
1477 char iobuf[4096];
1480 * The most straight-forward way to do this is to write
1481 * the container contents to a temp file and then load the
1482 * contents of the file with X509_LOOKUP_load_file(), like
1483 * is done in add_certs_in_dir(). What we don't know is if
1484 * each file should consist of one cacert or if they can all
1485 * just be jammed together into one file. To be safe, we'll use
1486 * one file per and do each in a separate operation.
1489 if(contents && *contents){
1490 for(p = contents; *p != '\0';){
1491 line = p;
1493 while(*p && *p != '\n')
1494 p++;
1496 save_p = NULL;
1497 if(*p == '\n'){
1498 save_p = p;
1499 *p++ = '\0';
1502 /* look for separator line */
1503 if(strncmp(CACERTSTORELEADER, line, strlen(CACERTSTORELEADER)) == 0){
1504 /* certtext is the content that should go in a file */
1505 certtext = strstr(p, "-----BEGIN");
1506 if(certtext != NULL){
1507 if((q = strstr(certtext, CACERTSTORELEADER)) != NULL){
1508 p = q;
1510 else{ /* end of file */
1511 q = certtext + strlen(certtext);
1512 p = q;
1515 in = BIO_new_mem_buf(certtext, q-certtext);
1516 if(in){
1517 tempfile = temp_nam(NULL, "az");
1518 out = tempfile != NULL ? BIO_new_file(tempfile, "w") : NULL;
1519 if(out != NULL){
1520 while((len = BIO_read(in, iobuf, sizeof(iobuf))) > 0)
1521 BIO_write(out, iobuf, len);
1523 BIO_free(out);
1524 if(!X509_LOOKUP_load_file(lookup, tempfile, X509_FILETYPE_PEM))
1525 failed++;
1528 if(tempfile != NULL){
1529 unlink(tempfile);
1530 fs_give((void **) &tempfile);
1533 BIO_free(in);
1536 else{
1537 p = p + strlen(p);
1538 q_status_message1(SM_ORDER | SM_DING, 3, 3, _("Error in cacert container, missing BEGIN, certtext=%s"), certtext);
1541 else{
1542 p = p + strlen(p);
1543 q_status_message1(SM_ORDER | SM_DING, 3, 3, _("Error in cacert container, missing separator, line=%s"), line);
1546 if(save_p)
1547 *save_p = '\n';
1551 return(!failed);
1556 certlist_to_file(char *filename, CertList *certlist)
1558 CertList *cl;
1559 BIO *bio_out = NULL;
1560 int ret = -1;
1562 if(filename && (bio_out=BIO_new_file(filename, "w")) != NULL){
1563 ret = 0;
1564 for(cl = certlist; cl; cl = cl->next){
1565 if(cl->name && cl->name[0] && cl->x509_cert){
1566 if(!((BIO_puts(bio_out, EMAILADDRLEADER) > 0)
1567 && (BIO_puts(bio_out, cl->name) > 0)
1568 && (BIO_puts(bio_out, "\n") > 0)))
1569 ret = -1;
1571 if(!PEM_write_bio_X509(bio_out, (X509 *) cl->x509_cert))
1572 ret = -1;
1576 BIO_free(bio_out);
1579 return ret;
1583 void
1584 add_to_end_of_certlist(CertList **cl, char *name, X509 *cert)
1586 CertList *new;
1588 if(!cl)
1589 return;
1591 new = smime_X509_to_cert_info(cert, name);
1592 new->next = *cl;
1593 *cl = new;
1597 void
1598 free_certlist(CertList **cl)
1600 if(cl && *cl){
1601 if((*cl)->data.date_from)
1602 fs_give((void **) &(*cl)->data.date_from);
1604 if((*cl)->data.date_to)
1605 fs_give((void **) &(*cl)->data.date_to);
1607 if((*cl)->data.md5)
1608 fs_give((void **) &(*cl)->data.md5);
1610 if((*cl)->name)
1611 fs_give((void **) &(*cl)->name);
1613 if((*cl)->cn)
1614 fs_give((void **) &(*cl)->cn);
1616 if((*cl)->x509_cert)
1617 X509_free((X509 *) (*cl)->x509_cert);
1619 free_certlist(&(*cl)->next);
1621 fs_give((void **) cl);
1626 void
1627 free_personal_certs(PERSONAL_CERT **pc)
1629 if(pc && *pc){
1630 if((*pc)->name)
1631 fs_give((void **) &(*pc)->name);
1633 if((*pc)->cname)
1634 fs_give((void **) &(*pc)->cname);
1636 if((*pc)->cert)
1637 X509_free((*pc)->cert);
1639 if((*pc)->key)
1640 EVP_PKEY_free((*pc)->key);
1642 free_personal_certs(&(*pc)->next);
1644 fs_give((void **) pc);
1648 #endif /* SMIME */