aboutsummaryrefslogblamecommitdiffstats
path: root/mail/mail-crypto.c
blob: 4db4357b44bbb2407871c7d03b55ed837c9325c5 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405




















































































































































































































































































































































































































                                                                               
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */

/*
 * mail-crypto.h: OpenPGP en/decryption & signature code
 *
 * FIXME FIXME FIXME: This should be in its own library or component
 */

/*
 * Authors:
 *  Nathan Thompson-Amato <ndt@jps.net>
 *  Dan Winship <danw@helixcode.com>
 *
 *  Copyright 2000, Helix Code, Inc. (http://www.helixcode.com)
 *  Copyright 2000, Nathan Thompson-Amato
 *  Copyright 1999, 2000, Anthony Mulcahy
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
 *
 */

#include "config.h"

#ifdef PGP_PROGRAM
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include <gnome.h>

#include "mail.h"

#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <signal.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#include <signal.h>

static int
cleanup_child (pid_t child)
{
    int status;
    pid_t wait_result;
    sigset_t mask, omask;

    /* PGP5 closes fds before exiting, meaning this might be called
     * too early. So wait a bit for the result.
     */
    sigemptyset (&mask);
    sigaddset (&mask, SIGALRM);
    sigprocmask (SIG_BLOCK, &mask, &omask);
    alarm (1);
    wait_result = waitpid (child, &status, 0);
    alarm (0);
    sigprocmask (SIG_SETMASK, &omask, NULL);

    if (wait_result == -1 && errno == EINTR) {
        /* The child is hanging: send a friendly reminder. */
        kill (child, SIGTERM);
        sleep (1);
        wait_result = waitpid (child, &status, WNOHANG);
        if (wait_result == 0) {
            /* Still hanging; use brute force. */
            kill (child, SIGKILL);
            sleep (1);
            wait_result = waitpid (child, &status, WNOHANG);
        }
    }

    if (wait_result != -1 && WIFEXITED (status))
        return WEXITSTATUS (status);
    else
        return -1;
}

static void
cleanup_before_exec (int fd)
{
    int maxfd, i;

    maxfd = sysconf (_SC_OPEN_MAX);
    if (maxfd < 0)
        return;

    /* Loop over all fds. */
    for (i = 0; i < maxfd; i++) {
        if ((STDIN_FILENO != i) &&
            (STDOUT_FILENO != i) &&
            (STDERR_FILENO != i) &&
            (fd != i))
            close (i);
    }
}

