2 * Copyright notice from original mutt:
3 * Copyright (C) 2001,2002 Oliver Ehli <elmy@acm.org>
4 * Copyright (C) 2002 Mike Schiraldi <raldi@research.netsol.com>
5 * Copyright (C) 2004 g10 Code GmbH
7 * This file is part of mutt-ng, see http://www.muttng.org/.
8 * It's licensed under the GNU General Public License,
9 * please see the file GPL in the top level source directory.
27 #ifdef HAVE_SYS_TIME_H
28 # include <sys/time.h>
30 #ifdef HAVE_SYS_RESOURCE_H
31 # include <sys/resource.h>
34 #include <lib-lib/mem.h>
35 #include <lib-lib/str.h>
36 #include <lib-lib/macros.h>
37 #include <lib-lib/file.h>
38 #include <lib-lib/debug.h>
40 #include <lib-mime/mime.h>
42 #include <lib-ui/curses.h>
43 #include <lib-ui/enter.h>
44 #include <lib-ui/menu.h>
53 struct smime_command_context {
54 const char *key; /* %k */
55 const char *cryptalg; /* %a */
56 const char *fname; /* %f */
57 const char *sig_fname; /* %s */
58 const char *certificates; /* %c */
59 const char *intermediates; /* %i */
68 char trust; /* i=Invalid r=revoked e=expired u=unverified v=verified t=trusted */
69 short public; /* 1=public 0=private */
73 char SmimePass[STRING];
74 time_t SmimeExptime = 0; /* when does the cached passphrase expire? */
77 static char SmimeKeyToUse[_POSIX_PATH_MAX] = { 0 };
78 static char SmimeCertToUse[_POSIX_PATH_MAX];
79 static char SmimeIntermediateToUse[_POSIX_PATH_MAX];
83 * Create a format string to be used with scanf.
84 * To use it, write, for instance, MUTT_FORMAT(HUGE_STRING).
86 * See K&R 2nd ed, p. 231 for an explanation.
88 #define _MUTT_FORMAT_2(a,b) "%" a b
89 #define _MUTT_FORMAT_1(a, b) _MUTT_FORMAT_2(#a, b)
90 #define MUTT_FORMAT(a) _MUTT_FORMAT_1(a, "s")
94 * Queries and passphrase handling.
98 /* these are copies from pgp.c */
101 void smime_void_passphrase (void)
103 p_clear(SmimePass, countof(SmimePass));
107 int smime_valid_passphrase (void)
109 time_t now = time (NULL);
111 if (now < SmimeExptime)
112 /* Use cached copy. */
115 smime_void_passphrase ();
117 if (mutt_get_field_unbuffered (_("Enter S/MIME passphrase:"), SmimePass,
118 sizeof (SmimePass), M_PASS) == 0) {
119 SmimeExptime = time (NULL) + SmimeTimeout;
130 * The OpenSSL interface
133 /* This is almost identical to ppgp's invoking interface. */
136 _mutt_fmt_smime_command (char *dest, ssize_t destlen, char op,
137 const char *src, const char *prefix,
138 const char *ifstring, const char *elsestring,
139 unsigned long data, format_flag flags)
142 struct smime_command_context *cctx = (struct smime_command_context *) data;
143 int optional = (flags & M_FORMAT_OPTIONAL);
149 char path[_POSIX_PATH_MAX];
150 char buf1[LONG_STRING], buf2[LONG_STRING];
153 m_strcpy(path, sizeof(path), NONULL(SmimeCALocation));
154 mutt_expand_path (path, sizeof (path));
155 mutt_quote_filename (buf1, sizeof (buf1), path);
157 if (stat (path, &sb) != 0 || !S_ISDIR (sb.st_mode))
158 snprintf (buf2, sizeof (buf2), "-CAfile %s", buf1);
160 snprintf (buf2, sizeof (buf2), "-CApath %s", buf1);
162 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
163 snprintf (dest, destlen, fmt, buf2);
165 else if (!SmimeCALocation)
171 { /* certificate (list) */
173 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
174 snprintf (dest, destlen, fmt, NONULL (cctx->certificates));
176 else if (!cctx->certificates)
182 { /* intermediate certificates */
184 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
185 snprintf (dest, destlen, fmt, NONULL (cctx->intermediates));
187 else if (!cctx->intermediates)
193 { /* detached signature */
195 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
196 snprintf (dest, destlen, fmt, NONULL (cctx->sig_fname));
198 else if (!cctx->sig_fname)
206 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
207 snprintf (dest, destlen, fmt, NONULL (cctx->key));
215 { /* algorithm for encryption */
217 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
218 snprintf (dest, destlen, fmt, NONULL (cctx->cryptalg));
226 { /* file to process */
228 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
229 snprintf (dest, destlen, fmt, NONULL (cctx->fname));
231 else if (!cctx->fname)
242 mutt_FormatString (dest, destlen, ifstring, _mutt_fmt_smime_command,
244 else if (flags & M_FORMAT_OPTIONAL)
245 mutt_FormatString (dest, destlen, elsestring, _mutt_fmt_smime_command,
253 static void mutt_smime_command (char *d, ssize_t dlen,
254 struct smime_command_context *cctx,
257 mutt_FormatString (d, dlen, NONULL (fmt), _mutt_fmt_smime_command,
258 (unsigned long) cctx, 0);
259 debug_print (2, ("%s\n", d));
262 static pid_t smime_invoke (FILE ** smimein, FILE ** smimeout,
263 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
264 int smimeerrfd, const char *fname,
265 const char *sig_fname, const char *cryptalg,
266 const char *key, const char *certificates,
267 const char *intermediates, const char *format)
269 struct smime_command_context cctx;
270 char cmd[HUGE_STRING];
274 if (!format || !*format)
278 cctx.sig_fname = sig_fname;
280 cctx.cryptalg = cryptalg;
281 cctx.certificates = certificates;
282 cctx.intermediates = intermediates;
284 mutt_smime_command (cmd, sizeof (cmd), &cctx, format);
286 return mutt_create_filter_fd (cmd, smimein, smimeout, smimeerr,
287 smimeinfd, smimeoutfd, smimeerrfd);
296 * Key and certificate handling.
302 Search the certificate index for given mailbox.
303 return certificate file name.
306 static void smime_entry (char *s, ssize_t l, MUTTMENU * menu, int num)
308 smime_id *Table = (smime_id *) menu->data;
309 smime_id this = Table[num];
310 const char *truststate;
312 switch (this.trust) {
314 truststate = N_("Trusted ");
317 truststate = N_("Verified ");
320 truststate = N_("Unverified");
323 truststate = N_("Expired ");
326 truststate = N_("Revoked ");
329 truststate = N_("Invalid ");
332 truststate = N_("Unknown ");
335 snprintf (s, l, " 0x%.8X.%i %s %-35.35s %s", this.hash, this.suffix,
336 truststate, this.email, this.nick);
338 snprintf (s, l, " 0x%.8X.%i %-35.35s %s", this.hash, this.suffix,
339 this.email, this.nick);
346 char *smime_ask_for_key (char *prompt, char *mailbox __attribute__((unused)),
351 long cert_num; /* Will contain the number of certificates.
352 * To be able to get it, the .index file will be read twice... */
353 char index_file[_POSIX_PATH_MAX];
355 char buf[LONG_STRING];
356 char fields[5][STRING];
357 int numFields, hash_suffix, done, cur; /* The current entry */
360 char helpstr[HUGE_STRING * 3];
365 prompt = _("Enter keyID: ");
366 snprintf (index_file, sizeof (index_file), "%s/.index",
367 public ? NONULL (SmimeCertificates) : NONULL (SmimeKeys));
369 idx = fopen (index_file, "r");
371 mutt_perror (index_file);
376 while (!feof (idx)) {
377 if (fgets (buf, sizeof (buf), idx))
384 if (mutt_get_field (prompt, qry, sizeof (qry), 0))
386 snprintf (title, sizeof (title),
387 _("S/MIME certificates matching \"%s\"."), qry);
390 idx = fopen (index_file, "r");
392 mutt_perror (index_file);
397 Table = p_new(smime_id, cert_num);
398 while (!feof (idx)) {
400 fscanf (idx, MUTT_FORMAT (STRING) " %x.%i " MUTT_FORMAT (STRING),
401 fields[0], &hash, &hash_suffix, fields[2]);
403 fscanf (idx, MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) "\n",
404 fields[3], fields[4]);
406 /* 0=email 1=name 2=nick 3=intermediate 4=trust */
410 /* Check if query matches this certificate */
411 if (!m_stristr(fields[0], qry) && !m_stristr(fields[2], qry))
414 Table[cur].hash = hash;
415 Table[cur].suffix = hash_suffix;
416 m_strcpy(Table[cur].email, sizeof(Table[cur].email), fields[0]);
417 m_strcpy(Table[cur].nick, sizeof(Table[cur].nick), fields[2]);
418 Table[cur].trust = *fields[4];
419 Table[cur].public = public;
425 /* Make Helpstring */
427 mutt_make_help (buf, sizeof (buf), _("Exit "), MENU_SMIME, OP_EXIT);
428 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
429 mutt_make_help (buf, sizeof (buf), _("Select "), MENU_SMIME,
430 OP_GENERIC_SELECT_ENTRY);
431 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
432 mutt_make_help (buf, sizeof (buf), _("Help"), MENU_SMIME, OP_HELP);
433 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
435 /* Create the menu */
436 menu = mutt_new_menu ();
438 menu->make_entry = smime_entry;
439 menu->menu = MENU_SMIME;
440 menu->help = helpstr;
443 /* sorting keys might be done later - TODO */
450 switch (mutt_menuLoop (menu)) {
451 case OP_GENERIC_SELECT_ENTRY:
463 fname = p_new(char, 13); /* Hash + '.' + Suffix + \0 */
464 sprintf (fname, "%.8x.%i", Table[cur].hash, Table[cur].suffix);
469 mutt_menuDestroy (&menu);
471 set_option (OPTNEEDREDRAW);
480 char *smime_get_field_from_db (char *mailbox, char *query, short public,
483 int addr_len, query_len, found = 0, ask = 0, choice = 0;
484 char cert_path[_POSIX_PATH_MAX];
485 char buf[LONG_STRING], prompt[STRING];
486 char fields[5][STRING];
490 char key_trust_level = 0;
493 if (!mailbox && !query)
496 addr_len = mailbox ? m_strlen(mailbox) : 0;
497 query_len = query ? m_strlen(query) : 0;
501 /* index-file format:
502 mailbox certfile label issuer_certfile trust_flags\n
504 certfile is a hash value generated by openssl.
505 Note that this was done according to the OpenSSL
506 specs on their CA-directory.
509 snprintf (cert_path, sizeof (cert_path), "%s/.index",
510 (public ? NONULL (SmimeCertificates) : NONULL (SmimeKeys)));
512 if (!stat (cert_path, &info)) {
513 if ((fp = safe_fopen (cert_path, "r")) == NULL) {
514 mutt_perror (cert_path);
518 while (fgets (buf, sizeof (buf) - 1, fp) != NULL)
519 if (mailbox && !(m_strncasecmp(mailbox, buf, addr_len))) {
520 numFields = sscanf (buf,
521 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
522 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
523 MUTT_FORMAT (STRING) "\n",
524 fields[0], fields[1],
525 fields[2], fields[3], fields[4]);
528 if (mailbox && public &&
530 *fields[4] == 'i' || *fields[4] == 'e' || *fields[4] == 'r'))
534 if (public && *fields[4] == 'u')
535 snprintf (prompt, sizeof (prompt),
537 ("ID %s is unverified. Do you want to use it for %s ?"),
539 else if (public && *fields[4] == 'v')
540 snprintf (prompt, sizeof (prompt),
541 _("Use (untrusted!) ID %s for %s ?"),
544 snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"),
548 if (may_ask && (choice = mutt_yesorno (prompt, M_NO)) == -1) {
554 else if (choice == M_NO) {
558 else if (choice == M_YES) {
559 m_strcpy(key, sizeof(key), fields[1]);
566 key_trust_level = *fields[4];
567 m_strcpy(key, sizeof(key), fields[1]);
572 numFields = sscanf (buf,
573 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
574 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
575 MUTT_FORMAT (STRING) "\n",
576 fields[0], fields[1],
577 fields[2], fields[3], fields[4]);
579 /* query = label: return certificate. */
580 if (numFields >= 3 &&
581 !(m_strncasecmp(query, fields[2], query_len))) {
583 m_strcpy(key, sizeof(key), fields[1]);
585 /* query = certificate: return intermediate certificate. */
586 else if (numFields >= 4 &&
587 !(m_strncasecmp(query, fields[1], query_len))) {
589 m_strcpy(key, sizeof(key), fields[3]);
596 if (public && *fields[4] == 'u')
597 snprintf (prompt, sizeof (prompt),
598 _("ID %s is unverified. Do you want to use it for %s ?"),
600 else if (public && *fields[4] == 'v')
601 snprintf (prompt, sizeof (prompt),
602 _("Use (untrusted!) ID %s for %s ?"), fields[1], mailbox);
604 snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"), key,
606 choice = mutt_yesorno (prompt, M_NO);
607 if (choice == -1 || choice == M_NO)
610 else if (key_trust_level && may_ask) {
611 if (key_trust_level == 'u') {
612 snprintf (prompt, sizeof (prompt),
613 _("ID %s is unverified. Do you want to use it for %s ?"),
615 choice = mutt_yesorno (prompt, M_NO);
619 else if (key_trust_level == 'v') {
621 ("Warning: You have not yet decided to trust ID %s. (any key to continue)"),
629 /* Note: m_strdup("") returns NULL. */
630 return m_strdup(key);
637 This sets the '*ToUse' variables for an upcoming decryption, where
638 the reuquired key is different from SmimeDefaultKey.
641 void _smime_getkeys (char *mailbox)
646 k = smime_get_field_from_db (mailbox, NULL, 0, 1);
649 snprintf (buf, sizeof (buf), _("Enter keyID for %s: "), mailbox);
650 k = smime_ask_for_key (buf, mailbox, 0);
654 /* the key used last time. */
655 if (*SmimeKeyToUse &&
656 !m_strcasecmp(k, SmimeKeyToUse + m_strlen(SmimeKeys) + 1)) {
661 smime_void_passphrase ();
663 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
664 NONULL (SmimeKeys), k);
666 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
667 NONULL (SmimeCertificates), k);
669 if (m_strcasecmp(k, SmimeDefaultKey))
670 smime_void_passphrase ();
676 if (*SmimeKeyToUse) {
677 if (!m_strcasecmp(SmimeDefaultKey,
678 SmimeKeyToUse + m_strlen(SmimeKeys) + 1))
681 smime_void_passphrase ();
684 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
685 NONULL (SmimeKeys), NONULL (SmimeDefaultKey));
687 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
688 NONULL (SmimeCertificates), NONULL (SmimeDefaultKey));
691 void smime_getkeys (ENVELOPE * env)
696 if (option (OPTSDEFAULTDECRYPTKEY) && SmimeDefaultKey && *SmimeDefaultKey) {
697 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
698 NONULL (SmimeKeys), SmimeDefaultKey);
700 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
701 NONULL (SmimeCertificates), SmimeDefaultKey);
706 for (t = env->to; !found && t; t = t->next)
707 if (mutt_addr_is_user (t)) {
709 _smime_getkeys (t->mailbox);
711 for (t = env->cc; !found && t; t = t->next)
712 if (mutt_addr_is_user (t)) {
714 _smime_getkeys (t->mailbox);
716 if (!found && (t = mutt_default_from ())) {
717 _smime_getkeys (t->mailbox);
718 address_list_wipe(&t);
722 /* This routine attempts to find the keyids of the recipients of a message.
723 * It returns NULL if any of the keys can not be found.
726 char *smime_findKeys (address_t * to, address_t * cc, address_t * bcc)
728 char *keyID, *keylist = NULL;
729 ssize_t keylist_size = 0;
730 ssize_t keylist_used = 0;
731 address_t *tmp = NULL, *addr = NULL;
732 address_t **last = &tmp;
736 const char *fqdn = mutt_fqdn (1);
738 for (i = 0; i < 3; i++) {
753 *last = address_list_dup (p);
755 last = &((*last)->next);
759 rfc822_qualify (tmp, fqdn);
761 tmp = mutt_remove_duplicates (tmp);
763 for (p = tmp; p; p = p->next) {
764 char buf[LONG_STRING];
768 if ((keyID = smime_get_field_from_db (q->mailbox, NULL, 1, 1)) == NULL) {
769 snprintf (buf, sizeof (buf), _("Enter keyID for %s: "), q->mailbox);
770 keyID = smime_ask_for_key (buf, q->mailbox, 1);
773 mutt_message (_("No (valid) certificate found for %s."), q->mailbox);
775 address_list_wipe(&tmp);
776 address_list_wipe(&addr);
780 keylist_size += m_strlen(keyID) + 2;
781 p_realloc(&keylist, keylist_size);
782 sprintf (keylist + keylist_used, "%s\n", keyID); /* __SPRINTF_CHECKED__ */
783 keylist_used = m_strlen(keylist);
785 address_list_wipe(&addr);
788 address_list_wipe(&tmp);
797 static int smime_handle_cert_email (char *certificate, char *mailbox,
798 int copy, char ***buffer, int *num)
800 FILE *fpout = NULL, *fperr = NULL;
801 char tmpfname[_POSIX_PATH_MAX];
803 int ret = -1, count = 0;
806 mutt_mktemp (tmpfname);
807 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
808 mutt_perror (tmpfname);
811 mutt_unlink (tmpfname);
813 mutt_mktemp (tmpfname);
814 if ((fpout = safe_fopen (tmpfname, "w+")) == NULL) {
816 mutt_perror (tmpfname);
819 mutt_unlink (tmpfname);
821 if ((thepid = smime_invoke (NULL, NULL, NULL,
822 -1, fileno (fpout), fileno (fperr),
823 certificate, NULL, NULL, NULL, NULL, NULL,
824 SmimeGetCertEmailCommand)) == -1) {
825 mutt_message (_("Error: unable to create OpenSSL subprocess!"));
831 mutt_wait_filter (thepid);
839 while ((fgets (email, sizeof (email), fpout))) {
840 *(email + m_strlen(email) - 1) = '\0';
841 if (m_strncasecmp(email, mailbox, m_strlen(mailbox)) == 0)
844 ret = ret < 0 ? 0 : ret;
850 mutt_copy_stream (fperr, stdout);
851 mutt_any_key_to_continue (_
852 ("Error: unable to create OpenSSL subprocess!"));
860 if (copy && buffer && num) {
862 *buffer = p_new(char *, count);
866 while ((fgets (email, sizeof (email), fpout))) {
867 *(email + m_strlen(email) - 1) = '\0';
868 (*buffer)[count] = p_dupstr(email, m_strlen(email));
883 static char *smime_extract_certificate (char *infile)
885 FILE *fpout = NULL, *fperr = NULL;
886 char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
887 char tmpfname[_POSIX_PATH_MAX];
892 mutt_mktemp (tmpfname);
893 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
894 mutt_perror (tmpfname);
897 mutt_unlink (tmpfname);
899 mutt_mktemp (pk7out);
900 if ((fpout = safe_fopen (pk7out, "w+")) == NULL) {
902 mutt_perror (pk7out);
906 /* Step 1: Convert the signature to a PKCS#7 structure, as we can't
907 extract the full set of certificates directly.
909 if ((thepid = smime_invoke (NULL, NULL, NULL,
910 -1, fileno (fpout), fileno (fperr),
911 infile, NULL, NULL, NULL, NULL, NULL,
912 SmimePk7outCommand)) == -1) {
913 mutt_any_key_to_continue (_
914 ("Error: unable to create OpenSSL subprocess!"));
917 mutt_unlink (pk7out);
921 mutt_wait_filter (thepid);
928 empty = (fgetc (fpout) == EOF);
930 mutt_perror (pk7out);
931 mutt_copy_stream (fperr, stdout);
934 mutt_unlink (pk7out);
941 mutt_mktemp (certfile);
942 if ((fpout = safe_fopen (certfile, "w+")) == NULL) {
944 mutt_unlink (pk7out);
945 mutt_perror (certfile);
949 /* Step 2: Extract the certificates from a PKCS#7 structure.
951 if ((thepid = smime_invoke (NULL, NULL, NULL,
952 -1, fileno (fpout), fileno (fperr),
953 pk7out, NULL, NULL, NULL, NULL, NULL,
954 SmimeGetCertCommand)) == -1) {
955 mutt_any_key_to_continue (_
956 ("Error: unable to create OpenSSL subprocess!"));
959 mutt_unlink (pk7out);
960 mutt_unlink (certfile);
964 mutt_wait_filter (thepid);
966 mutt_unlink (pk7out);
972 empty = (fgetc (fpout) == EOF);
974 mutt_copy_stream (fperr, stdout);
977 mutt_unlink (certfile);
984 return m_strdup(certfile);
987 static char *smime_extract_signer_certificate (char *infile)
989 FILE *fpout = NULL, *fperr = NULL;
990 char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
991 char tmpfname[_POSIX_PATH_MAX];
996 mutt_mktemp (tmpfname);
997 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
998 mutt_perror (tmpfname);
1001 mutt_unlink (tmpfname);
1004 mutt_mktemp (certfile);
1005 if ((fpout = safe_fopen (certfile, "w+")) == NULL) {
1007 mutt_perror (certfile);
1011 /* Extract signer's certificate
1013 if ((thepid = smime_invoke (NULL, NULL, NULL,
1014 -1, -1, fileno (fperr),
1015 infile, NULL, NULL, NULL, certfile, NULL,
1016 SmimeGetSignerCertCommand)) == -1) {
1017 mutt_any_key_to_continue (_
1018 ("Error: unable to create OpenSSL subprocess!"));
1021 mutt_unlink (pk7out);
1022 mutt_unlink (certfile);
1026 mutt_wait_filter (thepid);
1032 empty = (fgetc (fpout) == EOF);
1035 mutt_copy_stream (fperr, stdout);
1036 mutt_any_key_to_continue (NULL);
1039 mutt_unlink (certfile);
1046 return m_strdup(certfile);
1052 /* Add a certificate and update index file (externally). */
1054 void smime_invoke_import (char *infile, char *mailbox __attribute__ ((unused)))
1056 char tmpfname[_POSIX_PATH_MAX], *certfile = NULL, buf[STRING];
1057 FILE *smimein = NULL, *fpout = NULL, *fperr = NULL;
1060 mutt_mktemp (tmpfname);
1061 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
1062 mutt_perror (tmpfname);
1065 mutt_unlink (tmpfname);
1067 mutt_mktemp (tmpfname);
1068 if ((fpout = safe_fopen (tmpfname, "w+")) == NULL) {
1070 mutt_perror (tmpfname);
1073 mutt_unlink (tmpfname);
1077 if (option (OPTASKCERTLABEL))
1078 mutt_get_field ("Label for certificate:", buf, sizeof (buf), 0);
1081 if ((certfile = smime_extract_certificate (infile))) {
1084 if ((thepid = smime_invoke (&smimein, NULL, NULL,
1085 -1, fileno (fpout), fileno (fperr),
1086 certfile, NULL, NULL, NULL, NULL, NULL,
1087 SmimeImportCertCommand)) == -1) {
1088 mutt_message (_("Error: unable to create OpenSSL subprocess!"));
1091 fputs (buf, smimein);
1092 fputc ('\n', smimein);
1095 mutt_wait_filter (thepid);
1097 mutt_unlink (certfile);
1098 p_delete(&certfile);
1106 mutt_copy_stream (fpout, stdout);
1107 mutt_copy_stream (fperr, stdout);
1116 int smime_verify_sender (HEADER * h)
1118 char *mbox = NULL, *certfile, tempfname[_POSIX_PATH_MAX];
1122 mutt_mktemp (tempfname);
1123 if (!(fpout = safe_fopen (tempfname, "w"))) {
1124 mutt_perror (tempfname);
1128 if (h->security & ENCRYPT)
1129 mutt_copy_message (fpout, Context, h,
1130 M_CM_DECODE_CRYPT & M_CM_DECODE_SMIME,
1131 CH_MIME | CH_WEED | CH_NONEWLINE);
1133 mutt_copy_message (fpout, Context, h, 0, 0);
1139 h->env->from = mutt_expand_aliases (h->env->from);
1140 mbox = h->env->from->mailbox;
1142 else if (h->env->sender) {
1143 h->env->sender = mutt_expand_aliases (h->env->sender);
1144 mbox = h->env->sender->mailbox;
1148 if ((certfile = smime_extract_signer_certificate (tempfname))) {
1149 mutt_unlink (tempfname);
1150 if (smime_handle_cert_email (certfile, mbox, 0, NULL, NULL)) {
1152 mutt_any_key_to_continue (NULL);
1156 mutt_unlink (certfile);
1157 p_delete(&certfile);
1160 mutt_any_key_to_continue (_("no certfile"));
1163 mutt_any_key_to_continue (_("no mbox"));
1165 mutt_unlink (tempfname);
1178 * Creating S/MIME - bodies.
1185 pid_t smime_invoke_encrypt (FILE ** smimein, FILE ** smimeout,
1186 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1187 int smimeerrfd, const char *fname,
1190 return smime_invoke (smimein, smimeout, smimeerr,
1191 smimeinfd, smimeoutfd, smimeerrfd,
1192 fname, NULL, SmimeCryptAlg, NULL, uids, NULL,
1193 SmimeEncryptCommand);
1198 pid_t smime_invoke_sign (FILE ** smimein, FILE ** smimeout, FILE ** smimeerr,
1199 int smimeinfd, int smimeoutfd, int smimeerrfd,
1202 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1203 smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1204 SmimeCertToUse, SmimeIntermediateToUse,
1211 BODY *smime_build_smime_entity (BODY * a, char *certlist)
1213 char buf[LONG_STRING], certfile[LONG_STRING];
1214 char tempfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1215 char smimeinfile[_POSIX_PATH_MAX];
1216 char *cert_start = certlist, *cert_end = certlist;
1217 FILE *smimein = NULL, *smimeerr = NULL, *fpout = NULL, *fptmp = NULL;
1222 mutt_mktemp (tempfile);
1223 if ((fpout = safe_fopen (tempfile, "w+")) == NULL) {
1224 mutt_perror (tempfile);
1228 mutt_mktemp (smimeerrfile);
1229 if ((smimeerr = safe_fopen (smimeerrfile, "w+")) == NULL) {
1230 mutt_perror (smimeerrfile);
1232 mutt_unlink (tempfile);
1235 mutt_unlink (smimeerrfile);
1237 mutt_mktemp (smimeinfile);
1238 if ((fptmp = safe_fopen (smimeinfile, "w+")) == NULL) {
1239 mutt_perror (smimeinfile);
1240 mutt_unlink (tempfile);
1248 int off = m_strlen(certfile);
1250 while (*++cert_end && *cert_end != '\n');
1254 snprintf (certfile + off, sizeof (certfile) - off, " %s/%s",
1255 NONULL (SmimeCertificates), cert_start);
1257 cert_start = cert_end;
1261 /* write a MIME entity */
1262 mutt_write_mime_header (a, fptmp);
1263 fputc ('\n', fptmp);
1264 mutt_write_mime_body (a, fptmp);
1268 smime_invoke_encrypt (&smimein, NULL, NULL, -1,
1269 fileno (fpout), fileno (smimeerr),
1270 smimeinfile, certfile)) == -1) {
1272 mutt_unlink (smimeinfile);
1273 mutt_unlink (certfile);
1279 mutt_wait_filter (thepid);
1280 mutt_unlink (smimeinfile);
1281 mutt_unlink (certfile);
1285 empty = (fgetc (fpout) == EOF);
1290 while (fgets (buf, sizeof (buf) - 1, smimeerr) != NULL) {
1292 fputs (buf, stdout);
1296 /* pause if there is any error output from SMIME */
1298 mutt_any_key_to_continue (NULL);
1301 /* fatal error while trying to encrypt message */
1303 mutt_any_key_to_continue _("No output from OpenSSL..");
1305 mutt_unlink (tempfile);
1309 t = mutt_new_body ();
1310 t->type = TYPEAPPLICATION;
1311 t->subtype = m_strdup("x-pkcs7-mime");
1312 mutt_set_parameter ("name", "smime.p7m", &t->parameter);
1313 mutt_set_parameter ("smime-type", "enveloped-data", &t->parameter);
1314 t->encoding = ENCBASE64; /* The output of OpenSSL SHOULD be binary */
1316 t->disposition = DISPATTACH;
1317 t->d_filename = m_strdup("smime.p7m");
1318 t->filename = m_strdup(tempfile);
1319 t->unlink = 1; /*delete after sending the message */
1329 BODY *smime_sign_message (BODY * a)
1332 char buffer[LONG_STRING];
1333 char signedfile[_POSIX_PATH_MAX], filetosign[_POSIX_PATH_MAX];
1334 FILE *smimein = NULL, *smimeout = NULL, *smimeerr = NULL, *sfp = NULL;
1338 char *intermediates = smime_get_field_from_db (NULL, SmimeDefaultKey, 1, 1);
1340 if (!intermediates) {
1341 mutt_message (_("Warning: Intermediate certificate not found."));
1342 intermediates = SmimeDefaultKey; /* so openssl won't complain in any case */
1345 convert_to_7bit (a); /* Signed data _must_ be in 7-bit format. */
1347 mutt_mktemp (filetosign);
1348 if ((sfp = safe_fopen (filetosign, "w+")) == NULL) {
1349 mutt_perror (filetosign);
1353 mutt_mktemp (signedfile);
1354 if ((smimeout = safe_fopen (signedfile, "w+")) == NULL) {
1355 mutt_perror (signedfile);
1357 mutt_unlink (filetosign);
1361 mutt_write_mime_header (a, sfp);
1363 mutt_write_mime_body (a, sfp);
1368 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
1369 NONULL (SmimeKeys), SmimeDefaultKey);
1371 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
1372 NONULL (SmimeCertificates), SmimeDefaultKey);
1374 snprintf (SmimeIntermediateToUse, sizeof (SmimeIntermediateToUse), "%s/%s",
1375 NONULL (SmimeCertificates), intermediates);
1379 if ((thepid = smime_invoke_sign (&smimein, NULL, &smimeerr,
1380 -1, fileno (smimeout), -1,
1381 filetosign)) == -1) {
1382 mutt_perror (_("Can't open OpenSSL subprocess!"));
1385 mutt_unlink (signedfile);
1386 mutt_unlink (filetosign);
1389 fputs (SmimePass, smimein);
1390 fputc ('\n', smimein);
1394 mutt_wait_filter (thepid);
1396 /* check for errors from OpenSSL */
1400 while (fgets (buffer, sizeof (buffer) - 1, smimeerr) != NULL) {
1402 fputs (buffer, stdout);
1409 empty = (fgetc (smimeout) == EOF);
1412 mutt_unlink (filetosign);
1416 mutt_any_key_to_continue (NULL);
1419 mutt_any_key_to_continue _("No output from OpenSSL...");
1421 mutt_unlink (signedfile);
1422 return (NULL); /* fatal error while signing */
1425 t = mutt_new_body ();
1426 t->type = TYPEMULTIPART;
1427 t->subtype = m_strdup("signed");
1428 t->encoding = ENC7BIT;
1430 t->disposition = DISPINLINE;
1432 mutt_generate_boundary (&t->parameter);
1433 /* check if this can be extracted from private key somehow.... */
1434 mutt_set_parameter ("micalg", "sha1", &t->parameter);
1435 mutt_set_parameter ("protocol", "application/x-pkcs7-signature",
1441 t->parts->next = mutt_new_body ();
1443 t->type = TYPEAPPLICATION;
1444 t->subtype = m_strdup("x-pkcs7-signature");
1445 t->filename = m_strdup(signedfile);
1446 t->d_filename = m_strdup("smime.p7s");
1448 t->disposition = DISPATTACH;
1449 t->encoding = ENCBASE64;
1450 t->unlink = 1; /* ok to remove this file after sending. */
1462 * Handling S/MIME - bodies.
1471 pid_t smime_invoke_verify (FILE ** smimein, FILE ** smimeout,
1472 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1473 int smimeerrfd, const char *fname,
1474 const char *sig_fname, int opaque)
1476 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1477 smimeerrfd, fname, sig_fname, NULL, NULL, NULL, NULL,
1478 (opaque ? SmimeVerifyOpaqueCommand :
1479 SmimeVerifyCommand));
1484 pid_t smime_invoke_decrypt (FILE ** smimein, FILE ** smimeout,
1485 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1486 int smimeerrfd, const char *fname)
1488 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1489 smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1490 SmimeCertToUse, NULL, SmimeDecryptCommand);
1495 int smime_verify_one (BODY * sigbdy, STATE * s, const char *tempfile)
1497 char signedfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1498 FILE *fp = NULL, *smimeout = NULL, *smimeerr = NULL;
1503 ssize_t tmplength = 0;
1504 int origType = sigbdy->type;
1505 char *savePrefix = NULL;
1508 snprintf (signedfile, sizeof (signedfile), "%s.sig", tempfile);
1510 /* decode to a tempfile, saving the original destination */
1512 if ((s->fpout = safe_fopen (signedfile, "w")) == NULL) {
1513 mutt_perror (signedfile);
1516 /* decoding the attachment changes the size and offset, so save a copy
1517 * of the "real" values now, and restore them after processing
1519 tmplength = sigbdy->length;
1520 tmpoffset = sigbdy->offset;
1522 /* if we are decoding binary bodies, we don't want to prefix each
1523 * line with the prefix or else the data will get corrupted.
1525 savePrefix = s->prefix;
1528 mutt_decode_attachment (sigbdy, s);
1530 sigbdy->length = ftello (s->fpout);
1534 /* restore final destination and substitute the tempfile for input */
1537 s->fpin = fopen (signedfile, "r");
1539 /* restore the prefix */
1540 s->prefix = savePrefix;
1542 sigbdy->type = origType;
1545 mutt_mktemp (smimeerrfile);
1546 if (!(smimeerr = safe_fopen (smimeerrfile, "w+"))) {
1547 mutt_perror (smimeerrfile);
1548 mutt_unlink (signedfile);
1552 crypt_current_time (s, "OpenSSL");
1554 if ((thepid = smime_invoke_verify (NULL, &smimeout, NULL,
1555 -1, -1, fileno (smimeerr),
1556 tempfile, signedfile, 0)) != -1) {
1560 if (mutt_wait_filter (thepid))
1570 line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1571 if (linelen && !m_strcasecmp(line, "verification successful"))
1580 mutt_copy_stream (smimeerr, s->fpout);
1583 state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1585 mutt_unlink (signedfile);
1586 mutt_unlink (smimeerrfile);
1588 sigbdy->length = tmplength;
1589 sigbdy->offset = tmpoffset;
1591 /* restore the original source stream */
1604 This handles application/pkcs7-mime which can either be a signed
1605 or an encrypted message.
1608 static BODY *smime_handle_entity (BODY * m, STATE * s, FILE * outFile)
1613 char buf[HUGE_STRING];
1614 char outfile[_POSIX_PATH_MAX], errfile[_POSIX_PATH_MAX];
1615 char tmpfname[_POSIX_PATH_MAX];
1616 char tmptmpfname[_POSIX_PATH_MAX];
1617 FILE *smimeout = NULL, *smimein = NULL, *smimeerr = NULL;
1618 FILE *tmpfp = NULL, *tmpfp_buffer = NULL, *fpout = NULL;
1622 unsigned int type = mutt_is_application_smime (m);
1624 if (!(type & APPLICATION_SMIME))
1627 mutt_mktemp (outfile);
1628 if ((smimeout = safe_fopen (outfile, "w+")) == NULL) {
1629 mutt_perror (outfile);
1633 mutt_mktemp (errfile);
1634 if ((smimeerr = safe_fopen (errfile, "w+")) == NULL) {
1635 mutt_perror (errfile);
1640 mutt_unlink (errfile);
1643 mutt_mktemp (tmpfname);
1644 if ((tmpfp = safe_fopen (tmpfname, "w+")) == NULL) {
1645 mutt_perror (tmpfname);
1653 fseeko (s->fpin, m->offset, 0);
1654 last_pos = m->offset;
1656 mutt_copy_bytes (s->fpin, tmpfp, m->length);
1661 if ((type & ENCRYPT) &&
1662 (thepid = smime_invoke_decrypt (&smimein, NULL, NULL, -1,
1663 fileno (smimeout), fileno (smimeerr),
1667 mutt_unlink (tmpfname);
1668 if (s->flags & M_DISPLAY)
1669 state_attach_puts (_("[-- Error: unable to create OpenSSL subprocess! --]\n"), s);
1672 else if ((type & SIGNOPAQUE) &&
1673 (thepid = smime_invoke_verify (&smimein, NULL, NULL, -1,
1675 fileno (smimeerr), NULL, tmpfname,
1676 SIGNOPAQUE)) == -1) {
1679 mutt_unlink (tmpfname);
1680 if (s->flags & M_DISPLAY)
1681 state_attach_puts (_("[-- Error: unable to create OpenSSL subprocess! --]\n"), s);
1686 if (type & ENCRYPT) {
1687 if (!smime_valid_passphrase ())
1688 smime_void_passphrase ();
1689 fputs (SmimePass, smimein);
1690 fputc ('\n', smimein);
1695 mutt_wait_filter (thepid);
1696 mutt_unlink (tmpfname);
1699 if (s->flags & M_DISPLAY) {
1702 if ((c = fgetc (smimeerr)) != EOF) {
1703 ungetc (c, smimeerr);
1705 crypt_current_time (s, "OpenSSL");
1706 mutt_copy_stream (smimeerr, s->fpout);
1707 state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1711 state_attach_puts (_("[-- The following data is S/MIME"
1712 " encrypted --]\n"), s);
1714 state_attach_puts (_("[-- The following data is S/MIME signed --]\n"),
1725 mutt_mktemp (tmptmpfname);
1726 if ((fpout = safe_fopen (tmptmpfname, "w+")) == NULL) {
1727 mutt_perror (tmptmpfname);
1733 while (fgets (buf, sizeof (buf) - 1, smimeout) != NULL) {
1734 len = m_strlen(buf);
1735 if (len > 1 && buf[len - 2] == '\r') {
1736 buf[len - 2] = '\n';
1737 buf[len - 1] = '\0';
1745 if ((p = mutt_read_mime_header (fpout, 0)) != NULL) {
1746 fstat (fileno (fpout), &info);
1747 p->length = info.st_size - p->offset;
1749 mutt_parse_part (fpout, p);
1752 tmpfp_buffer = s->fpin;
1754 mutt_body_handler (p, s);
1755 s->fpin = tmpfp_buffer;
1761 mutt_unlink (outfile);
1765 mutt_unlink (tmptmpfname);
1770 if (s->flags & M_DISPLAY) {
1772 state_attach_puts (_("\n[-- End of S/MIME encrypted data. --]\n"), s);
1774 state_attach_puts (_("\n[-- End of S/MIME signed data. --]\n"), s);
1777 if (type & SIGNOPAQUE) {
1784 line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1785 if (linelen && !m_strcasecmp(line, "verification successful"))
1790 m->goodsig = p->goodsig;
1791 m->badsig = p->badsig;
1802 int smime_decrypt_mime (FILE * fpin, FILE ** fpout, BODY * b, BODY ** cur)
1806 char tempfile[_POSIX_PATH_MAX];
1808 long tmpoffset = b->offset;
1809 ssize_t tmplength = b->length;
1810 int origType = b->type;
1814 if (!mutt_is_application_smime (b))
1822 fseeko (s.fpin, b->offset, 0);
1824 mutt_mktemp (tempfile);
1825 if ((tmpfp = safe_fopen (tempfile, "w+")) == NULL) {
1826 mutt_perror (tempfile);
1830 mutt_unlink (tempfile);
1832 mutt_decode_attachment (b, &s);
1834 b->length = ftello (s.fpout);
1840 mutt_mktemp (tempfile);
1841 if ((*fpout = safe_fopen (tempfile, "w+")) == NULL) {
1842 mutt_perror (tempfile);
1846 mutt_unlink (tempfile);
1848 if (!(*cur = smime_handle_entity (b, &s, *fpout))) {
1853 (*cur)->goodsig = b->goodsig;
1854 (*cur)->badsig = b->badsig;
1858 b->length = tmplength;
1859 b->offset = tmpoffset;
1861 safe_fclose (&tmpfp);
1868 int smime_application_smime_handler (BODY * m, STATE * s)
1870 return smime_handle_entity (m, s, NULL) ? 0 : -1;
1873 int smime_send_menu (HEADER * msg, int *redraw)
1877 switch (mutt_multi_choice
1878 (_("S/MIME (e)ncrypt, (s)ign, encrypt (w)ith, sign (a)s, (b)oth, or (c)lear? "),
1880 case 1: /* (e)ncrypt */
1881 msg->security |= ENCRYPT;
1882 msg->security &= ~SIGN;
1885 case 3: /* encrypt (w)ith */
1888 msg->security |= ENCRYPT;
1891 /* I use "dra" because "123" is recognized anyway */
1892 switch (mutt_multi_choice (_("Choose algorithm family:"
1893 " 1: DES, 2: RC2, 3: AES,"
1894 " or (c)lear? "), _("drac"))) {
1896 switch (choice = mutt_multi_choice (_("1: DES, 2: Triple-DES "),
1899 m_strreplace(&SmimeCryptAlg, "des");
1902 m_strreplace(&SmimeCryptAlg, "des3");
1908 switch (choice = mutt_multi_choice (_("1: RC2-40, 2: RC2-64, 3: RC2-128 "),
1911 m_strreplace(&SmimeCryptAlg, "rc2-40");
1914 m_strreplace(&SmimeCryptAlg, "rc2-64");
1917 m_strreplace(&SmimeCryptAlg, "rc2-128");
1923 switch (choice = mutt_multi_choice (_("1: AES128, 2: AES192, 3: AES256 "),
1926 m_strreplace(&SmimeCryptAlg, "aes128");
1929 m_strreplace(&SmimeCryptAlg, "aes192");
1932 m_strreplace(&SmimeCryptAlg, "aes256");
1937 case 4: /* (c)lear */
1938 p_delete(&SmimeCryptAlg);
1940 case -1: /* Ctrl-G or Enter */
1944 } while (choice == -1);
1948 case 2: /* (s)ign */
1950 if (!SmimeDefaultKey)
1951 mutt_message (_("Can't sign: No key specified. Use Sign As."));
1954 msg->security |= SIGN;
1955 msg->security &= ~ENCRYPT;
1959 case 4: /* sign (a)s */
1961 if ((p = smime_ask_for_key (_("Sign as: "), NULL, 0))) {
1962 m_strreplace(&SmimeDefaultKey, p);
1964 msg->security |= SIGN;
1966 /* probably need a different passphrase */
1967 crypt_smime_void_passphrase ();
1971 msg->security &= ~SIGN;
1974 *redraw = REDRAW_FULL;
1977 case 5: /* (b)oth */
1978 msg->security |= (ENCRYPT | SIGN);
1981 case 6: /* (f)orget it */
1982 case 7: /* (c)lear */
1987 if (msg->security && msg->security != APPLICATION_SMIME)
1988 msg->security |= APPLICATION_SMIME;
1992 return (msg->security);