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-2014 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
);
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.
60 setup_certs_backup_by_type(WhichCerts ctype
)
62 int rv
= 0; /* assume success */
66 char p
[MAXPATH
+1]; /* path to where the backup is */
67 char buf
[MAXPATH
+1], buf2
[MAXPATH
+1];
71 struct dirent
*df
; /* file in the directory */
76 return rv
; /* remove when this function is complete */
78 if(SMHOLDERTYPE(ctype
) == Directory
){
79 d
= PATHCERTDIR(ctype
);
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
);
84 if(our_stat(p
, &sbuf
) < 0){
85 if(our_mkpath(p
, 0700) != 0)
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)
94 else if((sbuf
.st_mode
& S_IFMT
) == S_IFDIR
)
97 strncpy(p
, buf2
, MAXPATH
);
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
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;
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;
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)
127 } else if((sbuf
.st_mode
& S_IFMT
) == S_IFREG
)
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
);
150 for (cl2
= data
; cl2
&& cl2
->next
; cl2
= cl2
->next
);
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
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 */
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
)
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)
193 /* ok, if it is not in the list, and it is a certificate. Add it */
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
));
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 */
213 for (cl2
= data
; cl2
&& cl2
->next
; cl2
= cl2
->next
);
222 /* here we must check it is a key of some cert....*/
225 default: alpine_panic("Bad ctype (1)");
231 /* Now that we are here, we have all the information in the backup
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 */
249 compare_certs_by_name(const void *data1
, const void *data2
)
254 CertList
*cl1
= *(CertList
**) data1
;
255 CertList
*cl2
= *(CertList
**) data2
;
258 if((s
= strchr(cl1
->name
, '@')) != NULL
){
263 if((s
= strchr(cl2
->name
, '@')) != NULL
){
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
] = '@';
276 resort_certificates(CertList
**data
, WhichCerts ctype
)
279 CertList
*cl
= *data
;
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"); s
= t
+1);
289 if (s
) *(s
-1) = '\0';
292 cll
= fs_get(i
*sizeof(CertList
*));
293 for(cl
= *data
, i
= 0; cl
; cl
= cl
->next
, i
++)
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];
299 cll
[i
]->name
[strlen(cll
[i
]->name
)]= '.'; /* restore ".crt" part */
302 cll
[j
-1]->name
[strlen(cll
[j
-1]->name
)]= '.'; /* restore ".crt" part */
303 cll
[j
-1]->next
= NULL
;
309 get_fingerprint(X509
*cert
, const EVP_MD
*type
, char *buf
, size_t maxLen
, char *s
)
311 unsigned char md
[128];
317 X509_digest(cert
, type
, md
, &len
);
321 for(i
=0; i
<len
; i
++){
325 if(i
!= 0 && s
&& *s
)
328 snprintf(b
, maxLen
- (b
-buf
), "%02x", md
[i
]);
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
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 */
372 smime_get_date(ASN1_GENERALIZEDTIME
*tm
)
374 BIO
*mb
= BIO_new(BIO_s_mem());
376 char date
[MAILTMPLEN
];
377 char buf
[MAILTMPLEN
];
378 char *m
, *d
, *t
, *y
, *z
;
382 (void) BIO_reset(mb
);
383 ASN1_UTCTIME_print(mb
, tm
);
384 (void) BIO_flush(mb
);
385 BIO_read(mb
, iobuf
, sizeof(iobuf
));
387 /* openssl returns the date in the format:
388 * "MONTH (as name) DAY (as number) TIME(hh:mm:ss) YEAR GMT"
391 d
= strchr(iobuf
, ' ');
393 while(*d
== ' ') d
++;
394 t
= strchr(d
+1, ' ');
396 while(*t
== ' ') t
++;
397 y
= strchr(t
+1, ' ');
399 while(*y
== ' ') y
++;
400 z
= strchr(y
+1, ' ');
402 while(*z
== ' ') z
++;
404 snprintf(date
, sizeof(date
), "%s %s %s %s (%s)", d
, m
, y
, t
, z
);
405 date
[sizeof(date
)-1] = '\0';
406 if(F_ON(F_DATES_TO_LOCAL
,ps_global
)){
407 parse_date(convert_date_to_local(date
), &smd
);
408 memset(&smtm
, 0, sizeof(smtm
));
409 smtm
.tm_year
= MIN(MAX(smd
.year
-1900, 0), 2000) % 100 - 1900;
410 smtm
.tm_mon
= MIN(MAX(smd
.month
-1, 0), 11);
411 smtm
.tm_mday
= MIN(MAX(smd
.day
, 1), 31);
412 our_strftime(buf
, sizeof(buf
), "%x", &smtm
);
415 snprintf(buf
, sizeof(buf
), "%s/%s/%s", m
, d
, y
+ strlen(y
) - 2);
416 buf
[sizeof(buf
)-1] = '\0';
422 * Add a lookup for each "*.crt*" file in the given directory.
425 add_certs_in_dir(X509_LOOKUP
*lookup
, char *path
, char *ext
, CertList
**cdata
)
433 if((dirp
= opendir(path
)) != NULL
){
434 while(!ret
&& (d
=readdir(dirp
)) != NULL
){
435 if(srchrstr(d
->d_name
, ext
)){
436 build_path(buf
, path
, d
->d_name
, sizeof(buf
));
438 if(!X509_LOOKUP_load_file(lookup
, buf
, X509_FILETYPE_PEM
)){
439 q_status_message1(SM_ORDER
, 3, 3, _("Error loading file %s"), buf
);
446 cert
= fs_get(sizeof(CertList
));
447 memset((void *)cert
, 0, sizeof(CertList
));
448 cert
->name
= cpystr(d
->d_name
);
449 /* read buf into a bio and fill the CertData structure */
450 if((in
= BIO_new_file(buf
, "r"))!=0){
451 x
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
);
452 if(x
&& x
->cert_info
){
453 cert
->data
.date_from
= smime_get_date(x
->cert_info
->validity
->notBefore
);
454 cert
->data
.date_to
= smime_get_date(x
->cert_info
->validity
->notAfter
);
455 get_fingerprint(x
, EVP_md5(), buf
, sizeof(buf
), NULL
);
456 cert
->data
.md5
= cpystr(buf
);
464 for (cl
= *cdata
; cl
&& cl
->next
; cl
= cl
->next
);
482 * Get an X509_STORE. This consists of the system
483 * certs directory and any certificates in the user's
484 * ~/.alpine-smime/ca directory.
490 X509_STORE
*store
= NULL
;
492 dprint((9, "get_ca_store()"));
494 if(!(store
=X509_STORE_new())){
495 dprint((9, "X509_STORE_new() failed"));
499 if(!(lookup
=X509_STORE_add_lookup(store
, X509_LOOKUP_file()))){
500 dprint((9, "X509_STORE_add_lookup() failed"));
501 X509_STORE_free(store
);
505 if(ps_global
->smime
&& ps_global
->smime
->catype
== Container
506 && ps_global
->smime
->cacontent
){
508 if(!mem_add_extra_cacerts(ps_global
->smime
->cacontent
, lookup
)){
509 X509_STORE_free(store
);
513 else if(ps_global
->smime
&& ps_global
->smime
->catype
== Directory
514 && ps_global
->smime
->capath
){
515 if(add_certs_in_dir(lookup
, ps_global
->smime
->capath
, ".crt", &ps_global
->smime
->cacertlist
) < 0){
516 X509_STORE_free(store
);
519 resort_certificates(&ps_global
->smime
->cacertlist
, CACert
);
522 if(!(lookup
=X509_STORE_add_lookup(store
, X509_LOOKUP_hash_dir()))){
523 X509_STORE_free(store
);
527 #ifdef SMIME_SSLCERTS
528 dprint((9, "get_ca_store(): adding cacerts from %s", SMIME_SSLCERTS
));
529 X509_LOOKUP_add_dir(lookup
, SMIME_SSLCERTS
, X509_FILETYPE_PEM
);
537 load_key(PERSONAL_CERT
*pc
, char *pass
, int flag
)
540 EVP_PKEY
*key
= NULL
;
541 char buf
[MAXPATH
], file
[MAXPATH
];
543 if(!(ps_global
->smime
&& pc
&& pc
->name
))
546 if(ps_global
->smime
->privatetype
== Container
){
549 if(pc
->keytext
&& (q
= strstr(pc
->keytext
, "-----END")) != NULL
){
550 while(*q
&& *q
!= '\n')
556 if((in
= BIO_new_mem_buf(pc
->keytext
, q
-pc
->keytext
)) != NULL
){
557 key
= PEM_read_bio_PrivateKey(in
, NULL
, NULL
, pass
);
562 else if(ps_global
->smime
->privatetype
== Directory
){
563 /* filename is path/name.key */
564 strncpy(buf
, pc
->name
, sizeof(buf
)-5);
565 buf
[sizeof(buf
)-5] = '\0';
566 strncat(buf
, ".key", 5);
567 build_path(file
, ps_global
->smime
->privatepath
, buf
, sizeof(file
));
569 if(!(in
= BIO_new_file(file
, "r")))
572 key
= PEM_read_bio_PrivateKey(in
, NULL
, NULL
, pass
);
580 #include <openssl/x509v3.h>
582 * This newer version is from Adrian Vogel. It looks for the email
583 * address not only in the email address field, but also in an
584 * X509v3 extension field, Subject Altenative Name.
587 get_x509_subject_email(X509
*x
)
589 char **result
= NULL
;
591 STACK_OF(OPENSSL_STRING
) *emails
= X509_get1_email(x
);
592 if ((n
= sk_OPENSSL_STRING_num(emails
)) > 0) {
593 result
= fs_get((n
+1)*sizeof(char *));
594 for(i
= 0; i
< n
; i
++)
595 result
[i
] = cpystr(sk_OPENSSL_STRING_value(emails
, i
));
598 X509_email_free(emails
);
604 * Save the certificate for the given email address in
605 * ~/.alpine-smime/public.
607 * Should consider the security hazards in making a file with
608 * the email address that has come from the certificate.
610 * The argument email is destroyed.
612 * args: ctype says where the user wants to save the certificate
615 save_cert_for(char *email
, X509
*cert
, WhichCerts ctype
)
617 if(!ps_global
->smime
|| ctype
== Private
)
620 dprint((9, "save_cert_for(%s, %s)", email
? email
: "?", ctype
== Public
? _("Public") : ctype
== Private
? _("Private") : "CACert"));
621 emailstrclean(email
);
623 if(ps_global
->smime
->publictype
== Keychain
){
627 SecCertificateRef secCertificateRef
;
630 memset((void *) &certData
, 0, sizeof(certData
));
631 memset((void *) &secCertificateRef
, 0, sizeof(secCertificateRef
));
633 /* convert OpenSSL X509 cert data to MacOS certData */
634 if((certData
.Length
= i2d_X509(cert
, &(certData
.Data
))) > 0){
637 * Put that certData into a SecCertificateRef.
638 * Version 3 should work for versions 1-3.
640 if(!(rc
=SecCertificateCreateFromData(&certData
,
642 CSSM_CERT_ENCODING_DER
,
643 &secCertificateRef
))){
645 /* add it to the default keychain */
646 if(!(rc
=SecCertificateAddToKeychain(secCertificateRef
, NULL
))){
649 else if(rc
== errSecDuplicateItem
){
650 dprint((9, "save_cert_for: certificate for %s already in keychain", email
));
653 dprint((9, "SecCertificateAddToKeychain failed"));
657 dprint((9, "SecCertificateCreateFromData failed"));
661 dprint((9, "i2d_X509 failed"));
664 #endif /* APPLEKEYCHAIN */
666 else if(SMHOLDERTYPE(ctype
) == Container
){
667 REMDATA_S
*rd
= NULL
;
668 char *ret_dir
= NULL
;
671 char *upath
= PATHCERTDIR(ctype
);
672 char *tempfile
= NULL
;
674 CertList
*clist
= DATACERT(ctype
);
676 add_to_end_of_certlist(&clist
, email
, X509_dup(cert
));
679 case Private
: ps_global
->smime
->privatecertlist
= clist
; break;
680 case Public
: ps_global
->smime
->publiccertlist
= clist
; break;
681 case CACert
: ps_global
->smime
->cacertlist
= clist
; break;
688 if(IS_REMOTE(upath
)){
689 rd
= rd_create_remote(RemImap
, upath
, REMOTE_SMIME_SUBTYPE
,
691 _("Can't access remote smime configuration."));
696 (void) rd_read_metadata(rd
);
698 if(rd
->access
== MaybeRorW
){
699 if(rd
->read_status
== 'R')
700 rd
->access
= ReadOnly
;
702 rd
->access
= ReadWrite
;
705 if(rd
->access
!= NoExists
){
707 rd_check_remvalid(rd
, 1L);
710 * If the cached info says it is readonly but
711 * it looks like it's been fixed now, change it to readwrite.
713 if(rd
->read_status
== 'R'){
714 rd_check_readonly_access(rd
);
715 if(rd
->read_status
== 'W'){
716 rd
->access
= ReadWrite
;
717 rd
->flags
|= REM_OUTOFDATE
;
720 rd
->access
= ReadOnly
;
724 if(rd
->flags
& REM_OUTOFDATE
){
725 if(rd_update_local(rd
) != 0){
727 dprint((1, "save_cert_for: rd_update_local failed\n"));
728 rd_close_remdata(&rd
);
735 if(rd
->access
!= ReadWrite
|| rd_remote_is_readonly(rd
)){
736 rd_close_remdata(&rd
);
740 rd
->flags
|= DO_REMTRIM
;
742 strncpy(path
, rd
->lf
, sizeof(path
)-1);
743 path
[sizeof(path
)-1] = '\0';
746 strncpy(path
, upath
, sizeof(path
)-1);
747 path
[sizeof(path
)-1] = '\0';
750 tempfile
= tempfile_in_same_dir(path
, "az", &ret_dir
);
752 if(certlist_to_file(tempfile
, DATACERT(ctype
)))
756 if(strlen(path
) + strlen(tempfile
) - strlen(ret_dir
) + 1 < sizeof(path
))
757 snprintf(fpath
, sizeof(fpath
), "%s%c%s",
758 path
, tempfile
[strlen(ret_dir
)], tempfile
+ strlen(ret_dir
) + 1);
764 fs_give((void **)&ret_dir
);
767 if(rename_file(tempfile
, fpath
) < 0){
768 q_status_message2(SM_ORDER
, 3, 3,
769 _("Can't rename %s to %s"), tempfile
, fpath
);
774 if(!err
&& IS_REMOTE(upath
)){
780 we_cancel
= busy_cue(_("Copying to remote smime container"), NULL
, 1);
781 if((e
= rd_update_remote(rd
, datebuf
)) != 0){
783 q_status_message2(SM_ORDER
| SM_DING
, 3, 5,
784 _("Error opening temporary smime file %s: %s"),
785 rd
->lf
, error_description(errno
));
787 "write_remote_smime: error opening temp file %s\n",
788 rd
->lf
? rd
->lf
: "?"));
791 q_status_message2(SM_ORDER
| SM_DING
, 3, 5,
792 _("Error copying to %s: %s"),
793 rd
->rn
, error_description(errno
));
795 "write_remote_smime: error copying from %s to %s\n",
796 rd
->lf
? rd
->lf
: "?", rd
->rn
? rd
->rn
: "?"));
799 q_status_message(SM_ORDER
| SM_DING
, 5, 5,
800 _("Copy of smime cert to remote folder failed, changes NOT saved remotely"));
803 rd_update_metadata(rd
, datebuf
);
804 rd
->read_status
= 'W';
807 rd_close_remdata(&rd
);
813 fs_give((void **) &tempfile
);
816 else if(SMHOLDERTYPE(ctype
) == Directory
){
817 char *path
= PATHCERTDIR(ctype
);
818 char certfilename
[MAXPATH
];
821 build_path(certfilename
, path
, email
, sizeof(certfilename
));
822 strncat(certfilename
, ".crt", sizeof(certfilename
)-1-strlen(certfilename
));
823 certfilename
[sizeof(certfilename
)-1] = 0;
825 bio_out
= BIO_new_file(certfilename
, "w");
827 PEM_write_bio_X509(bio_out
, cert
);
829 q_status_message1(SM_ORDER
, 1, 1, _("Saved certificate for <%s>"), email
);
832 q_status_message1(SM_ORDER
, 1, 1, _("Couldn't save certificate for <%s>"), email
);
839 * Try to retrieve the certificate for the given email address.
840 * The caller should free the cert.
843 get_cert_for(char *email
, WhichCerts ctype
)
845 char certfilename
[MAXPATH
];
846 char emailaddr
[MAXPATH
];
850 if(!ps_global
->smime
)
853 dprint((9, "get_cert_for(%s, %s)", email
? email
: "?", "none yet"));
855 if(ctype
== Private
) /* there is no private certificate info */
856 ctype
= Public
; /* return public information instead */
857 strncpy(emailaddr
, email
, sizeof(emailaddr
)-1);
858 emailaddr
[sizeof(emailaddr
)-1] = 0;
860 /* clean it up (lowercase, space removal) */
861 emailstrclean(emailaddr
);
863 if(ps_global
->smime
->publictype
== Keychain
){
867 SecKeychainItemRef itemRef
= nil
;
868 SecKeychainAttributeList attrList
;
869 SecKeychainAttribute attrib
;
870 SecKeychainSearchRef searchRef
= nil
;
873 /* low-level form of MacOS data */
874 memset((void *) &certData
, 0, sizeof(certData
));
877 attrList
.attr
= &attrib
;
879 /* kSecAlias means email address for a certificate */
880 attrib
.tag
= kSecAlias
;
881 attrib
.data
= emailaddr
;
882 attrib
.length
= strlen(attrib
.data
);
884 /* Find the certificate in the default keychain */
885 if(!(rc
=SecKeychainSearchCreateFromAttributes(NULL
,
886 kSecCertificateItemClass
,
890 if(!(rc
=SecKeychainSearchCopyNext(searchRef
, &itemRef
))){
892 /* extract the data portion of the certificate */
893 if(!(rc
=SecCertificateGetData((SecCertificateRef
) itemRef
, &certData
))){
896 * Convert it from MacOS form to OpenSSL form.
897 * The input is certData from above and the output
900 if(!d2i_X509(&cert
, &(certData
.Data
), certData
.Length
)){
901 dprint((9, "d2i_X509 failed"));
905 dprint((9, "SecCertificateGetData failed"));
908 else if(rc
== errSecItemNotFound
){
909 dprint((9, "get_cert_for: Public cert for %s not found", emailaddr
));
912 dprint((9, "SecKeychainSearchCopyNext failed"));
916 dprint((9, "SecKeychainSearchCreateFromAttributes failed"));
920 CFRelease(searchRef
);
922 #endif /* APPLEKEYCHAIN */
924 else if(SMHOLDERTYPE(ctype
) == Container
){
927 for(cl
= DATACERT(ctype
); cl
; cl
= cl
->next
){
928 if(cl
->name
&& !strucmp(emailaddr
, cl
->name
))
933 cert
= X509_dup((X509
*) cl
->x509_cert
);
935 else if(SMHOLDERTYPE(ctype
) == Directory
){
936 build_path(certfilename
, PATHCERTDIR(ctype
), emailaddr
, sizeof(certfilename
));
937 strncat(certfilename
, EXTCERT(ctype
), sizeof(certfilename
)-1-strlen(certfilename
));
938 certfilename
[sizeof(certfilename
)-1] = 0;
940 if((in
= BIO_new_file(certfilename
, "r"))!=0){
942 cert
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
);
945 /* could check email addr in cert matches */
956 * load_cert_for_key finds a certificate in pathdir that matches a private key
957 * pkey. It returns its name in certfile, and the certificate in *pcert.
958 * return value: success: different from zero, failure 0. If both certfile
959 * and pcert are NULL, this function returns if there is certificate that
960 * matches the given key.
963 load_cert_for_key(char *pathdir
, EVP_PKEY
*pkey
, char **certfile
, X509
**pcert
)
970 char buf
[MAXPATH
+1], pathcert
[MAXPATH
+1];
972 if(pathdir
== NULL
|| pkey
== NULL
)
975 if(certfile
) *certfile
= NULL
;
976 if(pcert
) *pcert
= NULL
;
978 if((dirp
= opendir(pathdir
)) != NULL
){
979 while(rv
== 0 && (d
=readdir(dirp
)) != NULL
){
982 if((ll
=strlen(d
->d_name
)) && ll
> 4){
983 if(!strcmp(d
->d_name
+ll
-4, ".crt")){
984 strncpy(buf
, d
->d_name
, sizeof(buf
));
985 buf
[sizeof(buf
)-1] = '\0';
986 build_path(pathcert
, pathdir
, buf
, sizeof(pathcert
));
987 if((in
= BIO_new_file(pathcert
, "r")) != NULL
){
988 if((x
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
)) != NULL
){
989 if(X509_check_private_key(x
, pkey
) > 0){
991 if(certfile
) *certfile
= cpystr(buf
);
992 if(pcert
) *pcert
= x
;
1009 mem_to_personal_certs(char *contents
)
1011 PERSONAL_CERT
*result
= NULL
;
1012 char *p
, *q
, *line
, *name
, *keytext
, *save_p
;
1015 if(contents
&& *contents
){
1016 for(p
= contents
; *p
!= '\0';){
1019 while(*p
&& *p
!= '\n')
1028 if(strncmp(EMAILADDRLEADER
, line
, strlen(EMAILADDRLEADER
)) == 0){
1029 name
= line
+ strlen(EMAILADDRLEADER
);
1030 cert
= get_cert_for(name
, Public
);
1033 /* advance p past this record */
1034 if((q
= strstr(keytext
, "-----END")) != NULL
){
1035 while(*q
&& *q
!= '\n')
1045 q_status_message(SM_ORDER
| SM_DING
, 3, 3, _("Error in privatekey container, missing END"));
1051 pc
= (PERSONAL_CERT
*) fs_get(sizeof(*pc
));
1053 pc
->name
= cpystr(name
);
1054 pc
->keytext
= keytext
; /* a pointer into contents */
1056 pc
->key
= load_key(pc
, "", SM_NORMALCERT
);
1073 mem_to_certlist(char *contents
, WhichCerts ctype
)
1075 CertList
*ret
= NULL
;
1076 char *p
, *q
, *line
, *name
, *certtext
, *save_p
;
1079 char *sep
= (ctype
== Public
|| ctype
== Private
)
1080 ? EMAILADDRLEADER
: CACERTSTORELEADER
;
1082 if(contents
&& *contents
){
1083 for(p
= contents
; *p
!= '\0';){
1086 while(*p
&& *p
!= '\n')
1095 if(strncmp(sep
, line
, strlen(sep
)) == 0){
1096 name
= line
+ strlen(sep
);
1098 certtext
= strstr(p
, "-----BEGIN");
1099 if(certtext
!= NULL
){
1100 if((q
= strstr(certtext
, sep
)) != NULL
)
1103 p
= q
= certtext
+strlen(certtext
);
1105 if((in
= BIO_new_mem_buf(certtext
, q
-certtext
)) != 0){
1106 cert
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
);
1111 q_status_message2(SM_ORDER
| SM_DING
, 3, 3, _("Error in %scert container, missing BEGIN, certtext=%s"), ctype
== Public
? _("public") : _("ca"), p
);
1116 add_to_end_of_certlist(&ret
, name
, cert
);
1129 * Add the CACert Container contents into the CACert store.
1131 * Returns > 0 for success, 0 for failure
1134 mem_add_extra_cacerts(char *contents
, X509_LOOKUP
*lookup
)
1136 char *p
, *q
, *line
, *certtext
, *save_p
;
1138 int len
, failed
= 0;
1143 * The most straight-forward way to do this is to write
1144 * the container contents to a temp file and then load the
1145 * contents of the file with X509_LOOKUP_load_file(), like
1146 * is done in add_certs_in_dir(). What we don't know is if
1147 * each file should consist of one cacert or if they can all
1148 * just be jammed together into one file. To be safe, we'll use
1149 * one file per and do each in a separate operation.
1152 if(contents
&& *contents
){
1153 for(p
= contents
; *p
!= '\0';){
1156 while(*p
&& *p
!= '\n')
1165 /* look for separator line */
1166 if(strncmp(CACERTSTORELEADER
, line
, strlen(CACERTSTORELEADER
)) == 0){
1167 /* certtext is the content that should go in a file */
1168 certtext
= strstr(p
, "-----BEGIN");
1169 if(certtext
!= NULL
){
1170 if((q
= strstr(certtext
, CACERTSTORELEADER
)) != NULL
){
1173 else{ /* end of file */
1174 q
= certtext
+ strlen(certtext
);
1178 in
= BIO_new_mem_buf(certtext
, q
-certtext
);
1180 tempfile
= temp_nam(NULL
, "az");
1183 out
= BIO_new_file(tempfile
, "w");
1186 while((len
= BIO_read(in
, iobuf
, sizeof(iobuf
))) > 0)
1187 BIO_write(out
, iobuf
, len
);
1190 if(!X509_LOOKUP_load_file(lookup
, tempfile
, X509_FILETYPE_PEM
))
1193 fs_give((void **) &tempfile
);
1201 q_status_message1(SM_ORDER
| SM_DING
, 3, 3, _("Error in cacert container, missing BEGIN, certtext=%s"), certtext
);
1206 q_status_message1(SM_ORDER
| SM_DING
, 3, 3, _("Error in cacert container, missing separator, line=%s"), line
);
1219 certlist_to_file(char *filename
, CertList
*certlist
)
1222 BIO
*bio_out
= NULL
;
1225 if(filename
&& (bio_out
=BIO_new_file(filename
, "w")) != NULL
){
1227 for(cl
= certlist
; cl
; cl
= cl
->next
){
1228 if(cl
->name
&& cl
->name
[0] && cl
->x509_cert
){
1229 if(!((BIO_puts(bio_out
, EMAILADDRLEADER
) > 0)
1230 && (BIO_puts(bio_out
, cl
->name
) > 0)
1231 && (BIO_puts(bio_out
, "\n") > 0)))
1234 if(!PEM_write_bio_X509(bio_out
, (X509
*) cl
->x509_cert
))
1247 add_to_end_of_certlist(CertList
**cl
, char *name
, X509
*cert
)
1249 CertList
*new, *clp
;
1254 new = (CertList
*) fs_get(sizeof(*new));
1255 memset((void *) new, 0, sizeof(*new));
1256 new->x509_cert
= cert
;
1257 new->name
= name
? cpystr(name
) : NULL
;
1263 for(clp
= (*cl
); clp
->next
; clp
= clp
->next
)
1272 free_certlist(CertList
**cl
)
1275 if((*cl
)->data
.date_from
)
1276 fs_give((void **) &(*cl
)->data
.date_from
);
1278 if((*cl
)->data
.date_to
)
1279 fs_give((void **) &(*cl
)->data
.date_to
);
1282 fs_give((void **) &(*cl
)->data
.md5
);
1285 fs_give((void **) &(*cl
)->name
);
1287 if((*cl
)->x509_cert
)
1288 X509_free((X509
*) (*cl
)->x509_cert
);
1290 free_certlist(&(*cl
)->next
);
1292 fs_give((void **) cl
);
1298 free_personal_certs(PERSONAL_CERT
**pc
)
1301 free_personal_certs(&(*pc
)->next
);
1303 fs_give((void **) &(*pc
)->name
);
1306 fs_give((void **) &(*pc
)->name
);
1309 X509_free((*pc
)->cert
);
1312 EVP_PKEY_free((*pc
)->key
);
1314 fs_give((void **) pc
);