1 #if !defined(lint) && !defined(DOS)
2 static char rcsid
[] = "$Id: smkeys.c 1266 2009-07-14 18:39:12Z hubert@u.washington.edu $";
6 * ========================================================================
7 * Copyright 2013-2016 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"
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"
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
);
54 smime_X509_to_cert_info(X509
*x
, char *name
)
59 if(x
== NULL
) return NULL
;
61 cert
= fs_get(sizeof(CertList
));
62 memset((void *)cert
, 0, sizeof(CertList
));
64 cert
->name
= name
? cpystr(name
) : NULL
;
65 if(x
&& x
->cert_info
){
66 cert
->data
.date_from
= smime_get_date(x
->cert_info
->validity
->notBefore
);
67 cert
->data
.date_to
= smime_get_date(x
->cert_info
->validity
->notAfter
);
68 cert
->cn
= smime_get_cn(x
->cert_info
->subject
);
70 get_fingerprint(x
, EVP_md5(), buf
, sizeof(buf
), NULL
);
71 cert
->data
.md5
= cpystr(buf
);
76 #define SMIME_BACKUP_DIR ".backup"
77 #define MAX_TRY_BACKUP 100
79 /* return value: 0 - success, -1 error
80 * Call this function after setting up paths in ps_global->smime
81 * and reading certificates names in certlist.
84 setup_certs_backup_by_type(WhichCerts ctype
)
86 int rv
= 0; /* assume success */
90 char p
[MAXPATH
+1]; /* path to where the backup is */
91 char buf
[MAXPATH
+1], buf2
[MAXPATH
+1];
95 struct dirent
*df
; /* file in the directory */
100 return rv
; /* remove when this function is complete */
102 if(SMHOLDERTYPE(ctype
) == Directory
){
103 d
= PATHCERTDIR(ctype
);
105 len
= strlen(d
) + strlen(S_FILESEP
) + strlen(SMIME_BACKUP_DIR
) + 1;
106 snprintf(p
, MAXPATH
, "%s%s%s", d
, S_FILESEP
, SMIME_BACKUP_DIR
);
108 if(our_stat(p
, &sbuf
) < 0){
109 if(our_mkpath(p
, 0700) != 0)
111 } else if((sbuf
.st_mode
& S_IFMT
) != S_IFDIR
){
112 for(i
= 0, done
= 0; done
== 0 && i
< MAX_TRY_BACKUP
; i
++){
113 snprintf(buf2
, len
+2, "%s%d", p
, i
);
114 if(our_stat(buf2
, &sbuf
) < 0){
115 if(our_mkpath(buf2
, 0700) == 0)
118 else if((sbuf
.st_mode
& S_IFMT
) == S_IFDIR
)
121 strncpy(p
, buf2
, MAXPATH
);
128 /* if we are here, we have a backup directory where to
129 * backup certificates/keys, so now we will go
130 * through the list of certificates and back them up
133 data
= BACKUPDATACERT(ctype
);
134 for(cl
= DATACERT(ctype
); cl
; cl
= cl
->next
){
135 char clname
[MAXPATH
+1];
137 snprintf(clname
, MAXPATH
, "%s%s", cl
->name
, ctype
== Private
? ".key" : "");
138 clname
[MAXPATH
] = '\0';
139 len
= strlen(d
) + strlen(clname
) + 2;
141 snprintf(buf
, len
, "%s%s%s", d
, S_FILESEP
, clname
);
142 buf
[sizeof(buf
)-1] = '\0';
143 len
= strlen(p
) + strlen(clname
) + strlen(cl
->data
.md5
) + 3;
145 snprintf(buf2
, len
, "%s%s%s.%s", p
, S_FILESEP
, clname
, cl
->data
.md5
);
146 buf2
[sizeof(buf2
)-1] = '\0';
147 done
= 0; /* recycle done: it means we have a file that may be a certifificate*/
148 if(stat(buf2
, &sbuf
) < 0){
149 if (our_copy(buf2
, buf
) == 0)
151 } else if((sbuf
.st_mode
& S_IFMT
) == S_IFREG
)
158 if((in
= BIO_new_file(buf2
, "r"))!=0){
159 cert
= fs_get(sizeof(CertList
));
160 memset((void *)cert
, 0, sizeof(CertList
));
161 cert
->x509_cert
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
);
162 if(cl
->data
.date_from
!= NULL
)
163 cert
->data
.date_from
= cpystr(cl
->data
.date_from
);
164 if(cl
->data
.date_to
!= NULL
)
165 cert
->data
.date_to
= cpystr(cl
->data
.date_to
);
166 if(cl
->data
.md5
!= NULL
)
167 cert
->data
.md5
= cpystr(cl
->data
.md5
);
169 cert
->cn
= cpystr(cl
->cn
);
170 snprintf(buf2
, len
, "%s.%s", cl
->name
, cl
->data
.md5
);
171 buf2
[sizeof(buf2
)-1] = '\0';
172 cert
->name
= cpystr(buf2
);
176 for (cl2
= data
; cl2
&& cl2
->next
; cl2
= cl2
->next
);
184 default: alpine_panic("Bad ctype (0)");
190 /* if we are here, it means we just loaded the backup variable with
191 * a copy of the data that comes from the certlist not coming from
192 * backup. Now we are going to load the contents of the .backup
196 /* Here is the plan: read the backup directory (in the variable "p")
197 * and attempt to add it. If already there, skip it; otherwise continue
200 if((dirp
= opendir(p
)) != NULL
){
201 while((df
=readdir(dirp
)) != NULL
){
202 if(df
->d_name
&& *df
->d_name
== '.') /* no hidden files here */
205 /* make sure that we have a file */
206 snprintf(buf2
, sizeof(buf2
), "%s%s%s", p
, S_FILESEP
, df
->d_name
);
207 buf2
[sizeof(buf2
)-1] = '\0';
208 if(our_stat(buf2
, &sbuf
) == 0
209 && (sbuf
.st_mode
& S_IFMT
) != S_IFREG
)
212 /* make sure it is not already in the list */
213 for(cl
= data
; cl
; cl
= cl
->next
)
214 if(strcmp(cl
->name
, df
->d_name
) == 0)
219 /* ok, if it is not in the list, and it is a certificate. Add it */
223 if((in
= BIO_new_file(buf2
, "r"))!=0){
224 x
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
);
225 if(x
&& x
->cert_info
){ /* for now copy this information */
226 cert
= smime_X509_to_cert_info(x
, df
->d_name
);
227 /* we will use the cert->data.md5 variable to find a backup
228 certificate, not the name */
237 /* here we must check it is a key of some cert....*/
240 default: alpine_panic("Bad ctype (1)");
246 /* Now that we are here, we have all the information in the backup
251 case Public
: ps_global
->smime
->backuppubliccertlist
= data
; break;
252 case Private
: ps_global
->smime
->backupprivatecertlist
= data
; break;
253 case CACert
: ps_global
->smime
->backupcacertlist
= data
; break;
254 default : alpine_panic("Bad ctype (n)");
257 } else if(SMHOLDERTYPE(ctype
) == Container
){
259 } /* else APPLEKEYCHAIN */
264 smime_get_cn(X509_NAME
*subject
)
268 e
= X509_NAME_get_entry(subject
, X509_NAME_entry_count(subject
)-1);
270 X509_NAME_get_text_by_OBJ(subject
, e
->object
, buf
, sizeof(buf
));
275 compare_certs_by_name(const void *data1
, const void *data2
)
280 CertList
*cl1
= *(CertList
**) data1
;
281 CertList
*cl2
= *(CertList
**) data2
;
284 if((s
= strchr(cl1
->name
, '@')) != NULL
){
289 if((s
= strchr(cl2
->name
, '@')) != NULL
){
294 if((rv
= strucmp(cl1
->name
, cl2
->name
)) == 0)
295 rv
= strucmp(cl1
->name
+ i
+ 1, cl2
->name
+ j
+ 1);
296 if(i
>= 0) cl1
->name
[i
] = '@';
297 if(j
>= 0) cl2
->name
[j
] = '@';
302 resort_certificates(CertList
**data
, WhichCerts ctype
)
305 CertList
*cl
= *data
;
312 for(i
= 0; cl
; cl
= cl
->next
, i
++)
313 if(SMHOLDERTYPE(ctype
) == Directory
&& ctype
!= Private
){
314 for(t
= s
= cl
->name
; (t
= strstr(s
, ".crt")) != NULL
; s
= t
+1);
315 if (s
) *(s
-1) = '\0';
318 cll
= fs_get(i
*sizeof(CertList
*));
319 for(cl
= *data
, i
= 0; cl
; cl
= cl
->next
, i
++)
321 qsort((void *)cll
, j
, sizeof(CertList
*), compare_certs_by_name
);
322 for(i
= 0; i
< j
- 1; i
++){
323 cll
[i
]->next
= cll
[i
+1];
324 if(SMHOLDERTYPE(ctype
) == Directory
&& ctype
!= Private
)
325 cll
[i
]->name
[strlen(cll
[i
]->name
)]= '.'; /* restore ".crt" part */
327 if(SMHOLDERTYPE(ctype
) == Directory
&& ctype
!= Private
)
328 cll
[j
-1]->name
[strlen(cll
[j
-1]->name
)]= '.'; /* restore ".crt" part */
329 cll
[j
-1]->next
= NULL
;
335 get_fingerprint(X509
*cert
, const EVP_MD
*type
, char *buf
, size_t maxLen
, char *s
)
337 unsigned char md
[128];
343 X509_digest(cert
, type
, md
, &len
);
347 for(i
=0; i
<len
; i
++){
351 if(i
!= 0 && s
&& *s
)
354 snprintf(b
, maxLen
- (b
-buf
), "%02x", md
[i
]);
361 * Remove leading whitespace, trailing whitespace and convert
362 * to lowercase. Also remove slash characters
364 * Args: s, -- The string to clean
366 * Result: the cleaned string
369 emailstrclean(char *string
)
371 char *s
= string
, *sc
= NULL
, *p
= NULL
;
373 for(; *s
; s
++){ /* single pass */
374 if(!isspace((unsigned char) (*s
))){
375 p
= NULL
; /* not start of blanks */
376 if(!sc
) /* first non-blank? */
377 sc
= string
; /* start copying */
379 else if(!p
) /* it's OK if sc == NULL */
380 p
= sc
; /* start of blanks? */
382 if(sc
&& *s
!='/' && *s
!='\\') /* if copying, copy */
383 *sc
++ = isupper((unsigned char) (*s
))
384 ? (unsigned char) tolower((unsigned char) (*s
))
385 : (unsigned char) (*s
);
388 if(p
) /* if ending blanks */
389 *p
= '\0'; /* tie off beginning */
390 else if(!sc
) /* never saw a non-blank */
391 *string
= '\0'; /* so tie whole thing off */
398 smime_get_date(ASN1_GENERALIZEDTIME
*tm
)
400 BIO
*mb
= BIO_new(BIO_s_mem());
402 char date
[MAILTMPLEN
];
403 char buf
[MAILTMPLEN
];
404 char *m
, *d
, *t
, *y
, *z
;
408 (void) BIO_reset(mb
);
409 if(ASN1_TIME_print(mb
, tm
) == 0)
410 return cpystr(_("Invalid"));
412 (void) BIO_flush(mb
);
413 BIO_read(mb
, iobuf
, sizeof(iobuf
));
415 /* openssl returns the date in the format:
416 * "MONTH (as name) DAY (as number) TIME(hh:mm:ss) YEAR GMT"
419 d
= strchr(iobuf
, ' ');
421 while(*d
== ' ') d
++;
422 t
= strchr(d
+1, ' ');
424 while(*t
== ' ') t
++;
425 y
= strchr(t
+1, ' ');
427 while(*y
== ' ') y
++;
428 z
= strchr(y
+1, ' ');
430 while(*z
== ' ') z
++;
432 snprintf(date
, sizeof(date
), "%s %s %s %s (%s)", d
, m
, y
, t
, z
);
433 date
[sizeof(date
)-1] = '\0';
434 if(F_ON(F_DATES_TO_LOCAL
,ps_global
)){
435 parse_date(convert_date_to_local(date
), &smd
);
436 memset(&smtm
, 0, sizeof(smtm
));
437 smtm
.tm_year
= smd
.year
- 1900;
438 smtm
.tm_mon
= MIN(MAX(smd
.month
-1, 0), 11);
439 smtm
.tm_mday
= MIN(MAX(smd
.day
, 1), 31);
440 our_strftime(buf
, sizeof(buf
), "%x", &smtm
);
443 snprintf(buf
, sizeof(buf
), "%s/%s/%s", m
, d
, y
+ strlen(y
) - 2);
444 buf
[sizeof(buf
)-1] = '\0';
450 * Add a lookup for each "*.crt*" file in the given directory.
453 add_certs_in_dir(X509_LOOKUP
*lookup
, char *path
, char *ext
, CertList
**cdata
)
461 if((dirp
= opendir(path
)) != NULL
){
462 while(!ret
&& (d
=readdir(dirp
)) != NULL
){
463 if(srchrstr(d
->d_name
, ext
)){
464 build_path(buf
, path
, d
->d_name
, sizeof(buf
));
466 if(!X509_LOOKUP_load_file(lookup
, buf
, X509_FILETYPE_PEM
)){
467 q_status_message1(SM_ORDER
, 3, 3, _("Error loading file %s"), buf
);
474 cert
= fs_get(sizeof(CertList
));
475 memset((void *)cert
, 0, sizeof(CertList
));
476 cert
->name
= cpystr(d
->d_name
);
477 /* read buf into a bio and fill the CertData structure */
478 if((in
= BIO_new_file(buf
, "r"))!=0){
479 x
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
);
480 if(x
&& x
->cert_info
){
481 cert
->data
.date_from
= smime_get_date(x
->cert_info
->validity
->notBefore
);
482 cert
->data
.date_to
= smime_get_date(x
->cert_info
->validity
->notAfter
);
483 get_fingerprint(x
, EVP_md5(), buf
, sizeof(buf
), NULL
);
484 cert
->data
.md5
= cpystr(buf
);
485 cert
->cn
= smime_get_cn(x
->cert_info
->subject
);
493 for (cl
= *cdata
; cl
&& cl
->next
; cl
= cl
->next
);
511 * Get an X509_STORE. This consists of the system
512 * certs directory and any certificates in the user's
513 * ~/.alpine-smime/ca directory.
519 X509_STORE
*store
= NULL
;
521 dprint((9, "get_ca_store()"));
523 if(!(store
=X509_STORE_new())){
524 dprint((9, "X509_STORE_new() failed"));
528 if(!(lookup
=X509_STORE_add_lookup(store
, X509_LOOKUP_file()))){
529 dprint((9, "X509_STORE_add_lookup() failed"));
530 X509_STORE_free(store
);
534 if(ps_global
->smime
&& ps_global
->smime
->catype
== Container
535 && ps_global
->smime
->cacontent
){
537 if(!mem_add_extra_cacerts(ps_global
->smime
->cacontent
, lookup
)){
538 X509_STORE_free(store
);
542 else if(ps_global
->smime
&& ps_global
->smime
->catype
== Directory
543 && ps_global
->smime
->capath
){
544 if(add_certs_in_dir(lookup
, ps_global
->smime
->capath
, ".crt", &ps_global
->smime
->cacertlist
) < 0){
545 X509_STORE_free(store
);
548 resort_certificates(&ps_global
->smime
->cacertlist
, CACert
);
551 if(!(lookup
=X509_STORE_add_lookup(store
, X509_LOOKUP_hash_dir()))){
552 X509_STORE_free(store
);
556 #ifdef SMIME_SSLCERTS
557 dprint((9, "get_ca_store(): adding cacerts from %s", SMIME_SSLCERTS
));
558 X509_LOOKUP_add_dir(lookup
, SMIME_SSLCERTS
, X509_FILETYPE_PEM
);
566 load_key(PERSONAL_CERT
*pc
, char *pass
, int flag
)
569 EVP_PKEY
*key
= NULL
;
570 char buf
[MAXPATH
], file
[MAXPATH
];
572 if(!(ps_global
->smime
&& pc
&& pc
->name
))
575 if(ps_global
->smime
->privatetype
== Container
){
578 if(pc
->keytext
&& (q
= strstr(pc
->keytext
, "-----END")) != NULL
){
579 while(*q
&& *q
!= '\n')
585 if((in
= BIO_new_mem_buf(pc
->keytext
, q
-pc
->keytext
)) != NULL
){
586 key
= PEM_read_bio_PrivateKey(in
, NULL
, NULL
, pass
);
591 else if(ps_global
->smime
->privatetype
== Directory
){
592 /* filename is path/name.key */
593 strncpy(buf
, pc
->name
, sizeof(buf
)-5);
594 buf
[sizeof(buf
)-5] = '\0';
595 strncat(buf
, ".key", 5);
596 build_path(file
, ps_global
->smime
->privatepath
, buf
, sizeof(file
));
598 if(!(in
= BIO_new_file(file
, "r")))
601 key
= PEM_read_bio_PrivateKey(in
, NULL
, NULL
, pass
);
609 #include <openssl/x509v3.h>
611 * This newer version is from Adrian Vogel. It looks for the email
612 * address not only in the email address field, but also in an
613 * X509v3 extension field, Subject Altenative Name.
616 get_x509_subject_email(X509
*x
)
618 char **result
= NULL
;
620 STACK_OF(OPENSSL_STRING
) *emails
= X509_get1_email(x
);
621 if ((n
= sk_OPENSSL_STRING_num(emails
)) > 0) {
622 result
= fs_get((n
+1)*sizeof(char *));
623 for(i
= 0; i
< n
; i
++)
624 result
[i
] = cpystr(sk_OPENSSL_STRING_value(emails
, i
));
627 X509_email_free(emails
);
633 * Save the certificate for the given email address in
634 * ~/.alpine-smime/public.
636 * Should consider the security hazards in making a file with
637 * the email address that has come from the certificate.
639 * The argument email is destroyed.
641 * args: ctype says where the user wants to save the certificate
644 save_cert_for(char *email
, X509
*cert
, WhichCerts ctype
)
646 if(!ps_global
->smime
|| ctype
== Private
)
649 dprint((9, "save_cert_for(%s, %s)", email
? email
: "?", ctype
== Public
? _("Public") : ctype
== Private
? _("Private") : "CACert"));
650 emailstrclean(email
);
652 if(ps_global
->smime
->publictype
== Keychain
){
656 SecCertificateRef secCertificateRef
;
659 memset((void *) &certData
, 0, sizeof(certData
));
660 memset((void *) &secCertificateRef
, 0, sizeof(secCertificateRef
));
662 /* convert OpenSSL X509 cert data to MacOS certData */
663 if((certData
.Length
= i2d_X509(cert
, &(certData
.Data
))) > 0){
666 * Put that certData into a SecCertificateRef.
667 * Version 3 should work for versions 1-3.
669 if(!(rc
=SecCertificateCreateFromData(&certData
,
671 CSSM_CERT_ENCODING_DER
,
672 &secCertificateRef
))){
674 /* add it to the default keychain */
675 if(!(rc
=SecCertificateAddToKeychain(secCertificateRef
, NULL
))){
678 else if(rc
== errSecDuplicateItem
){
679 dprint((9, "save_cert_for: certificate for %s already in keychain", email
));
682 dprint((9, "SecCertificateAddToKeychain failed"));
686 dprint((9, "SecCertificateCreateFromData failed"));
690 dprint((9, "i2d_X509 failed"));
693 #endif /* APPLEKEYCHAIN */
695 else if(SMHOLDERTYPE(ctype
) == Container
){
696 REMDATA_S
*rd
= NULL
;
697 char *ret_dir
= NULL
;
700 char *upath
= PATHCERTDIR(ctype
);
701 char *tempfile
= NULL
;
703 CertList
*clist
= DATACERT(ctype
);
705 add_to_end_of_certlist(&clist
, email
, X509_dup(cert
));
708 case Private
: ps_global
->smime
->privatecertlist
= clist
; break;
709 case Public
: ps_global
->smime
->publiccertlist
= clist
; break;
710 case CACert
: ps_global
->smime
->cacertlist
= clist
; break;
717 if(IS_REMOTE(upath
)){
718 rd
= rd_create_remote(RemImap
, upath
, REMOTE_SMIME_SUBTYPE
,
720 _("Can't access remote smime configuration."));
725 (void) rd_read_metadata(rd
);
727 if(rd
->access
== MaybeRorW
){
728 if(rd
->read_status
== 'R')
729 rd
->access
= ReadOnly
;
731 rd
->access
= ReadWrite
;
734 if(rd
->access
!= NoExists
){
736 rd_check_remvalid(rd
, 1L);
739 * If the cached info says it is readonly but
740 * it looks like it's been fixed now, change it to readwrite.
742 if(rd
->read_status
== 'R'){
743 rd_check_readonly_access(rd
);
744 if(rd
->read_status
== 'W'){
745 rd
->access
= ReadWrite
;
746 rd
->flags
|= REM_OUTOFDATE
;
749 rd
->access
= ReadOnly
;
753 if(rd
->flags
& REM_OUTOFDATE
){
754 if(rd_update_local(rd
) != 0){
756 dprint((1, "save_cert_for: rd_update_local failed\n"));
757 rd_close_remdata(&rd
);
764 if(rd
->access
!= ReadWrite
|| rd_remote_is_readonly(rd
)){
765 rd_close_remdata(&rd
);
769 rd
->flags
|= DO_REMTRIM
;
771 strncpy(path
, rd
->lf
, sizeof(path
)-1);
772 path
[sizeof(path
)-1] = '\0';
775 strncpy(path
, upath
, sizeof(path
)-1);
776 path
[sizeof(path
)-1] = '\0';
779 tempfile
= tempfile_in_same_dir(path
, "az", &ret_dir
);
781 if(certlist_to_file(tempfile
, DATACERT(ctype
)))
785 if(IS_REMOTE(upath
)){
786 strncpy(fpath
, rd
->lf
, sizeof(fpath
));
787 fpath
[sizeof(fpath
)-1] = '\0';
790 if(strlen(path
) + strlen(tempfile
) - strlen(ret_dir
) + 1 < sizeof(path
))
791 snprintf(fpath
, sizeof(fpath
), "%s%c%s",
792 path
, tempfile
[strlen(ret_dir
)], tempfile
+ strlen(ret_dir
) + 1);
799 fs_give((void **)&ret_dir
);
802 if(rename_file(tempfile
, fpath
) < 0){
803 q_status_message2(SM_ORDER
, 3, 3,
804 _("Can't rename %s to %s"), tempfile
, fpath
);
809 if(!err
&& IS_REMOTE(upath
)){
815 we_cancel
= busy_cue(_("Copying to remote smime container"), NULL
, 1);
816 if((e
= rd_update_remote(rd
, datebuf
)) != 0){
818 q_status_message2(SM_ORDER
| SM_DING
, 3, 5,
819 _("Error opening temporary smime file %s: %s"),
820 rd
->lf
, error_description(errno
));
822 "write_remote_smime: error opening temp file %s\n",
823 rd
->lf
? rd
->lf
: "?"));
826 q_status_message2(SM_ORDER
| SM_DING
, 3, 5,
827 _("Error copying to %s: %s"),
828 rd
->rn
, error_description(errno
));
830 "write_remote_smime: error copying from %s to %s\n",
831 rd
->lf
? rd
->lf
: "?", rd
->rn
? rd
->rn
: "?"));
834 q_status_message(SM_ORDER
| SM_DING
, 5, 5,
835 _("Copy of smime cert to remote folder failed, changes NOT saved remotely"));
838 rd_update_metadata(rd
, datebuf
);
839 rd
->read_status
= 'W';
842 rd_close_remdata(&rd
);
848 fs_give((void **) &tempfile
);
851 else if(SMHOLDERTYPE(ctype
) == Directory
){
852 char *path
= PATHCERTDIR(ctype
);
853 char certfilename
[MAXPATH
];
856 build_path(certfilename
, path
, email
, sizeof(certfilename
));
857 strncat(certfilename
, ".crt", sizeof(certfilename
)-1-strlen(certfilename
));
858 certfilename
[sizeof(certfilename
)-1] = 0;
860 bio_out
= BIO_new_file(certfilename
, "w");
862 PEM_write_bio_X509(bio_out
, cert
);
864 q_status_message1(SM_ORDER
, 1, 1, _("Saved certificate for <%s>"), email
);
867 q_status_message1(SM_ORDER
, 1, 1, _("Couldn't save certificate for <%s>"), email
);
874 * Try to retrieve the certificate for the given email address.
875 * The caller should free the cert.
878 get_cert_for(char *email
, WhichCerts ctype
, int tolower
)
880 char certfilename
[MAXPATH
];
881 char emailaddr
[MAXPATH
];
885 if(ctype
== Password
){
886 build_path(certfilename
, PATHCERTDIR(ctype
), email
, sizeof(certfilename
));
887 strncat(certfilename
, EXTCERT(Public
), sizeof(certfilename
)-1-strlen(certfilename
));
888 certfilename
[sizeof(certfilename
)-1] = 0;
890 if((in
= BIO_new_file(certfilename
, "r"))!=0){
892 cert
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
);
895 /* could check email addr in cert matches */
904 if(!ps_global
->smime
)
907 dprint((9, "get_cert_for(%s, %s)", email
? email
: "?", "none yet"));
909 if(ctype
== Private
) /* there is no private certificate info */
910 ctype
= Public
; /* return public information instead */
911 strncpy(emailaddr
, email
, sizeof(emailaddr
)-1);
912 emailaddr
[sizeof(emailaddr
)-1] = 0;
914 /* clean it up (lowercase, space removal) */
916 emailstrclean(emailaddr
);
918 if(ps_global
->smime
->publictype
== Keychain
){
922 SecKeychainItemRef itemRef
= nil
;
923 SecKeychainAttributeList attrList
;
924 SecKeychainAttribute attrib
;
925 SecKeychainSearchRef searchRef
= nil
;
928 /* low-level form of MacOS data */
929 memset((void *) &certData
, 0, sizeof(certData
));
932 attrList
.attr
= &attrib
;
934 /* kSecAlias means email address for a certificate */
935 attrib
.tag
= kSecAlias
;
936 attrib
.data
= emailaddr
;
937 attrib
.length
= strlen(attrib
.data
);
939 /* Find the certificate in the default keychain */
940 if(!(rc
=SecKeychainSearchCreateFromAttributes(NULL
,
941 kSecCertificateItemClass
,
945 if(!(rc
=SecKeychainSearchCopyNext(searchRef
, &itemRef
))){
947 /* extract the data portion of the certificate */
948 if(!(rc
=SecCertificateGetData((SecCertificateRef
) itemRef
, &certData
))){
951 * Convert it from MacOS form to OpenSSL form.
952 * The input is certData from above and the output
955 if(!d2i_X509(&cert
, &(certData
.Data
), certData
.Length
)){
956 dprint((9, "d2i_X509 failed"));
960 dprint((9, "SecCertificateGetData failed"));
963 else if(rc
== errSecItemNotFound
){
964 dprint((9, "get_cert_for: Public cert for %s not found", emailaddr
));
967 dprint((9, "SecKeychainSearchCopyNext failed"));
971 dprint((9, "SecKeychainSearchCreateFromAttributes failed"));
975 CFRelease(searchRef
);
977 #endif /* APPLEKEYCHAIN */
979 else if(SMHOLDERTYPE(ctype
) == Container
){
982 for(cl
= DATACERT(ctype
); cl
; cl
= cl
->next
){
983 if(cl
->name
&& !strucmp(emailaddr
, cl
->name
))
988 cert
= X509_dup((X509
*) cl
->x509_cert
);
990 else if(SMHOLDERTYPE(ctype
) == Directory
){
991 build_path(certfilename
, PATHCERTDIR(ctype
), emailaddr
, sizeof(certfilename
));
992 strncat(certfilename
, EXTCERT(ctype
), sizeof(certfilename
)-1-strlen(certfilename
));
993 certfilename
[sizeof(certfilename
)-1] = 0;
995 if((in
= BIO_new_file(certfilename
, "r"))!=0){
997 cert
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
);
1000 /* could check email addr in cert matches */
1011 * load_cert_for_key finds a certificate in pathdir that matches a private key
1012 * pkey. It returns its name in certfile, and the certificate in *pcert.
1013 * return value: success: different from zero, failure 0. If both certfile
1014 * and pcert are NULL, this function returns if there is certificate that
1015 * matches the given key.
1018 load_cert_for_key(char *pathdir
, EVP_PKEY
*pkey
, char **certfile
, X509
**pcert
)
1025 char buf
[MAXPATH
+1], pathcert
[MAXPATH
+1];
1027 if(pathdir
== NULL
|| pkey
== NULL
)
1030 if(certfile
) *certfile
= NULL
;
1031 if(pcert
) *pcert
= NULL
;
1033 if((dirp
= opendir(pathdir
)) != NULL
){
1034 while(rv
== 0 && (d
=readdir(dirp
)) != NULL
){
1037 if((ll
=strlen(d
->d_name
)) && ll
> 4){
1038 if(!strcmp(d
->d_name
+ll
-4, ".crt")){
1039 strncpy(buf
, d
->d_name
, sizeof(buf
));
1040 buf
[sizeof(buf
)-1] = '\0';
1041 build_path(pathcert
, pathdir
, buf
, sizeof(pathcert
));
1042 if((in
= BIO_new_file(pathcert
, "r")) != NULL
){
1043 if((x
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
)) != NULL
){
1044 if(X509_check_private_key(x
, pkey
) > 0){
1046 if(certfile
) *certfile
= cpystr(buf
);
1047 if(pcert
) *pcert
= x
;
1064 mem_to_personal_certs(char *contents
)
1066 PERSONAL_CERT
*result
= NULL
;
1067 char *p
, *q
, *line
, *name
, *keytext
, *save_p
;
1070 if(contents
&& *contents
){
1071 for(p
= contents
; *p
!= '\0';){
1074 while(*p
&& *p
!= '\n')
1083 if(strncmp(EMAILADDRLEADER
, line
, strlen(EMAILADDRLEADER
)) == 0){
1084 name
= line
+ strlen(EMAILADDRLEADER
);
1085 cert
= get_cert_for(name
, Public
, 1);
1088 /* advance p past this record */
1089 if((q
= strstr(keytext
, "-----END")) != NULL
){
1090 while(*q
&& *q
!= '\n')
1100 q_status_message(SM_ORDER
| SM_DING
, 3, 3, _("Error in privatekey container, missing END"));
1106 pc
= (PERSONAL_CERT
*) fs_get(sizeof(*pc
));
1108 pc
->name
= cpystr(name
);
1110 pc
->keytext
= keytext
; /* a pointer into contents */
1112 pc
->key
= load_key(pc
, "", SM_NORMALCERT
);
1129 mem_to_certlist(char *contents
, WhichCerts ctype
)
1131 CertList
*ret
= NULL
;
1132 char *p
, *q
, *line
, *name
, *certtext
, *save_p
;
1135 char *sep
= (ctype
== Public
|| ctype
== Private
)
1136 ? EMAILADDRLEADER
: CACERTSTORELEADER
;
1138 if(contents
&& *contents
){
1139 for(p
= contents
; *p
!= '\0';){
1142 while(*p
&& *p
!= '\n')
1151 if(strncmp(sep
, line
, strlen(sep
)) == 0){
1152 name
= line
+ strlen(sep
);
1154 certtext
= strstr(p
, "-----BEGIN");
1155 if(certtext
!= NULL
){
1156 if((q
= strstr(certtext
, sep
)) != NULL
)
1159 p
= q
= certtext
+strlen(certtext
);
1161 if((in
= BIO_new_mem_buf(certtext
, q
-certtext
)) != 0){
1162 cert
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
);
1167 q_status_message2(SM_ORDER
| SM_DING
, 3, 3, _("Error in %scert container, missing BEGIN, certtext=%s"), ctype
== Public
? _("public") : _("ca"), p
);
1172 add_to_end_of_certlist(&ret
, name
, cert
);
1180 resort_certificates(&ret
, ctype
);
1187 * Add the CACert Container contents into the CACert store.
1189 * Returns > 0 for success, 0 for failure
1192 mem_add_extra_cacerts(char *contents
, X509_LOOKUP
*lookup
)
1194 char *p
, *q
, *line
, *certtext
, *save_p
;
1196 int len
, failed
= 0;
1201 * The most straight-forward way to do this is to write
1202 * the container contents to a temp file and then load the
1203 * contents of the file with X509_LOOKUP_load_file(), like
1204 * is done in add_certs_in_dir(). What we don't know is if
1205 * each file should consist of one cacert or if they can all
1206 * just be jammed together into one file. To be safe, we'll use
1207 * one file per and do each in a separate operation.
1210 if(contents
&& *contents
){
1211 for(p
= contents
; *p
!= '\0';){
1214 while(*p
&& *p
!= '\n')
1223 /* look for separator line */
1224 if(strncmp(CACERTSTORELEADER
, line
, strlen(CACERTSTORELEADER
)) == 0){
1225 /* certtext is the content that should go in a file */
1226 certtext
= strstr(p
, "-----BEGIN");
1227 if(certtext
!= NULL
){
1228 if((q
= strstr(certtext
, CACERTSTORELEADER
)) != NULL
){
1231 else{ /* end of file */
1232 q
= certtext
+ strlen(certtext
);
1236 in
= BIO_new_mem_buf(certtext
, q
-certtext
);
1238 tempfile
= temp_nam(NULL
, "az");
1239 out
= tempfile
!= NULL
? BIO_new_file(tempfile
, "w") : NULL
;
1241 while((len
= BIO_read(in
, iobuf
, sizeof(iobuf
))) > 0)
1242 BIO_write(out
, iobuf
, len
);
1245 if(!X509_LOOKUP_load_file(lookup
, tempfile
, X509_FILETYPE_PEM
))
1249 if(tempfile
!= NULL
){
1251 fs_give((void **) &tempfile
);
1259 q_status_message1(SM_ORDER
| SM_DING
, 3, 3, _("Error in cacert container, missing BEGIN, certtext=%s"), certtext
);
1264 q_status_message1(SM_ORDER
| SM_DING
, 3, 3, _("Error in cacert container, missing separator, line=%s"), line
);
1277 certlist_to_file(char *filename
, CertList
*certlist
)
1280 BIO
*bio_out
= NULL
;
1283 if(filename
&& (bio_out
=BIO_new_file(filename
, "w")) != NULL
){
1285 for(cl
= certlist
; cl
; cl
= cl
->next
){
1286 if(cl
->name
&& cl
->name
[0] && cl
->x509_cert
){
1287 if(!((BIO_puts(bio_out
, EMAILADDRLEADER
) > 0)
1288 && (BIO_puts(bio_out
, cl
->name
) > 0)
1289 && (BIO_puts(bio_out
, "\n") > 0)))
1292 if(!PEM_write_bio_X509(bio_out
, (X509
*) cl
->x509_cert
))
1305 add_to_end_of_certlist(CertList
**cl
, char *name
, X509
*cert
)
1312 new = smime_X509_to_cert_info(cert
, name
);
1319 free_certlist(CertList
**cl
)
1322 if((*cl
)->data
.date_from
)
1323 fs_give((void **) &(*cl
)->data
.date_from
);
1325 if((*cl
)->data
.date_to
)
1326 fs_give((void **) &(*cl
)->data
.date_to
);
1329 fs_give((void **) &(*cl
)->data
.md5
);
1332 fs_give((void **) &(*cl
)->name
);
1335 fs_give((void **) &(*cl
)->cn
);
1337 if((*cl
)->x509_cert
)
1338 X509_free((X509
*) (*cl
)->x509_cert
);
1340 free_certlist(&(*cl
)->next
);
1342 fs_give((void **) cl
);
1348 free_personal_certs(PERSONAL_CERT
**pc
)
1352 fs_give((void **) &(*pc
)->name
);
1355 fs_give((void **) &(*pc
)->cname
);
1358 X509_free((*pc
)->cert
);
1361 EVP_PKEY_free((*pc
)->key
);
1363 free_personal_certs(&(*pc
)->next
);
1365 fs_give((void **) pc
);