static int
crypto_exec_with_passwd (char *path, char *argv[], const char *input,
             int passwd_fds[], const char *passphrase,
             char **output, char **diagnostics)
{
    fd_set fdset, write_fdset;
    int ip_fds[2], op_fds[2], diag_fds[2];
    int select_result, read_len, write_len;
        size_t tmp_len;
    pid_t child;
    char *buf, *diag_buf;
    const char *passwd_next, *input_next;
    size_t size, alloc_size, diag_size, diag_alloc_size;
        gboolean eof_seen, diag_eof_seen, passwd_eof_seen, input_eof_seen;
        size_t passwd_remaining, passwd_incr, input_remaining, input_incr;
    struct timeval timeout;
        long tmp;

    if ((pipe (ip_fds) < 0 ) ||
        (pipe (op_fds) < 0 ) ||
        (pipe (diag_fds) < 0 )) {
        *diagnostics = g_strdup_printf ("Couldn't create pipe to %s: "
                        "%s", PGP_PROGRAM,
                        g_strerror (errno));
        return 0;
    }

    if (!(child = fork ())) {
        /* In child */

                if ((dup2 (ip_fds[0], STDIN_FILENO) < 0 ) ||
            (dup2 (op_fds[1], STDOUT_FILENO) < 0 ) ||
            (dup2 (diag_fds[1], STDERR_FILENO) < 0 )) {
            _exit (255);
        }

        /* Dissociate from evolution-mail's controlling
         * terminal so that pgp/gpg won't be able to read from
         * it: PGP 2 will fall back to asking for the password
         * on /dev/tty if the passed-in password is incorrect.
         * This will make that fail rather than hanging.
         */
        setsid ();

        /* Close excess fds */
                cleanup_before_exec(passwd_fds[0]);

        execvp (path, argv);
        fprintf (stderr, "Could not execute %s: %s\n", argv[0],
             g_strerror (errno));
        _exit (255);
    } else if (child < 0) {
        *diagnostics = g_strdup_printf ("Cannot fork %s: %s",
                        argv[0], g_strerror (errno));
        return 0;
    }

    /* Parent */
    close (ip_fds[0]);
    close (op_fds[1]);
    close (diag_fds[1]);
    close (passwd_fds[0]);

    timeout.tv_sec = 10; /* timeout in seconds */
    timeout.tv_usec = 0;

    size = diag_size = 0;
    alloc_size = 4096;
    diag_alloc_size = 1024;
        eof_seen = diag_eof_seen = FALSE;

    buf = g_malloc (alloc_size);
    diag_buf = g_malloc (diag_alloc_size);

        passwd_next = passphrase;
        passwd_remaining = strlen (passphrase);
        passwd_incr = fpathconf (passwd_fds[1], _PC_PIPE_BUF);
    /* Use a reasonable default value on error. */
        if (passwd_incr <= 0)
        passwd_incr = 1024;
        passwd_eof_seen = FALSE;

    input_next = input;
    input_remaining = strlen (input);
    input_incr = fpathconf (ip_fds[1], _PC_PIPE_BUF);
    if (input_incr <= 0)
                input_incr = 1024;
    input_eof_seen = FALSE;

    while (!(eof_seen && diag_eof_seen)) {
        FD_ZERO (&fdset);
                if (!eof_seen)
            FD_SET (op_fds[0], &fdset);
                if (!diag_eof_seen)
            FD_SET (diag_fds[0], &fdset);

        FD_ZERO (&write_fdset);
                if (!passwd_eof_seen)
            FD_SET (passwd_fds[1], &write_fdset);
                if (!input_eof_seen)
            FD_SET (ip_fds[1], &write_fdset);

        select_result = select (FD_SETSIZE, &fdset, &write_fdset,
                    NULL, &timeout);
        if (select_result < 0) {
            if (errno == EINTR)
                continue;
            break;
        }
        if (select_result == 0) {
            /* timeout */
            break;
        }

                if (FD_ISSET (op_fds[0], &fdset)) {
            /* More output is available. */

            if (size + 4096 > alloc_size) {
                alloc_size += 4096;
                buf = g_realloc (buf , alloc_size);
            }
            read_len = read (op_fds[0], &buf[size],
                     alloc_size - size - 1);
            if (read_len < 0) {
                if (errno == EINTR)
                    continue;
                break;
            }
            if (read_len == 0)
                eof_seen = TRUE;
            size += read_len;
                }

                if (FD_ISSET(diag_fds[0], &fdset) ) {
            /* More stderr is available. */

            if (diag_size + 1024 > diag_alloc_size) {
                diag_alloc_size += 1024;
                diag_buf = g_realloc (diag_buf,
                              diag_alloc_size);
            }

            read_len = read (diag_fds[0], &diag_buf[diag_size],
                     diag_alloc_size - diag_size - 1);
            if (read_len < 0) {
                if (errno == EINTR)
                    continue;
                break;
            }
            if (read_len == 0)
                diag_eof_seen = TRUE;
            diag_size += read_len;
                }

                if (FD_ISSET(passwd_fds[1], &write_fdset)) {
            /* Ready for more password input. */

            tmp_len = passwd_incr;
            if (tmp_len > passwd_remaining)
                tmp_len = passwd_remaining;
            write_len = write (passwd_fds[1], passwd_next,
                       tmp_len);
            if (write_len < 0) {
                if (errno == EINTR)
                    continue;
                break;
            }
            passwd_next += write_len;
            passwd_remaining -= write_len;
            if (passwd_remaining == 0) {
                close (passwd_fds[1]);
                passwd_eof_seen = TRUE;
            }
                }

                if (FD_ISSET(ip_fds[1], &write_fdset)) {
            /* Ready for more ciphertext input. */

            tmp_len = input_incr;
            if (tmp_len > input_remaining)
                tmp_len = input_remaining;
            write_len = write (ip_fds[1], input_next, tmp_len);
            if (write_len < 0) {
                if (errno == EINTR)
                    continue;
                break;
            }
            input_next += write_len;
            input_remaining -= write_len;
            if (input_remaining == 0 ) {
                close (ip_fds[1]);
                input_eof_seen = TRUE;
            }
                }
    }

    buf[size] = 0;
    diag_buf[diag_size] = 0;
    close (op_fds[0]);
    close (diag_fds[0]);

    *output = buf;
    *diagnostics = diag_buf;

        return cleanup_child (child);
}

/*----------------------------------------------------------------------*
 *                     Public crypto functions
 *----------------------------------------------------------------------*/


char *
mail_crypto_openpgp_decrypt (const char *ciphertext, const char *passphrase,
                 CamelException *ex)
{
    int retval;
    char *path, *argv[12];
    int i;
    char *plaintext = NULL;
    char *diagnostics = NULL;
    int passwd_fds[2];
    char passwd_fd[32];

#ifndef PGP_PROGRAM
    camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
                  "No GPG/PGP program available.");
    return NULL;
#endif

    if (pipe (passwd_fds) < 0) {
        camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
                      _("Couldn't create pipe to GPG/PGP: %s"),
                      g_strerror (errno));
        return NULL;
    }

    i = 0;
#if defined(GPG_PATH)
    path = GPG_PATH;

    argv[i++] = "gpg";
    argv[i++] = "--verbose";
    argv[i++] = "--yes";
    argv[i++] = "--batch";

    argv[i++] = "--output";
    argv[i++] = "-";            /* output to stdout */

    argv[i++] = "--decrypt";

    argv[i++] = "--passphrase-fd";
    sprintf (passwd_fd, "%d", passwd_fds[0]);
    argv[i++] = passwd_fd;
#elif defined(PGP5_PATH)
    path = PGP5_PATH;

    argv[i++] = "pgpv";
    argv[i++] = "-f";
    argv[i++] = "+batchmode=1";

    sprintf (passwd_fd, "PGPPASSFD=%d", passwd_fds[0]);
    putenv (passwd_fd);
#else
    path = PGP_PATH;

    argv[i++] = "pgp";
    argv[i++] = "-f";

    sprintf (passwd_fd, "PGPPASSFD=%d", passwd_fds[0]);
    putenv (passwd_fd);
#endif
    argv[i++] = NULL;

    retval = crypto_exec_with_passwd (path, argv, ciphertext, passwd_fds,
                      passphrase, &plaintext,
                      &diagnostics);
    if (retval != 0 || !*plaintext) {
        camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
                      "%s", diagnostics);
        g_free (plaintext);
        g_free (diagnostics);
        return NULL;
    }

    g_free (diagnostics);
    return plaintext;
}

#endif /* PGP_PROGRAM */