Add CRAM-MD5 authentication support for the DragonFly Mail Agent. This is the
[dragonfly.git] / libexec / dma / net.c
1 /*
2  * Copyright (c) 2008 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthias Schmidt <matthias@dragonflybsd.org>, University of Marburg,
6  * Germany.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  * 3. Neither the name of The DragonFly Project nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific, prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
26  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  * $DragonFly: src/libexec/dma/net.c,v 1.7 2008/09/02 15:11:49 matthias Exp $
36  */
37
38 #include <sys/param.h>
39 #include <sys/queue.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <sys/socket.h>
43 #include <netinet/in.h>
44 #include <arpa/inet.h>
45
46 #ifdef HAVE_CRYPTO
47 #include <openssl/ssl.h>
48 #endif /* HAVE_CRYPTO */
49
50 #include <netdb.h>
51 #include <setjmp.h>
52 #include <signal.h>
53 #include <syslog.h>
54 #include <unistd.h>
55
56 #include "dma.h"
57
58 extern struct config *config;
59 extern struct authusers authusers;
60 static jmp_buf timeout_alarm;
61
62 static void
63 sig_alarm(int signo __unused)
64 {
65         longjmp(timeout_alarm, 1);
66 }
67
68 ssize_t
69 send_remote_command(int fd, const char* fmt, ...)
70 {
71         va_list va;
72         char cmd[4096];
73         ssize_t len = 0;
74
75         va_start(va, fmt);
76         vsprintf(cmd, fmt, va);
77
78         if (((config->features & SECURETRANS) != 0) &&
79             ((config->features & NOSSL) == 0)) {
80                 len = SSL_write(config->ssl, (const char*)cmd, strlen(cmd));
81                 SSL_write(config->ssl, "\r\n", 2);
82         }
83         else {
84                 len = write(fd, cmd, strlen(cmd));
85                 write(fd, "\r\n", 2);
86         }
87         va_end(va);
88
89         return (len+2);
90 }
91
92 int
93 read_remote(int fd, int extbufsize, char *extbuf)
94 {
95         ssize_t rlen = 0;
96         size_t pos, len;
97         char buff[BUF_SIZE];
98         int done = 0, status = 0, extbufpos = 0;
99
100         if (signal(SIGALRM, sig_alarm) == SIG_ERR) {
101                 syslog(LOG_ERR, "SIGALRM error: %m");
102         }
103         if (setjmp(timeout_alarm) != 0) {
104                 syslog(LOG_ERR, "Timeout reached");
105                 return (1);
106         }
107         alarm(CON_TIMEOUT);
108
109         /*
110          * Remote reading code from femail.c written by Henning Brauer of
111          * OpenBSD and released under a BSD style license.
112          */
113         for (len = pos = 0; !done; ) {
114                 rlen = 0;
115                 if (pos == 0 ||
116                     (pos > 0 && memchr(buff + pos, '\n', len - pos) == NULL)) {
117                         memmove(buff, buff + pos, len - pos);
118                         len -= pos;
119                         pos = 0;
120                         if (((config->features & SECURETRANS) != 0) &&
121                             (config->features & NOSSL) == 0) {
122                                 if ((rlen = SSL_read(config->ssl, buff + len,
123                                     sizeof(buff) - len)) == -1)
124                                         err(1, "read");
125                         } else {
126                                 if ((rlen = read(fd, buff + len,
127                                     sizeof(buff) - len)) == -1)
128                                         err(1, "read");
129                         }
130                         len += rlen;
131                 }
132                 /*
133                  * If there is an external buffer with a size bigger than zero
134                  * and as long as there is space in the external buffer and
135                  * there are new characters read from the mailserver
136                  * copy them to the external buffer
137                  */
138                 if (extbufpos <= (extbufsize - 1) && rlen && extbufsize > 0 
139                     && extbuf != NULL) {
140                         /* do not write over the bounds of the buffer */
141                         if(extbufpos + rlen > (extbufsize - 1)) {
142                                 rlen = extbufsize - extbufpos;
143                         }
144                         memcpy(extbuf + extbufpos, buff + len - rlen, rlen);
145                         extbufpos += rlen;
146                 }
147                 for (; pos < len && buff[pos] >= '0' && buff[pos] <= '9'; pos++)
148                         ; /* Do nothing */
149
150                 if (pos == len)
151                         return (0);
152
153                 if (buff[pos] == ' ')
154                         done = 1;
155                 else if (buff[pos] != '-')
156                         syslog(LOG_ERR, "invalid syntax in reply from server");
157
158                 /* skip up to \n */
159                 for (; pos < len && buff[pos - 1] != '\n'; pos++)
160                         ; /* Do nothing */
161
162         }
163         alarm(0);
164
165         status = atoi(buff);
166         return (status/100);
167 }
168
169 /*
170  * Handle SMTP authentication
171  */
172 static int
173 smtp_login(struct qitem *it, int fd, char *login, char* password)
174 {
175         char *temp;
176         int len, res = 0;
177
178 #ifdef HAVE_CRYPTO
179         res = smtp_auth_md5(it, fd, login, password);
180         if (res == 0) {
181                 return (0);
182         } else if (res == -2) {
183         /*
184          * If the return code is -2, then then the login attempt failed, 
185          * do not try other login mechanisms
186          */
187                 return (-1);
188         }
189 #endif /* HAVE_CRYPTO */
190
191         if ((config->features & INSECURE) != 0) {
192                 /* Send AUTH command according to RFC 2554 */
193                 send_remote_command(fd, "AUTH LOGIN");
194                 if (read_remote(fd, 0, NULL) != 3) {
195                         syslog(LOG_ERR, "%s: remote delivery deferred:"
196                                         " AUTH login not available: %m", it->queueid);
197                         return (1);
198                 }
199
200                 len = base64_encode(login, strlen(login), &temp);
201                 if (len <= 0)
202                         return (-1);
203
204                 send_remote_command(fd, "%s", temp);
205                 if (read_remote(fd, 0, NULL) != 3) {
206                         syslog(LOG_ERR, "%s: remote delivery deferred:"
207                                         " AUTH login failed: %m", it->queueid);
208                         return (-1);
209                 }
210
211                 len = base64_encode(password, strlen(password), &temp);
212                 if (len <= 0)
213                         return (-1);
214
215                 send_remote_command(fd, "%s", temp);
216                 res = read_remote(fd, 0, NULL);
217                 if (res == 5) {
218                         syslog(LOG_ERR, "%s: remote delivery failed:"
219                                         " Authentication failed: %m", it->queueid);
220                         return (-1);
221                 } else if (res != 2) {
222                         syslog(LOG_ERR, "%s: remote delivery failed:"
223                                         " AUTH password failed: %m", it->queueid);
224                         return (-1);
225                 }
226         } else {
227                 syslog(LOG_ERR, "%s: non-encrypted SMTP login is disabled in config, so skipping it. ",
228                                 it->queueid);
229                 return (1);
230         }
231
232         return (0);
233 }
234
235 static int
236 open_connection(struct qitem *it, const char *host)
237 {
238         struct addrinfo hints, *res, *res0;
239         char servname[128];
240         const char *errmsg = NULL;
241         int fd, error = 0, port;
242
243         if (config->port != 0)
244                 port = config->port;
245         else
246                 port = SMTP_PORT;
247
248         /* FIXME get MX record of host */
249         /* Shamelessly taken from getaddrinfo(3) */
250         memset(&hints, 0, sizeof(hints));
251         hints.ai_family = PF_UNSPEC;
252         hints.ai_socktype = SOCK_STREAM;
253         hints.ai_protocol = IPPROTO_TCP;
254
255         snprintf(servname, sizeof(servname), "%d", port);
256         error = getaddrinfo(host, servname, &hints, &res0);
257         if (error) {
258                 syslog(LOG_ERR, "%s: remote delivery deferred: "
259                        "%s: %m", it->queueid, gai_strerror(error));
260                 return (-1);
261         }
262         fd = -1;
263         for (res = res0; res; res = res->ai_next) {
264                 fd=socket(res->ai_family, res->ai_socktype, res->ai_protocol);
265                 if (fd < 0) {
266                         errmsg = "socket failed";
267                         continue;
268                 }
269                 if (connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
270                         errmsg = "connect failed";
271                         close(fd);
272                         fd = -1;
273                         continue;
274                 }
275                 break;
276         }
277         if (fd < 0) {
278                 syslog(LOG_ERR, "%s: remote delivery deferred: %s (%s:%s)",
279                         it->queueid, errmsg, host, servname);
280                 freeaddrinfo(res0);
281                 return (-1);
282         }
283         freeaddrinfo(res0);
284         return (fd);
285 }
286
287 int
288 deliver_remote(struct qitem *it, const char **errmsg)
289 {
290         struct authuser *a;
291         char *host, line[1000];
292         int fd, error = 0, do_auth = 0, res = 0;
293         size_t linelen;
294
295         host = strrchr(it->addr, '@');
296         /* Should not happen */
297         if (host == NULL)
298                 return(-1);
299         else
300                 /* Step over the @ */
301                 host++;
302
303         /* Smarthost support? */
304         if (config->smarthost != NULL && strlen(config->smarthost) > 0) {
305                 syslog(LOG_INFO, "%s: using smarthost (%s)",
306                        it->queueid, config->smarthost);
307                 host = config->smarthost;
308         }
309
310         fd = open_connection(it, host);
311         if (fd < 0)
312                 return (1);
313
314         /* Check first reply from remote host */
315         config->features |= NOSSL;
316         res = read_remote(fd, 0, NULL);
317         if (res != 2) {
318                 syslog(LOG_INFO, "%s: Invalid initial response: %i",
319                         it->queueid, res);
320                 return(1);
321         }
322         config->features &= ~NOSSL;
323
324 #ifdef HAVE_CRYPTO
325         if ((config->features & SECURETRANS) != 0) {
326                 error = smtp_init_crypto(it, fd, config->features);
327                 if (error >= 0)
328                         syslog(LOG_INFO, "%s: SSL initialization successful",
329                                 it->queueid);
330                 else
331                         goto out;
332         }
333
334         /*
335          * If the user doesn't want STARTTLS, but SSL encryption, we
336          * have to enable SSL first, then send EHLO
337          */
338         if (((config->features & STARTTLS) == 0) &&
339             ((config->features & SECURETRANS) != 0)) {
340                 send_remote_command(fd, "EHLO %s", hostname());
341                 if (read_remote(fd, 0, NULL) != 2) {
342                         syslog(LOG_ERR, "%s: remote delivery deferred: "
343                                " EHLO failed: %m", it->queueid);
344                         return (-1);
345                 }
346         }
347 #endif /* HAVE_CRYPTO */
348         if (((config->features & SECURETRANS) == 0)) {
349                 send_remote_command(fd, "EHLO %s", hostname());
350                 if (read_remote(fd, 0, NULL) != 2) {
351                         syslog(LOG_ERR, "%s: remote delivery deferred: "
352                                " EHLO failed: %m", it->queueid);
353                         return (-1);
354                 }
355         }
356
357         /*
358          * Use SMTP authentication if the user defined an entry for the remote
359          * or smarthost
360          */
361         SLIST_FOREACH(a, &authusers, next) {
362                 if (strcmp(a->host, host) == 0) {
363                         do_auth = 1;
364                         break;
365                 }
366         }
367
368         if (do_auth == 1) {
369                 /*
370                  * Check if the user wants plain text login without using
371                  * encryption.
372                  */
373                 syslog(LOG_INFO, "%s: Use SMTP authentication",
374                                 it->queueid);
375                 error = smtp_login(it, fd, a->login, a->password);
376                 if (error < 0) {
377                         syslog(LOG_ERR, "%s: remote delivery failed:"
378                                         " SMTP login failed: %m", it->queueid);
379                         return (-1);
380                 }
381                 /* SMTP login is not available, so try without */
382                 else if (error > 0)
383                         syslog(LOG_ERR, "%s: SMTP login not available."
384                                         " Try without", it->queueid);
385         }
386
387         send_remote_command(fd, "MAIL FROM:<%s>", it->sender);
388         if (read_remote(fd, 0, NULL) != 2) {
389                 syslog(LOG_ERR, "%s: remote delivery deferred:"
390                        " MAIL FROM failed: %m", it->queueid);
391                 return (1);
392         }
393
394         send_remote_command(fd, "RCPT TO:<%s>", it->addr);
395         if (read_remote(fd, 0, NULL) != 2) {
396                 syslog(LOG_ERR, "%s: remote delivery deferred:"
397                                 " RCPT TO failed: %m", it->queueid);
398                 return (1);
399         }
400
401         send_remote_command(fd, "DATA");
402         if (read_remote(fd, 0, NULL) != 3) {
403                 syslog(LOG_ERR, "%s: remote delivery deferred:"
404                        " DATA failed: %m", it->queueid);
405                 return (1);
406         }
407
408         if (fseek(it->queuef, it->hdrlen, SEEK_SET) != 0) {
409                 syslog(LOG_ERR, "%s: remote delivery deferred: cannot seek: %m",
410                        it->queueid);
411                 return (1);
412         }
413
414         while (!feof(it->queuef)) {
415                 if (fgets(line, sizeof(line), it->queuef) == NULL)
416                         break;
417                 linelen = strlen(line);
418                 if (linelen == 0 || line[linelen - 1] != '\n') {
419                         syslog(LOG_CRIT, "%s: remote delivery failed:"
420                                 "corrupted queue file", it->queueid);
421                         *errmsg = "corrupted queue file";
422                         error = -1;
423                         goto out;
424                 }
425
426                 /* Remove trailing \n's and escape leading dots */
427                 trim_line(line);
428
429                 /*
430                  * If the first character is a dot, we escape it so the line
431                  * length increases
432                 */
433                 if (line[0] == '.')
434                         linelen++;
435
436                 if (send_remote_command(fd, "%s", line) != (ssize_t)linelen+1) {
437                         syslog(LOG_ERR, "%s: remote delivery deferred: "
438                                 "write error", it->queueid);
439                         error = 1;
440                         goto out;
441                 }
442         }
443
444         send_remote_command(fd, ".");
445         if (read_remote(fd, 0, NULL) != 2) {
446                 syslog(LOG_ERR, "%s: remote delivery deferred: %m",
447                        it->queueid);
448                 return (1);
449         }
450
451         send_remote_command(fd, "QUIT");
452         if (read_remote(fd, 0, NULL) != 2) {
453                 syslog(LOG_ERR, "%s: remote delivery deferred: "
454                        "QUIT failed: %m", it->queueid);
455                 return (1);
456         }
457 out:
458
459         close(fd);
460         return (error);
461 }
462