Merge branch 'vendor/LIBARCHIVE'
[dragonfly.git] / libexec / dma / crypto.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
36 #include <openssl/x509.h>
37 #include <openssl/md5.h>
38 #include <openssl/ssl.h>
39 #include <openssl/err.h>
40 #include <openssl/pem.h>
41 #include <openssl/rand.h>
42
43 #include <syslog.h>
44
45 #include "dma.h"
46
47 static int
48 init_cert_file(SSL_CTX *ctx, const char *path)
49 {
50         int error;
51
52         /* Load certificate into ctx */
53         error = SSL_CTX_use_certificate_chain_file(ctx, path);
54         if (error < 1) {
55                 syslog(LOG_ERR, "SSL: Cannot load certificate `%s': %s", path, ssl_errstr());
56                 return (-1);
57         }
58
59         /* Add private key to ctx */
60         error = SSL_CTX_use_PrivateKey_file(ctx, path, SSL_FILETYPE_PEM);
61         if (error < 1) {
62                 syslog(LOG_ERR, "SSL: Cannot load private key `%s': %s", path, ssl_errstr());
63                 return (-1);
64         }
65
66         /*
67          * Check the consistency of a private key with the corresponding
68          * certificate
69          */
70         error = SSL_CTX_check_private_key(ctx);
71         if (error < 1) {
72                 syslog(LOG_ERR, "SSL: Cannot check private key: %s", ssl_errstr());
73                 return (-1);
74         }
75
76         return (0);
77 }
78
79 int
80 smtp_init_crypto(int fd, int feature)
81 {
82         SSL_CTX *ctx = NULL;
83         const SSL_METHOD *meth = NULL;
84         X509 *cert;
85         int error;
86
87         /* XXX clean up on error/close */
88         /* Init SSL library */
89         SSL_library_init();
90         SSL_load_error_strings();
91
92         meth = TLSv1_client_method();
93
94         ctx = SSL_CTX_new(meth);
95         if (ctx == NULL) {
96                 syslog(LOG_WARNING, "remote delivery deferred: SSL init failed: %s", ssl_errstr());
97                 return (1);
98         }
99
100         /* User supplied a certificate */
101         if (config.certfile != NULL) {
102                 error = init_cert_file(ctx, config.certfile);
103                 if (error) {
104                         syslog(LOG_WARNING, "remote delivery deferred");
105                         return (1);
106                 }
107         }
108
109         /*
110          * If the user wants STARTTLS, we have to send EHLO here
111          */
112         if (((feature & SECURETRANS) != 0) &&
113              (feature & STARTTLS) != 0) {
114                 /* TLS init phase, disable SSL_write */
115                 config.features |= NOSSL;
116
117                 send_remote_command(fd, "EHLO %s", hostname());
118                 if (read_remote(fd, 0, NULL) == 2) {
119                         send_remote_command(fd, "STARTTLS");
120                         if (read_remote(fd, 0, NULL) != 2) {
121                                 if ((feature & TLS_OPP) == 0) {
122                                         syslog(LOG_ERR, "remote delivery deferred: STARTTLS not available: %s", neterr);
123                                         return (1);
124                                 } else {
125                                         syslog(LOG_INFO, "in opportunistic TLS mode, STARTTLS not available: %s", neterr);
126                                         return (0);
127                                 }
128                         }
129                 }
130                 /* End of TLS init phase, enable SSL_write/read */
131                 config.features &= ~NOSSL;
132         }
133
134         config.ssl = SSL_new(ctx);
135         if (config.ssl == NULL) {
136                 syslog(LOG_NOTICE, "remote delivery deferred: SSL struct creation failed: %s",
137                        ssl_errstr());
138                 return (1);
139         }
140
141         /* Set ssl to work in client mode */
142         SSL_set_connect_state(config.ssl);
143
144         /* Set fd for SSL in/output */
145         error = SSL_set_fd(config.ssl, fd);
146         if (error == 0) {
147                 syslog(LOG_NOTICE, "remote delivery deferred: SSL set fd failed: %s",
148                        ssl_errstr());
149                 return (1);
150         }
151
152         /* Open SSL connection */
153         error = SSL_connect(config.ssl);
154         if (error < 0) {
155                 syslog(LOG_ERR, "remote delivery deferred: SSL handshake failed fatally: %s",
156                        ssl_errstr());
157                 return (1);
158         }
159
160         /* Get peer certificate */
161         cert = SSL_get_peer_certificate(config.ssl);
162         if (cert == NULL) {
163                 syslog(LOG_WARNING, "remote delivery deferred: Peer did not provide certificate: %s",
164                        ssl_errstr());
165         }
166         X509_free(cert);
167
168         return (0);
169 }
170
171 /*
172  * hmac_md5() taken out of RFC 2104.  This RFC was written by H. Krawczyk,
173  * M. Bellare and R. Canetti.
174  *
175  * text      pointer to data stream
176  * text_len  length of data stream
177  * key       pointer to authentication key
178  * key_len   length of authentication key
179  * digest    caller digest to be filled int
180  */
181 void
182 hmac_md5(unsigned char *text, int text_len, unsigned char *key, int key_len,
183     unsigned char* digest)
184 {
185         MD5_CTX context;
186         unsigned char k_ipad[65];    /* inner padding -
187                                       * key XORd with ipad
188                                       */
189         unsigned char k_opad[65];    /* outer padding -
190                                       * key XORd with opad
191                                       */
192         unsigned char tk[16];
193         int i;
194         /* if key is longer than 64 bytes reset it to key=MD5(key) */
195         if (key_len > 64) {
196
197                 MD5_CTX      tctx;
198
199                 MD5_Init(&tctx);
200                 MD5_Update(&tctx, key, key_len);
201                 MD5_Final(tk, &tctx);
202
203                 key = tk;
204                 key_len = 16;
205         }
206
207         /*
208          * the HMAC_MD5 transform looks like:
209          *
210          * MD5(K XOR opad, MD5(K XOR ipad, text))
211          *
212          * where K is an n byte key
213          * ipad is the byte 0x36 repeated 64 times
214          *
215          * opad is the byte 0x5c repeated 64 times
216          * and text is the data being protected
217          */
218
219         /* start out by storing key in pads */
220         bzero( k_ipad, sizeof k_ipad);
221         bzero( k_opad, sizeof k_opad);
222         bcopy( key, k_ipad, key_len);
223         bcopy( key, k_opad, key_len);
224
225         /* XOR key with ipad and opad values */
226         for (i=0; i<64; i++) {
227                 k_ipad[i] ^= 0x36;
228                 k_opad[i] ^= 0x5c;
229         }
230         /*
231          * perform inner MD5
232          */
233         MD5_Init(&context);                   /* init context for 1st
234                                               * pass */
235         MD5_Update(&context, k_ipad, 64);     /* start with inner pad */
236         MD5_Update(&context, text, text_len); /* then text of datagram */
237         MD5_Final(digest, &context);          /* finish up 1st pass */
238         /*
239          * perform outer MD5
240          */
241         MD5_Init(&context);                   /* init context for 2nd
242                                               * pass */
243         MD5_Update(&context, k_opad, 64);     /* start with outer pad */
244         MD5_Update(&context, digest, 16);     /* then results of 1st
245                                               * hash */
246         MD5_Final(digest, &context);          /* finish up 2nd pass */
247 }
248
249 /*
250  * CRAM-MD5 authentication
251  */
252 int
253 smtp_auth_md5(int fd, char *login, char *password)
254 {
255         unsigned char digest[BUF_SIZE];
256         char buffer[BUF_SIZE], ascii_digest[33];
257         char *temp;
258         int len, i;
259         static char hextab[] = "0123456789abcdef";
260
261         temp = calloc(BUF_SIZE, 1);
262         memset(buffer, 0, sizeof(buffer));
263         memset(digest, 0, sizeof(digest));
264         memset(ascii_digest, 0, sizeof(ascii_digest));
265
266         /* Send AUTH command according to RFC 2554 */
267         send_remote_command(fd, "AUTH CRAM-MD5");
268         if (read_remote(fd, sizeof(buffer), buffer) != 3) {
269                 syslog(LOG_DEBUG, "smarthost authentication:"
270                        " AUTH cram-md5 not available: %s", neterr);
271                 /* if cram-md5 is not available */
272                 free(temp);
273                 return (-1);
274         }
275
276         /* skip 3 char status + 1 char space */
277         base64_decode(buffer + 4, temp);
278         hmac_md5((unsigned char *)temp, strlen(temp),
279                  (unsigned char *)password, strlen(password), digest);
280         free(temp);
281
282         ascii_digest[32] = 0;
283         for (i = 0; i < 16; i++) {
284                 ascii_digest[2*i] = hextab[digest[i] >> 4];
285                 ascii_digest[2*i+1] = hextab[digest[i] & 15];
286         }
287
288         /* prepare answer */
289         snprintf(buffer, BUF_SIZE, "%s %s", login, ascii_digest);
290
291         /* encode answer */
292         len = base64_encode(buffer, strlen(buffer), &temp);
293         if (len < 0) {
294                 syslog(LOG_ERR, "can not encode auth reply: %m");
295                 return (-1);
296         }
297
298         /* send answer */
299         send_remote_command(fd, "%s", temp);
300         free(temp);
301         if (read_remote(fd, 0, NULL) != 2) {
302                 syslog(LOG_WARNING, "remote delivery deferred:"
303                                 " AUTH cram-md5 failed: %s", neterr);
304                 return (-2);
305         }
306
307         return (0);
308 }