* S/MIME: information on certificates is now available for certificates
[alpine.git] / pith / smkeys.c
blob7e992a53b22d743f48160483954c328b0dcd909d
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-2015 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);
52 #define SMIME_BACKUP_DIR ".backup"
53 #define MAX_TRY_BACKUP 100
55 /* return value: 0 - success, -1 error
56 * Call this function after setting up paths in ps_global->smime
57 * and reading certificates names in certlist.
59 int
60 setup_certs_backup_by_type(WhichCerts ctype)
62 int rv = 0; /* assume success */
63 int len;
64 int i, done;
65 char *d;
66 char p[MAXPATH+1]; /* path to where the backup is */
67 char buf[MAXPATH+1], buf2[MAXPATH+1];
68 struct stat sbuf;
69 CertList *data, *cl;
70 DIR *dirp;
71 struct dirent *df; /* file in the directory */
72 CertList *cert, *cl2;
73 X509 *x;
74 BIO *in;
76 return rv; /* remove when this function is complete */
78 if(SMHOLDERTYPE(ctype) == Directory){
79 d = PATHCERTDIR(ctype);
80 if(d != NULL){
81 len = strlen(d) + strlen(S_FILESEP) + strlen(SMIME_BACKUP_DIR) + 1;
82 snprintf(p, MAXPATH, "%s%s%s", d, S_FILESEP, SMIME_BACKUP_DIR);
83 p[MAXPATH] = '\0';
84 if(our_stat(p, &sbuf) < 0){
85 if(our_mkpath(p, 0700) != 0)
86 return -1;
87 } else if((sbuf.st_mode & S_IFMT) != S_IFDIR){
88 for(i = 0, done = 0; done == 0 && i < MAX_TRY_BACKUP; i++){
89 snprintf(buf2, len+2, "%s%d", p, i);
90 if(our_stat(buf2, &sbuf) < 0){
91 if(our_mkpath(buf2, 0700) == 0)
92 done++;
94 else if((sbuf.st_mode & S_IFMT) == S_IFDIR)
95 done++;
96 if(done){
97 strncpy(p, buf2, MAXPATH);
98 p[MAXPATH] = '\0';
101 if(done == 0)
102 return -1;
104 /* if we are here, we have a backup directory where to
105 * backup certificates/keys, so now we will go
106 * through the list of certificates and back them up
107 * if we need to.
109 data = BACKUPDATACERT(ctype);
110 for(cl = DATACERT(ctype); cl; cl = cl->next){
111 char clname[MAXPATH+1];
113 snprintf(clname, MAXPATH, "%s%s", cl->name, ctype == Private ? ".key" : "");
114 clname[MAXPATH] = '\0';
115 len = strlen(d) + strlen(clname) + 2;
116 if(len < MAXPATH){
117 snprintf(buf, len, "%s%s%s", d, S_FILESEP, clname);
118 buf[sizeof(buf)-1] = '\0';
119 len = strlen(p) + strlen(clname) + strlen(cl->data.md5) + 3;
120 if(len < MAXPATH){
121 snprintf(buf2, len, "%s%s%s.%s", p, S_FILESEP, clname, cl->data.md5);
122 buf2[sizeof(buf2)-1] = '\0';
123 done = 0; /* recycle done: it means we have a file that may be a certifificate*/
124 if(stat(buf2, &sbuf) < 0){
125 if (our_copy(buf2, buf) == 0)
126 done++;
127 } else if((sbuf.st_mode & S_IFMT) == S_IFREG)
128 done++;
130 if(done){
131 switch(ctype){
132 case Public:
133 case CACert:
134 if((in = BIO_new_file(buf2, "r"))!=0){
135 cert = fs_get(sizeof(CertList));
136 memset((void *)cert, 0, sizeof(CertList));
137 cert->x509_cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
138 if(cl->data.date_from != NULL)
139 cert->data.date_from = cpystr(cl->data.date_from);
140 if(cl->data.date_to != NULL)
141 cert->data.date_to = cpystr(cl->data.date_to);
142 if(cl->data.md5 != NULL)
143 cert->data.md5 = cpystr(cl->data.md5);
144 snprintf(buf2, len, "%s.%s", cl->name, cl->data.md5);
145 buf2[sizeof(buf2)-1] = '\0';
146 cert->name = cpystr(buf2);
147 if(data == NULL)
148 data = cert;
149 else{
150 for (cl2 = data; cl2 && cl2->next; cl2 = cl2->next);
151 cl2->next = cert;
153 BIO_free(in);
155 break;
157 case Private: break;
158 default: alpine_panic("Bad ctype (0)");
164 /* if we are here, it means we just loaded the backup variable with
165 * a copy of the data that comes from the certlist not coming from
166 * backup. Now we are going to load the contents of the .backup
167 * directory.
170 /* Here is the plan: read the backup directory (in the variable "p")
171 * and attempt to add it. If already there, skip it; otherwise continue
174 if((dirp = opendir(p)) != NULL){
175 while((df=readdir(dirp)) != NULL){
176 if(df->d_name && *df->d_name == '.') /* no hidden files here */
177 continue;
179 /* make sure that we have a file */
180 snprintf(buf2, sizeof(buf2), "%s%s%s", p, S_FILESEP, df->d_name);
181 buf2[sizeof(buf2)-1] = '\0';
182 if(our_stat(buf2, &sbuf) == 0
183 && (sbuf.st_mode & S_IFMT) != S_IFREG)
184 continue;
186 /* make sure it is not already in the list */
187 for(cl = data; cl; cl = cl->next)
188 if(strcmp(cl->name, df->d_name) == 0)
189 break;
190 if(cl != NULL)
191 continue;
193 /* ok, if it is not in the list, and it is a certificate. Add it */
194 switch(ctype){
195 case Public:
196 case CACert:
197 if((in = BIO_new_file(buf2, "r"))!=0){
198 x = PEM_read_bio_X509(in, NULL, NULL, NULL);
199 if(x && x->cert_info){ /* for now copy this information */
200 cert = fs_get(sizeof(CertList));
201 memset((void *)cert, 0, sizeof(CertList));
202 cert->x509_cert = x;
203 cert->data.date_from = smime_get_date(x->cert_info->validity->notBefore);
204 cert->data.date_to = smime_get_date(x->cert_info->validity->notAfter);
205 get_fingerprint(x, EVP_md5(), buf, sizeof(buf), NULL);
206 cert->data.md5 = cpystr(buf);
207 cert->name = cpystr(df->d_name);
208 /* we will use the cert->data.md5 variable to find a backup
209 certificate, not the name */
210 if(data == NULL)
211 data = cert;
212 else{
213 for (cl2 = data; cl2 && cl2->next; cl2 = cl2->next);
214 cl2->next = cert;
217 BIO_free(in);
219 break;
221 case Private:
222 /* here we must check it is a key of some cert....*/
223 break;
225 default: alpine_panic("Bad ctype (1)");
226 } /* end switch */
228 closedir(dirp);
231 /* Now that we are here, we have all the information in the backup
232 * directory
235 switch(ctype){
236 case Public : ps_global->smime->backuppubliccertlist = data; break;
237 case Private: ps_global->smime->backupprivatecertlist = data; break;
238 case CACert : ps_global->smime->backupcacertlist = data; break;
239 default : alpine_panic("Bad ctype (n)");
242 } else if(SMHOLDERTYPE(ctype) == Container){
244 } /* else APPLEKEYCHAIN */
245 return rv;
249 compare_certs_by_name(const void *data1, const void *data2)
251 int rv, i, j;
252 char *s;
254 CertList *cl1 = *(CertList **) data1;
255 CertList *cl2 = *(CertList **) data2;
257 i = j = -1;
258 if((s = strchr(cl1->name, '@')) != NULL){
259 i = s - cl1->name;
260 *s = '\0';
263 if((s = strchr(cl2->name, '@')) != NULL){
264 j = s - cl2->name;
265 *s = '\0';
268 if((rv = strucmp(cl1->name, cl2->name)) == 0)
269 rv = strucmp(cl1->name + i + 1, cl2->name + j + 1);
270 if(i >= 0) cl1->name[i] = '@';
271 if(j >= 0) cl2->name[j] = '@';
272 return rv;
275 void
276 resort_certificates(CertList **data, WhichCerts ctype)
278 int i, j;
279 CertList *cl = *data;
280 CertList **cll;
281 char *s, *t;
283 if(cl == NULL)
284 return;
286 for(i = 0; cl; cl = cl->next, i++)
287 if(ctype != Private){ /* ctype == Public or ctype == CACerts */
288 for(t = s = cl->name; (t = strstr(s, ".crt")) != NULL; s = t+1);
289 if (s) *(s-1) = '\0';
291 j = i;
292 cll = fs_get(i*sizeof(CertList *));
293 for(cl = *data, i = 0; cl; cl = cl->next, i++)
294 cll[i] = cl;
295 qsort((void *)cll, j, sizeof(CertList *), compare_certs_by_name);
296 for(i = 0; i < j - 1; i++){
297 cll[i]->next = cll[i+1];
298 if(ctype != Private)
299 cll[i]->name[strlen(cll[i]->name)]= '.'; /* restore ".crt" part */
301 if(ctype != Private)
302 cll[j-1]->name[strlen(cll[j-1]->name)]= '.'; /* restore ".crt" part */
303 cll[j-1]->next = NULL;
304 *data = cll[0];
308 void
309 get_fingerprint(X509 *cert, const EVP_MD *type, char *buf, size_t maxLen, char *s)
311 unsigned char md[128];
312 char *b;
313 unsigned int len, i;
315 len = sizeof(md);
317 X509_digest(cert, type, md, &len);
319 b = buf;
320 *b = 0;
321 for(i=0; i<len; i++){
322 if(b-buf+3>=maxLen)
323 break;
325 if(i != 0 && s && *s)
326 *b++ = *s;
328 snprintf(b, maxLen - (b-buf), "%02x", md[i]);
329 b+=2;
335 * Remove leading whitespace, trailing whitespace and convert
336 * to lowercase. Also remove slash characters
338 * Args: s, -- The string to clean
340 * Result: the cleaned string
342 static char *
343 emailstrclean(char *string)
345 char *s = string, *sc = NULL, *p = NULL;
347 for(; *s; s++){ /* single pass */
348 if(!isspace((unsigned char) (*s))){
349 p = NULL; /* not start of blanks */
350 if(!sc) /* first non-blank? */
351 sc = string; /* start copying */
353 else if(!p) /* it's OK if sc == NULL */
354 p = sc; /* start of blanks? */
356 if(sc && *s!='/' && *s!='\\') /* if copying, copy */
357 *sc++ = isupper((unsigned char) (*s))
358 ? (unsigned char) tolower((unsigned char) (*s))
359 : (unsigned char) (*s);
362 if(p) /* if ending blanks */
363 *p = '\0'; /* tie off beginning */
364 else if(!sc) /* never saw a non-blank */
365 *string = '\0'; /* so tie whole thing off */
367 return(string);
371 char *
372 smime_get_date(ASN1_GENERALIZEDTIME *tm)
374 BIO *mb = BIO_new(BIO_s_mem());
375 char iobuf[4096];
376 char date[MAILTMPLEN];
377 char buf[MAILTMPLEN];
378 char *m, *d, *t, *y, *z;
379 struct date smd;
380 struct tm smtm;
382 (void) BIO_reset(mb);
383 if(ASN1_TIME_print(mb, tm) == 0)
384 return cpystr(_("Invalid"));
386 (void) BIO_flush(mb);
387 BIO_read(mb, iobuf, sizeof(iobuf));
389 /* openssl returns the date in the format:
390 * "MONTH (as name) DAY (as number) TIME(hh:mm:ss) YEAR GMT"
392 m = iobuf;
393 d = strchr(iobuf, ' ');
394 *d++ = '\0';
395 while(*d == ' ') d++;
396 t = strchr(d+1, ' ');
397 *t++ = '\0';
398 while(*t == ' ') t++;
399 y = strchr(t+1, ' ');
400 *y++ = '\0';
401 while(*y == ' ') y++;
402 z = strchr(y+1, ' ');
403 *z++ = '\0';
404 while(*z == ' ') z++;
406 snprintf(date, sizeof(date), "%s %s %s %s (%s)", d, m, y, t, z);
407 date[sizeof(date)-1] = '\0';
408 if(F_ON(F_DATES_TO_LOCAL,ps_global)){
409 parse_date(convert_date_to_local(date), &smd);
410 memset(&smtm, 0, sizeof(smtm));
411 smtm.tm_year = MIN(MAX(smd.year-1900, 0), 2000) % 100 - 1900;
412 smtm.tm_mon = MIN(MAX(smd.month-1, 0), 11);
413 smtm.tm_mday = MIN(MAX(smd.day, 1), 31);
414 our_strftime(buf, sizeof(buf), "%x", &smtm);
416 else
417 snprintf(buf, sizeof(buf), "%s/%s/%s", m, d, y + strlen(y) - 2);
418 buf[sizeof(buf)-1] = '\0';
420 return cpystr(buf);
424 * Add a lookup for each "*.crt*" file in the given directory.
427 add_certs_in_dir(X509_LOOKUP *lookup, char *path, char *ext, CertList **cdata)
429 char buf[MAXPATH];
430 struct direct *d;
431 DIR *dirp;
432 CertList *cert, *cl;
433 int ret = 0;
435 if((dirp = opendir(path)) != NULL){
436 while(!ret && (d=readdir(dirp)) != NULL){
437 if(srchrstr(d->d_name, ext)){
438 build_path(buf, path, d->d_name, sizeof(buf));
440 if(!X509_LOOKUP_load_file(lookup, buf, X509_FILETYPE_PEM)){
441 q_status_message1(SM_ORDER, 3, 3, _("Error loading file %s"), buf);
442 ret = -1;
443 } else {
444 if(cdata){
445 BIO *in;
446 X509 *x;
448 cert = fs_get(sizeof(CertList));
449 memset((void *)cert, 0, sizeof(CertList));
450 cert->name = cpystr(d->d_name);
451 /* read buf into a bio and fill the CertData structure */
452 if((in = BIO_new_file(buf, "r"))!=0){
453 x = PEM_read_bio_X509(in, NULL, NULL, NULL);
454 if(x && x->cert_info){
455 cert->data.date_from = smime_get_date(x->cert_info->validity->notBefore);
456 cert->data.date_to = smime_get_date(x->cert_info->validity->notAfter);
457 get_fingerprint(x, EVP_md5(), buf, sizeof(buf), NULL);
458 cert->data.md5 = cpystr(buf);
459 X509_free(x);
461 BIO_free(in);
463 if(*cdata == NULL)
464 *cdata = cert;
465 else{
466 for (cl = *cdata; cl && cl->next; cl = cl->next);
467 cl->next = cert;
476 closedir(dirp);
479 return ret;
484 * Get an X509_STORE. This consists of the system
485 * certs directory and any certificates in the user's
486 * ~/.alpine-smime/ca directory.
488 X509_STORE *
489 get_ca_store(void)
491 X509_LOOKUP *lookup;
492 X509_STORE *store = NULL;
494 dprint((9, "get_ca_store()"));
496 if(!(store=X509_STORE_new())){
497 dprint((9, "X509_STORE_new() failed"));
498 return store;
501 if(!(lookup=X509_STORE_add_lookup(store, X509_LOOKUP_file()))){
502 dprint((9, "X509_STORE_add_lookup() failed"));
503 X509_STORE_free(store);
504 return NULL;
507 if(ps_global->smime && ps_global->smime->catype == Container
508 && ps_global->smime->cacontent){
510 if(!mem_add_extra_cacerts(ps_global->smime->cacontent, lookup)){
511 X509_STORE_free(store);
512 return NULL;
515 else if(ps_global->smime && ps_global->smime->catype == Directory
516 && ps_global->smime->capath){
517 if(add_certs_in_dir(lookup, ps_global->smime->capath, ".crt", &ps_global->smime->cacertlist) < 0){
518 X509_STORE_free(store);
519 return NULL;
521 resort_certificates(&ps_global->smime->cacertlist, CACert);
524 if(!(lookup=X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()))){
525 X509_STORE_free(store);
526 return NULL;
529 #ifdef SMIME_SSLCERTS
530 dprint((9, "get_ca_store(): adding cacerts from %s", SMIME_SSLCERTS));
531 X509_LOOKUP_add_dir(lookup, SMIME_SSLCERTS, X509_FILETYPE_PEM);
532 #endif
534 return store;
538 EVP_PKEY *
539 load_key(PERSONAL_CERT *pc, char *pass, int flag)
541 BIO *in;
542 EVP_PKEY *key = NULL;
543 char buf[MAXPATH], file[MAXPATH];
545 if(!(ps_global->smime && pc && pc->name))
546 return key;
548 if(ps_global->smime->privatetype == Container){
549 char *q;
551 if(pc->keytext && (q = strstr(pc->keytext, "-----END")) != NULL){
552 while(*q && *q != '\n')
553 q++;
555 if(*q == '\n')
556 q++;
558 if((in = BIO_new_mem_buf(pc->keytext, q-pc->keytext)) != NULL){
559 key = PEM_read_bio_PrivateKey(in, NULL, NULL, pass);
560 BIO_free(in);
564 else if(ps_global->smime->privatetype == Directory){
565 /* filename is path/name.key */
566 strncpy(buf, pc->name, sizeof(buf)-5);
567 buf[sizeof(buf)-5] = '\0';
568 strncat(buf, ".key", 5);
569 build_path(file, ps_global->smime->privatepath, buf, sizeof(file));
571 if(!(in = BIO_new_file(file, "r")))
572 return NULL;
574 key = PEM_read_bio_PrivateKey(in, NULL, NULL, pass);
575 BIO_free(in);
578 return key;
582 #include <openssl/x509v3.h>
584 * This newer version is from Adrian Vogel. It looks for the email
585 * address not only in the email address field, but also in an
586 * X509v3 extension field, Subject Altenative Name.
588 char **
589 get_x509_subject_email(X509 *x)
591 char **result = NULL;
592 int i, n;
593 STACK_OF(OPENSSL_STRING) *emails = X509_get1_email(x);
594 if ((n = sk_OPENSSL_STRING_num(emails)) > 0) {
595 result = fs_get((n+1)*sizeof(char *));
596 for(i = 0; i < n; i++)
597 result[i] = cpystr(sk_OPENSSL_STRING_value(emails, i));
598 result[i] = NULL;
600 X509_email_free(emails);
601 return result;
606 * Save the certificate for the given email address in
607 * ~/.alpine-smime/public.
609 * Should consider the security hazards in making a file with
610 * the email address that has come from the certificate.
612 * The argument email is destroyed.
614 * args: ctype says where the user wants to save the certificate
616 void
617 save_cert_for(char *email, X509 *cert, WhichCerts ctype)
619 if(!ps_global->smime || ctype == Private)
620 return;
622 dprint((9, "save_cert_for(%s, %s)", email ? email : "?", ctype == Public ? _("Public") : ctype == Private ? _("Private") : "CACert"));
623 emailstrclean(email);
625 if(ps_global->smime->publictype == Keychain){
626 #ifdef APPLEKEYCHAIN
628 OSStatus rc;
629 SecCertificateRef secCertificateRef;
630 CSSM_DATA certData;
632 memset((void *) &certData, 0, sizeof(certData));
633 memset((void *) &secCertificateRef, 0, sizeof(secCertificateRef));
635 /* convert OpenSSL X509 cert data to MacOS certData */
636 if((certData.Length = i2d_X509(cert, &(certData.Data))) > 0){
639 * Put that certData into a SecCertificateRef.
640 * Version 3 should work for versions 1-3.
642 if(!(rc=SecCertificateCreateFromData(&certData,
643 CSSM_CERT_X_509v3,
644 CSSM_CERT_ENCODING_DER,
645 &secCertificateRef))){
647 /* add it to the default keychain */
648 if(!(rc=SecCertificateAddToKeychain(secCertificateRef, NULL))){
649 /* ok */
651 else if(rc == errSecDuplicateItem){
652 dprint((9, "save_cert_for: certificate for %s already in keychain", email));
654 else{
655 dprint((9, "SecCertificateAddToKeychain failed"));
658 else{
659 dprint((9, "SecCertificateCreateFromData failed"));
662 else{
663 dprint((9, "i2d_X509 failed"));
666 #endif /* APPLEKEYCHAIN */
668 else if(SMHOLDERTYPE(ctype) == Container){
669 REMDATA_S *rd = NULL;
670 char *ret_dir = NULL;
671 char path[MAXPATH];
672 char fpath[MAXPATH];
673 char *upath = PATHCERTDIR(ctype);
674 char *tempfile = NULL;
675 int err = 0;
676 CertList *clist = DATACERT(ctype);
678 add_to_end_of_certlist(&clist, email, X509_dup(cert));
680 switch(ctype){
681 case Private: ps_global->smime->privatecertlist = clist; break;
682 case Public : ps_global->smime->publiccertlist = clist; break;
683 case CACert : ps_global->smime->cacertlist = clist; break;
684 default: break;
687 if(!upath)
688 return;
690 if(IS_REMOTE(upath)){
691 rd = rd_create_remote(RemImap, upath, REMOTE_SMIME_SUBTYPE,
692 NULL, "Error: ",
693 _("Can't access remote smime configuration."));
694 if(!rd){
695 return;
698 (void) rd_read_metadata(rd);
700 if(rd->access == MaybeRorW){
701 if(rd->read_status == 'R')
702 rd->access = ReadOnly;
703 else
704 rd->access = ReadWrite;
707 if(rd->access != NoExists){
709 rd_check_remvalid(rd, 1L);
712 * If the cached info says it is readonly but
713 * it looks like it's been fixed now, change it to readwrite.
715 if(rd->read_status == 'R'){
716 rd_check_readonly_access(rd);
717 if(rd->read_status == 'W'){
718 rd->access = ReadWrite;
719 rd->flags |= REM_OUTOFDATE;
721 else
722 rd->access = ReadOnly;
726 if(rd->flags & REM_OUTOFDATE){
727 if(rd_update_local(rd) != 0){
729 dprint((1, "save_cert_for: rd_update_local failed\n"));
730 rd_close_remdata(&rd);
731 return;
734 else
735 rd_open_remote(rd);
737 if(rd->access != ReadWrite || rd_remote_is_readonly(rd)){
738 rd_close_remdata(&rd);
739 return;
742 rd->flags |= DO_REMTRIM;
744 strncpy(path, rd->lf, sizeof(path)-1);
745 path[sizeof(path)-1] = '\0';
747 else{
748 strncpy(path, upath, sizeof(path)-1);
749 path[sizeof(path)-1] = '\0';
752 tempfile = tempfile_in_same_dir(path, "az", &ret_dir);
753 if(tempfile){
754 if(certlist_to_file(tempfile, DATACERT(ctype)))
755 err++;
757 if(!err && ret_dir){
758 if(strlen(path) + strlen(tempfile) - strlen(ret_dir) + 1 < sizeof(path))
759 snprintf(fpath, sizeof(fpath), "%s%c%s",
760 path, tempfile[strlen(ret_dir)], tempfile + strlen(ret_dir) + 1);
761 else
762 err++;
764 else err++;
766 fs_give((void **)&ret_dir);
768 if(!err){
769 if(rename_file(tempfile, fpath) < 0){
770 q_status_message2(SM_ORDER, 3, 3,
771 _("Can't rename %s to %s"), tempfile, fpath);
772 err++;
776 if(!err && IS_REMOTE(upath)){
777 int e, we_cancel;
778 char datebuf[200];
780 datebuf[0] = '\0';
782 we_cancel = busy_cue(_("Copying to remote smime container"), NULL, 1);
783 if((e = rd_update_remote(rd, datebuf)) != 0){
784 if(e == -1){
785 q_status_message2(SM_ORDER | SM_DING, 3, 5,
786 _("Error opening temporary smime file %s: %s"),
787 rd->lf, error_description(errno));
788 dprint((1,
789 "write_remote_smime: error opening temp file %s\n",
790 rd->lf ? rd->lf : "?"));
792 else{
793 q_status_message2(SM_ORDER | SM_DING, 3, 5,
794 _("Error copying to %s: %s"),
795 rd->rn, error_description(errno));
796 dprint((1,
797 "write_remote_smime: error copying from %s to %s\n",
798 rd->lf ? rd->lf : "?", rd->rn ? rd->rn : "?"));
801 q_status_message(SM_ORDER | SM_DING, 5, 5,
802 _("Copy of smime cert to remote folder failed, changes NOT saved remotely"));
804 else{
805 rd_update_metadata(rd, datebuf);
806 rd->read_status = 'W';
809 rd_close_remdata(&rd);
811 if(we_cancel)
812 cancel_busy_cue(-1);
815 fs_give((void **) &tempfile);
818 else if(SMHOLDERTYPE(ctype) == Directory){
819 char *path = PATHCERTDIR(ctype);
820 char certfilename[MAXPATH];
821 BIO *bio_out;
823 build_path(certfilename, path, email, sizeof(certfilename));
824 strncat(certfilename, ".crt", sizeof(certfilename)-1-strlen(certfilename));
825 certfilename[sizeof(certfilename)-1] = 0;
827 bio_out = BIO_new_file(certfilename, "w");
828 if(bio_out){
829 PEM_write_bio_X509(bio_out, cert);
830 BIO_free(bio_out);
831 q_status_message1(SM_ORDER, 1, 1, _("Saved certificate for <%s>"), email);
833 else{
834 q_status_message1(SM_ORDER, 1, 1, _("Couldn't save certificate for <%s>"), email);
841 * Try to retrieve the certificate for the given email address.
842 * The caller should free the cert.
844 X509 *
845 get_cert_for(char *email, WhichCerts ctype)
847 char certfilename[MAXPATH];
848 char emailaddr[MAXPATH];
849 X509 *cert = NULL;
850 BIO *in;
852 if(!ps_global->smime)
853 return cert;
855 dprint((9, "get_cert_for(%s, %s)", email ? email : "?", "none yet"));
857 if(ctype == Private) /* there is no private certificate info */
858 ctype = Public; /* return public information instead */
859 strncpy(emailaddr, email, sizeof(emailaddr)-1);
860 emailaddr[sizeof(emailaddr)-1] = 0;
862 /* clean it up (lowercase, space removal) */
863 emailstrclean(emailaddr);
865 if(ps_global->smime->publictype == Keychain){
866 #ifdef APPLEKEYCHAIN
868 OSStatus rc;
869 SecKeychainItemRef itemRef = nil;
870 SecKeychainAttributeList attrList;
871 SecKeychainAttribute attrib;
872 SecKeychainSearchRef searchRef = nil;
873 CSSM_DATA certData;
875 /* low-level form of MacOS data */
876 memset((void *) &certData, 0, sizeof(certData));
878 attrList.count = 1;
879 attrList.attr = &attrib;
881 /* kSecAlias means email address for a certificate */
882 attrib.tag = kSecAlias;
883 attrib.data = emailaddr;
884 attrib.length = strlen(attrib.data);
886 /* Find the certificate in the default keychain */
887 if(!(rc=SecKeychainSearchCreateFromAttributes(NULL,
888 kSecCertificateItemClass,
889 &attrList,
890 &searchRef))){
892 if(!(rc=SecKeychainSearchCopyNext(searchRef, &itemRef))){
894 /* extract the data portion of the certificate */
895 if(!(rc=SecCertificateGetData((SecCertificateRef) itemRef, &certData))){
898 * Convert it from MacOS form to OpenSSL form.
899 * The input is certData from above and the output
900 * is the X509 *cert.
902 if(!d2i_X509(&cert, &(certData.Data), certData.Length)){
903 dprint((9, "d2i_X509 failed"));
906 else{
907 dprint((9, "SecCertificateGetData failed"));
910 else if(rc == errSecItemNotFound){
911 dprint((9, "get_cert_for: Public cert for %s not found", emailaddr));
913 else{
914 dprint((9, "SecKeychainSearchCopyNext failed"));
917 else{
918 dprint((9, "SecKeychainSearchCreateFromAttributes failed"));
921 if(searchRef)
922 CFRelease(searchRef);
924 #endif /* APPLEKEYCHAIN */
926 else if(SMHOLDERTYPE(ctype) == Container){
927 CertList *cl;
929 for(cl = DATACERT(ctype); cl; cl = cl->next){
930 if(cl->name && !strucmp(emailaddr, cl->name))
931 break;
934 if(cl)
935 cert = X509_dup((X509 *) cl->x509_cert);
937 else if(SMHOLDERTYPE(ctype) == Directory){
938 build_path(certfilename, PATHCERTDIR(ctype), emailaddr, sizeof(certfilename));
939 strncat(certfilename, EXTCERT(ctype), sizeof(certfilename)-1-strlen(certfilename));
940 certfilename[sizeof(certfilename)-1] = 0;
942 if((in = BIO_new_file(certfilename, "r"))!=0){
944 cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
946 if(cert){
947 /* could check email addr in cert matches */
950 BIO_free(in);
954 return cert;
958 * load_cert_for_key finds a certificate in pathdir that matches a private key
959 * pkey. It returns its name in certfile, and the certificate in *pcert.
960 * return value: success: different from zero, failure 0. If both certfile
961 * and pcert are NULL, this function returns if there is certificate that
962 * matches the given key.
965 load_cert_for_key(char *pathdir, EVP_PKEY *pkey, char **certfile, X509 **pcert)
967 DIR *dirp;
968 struct dirent *d;
969 int rv = 0;
970 BIO *in;
971 X509 *x;
972 char buf[MAXPATH+1], pathcert[MAXPATH+1];
974 if(pathdir == NULL || pkey == NULL)
975 return 0;
977 if(certfile) *certfile = NULL;
978 if(pcert) *pcert = NULL;
980 if((dirp = opendir(pathdir)) != NULL){
981 while(rv == 0 && (d=readdir(dirp)) != NULL){
982 size_t ll;
984 if((ll=strlen(d->d_name)) && ll > 4){
985 if(!strcmp(d->d_name+ll-4, ".crt")){
986 strncpy(buf, d->d_name, sizeof(buf));
987 buf[sizeof(buf)-1] = '\0';
988 build_path(pathcert, pathdir, buf, sizeof(pathcert));
989 if((in = BIO_new_file(pathcert, "r")) != NULL){
990 if((x = PEM_read_bio_X509(in, NULL, NULL, NULL)) != NULL){
991 if(X509_check_private_key(x, pkey) > 0){
992 rv = 1;
993 if(certfile) *certfile = cpystr(buf);
994 if(pcert) *pcert = x;
996 else
997 X509_free(x);
999 BIO_free(in);
1004 closedir(dirp);
1006 return rv;
1010 PERSONAL_CERT *
1011 mem_to_personal_certs(char *contents)
1013 PERSONAL_CERT *result = NULL;
1014 char *p, *q, *line, *name, *keytext, *save_p;
1015 X509 *cert = NULL;
1017 if(contents && *contents){
1018 for(p = contents; *p != '\0';){
1019 line = p;
1021 while(*p && *p != '\n')
1022 p++;
1024 save_p = NULL;
1025 if(*p == '\n'){
1026 save_p = p;
1027 *p++ = '\0';
1030 if(strncmp(EMAILADDRLEADER, line, strlen(EMAILADDRLEADER)) == 0){
1031 name = line + strlen(EMAILADDRLEADER);
1032 cert = get_cert_for(name, Public);
1033 keytext = p;
1035 /* advance p past this record */
1036 if((q = strstr(keytext, "-----END")) != NULL){
1037 while(*q && *q != '\n')
1038 q++;
1040 if(*q == '\n')
1041 q++;
1043 p = q;
1045 else{
1046 p = p + strlen(p);
1047 q_status_message(SM_ORDER | SM_DING, 3, 3, _("Error in privatekey container, missing END"));
1050 if(cert){
1051 PERSONAL_CERT *pc;
1053 pc = (PERSONAL_CERT *) fs_get(sizeof(*pc));
1054 pc->cert = cert;
1055 pc->name = cpystr(name);
1056 pc->keytext = keytext; /* a pointer into contents */
1058 pc->key = load_key(pc, "", SM_NORMALCERT);
1060 pc->next = result;
1061 result = pc;
1065 if(save_p)
1066 *save_p = '\n';
1070 return result;
1074 CertList *
1075 mem_to_certlist(char *contents, WhichCerts ctype)
1077 CertList *ret = NULL;
1078 char *p, *q, *line, *name, *certtext, *save_p;
1079 X509 *cert = NULL;
1080 BIO *in;
1081 char *sep = (ctype == Public || ctype == Private)
1082 ? EMAILADDRLEADER : CACERTSTORELEADER;
1084 if(contents && *contents){
1085 for(p = contents; *p != '\0';){
1086 line = p;
1088 while(*p && *p != '\n')
1089 p++;
1091 save_p = NULL;
1092 if(*p == '\n'){
1093 save_p = p;
1094 *p++ = '\0';
1097 if(strncmp(sep, line, strlen(sep)) == 0){
1098 name = line + strlen(sep);
1099 cert = NULL;
1100 certtext = strstr(p, "-----BEGIN");
1101 if(certtext != NULL){
1102 if((q = strstr(certtext, sep)) != NULL)
1103 p = q;
1104 else
1105 p = q = certtext+strlen(certtext);
1107 if((in = BIO_new_mem_buf(certtext, q-certtext)) != 0){
1108 cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
1109 BIO_free(in);
1112 else{
1113 q_status_message2(SM_ORDER | SM_DING, 3, 3, _("Error in %scert container, missing BEGIN, certtext=%s"), ctype == Public ? _("public") : _("ca"), p);
1114 p = p + strlen(p);
1117 if(name && cert)
1118 add_to_end_of_certlist(&ret, name, cert);
1121 if(save_p)
1122 *save_p = '\n';
1126 return ret;
1131 * Add the CACert Container contents into the CACert store.
1133 * Returns > 0 for success, 0 for failure
1136 mem_add_extra_cacerts(char *contents, X509_LOOKUP *lookup)
1138 char *p, *q, *line, *certtext, *save_p;
1139 BIO *in, *out;
1140 int len, failed = 0;
1141 char *tempfile;
1142 char iobuf[4096];
1145 * The most straight-forward way to do this is to write
1146 * the container contents to a temp file and then load the
1147 * contents of the file with X509_LOOKUP_load_file(), like
1148 * is done in add_certs_in_dir(). What we don't know is if
1149 * each file should consist of one cacert or if they can all
1150 * just be jammed together into one file. To be safe, we'll use
1151 * one file per and do each in a separate operation.
1154 if(contents && *contents){
1155 for(p = contents; *p != '\0';){
1156 line = p;
1158 while(*p && *p != '\n')
1159 p++;
1161 save_p = NULL;
1162 if(*p == '\n'){
1163 save_p = p;
1164 *p++ = '\0';
1167 /* look for separator line */
1168 if(strncmp(CACERTSTORELEADER, line, strlen(CACERTSTORELEADER)) == 0){
1169 /* certtext is the content that should go in a file */
1170 certtext = strstr(p, "-----BEGIN");
1171 if(certtext != NULL){
1172 if((q = strstr(certtext, CACERTSTORELEADER)) != NULL){
1173 p = q;
1175 else{ /* end of file */
1176 q = certtext + strlen(certtext);
1177 p = q;
1180 in = BIO_new_mem_buf(certtext, q-certtext);
1181 if(in){
1182 tempfile = temp_nam(NULL, "az");
1183 out = NULL;
1184 if(tempfile)
1185 out = BIO_new_file(tempfile, "w");
1187 if(out){
1188 while((len = BIO_read(in, iobuf, sizeof(iobuf))) > 0)
1189 BIO_write(out, iobuf, len);
1191 BIO_free(out);
1192 if(!X509_LOOKUP_load_file(lookup, tempfile, X509_FILETYPE_PEM))
1193 failed++;
1195 fs_give((void **) &tempfile);
1198 BIO_free(in);
1201 else{
1202 p = p + strlen(p);
1203 q_status_message1(SM_ORDER | SM_DING, 3, 3, _("Error in cacert container, missing BEGIN, certtext=%s"), certtext);
1206 else{
1207 p = p + strlen(p);
1208 q_status_message1(SM_ORDER | SM_DING, 3, 3, _("Error in cacert container, missing separator, line=%s"), line);
1211 if(save_p)
1212 *save_p = '\n';
1216 return(!failed);
1221 certlist_to_file(char *filename, CertList *certlist)
1223 CertList *cl;
1224 BIO *bio_out = NULL;
1225 int ret = -1;
1227 if(filename && (bio_out=BIO_new_file(filename, "w")) != NULL){
1228 ret = 0;
1229 for(cl = certlist; cl; cl = cl->next){
1230 if(cl->name && cl->name[0] && cl->x509_cert){
1231 if(!((BIO_puts(bio_out, EMAILADDRLEADER) > 0)
1232 && (BIO_puts(bio_out, cl->name) > 0)
1233 && (BIO_puts(bio_out, "\n") > 0)))
1234 ret = -1;
1236 if(!PEM_write_bio_X509(bio_out, (X509 *) cl->x509_cert))
1237 ret = -1;
1241 BIO_free(bio_out);
1244 return ret;
1248 void
1249 add_to_end_of_certlist(CertList **cl, char *name, X509 *cert)
1251 CertList *new, *clp;
1252 char buf[MAILTMPLEN];
1254 if(!cl)
1255 return;
1257 new = (CertList *) fs_get(sizeof(*new));
1258 memset((void *) new, 0, sizeof(*new));
1259 new->x509_cert = cert;
1260 new->name = name ? cpystr(name) : NULL;
1261 if(cert && cert->cert_info){
1262 new->data.date_from = smime_get_date(cert->cert_info->validity->notBefore);
1263 new->data.date_to = smime_get_date(cert->cert_info->validity->notAfter);
1264 get_fingerprint(cert, EVP_md5(), buf, sizeof(buf), NULL);
1265 new->data.md5 = cpystr(buf);
1268 if(!*cl){
1269 *cl = new;
1271 else{
1272 for(clp = (*cl); clp->next; clp = clp->next)
1275 clp->next = new;
1280 void
1281 free_certlist(CertList **cl)
1283 if(cl && *cl){
1284 if((*cl)->data.date_from)
1285 fs_give((void **) &(*cl)->data.date_from);
1287 if((*cl)->data.date_to)
1288 fs_give((void **) &(*cl)->data.date_to);
1290 if((*cl)->data.md5)
1291 fs_give((void **) &(*cl)->data.md5);
1293 if((*cl)->name)
1294 fs_give((void **) &(*cl)->name);
1296 if((*cl)->x509_cert)
1297 X509_free((X509 *) (*cl)->x509_cert);
1299 free_certlist(&(*cl)->next);
1301 fs_give((void **) cl);
1306 void
1307 free_personal_certs(PERSONAL_CERT **pc)
1309 if(pc && *pc){
1310 free_personal_certs(&(*pc)->next);
1311 if((*pc)->name)
1312 fs_give((void **) &(*pc)->name);
1314 if((*pc)->name)
1315 fs_give((void **) &(*pc)->name);
1317 if((*pc)->cert)
1318 X509_free((*pc)->cert);
1320 if((*pc)->key)
1321 EVP_PKEY_free((*pc)->key);
1323 fs_give((void **) pc);
1327 #endif /* SMIME */