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>
39 #include <lib-mime/mime.h>
41 #include <lib-ui/curses.h>
42 #include <lib-ui/enter.h>
43 #include <lib-ui/menu.h>
52 struct smime_command_context {
53 const char *key; /* %k */
54 const char *cryptalg; /* %a */
55 const char *fname; /* %f */
56 const char *sig_fname; /* %s */
57 const char *certificates; /* %c */
58 const char *intermediates; /* %i */
67 char trust; /* i=Invalid r=revoked e=expired u=unverified v=verified t=trusted */
68 short public; /* 1=public 0=private */
72 char SmimePass[STRING];
73 time_t SmimeExptime = 0; /* when does the cached passphrase expire? */
76 static char SmimeKeyToUse[_POSIX_PATH_MAX] = { 0 };
77 static char SmimeCertToUse[_POSIX_PATH_MAX];
78 static char SmimeIntermediateToUse[_POSIX_PATH_MAX];
82 * Create a format string to be used with scanf.
83 * To use it, write, for instance, MUTT_FORMAT(HUGE_STRING).
85 * See K&R 2nd ed, p. 231 for an explanation.
87 #define _MUTT_FORMAT_2(a,b) "%" a b
88 #define _MUTT_FORMAT_1(a, b) _MUTT_FORMAT_2(#a, b)
89 #define MUTT_FORMAT(a) _MUTT_FORMAT_1(a, "s")
93 * Queries and passphrase handling.
97 /* these are copies from pgp.c */
100 void smime_void_passphrase (void)
102 p_clear(SmimePass, countof(SmimePass));
106 int smime_valid_passphrase (void)
108 time_t now = time (NULL);
110 if (now < SmimeExptime)
111 /* Use cached copy. */
114 smime_void_passphrase ();
116 if (mutt_get_field_unbuffered (_("Enter S/MIME passphrase:"), SmimePass,
117 sizeof (SmimePass), M_PASS) == 0) {
118 SmimeExptime = time (NULL) + SmimeTimeout;
129 * The OpenSSL interface
132 /* This is almost identical to ppgp's invoking interface. */
135 _mutt_fmt_smime_command (char *dest, ssize_t destlen, char op,
136 const char *src, const char *prefix,
137 const char *ifstring, const char *elsestring,
138 unsigned long data, format_flag flags)
141 struct smime_command_context *cctx = (struct smime_command_context *) data;
142 int optional = (flags & M_FORMAT_OPTIONAL);
148 char path[_POSIX_PATH_MAX];
149 char buf1[LONG_STRING], buf2[LONG_STRING];
152 m_strcpy(path, sizeof(path), NONULL(SmimeCALocation));
153 mutt_expand_path (path, sizeof (path));
154 mutt_quote_filename (buf1, sizeof (buf1), path);
156 if (stat (path, &sb) != 0 || !S_ISDIR (sb.st_mode))
157 snprintf (buf2, sizeof (buf2), "-CAfile %s", buf1);
159 snprintf (buf2, sizeof (buf2), "-CApath %s", buf1);
161 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
162 snprintf (dest, destlen, fmt, buf2);
164 else if (!SmimeCALocation)
170 { /* certificate (list) */
172 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
173 snprintf (dest, destlen, fmt, NONULL (cctx->certificates));
175 else if (!cctx->certificates)
181 { /* intermediate certificates */
183 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
184 snprintf (dest, destlen, fmt, NONULL (cctx->intermediates));
186 else if (!cctx->intermediates)
192 { /* detached signature */
194 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
195 snprintf (dest, destlen, fmt, NONULL (cctx->sig_fname));
197 else if (!cctx->sig_fname)
205 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
206 snprintf (dest, destlen, fmt, NONULL (cctx->key));
214 { /* algorithm for encryption */
216 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
217 snprintf (dest, destlen, fmt, NONULL (cctx->cryptalg));
225 { /* file to process */
227 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
228 snprintf (dest, destlen, fmt, NONULL (cctx->fname));
230 else if (!cctx->fname)
241 mutt_FormatString (dest, destlen, ifstring, _mutt_fmt_smime_command,
243 else if (flags & M_FORMAT_OPTIONAL)
244 mutt_FormatString (dest, destlen, elsestring, _mutt_fmt_smime_command,
252 static void mutt_smime_command (char *d, ssize_t dlen,
253 struct smime_command_context *cctx,
256 mutt_FormatString (d, dlen, NONULL (fmt), _mutt_fmt_smime_command,
257 (unsigned long) cctx, 0);
260 static pid_t smime_invoke (FILE ** smimein, FILE ** smimeout,
261 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
262 int smimeerrfd, const char *fname,
263 const char *sig_fname, const char *cryptalg,
264 const char *key, const char *certificates,
265 const char *intermediates, const char *format)
267 struct smime_command_context cctx;
268 char cmd[HUGE_STRING];
272 if (!format || !*format)
276 cctx.sig_fname = sig_fname;
278 cctx.cryptalg = cryptalg;
279 cctx.certificates = certificates;
280 cctx.intermediates = intermediates;
282 mutt_smime_command (cmd, sizeof (cmd), &cctx, format);
284 return mutt_create_filter_fd (cmd, smimein, smimeout, smimeerr,
285 smimeinfd, smimeoutfd, smimeerrfd);
294 * Key and certificate handling.
300 Search the certificate index for given mailbox.
301 return certificate file name.
304 static void smime_entry (char *s, ssize_t l, MUTTMENU * menu, int num)
306 smime_id *Table = (smime_id *) menu->data;
307 smime_id this = Table[num];
308 const char *truststate;
310 switch (this.trust) {
312 truststate = N_("Trusted ");
315 truststate = N_("Verified ");
318 truststate = N_("Unverified");
321 truststate = N_("Expired ");
324 truststate = N_("Revoked ");
327 truststate = N_("Invalid ");
330 truststate = N_("Unknown ");
333 snprintf (s, l, " 0x%.8X.%i %s %-35.35s %s", this.hash, this.suffix,
334 truststate, this.email, this.nick);
336 snprintf (s, l, " 0x%.8X.%i %-35.35s %s", this.hash, this.suffix,
337 this.email, this.nick);
344 char *smime_ask_for_key (char *prompt, char *mailbox __attribute__((unused)),
349 long cert_num; /* Will contain the number of certificates.
350 * To be able to get it, the .index file will be read twice... */
351 char index_file[_POSIX_PATH_MAX];
353 char buf[LONG_STRING];
354 char fields[5][STRING];
355 int numFields, hash_suffix, done, cur; /* The current entry */
358 char helpstr[HUGE_STRING * 3];
363 prompt = _("Enter keyID: ");
364 snprintf (index_file, sizeof (index_file), "%s/.index",
365 public ? NONULL (SmimeCertificates) : NONULL (SmimeKeys));
367 idx = fopen (index_file, "r");
369 mutt_perror (index_file);
374 while (!feof (idx)) {
375 if (fgets (buf, sizeof (buf), idx))
382 if (mutt_get_field (prompt, qry, sizeof (qry), 0))
384 snprintf (title, sizeof (title),
385 _("S/MIME certificates matching \"%s\"."), qry);
388 idx = fopen (index_file, "r");
390 mutt_perror (index_file);
395 Table = p_new(smime_id, cert_num);
396 while (!feof (idx)) {
398 fscanf (idx, MUTT_FORMAT (STRING) " %x.%i " MUTT_FORMAT (STRING),
399 fields[0], &hash, &hash_suffix, fields[2]);
401 fscanf (idx, MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) "\n",
402 fields[3], fields[4]);
404 /* 0=email 1=name 2=nick 3=intermediate 4=trust */
408 /* Check if query matches this certificate */
409 if (!m_stristr(fields[0], qry) && !m_stristr(fields[2], qry))
412 Table[cur].hash = hash;
413 Table[cur].suffix = hash_suffix;
414 m_strcpy(Table[cur].email, sizeof(Table[cur].email), fields[0]);
415 m_strcpy(Table[cur].nick, sizeof(Table[cur].nick), fields[2]);
416 Table[cur].trust = *fields[4];
417 Table[cur].public = public;
423 /* Make Helpstring */
425 mutt_make_help (buf, sizeof (buf), _("Exit "), MENU_SMIME, OP_EXIT);
426 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
427 mutt_make_help (buf, sizeof (buf), _("Select "), MENU_SMIME,
428 OP_GENERIC_SELECT_ENTRY);
429 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
430 mutt_make_help (buf, sizeof (buf), _("Help"), MENU_SMIME, OP_HELP);
431 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
433 /* Create the menu */
434 menu = mutt_new_menu ();
436 menu->make_entry = smime_entry;
437 menu->menu = MENU_SMIME;
438 menu->help = helpstr;
441 /* sorting keys might be done later - TODO */
448 switch (mutt_menuLoop (menu)) {
449 case OP_GENERIC_SELECT_ENTRY:
461 fname = p_new(char, 13); /* Hash + '.' + Suffix + \0 */
462 sprintf (fname, "%.8x.%i", Table[cur].hash, Table[cur].suffix);
467 mutt_menuDestroy (&menu);
469 set_option (OPTNEEDREDRAW);
478 char *smime_get_field_from_db (char *mailbox, char *query, short public,
481 int addr_len, query_len, found = 0, ask = 0, choice = 0;
482 char cert_path[_POSIX_PATH_MAX];
483 char buf[LONG_STRING], prompt[STRING];
484 char fields[5][STRING];
488 char key_trust_level = 0;
491 if (!mailbox && !query)
494 addr_len = mailbox ? m_strlen(mailbox) : 0;
495 query_len = query ? m_strlen(query) : 0;
499 /* index-file format:
500 mailbox certfile label issuer_certfile trust_flags\n
502 certfile is a hash value generated by openssl.
503 Note that this was done according to the OpenSSL
504 specs on their CA-directory.
507 snprintf (cert_path, sizeof (cert_path), "%s/.index",
508 (public ? NONULL (SmimeCertificates) : NONULL (SmimeKeys)));
510 if (!stat (cert_path, &info)) {
511 if ((fp = safe_fopen (cert_path, "r")) == NULL) {
512 mutt_perror (cert_path);
516 while (fgets (buf, sizeof (buf) - 1, fp) != NULL)
517 if (mailbox && !(m_strncasecmp(mailbox, buf, addr_len))) {
518 numFields = sscanf (buf,
519 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
520 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
521 MUTT_FORMAT (STRING) "\n",
522 fields[0], fields[1],
523 fields[2], fields[3], fields[4]);
526 if (mailbox && public &&
528 *fields[4] == 'i' || *fields[4] == 'e' || *fields[4] == 'r'))
532 if (public && *fields[4] == 'u')
533 snprintf (prompt, sizeof (prompt),
535 ("ID %s is unverified. Do you want to use it for %s ?"),
537 else if (public && *fields[4] == 'v')
538 snprintf (prompt, sizeof (prompt),
539 _("Use (untrusted!) ID %s for %s ?"),
542 snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"),
546 if (may_ask && (choice = mutt_yesorno (prompt, M_NO)) == -1) {
552 else if (choice == M_NO) {
556 else if (choice == M_YES) {
557 m_strcpy(key, sizeof(key), fields[1]);
564 key_trust_level = *fields[4];
565 m_strcpy(key, sizeof(key), fields[1]);
570 numFields = sscanf (buf,
571 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
572 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
573 MUTT_FORMAT (STRING) "\n",
574 fields[0], fields[1],
575 fields[2], fields[3], fields[4]);
577 /* query = label: return certificate. */
578 if (numFields >= 3 &&
579 !(m_strncasecmp(query, fields[2], query_len))) {
581 m_strcpy(key, sizeof(key), fields[1]);
583 /* query = certificate: return intermediate certificate. */
584 else if (numFields >= 4 &&
585 !(m_strncasecmp(query, fields[1], query_len))) {
587 m_strcpy(key, sizeof(key), fields[3]);
594 if (public && *fields[4] == 'u')
595 snprintf (prompt, sizeof (prompt),
596 _("ID %s is unverified. Do you want to use it for %s ?"),
598 else if (public && *fields[4] == 'v')
599 snprintf (prompt, sizeof (prompt),
600 _("Use (untrusted!) ID %s for %s ?"), fields[1], mailbox);
602 snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"), key,
604 choice = mutt_yesorno (prompt, M_NO);
605 if (choice == -1 || choice == M_NO)
608 else if (key_trust_level && may_ask) {
609 if (key_trust_level == 'u') {
610 snprintf (prompt, sizeof (prompt),
611 _("ID %s is unverified. Do you want to use it for %s ?"),
613 choice = mutt_yesorno (prompt, M_NO);
617 else if (key_trust_level == 'v') {
619 ("Warning: You have not yet decided to trust ID %s. (any key to continue)"),
627 /* Note: m_strdup("") returns NULL. */
628 return m_strdup(key);
635 This sets the '*ToUse' variables for an upcoming decryption, where
636 the reuquired key is different from SmimeDefaultKey.
639 void _smime_getkeys (char *mailbox)
644 k = smime_get_field_from_db (mailbox, NULL, 0, 1);
647 snprintf (buf, sizeof (buf), _("Enter keyID for %s: "), mailbox);
648 k = smime_ask_for_key (buf, mailbox, 0);
652 /* the key used last time. */
653 if (*SmimeKeyToUse &&
654 !m_strcasecmp(k, SmimeKeyToUse + m_strlen(SmimeKeys) + 1)) {
659 smime_void_passphrase ();
661 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
662 NONULL (SmimeKeys), k);
664 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
665 NONULL (SmimeCertificates), k);
667 if (m_strcasecmp(k, SmimeDefaultKey))
668 smime_void_passphrase ();
674 if (*SmimeKeyToUse) {
675 if (!m_strcasecmp(SmimeDefaultKey,
676 SmimeKeyToUse + m_strlen(SmimeKeys) + 1))
679 smime_void_passphrase ();
682 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
683 NONULL (SmimeKeys), NONULL (SmimeDefaultKey));
685 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
686 NONULL (SmimeCertificates), NONULL (SmimeDefaultKey));
689 void smime_getkeys (ENVELOPE * env)
694 if (option (OPTSDEFAULTDECRYPTKEY) && SmimeDefaultKey && *SmimeDefaultKey) {
695 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
696 NONULL (SmimeKeys), SmimeDefaultKey);
698 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
699 NONULL (SmimeCertificates), SmimeDefaultKey);
704 for (t = env->to; !found && t; t = t->next)
705 if (mutt_addr_is_user (t)) {
707 _smime_getkeys (t->mailbox);
709 for (t = env->cc; !found && t; t = t->next)
710 if (mutt_addr_is_user (t)) {
712 _smime_getkeys (t->mailbox);
714 if (!found && (t = mutt_default_from ())) {
715 _smime_getkeys (t->mailbox);
716 address_list_wipe(&t);
720 /* This routine attempts to find the keyids of the recipients of a message.
721 * It returns NULL if any of the keys can not be found.
724 char *smime_findKeys (address_t * to, address_t * cc, address_t * bcc)
726 char *keyID, *keylist = NULL;
727 ssize_t keylist_size = 0;
728 ssize_t keylist_used = 0;
729 address_t *tmp = NULL, *addr = NULL;
730 address_t **last = &tmp;
734 const char *fqdn = mutt_fqdn (1);
736 for (i = 0; i < 3; i++) {
751 *last = address_list_dup (p);
753 last = &((*last)->next);
757 rfc822_qualify (tmp, fqdn);
759 tmp = mutt_remove_duplicates (tmp);
761 for (p = tmp; p; p = p->next) {
762 char buf[LONG_STRING];
766 if ((keyID = smime_get_field_from_db (q->mailbox, NULL, 1, 1)) == NULL) {
767 snprintf (buf, sizeof (buf), _("Enter keyID for %s: "), q->mailbox);
768 keyID = smime_ask_for_key (buf, q->mailbox, 1);
771 mutt_message (_("No (valid) certificate found for %s."), q->mailbox);
773 address_list_wipe(&tmp);
774 address_list_wipe(&addr);
778 keylist_size += m_strlen(keyID) + 2;
779 p_realloc(&keylist, keylist_size);
780 sprintf (keylist + keylist_used, "%s\n", keyID); /* __SPRINTF_CHECKED__ */
781 keylist_used = m_strlen(keylist);
783 address_list_wipe(&addr);
786 address_list_wipe(&tmp);
795 static int smime_handle_cert_email (char *certificate, char *mailbox,
796 int copy, char ***buffer, int *num)
798 FILE *fpout = NULL, *fperr = NULL;
799 char tmpfname[_POSIX_PATH_MAX];
801 int ret = -1, count = 0;
804 mutt_mktemp (tmpfname);
805 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
806 mutt_perror (tmpfname);
809 mutt_unlink (tmpfname);
811 mutt_mktemp (tmpfname);
812 if ((fpout = safe_fopen (tmpfname, "w+")) == NULL) {
814 mutt_perror (tmpfname);
817 mutt_unlink (tmpfname);
819 if ((thepid = smime_invoke (NULL, NULL, NULL,
820 -1, fileno (fpout), fileno (fperr),
821 certificate, NULL, NULL, NULL, NULL, NULL,
822 SmimeGetCertEmailCommand)) == -1) {
823 mutt_message (_("Error: unable to create OpenSSL subprocess!"));
829 mutt_wait_filter (thepid);
837 while ((fgets (email, sizeof (email), fpout))) {
838 *(email + m_strlen(email) - 1) = '\0';
839 if (m_strncasecmp(email, mailbox, m_strlen(mailbox)) == 0)
842 ret = ret < 0 ? 0 : ret;
848 mutt_copy_stream (fperr, stdout);
849 mutt_any_key_to_continue (_
850 ("Error: unable to create OpenSSL subprocess!"));
858 if (copy && buffer && num) {
860 *buffer = p_new(char *, count);
864 while ((fgets (email, sizeof (email), fpout))) {
865 *(email + m_strlen(email) - 1) = '\0';
866 (*buffer)[count] = p_dupstr(email, m_strlen(email));
881 static char *smime_extract_certificate (char *infile)
883 FILE *fpout = NULL, *fperr = NULL;
884 char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
885 char tmpfname[_POSIX_PATH_MAX];
890 mutt_mktemp (tmpfname);
891 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
892 mutt_perror (tmpfname);
895 mutt_unlink (tmpfname);
897 mutt_mktemp (pk7out);
898 if ((fpout = safe_fopen (pk7out, "w+")) == NULL) {
900 mutt_perror (pk7out);
904 /* Step 1: Convert the signature to a PKCS#7 structure, as we can't
905 extract the full set of certificates directly.
907 if ((thepid = smime_invoke (NULL, NULL, NULL,
908 -1, fileno (fpout), fileno (fperr),
909 infile, NULL, NULL, NULL, NULL, NULL,
910 SmimePk7outCommand)) == -1) {
911 mutt_any_key_to_continue (_
912 ("Error: unable to create OpenSSL subprocess!"));
915 mutt_unlink (pk7out);
919 mutt_wait_filter (thepid);
926 empty = (fgetc (fpout) == EOF);
928 mutt_perror (pk7out);
929 mutt_copy_stream (fperr, stdout);
932 mutt_unlink (pk7out);
939 mutt_mktemp (certfile);
940 if ((fpout = safe_fopen (certfile, "w+")) == NULL) {
942 mutt_unlink (pk7out);
943 mutt_perror (certfile);
947 /* Step 2: Extract the certificates from a PKCS#7 structure.
949 if ((thepid = smime_invoke (NULL, NULL, NULL,
950 -1, fileno (fpout), fileno (fperr),
951 pk7out, NULL, NULL, NULL, NULL, NULL,
952 SmimeGetCertCommand)) == -1) {
953 mutt_any_key_to_continue (_
954 ("Error: unable to create OpenSSL subprocess!"));
957 mutt_unlink (pk7out);
958 mutt_unlink (certfile);
962 mutt_wait_filter (thepid);
964 mutt_unlink (pk7out);
970 empty = (fgetc (fpout) == EOF);
972 mutt_copy_stream (fperr, stdout);
975 mutt_unlink (certfile);
982 return m_strdup(certfile);
985 static char *smime_extract_signer_certificate (char *infile)
987 FILE *fpout = NULL, *fperr = NULL;
988 char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
989 char tmpfname[_POSIX_PATH_MAX];
994 mutt_mktemp (tmpfname);
995 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
996 mutt_perror (tmpfname);
999 mutt_unlink (tmpfname);
1002 mutt_mktemp (certfile);
1003 if ((fpout = safe_fopen (certfile, "w+")) == NULL) {
1005 mutt_perror (certfile);
1009 /* Extract signer's certificate
1011 if ((thepid = smime_invoke (NULL, NULL, NULL,
1012 -1, -1, fileno (fperr),
1013 infile, NULL, NULL, NULL, certfile, NULL,
1014 SmimeGetSignerCertCommand)) == -1) {
1015 mutt_any_key_to_continue (_
1016 ("Error: unable to create OpenSSL subprocess!"));
1019 mutt_unlink (pk7out);
1020 mutt_unlink (certfile);
1024 mutt_wait_filter (thepid);
1030 empty = (fgetc (fpout) == EOF);
1033 mutt_copy_stream (fperr, stdout);
1034 mutt_any_key_to_continue (NULL);
1037 mutt_unlink (certfile);
1044 return m_strdup(certfile);
1050 /* Add a certificate and update index file (externally). */
1052 void smime_invoke_import (char *infile, char *mailbox __attribute__ ((unused)))
1054 char tmpfname[_POSIX_PATH_MAX], *certfile = NULL, buf[STRING];
1055 FILE *smimein = NULL, *fpout = NULL, *fperr = NULL;
1058 mutt_mktemp (tmpfname);
1059 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
1060 mutt_perror (tmpfname);
1063 mutt_unlink (tmpfname);
1065 mutt_mktemp (tmpfname);
1066 if ((fpout = safe_fopen (tmpfname, "w+")) == NULL) {
1068 mutt_perror (tmpfname);
1071 mutt_unlink (tmpfname);
1075 if (option (OPTASKCERTLABEL))
1076 mutt_get_field ("Label for certificate:", buf, sizeof (buf), 0);
1079 if ((certfile = smime_extract_certificate (infile))) {
1082 if ((thepid = smime_invoke (&smimein, NULL, NULL,
1083 -1, fileno (fpout), fileno (fperr),
1084 certfile, NULL, NULL, NULL, NULL, NULL,
1085 SmimeImportCertCommand)) == -1) {
1086 mutt_message (_("Error: unable to create OpenSSL subprocess!"));
1089 fputs (buf, smimein);
1090 fputc ('\n', smimein);
1093 mutt_wait_filter (thepid);
1095 mutt_unlink (certfile);
1096 p_delete(&certfile);
1104 mutt_copy_stream (fpout, stdout);
1105 mutt_copy_stream (fperr, stdout);
1114 int smime_verify_sender (HEADER * h)
1116 char *mbox = NULL, *certfile, tempfname[_POSIX_PATH_MAX];
1120 mutt_mktemp (tempfname);
1121 if (!(fpout = safe_fopen (tempfname, "w"))) {
1122 mutt_perror (tempfname);
1126 if (h->security & ENCRYPT)
1127 mutt_copy_message (fpout, Context, h,
1128 M_CM_DECODE_CRYPT & M_CM_DECODE_SMIME,
1129 CH_MIME | CH_WEED | CH_NONEWLINE);
1131 mutt_copy_message (fpout, Context, h, 0, 0);
1137 h->env->from = mutt_expand_aliases (h->env->from);
1138 mbox = h->env->from->mailbox;
1140 else if (h->env->sender) {
1141 h->env->sender = mutt_expand_aliases (h->env->sender);
1142 mbox = h->env->sender->mailbox;
1146 if ((certfile = smime_extract_signer_certificate (tempfname))) {
1147 mutt_unlink (tempfname);
1148 if (smime_handle_cert_email (certfile, mbox, 0, NULL, NULL)) {
1150 mutt_any_key_to_continue (NULL);
1154 mutt_unlink (certfile);
1155 p_delete(&certfile);
1158 mutt_any_key_to_continue (_("no certfile"));
1161 mutt_any_key_to_continue (_("no mbox"));
1163 mutt_unlink (tempfname);
1176 * Creating S/MIME - bodies.
1183 pid_t smime_invoke_encrypt (FILE ** smimein, FILE ** smimeout,
1184 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1185 int smimeerrfd, const char *fname,
1188 return smime_invoke (smimein, smimeout, smimeerr,
1189 smimeinfd, smimeoutfd, smimeerrfd,
1190 fname, NULL, SmimeCryptAlg, NULL, uids, NULL,
1191 SmimeEncryptCommand);
1196 pid_t smime_invoke_sign (FILE ** smimein, FILE ** smimeout, FILE ** smimeerr,
1197 int smimeinfd, int smimeoutfd, int smimeerrfd,
1200 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1201 smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1202 SmimeCertToUse, SmimeIntermediateToUse,
1209 BODY *smime_build_smime_entity (BODY * a, char *certlist)
1211 char buf[LONG_STRING], certfile[LONG_STRING];
1212 char tempfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1213 char smimeinfile[_POSIX_PATH_MAX];
1214 char *cert_start = certlist, *cert_end = certlist;
1215 FILE *smimein = NULL, *smimeerr = NULL, *fpout = NULL, *fptmp = NULL;
1220 mutt_mktemp (tempfile);
1221 if ((fpout = safe_fopen (tempfile, "w+")) == NULL) {
1222 mutt_perror (tempfile);
1226 mutt_mktemp (smimeerrfile);
1227 if ((smimeerr = safe_fopen (smimeerrfile, "w+")) == NULL) {
1228 mutt_perror (smimeerrfile);
1230 mutt_unlink (tempfile);
1233 mutt_unlink (smimeerrfile);
1235 mutt_mktemp (smimeinfile);
1236 if ((fptmp = safe_fopen (smimeinfile, "w+")) == NULL) {
1237 mutt_perror (smimeinfile);
1238 mutt_unlink (tempfile);
1246 int off = m_strlen(certfile);
1248 while (*++cert_end && *cert_end != '\n');
1252 snprintf (certfile + off, sizeof (certfile) - off, " %s/%s",
1253 NONULL (SmimeCertificates), cert_start);
1255 cert_start = cert_end;
1259 /* write a MIME entity */
1260 mutt_write_mime_header (a, fptmp);
1261 fputc ('\n', fptmp);
1262 mutt_write_mime_body (a, fptmp);
1266 smime_invoke_encrypt (&smimein, NULL, NULL, -1,
1267 fileno (fpout), fileno (smimeerr),
1268 smimeinfile, certfile)) == -1) {
1270 mutt_unlink (smimeinfile);
1271 mutt_unlink (certfile);
1277 mutt_wait_filter (thepid);
1278 mutt_unlink (smimeinfile);
1279 mutt_unlink (certfile);
1283 empty = (fgetc (fpout) == EOF);
1288 while (fgets (buf, sizeof (buf) - 1, smimeerr) != NULL) {
1290 fputs (buf, stdout);
1294 /* pause if there is any error output from SMIME */
1296 mutt_any_key_to_continue (NULL);
1299 /* fatal error while trying to encrypt message */
1301 mutt_any_key_to_continue _("No output from OpenSSL..");
1303 mutt_unlink (tempfile);
1307 t = mutt_new_body ();
1308 t->type = TYPEAPPLICATION;
1309 t->subtype = m_strdup("x-pkcs7-mime");
1310 mutt_set_parameter ("name", "smime.p7m", &t->parameter);
1311 mutt_set_parameter ("smime-type", "enveloped-data", &t->parameter);
1312 t->encoding = ENCBASE64; /* The output of OpenSSL SHOULD be binary */
1314 t->disposition = DISPATTACH;
1315 t->d_filename = m_strdup("smime.p7m");
1316 t->filename = m_strdup(tempfile);
1317 t->unlink = 1; /*delete after sending the message */
1327 BODY *smime_sign_message (BODY * a)
1330 char buffer[LONG_STRING];
1331 char signedfile[_POSIX_PATH_MAX], filetosign[_POSIX_PATH_MAX];
1332 FILE *smimein = NULL, *smimeout = NULL, *smimeerr = NULL, *sfp = NULL;
1336 char *intermediates = smime_get_field_from_db (NULL, SmimeDefaultKey, 1, 1);
1338 if (!intermediates) {
1339 mutt_message (_("Warning: Intermediate certificate not found."));
1340 intermediates = SmimeDefaultKey; /* so openssl won't complain in any case */
1343 convert_to_7bit (a); /* Signed data _must_ be in 7-bit format. */
1345 mutt_mktemp (filetosign);
1346 if ((sfp = safe_fopen (filetosign, "w+")) == NULL) {
1347 mutt_perror (filetosign);
1351 mutt_mktemp (signedfile);
1352 if ((smimeout = safe_fopen (signedfile, "w+")) == NULL) {
1353 mutt_perror (signedfile);
1355 mutt_unlink (filetosign);
1359 mutt_write_mime_header (a, sfp);
1361 mutt_write_mime_body (a, sfp);
1366 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
1367 NONULL (SmimeKeys), SmimeDefaultKey);
1369 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
1370 NONULL (SmimeCertificates), SmimeDefaultKey);
1372 snprintf (SmimeIntermediateToUse, sizeof (SmimeIntermediateToUse), "%s/%s",
1373 NONULL (SmimeCertificates), intermediates);
1377 if ((thepid = smime_invoke_sign (&smimein, NULL, &smimeerr,
1378 -1, fileno (smimeout), -1,
1379 filetosign)) == -1) {
1380 mutt_perror (_("Can't open OpenSSL subprocess!"));
1383 mutt_unlink (signedfile);
1384 mutt_unlink (filetosign);
1387 fputs (SmimePass, smimein);
1388 fputc ('\n', smimein);
1392 mutt_wait_filter (thepid);
1394 /* check for errors from OpenSSL */
1398 while (fgets (buffer, sizeof (buffer) - 1, smimeerr) != NULL) {
1400 fputs (buffer, stdout);
1407 empty = (fgetc (smimeout) == EOF);
1410 mutt_unlink (filetosign);
1414 mutt_any_key_to_continue (NULL);
1417 mutt_any_key_to_continue _("No output from OpenSSL...");
1419 mutt_unlink (signedfile);
1420 return (NULL); /* fatal error while signing */
1423 t = mutt_new_body ();
1424 t->type = TYPEMULTIPART;
1425 t->subtype = m_strdup("signed");
1426 t->encoding = ENC7BIT;
1428 t->disposition = DISPINLINE;
1430 mutt_generate_boundary (&t->parameter);
1431 /* check if this can be extracted from private key somehow.... */
1432 mutt_set_parameter ("micalg", "sha1", &t->parameter);
1433 mutt_set_parameter ("protocol", "application/x-pkcs7-signature",
1439 t->parts->next = mutt_new_body ();
1441 t->type = TYPEAPPLICATION;
1442 t->subtype = m_strdup("x-pkcs7-signature");
1443 t->filename = m_strdup(signedfile);
1444 t->d_filename = m_strdup("smime.p7s");
1446 t->disposition = DISPATTACH;
1447 t->encoding = ENCBASE64;
1448 t->unlink = 1; /* ok to remove this file after sending. */
1460 * Handling S/MIME - bodies.
1469 pid_t smime_invoke_verify (FILE ** smimein, FILE ** smimeout,
1470 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1471 int smimeerrfd, const char *fname,
1472 const char *sig_fname, int opaque)
1474 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1475 smimeerrfd, fname, sig_fname, NULL, NULL, NULL, NULL,
1476 (opaque ? SmimeVerifyOpaqueCommand :
1477 SmimeVerifyCommand));
1482 pid_t smime_invoke_decrypt (FILE ** smimein, FILE ** smimeout,
1483 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1484 int smimeerrfd, const char *fname)
1486 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1487 smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1488 SmimeCertToUse, NULL, SmimeDecryptCommand);
1493 int smime_verify_one (BODY * sigbdy, STATE * s, const char *tempfile)
1495 char signedfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1496 FILE *fp = NULL, *smimeout = NULL, *smimeerr = NULL;
1501 ssize_t tmplength = 0;
1502 int origType = sigbdy->type;
1503 char *savePrefix = NULL;
1506 snprintf (signedfile, sizeof (signedfile), "%s.sig", tempfile);
1508 /* decode to a tempfile, saving the original destination */
1510 if ((s->fpout = safe_fopen (signedfile, "w")) == NULL) {
1511 mutt_perror (signedfile);
1514 /* decoding the attachment changes the size and offset, so save a copy
1515 * of the "real" values now, and restore them after processing
1517 tmplength = sigbdy->length;
1518 tmpoffset = sigbdy->offset;
1520 /* if we are decoding binary bodies, we don't want to prefix each
1521 * line with the prefix or else the data will get corrupted.
1523 savePrefix = s->prefix;
1526 mutt_decode_attachment (sigbdy, s);
1528 sigbdy->length = ftello (s->fpout);
1532 /* restore final destination and substitute the tempfile for input */
1535 s->fpin = fopen (signedfile, "r");
1537 /* restore the prefix */
1538 s->prefix = savePrefix;
1540 sigbdy->type = origType;
1543 mutt_mktemp (smimeerrfile);
1544 if (!(smimeerr = safe_fopen (smimeerrfile, "w+"))) {
1545 mutt_perror (smimeerrfile);
1546 mutt_unlink (signedfile);
1550 crypt_current_time (s, "OpenSSL");
1552 if ((thepid = smime_invoke_verify (NULL, &smimeout, NULL,
1553 -1, -1, fileno (smimeerr),
1554 tempfile, signedfile, 0)) != -1) {
1558 if (mutt_wait_filter (thepid))
1568 line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1569 if (linelen && !m_strcasecmp(line, "verification successful"))
1578 mutt_copy_stream (smimeerr, s->fpout);
1581 state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1583 mutt_unlink (signedfile);
1584 mutt_unlink (smimeerrfile);
1586 sigbdy->length = tmplength;
1587 sigbdy->offset = tmpoffset;
1589 /* restore the original source stream */
1602 This handles application/pkcs7-mime which can either be a signed
1603 or an encrypted message.
1606 static BODY *smime_handle_entity (BODY * m, STATE * s, FILE * outFile)
1611 char buf[HUGE_STRING];
1612 char outfile[_POSIX_PATH_MAX], errfile[_POSIX_PATH_MAX];
1613 char tmpfname[_POSIX_PATH_MAX];
1614 char tmptmpfname[_POSIX_PATH_MAX];
1615 FILE *smimeout = NULL, *smimein = NULL, *smimeerr = NULL;
1616 FILE *tmpfp = NULL, *tmpfp_buffer = NULL, *fpout = NULL;
1620 unsigned int type = mutt_is_application_smime (m);
1622 if (!(type & APPLICATION_SMIME))
1625 mutt_mktemp (outfile);
1626 if ((smimeout = safe_fopen (outfile, "w+")) == NULL) {
1627 mutt_perror (outfile);
1631 mutt_mktemp (errfile);
1632 if ((smimeerr = safe_fopen (errfile, "w+")) == NULL) {
1633 mutt_perror (errfile);
1638 mutt_unlink (errfile);
1641 mutt_mktemp (tmpfname);
1642 if ((tmpfp = safe_fopen (tmpfname, "w+")) == NULL) {
1643 mutt_perror (tmpfname);
1651 fseeko (s->fpin, m->offset, 0);
1652 last_pos = m->offset;
1654 mutt_copy_bytes (s->fpin, tmpfp, m->length);
1659 if ((type & ENCRYPT) &&
1660 (thepid = smime_invoke_decrypt (&smimein, NULL, NULL, -1,
1661 fileno (smimeout), fileno (smimeerr),
1665 mutt_unlink (tmpfname);
1666 if (s->flags & M_DISPLAY)
1667 state_attach_puts (_("[-- Error: unable to create OpenSSL subprocess! --]\n"), s);
1670 else if ((type & SIGNOPAQUE) &&
1671 (thepid = smime_invoke_verify (&smimein, NULL, NULL, -1,
1673 fileno (smimeerr), NULL, tmpfname,
1674 SIGNOPAQUE)) == -1) {
1677 mutt_unlink (tmpfname);
1678 if (s->flags & M_DISPLAY)
1679 state_attach_puts (_("[-- Error: unable to create OpenSSL subprocess! --]\n"), s);
1684 if (type & ENCRYPT) {
1685 if (!smime_valid_passphrase ())
1686 smime_void_passphrase ();
1687 fputs (SmimePass, smimein);
1688 fputc ('\n', smimein);
1693 mutt_wait_filter (thepid);
1694 mutt_unlink (tmpfname);
1697 if (s->flags & M_DISPLAY) {
1700 if ((c = fgetc (smimeerr)) != EOF) {
1701 ungetc (c, smimeerr);
1703 crypt_current_time (s, "OpenSSL");
1704 mutt_copy_stream (smimeerr, s->fpout);
1705 state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1709 state_attach_puts (_("[-- The following data is S/MIME"
1710 " encrypted --]\n"), s);
1712 state_attach_puts (_("[-- The following data is S/MIME signed --]\n"),
1723 mutt_mktemp (tmptmpfname);
1724 if ((fpout = safe_fopen (tmptmpfname, "w+")) == NULL) {
1725 mutt_perror (tmptmpfname);
1731 while (fgets (buf, sizeof (buf) - 1, smimeout) != NULL) {
1732 len = m_strlen(buf);
1733 if (len > 1 && buf[len - 2] == '\r') {
1734 buf[len - 2] = '\n';
1735 buf[len - 1] = '\0';
1743 if ((p = mutt_read_mime_header (fpout, 0)) != NULL) {
1744 fstat (fileno (fpout), &info);
1745 p->length = info.st_size - p->offset;
1747 mutt_parse_part (fpout, p);
1750 tmpfp_buffer = s->fpin;
1752 mutt_body_handler (p, s);
1753 s->fpin = tmpfp_buffer;
1759 mutt_unlink (outfile);
1763 mutt_unlink (tmptmpfname);
1768 if (s->flags & M_DISPLAY) {
1770 state_attach_puts (_("\n[-- End of S/MIME encrypted data. --]\n"), s);
1772 state_attach_puts (_("\n[-- End of S/MIME signed data. --]\n"), s);
1775 if (type & SIGNOPAQUE) {
1782 line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1783 if (linelen && !m_strcasecmp(line, "verification successful"))
1788 m->goodsig = p->goodsig;
1789 m->badsig = p->badsig;
1800 int smime_decrypt_mime (FILE * fpin, FILE ** fpout, BODY * b, BODY ** cur)
1804 char tempfile[_POSIX_PATH_MAX];
1806 long tmpoffset = b->offset;
1807 ssize_t tmplength = b->length;
1808 int origType = b->type;
1812 if (!mutt_is_application_smime (b))
1820 fseeko (s.fpin, b->offset, 0);
1822 mutt_mktemp (tempfile);
1823 if ((tmpfp = safe_fopen (tempfile, "w+")) == NULL) {
1824 mutt_perror (tempfile);
1828 mutt_unlink (tempfile);
1830 mutt_decode_attachment (b, &s);
1832 b->length = ftello (s.fpout);
1838 mutt_mktemp (tempfile);
1839 if ((*fpout = safe_fopen (tempfile, "w+")) == NULL) {
1840 mutt_perror (tempfile);
1844 mutt_unlink (tempfile);
1846 if (!(*cur = smime_handle_entity (b, &s, *fpout))) {
1851 (*cur)->goodsig = b->goodsig;
1852 (*cur)->badsig = b->badsig;
1856 b->length = tmplength;
1857 b->offset = tmpoffset;
1859 safe_fclose (&tmpfp);
1866 int smime_application_smime_handler (BODY * m, STATE * s)
1868 return smime_handle_entity (m, s, NULL) ? 0 : -1;
1871 int smime_send_menu (HEADER * msg, int *redraw)
1875 switch (mutt_multi_choice
1876 (_("S/MIME (e)ncrypt, (s)ign, encrypt (w)ith, sign (a)s, (b)oth, or (c)lear? "),
1878 case 1: /* (e)ncrypt */
1879 msg->security |= ENCRYPT;
1880 msg->security &= ~SIGN;
1883 case 3: /* encrypt (w)ith */
1886 msg->security |= ENCRYPT;
1889 /* I use "dra" because "123" is recognized anyway */
1890 switch (mutt_multi_choice (_("Choose algorithm family:"
1891 " 1: DES, 2: RC2, 3: AES,"
1892 " or (c)lear? "), _("drac"))) {
1894 switch (choice = mutt_multi_choice (_("1: DES, 2: Triple-DES "),
1897 m_strreplace(&SmimeCryptAlg, "des");
1900 m_strreplace(&SmimeCryptAlg, "des3");
1906 switch (choice = mutt_multi_choice (_("1: RC2-40, 2: RC2-64, 3: RC2-128 "),
1909 m_strreplace(&SmimeCryptAlg, "rc2-40");
1912 m_strreplace(&SmimeCryptAlg, "rc2-64");
1915 m_strreplace(&SmimeCryptAlg, "rc2-128");
1921 switch (choice = mutt_multi_choice (_("1: AES128, 2: AES192, 3: AES256 "),
1924 m_strreplace(&SmimeCryptAlg, "aes128");
1927 m_strreplace(&SmimeCryptAlg, "aes192");
1930 m_strreplace(&SmimeCryptAlg, "aes256");
1935 case 4: /* (c)lear */
1936 p_delete(&SmimeCryptAlg);
1938 case -1: /* Ctrl-G or Enter */
1942 } while (choice == -1);
1946 case 2: /* (s)ign */
1948 if (!SmimeDefaultKey)
1949 mutt_message (_("Can't sign: No key specified. Use Sign As."));
1952 msg->security |= SIGN;
1953 msg->security &= ~ENCRYPT;
1957 case 4: /* sign (a)s */
1959 if ((p = smime_ask_for_key (_("Sign as: "), NULL, 0))) {
1960 m_strreplace(&SmimeDefaultKey, p);
1962 msg->security |= SIGN;
1964 /* probably need a different passphrase */
1965 crypt_smime_void_passphrase ();
1969 msg->security &= ~SIGN;
1972 *redraw = REDRAW_FULL;
1975 case 5: /* (b)oth */
1976 msg->security |= (ENCRYPT | SIGN);
1979 case 6: /* (f)orget it */
1980 case 7: /* (c)lear */
1985 if (msg->security && msg->security != APPLICATION_SMIME)
1986 msg->security |= APPLICATION_SMIME;
1990 return (msg->security);