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.
12 #include <lib-lib/lib-lib.h>
14 #ifdef HAVE_SYS_RESOURCE_H
15 # include <sys/resource.h>
18 #include <lib-mime/mime.h>
19 #include <lib-sys/unix.h>
21 #include <lib-ui/curses.h>
22 #include <lib-ui/enter.h>
23 #include <lib-ui/menu.h>
33 struct smime_command_context {
34 const char *key; /* %k */
35 const char *cryptalg; /* %a */
36 const char *fname; /* %f */
37 const char *sig_fname; /* %s */
38 const char *certificates; /* %c */
39 const char *intermediates; /* %i */
48 char trust; /* i=Invalid r=revoked e=expired u=unverified v=verified t=trusted */
49 short public; /* 1=public 0=private */
53 char SmimePass[STRING];
54 time_t SmimeExptime = 0; /* when does the cached passphrase expire? */
57 static char SmimeKeyToUse[_POSIX_PATH_MAX] = { 0 };
58 static char SmimeCertToUse[_POSIX_PATH_MAX];
59 static char SmimeIntermediateToUse[_POSIX_PATH_MAX];
63 * Create a format string to be used with scanf.
64 * To use it, write, for instance, MUTT_FORMAT(HUGE_STRING).
66 * See K&R 2nd ed, p. 231 for an explanation.
68 #define _MUTT_FORMAT_2(a,b) "%" a b
69 #define _MUTT_FORMAT_1(a, b) _MUTT_FORMAT_2(#a, b)
70 #define MUTT_FORMAT(a) _MUTT_FORMAT_1(a, "s")
74 * Queries and passphrase handling.
78 /* these are copies from pgp.c */
81 void smime_void_passphrase (void)
83 p_clear(SmimePass, countof(SmimePass));
87 int smime_valid_passphrase (void)
89 time_t now = time (NULL);
91 if (now < SmimeExptime)
92 /* Use cached copy. */
95 smime_void_passphrase ();
97 if (mutt_get_field_unbuffered (_("Enter S/MIME passphrase:"), SmimePass,
98 sizeof (SmimePass), M_PASS) == 0) {
99 SmimeExptime = time (NULL) + SmimeTimeout;
110 * The OpenSSL interface
113 /* This is almost identical to ppgp's invoking interface. */
116 _mutt_fmt_smime_command (char *dest, ssize_t destlen, char op,
117 const char *src, const char *prefix,
118 const char *ifstring, const char *elsestring,
119 unsigned long data, format_flag flags)
122 struct smime_command_context *cctx = (struct smime_command_context *) data;
123 int optional = (flags & M_FORMAT_OPTIONAL);
129 char path[_POSIX_PATH_MAX];
130 char buf1[LONG_STRING], buf2[LONG_STRING];
133 m_strcpy(path, sizeof(path), NONULL(SmimeCALocation));
134 mutt_expand_path (path, sizeof (path));
135 mutt_quote_filename (buf1, sizeof (buf1), path);
137 if (stat (path, &sb) != 0 || !S_ISDIR (sb.st_mode))
138 snprintf (buf2, sizeof (buf2), "-CAfile %s", buf1);
140 snprintf (buf2, sizeof (buf2), "-CApath %s", buf1);
142 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
143 snprintf (dest, destlen, fmt, buf2);
145 else if (!SmimeCALocation)
151 { /* certificate (list) */
153 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
154 snprintf (dest, destlen, fmt, NONULL (cctx->certificates));
156 else if (!cctx->certificates)
162 { /* intermediate certificates */
164 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
165 snprintf (dest, destlen, fmt, NONULL (cctx->intermediates));
167 else if (!cctx->intermediates)
173 { /* detached signature */
175 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
176 snprintf (dest, destlen, fmt, NONULL (cctx->sig_fname));
178 else if (!cctx->sig_fname)
186 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
187 snprintf (dest, destlen, fmt, NONULL (cctx->key));
195 { /* algorithm for encryption */
197 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
198 snprintf (dest, destlen, fmt, NONULL (cctx->cryptalg));
206 { /* file to process */
208 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
209 snprintf (dest, destlen, fmt, NONULL (cctx->fname));
211 else if (!cctx->fname)
222 m_strformat(dest, destlen, ifstring, _mutt_fmt_smime_command, data, 0);
223 else if (flags & M_FORMAT_OPTIONAL)
224 m_strformat(dest, destlen, elsestring, _mutt_fmt_smime_command, data, 0);
231 static void mutt_smime_command (char *d, ssize_t dlen,
232 struct smime_command_context *cctx,
235 m_strformat(d, dlen, NONULL (fmt), _mutt_fmt_smime_command,
236 (unsigned long)cctx, 0);
239 static pid_t smime_invoke (FILE ** smimein, FILE ** smimeout,
240 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
241 int smimeerrfd, const char *fname,
242 const char *sig_fname, const char *cryptalg,
243 const char *key, const char *certificates,
244 const char *intermediates, const char *format)
246 struct smime_command_context cctx;
247 char cmd[HUGE_STRING];
251 if (!format || !*format)
255 cctx.sig_fname = sig_fname;
257 cctx.cryptalg = cryptalg;
258 cctx.certificates = certificates;
259 cctx.intermediates = intermediates;
261 mutt_smime_command (cmd, sizeof (cmd), &cctx, format);
263 return mutt_create_filter_fd (cmd, smimein, smimeout, smimeerr,
264 smimeinfd, smimeoutfd, smimeerrfd);
273 * Key and certificate handling.
279 Search the certificate index for given mailbox.
280 return certificate file name.
283 static void smime_entry (char *s, ssize_t l, MUTTMENU * menu, int num)
285 smime_id *Table = (smime_id *) menu->data;
286 smime_id this = Table[num];
287 const char *truststate;
289 switch (this.trust) {
291 truststate = N_("Trusted ");
294 truststate = N_("Verified ");
297 truststate = N_("Unverified");
300 truststate = N_("Expired ");
303 truststate = N_("Revoked ");
306 truststate = N_("Invalid ");
309 truststate = N_("Unknown ");
312 snprintf (s, l, " 0x%.8X.%i %s %-35.35s %s", this.hash, this.suffix,
313 truststate, this.email, this.nick);
315 snprintf (s, l, " 0x%.8X.%i %-35.35s %s", this.hash, this.suffix,
316 this.email, this.nick);
323 char *smime_ask_for_key (char *prompt, char *mailbox __attribute__((unused)),
328 long cert_num; /* Will contain the number of certificates.
329 * To be able to get it, the .index file will be read twice... */
330 char index_file[_POSIX_PATH_MAX];
332 char buf[LONG_STRING];
333 char fields[5][STRING];
334 int numFields, hash_suffix, done, cur; /* The current entry */
337 char helpstr[HUGE_STRING * 3];
342 prompt = _("Enter keyID: ");
343 snprintf (index_file, sizeof (index_file), "%s/.index",
344 public ? NONULL (SmimeCertificates) : NONULL (SmimeKeys));
346 idx = fopen (index_file, "r");
348 mutt_perror (index_file);
353 while (!feof (idx)) {
354 if (fgets (buf, sizeof (buf), idx))
361 if (mutt_get_field (prompt, qry, sizeof (qry), 0))
363 snprintf (title, sizeof (title),
364 _("S/MIME certificates matching \"%s\"."), qry);
367 idx = fopen (index_file, "r");
369 mutt_perror (index_file);
374 Table = p_new(smime_id, cert_num);
375 while (!feof (idx)) {
377 fscanf (idx, MUTT_FORMAT (STRING) " %x.%i " MUTT_FORMAT (STRING),
378 fields[0], &hash, &hash_suffix, fields[2]);
380 fscanf (idx, MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) "\n",
381 fields[3], fields[4]);
383 /* 0=email 1=name 2=nick 3=intermediate 4=trust */
387 /* Check if query matches this certificate */
388 if (!m_stristr(fields[0], qry) && !m_stristr(fields[2], qry))
391 Table[cur].hash = hash;
392 Table[cur].suffix = hash_suffix;
393 m_strcpy(Table[cur].email, sizeof(Table[cur].email), fields[0]);
394 m_strcpy(Table[cur].nick, sizeof(Table[cur].nick), fields[2]);
395 Table[cur].trust = *fields[4];
396 Table[cur].public = public;
402 /* Make Helpstring */
404 mutt_make_help (buf, sizeof (buf), _("Exit "), MENU_SMIME, OP_EXIT);
405 m_strcat(helpstr, sizeof(helpstr), buf);
406 mutt_make_help (buf, sizeof (buf), _("Select "), MENU_SMIME,
407 OP_GENERIC_SELECT_ENTRY);
408 m_strcat(helpstr, sizeof(helpstr), buf);
409 mutt_make_help (buf, sizeof (buf), _("Help"), MENU_SMIME, OP_HELP);
410 m_strcat(helpstr, sizeof(helpstr), buf);
412 /* Create the menu */
413 menu = mutt_new_menu ();
415 menu->make_entry = smime_entry;
416 menu->menu = MENU_SMIME;
417 menu->help = helpstr;
420 /* sorting keys might be done later - TODO */
427 switch (mutt_menuLoop (menu)) {
428 case OP_GENERIC_SELECT_ENTRY:
440 fname = p_new(char, 13); /* Hash + '.' + Suffix + \0 */
441 sprintf (fname, "%.8x.%i", Table[cur].hash, Table[cur].suffix);
446 mutt_menuDestroy (&menu);
448 set_option (OPTNEEDREDRAW);
457 char *smime_get_field_from_db (char *mailbox, char *query, short public,
460 int addr_len, query_len, found = 0, ask = 0, choice = 0;
461 char cert_path[_POSIX_PATH_MAX];
462 char buf[LONG_STRING], prompt[STRING];
463 char fields[5][STRING];
467 char key_trust_level = 0;
470 if (!mailbox && !query)
473 addr_len = mailbox ? m_strlen(mailbox) : 0;
474 query_len = query ? m_strlen(query) : 0;
478 /* index-file format:
479 mailbox certfile label issuer_certfile trust_flags\n
481 certfile is a hash value generated by openssl.
482 Note that this was done according to the OpenSSL
483 specs on their CA-directory.
486 snprintf (cert_path, sizeof (cert_path), "%s/.index",
487 (public ? NONULL (SmimeCertificates) : NONULL (SmimeKeys)));
489 if (!stat (cert_path, &info)) {
490 if ((fp = safe_fopen (cert_path, "r")) == NULL) {
491 mutt_perror (cert_path);
495 while (fgets (buf, sizeof (buf) - 1, fp) != NULL)
496 if (mailbox && !(m_strncasecmp(mailbox, buf, addr_len))) {
497 numFields = sscanf (buf,
498 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
499 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
500 MUTT_FORMAT (STRING) "\n",
501 fields[0], fields[1],
502 fields[2], fields[3], fields[4]);
505 if (mailbox && public &&
507 *fields[4] == 'i' || *fields[4] == 'e' || *fields[4] == 'r'))
511 if (public && *fields[4] == 'u')
512 snprintf (prompt, sizeof (prompt),
514 ("ID %s is unverified. Do you want to use it for %s ?"),
516 else if (public && *fields[4] == 'v')
517 snprintf (prompt, sizeof (prompt),
518 _("Use (untrusted!) ID %s for %s ?"),
521 snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"),
525 if (may_ask && (choice = mutt_yesorno (prompt, M_NO)) == -1) {
531 else if (choice == M_NO) {
535 else if (choice == M_YES) {
536 m_strcpy(key, sizeof(key), fields[1]);
543 key_trust_level = *fields[4];
544 m_strcpy(key, sizeof(key), fields[1]);
549 numFields = sscanf (buf,
550 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
551 MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
552 MUTT_FORMAT (STRING) "\n",
553 fields[0], fields[1],
554 fields[2], fields[3], fields[4]);
556 /* query = label: return certificate. */
557 if (numFields >= 3 &&
558 !(m_strncasecmp(query, fields[2], query_len))) {
560 m_strcpy(key, sizeof(key), fields[1]);
562 /* query = certificate: return intermediate certificate. */
563 else if (numFields >= 4 &&
564 !(m_strncasecmp(query, fields[1], query_len))) {
566 m_strcpy(key, sizeof(key), fields[3]);
573 if (public && *fields[4] == 'u')
574 snprintf (prompt, sizeof (prompt),
575 _("ID %s is unverified. Do you want to use it for %s ?"),
577 else if (public && *fields[4] == 'v')
578 snprintf (prompt, sizeof (prompt),
579 _("Use (untrusted!) ID %s for %s ?"), fields[1], mailbox);
581 snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"), key,
583 choice = mutt_yesorno (prompt, M_NO);
584 if (choice == -1 || choice == M_NO)
587 else if (key_trust_level && may_ask) {
588 if (key_trust_level == 'u') {
589 snprintf (prompt, sizeof (prompt),
590 _("ID %s is unverified. Do you want to use it for %s ?"),
592 choice = mutt_yesorno (prompt, M_NO);
596 else if (key_trust_level == 'v') {
598 ("Warning: You have not yet decided to trust ID %s. (any key to continue)"),
606 /* Note: m_strdup("") returns NULL. */
607 return m_strdup(key);
611 This sets the '*ToUse' variables for an upcoming decryption, where
612 the reuquired key is different from SmimeDefaultKey.
614 static void _smime_getkeys (char *mailbox)
619 k = smime_get_field_from_db (mailbox, NULL, 0, 1);
622 snprintf (buf, sizeof (buf), _("Enter keyID for %s: "), mailbox);
623 k = smime_ask_for_key (buf, mailbox, 0);
627 /* the key used last time. */
628 if (*SmimeKeyToUse &&
629 !m_strcasecmp(k, SmimeKeyToUse + m_strlen(SmimeKeys) + 1)) {
634 smime_void_passphrase ();
636 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
637 NONULL (SmimeKeys), k);
639 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
640 NONULL (SmimeCertificates), k);
642 if (m_strcasecmp(k, SmimeDefaultKey))
643 smime_void_passphrase ();
649 if (*SmimeKeyToUse) {
650 if (!m_strcasecmp(SmimeDefaultKey,
651 SmimeKeyToUse + m_strlen(SmimeKeys) + 1))
654 smime_void_passphrase ();
657 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
658 NONULL (SmimeKeys), NONULL (SmimeDefaultKey));
660 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
661 NONULL (SmimeCertificates), NONULL (SmimeDefaultKey));
664 void smime_getkeys (ENVELOPE * env)
669 if (option (OPTSDEFAULTDECRYPTKEY) && SmimeDefaultKey && *SmimeDefaultKey) {
670 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
671 NONULL (SmimeKeys), SmimeDefaultKey);
673 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
674 NONULL (SmimeCertificates), SmimeDefaultKey);
679 for (t = env->to; !found && t; t = t->next)
680 if (mutt_addr_is_user (t)) {
682 _smime_getkeys (t->mailbox);
684 for (t = env->cc; !found && t; t = t->next)
685 if (mutt_addr_is_user (t)) {
687 _smime_getkeys (t->mailbox);
689 if (!found && (t = mutt_default_from ())) {
690 _smime_getkeys (t->mailbox);
691 address_list_wipe(&t);
695 /* This routine attempts to find the keyids of the recipients of a message.
696 * It returns NULL if any of the keys can not be found.
699 char *smime_findKeys (address_t * to, address_t * cc, address_t * bcc)
701 char *keyID, *keylist = NULL;
702 ssize_t keylist_size = 0;
703 ssize_t keylist_used = 0;
704 address_t *tmp = NULL, *addr = NULL;
705 address_t **last = &tmp;
709 for (i = 0; i < 3; i++) {
724 *last = address_list_dup (p);
726 last = &((*last)->next);
729 rfc822_qualify(tmp, mutt_fqdn(1));
731 address_list_uniq(tmp);
733 for (p = tmp; p; p = p->next) {
734 char buf[LONG_STRING];
738 if ((keyID = smime_get_field_from_db (q->mailbox, NULL, 1, 1)) == NULL) {
739 snprintf (buf, sizeof (buf), _("Enter keyID for %s: "), q->mailbox);
740 keyID = smime_ask_for_key (buf, q->mailbox, 1);
743 mutt_message (_("No (valid) certificate found for %s."), q->mailbox);
745 address_list_wipe(&tmp);
746 address_list_wipe(&addr);
750 keylist_size += m_strlen(keyID) + 2;
751 p_realloc(&keylist, keylist_size);
752 sprintf (keylist + keylist_used, "%s\n", keyID);
753 keylist_used = m_strlen(keylist);
755 address_list_wipe(&addr);
758 address_list_wipe(&tmp);
767 static int smime_handle_cert_email (char *certificate, char *mailbox,
768 int copy, char ***buffer, int *num)
770 FILE *fpout = NULL, *fperr = NULL;
771 char tmpfname[_POSIX_PATH_MAX];
773 int ret = -1, count = 0;
776 fperr = m_tempfile (tmpfname, sizeof(tmpfname), NONULL(Tempdir), NULL);
778 mutt_perror (tmpfname);
781 mutt_unlink (tmpfname);
783 fpout = m_tempfile (tmpfname, sizeof(tmpfname), NONULL(Tempdir), NULL);
786 mutt_perror (tmpfname);
789 mutt_unlink (tmpfname);
791 if ((thepid = smime_invoke (NULL, NULL, NULL,
792 -1, fileno (fpout), fileno (fperr),
793 certificate, NULL, NULL, NULL, NULL, NULL,
794 SmimeGetCertEmailCommand)) == -1) {
795 mutt_message (_("Error: unable to create OpenSSL subprocess!"));
801 mutt_wait_filter (thepid);
809 while ((fgets (email, sizeof (email), fpout))) {
810 *(email + m_strlen(email) - 1) = '\0';
811 if (m_strncasecmp(email, mailbox, m_strlen(mailbox)) == 0)
814 ret = ret < 0 ? 0 : ret;
820 mutt_copy_stream (fperr, stdout);
821 mutt_any_key_to_continue (_
822 ("Error: unable to create OpenSSL subprocess!"));
830 if (copy && buffer && num) {
832 *buffer = p_new(char *, count);
836 while ((fgets (email, sizeof (email), fpout))) {
837 *(email + m_strlen(email) - 1) = '\0';
838 (*buffer)[count] = p_dupstr(email, m_strlen(email));
853 static char *smime_extract_certificate (char *infile)
855 FILE *fpout = NULL, *fperr = NULL;
856 char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
857 char tmpfname[_POSIX_PATH_MAX];
862 fperr = m_tempfile (tmpfname, sizeof(tmpfname), NONULL(Tempdir), NULL);
864 mutt_perror (tmpfname);
867 mutt_unlink (tmpfname);
869 fpout = m_tempfile (pk7out, sizeof(tmpfname), NONULL(Tempdir), NULL);
872 mutt_perror (pk7out);
876 /* Step 1: Convert the signature to a PKCS#7 structure, as we can't
877 extract the full set of certificates directly.
879 if ((thepid = smime_invoke (NULL, NULL, NULL,
880 -1, fileno (fpout), fileno (fperr),
881 infile, NULL, NULL, NULL, NULL, NULL,
882 SmimePk7outCommand)) == -1) {
883 mutt_any_key_to_continue (_
884 ("Error: unable to create OpenSSL subprocess!"));
887 mutt_unlink (pk7out);
891 mutt_wait_filter (thepid);
899 empty = (fgetc (fpout) == EOF);
904 mutt_perror (pk7out);
905 mutt_copy_stream (fperr, stdout);
907 mutt_unlink (pk7out);
911 fpout = m_tempfile (certfile, sizeof(certfile), NONULL(Tempdir), NULL);
914 mutt_unlink (pk7out);
915 mutt_perror (certfile);
919 /* Step 2: Extract the certificates from a PKCS#7 structure.
921 if ((thepid = smime_invoke (NULL, NULL, NULL,
922 -1, fileno (fpout), fileno (fperr),
923 pk7out, NULL, NULL, NULL, NULL, NULL,
924 SmimeGetCertCommand)) == -1) {
925 mutt_any_key_to_continue (_
926 ("Error: unable to create OpenSSL subprocess!"));
929 mutt_unlink (pk7out);
930 mutt_unlink (certfile);
934 mutt_wait_filter (thepid);
936 mutt_unlink (pk7out);
942 empty = (fgetc (fpout) == EOF);
944 mutt_copy_stream (fperr, stdout);
947 mutt_unlink (certfile);
954 return m_strdup(certfile);
957 static char *smime_extract_signer_certificate (char *infile)
959 FILE *fpout = NULL, *fperr = NULL;
960 char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
961 char tmpfname[_POSIX_PATH_MAX];
965 fperr = m_tempfile (tmpfname, sizeof(tmpfname), NONULL(Tempdir), NULL);
967 mutt_perror (tmpfname);
970 mutt_unlink (tmpfname);
972 m_tempfile (certfile, sizeof(certfile), NONULL(Tempdir), NULL);
975 mutt_perror (certfile);
979 /* Extract signer's certificate
981 if ((thepid = smime_invoke (NULL, NULL, NULL,
982 -1, -1, fileno (fperr),
983 infile, NULL, NULL, NULL, certfile, NULL,
984 SmimeGetSignerCertCommand)) == -1) {
985 mutt_any_key_to_continue (_
986 ("Error: unable to create OpenSSL subprocess!"));
989 mutt_unlink (pk7out);
990 mutt_unlink (certfile);
994 mutt_wait_filter (thepid);
1000 empty = (fgetc (fpout) == EOF);
1005 mutt_copy_stream (fperr, stdout);
1006 mutt_any_key_to_continue (NULL);
1008 mutt_unlink (certfile);
1014 return m_strdup(certfile);
1017 /* Add a certificate and update index file (externally). */
1019 void smime_invoke_import (char *infile, char *mailbox __attribute__ ((unused)))
1021 char tmpfname[_POSIX_PATH_MAX], *certfile = NULL, buf[STRING];
1022 FILE *smimein = NULL, *fpout = NULL, *fperr = NULL;
1025 fperr = m_tempfile (tmpfname, sizeof(tmpfname), NONULL(Tempdir), NULL);
1027 mutt_perror (tmpfname);
1030 mutt_unlink (tmpfname);
1032 fpout = m_tempfile (tmpfname, sizeof(tmpfname), NONULL(Tempdir), NULL);
1035 mutt_perror (tmpfname);
1038 mutt_unlink (tmpfname);
1041 if (option (OPTASKCERTLABEL))
1042 mutt_get_field ("Label for certificate:", buf, sizeof (buf), 0);
1045 if ((certfile = smime_extract_certificate (infile))) {
1048 if ((thepid = smime_invoke (&smimein, NULL, NULL,
1049 -1, fileno (fpout), fileno (fperr),
1050 certfile, NULL, NULL, NULL, NULL, NULL,
1051 SmimeImportCertCommand)) == -1) {
1052 mutt_message (_("Error: unable to create OpenSSL subprocess!"));
1055 fputs (buf, smimein);
1056 fputc ('\n', smimein);
1059 mutt_wait_filter (thepid);
1061 mutt_unlink (certfile);
1062 p_delete(&certfile);
1070 mutt_copy_stream (fpout, stdout);
1071 mutt_copy_stream (fperr, stdout);
1077 int smime_verify_sender (HEADER * h)
1079 char *mbox = NULL, *certfile, tempfname[_POSIX_PATH_MAX];
1083 fpout = m_tempfile (tempfname, sizeof(tempfname), NONULL(Tempdir), NULL);
1085 mutt_perror (_("Can't create temporary file"));
1089 if (h->security & ENCRYPT)
1090 mutt_copy_message (fpout, Context, h,
1091 M_CM_DECODE_CRYPT & M_CM_DECODE_SMIME,
1092 CH_MIME | CH_WEED | CH_NONEWLINE);
1094 mutt_copy_message (fpout, Context, h, 0, 0);
1100 h->env->from = mutt_expand_aliases (h->env->from);
1101 mbox = h->env->from->mailbox;
1103 else if (h->env->sender) {
1104 h->env->sender = mutt_expand_aliases (h->env->sender);
1105 mbox = h->env->sender->mailbox;
1109 if ((certfile = smime_extract_signer_certificate (tempfname))) {
1110 mutt_unlink (tempfname);
1111 if (smime_handle_cert_email (certfile, mbox, 0, NULL, NULL)) {
1113 mutt_any_key_to_continue (NULL);
1117 mutt_unlink (certfile);
1118 p_delete(&certfile);
1121 mutt_any_key_to_continue (_("no certfile"));
1124 mutt_any_key_to_continue (_("no mbox"));
1126 mutt_unlink (tempfname);
1139 * Creating S/MIME - bodies.
1146 pid_t smime_invoke_encrypt (FILE ** smimein, FILE ** smimeout,
1147 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1148 int smimeerrfd, const char *fname,
1151 return smime_invoke (smimein, smimeout, smimeerr,
1152 smimeinfd, smimeoutfd, smimeerrfd,
1153 fname, NULL, SmimeCryptAlg, NULL, uids, NULL,
1154 SmimeEncryptCommand);
1159 pid_t smime_invoke_sign (FILE ** smimein, FILE ** smimeout, FILE ** smimeerr,
1160 int smimeinfd, int smimeoutfd, int smimeerrfd,
1163 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1164 smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1165 SmimeCertToUse, SmimeIntermediateToUse,
1172 BODY *smime_build_smime_entity (BODY * a, char *certlist)
1174 char buf[LONG_STRING], certfile[LONG_STRING];
1175 char tempfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1176 char smimeinfile[_POSIX_PATH_MAX];
1177 char *cert_start = certlist, *cert_end = certlist;
1178 FILE *smimein = NULL, *smimeerr = NULL, *fpout = NULL, *fptmp = NULL;
1183 fpout = m_tempfile (tempfile, sizeof(tempfile), NONULL(Tempdir), NULL);
1185 mutt_perror (_("Can't create temporary file"));
1189 smimeerr = m_tempfile (smimeerrfile, sizeof(smimeerrfile), NONULL(Tempdir), NULL);
1191 mutt_perror (smimeerrfile);
1193 mutt_unlink (tempfile);
1196 mutt_unlink (smimeerrfile);
1198 fptmp = m_tempfile (smimeinfile, sizeof(smimeinfile), NONULL(Tempdir), NULL);
1200 mutt_perror (smimeinfile);
1201 mutt_unlink (tempfile);
1203 m_fclose(&smimeerr);
1209 int off = m_strlen(certfile);
1211 while (*++cert_end && *cert_end != '\n');
1215 snprintf (certfile + off, sizeof (certfile) - off, " %s/%s",
1216 NONULL (SmimeCertificates), cert_start);
1218 cert_start = cert_end;
1222 /* write a MIME entity */
1223 mutt_write_mime_header (a, fptmp);
1224 fputc ('\n', fptmp);
1225 mutt_write_mime_body (a, fptmp);
1229 smime_invoke_encrypt (&smimein, NULL, NULL, -1,
1230 fileno (fpout), fileno (smimeerr),
1231 smimeinfile, certfile)) == -1) {
1232 m_fclose(&smimeerr);
1233 mutt_unlink (smimeinfile);
1234 mutt_unlink (certfile);
1240 mutt_wait_filter (thepid);
1241 mutt_unlink (smimeinfile);
1242 mutt_unlink (certfile);
1246 empty = (fgetc (fpout) == EOF);
1251 while (fgets (buf, sizeof (buf) - 1, smimeerr) != NULL) {
1253 fputs (buf, stdout);
1255 m_fclose(&smimeerr);
1257 /* pause if there is any error output from SMIME */
1259 mutt_any_key_to_continue (NULL);
1262 /* fatal error while trying to encrypt message */
1264 mutt_any_key_to_continue _("No output from OpenSSL..");
1266 mutt_unlink (tempfile);
1271 t->type = TYPEAPPLICATION;
1272 t->subtype = m_strdup("x-pkcs7-mime");
1273 parameter_setval(&t->parameter, "name", "smime.p7m");
1274 parameter_setval(&t->parameter, "smime-type", "enveloped-data");
1275 t->encoding = ENCBASE64; /* The output of OpenSSL SHOULD be binary */
1277 t->disposition = DISPATTACH;
1278 t->d_filename = m_strdup("smime.p7m");
1279 t->filename = m_strdup(tempfile);
1280 t->unlink = 1; /*delete after sending the message */
1290 BODY *smime_sign_message (BODY * a)
1293 char buffer[LONG_STRING];
1294 char signedfile[_POSIX_PATH_MAX], filetosign[_POSIX_PATH_MAX];
1295 FILE *smimein = NULL, *smimeout = NULL, *smimeerr = NULL, *sfp = NULL;
1299 char *intermediates = smime_get_field_from_db (NULL, SmimeDefaultKey, 1, 1);
1301 if (!intermediates) {
1302 mutt_message (_("Warning: Intermediate certificate not found."));
1303 intermediates = SmimeDefaultKey; /* so openssl won't complain in any case */
1306 convert_to_7bit (a); /* Signed data _must_ be in 7-bit format. */
1308 sfp = m_tempfile (filetosign, sizeof(filetosign), NONULL(Tempdir), NULL);
1310 mutt_perror (filetosign);
1314 smimeout = m_tempfile (signedfile, sizeof(signedfile), NONULL(Tempdir), NULL);
1316 mutt_perror (signedfile);
1318 mutt_unlink (filetosign);
1322 mutt_write_mime_header (a, sfp);
1324 mutt_write_mime_body (a, sfp);
1329 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
1330 NONULL (SmimeKeys), SmimeDefaultKey);
1332 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
1333 NONULL (SmimeCertificates), SmimeDefaultKey);
1335 snprintf (SmimeIntermediateToUse, sizeof (SmimeIntermediateToUse), "%s/%s",
1336 NONULL (SmimeCertificates), intermediates);
1340 if ((thepid = smime_invoke_sign (&smimein, NULL, &smimeerr,
1341 -1, fileno (smimeout), -1,
1342 filetosign)) == -1) {
1343 mutt_perror (_("Can't open OpenSSL subprocess!"));
1345 m_fclose(&smimeout);
1346 mutt_unlink (signedfile);
1347 mutt_unlink (filetosign);
1350 fputs (SmimePass, smimein);
1351 fputc ('\n', smimein);
1355 mutt_wait_filter (thepid);
1357 /* check for errors from OpenSSL */
1361 while (fgets (buffer, sizeof (buffer) - 1, smimeerr) != NULL) {
1363 fputs (buffer, stdout);
1365 m_fclose(&smimeerr);
1370 empty = (fgetc (smimeout) == EOF);
1371 m_fclose(&smimeout);
1373 mutt_unlink (filetosign);
1377 mutt_any_key_to_continue (NULL);
1380 mutt_any_key_to_continue _("No output from OpenSSL...");
1382 mutt_unlink (signedfile);
1383 return (NULL); /* fatal error while signing */
1387 t->type = TYPEMULTIPART;
1388 t->subtype = m_strdup("signed");
1389 t->encoding = ENC7BIT;
1391 t->disposition = DISPINLINE;
1393 parameter_set_boundary(&t->parameter);
1394 /* check if this can be extracted from private key somehow.... */
1395 parameter_setval(&t->parameter, "micalg", "sha1");
1396 parameter_setval(&t->parameter, "protocol",
1397 "application/x-pkcs7-signature");
1402 t->parts->next = body_new();
1404 t->type = TYPEAPPLICATION;
1405 t->subtype = m_strdup("x-pkcs7-signature");
1406 t->filename = m_strdup(signedfile);
1407 t->d_filename = m_strdup("smime.p7s");
1409 t->disposition = DISPATTACH;
1410 t->encoding = ENCBASE64;
1411 t->unlink = 1; /* ok to remove this file after sending. */
1419 * Handling S/MIME - bodies.
1424 pid_t smime_invoke_verify (FILE ** smimein, FILE ** smimeout,
1425 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1426 int smimeerrfd, const char *fname,
1427 const char *sig_fname, int opaque)
1429 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1430 smimeerrfd, fname, sig_fname, NULL, NULL, NULL, NULL,
1431 (opaque ? SmimeVerifyOpaqueCommand :
1432 SmimeVerifyCommand));
1437 pid_t smime_invoke_decrypt (FILE ** smimein, FILE ** smimeout,
1438 FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1439 int smimeerrfd, const char *fname)
1441 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1442 smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1443 SmimeCertToUse, NULL, SmimeDecryptCommand);
1448 int smime_verify_one (BODY * sigbdy, STATE * s, const char *tempfile)
1450 char signedfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1451 FILE *fp = NULL, *smimeout = NULL, *smimeerr = NULL;
1456 ssize_t tmplength = 0;
1457 int origType = sigbdy->type;
1458 char *savePrefix = NULL;
1461 snprintf (signedfile, sizeof (signedfile), "%s.sig", tempfile);
1463 /* decode to a tempfile, saving the original destination */
1465 if ((s->fpout = safe_fopen (signedfile, "w")) == NULL) {
1466 mutt_perror (signedfile);
1469 /* decoding the attachment changes the size and offset, so save a copy
1470 * of the "real" values now, and restore them after processing
1472 tmplength = sigbdy->length;
1473 tmpoffset = sigbdy->offset;
1475 /* if we are decoding binary bodies, we don't want to prefix each
1476 * line with the prefix or else the data will get corrupted.
1478 savePrefix = s->prefix;
1481 mutt_decode_attachment (sigbdy, s);
1483 sigbdy->length = ftello (s->fpout);
1485 m_fclose(&s->fpout);
1487 /* restore final destination and substitute the tempfile for input */
1490 s->fpin = fopen (signedfile, "r");
1492 /* restore the prefix */
1493 s->prefix = savePrefix;
1495 sigbdy->type = origType;
1497 smimeerr = m_tempfile(smimeerrfile, sizeof(smimeerrfile), NONULL(Tempdir), NULL);
1499 mutt_perror (smimeerrfile);
1500 mutt_unlink (signedfile);
1504 crypt_current_time (s, "OpenSSL");
1506 if ((thepid = smime_invoke_verify (NULL, &smimeout, NULL,
1507 -1, -1, fileno (smimeerr),
1508 tempfile, signedfile, 0)) != -1) {
1509 m_fclose(&smimeout);
1511 if (mutt_wait_filter (thepid))
1521 line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1522 if (linelen && !m_strcasecmp(line, "verification successful"))
1531 mutt_copy_stream (smimeerr, s->fpout);
1532 m_fclose(&smimeerr);
1534 state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1536 mutt_unlink (signedfile);
1537 mutt_unlink (smimeerrfile);
1539 sigbdy->length = tmplength;
1540 sigbdy->offset = tmpoffset;
1542 /* restore the original source stream */
1555 This handles application/pkcs7-mime which can either be a signed
1556 or an encrypted message.
1559 static BODY *smime_handle_entity (BODY * m, STATE * s, FILE * outFile)
1564 char buf[HUGE_STRING];
1565 char outfile[_POSIX_PATH_MAX], errfile[_POSIX_PATH_MAX];
1566 char tmpfname[_POSIX_PATH_MAX];
1567 char tmptmpfname[_POSIX_PATH_MAX];
1568 FILE *smimeout = NULL, *smimein = NULL, *smimeerr = NULL;
1569 FILE *tmpfp = NULL, *tmpfp_buffer = NULL, *fpout = NULL;
1573 unsigned int type = mutt_is_application_smime (m);
1575 if (!(type & APPLICATION_SMIME))
1578 smimeout = m_tempfile (outfile, sizeof(outfile), NONULL(Tempdir), NULL);
1580 mutt_perror (outfile);
1584 smimeerr = m_tempfile(errfile, sizeof(errfile), NONULL(Tempdir), NULL);
1586 mutt_perror (errfile);
1587 m_fclose(&smimeout);
1590 mutt_unlink (errfile);
1592 tmpfp = m_tempfile (tmpfname, sizeof(tmpfname), NONULL(Tempdir), NULL);
1594 mutt_perror (tmpfname);
1595 m_fclose(&smimeout);
1596 m_fclose(&smimeerr);
1600 fseeko (s->fpin, m->offset, 0);
1601 last_pos = m->offset;
1603 mutt_copy_bytes (s->fpin, tmpfp, m->length);
1606 if ((type & ENCRYPT) &&
1607 (thepid = smime_invoke_decrypt (&smimein, NULL, NULL, -1,
1608 fileno (smimeout), fileno (smimeerr),
1610 m_fclose(&smimeout);
1611 mutt_unlink (tmpfname);
1612 if (s->flags & M_DISPLAY)
1613 state_attach_puts (_("[-- Error: unable to create OpenSSL subprocess! --]\n"), s);
1616 else if ((type & SIGNOPAQUE) &&
1617 (thepid = smime_invoke_verify (&smimein, NULL, NULL, -1,
1619 fileno (smimeerr), NULL, tmpfname,
1620 SIGNOPAQUE)) == -1) {
1621 m_fclose(&smimeout);
1622 mutt_unlink (tmpfname);
1623 if (s->flags & M_DISPLAY)
1624 state_attach_puts (_("[-- Error: unable to create OpenSSL subprocess! --]\n"), s);
1629 if (type & ENCRYPT) {
1630 if (!smime_valid_passphrase ())
1631 smime_void_passphrase ();
1632 fputs (SmimePass, smimein);
1633 fputc ('\n', smimein);
1638 mutt_wait_filter (thepid);
1639 mutt_unlink (tmpfname);
1642 if (s->flags & M_DISPLAY) {
1645 if ((c = fgetc (smimeerr)) != EOF) {
1646 ungetc (c, smimeerr);
1648 crypt_current_time (s, "OpenSSL");
1649 mutt_copy_stream (smimeerr, s->fpout);
1650 state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1654 state_attach_puts (_("[-- The following data is S/MIME"
1655 " encrypted --]\n"), s);
1657 state_attach_puts (_("[-- The following data is S/MIME signed --]\n"),
1668 fpout = m_tempfile (tmptmpfname, sizeof(tmptmpfname), NONULL(Tempdir), NULL);
1670 mutt_perror (tmptmpfname);
1671 m_fclose(&smimeout);
1675 while (fgets (buf, sizeof (buf) - 1, smimeout) != NULL) {
1676 len = m_strlen(buf);
1677 if (len > 1 && buf[len - 2] == '\r') {
1678 buf[len - 2] = '\n';
1679 buf[len - 1] = '\0';
1687 if ((p = mutt_read_mime_header (fpout, 0)) != NULL) {
1688 fstat (fileno (fpout), &info);
1689 p->length = info.st_size - p->offset;
1691 mutt_parse_part (fpout, p);
1694 tmpfp_buffer = s->fpin;
1696 mutt_body_handler (p, s);
1697 s->fpin = tmpfp_buffer;
1701 m_fclose(&smimeout);
1702 mutt_unlink (outfile);
1706 mutt_unlink (tmptmpfname);
1711 if (s->flags & M_DISPLAY) {
1713 state_attach_puts (_("\n[-- End of S/MIME encrypted data. --]\n"), s);
1715 state_attach_puts (_("\n[-- End of S/MIME signed data. --]\n"), s);
1718 if (type & SIGNOPAQUE) {
1725 line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1726 if (linelen && !m_strcasecmp(line, "verification successful"))
1731 m->goodsig = p->goodsig;
1732 m->badsig = p->badsig;
1734 m_fclose(&smimeerr);
1743 int smime_decrypt_mime (FILE * fpin, FILE ** fpout, BODY * b, BODY ** cur)
1747 char tempfile[_POSIX_PATH_MAX];
1749 long tmpoffset = b->offset;
1750 ssize_t tmplength = b->length;
1751 int origType = b->type;
1755 if (!mutt_is_application_smime (b))
1763 fseeko (s.fpin, b->offset, 0);
1765 tmpfp = m_tempfile (tempfile, sizeof(tempfile), NONULL(Tempdir), NULL);
1767 mutt_perror (_("Can't create temporary file"));
1771 mutt_unlink (tempfile);
1773 mutt_decode_attachment (b, &s);
1775 b->length = ftello (s.fpout);
1781 *fpout = m_tempfile (tempfile, sizeof(tempfile), NONULL(Tempdir), NULL);
1783 mutt_perror (_("Can't create temporary file"));
1787 mutt_unlink (tempfile);
1789 if (!(*cur = smime_handle_entity (b, &s, *fpout))) {
1794 (*cur)->goodsig = b->goodsig;
1795 (*cur)->badsig = b->badsig;
1799 b->length = tmplength;
1800 b->offset = tmpoffset;
1809 int smime_application_smime_handler (BODY * m, STATE * s)
1811 return smime_handle_entity (m, s, NULL) ? 0 : -1;
1814 int smime_send_menu (HEADER * msg, int *redraw)
1818 switch (mutt_multi_choice
1819 (_("S/MIME (e)ncrypt, (s)ign, encrypt (w)ith, sign (a)s, (b)oth, or (c)lear? "),
1821 case 1: /* (e)ncrypt */
1822 msg->security |= ENCRYPT;
1823 msg->security &= ~SIGN;
1826 case 3: /* encrypt (w)ith */
1829 msg->security |= ENCRYPT;
1832 /* I use "dra" because "123" is recognized anyway */
1833 switch (mutt_multi_choice (_("Choose algorithm family:"
1834 " 1: DES, 2: RC2, 3: AES,"
1835 " or (c)lear? "), _("drac"))) {
1837 switch (choice = mutt_multi_choice (_("1: DES, 2: Triple-DES "),
1840 m_strreplace(&SmimeCryptAlg, "des");
1843 m_strreplace(&SmimeCryptAlg, "des3");
1849 switch (choice = mutt_multi_choice (_("1: RC2-40, 2: RC2-64, 3: RC2-128 "),
1852 m_strreplace(&SmimeCryptAlg, "rc2-40");
1855 m_strreplace(&SmimeCryptAlg, "rc2-64");
1858 m_strreplace(&SmimeCryptAlg, "rc2-128");
1864 switch (choice = mutt_multi_choice (_("1: AES128, 2: AES192, 3: AES256 "),
1867 m_strreplace(&SmimeCryptAlg, "aes128");
1870 m_strreplace(&SmimeCryptAlg, "aes192");
1873 m_strreplace(&SmimeCryptAlg, "aes256");
1878 case 4: /* (c)lear */
1879 p_delete(&SmimeCryptAlg);
1881 case -1: /* Ctrl-G or Enter */
1885 } while (choice == -1);
1889 case 2: /* (s)ign */
1891 if (!SmimeDefaultKey)
1892 mutt_message (_("Can't sign: No key specified. Use Sign As."));
1895 msg->security |= SIGN;
1896 msg->security &= ~ENCRYPT;
1900 case 4: /* sign (a)s */
1902 if ((p = smime_ask_for_key (_("Sign as: "), NULL, 0))) {
1903 m_strreplace(&SmimeDefaultKey, p);
1905 msg->security |= SIGN;
1907 /* probably need a different passphrase */
1908 crypt_smime_void_passphrase ();
1911 *redraw = REDRAW_FULL;
1914 case 5: /* (b)oth */
1915 msg->security |= (ENCRYPT | SIGN);
1918 case 6: /* (f)orget it */
1919 case 7: /* (c)lear */
1924 if (msg->security && msg->security != APPLICATION_SMIME)
1925 msg->security |= APPLICATION_SMIME;
1929 return (msg->security);