Line 0
Link Here
|
|
|
1 |
/*++ |
2 |
/* NAME |
3 |
/* pfixtls |
4 |
/* SUMMARY |
5 |
/* interface to openssl routines |
6 |
/* SYNOPSIS |
7 |
/* #include <pfixtls.h> |
8 |
/* |
9 |
/* const long scache_db_version; |
10 |
/* const long openssl_version; |
11 |
/* |
12 |
/* int pfixtls_serverengine; |
13 |
/* |
14 |
/* int pfixtls_clientengine; |
15 |
/* |
16 |
/* int pfixtls_timed_read(fd, buf, len, timeout, unused_context) |
17 |
/* int fd; |
18 |
/* void *buf; |
19 |
/* unsigned len; |
20 |
/* int timeout; |
21 |
/* void *context; |
22 |
/* |
23 |
/* int pfixtls_timed_write(fd, buf, len, timeout, unused_context); |
24 |
/* int fd; |
25 |
/* void *buf; |
26 |
/* unsigned len; |
27 |
/* int timeout; |
28 |
/* void *context; |
29 |
/* |
30 |
/* int pfixtls_init_serverengine(verifydepth, askcert); |
31 |
/* int verifydepth; |
32 |
/* int askcert; |
33 |
/* |
34 |
/* int pfixtls_start_servertls(stream, timeout, peername, peeraddr, |
35 |
/* tls_info, requirecert); |
36 |
/* VSTREAM *stream; |
37 |
/* int timeout; |
38 |
/* const char *peername; |
39 |
/* const char *peeraddr; |
40 |
/* tls_info_t *tls_info; |
41 |
/* int requirecert; |
42 |
/* |
43 |
/* int pfixtls_stop_servertls(stream, failure, tls_info); |
44 |
/* VSTREAM *stream; |
45 |
/* int failure; |
46 |
/* tls_info_t *tls_info; |
47 |
/* |
48 |
/* int pfixtls_init_clientengine(verifydepth); |
49 |
/* int verifydepth; |
50 |
/* |
51 |
/* int pfixtls_start_clienttls(stream, timeout, peername, peeraddr, |
52 |
/* tls_info); |
53 |
/* VSTREAM *stream; |
54 |
/* int timeout; |
55 |
/* const char *peername; |
56 |
/* const char *peeraddr; |
57 |
/* tls_info_t *tls_info; |
58 |
/* |
59 |
/* int pfixtls_stop_clienttls(stream, failure, tls_info); |
60 |
/* VSTREAM *stream; |
61 |
/* int failure; |
62 |
/* tls_info_t *tls_info; |
63 |
/* |
64 |
/* DESCRIPTION |
65 |
/* This module is the interface between Postfix and the OpenSSL library. |
66 |
/* |
67 |
/* pfixtls_timed_read() reads the requested number of bytes calling |
68 |
/* SSL_read(). pfixtls_time_read() will only be called indirect |
69 |
/* as a VSTREAM_FN function. |
70 |
/* pfixtls_timed_write() is the corresponding write function. |
71 |
/* |
72 |
/* pfixtls_init_serverengine() is called once when smtpd is started |
73 |
/* in order to initialize as much of the TLS stuff as possible. |
74 |
/* The certificate handling is also decided during the setup phase, |
75 |
/* so that a peer specific handling is not possible. |
76 |
/* |
77 |
/* pfixtls_init_clientengine() is the corresponding function called |
78 |
/* in smtp. Here we take the peer's (server's) certificate in any |
79 |
/* case. |
80 |
/* |
81 |
/* pfixtls_start_servertls() activates the TLS feature for the VSTREAM |
82 |
/* passed as argument. We expect that all buffers are flushed and the |
83 |
/* TLS handshake can begin immediately. Information about the peer |
84 |
/* is stored into the tls_info structure passed as argument. |
85 |
/* |
86 |
/* pfixtls_stop_servertls() sends the "close notify" alert via |
87 |
/* SSL_shutdown() to the peer and resets all connection specific |
88 |
/* TLS data. As RFC2487 does not specify a seperate shutdown, it |
89 |
/* is supposed that the underlying TCP connection is shut down |
90 |
/* immediately afterwards, so we don't care about additional data |
91 |
/* coming through the channel. |
92 |
/* If the failure flag is set, the session is cleared from the cache. |
93 |
/* |
94 |
/* pfixtls_start_clienttls() and pfixtls_stop_clienttls() are the |
95 |
/* corresponding functions for smtp. |
96 |
/* |
97 |
/* Once the TLS connection is initiated, information about the TLS |
98 |
/* state is available via the tls_info structure: |
99 |
/* protocol holds the protocol name (SSLv2, SSLv3, TLSv1), |
100 |
/* tls_info->cipher_name the cipher name (e.g. RC4/MD5), |
101 |
/* tls_info->cipher_usebits the number of bits actually used (e.g. 40), |
102 |
/* tls_info->cipher_algbits the number of bits the algorithm is based on |
103 |
/* (e.g. 128). |
104 |
/* The last two values may be different when talking to a crippled |
105 |
/* - ahem - export controled peer (e.g. 40/128). |
106 |
/* |
107 |
/* The status of the peer certificate verification is available in |
108 |
/* pfixtls_peer_verified. It is set to 1, when the certificate could |
109 |
/* be verified. |
110 |
/* If the peer offered a certifcate, part of the certificate data are |
111 |
/* available as: |
112 |
/* tls_info->peer_subject X509v3-oneline with the DN of the peer |
113 |
/* tls_info->peer_CN extracted CommonName of the peer |
114 |
/* tls_info->peer_issuer X509v3-oneline with the DN of the issuer |
115 |
/* tls_info->peer_CN extracted CommonName of the issuer |
116 |
/* tls_info->PEER_FINGERPRINT fingerprint of the certificate |
117 |
/* |
118 |
/* DESCRIPTION (SESSION CACHING) |
119 |
/* In order to achieve high performance when using a lot of connections |
120 |
/* with TLS, session caching is implemented. It reduces both the CPU load |
121 |
/* (less cryptograpic operations) and the network load (the amount of |
122 |
/* certificate data exchanged is reduced). |
123 |
/* Since postfix uses a setup of independent processes for receiving |
124 |
/* and sending email, the processes must exchange the session information. |
125 |
/* Several connections at the same time between the identical peers can |
126 |
/* occur, so uniqueness and race conditions have to be taken into |
127 |
/* account. |
128 |
/* I have checked both Apache-SSL (Ben Laurie), using a seperate "gcache" |
129 |
/* process and Apache mod_ssl (Ralf S. Engelshall), using shared memory |
130 |
/* between several identical processes spawned from one parent. |
131 |
/* |
132 |
/* Postfix/TLS uses a database approach based on the internal "dict" |
133 |
/* interface. Since the session cache information is approximately |
134 |
/* 1300 bytes binary data, it will not fit into the dbm/ndbm model. |
135 |
/* It also needs write access to the database, ruling out most other |
136 |
/* interface, leaving Berkeley DB, which however cannot handle concurrent |
137 |
/* access by several processes. Hence a modified SDBM (public domain DBM) |
138 |
/* with enhanced buffer size is used and concurrent write capability |
139 |
/* is used. SDBM is part of Postfix/TLS. |
140 |
/* |
141 |
/* Realization: |
142 |
/* Both (client and server) session cache are realized by individual |
143 |
/* cache databases. A common database would not make sense, since the |
144 |
/* key criteria are different (session ID for server, peername for |
145 |
/* client). |
146 |
/* |
147 |
/* Server side: |
148 |
/* Session created by OpenSSL have a 32 byte session id, yielding a |
149 |
/* 64 char file name. I consider these sessions to be unique. If they |
150 |
/* are not, the last session will win, overwriting the older one in |
151 |
/* the database. Remember: everything that is lost is a temporary |
152 |
/* information and not more than a renegotiation will happen. |
153 |
/* Originating from the same client host, several sessions can come |
154 |
/* in (e.g. from several users sending mail with Netscape at the same |
155 |
/* time), so the session id is the correct identifier; the hostname |
156 |
/* is of no importance, here. |
157 |
/* |
158 |
/* Client side: |
159 |
/* We cannot recall sessions based on their session id, because we would |
160 |
/* have to check every session on disk for a matching server name, so |
161 |
/* the lookup has to be done based on the FQDN of the peer (receiving |
162 |
/* host). |
163 |
/* With regard to uniqueness, we might experience several open connections |
164 |
/* to the same server at the same time. This is even very likely to |
165 |
/* happen, since we might have several mails for the same destination |
166 |
/* in the queue, when a queue run is started. So several smtp's might |
167 |
/* negotiate sessions at the same time. We can however only save one |
168 |
/* session for one host. |
169 |
/* Like on the server side, the "last write" wins. The reason is |
170 |
/* quite simple. If we don't want to overwrite old sessions, an old |
171 |
/* session file will just stay in place until it is expired. In the |
172 |
/* meantime we would lose "fresh" session however. So we will keep the |
173 |
/* fresh one instead to avoid unnecessary renegotiations. |
174 |
/* |
175 |
/* Session lifetime: |
176 |
/* RFC2246 recommends a session lifetime of less than 24 hours. The |
177 |
/* default is 300 seconds (5 minutes) for OpenSSL and is also used |
178 |
/* this way in e.g. mod_ssl. The typical usage for emails might be |
179 |
/* humans typing in emails and sending them, which might take just |
180 |
/* a while, so I think 3600 seconds (1 hour) is a good compromise. |
181 |
/* If the environment is save (the cached session contains secret |
182 |
/* key data), one might even consider using a longer timeout. Anyway, |
183 |
/* since everlasting sessions must be avoided, the session timeout |
184 |
/* is done based on the creation date of the session and so each |
185 |
/* session will timeout eventually. |
186 |
/* |
187 |
/* Connection failures: |
188 |
/* RFC2246 requires us to remove sessions if something went wrong. |
189 |
/* Since the in-memory session cache of other smtp[d] processes cannot |
190 |
/* be controlled by simple means, we completely rely on the disc |
191 |
/* based session caching and remove all sessions from memory after |
192 |
/* connection closure. |
193 |
/* |
194 |
/* Cache cleanup: |
195 |
/* Since old entries have to be removed from the session cache, a |
196 |
/* cleanup process is needed that runs through the collected session |
197 |
/* files on regular basis. The task is performed by tlsmgr based on |
198 |
/* the timestamp created by pfixtls and included in the saved session, |
199 |
/* so that tlsmgr has not to care about the SSL_SESSION internal data. |
200 |
/* |
201 |
/* BUGS |
202 |
/* The memory allocation policy of the OpenSSL library is not well |
203 |
/* documented, especially when loading sessions from disc. Hence there |
204 |
/* might be memory leaks. |
205 |
/* |
206 |
/* LICENSE |
207 |
/* AUTHOR(S) |
208 |
/* Lutz Jaenicke |
209 |
/* BTU Cottbus |
210 |
/* Allgemeine Elektrotechnik |
211 |
/* Universitaetsplatz 3-4 |
212 |
/* D-03044 Cottbus, Germany |
213 |
/*--*/ |
214 |
|
215 |
/* System library. */ |
216 |
|
217 |
#include <sys_defs.h> |
218 |
#include <sys/types.h> |
219 |
#include <sys/stat.h> |
220 |
#include <sys/time.h> /* gettimeofday, not in POSIX */ |
221 |
#include <unistd.h> |
222 |
#include <stdio.h> |
223 |
#include <string.h> |
224 |
#include <errno.h> |
225 |
#include <ctype.h> |
226 |
|
227 |
/* Utility library. */ |
228 |
|
229 |
#include <iostuff.h> |
230 |
#include <mymalloc.h> |
231 |
#include <vstring.h> |
232 |
#include <vstream.h> |
233 |
#include <dict.h> |
234 |
#include <myflock.h> |
235 |
#include <stringops.h> |
236 |
#include <msg.h> |
237 |
#include <connect.h> |
238 |
|
239 |
/* Application-specific. */ |
240 |
|
241 |
#include "mail_params.h" |
242 |
#include "pfixtls.h" |
243 |
|
244 |
#define STR vstring_str |
245 |
|
246 |
const tls_info_t tls_info_zero = { |
247 |
0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0 |
248 |
}; |
249 |
|
250 |
#ifdef HAS_SSL |
251 |
|
252 |
/* OpenSSL library. */ |
253 |
|
254 |
#include <openssl/lhash.h> |
255 |
#include <openssl/bn.h> |
256 |
#include <openssl/err.h> |
257 |
#include <openssl/pem.h> |
258 |
#include <openssl/x509.h> |
259 |
#include <openssl/rand.h> |
260 |
#include <openssl/ssl.h> |
261 |
|
262 |
/* We must keep some of the info available */ |
263 |
static const char hexcodes[] = "0123456789ABCDEF"; |
264 |
|
265 |
/* |
266 |
* When saving sessions, we want to make sure, that the lenght of the key |
267 |
* is somehow limited. When saving client sessions, the hostname is used |
268 |
* as key. According to HP-UX 10.20, MAXHOSTNAMELEN=64. Maybe new standards |
269 |
* will increase this value, but as this will break compatiblity with existing |
270 |
* implementations, we won't see this for long. We therefore choose a limit |
271 |
* of 64 bytes. |
272 |
* The length of the (TLS) session id can be up to 32 bytes according to |
273 |
* RFC2246, so it fits well into the 64bytes limit. |
274 |
*/ |
275 |
#define ID_MAXLENGTH 64 /* Max ID length in bytes */ |
276 |
|
277 |
/* |
278 |
* The session_id_context is set, such that the client knows which services |
279 |
* on a host share the same session information (on the postfix host may |
280 |
* as well run a TLS-enabled webserver. |
281 |
*/ |
282 |
static char server_session_id_context[] = "Postfix/TLS"; /* anything will do */ |
283 |
static int TLScontext_index = -1; |
284 |
static int TLSpeername_index = -1; |
285 |
static int do_dump = 0; |
286 |
static DH *dh_512 = NULL, *dh_1024 = NULL; |
287 |
static SSL_CTX *ctx = NULL; |
288 |
|
289 |
static int rand_exch_fd = -1; |
290 |
|
291 |
static DICT *scache_db = NULL; |
292 |
const long scache_db_version = 0x00000003L; |
293 |
const long openssl_version = OPENSSL_VERSION_NUMBER; |
294 |
|
295 |
|
296 |
int pfixtls_serverengine = 0; |
297 |
static int pfixtls_serveractive = 0; /* available or not */ |
298 |
|
299 |
int pfixtls_clientengine = 0; |
300 |
static int pfixtls_clientactive = 0; /* available or not */ |
301 |
|
302 |
/* |
303 |
* Define a maxlength for certificate onelines. The length is checked by |
304 |
* all routines when copying. |
305 |
*/ |
306 |
#define CCERT_BUFSIZ 256 |
307 |
|
308 |
typedef struct { |
309 |
SSL *con; |
310 |
BIO *internal_bio; /* postfix/TLS side of pair */ |
311 |
BIO *network_bio; /* netsork side of pair */ |
312 |
char peer_subject[CCERT_BUFSIZ]; |
313 |
char peer_issuer[CCERT_BUFSIZ]; |
314 |
char peer_CN[CCERT_BUFSIZ]; |
315 |
char issuer_CN[CCERT_BUFSIZ]; |
316 |
unsigned char md[EVP_MAX_MD_SIZE]; |
317 |
char fingerprint[EVP_MAX_MD_SIZE * 3]; |
318 |
char peername_save[129]; |
319 |
int enforce_verify_errors; |
320 |
int enforce_CN; |
321 |
} TLScontext_t; |
322 |
|
323 |
typedef struct { |
324 |
int pid; |
325 |
struct timeval tv; |
326 |
} randseed_t; |
327 |
|
328 |
static randseed_t randseed; |
329 |
|
330 |
/* |
331 |
* Finally some "backup" DH-Parameters to be loaded, if no parameters are |
332 |
* explicitely loaded from file. |
333 |
*/ |
334 |
static unsigned char dh512_p[] = { |
335 |
0x88, 0x3F, 0x00, 0xAF, 0xFC, 0x0C, 0x8A, 0xB8, 0x35, 0xCD, 0xE5, 0xC2, |
336 |
0x0F, 0x55, 0xDF, 0x06, 0x3F, 0x16, 0x07, 0xBF, 0xCE, 0x13, 0x35, 0xE4, |
337 |
0x1C, 0x1E, 0x03, 0xF3, 0xAB, 0x17, 0xF6, 0x63, 0x50, 0x63, 0x67, 0x3E, |
338 |
0x10, 0xD7, 0x3E, 0xB4, 0xEB, 0x46, 0x8C, 0x40, 0x50, 0xE6, 0x91, 0xA5, |
339 |
0x6E, 0x01, 0x45, 0xDE, 0xC9, 0xB1, 0x1F, 0x64, 0x54, 0xFA, 0xD9, 0xAB, |
340 |
0x4F, 0x70, 0xBA, 0x5B, |
341 |
}; |
342 |
|
343 |
static unsigned char dh512_g[] = { |
344 |
0x02, |
345 |
}; |
346 |
|
347 |
static unsigned char dh1024_p[] = { |
348 |
0xB0, 0xFE, 0xB4, 0xCF, 0xD4, 0x55, 0x07, 0xE7, 0xCC, 0x88, 0x59, 0x0D, |
349 |
0x17, 0x26, 0xC5, 0x0C, 0xA5, 0x4A, 0x92, 0x23, 0x81, 0x78, 0xDA, 0x88, |
350 |
0xAA, 0x4C, 0x13, 0x06, 0xBF, 0x5D, 0x2F, 0x9E, 0xBC, 0x96, 0xB8, 0x51, |
351 |
0x00, 0x9D, 0x0C, 0x0D, 0x75, 0xAD, 0xFD, 0x3B, 0xB1, 0x7E, 0x71, 0x4F, |
352 |
0x3F, 0x91, 0x54, 0x14, 0x44, 0xB8, 0x30, 0x25, 0x1C, 0xEB, 0xDF, 0x72, |
353 |
0x9C, 0x4C, 0xF1, 0x89, 0x0D, 0x68, 0x3F, 0x94, 0x8E, 0xA4, 0xFB, 0x76, |
354 |
0x89, 0x18, 0xB2, 0x91, 0x16, 0x90, 0x01, 0x99, 0x66, 0x8C, 0x53, 0x81, |
355 |
0x4E, 0x27, 0x3D, 0x99, 0xE7, 0x5A, 0x7A, 0xAF, 0xD5, 0xEC, 0xE2, 0x7E, |
356 |
0xFA, 0xED, 0x01, 0x18, 0xC2, 0x78, 0x25, 0x59, 0x06, 0x5C, 0x39, 0xF6, |
357 |
0xCD, 0x49, 0x54, 0xAF, 0xC1, 0xB1, 0xEA, 0x4A, 0xF9, 0x53, 0xD0, 0xDF, |
358 |
0x6D, 0xAF, 0xD4, 0x93, 0xE7, 0xBA, 0xAE, 0x9B, |
359 |
}; |
360 |
|
361 |
static unsigned char dh1024_g[] = { |
362 |
0x02, |
363 |
}; |
364 |
|
365 |
/* |
366 |
* DESCRIPTION: Keeping control of the network interface using BIO-pairs. |
367 |
* |
368 |
* When the TLS layer is active, all input/output must be filtered through |
369 |
* it. On the other hand to handle timeout conditions, full control over |
370 |
* the network socket must be kept. This rules out the "normal way" of |
371 |
* connecting the TLS layer directly to the socket. |
372 |
* The TLS layer is realized with a BIO-pair: |
373 |
* |
374 |
* postfix | TLS-engine |
375 |
* | | |
376 |
* +--------> SSL_operations() |
377 |
* | /\ || |
378 |
* | || \/ |
379 |
* | BIO-pair (internal_bio) |
380 |
* +--------< BIO-pair (network_bio) |
381 |
* | | |
382 |
* socket | |
383 |
* |
384 |
* The normal postfix operations connect to the SSL operations to send |
385 |
* and retrieve (cleartext) data. Inside the TLS-engine the data are converted |
386 |
* to/from TLS protocol. The TLS functionality itself is only connected to |
387 |
* the internal_bio and hence only has status information about this internal |
388 |
* interface. |
389 |
* Thus, if the SSL_operations() return successfully (SSL_ERROR_NONE) or want |
390 |
* to read (SSL_ERROR_WANT_READ) there may as well be data inside the buffering |
391 |
* BIO-pair. So whenever an SSL_operation() returns without a fatal error, |
392 |
* the BIO-pair internal buffer must be flushed to the network. |
393 |
* NOTE: This is especially true in the SSL_ERROR_WANT_READ case: the TLS-layer |
394 |
* might want to read handshake data, that will never come since its own |
395 |
* written data will only reach the peer after flushing the buffer! |
396 |
* |
397 |
* The BIO-pair buffer size has been set to 8192 bytes, this is an arbitrary |
398 |
* value that can hold more data than the typical PMTU, so that it does |
399 |
* not force the generation of packets smaller than necessary. |
400 |
* It is also larger than the default VSTREAM_BUFSIZE (4096, see vstream.h), |
401 |
* so that large write operations could be handled within one call. |
402 |
* The internal buffer in the network/network_bio handling layer has been |
403 |
* set to the same value, since this seems to be reasonable. The code is |
404 |
* however able to handle arbitrary values smaller or larger than the |
405 |
* buffer size in the BIO-pair. |
406 |
*/ |
407 |
|
408 |
const ssize_t BIO_bufsiz = 8192; |
409 |
|
410 |
/* |
411 |
* The interface layer between network and BIO-pair. The BIO-pair buffers |
412 |
* the data to/from the TLS layer. Hence, at any time, there may be data |
413 |
* in the buffer that must be written to the network. This writing has |
414 |
* highest priority because the handshake might fail otherwise. |
415 |
* Only then a read_request can be satisfied. |
416 |
*/ |
417 |
static int network_biopair_interop(int fd, int timeout, BIO *network_bio) |
418 |
{ |
419 |
int want_write; |
420 |
int num_write; |
421 |
int write_pos; |
422 |
int from_bio; |
423 |
int want_read; |
424 |
int num_read; |
425 |
int to_bio; |
426 |
#define NETLAYER_BUFFERSIZE 8192 |
427 |
char buffer[8192]; |
428 |
|
429 |
while ((want_write = BIO_ctrl_pending(network_bio)) > 0) { |
430 |
if (want_write > NETLAYER_BUFFERSIZE) |
431 |
want_write = NETLAYER_BUFFERSIZE; |
432 |
from_bio = BIO_read(network_bio, buffer, want_write); |
433 |
|
434 |
/* |
435 |
* Write the complete contents of the buffer. Since TLS performs |
436 |
* underlying handshaking, we cannot afford to leave the buffer |
437 |
* unflushed, as we could run into a deadlock trap (the peer |
438 |
* waiting for a final byte and we already waiting for his reply |
439 |
* in read position). |
440 |
*/ |
441 |
write_pos = 0; |
442 |
do { |
443 |
if (timeout > 0 && write_wait(fd, timeout) < 0) |
444 |
return (-1); |
445 |
num_write = write(fd, buffer + write_pos, from_bio - write_pos); |
446 |
if (num_write <= 0) |
447 |
return (-1); /* something happened to the socket */ |
448 |
write_pos += num_write; |
449 |
} while (write_pos < from_bio); |
450 |
} |
451 |
|
452 |
while ((want_read = BIO_ctrl_get_read_request(network_bio)) > 0) { |
453 |
if (want_read > NETLAYER_BUFFERSIZE) |
454 |
want_read = NETLAYER_BUFFERSIZE; |
455 |
if (timeout > 0 && read_wait(fd, timeout) < 0) |
456 |
return (-1); |
457 |
num_read = read(fd, buffer, want_read); |
458 |
if (num_read <= 0) |
459 |
return (-1); /* something happened to the socket */ |
460 |
to_bio = BIO_write(network_bio, buffer, num_read); |
461 |
if (to_bio != num_read) |
462 |
msg_fatal("to_bio != num_read"); |
463 |
} |
464 |
|
465 |
return (0); |
466 |
} |
467 |
|
468 |
static void pfixtls_print_errors(void); |
469 |
|
470 |
/* |
471 |
* Function to perform the handshake for SSL_accept(), SSL_connect(), |
472 |
* and SSL_shutdown() and perform the SSL_read(), SSL_write() operations. |
473 |
* Call the underlying network_biopair_interop-layer to make sure the |
474 |
* write buffer is flushed after every operation (that did not fail with |
475 |
* a fatal error). |
476 |
*/ |
477 |
static int do_tls_operation(int fd, int timeout, TLScontext_t *TLScontext, |
478 |
int (*hsfunc)(SSL *), |
479 |
int (*rfunc)(SSL *, void *, int), |
480 |
int (*wfunc)(SSL *, const void *, int), |
481 |
char *buf, int num) |
482 |
{ |
483 |
int status; |
484 |
int err; |
485 |
int retval = 0; |
486 |
int biop_retval; |
487 |
int done = 0; |
488 |
|
489 |
while (!done) { |
490 |
if (hsfunc) |
491 |
status = hsfunc(TLScontext->con); |
492 |
else if (rfunc) |
493 |
status = rfunc(TLScontext->con, buf, num); |
494 |
else |
495 |
status = wfunc(TLScontext->con, (const char *)buf, num); |
496 |
err = SSL_get_error(TLScontext->con, status); |
497 |
|
498 |
#if (OPENSSL_VERSION_NUMBER <= 0x0090581fL) |
499 |
/* |
500 |
* There is a bug up to and including OpenSSL-0.9.5a: if an error |
501 |
* occurs while checking the peers certificate due to some certificate |
502 |
* error (e.g. as happend with a RSA-padding error), the error is put |
503 |
* onto the error stack. If verification is not enforced, this error |
504 |
* should be ignored, but the error-queue is not cleared, so we |
505 |
* can find this error here. The bug has been fixed on May 28, 2000. |
506 |
* |
507 |
* This bug so far has only manifested as |
508 |
* 4800:error:0407006A:rsa routines:RSA_padding_check_PKCS1_type_1:block type is not 01:rsa_pk1.c:100: |
509 |
* 4800:error:04067072:rsa routines:RSA_EAY_PUBLIC_DECRYPT:padding check failed:rsa_eay.c:396: |
510 |
* 4800:error:0D079006:asn1 encoding routines:ASN1_verify:bad get asn1 object call:a_verify.c:109: |
511 |
* so that we specifically test for this error. We print the errors |
512 |
* to the logfile and automatically clear the error queue. Then we |
513 |
* retry to get another error code. We cannot do better, since we |
514 |
* can only retrieve the last entry of the error-queue without |
515 |
* actually cleaning it on the way. |
516 |
* |
517 |
* This workaround is secure, as verify_result is set to "failed" |
518 |
* anyway. |
519 |
*/ |
520 |
if (err == SSL_ERROR_SSL) { |
521 |
if (ERR_peek_error() == 0x0407006AL) { |
522 |
pfixtls_print_errors(); /* Keep information for the logfile */ |
523 |
msg_info("OpenSSL <= 0.9.5a workaround called: certificate errors ignored"); |
524 |
err = SSL_get_error(TLScontext->con, status); |
525 |
} |
526 |
} |
527 |
#endif |
528 |
|
529 |
switch (err) { |
530 |
case SSL_ERROR_NONE: /* success */ |
531 |
retval = status; |
532 |
done = 1; /* no break, flush buffer before */ |
533 |
/* leaving */ |
534 |
case SSL_ERROR_WANT_WRITE: |
535 |
case SSL_ERROR_WANT_READ: |
536 |
biop_retval = network_biopair_interop(fd, timeout, |
537 |
TLScontext->network_bio); |
538 |
if (biop_retval < 0) |
539 |
return (-1); /* fatal network error */ |
540 |
break; |
541 |
case SSL_ERROR_ZERO_RETURN: /* connection was closed cleanly */ |
542 |
case SSL_ERROR_SYSCALL: |
543 |
case SSL_ERROR_SSL: |
544 |
default: |
545 |
retval = status; |
546 |
done = 1; |
547 |
; |
548 |
} |
549 |
}; |
550 |
return retval; |
551 |
} |
552 |
|
553 |
int pfixtls_timed_read(int fd, void *buf, unsigned buf_len, int timeout, |
554 |
void *context) |
555 |
{ |
556 |
int i; |
557 |
int ret; |
558 |
char mybuf[40]; |
559 |
char *mybuf2; |
560 |
TLScontext_t *TLScontext; |
561 |
|
562 |
TLScontext = (TLScontext_t *)context; |
563 |
if (!TLScontext) |
564 |
msg_fatal("Called tls_timed_read() without TLS-context"); |
565 |
|
566 |
ret = do_tls_operation(fd, timeout, TLScontext, NULL, SSL_read, NULL, |
567 |
(char *)buf, buf_len); |
568 |
if ((pfixtls_serveractive && var_smtpd_tls_loglevel >= 4) || |
569 |
(pfixtls_clientactive && var_smtp_tls_loglevel >= 4)) { |
570 |
mybuf2 = (char *) buf; |
571 |
if (ret > 0) { |
572 |
i = 0; |
573 |
while ((i < 39) && (i < ret) && (mybuf2[i] != 0)) { |
574 |
mybuf[i] = mybuf2[i]; |
575 |
i++; |
576 |
} |
577 |
mybuf[i] = '\0'; |
578 |
msg_info("Read %d chars: %s", ret, mybuf); |
579 |
} |
580 |
} |
581 |
return (ret); |
582 |
} |
583 |
|
584 |
int pfixtls_timed_write(int fd, void *buf, unsigned len, int timeout, |
585 |
void *context) |
586 |
{ |
587 |
int i; |
588 |
char mybuf[40]; |
589 |
char *mybuf2; |
590 |
TLScontext_t *TLScontext; |
591 |
|
592 |
TLScontext = (TLScontext_t *)context; |
593 |
if (!TLScontext) |
594 |
msg_fatal("Called tls_timed_write() without TLS-context"); |
595 |
|
596 |
if ((pfixtls_serveractive && var_smtpd_tls_loglevel >= 4) || |
597 |
(pfixtls_clientactive && var_smtp_tls_loglevel >= 4)) { |
598 |
mybuf2 = (char *) buf; |
599 |
if (len > 0) { |
600 |
i = 0; |
601 |
while ((i < 39) && (i < len) && (mybuf2[i] != 0)) { |
602 |
mybuf[i] = mybuf2[i]; |
603 |
i++; |
604 |
} |
605 |
mybuf[i] = '\0'; |
606 |
msg_info("Write %d chars: %s", len, mybuf); |
607 |
} |
608 |
} |
609 |
return (do_tls_operation(fd, timeout, TLScontext, NULL, NULL, SSL_write, |
610 |
buf, len)); |
611 |
} |
612 |
|
613 |
/* Add some more entropy to the pool by adding the actual time */ |
614 |
|
615 |
static void pfixtls_stir_seed(void) |
616 |
{ |
617 |
GETTIMEOFDAY(&randseed.tv); |
618 |
RAND_seed(&randseed, sizeof(randseed_t)); |
619 |
} |
620 |
|
621 |
/* |
622 |
* Skeleton taken from OpenSSL crypto/err/err_prn.c. |
623 |
* Query the error stack and print the error string into the logging facility. |
624 |
* Clear the error stack on the way. |
625 |
*/ |
626 |
|
627 |
static void pfixtls_print_errors(void) |
628 |
{ |
629 |
unsigned long l; |
630 |
char buf[256]; |
631 |
const char *file; |
632 |
const char *data; |
633 |
int line; |
634 |
int flags; |
635 |
unsigned long es; |
636 |
|
637 |
es = CRYPTO_thread_id(); |
638 |
while ((l = ERR_get_error_line_data(&file, &line, &data, &flags)) != 0) { |
639 |
if (flags & ERR_TXT_STRING) |
640 |
msg_info("%lu:%s:%s:%d:%s:", es, ERR_error_string(l, buf), |
641 |
file, line, data); |
642 |
else |
643 |
msg_info("%lu:%s:%s:%d:", es, ERR_error_string(l, buf), |
644 |
file, line); |
645 |
} |
646 |
} |
647 |
|
648 |
/* |
649 |
* Set up the cert things on the server side. We do need both the |
650 |
* private key (in key_file) and the cert (in cert_file). |
651 |
* Both files may be identical. |
652 |
* |
653 |
* This function is taken from OpenSSL apps/s_cb.c |
654 |
*/ |
655 |
|
656 |
static int set_cert_stuff(SSL_CTX * ctx, char *cert_file, char *key_file) |
657 |
{ |
658 |
if (cert_file != NULL) { |
659 |
if (SSL_CTX_use_certificate_chain_file(ctx, cert_file) <= 0) { |
660 |
msg_info("unable to get certificate from '%s'", cert_file); |
661 |
pfixtls_print_errors(); |
662 |
return (0); |
663 |
} |
664 |
if (key_file == NULL) |
665 |
key_file = cert_file; |
666 |
if (SSL_CTX_use_PrivateKey_file(ctx, key_file, |
667 |
SSL_FILETYPE_PEM) <= 0) { |
668 |
msg_info("unable to get private key from '%s'", key_file); |
669 |
pfixtls_print_errors(); |
670 |
return (0); |
671 |
} |
672 |
/* Now we know that a key and cert have been set against |
673 |
* the SSL context */ |
674 |
if (!SSL_CTX_check_private_key(ctx)) { |
675 |
msg_info("Private key does not match the certificate public key"); |
676 |
return (0); |
677 |
} |
678 |
} |
679 |
return (1); |
680 |
} |
681 |
|
682 |
/* taken from OpenSSL apps/s_cb.c */ |
683 |
|
684 |
static RSA *tmp_rsa_cb(SSL * s, int export, int keylength) |
685 |
{ |
686 |
static RSA *rsa_tmp = NULL; |
687 |
|
688 |
if (rsa_tmp == NULL) { |
689 |
rsa_tmp = RSA_generate_key(keylength, RSA_F4, NULL, NULL); |
690 |
} |
691 |
return (rsa_tmp); |
692 |
} |
693 |
|
694 |
|
695 |
static DH *get_dh512(void) |
696 |
{ |
697 |
DH *dh; |
698 |
|
699 |
if (dh_512 == NULL) { |
700 |
/* No parameter file loaded, use the compiled in parameters */ |
701 |
if ((dh = DH_new()) == NULL) return(NULL); |
702 |
dh->p = BN_bin2bn(dh512_p, sizeof(dh512_p), NULL); |
703 |
dh->g = BN_bin2bn(dh512_g, sizeof(dh512_g), NULL); |
704 |
if ((dh->p == NULL) || (dh->g == NULL)) |
705 |
return(NULL); |
706 |
else |
707 |
dh_512 = dh; |
708 |
} |
709 |
return (dh_512); |
710 |
} |
711 |
|
712 |
static DH *get_dh1024(void) |
713 |
{ |
714 |
DH *dh; |
715 |
|
716 |
if (dh_1024 == NULL) { |
717 |
/* No parameter file loaded, use the compiled in parameters */ |
718 |
if ((dh = DH_new()) == NULL) return(NULL); |
719 |
dh->p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), NULL); |
720 |
dh->g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), NULL); |
721 |
if ((dh->p == NULL) || (dh->g == NULL)) |
722 |
return(NULL); |
723 |
else |
724 |
dh_1024 = dh; |
725 |
} |
726 |
return (dh_1024); |
727 |
} |
728 |
|
729 |
/* partly inspired by mod_ssl */ |
730 |
|
731 |
static DH *tmp_dh_cb(SSL *s, int export, int keylength) |
732 |
{ |
733 |
DH *dh_tmp = NULL; |
734 |
|
735 |
if (export) { |
736 |
if (keylength == 512) |
737 |
dh_tmp = get_dh512(); /* export cipher */ |
738 |
else if (keylength == 1024) |
739 |
dh_tmp = get_dh1024(); /* normal */ |
740 |
else |
741 |
dh_tmp = get_dh1024(); /* not on-the-fly (too expensive) */ |
742 |
/* so use the 1024bit instead */ |
743 |
} |
744 |
else { |
745 |
dh_tmp = get_dh1024(); /* sign-only certificate */ |
746 |
} |
747 |
return (dh_tmp); |
748 |
} |
749 |
|
750 |
|
751 |
/* |
752 |
* Skeleton taken from OpenSSL apps/s_cb.c |
753 |
* |
754 |
* The verify_callback is called several times (directly or indirectly) from |
755 |
* crypto/x509/x509_vfy.c. It is called as a last check for several issues, |
756 |
* so this verify_callback() has the famous "last word". If it does return "0", |
757 |
* the handshake is immediately shut down and the connection fails. |
758 |
* |
759 |
* Postfix/TLS has two modes, the "use" mode and the "enforce" mode: |
760 |
* |
761 |
* In the "use" mode we never want the connection to fail just because there is |
762 |
* something wrong with the certificate (as we would have sent happily without |
763 |
* TLS). Therefore the return value is always "1". |
764 |
* |
765 |
* In the "enforce" mode we can shut down the connection as soon as possible. |
766 |
* In server mode TLS itself may be enforced (e.g. to protect passwords), |
767 |
* but certificates are optional. In this case the handshake must not fail |
768 |
* if we are unhappy with the certificate and return "1" in any case. |
769 |
* Only if a certificate is required the certificate must pass the verification |
770 |
* and failure to do so will result in immediate termination (return 0). |
771 |
* In the client mode the decision is made with respect to the peername |
772 |
* enforcement. If we strictly enforce the matching of the expected peername |
773 |
* the verification must fail immediatly on verification errors. We can also |
774 |
* immediatly check the expected peername, as it is the CommonName at level 0. |
775 |
* In all other cases, the problem is logged, so the SSL_get_verify_result() |
776 |
* will inform about the verification failure, but the handshake (and SMTP |
777 |
* connection will continue). |
778 |
* |
779 |
* The only error condition not handled inside the OpenSSL-Library is the |
780 |
* case of a too-long certificate chain, so we check inside verify_callback(). |
781 |
* We only take care of this problem, if "ok = 1", because otherwise the |
782 |
* verification already failed because of another problem and we don't want |
783 |
* to overwrite the other error message. And if the verification failed, |
784 |
* there is no such thing as "more failed", "most failed"... :-) |
785 |
*/ |
786 |
|
787 |
static int verify_callback(int ok, X509_STORE_CTX * ctx) |
788 |
{ |
789 |
char buf[256]; |
790 |
char *CN_lowercase; |
791 |
char *peername_left; |
792 |
X509 *err_cert; |
793 |
int err; |
794 |
int depth; |
795 |
int verify_depth; |
796 |
int hostname_matched; |
797 |
SSL *con; |
798 |
TLScontext_t *TLScontext; |
799 |
|
800 |
err_cert = X509_STORE_CTX_get_current_cert(ctx); |
801 |
err = X509_STORE_CTX_get_error(ctx); |
802 |
depth = X509_STORE_CTX_get_error_depth(ctx); |
803 |
|
804 |
con = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); |
805 |
TLScontext = SSL_get_ex_data(con, TLScontext_index); |
806 |
|
807 |
X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256); |
808 |
if (((pfixtls_serverengine) && (var_smtpd_tls_loglevel >= 2)) || |
809 |
((pfixtls_clientengine) && (var_smtp_tls_loglevel >= 2))) |
810 |
msg_info("Peer cert verify depth=%d %s", depth, buf); |
811 |
|
812 |
verify_depth = SSL_get_verify_depth(con); |
813 |
if (ok && (verify_depth >= 0) && (depth > verify_depth)) { |
814 |
ok = 0; |
815 |
err = X509_V_ERR_CERT_CHAIN_TOO_LONG; |
816 |
X509_STORE_CTX_set_error(ctx, err); |
817 |
} |
818 |
if (!ok) { |
819 |
msg_info("verify error:num=%d:%s", err, |
820 |
X509_verify_cert_error_string(err)); |
821 |
} |
822 |
|
823 |
if (ok && (depth == 0) && pfixtls_clientengine) { |
824 |
/* |
825 |
* Check out the name certified against the hostname expected. |
826 |
* In case it does not match, print an information about the result. |
827 |
* If a matching is enforced, bump out with a verification error |
828 |
* immediately. |
829 |
*/ |
830 |
buf[0] = '\0'; |
831 |
if (!X509_NAME_get_text_by_NID(X509_get_subject_name(err_cert), |
832 |
NID_commonName, buf, 256)) { |
833 |
msg_info("Could not parse server's subject CN"); |
834 |
pfixtls_print_errors(); |
835 |
} |
836 |
CN_lowercase = lowercase(buf); |
837 |
hostname_matched = 0; |
838 |
if (!strcmp(TLScontext->peername_save, CN_lowercase)) |
839 |
hostname_matched = 1; |
840 |
else if ((strlen(CN_lowercase) > 2) && |
841 |
(CN_lowercase[0] == '*') && (CN_lowercase[1] == '.')) { |
842 |
/* |
843 |
* Allow wildcard certificate matching. The proposed rules in |
844 |
* RFCs (2818: HTTP/TLS, 2830: LDAP/TLS) are different, RFC2874 |
845 |
* does not specify a rule, so here the strict rule is applied. |
846 |
* An asterisk '*' is allowed as the leftmost component and may |
847 |
* replace the left most part of the hostname. Matching is done |
848 |
* by removing '*.' from the wildcard name and the `name.` from |
849 |
* the peername and compare what is left. |
850 |
*/ |
851 |
peername_left = strchr(TLScontext->peername_save, '.'); |
852 |
if (peername_left) { |
853 |
if (!strcmp(peername_left + 1, CN_lowercase + 2)) |
854 |
hostname_matched = 1; |
855 |
} |
856 |
} |
857 |
|
858 |
if (!hostname_matched) { |
859 |
msg_info("Peer verification: CommonName in certificate does not match: %s != %s", CN_lowercase, TLScontext->peername_save); |
860 |
if (TLScontext->enforce_verify_errors && TLScontext->enforce_CN) { |
861 |
err = X509_V_ERR_CERT_REJECTED; |
862 |
X509_STORE_CTX_set_error(ctx, err); |
863 |
msg_info("Verify failure: Hostname mismatch"); |
864 |
ok = 0; |
865 |
} |
866 |
} |
867 |
} |
868 |
|
869 |
switch (ctx->error) { |
870 |
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: |
871 |
X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256); |
872 |
msg_info("issuer= %s", buf); |
873 |
break; |
874 |
case X509_V_ERR_CERT_NOT_YET_VALID: |
875 |
case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: |
876 |
msg_info("cert not yet valid"); |
877 |
break; |
878 |
case X509_V_ERR_CERT_HAS_EXPIRED: |
879 |
case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: |
880 |
msg_info("cert has expired"); |
881 |
break; |
882 |
} |
883 |
if (((pfixtls_serverengine) && (var_smtpd_tls_loglevel >= 2)) || |
884 |
((pfixtls_clientengine) && (var_smtp_tls_loglevel >= 2))) |
885 |
msg_info("verify return:%d", ok); |
886 |
|
887 |
if (TLScontext->enforce_verify_errors) |
888 |
return (ok); |
889 |
else |
890 |
return (1); |
891 |
} |
892 |
|
893 |
/* taken from OpenSSL apps/s_cb.c */ |
894 |
|
895 |
static void apps_ssl_info_callback(SSL * s, int where, int ret) |
896 |
{ |
897 |
char *str; |
898 |
int w; |
899 |
|
900 |
w = where & ~SSL_ST_MASK; |
901 |
|
902 |
if (w & SSL_ST_CONNECT) |
903 |
str = "SSL_connect"; |
904 |
else if (w & SSL_ST_ACCEPT) |
905 |
str = "SSL_accept"; |
906 |
else |
907 |
str = "undefined"; |
908 |
|
909 |
if (where & SSL_CB_LOOP) { |
910 |
msg_info("%s:%s", str, SSL_state_string_long(s)); |
911 |
} else if (where & SSL_CB_ALERT) { |
912 |
str = (where & SSL_CB_READ) ? "read" : "write"; |
913 |
if ((ret & 0xff) != SSL3_AD_CLOSE_NOTIFY) |
914 |
msg_info("SSL3 alert %s:%s:%s", str, |
915 |
SSL_alert_type_string_long(ret), |
916 |
SSL_alert_desc_string_long(ret)); |
917 |
} else if (where & SSL_CB_EXIT) { |
918 |
if (ret == 0) |
919 |
msg_info("%s:failed in %s", |
920 |
str, SSL_state_string_long(s)); |
921 |
else if (ret < 0) { |
922 |
msg_info("%s:error in %s", |
923 |
str, SSL_state_string_long(s)); |
924 |
} |
925 |
} |
926 |
} |
927 |
|
928 |
/* |
929 |
* taken from OpenSSL crypto/bio/b_dump.c, modified to save a lot of strcpy |
930 |
* and strcat by Matti Aarnio. |
931 |
*/ |
932 |
|
933 |
#define TRUNCATE |
934 |
#define DUMP_WIDTH 16 |
935 |
|
936 |
static int pfixtls_dump(const char *s, int len) |
937 |
{ |
938 |
int ret = 0; |
939 |
char buf[160 + 1]; |
940 |
char *ss; |
941 |
int i; |
942 |
int j; |
943 |
int rows; |
944 |
int trunc; |
945 |
unsigned char ch; |
946 |
|
947 |
trunc = 0; |
948 |
|
949 |
#ifdef TRUNCATE |
950 |
for (; (len > 0) && ((s[len - 1] == ' ') || (s[len - 1] == '\0')); len--) |
951 |
trunc++; |
952 |
#endif |
953 |
|
954 |
rows = (len / DUMP_WIDTH); |
955 |
if ((rows * DUMP_WIDTH) < len) |
956 |
rows++; |
957 |
|
958 |
for (i = 0; i < rows; i++) { |
959 |
buf[0] = '\0'; /* start with empty string */ |
960 |
ss = buf; |
961 |
|
962 |
sprintf(ss, "%04x ", i * DUMP_WIDTH); |
963 |
ss += strlen(ss); |
964 |
for (j = 0; j < DUMP_WIDTH; j++) { |
965 |
if (((i * DUMP_WIDTH) + j) >= len) { |
966 |
strcpy(ss, " "); |
967 |
} else { |
968 |
ch = ((unsigned char) *((char *) (s) + i * DUMP_WIDTH + j)) |
969 |
& 0xff; |
970 |
sprintf(ss, "%02x%c", ch, j == 7 ? '|' : ' '); |
971 |
ss += 3; |
972 |
} |
973 |
} |
974 |
ss += strlen(ss); |
975 |
*ss++ = ' '; |
976 |
for (j = 0; j < DUMP_WIDTH; j++) { |
977 |
if (((i * DUMP_WIDTH) + j) >= len) |
978 |
break; |
979 |
ch = ((unsigned char) *((char *) (s) + i * DUMP_WIDTH + j)) & 0xff; |
980 |
*ss++ = (((ch >= ' ') && (ch <= '~')) ? ch : '.'); |
981 |
if (j == 7) *ss++ = ' '; |
982 |
} |
983 |
*ss = 0; |
984 |
/* |
985 |
* if this is the last call then update the ddt_dump thing so that |
986 |
* we will move the selection point in the debug window |
987 |
*/ |
988 |
msg_info("%s", buf); |
989 |
ret += strlen(buf); |
990 |
} |
991 |
#ifdef TRUNCATE |
992 |
if (trunc > 0) { |
993 |
sprintf(buf, "%04x - <SPACES/NULS>\n", len + trunc); |
994 |
msg_info("%s", buf); |
995 |
ret += strlen(buf); |
996 |
} |
997 |
#endif |
998 |
return (ret); |
999 |
} |
1000 |
|
1001 |
|
1002 |
|
1003 |
/* taken from OpenSSL apps/s_cb.c */ |
1004 |
|
1005 |
static long bio_dump_cb(BIO * bio, int cmd, const char *argp, int argi, |
1006 |
long argl, long ret) |
1007 |
{ |
1008 |
if (!do_dump) |
1009 |
return (ret); |
1010 |
|
1011 |
if (cmd == (BIO_CB_READ | BIO_CB_RETURN)) { |
1012 |
msg_info("read from %08X [%08lX] (%d bytes => %ld (0x%X))", |
1013 |
(unsigned int)bio, (unsigned long)argp, argi, |
1014 |
ret, (unsigned int)ret); |
1015 |
pfixtls_dump(argp, (int) ret); |
1016 |
return (ret); |
1017 |
} else if (cmd == (BIO_CB_WRITE | BIO_CB_RETURN)) { |
1018 |
msg_info("write to %08X [%08lX] (%d bytes => %ld (0x%X))", |
1019 |
(unsigned int)bio, (unsigned long)argp, argi, |
1020 |
ret, (unsigned int)ret); |
1021 |
pfixtls_dump(argp, (int) ret); |
1022 |
} |
1023 |
return (ret); |
1024 |
} |
1025 |
|
1026 |
|
1027 |
/* |
1028 |
* Callback to retrieve a session from the external session cache. |
1029 |
*/ |
1030 |
static SSL_SESSION *get_session_cb(SSL *ssl, unsigned char *SessionID, |
1031 |
int length, int *copy) |
1032 |
{ |
1033 |
SSL_SESSION *session; |
1034 |
char idstring[2 * ID_MAXLENGTH + 1]; |
1035 |
int n; |
1036 |
int uselength; |
1037 |
int hex_length; |
1038 |
const char *session_hex; |
1039 |
pfixtls_scache_info_t scache_info; |
1040 |
unsigned char nibble, *data, *sess_data; |
1041 |
|
1042 |
if (length > ID_MAXLENGTH) |
1043 |
uselength = ID_MAXLENGTH; /* Limit length of ID */ |
1044 |
else |
1045 |
uselength = length; |
1046 |
|
1047 |
for(n=0 ; n < uselength ; n++) |
1048 |
sprintf(idstring + 2 * n, "%02x", SessionID[n]); |
1049 |
if (var_smtpd_tls_loglevel >= 3) |
1050 |
msg_info("Trying to reload Session from disc: %s", idstring); |
1051 |
|
1052 |
session = NULL; |
1053 |
|
1054 |
session_hex = dict_get(scache_db, idstring); |
1055 |
if (session_hex) { |
1056 |
hex_length = strlen(session_hex); |
1057 |
data = (unsigned char *)mymalloc(hex_length / 2); |
1058 |
if (!data) { |
1059 |
msg_info("could not allocate memory for session reload"); |
1060 |
return(NULL); |
1061 |
} |
1062 |
|
1063 |
memset(data, 0, hex_length / 2); |
1064 |
for (n = 0; n < hex_length; n++) { |
1065 |
if ((session_hex[n] >= '0') && (session_hex[n] <= '9')) |
1066 |
nibble = session_hex[n] - '0'; |
1067 |
else |
1068 |
nibble = session_hex[n] - 'A' + 10; |
1069 |
if (n % 2) |
1070 |
data[n / 2] |= nibble; |
1071 |
else |
1072 |
data[n / 2] |= (nibble << 4); |
1073 |
} |
1074 |
|
1075 |
/* |
1076 |
* First check the version numbers, since wrong session data might |
1077 |
* hit us hard (SEGFAULT). We also have to check for expiry. |
1078 |
*/ |
1079 |
memcpy(&scache_info, data, sizeof(pfixtls_scache_info_t)); |
1080 |
if ((scache_info.scache_db_version != scache_db_version) || |
1081 |
(scache_info.openssl_version != openssl_version) || |
1082 |
(scache_info.timestamp + var_smtpd_tls_scache_timeout < time(NULL))) |
1083 |
dict_del(scache_db, idstring); |
1084 |
else { |
1085 |
sess_data = data + sizeof(pfixtls_scache_info_t); |
1086 |
session = d2i_SSL_SESSION(NULL, &sess_data, |
1087 |
hex_length / 2 - sizeof(pfixtls_scache_info_t)); |
1088 |
if (!session) |
1089 |
pfixtls_print_errors(); |
1090 |
} |
1091 |
myfree((char *)data); |
1092 |
} |
1093 |
|
1094 |
if (session && (var_smtpd_tls_loglevel >= 3)) |
1095 |
msg_info("Successfully reloaded session from disc"); |
1096 |
|
1097 |
return (session); |
1098 |
} |
1099 |
|
1100 |
|
1101 |
static SSL_SESSION *load_clnt_session(const char *hostname, |
1102 |
int enforce_peername) |
1103 |
{ |
1104 |
SSL_SESSION *session = NULL; |
1105 |
char idstring[ID_MAXLENGTH + 1]; |
1106 |
int n; |
1107 |
int uselength; |
1108 |
int length; |
1109 |
int hex_length; |
1110 |
const char *session_hex; |
1111 |
pfixtls_scache_info_t scache_info; |
1112 |
unsigned char nibble, *data, *sess_data; |
1113 |
|
1114 |
length = strlen(hostname); |
1115 |
if (length > ID_MAXLENGTH) |
1116 |
uselength = ID_MAXLENGTH; /* Limit length of ID */ |
1117 |
else |
1118 |
uselength = length; |
1119 |
|
1120 |
for(n=0 ; n < uselength ; n++) |
1121 |
idstring[n] = tolower(hostname[n]); |
1122 |
idstring[uselength] = '\0'; |
1123 |
if (var_smtp_tls_loglevel >= 3) |
1124 |
msg_info("Trying to reload Session from disc: %s", idstring); |
1125 |
|
1126 |
session_hex = dict_get(scache_db, idstring); |
1127 |
if (session_hex) { |
1128 |
hex_length = strlen(session_hex); |
1129 |
data = (unsigned char *)mymalloc(hex_length / 2); |
1130 |
if (!data) { |
1131 |
msg_info("could not allocate memory for session reload"); |
1132 |
return(NULL); |
1133 |
} |
1134 |
|
1135 |
memset(data, 0, hex_length / 2); |
1136 |
for (n = 0; n < hex_length; n++) { |
1137 |
if ((session_hex[n] >= '0') && (session_hex[n] <= '9')) |
1138 |
nibble = session_hex[n] - '0'; |
1139 |
else |
1140 |
nibble = session_hex[n] - 'A' + 10; |
1141 |
if (n % 2) |
1142 |
data[n / 2] |= nibble; |
1143 |
else |
1144 |
data[n / 2] |= (nibble << 4); |
1145 |
} |
1146 |
|
1147 |
/* |
1148 |
* First check the version numbers, since wrong session data might |
1149 |
* hit us hard (SEGFAULT). We also have to check for expiry. |
1150 |
* When we enforce_peername, we may find an old session, that was |
1151 |
* saved when enforcement was not set. In this case the session will |
1152 |
* be removed and a fresh session will be negotiated. |
1153 |
*/ |
1154 |
memcpy(&scache_info, data, sizeof(pfixtls_scache_info_t)); |
1155 |
if ((scache_info.scache_db_version != scache_db_version) || |
1156 |
(scache_info.openssl_version != openssl_version) || |
1157 |
(scache_info.timestamp + var_smtpd_tls_scache_timeout < time(NULL))) |
1158 |
dict_del(scache_db, idstring); |
1159 |
else if (enforce_peername && (!scache_info.enforce_peername)) |
1160 |
dict_del(scache_db, idstring); |
1161 |
else { |
1162 |
sess_data = data + sizeof(pfixtls_scache_info_t); |
1163 |
session = d2i_SSL_SESSION(NULL, &sess_data, |
1164 |
hex_length / 2 - sizeof(time_t)); |
1165 |
strncpy(SSL_SESSION_get_ex_data(session, TLSpeername_index), |
1166 |
idstring, ID_MAXLENGTH + 1); |
1167 |
if (!session) |
1168 |
pfixtls_print_errors(); |
1169 |
} |
1170 |
myfree((char *)data); |
1171 |
} |
1172 |
|
1173 |
if (session && (var_smtp_tls_loglevel >= 3)) |
1174 |
msg_info("Successfully reloaded session from disc"); |
1175 |
|
1176 |
return (session); |
1177 |
} |
1178 |
|
1179 |
|
1180 |
static void create_client_lookup_id(char *idstring, char *hostname) |
1181 |
{ |
1182 |
int n, len, uselength; |
1183 |
|
1184 |
len = strlen(hostname); |
1185 |
if (len > ID_MAXLENGTH) |
1186 |
uselength = ID_MAXLENGTH; /* Limit length of ID */ |
1187 |
else |
1188 |
uselength = len; |
1189 |
|
1190 |
for (n = 0 ; n < uselength ; n++) |
1191 |
idstring[n] = tolower(hostname[n]); |
1192 |
idstring[uselength] = '\0'; |
1193 |
} |
1194 |
|
1195 |
|
1196 |
static void create_server_lookup_id(char *idstring, SSL_SESSION *session) |
1197 |
{ |
1198 |
int n, uselength; |
1199 |
|
1200 |
if (session->session_id_length > ID_MAXLENGTH) |
1201 |
uselength = ID_MAXLENGTH; /* Limit length of ID */ |
1202 |
else |
1203 |
uselength = session->session_id_length; |
1204 |
|
1205 |
for(n = 0; n < uselength ; n++) |
1206 |
sprintf(idstring + 2 * n, "%02x", session->session_id[n]); |
1207 |
} |
1208 |
|
1209 |
|
1210 |
static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *session) |
1211 |
{ |
1212 |
char idstring[2 * ID_MAXLENGTH + 1]; |
1213 |
char *hostname; |
1214 |
|
1215 |
if (pfixtls_clientengine) { |
1216 |
hostname = SSL_SESSION_get_ex_data(session, TLSpeername_index); |
1217 |
create_client_lookup_id(idstring, hostname); |
1218 |
if (var_smtp_tls_loglevel >= 3) |
1219 |
msg_info("Trying to remove session from disc: %s", idstring); |
1220 |
} |
1221 |
else { |
1222 |
create_server_lookup_id(idstring, session); |
1223 |
if (var_smtpd_tls_loglevel >= 3) |
1224 |
msg_info("Trying to remove session from disc: %s", idstring); |
1225 |
} |
1226 |
|
1227 |
if (scache_db) |
1228 |
dict_del(scache_db, idstring); |
1229 |
} |
1230 |
|
1231 |
|
1232 |
/* |
1233 |
* We need space to save the peername into the SSL_SESSION, as we must |
1234 |
* look up the external database for client sessions by peername, not |
1235 |
* by session id. We therefore allocate place for the peername string, |
1236 |
* when a new SSL_SESSION is generated. It is filled later. |
1237 |
*/ |
1238 |
static int new_peername_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, |
1239 |
int idx, long argl, void *argp) |
1240 |
{ |
1241 |
char *peername; |
1242 |
|
1243 |
peername = (char *)mymalloc(ID_MAXLENGTH + 1); |
1244 |
if (!peername) |
1245 |
return 0; |
1246 |
peername[0] = '\0'; /* initialize */ |
1247 |
return CRYPTO_set_ex_data(ad, idx, peername); |
1248 |
} |
1249 |
|
1250 |
/* |
1251 |
* When the SSL_SESSION is removed again, we must free the memory to avoid |
1252 |
* leaks. |
1253 |
*/ |
1254 |
static void free_peername_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, |
1255 |
int idx, long argl, void *argp) |
1256 |
{ |
1257 |
myfree(CRYPTO_get_ex_data(ad, idx)); |
1258 |
} |
1259 |
|
1260 |
/* |
1261 |
* Duplicate application data, when a SSL_SESSION is duplicated |
1262 |
*/ |
1263 |
static int dup_peername_func(CRYPTO_EX_DATA *to, CRYPTO_EX_DATA *from, |
1264 |
void *from_d, int idx, long argl, void *argp) |
1265 |
{ |
1266 |
char *peername_old, *peername_new; |
1267 |
|
1268 |
peername_old = CRYPTO_get_ex_data(from, idx); |
1269 |
peername_new = CRYPTO_get_ex_data(to, idx); |
1270 |
if (!peername_old || !peername_new) |
1271 |
return 0; |
1272 |
memcpy(peername_new, peername_old, ID_MAXLENGTH + 1); |
1273 |
return 1; |
1274 |
} |
1275 |
|
1276 |
|
1277 |
/* |
1278 |
* Save a new session to the external cache |
1279 |
*/ |
1280 |
static int new_session_cb(SSL *ssl, SSL_SESSION *session) |
1281 |
{ |
1282 |
char idstring[2 * ID_MAXLENGTH + 1]; |
1283 |
int n; |
1284 |
int dsize; |
1285 |
int len; |
1286 |
unsigned char *data, *sess_data; |
1287 |
pfixtls_scache_info_t scache_info; |
1288 |
char *hexdata, *hostname; |
1289 |
TLScontext_t *TLScontext; |
1290 |
|
1291 |
if (pfixtls_clientengine) { |
1292 |
TLScontext = SSL_get_ex_data(ssl, TLScontext_index); |
1293 |
hostname = TLScontext->peername_save; |
1294 |
create_client_lookup_id(idstring, hostname); |
1295 |
strncpy(SSL_SESSION_get_ex_data(session, TLSpeername_index), |
1296 |
hostname, ID_MAXLENGTH + 1); |
1297 |
/* |
1298 |
* Remember, whether peername matching was enforced when the session |
1299 |
* was created. If later enforce mode is enabled, we do not want to |
1300 |
* reuse a session that was not sufficiently checked. |
1301 |
*/ |
1302 |
scache_info.enforce_peername = |
1303 |
(TLScontext->enforce_verify_errors && TLScontext->enforce_CN); |
1304 |
|
1305 |
if (var_smtp_tls_loglevel >= 3) |
1306 |
msg_info("Trying to save session for hostID to disc: %s", idstring); |
1307 |
|
1308 |
#if (OPENSSL_VERSION_NUMBER < 0x00906011L) || (OPENSSL_VERSION_NUMBER == 0x00907000L) |
1309 |
/* |
1310 |
* Ugly Hack: OpenSSL before 0.9.6a does not store the verify |
1311 |
* result in sessions for the client side. |
1312 |
* We modify the session directly which is version specific, |
1313 |
* but this bug is version specific, too. |
1314 |
* |
1315 |
* READ: 0-09-06-01-1 = 0-9-6-a-beta1: all versions before |
1316 |
* beta1 have this bug, it has been fixed during development |
1317 |
* of 0.9.6a. The development version of 0.9.7 can have this |
1318 |
* bug, too. It has been fixed on 2000/11/29. |
1319 |
*/ |
1320 |
session->verify_result = SSL_get_verify_result(TLScontext->con); |
1321 |
#endif |
1322 |
|
1323 |
} |
1324 |
else { |
1325 |
create_server_lookup_id(idstring, session); |
1326 |
if (var_smtpd_tls_loglevel >= 3) |
1327 |
msg_info("Trying to save Session to disc: %s", idstring); |
1328 |
} |
1329 |
|
1330 |
|
1331 |
/* |
1332 |
* Get the session and convert it into some "database" useable form. |
1333 |
* First, get the length of the session to allocate the memory. |
1334 |
*/ |
1335 |
dsize = i2d_SSL_SESSION(session, NULL); |
1336 |
if (dsize < 0) { |
1337 |
msg_info("Could not access session"); |
1338 |
return 0; |
1339 |
} |
1340 |
data = (unsigned char *)mymalloc(dsize + sizeof(pfixtls_scache_info_t)); |
1341 |
if (!data) { |
1342 |
msg_info("could not allocate memory for SSL session"); |
1343 |
return 0; |
1344 |
} |
1345 |
|
1346 |
/* |
1347 |
* OpenSSL is not robust against wrong session data (might SEGFAULT), |
1348 |
* so we secure it against version ids (session cache structure as well |
1349 |
* as OpenSSL version). |
1350 |
*/ |
1351 |
scache_info.scache_db_version = scache_db_version; |
1352 |
scache_info.openssl_version = openssl_version; |
1353 |
|
1354 |
/* |
1355 |
* Put a timestamp, so that expiration can be checked without |
1356 |
* analyzing the session data itself. (We would need OpenSSL funtions, |
1357 |
* since the SSL_SESSION is a private structure.) |
1358 |
*/ |
1359 |
scache_info.timestamp = time(NULL); |
1360 |
|
1361 |
memcpy(data, &scache_info, sizeof(pfixtls_scache_info_t)); |
1362 |
sess_data = data + sizeof(pfixtls_scache_info_t); |
1363 |
|
1364 |
/* |
1365 |
* Now, obtain the session. Unfortunately, it is binary and dict_update |
1366 |
* cannot handle binary data (it could contain '\0' in it) directly. |
1367 |
* To save memory we could use base64 encoding. To make handling easier, |
1368 |
* we simply use hex format. |
1369 |
*/ |
1370 |
len = i2d_SSL_SESSION(session, &sess_data); |
1371 |
len += sizeof(pfixtls_scache_info_t); |
1372 |
|
1373 |
hexdata = (char *)mymalloc(2 * len + 1); |
1374 |
|
1375 |
if (!hexdata) { |
1376 |
msg_info("could not allocate memory for SSL session (HEX)"); |
1377 |
myfree((char *)data); |
1378 |
return 0; |
1379 |
} |
1380 |
for (n = 0; n < len; n++) { |
1381 |
hexdata[n * 2] = hexcodes[(data[n] & 0xf0) >> 4]; |
1382 |
hexdata[(n * 2) + 1] = hexcodes[(data[n] & 0x0f)]; |
1383 |
} |
1384 |
hexdata[len * 2] = '\0'; |
1385 |
|
1386 |
/* |
1387 |
* The session id is a hex string, all uppercase. We are using SDBM as |
1388 |
* compiled into Postfix with 8kB maximum entry size, so we set a limit |
1389 |
* when caching. If the session is not cached, we have to renegotiate, |
1390 |
* not more, not less. For a real session, this limit should never be |
1391 |
* met |
1392 |
*/ |
1393 |
if (strlen(idstring) + strlen(hexdata) < 8000) |
1394 |
dict_put(scache_db, idstring, hexdata); |
1395 |
|
1396 |
myfree(hexdata); |
1397 |
myfree((char *)data); |
1398 |
return (1); |
1399 |
} |
1400 |
|
1401 |
|
1402 |
/* |
1403 |
* pfixtls_exchange_seed: read bytes from the seed exchange-file (expect |
1404 |
* 1024 bytes)and immediately write back random bytes. Do so with EXCLUSIVE |
1405 |
* lock, so * that each process will find a completely different (and |
1406 |
* reseeded) file. |
1407 |
*/ |
1408 |
static void pfixtls_exchange_seed(void) |
1409 |
{ |
1410 |
unsigned char buffer[1024]; |
1411 |
|
1412 |
if (rand_exch_fd == -1) |
1413 |
return; |
1414 |
|
1415 |
if (myflock(rand_exch_fd, INTERNAL_LOCK, MYFLOCK_OP_EXCLUSIVE) != 0) |
1416 |
msg_info("Could not lock random exchange file: %s", |
1417 |
strerror(errno)); |
1418 |
|
1419 |
lseek(rand_exch_fd, 0, SEEK_SET); |
1420 |
if (read(rand_exch_fd, buffer, 1024) < 0) |
1421 |
msg_fatal("reading exchange file failed"); |
1422 |
RAND_seed(buffer, 1024); |
1423 |
|
1424 |
RAND_bytes(buffer, 1024); |
1425 |
lseek(rand_exch_fd, 0, SEEK_SET); |
1426 |
if (write(rand_exch_fd, buffer, 1024) != 1024) |
1427 |
msg_fatal("Writing exchange file failed"); |
1428 |
|
1429 |
if (myflock(rand_exch_fd, INTERNAL_LOCK, MYFLOCK_OP_NONE) != 0) |
1430 |
msg_fatal("Could not unlock random exchange file: %s", |
1431 |
strerror(errno)); |
1432 |
} |
1433 |
|
1434 |
/* |
1435 |
* This is the setup routine for the SSL server. As smtpd might be called |
1436 |
* more than once, we only want to do the initialization one time. |
1437 |
* |
1438 |
* The skeleton of this function is taken from OpenSSL apps/s_server.c. |
1439 |
*/ |
1440 |
|
1441 |
int pfixtls_init_serverengine(int verifydepth, int askcert) |
1442 |
{ |
1443 |
int off = 0; |
1444 |
int verify_flags = SSL_VERIFY_NONE; |
1445 |
int rand_bytes; |
1446 |
int rand_source_dev_fd; |
1447 |
int rand_source_socket_fd; |
1448 |
unsigned char buffer[255]; |
1449 |
char *CApath; |
1450 |
char *CAfile; |
1451 |
char *s_cert_file; |
1452 |
char *s_key_file; |
1453 |
char *s_dcert_file; |
1454 |
char *s_dkey_file; |
1455 |
FILE *paramfile; |
1456 |
|
1457 |
if (pfixtls_serverengine) |
1458 |
return (0); /* already running */ |
1459 |
|
1460 |
if (var_smtpd_tls_loglevel >= 2) |
1461 |
msg_info("starting TLS engine"); |
1462 |
|
1463 |
/* |
1464 |
* Initialize the OpenSSL library by the book! |
1465 |
* To start with, we must initialize the algorithms. |
1466 |
* We want cleartext error messages instead of just error codes, so we |
1467 |
* load the error_strings. |
1468 |
*/ |
1469 |
SSL_load_error_strings(); |
1470 |
OpenSSL_add_ssl_algorithms(); |
1471 |
|
1472 |
/* |
1473 |
* Side effect, call a non-existing function to disable TLS usage with an |
1474 |
* outdated OpenSSL version. There is a security reason (verify_result |
1475 |
* is not stored with the session data). |
1476 |
*/ |
1477 |
#if (OPENSSL_VERSION_NUMBER < 0x00905100L) |
1478 |
needs_openssl_095_or_later(); |
1479 |
#endif |
1480 |
|
1481 |
/* |
1482 |
* Initialize the PRNG Pseudo Random Number Generator with some seed. |
1483 |
*/ |
1484 |
randseed.pid = getpid(); |
1485 |
GETTIMEOFDAY(&randseed.tv); |
1486 |
RAND_seed(&randseed, sizeof(randseed_t)); |
1487 |
|
1488 |
/* |
1489 |
* Access the external sources for random seed. We will only query them |
1490 |
* once, this should be sufficient and we will stir our entropy by using |
1491 |
* the prng-exchange file anyway. |
1492 |
* For reliability, we don't consider failure to access the additional |
1493 |
* source fatal, as we can run happily without it (considering that we |
1494 |
* still have the exchange-file). We also don't care how much entropy |
1495 |
* we get back, as we must run anyway. We simply stir in the buffer |
1496 |
* regardless how many bytes are actually in it. |
1497 |
*/ |
1498 |
if (*var_tls_daemon_rand_source) { |
1499 |
if (!strncmp(var_tls_daemon_rand_source, "dev:", 4)) { |
1500 |
/* |
1501 |
* Source is a random device |
1502 |
*/ |
1503 |
rand_source_dev_fd = open(var_tls_daemon_rand_source + 4, 0, 0); |
1504 |
if (rand_source_dev_fd == -1) |
1505 |
msg_info("Could not open entropy device %s", |
1506 |
var_tls_daemon_rand_source); |
1507 |
else { |
1508 |
if (var_tls_daemon_rand_bytes > 255) |
1509 |
var_tls_daemon_rand_bytes = 255; |
1510 |
read(rand_source_dev_fd, buffer, var_tls_daemon_rand_bytes); |
1511 |
RAND_seed(buffer, var_tls_daemon_rand_bytes); |
1512 |
close(rand_source_dev_fd); |
1513 |
} |
1514 |
} else if (!strncmp(var_tls_daemon_rand_source, "egd:", 4)) { |
1515 |
/* |
1516 |
* Source is a EGD compatible socket |
1517 |
*/ |
1518 |
rand_source_socket_fd = unix_connect(var_tls_daemon_rand_source +4, |
1519 |
BLOCKING, 10); |
1520 |
if (rand_source_socket_fd == -1) |
1521 |
msg_info("Could not connect to %s", var_tls_daemon_rand_source); |
1522 |
else { |
1523 |
if (var_tls_daemon_rand_bytes > 255) |
1524 |
var_tls_daemon_rand_bytes = 255; |
1525 |
buffer[0] = 1; |
1526 |
buffer[1] = var_tls_daemon_rand_bytes; |
1527 |
if (write(rand_source_socket_fd, buffer, 2) != 2) |
1528 |
msg_info("Could not talk to %s", |
1529 |
var_tls_daemon_rand_source); |
1530 |
else if (read(rand_source_socket_fd, buffer, 1) != 1) |
1531 |
msg_info("Could not read info from %s", |
1532 |
var_tls_daemon_rand_source); |
1533 |
else { |
1534 |
rand_bytes = buffer[0]; |
1535 |
read(rand_source_socket_fd, buffer, rand_bytes); |
1536 |
RAND_seed(buffer, rand_bytes); |
1537 |
} |
1538 |
close(rand_source_socket_fd); |
1539 |
} |
1540 |
} else { |
1541 |
RAND_load_file(var_tls_daemon_rand_source, |
1542 |
var_tls_daemon_rand_bytes); |
1543 |
} |
1544 |
} |
1545 |
|
1546 |
if (*var_tls_rand_exch_name) { |
1547 |
rand_exch_fd = open(var_tls_rand_exch_name, O_RDWR | O_CREAT, 0600); |
1548 |
if (rand_exch_fd != -1) |
1549 |
pfixtls_exchange_seed(); |
1550 |
} |
1551 |
|
1552 |
randseed.pid = getpid(); |
1553 |
GETTIMEOFDAY(&randseed.tv); |
1554 |
RAND_seed(&randseed, sizeof(randseed_t)); |
1555 |
|
1556 |
/* |
1557 |
* The SSL/TLS speficications require the client to send a message in |
1558 |
* the oldest specification it understands with the highest level it |
1559 |
* understands in the message. |
1560 |
* Netscape communicator can still communicate with SSLv2 servers, so it |
1561 |
* sends out a SSLv2 client hello. To deal with it, our server must be |
1562 |
* SSLv2 aware (even if we don't like SSLv2), so we need to have the |
1563 |
* SSLv23 server here. If we want to limit the protocol level, we can |
1564 |
* add an option to not use SSLv2/v3/TLSv1 later. |
1565 |
*/ |
1566 |
ctx = SSL_CTX_new(SSLv23_server_method()); |
1567 |
if (ctx == NULL) { |
1568 |
pfixtls_print_errors(); |
1569 |
return (-1); |
1570 |
}; |
1571 |
|
1572 |
/* |
1573 |
* Here we might set SSL_OP_NO_SSLv2, SSL_OP_NO_SSLv3, SSL_OP_NO_TLSv1. |
1574 |
* Of course, the last one would not make sense, since RFC2487 is only |
1575 |
* defined for TLS, but we also want to accept Netscape communicator |
1576 |
* requests, and it only supports SSLv3. |
1577 |
*/ |
1578 |
off |= SSL_OP_ALL; /* Work around all known bugs */ |
1579 |
SSL_CTX_set_options(ctx, off); |
1580 |
|
1581 |
/* |
1582 |
* Set the info_callback, that will print out messages during |
1583 |
* communication on demand. |
1584 |
*/ |
1585 |
if (var_smtpd_tls_loglevel >= 2) |
1586 |
SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback); |
1587 |
|
1588 |
/* |
1589 |
* Set the list of ciphers, if explicitely given; otherwise the |
1590 |
* (reasonable) default list is kept. |
1591 |
*/ |
1592 |
if (strlen(var_smtpd_tls_cipherlist) != 0) |
1593 |
if (SSL_CTX_set_cipher_list(ctx, var_smtpd_tls_cipherlist) == 0) { |
1594 |
pfixtls_print_errors(); |
1595 |
return (-1); |
1596 |
} |
1597 |
|
1598 |
/* |
1599 |
* Now we must add the necessary certificate stuff: A server key, a |
1600 |
* server certificate, and the CA certificates for both the server |
1601 |
* cert and the verification of client certificates. |
1602 |
* As provided by OpenSSL we support two types of CA certificate handling: |
1603 |
* One possibility is to add all CA certificates to one large CAfile, |
1604 |
* the other possibility is a directory pointed to by CApath, containing |
1605 |
* seperate files for each CA pointed on by softlinks named by the hash |
1606 |
* values of the certificate. |
1607 |
* The first alternative has the advantage, that the file is opened and |
1608 |
* read at startup time, so that you don't have the hassle to maintain |
1609 |
* another copy of the CApath directory for chroot-jail. On the other |
1610 |
* hand, the file is not really readable. |
1611 |
*/ |
1612 |
if (strlen(var_smtpd_tls_CAfile) == 0) |
1613 |
CAfile = NULL; |
1614 |
else |
1615 |
CAfile = var_smtpd_tls_CAfile; |
1616 |
if (strlen(var_smtpd_tls_CApath) == 0) |
1617 |
CApath = NULL; |
1618 |
else |
1619 |
CApath = var_smtpd_tls_CApath; |
1620 |
|
1621 |
if (CAfile || CApath) { |
1622 |
if (!SSL_CTX_load_verify_locations(ctx, CAfile, CApath)) { |
1623 |
msg_info("TLS engine: cannot load CA data"); |
1624 |
pfixtls_print_errors(); |
1625 |
return (-1); |
1626 |
} |
1627 |
if (!SSL_CTX_set_default_verify_paths(ctx)) { |
1628 |
msg_info("TLS engine: cannot set verify paths"); |
1629 |
pfixtls_print_errors(); |
1630 |
return (-1); |
1631 |
} |
1632 |
} |
1633 |
|
1634 |
/* |
1635 |
* Now we load the certificate and key from the files and check, |
1636 |
* whether the cert matches the key (internally done by set_cert_stuff(). |
1637 |
* We cannot run without (we do not support ADH anonymous Diffie-Hellman |
1638 |
* ciphers as of now). |
1639 |
* We can use RSA certificates ("cert") and DSA certificates ("dcert"), |
1640 |
* both can be made available at the same time. The CA certificates for |
1641 |
* both are handled in the same setup already finished. |
1642 |
* Which one is used depends on the cipher negotiated (that is: the first |
1643 |
* cipher listed by the client which does match the server). A client with |
1644 |
* RSA only (e.g. Netscape) will use the RSA certificate only. |
1645 |
* A client with openssl-library will use RSA first if not especially |
1646 |
* changed in the cipher setup. |
1647 |
*/ |
1648 |
if (strlen(var_smtpd_tls_cert_file) == 0) |
1649 |
s_cert_file = NULL; |
1650 |
else |
1651 |
s_cert_file = var_smtpd_tls_cert_file; |
1652 |
if (strlen(var_smtpd_tls_key_file) == 0) |
1653 |
s_key_file = NULL; |
1654 |
else |
1655 |
s_key_file = var_smtpd_tls_key_file; |
1656 |
|
1657 |
if (strlen(var_smtpd_tls_dcert_file) == 0) |
1658 |
s_dcert_file = NULL; |
1659 |
else |
1660 |
s_dcert_file = var_smtpd_tls_dcert_file; |
1661 |
if (strlen(var_smtpd_tls_dkey_file) == 0) |
1662 |
s_dkey_file = NULL; |
1663 |
else |
1664 |
s_dkey_file = var_smtpd_tls_dkey_file; |
1665 |
|
1666 |
if (s_cert_file) { |
1667 |
if (!set_cert_stuff(ctx, s_cert_file, s_key_file)) { |
1668 |
msg_info("TLS engine: cannot load RSA cert/key data"); |
1669 |
pfixtls_print_errors(); |
1670 |
return (-1); |
1671 |
} |
1672 |
} |
1673 |
if (s_dcert_file) { |
1674 |
if (!set_cert_stuff(ctx, s_dcert_file, s_dkey_file)) { |
1675 |
msg_info("TLS engine: cannot load DSA cert/key data"); |
1676 |
pfixtls_print_errors(); |
1677 |
return (-1); |
1678 |
} |
1679 |
} |
1680 |
if (!s_cert_file && !s_dcert_file) { |
1681 |
msg_info("TLS engine: do need at least RSA _or_ DSA cert/key data"); |
1682 |
return (-1); |
1683 |
} |
1684 |
|
1685 |
/* |
1686 |
* Sometimes a temporary RSA key might be needed by the OpenSSL |
1687 |
* library. The OpenSSL doc indicates, that this might happen when |
1688 |
* export ciphers are in use. We have to provide one, so well, we |
1689 |
* just do it. |
1690 |
*/ |
1691 |
SSL_CTX_set_tmp_rsa_callback(ctx, tmp_rsa_cb); |
1692 |
|
1693 |
/* |
1694 |
* We might also need dh parameters, which can either be loaded from |
1695 |
* file (preferred) or we simply take the compiled in values. |
1696 |
* First, set the callback that will select the values when requested, |
1697 |
* then load the (possibly) available DH parameters from files. |
1698 |
* We are generous with the error handling, since we do have default |
1699 |
* values compiled in, so we will not abort but just log the error message. |
1700 |
*/ |
1701 |
SSL_CTX_set_tmp_dh_callback(ctx, tmp_dh_cb); |
1702 |
if (strlen(var_smtpd_tls_dh1024_param_file) != 0) { |
1703 |
if ((paramfile = fopen(var_smtpd_tls_dh1024_param_file, "r")) != NULL) { |
1704 |
dh_1024 = PEM_read_DHparams(paramfile, NULL, NULL, NULL); |
1705 |
if (dh_1024 == NULL) { |
1706 |
msg_info("TLS engine: cannot load 1024bit DH parameters"); |
1707 |
pfixtls_print_errors(); |
1708 |
} |
1709 |
} |
1710 |
else { |
1711 |
msg_info("TLS engine: cannot load 1024bit DH parameters: %s: %s", |
1712 |
var_smtpd_tls_dh1024_param_file, strerror(errno)); |
1713 |
} |
1714 |
} |
1715 |
if (strlen(var_smtpd_tls_dh512_param_file) != 0) { |
1716 |
if ((paramfile = fopen(var_smtpd_tls_dh512_param_file, "r")) != NULL) { |
1717 |
dh_512 = PEM_read_DHparams(paramfile, NULL, NULL, NULL); |
1718 |
if (dh_512 == NULL) { |
1719 |
msg_info("TLS engine: cannot load 512bit DH parameters"); |
1720 |
pfixtls_print_errors(); |
1721 |
} |
1722 |
} |
1723 |
else { |
1724 |
msg_info("TLS engine: cannot load 512bit DH parameters: %s: %s", |
1725 |
var_smtpd_tls_dh512_param_file, strerror(errno)); |
1726 |
} |
1727 |
} |
1728 |
|
1729 |
/* |
1730 |
* If we want to check client certificates, we have to indicate it |
1731 |
* in advance. By now we only allow to decide on a global basis. |
1732 |
* If we want to allow certificate based relaying, we must ask the |
1733 |
* client to provide one with SSL_VERIFY_PEER. The client now can |
1734 |
* decide, whether it provides one or not. We can enforce a failure |
1735 |
* of the negotiation with SSL_VERIFY_FAIL_IF_NO_PEER_CERT, if we |
1736 |
* do not allow a connection without one. |
1737 |
* In the "server hello" following the initialization by the "client hello" |
1738 |
* the server must provide a list of CAs it is willing to accept. |
1739 |
* Some clever clients will then select one from the list of available |
1740 |
* certificates matching these CAs. Netscape Communicator will present |
1741 |
* the list of certificates for selecting the one to be sent, or it will |
1742 |
* issue a warning, if there is no certificate matching the available |
1743 |
* CAs. |
1744 |
* |
1745 |
* With regard to the purpose of the certificate for relaying, we might |
1746 |
* like a later negotiation, maybe relaying would already be allowed |
1747 |
* for other reasons, but this would involve severe changes in the |
1748 |
* internal postfix logic, so we have to live with it the way it is. |
1749 |
*/ |
1750 |
if (askcert) |
1751 |
verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE; |
1752 |
SSL_CTX_set_verify(ctx, verify_flags, verify_callback); |
1753 |
SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile)); |
1754 |
|
1755 |
/* |
1756 |
* Initialize the session cache. We only want external caching to |
1757 |
* synchronize between server sessions, so we set it to a minimum value |
1758 |
* of 1. If the external cache is disabled, we won't cache at all. |
1759 |
* The recall of old sessions "get" and save to disk of just created |
1760 |
* sessions "new" is handled by the appropriate callback functions. |
1761 |
* |
1762 |
* We must not forget to set a session id context to identify to which |
1763 |
* kind of server process the session was related. In our case, the |
1764 |
* context is just the name of the patchkit: "Postfix/TLS". |
1765 |
*/ |
1766 |
SSL_CTX_sess_set_cache_size(ctx, 1); |
1767 |
SSL_CTX_set_timeout(ctx, var_smtpd_tls_scache_timeout); |
1768 |
SSL_CTX_set_session_id_context(ctx, (void*)&server_session_id_context, |
1769 |
sizeof(server_session_id_context)); |
1770 |
|
1771 |
/* |
1772 |
* The session cache is realized by an external database file, that |
1773 |
* must be opened before going to chroot jail. Since the session cache |
1774 |
* data can become quite large, "[n]dbm" cannot be used as it has a |
1775 |
* size limit that is by far to small. |
1776 |
*/ |
1777 |
if (*var_smtpd_tls_scache_db) { |
1778 |
/* |
1779 |
* Insert a test against other dbms here, otherwise while writing |
1780 |
* a session (content to large), we will receive a fatal error! |
1781 |
*/ |
1782 |
if (strncmp(var_smtpd_tls_scache_db, "sdbm:", 5)) |
1783 |
msg_warn("Only sdbm: type allowed for %s", |
1784 |
var_smtpd_tls_scache_db); |
1785 |
else |
1786 |
scache_db = dict_open(var_smtpd_tls_scache_db, O_RDWR, |
1787 |
DICT_FLAG_DUP_REPLACE | DICT_FLAG_LOCK | DICT_FLAG_SYNC_UPDATE); |
1788 |
if (scache_db) { |
1789 |
SSL_CTX_set_session_cache_mode(ctx, |
1790 |
SSL_SESS_CACHE_SERVER|SSL_SESS_CACHE_NO_AUTO_CLEAR); |
1791 |
SSL_CTX_sess_set_get_cb(ctx, get_session_cb); |
1792 |
SSL_CTX_sess_set_new_cb(ctx, new_session_cb); |
1793 |
SSL_CTX_sess_set_remove_cb(ctx, remove_session_cb); |
1794 |
} |
1795 |
else |
1796 |
msg_warn("Could not open session cache %s", |
1797 |
var_smtpd_tls_scache_db); |
1798 |
} |
1799 |
|
1800 |
/* |
1801 |
* Finally create the global index to access TLScontext information |
1802 |
* inside verify_callback. |
1803 |
*/ |
1804 |
TLScontext_index = SSL_get_ex_new_index(0, "TLScontext ex_data index", |
1805 |
NULL, NULL, NULL); |
1806 |
|
1807 |
pfixtls_serverengine = 1; |
1808 |
return (0); |
1809 |
} |
1810 |
|
1811 |
/* |
1812 |
* This is the actual startup routine for the connection. We expect |
1813 |
* that the buffers are flushed and the "220 Ready to start TLS" was |
1814 |
* send to the client, so that we can immediately can start the TLS |
1815 |
* handshake process. |
1816 |
*/ |
1817 |
int pfixtls_start_servertls(VSTREAM *stream, int timeout, |
1818 |
const char *peername, const char *peeraddr, |
1819 |
tls_info_t *tls_info, int requirecert) |
1820 |
{ |
1821 |
int sts; |
1822 |
int j; |
1823 |
int verify_flags; |
1824 |
unsigned int n; |
1825 |
TLScontext_t *TLScontext; |
1826 |
SSL_SESSION *session; |
1827 |
SSL_CIPHER *cipher; |
1828 |
X509 *peer; |
1829 |
|
1830 |
if (!pfixtls_serverengine) { /* should never happen */ |
1831 |
msg_info("tls_engine not running"); |
1832 |
return (-1); |
1833 |
} |
1834 |
if (var_smtpd_tls_loglevel >= 1) |
1835 |
msg_info("setting up TLS connection from %s[%s]", peername, peeraddr); |
1836 |
|
1837 |
/* |
1838 |
* Allocate a new TLScontext for the new connection and get an SSL |
1839 |
* structure. Add the location of TLScontext to the SSL to later |
1840 |
* retrieve the information inside the verify_callback(). |
1841 |
*/ |
1842 |
TLScontext = (TLScontext_t *)mymalloc(sizeof(TLScontext_t)); |
1843 |
if (!TLScontext) { |
1844 |
msg_fatal("Could not allocate 'TLScontext' with mymalloc"); |
1845 |
} |
1846 |
if ((TLScontext->con = (SSL *) SSL_new(ctx)) == NULL) { |
1847 |
msg_info("Could not allocate 'TLScontext->con' with SSL_new()"); |
1848 |
pfixtls_print_errors(); |
1849 |
myfree((char *)TLScontext); |
1850 |
return (-1); |
1851 |
} |
1852 |
if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) { |
1853 |
msg_info("Could not set application data for 'TLScontext->con'"); |
1854 |
pfixtls_print_errors(); |
1855 |
SSL_free(TLScontext->con); |
1856 |
myfree((char *)TLScontext); |
1857 |
return (-1); |
1858 |
} |
1859 |
|
1860 |
/* |
1861 |
* Set the verification parameters to be checked in verify_callback(). |
1862 |
*/ |
1863 |
if (requirecert) { |
1864 |
verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE; |
1865 |
verify_flags |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; |
1866 |
TLScontext->enforce_verify_errors = 1; |
1867 |
SSL_set_verify(TLScontext->con, verify_flags, verify_callback); |
1868 |
} |
1869 |
else { |
1870 |
TLScontext->enforce_verify_errors = 0; |
1871 |
} |
1872 |
TLScontext->enforce_CN = 0; |
1873 |
|
1874 |
/* |
1875 |
* The TLS connection is realized by a BIO_pair, so obtain the pair. |
1876 |
*/ |
1877 |
if (!BIO_new_bio_pair(&TLScontext->internal_bio, BIO_bufsiz, |
1878 |
&TLScontext->network_bio, BIO_bufsiz)) { |
1879 |
msg_info("Could not obtain BIO_pair"); |
1880 |
pfixtls_print_errors(); |
1881 |
SSL_free(TLScontext->con); |
1882 |
myfree((char *)TLScontext); |
1883 |
return (-1); |
1884 |
} |
1885 |
|
1886 |
/* |
1887 |
* Before really starting anything, try to seed the PRNG a little bit |
1888 |
* more. |
1889 |
*/ |
1890 |
pfixtls_stir_seed(); |
1891 |
pfixtls_exchange_seed(); |
1892 |
|
1893 |
/* |
1894 |
* Initialize the SSL connection to accept state. This should not be |
1895 |
* necessary anymore since 0.9.3, but the call is still in the library |
1896 |
* and maintaining compatibility never hurts. |
1897 |
*/ |
1898 |
SSL_set_accept_state(TLScontext->con); |
1899 |
|
1900 |
/* |
1901 |
* Connect the SSL-connection with the postfix side of the BIO-pair for |
1902 |
* reading and writing. |
1903 |
*/ |
1904 |
SSL_set_bio(TLScontext->con, TLScontext->internal_bio, |
1905 |
TLScontext->internal_bio); |
1906 |
|
1907 |
/* |
1908 |
* If the debug level selected is high enough, all of the data is |
1909 |
* dumped: 3 will dump the SSL negotiation, 4 will dump everything. |
1910 |
* |
1911 |
* We do have an SSL_set_fd() and now suddenly a BIO_ routine is called? |
1912 |
* Well there is a BIO below the SSL routines that is automatically |
1913 |
* created for us, so we can use it for debugging purposes. |
1914 |
*/ |
1915 |
if (var_smtpd_tls_loglevel >= 3) |
1916 |
BIO_set_callback(SSL_get_rbio(TLScontext->con), bio_dump_cb); |
1917 |
|
1918 |
|
1919 |
/* Dump the negotiation for loglevels 3 and 4 */ |
1920 |
if (var_smtpd_tls_loglevel >= 3) |
1921 |
do_dump = 1; |
1922 |
|
1923 |
/* |
1924 |
* Now we expect the negotiation to begin. This whole process is like a |
1925 |
* black box for us. We totally have to rely on the routines build into |
1926 |
* the OpenSSL library. The only thing we can do we already have done |
1927 |
* by choosing our own callbacks for session caching and certificate |
1928 |
* verification. |
1929 |
* |
1930 |
* Error handling: |
1931 |
* If the SSL handhake fails, we print out an error message and remove |
1932 |
* everything that might be there. A session has to be removed anyway, |
1933 |
* because RFC2246 requires it. |
1934 |
*/ |
1935 |
sts = do_tls_operation(vstream_fileno(stream), timeout, TLScontext, |
1936 |
SSL_accept, NULL, NULL, NULL, 0); |
1937 |
if (sts <= 0) { |
1938 |
msg_info("SSL_accept error from %s[%s]: %d", peername, peeraddr, sts); |
1939 |
pfixtls_print_errors(); |
1940 |
SSL_free(TLScontext->con); |
1941 |
myfree((char *)TLScontext); |
1942 |
return (-1); |
1943 |
} |
1944 |
|
1945 |
/* Only loglevel==4 dumps everything */ |
1946 |
if (var_smtpd_tls_loglevel < 4) |
1947 |
do_dump = 0; |
1948 |
|
1949 |
/* |
1950 |
* Lets see, whether a peer certificate is available and what is |
1951 |
* the actual information. We want to save it for later use. |
1952 |
*/ |
1953 |
peer = SSL_get_peer_certificate(TLScontext->con); |
1954 |
if (peer != NULL) { |
1955 |
if (SSL_get_verify_result(TLScontext->con) == X509_V_OK) |
1956 |
tls_info->peer_verified = 1; |
1957 |
|
1958 |
X509_NAME_oneline(X509_get_subject_name(peer), |
1959 |
TLScontext->peer_subject, CCERT_BUFSIZ); |
1960 |
if (var_smtpd_tls_loglevel >= 2) |
1961 |
msg_info("subject=%s", TLScontext->peer_subject); |
1962 |
tls_info->peer_subject = TLScontext->peer_subject; |
1963 |
X509_NAME_oneline(X509_get_issuer_name(peer), |
1964 |
TLScontext->peer_issuer, CCERT_BUFSIZ); |
1965 |
if (var_smtpd_tls_loglevel >= 2) |
1966 |
msg_info("issuer=%s", TLScontext->peer_issuer); |
1967 |
tls_info->peer_issuer = TLScontext->peer_issuer; |
1968 |
if (X509_digest(peer, EVP_md5(), TLScontext->md, &n)) { |
1969 |
for (j = 0; j < (int) n; j++) { |
1970 |
TLScontext->fingerprint[j * 3] = |
1971 |
hexcodes[(TLScontext->md[j] & 0xf0) >> 4]; |
1972 |
TLScontext->fingerprint[(j * 3) + 1] = |
1973 |
hexcodes[(TLScontext->md[j] & 0x0f)]; |
1974 |
if (j + 1 != (int) n) |
1975 |
TLScontext->fingerprint[(j * 3) + 2] = ':'; |
1976 |
else |
1977 |
TLScontext->fingerprint[(j * 3) + 2] = '\0'; |
1978 |
} |
1979 |
if (var_smtpd_tls_loglevel >= 1) |
1980 |
msg_info("fingerprint=%s", TLScontext->fingerprint); |
1981 |
tls_info->peer_fingerprint = TLScontext->fingerprint; |
1982 |
} |
1983 |
|
1984 |
TLScontext->peer_CN[0] = '\0'; |
1985 |
if (!X509_NAME_get_text_by_NID(X509_get_subject_name(peer), |
1986 |
NID_commonName, TLScontext->peer_CN, CCERT_BUFSIZ)) { |
1987 |
msg_info("Could not parse client's subject CN"); |
1988 |
pfixtls_print_errors(); |
1989 |
} |
1990 |
tls_info->peer_CN = TLScontext->peer_CN; |
1991 |
|
1992 |
TLScontext->issuer_CN[0] = '\0'; |
1993 |
if (!X509_NAME_get_text_by_NID(X509_get_issuer_name(peer), |
1994 |
NID_commonName, TLScontext->issuer_CN, CCERT_BUFSIZ)) { |
1995 |
msg_info("Could not parse client's issuer CN"); |
1996 |
pfixtls_print_errors(); |
1997 |
} |
1998 |
if (!TLScontext->issuer_CN[0]) { |
1999 |
/* No issuer CN field, use Organization instead */ |
2000 |
if (!X509_NAME_get_text_by_NID(X509_get_issuer_name(peer), |
2001 |
NID_organizationName, TLScontext->issuer_CN, CCERT_BUFSIZ)) { |
2002 |
msg_info("Could not parse client's issuer Organization"); |
2003 |
pfixtls_print_errors(); |
2004 |
} |
2005 |
} |
2006 |
tls_info->issuer_CN = TLScontext->issuer_CN; |
2007 |
|
2008 |
if (var_smtpd_tls_loglevel >= 1) { |
2009 |
if (tls_info->peer_verified) |
2010 |
msg_info("Verified: subject_CN=%s, issuer=%s", |
2011 |
TLScontext->peer_CN, TLScontext->issuer_CN); |
2012 |
else |
2013 |
msg_info("Unverified: subject_CN=%s, issuer=%s", |
2014 |
TLScontext->peer_CN, TLScontext->issuer_CN); |
2015 |
} |
2016 |
|
2017 |
X509_free(peer); |
2018 |
} |
2019 |
|
2020 |
/* |
2021 |
* At this point we should have a certificate when required. |
2022 |
* We may however have a cached session, so the callback would never |
2023 |
* be called. We therefore double-check to make sure and remove the |
2024 |
* session, if applicable. |
2025 |
*/ |
2026 |
if (requirecert) { |
2027 |
if (!tls_info->peer_verified || !tls_info->peer_CN) { |
2028 |
msg_info("Re-used session without peer certificate removed"); |
2029 |
session = SSL_get_session(TLScontext->con); |
2030 |
SSL_CTX_remove_session(ctx, session); |
2031 |
return (-1); |
2032 |
} |
2033 |
} |
2034 |
|
2035 |
/* |
2036 |
* Finally, collect information about protocol and cipher for logging |
2037 |
*/ |
2038 |
tls_info->protocol = SSL_get_version(TLScontext->con); |
2039 |
cipher = SSL_get_current_cipher(TLScontext->con); |
2040 |
tls_info->cipher_name = SSL_CIPHER_get_name(cipher); |
2041 |
tls_info->cipher_usebits = SSL_CIPHER_get_bits(cipher, |
2042 |
&(tls_info->cipher_algbits)); |
2043 |
|
2044 |
pfixtls_serveractive = 1; |
2045 |
|
2046 |
/* |
2047 |
* The TLS engine is active, switch to the pfixtls_timed_read/write() |
2048 |
* functions and store the context. |
2049 |
*/ |
2050 |
vstream_control(stream, |
2051 |
VSTREAM_CTL_READ_FN, pfixtls_timed_read, |
2052 |
VSTREAM_CTL_WRITE_FN, pfixtls_timed_write, |
2053 |
VSTREAM_CTL_CONTEXT, (void *)TLScontext, |
2054 |
VSTREAM_CTL_END); |
2055 |
|
2056 |
msg_info("TLS connection established from %s[%s]: %s with cipher %s (%d/%d bits)", |
2057 |
peername, peeraddr, |
2058 |
tls_info->protocol, tls_info->cipher_name, |
2059 |
tls_info->cipher_usebits, tls_info->cipher_algbits); |
2060 |
pfixtls_stir_seed(); |
2061 |
|
2062 |
return (0); |
2063 |
} |
2064 |
|
2065 |
/* |
2066 |
* Shut down the TLS connection, that does mean: remove all the information |
2067 |
* and reset the flags! This is needed if the actual running smtpd is to |
2068 |
* be restarted. We do not give back any value, as there is nothing to |
2069 |
* be reported. |
2070 |
* Since our session cache is external, we will remove the session from |
2071 |
* memory in any case. The SSL_CTX_flush_sessions might be redundant here, |
2072 |
* I however want to make sure nothing is left. |
2073 |
* RFC2246 requires us to remove sessions if something went wrong, as |
2074 |
* indicated by the "failure" value, so we remove it from the external |
2075 |
* cache, too. |
2076 |
*/ |
2077 |
int pfixtls_stop_servertls(VSTREAM *stream, int timeout, int failure, |
2078 |
tls_info_t *tls_info) |
2079 |
{ |
2080 |
TLScontext_t *TLScontext; |
2081 |
int retval; |
2082 |
|
2083 |
if (pfixtls_serveractive) { |
2084 |
TLScontext = (TLScontext_t *)vstream_context(stream); |
2085 |
/* |
2086 |
* Perform SSL_shutdown() twice, as the first attempt may return |
2087 |
* to early: it will only send out the shutdown alert but it will |
2088 |
* not wait for the peer's shutdown alert. Therefore, when we are |
2089 |
* the first party to send the alert, we must call SSL_shutdown() |
2090 |
* again. |
2091 |
* On failure we don't want to resume the session, so we will not |
2092 |
* perform SSL_shutdown() and the session will be removed as being |
2093 |
* bad. |
2094 |
*/ |
2095 |
if (!failure) { |
2096 |
retval = do_tls_operation(vstream_fileno(stream), timeout, |
2097 |
TLScontext, SSL_shutdown, NULL, NULL, NULL, 0); |
2098 |
if (retval == 0) |
2099 |
do_tls_operation(vstream_fileno(stream), timeout, TLScontext, |
2100 |
SSL_shutdown, NULL, NULL, NULL, 0); |
2101 |
} |
2102 |
/* |
2103 |
* Free the SSL structure and the BIOs. Warning: the internal_bio is |
2104 |
* connected to the SSL structure and is automatically freed with |
2105 |
* it. Do not free it again (core dump)!! |
2106 |
* Only free the network_bio. |
2107 |
*/ |
2108 |
SSL_free(TLScontext->con); |
2109 |
BIO_free(TLScontext->network_bio); |
2110 |
myfree((char *)TLScontext); |
2111 |
vstream_control(stream, |
2112 |
VSTREAM_CTL_READ_FN, (VSTREAM_FN) NULL, |
2113 |
VSTREAM_CTL_WRITE_FN, (VSTREAM_FN) NULL, |
2114 |
VSTREAM_CTL_CONTEXT, (void *) NULL, |
2115 |
VSTREAM_CTL_END); |
2116 |
SSL_CTX_flush_sessions(ctx, time(NULL)); |
2117 |
|
2118 |
pfixtls_stir_seed(); |
2119 |
pfixtls_exchange_seed(); |
2120 |
|
2121 |
*tls_info = tls_info_zero; |
2122 |
pfixtls_serveractive = 0; |
2123 |
|
2124 |
} |
2125 |
|
2126 |
return (0); |
2127 |
} |
2128 |
|
2129 |
|
2130 |
/* |
2131 |
* This is the setup routine for the SSL client. As smtpd might be called |
2132 |
* more than once, we only want to do the initialization one time. |
2133 |
* |
2134 |
* The skeleton of this function is taken from OpenSSL apps/s_client.c. |
2135 |
*/ |
2136 |
|
2137 |
int pfixtls_init_clientengine(int verifydepth) |
2138 |
{ |
2139 |
int off = 0; |
2140 |
int verify_flags = SSL_VERIFY_NONE; |
2141 |
int rand_bytes; |
2142 |
int rand_source_dev_fd; |
2143 |
int rand_source_socket_fd; |
2144 |
unsigned char buffer[255]; |
2145 |
char *CApath; |
2146 |
char *CAfile; |
2147 |
char *c_cert_file; |
2148 |
char *c_key_file; |
2149 |
|
2150 |
|
2151 |
if (pfixtls_clientengine) |
2152 |
return (0); /* already running */ |
2153 |
|
2154 |
if (var_smtp_tls_loglevel >= 2) |
2155 |
msg_info("starting TLS engine"); |
2156 |
|
2157 |
/* |
2158 |
* Initialize the OpenSSL library by the book! |
2159 |
* To start with, we must initialize the algorithms. |
2160 |
* We want cleartext error messages instead of just error codes, so we |
2161 |
* load the error_strings. |
2162 |
*/ |
2163 |
SSL_load_error_strings(); |
2164 |
OpenSSL_add_ssl_algorithms(); |
2165 |
|
2166 |
/* |
2167 |
* Side effect, call a non-existing function to disable TLS usage with an |
2168 |
* outdated OpenSSL version. There is a security reason (verify_result |
2169 |
* is not stored with the session data). |
2170 |
*/ |
2171 |
#if (OPENSSL_VERSION_NUMBER < 0x00905100L) |
2172 |
needs_openssl_095_or_later(); |
2173 |
#endif |
2174 |
|
2175 |
/* |
2176 |
* Initialize the PRNG Pseudo Random Number Generator with some seed. |
2177 |
*/ |
2178 |
randseed.pid = getpid(); |
2179 |
GETTIMEOFDAY(&randseed.tv); |
2180 |
RAND_seed(&randseed, sizeof(randseed_t)); |
2181 |
|
2182 |
/* |
2183 |
* Access the external sources for random seed. We will only query them |
2184 |
* once, this should be sufficient and we will stir our entropy by using |
2185 |
* the prng-exchange file anyway. |
2186 |
* For reliability, we don't consider failure to access the additional |
2187 |
* source fatal, as we can run happily without it (considering that we |
2188 |
* still have the exchange-file). We also don't care how much entropy |
2189 |
* we get back, as we must run anyway. We simply stir in the buffer |
2190 |
* regardless how many bytes are actually in it. |
2191 |
*/ |
2192 |
if (*var_tls_daemon_rand_source) { |
2193 |
if (!strncmp(var_tls_daemon_rand_source, "dev:", 4)) { |
2194 |
/* |
2195 |
* Source is a random device |
2196 |
*/ |
2197 |
rand_source_dev_fd = open(var_tls_daemon_rand_source + 4, 0, 0); |
2198 |
if (rand_source_dev_fd == -1) |
2199 |
msg_info("Could not open entropy device %s", |
2200 |
var_tls_daemon_rand_source); |
2201 |
else { |
2202 |
if (var_tls_daemon_rand_bytes > 255) |
2203 |
var_tls_daemon_rand_bytes = 255; |
2204 |
read(rand_source_dev_fd, buffer, var_tls_daemon_rand_bytes); |
2205 |
RAND_seed(buffer, var_tls_daemon_rand_bytes); |
2206 |
close(rand_source_dev_fd); |
2207 |
} |
2208 |
} else if (!strncmp(var_tls_daemon_rand_source, "egd:", 4)) { |
2209 |
/* |
2210 |
* Source is a EGD compatible socket |
2211 |
*/ |
2212 |
rand_source_socket_fd = unix_connect(var_tls_daemon_rand_source +4, |
2213 |
BLOCKING, 10); |
2214 |
if (rand_source_socket_fd == -1) |
2215 |
msg_info("Could not connect to %s", var_tls_daemon_rand_source); |
2216 |
else { |
2217 |
if (var_tls_daemon_rand_bytes > 255) |
2218 |
var_tls_daemon_rand_bytes = 255; |
2219 |
buffer[0] = 1; |
2220 |
buffer[1] = var_tls_daemon_rand_bytes; |
2221 |
if (write(rand_source_socket_fd, buffer, 2) != 2) |
2222 |
msg_info("Could not talk to %s", |
2223 |
var_tls_daemon_rand_source); |
2224 |
else if (read(rand_source_socket_fd, buffer, 1) != 1) |
2225 |
msg_info("Could not read info from %s", |
2226 |
var_tls_daemon_rand_source); |
2227 |
else { |
2228 |
rand_bytes = buffer[0]; |
2229 |
read(rand_source_socket_fd, buffer, rand_bytes); |
2230 |
RAND_seed(buffer, rand_bytes); |
2231 |
} |
2232 |
close(rand_source_socket_fd); |
2233 |
} |
2234 |
} else { |
2235 |
RAND_load_file(var_tls_daemon_rand_source, |
2236 |
var_tls_daemon_rand_bytes); |
2237 |
} |
2238 |
} |
2239 |
|
2240 |
if (*var_tls_rand_exch_name) { |
2241 |
rand_exch_fd = open(var_tls_rand_exch_name, O_RDWR | O_CREAT, 0600); |
2242 |
if (rand_exch_fd != -1) |
2243 |
pfixtls_exchange_seed(); |
2244 |
} |
2245 |
|
2246 |
randseed.pid = getpid(); |
2247 |
GETTIMEOFDAY(&randseed.tv); |
2248 |
RAND_seed(&randseed, sizeof(randseed_t)); |
2249 |
|
2250 |
/* |
2251 |
* The SSL/TLS speficications require the client to send a message in |
2252 |
* the oldest specification it understands with the highest level it |
2253 |
* understands in the message. |
2254 |
* RFC2487 is only specified for TLSv1, but we want to be as compatible |
2255 |
* as possible, so we will start off with a SSLv2 greeting allowing |
2256 |
* the best we can offer: TLSv1. |
2257 |
* We can restrict this with the options setting later, anyhow. |
2258 |
*/ |
2259 |
ctx = SSL_CTX_new(SSLv23_client_method()); |
2260 |
if (ctx == NULL) { |
2261 |
pfixtls_print_errors(); |
2262 |
return (-1); |
2263 |
}; |
2264 |
|
2265 |
/* |
2266 |
* Here we might set SSL_OP_NO_SSLv2, SSL_OP_NO_SSLv3, SSL_OP_NO_TLSv1. |
2267 |
* Of course, the last one would not make sense, since RFC2487 is only |
2268 |
* defined for TLS, but we don't know what is out there. So leave things |
2269 |
* completely open, as of today. |
2270 |
*/ |
2271 |
off |= SSL_OP_ALL; /* Work around all known bugs */ |
2272 |
SSL_CTX_set_options(ctx, off); |
2273 |
|
2274 |
/* |
2275 |
* Set the info_callback, that will print out messages during |
2276 |
* communication on demand. |
2277 |
*/ |
2278 |
if (var_smtp_tls_loglevel >= 2) |
2279 |
SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback); |
2280 |
|
2281 |
/* |
2282 |
* Set the list of ciphers, if explicitely given; otherwise the |
2283 |
* (reasonable) default list is kept. |
2284 |
*/ |
2285 |
if (strlen(var_smtp_tls_cipherlist) != 0) |
2286 |
if (SSL_CTX_set_cipher_list(ctx, var_smtp_tls_cipherlist) == 0) { |
2287 |
pfixtls_print_errors(); |
2288 |
return (-1); |
2289 |
} |
2290 |
|
2291 |
/* |
2292 |
* Now we must add the necessary certificate stuff: A client key, a |
2293 |
* client certificate, and the CA certificates for both the client |
2294 |
* cert and the verification of server certificates. |
2295 |
* In fact, we do not need a client certificate, so the certificates |
2296 |
* are only loaded (and checked), if supplied. A clever client would |
2297 |
* handle multiple client certificates and decide based on the list |
2298 |
* of acceptable CAs, sent by the server, which certificate to submit. |
2299 |
* OpenSSL does however not do this and also has no callback hoods to |
2300 |
* easily realize it. |
2301 |
* |
2302 |
* As provided by OpenSSL we support two types of CA certificate handling: |
2303 |
* One possibility is to add all CA certificates to one large CAfile, |
2304 |
* the other possibility is a directory pointed to by CApath, containing |
2305 |
* seperate files for each CA pointed on by softlinks named by the hash |
2306 |
* values of the certificate. |
2307 |
* The first alternative has the advantage, that the file is opened and |
2308 |
* read at startup time, so that you don't have the hassle to maintain |
2309 |
* another copy of the CApath directory for chroot-jail. On the other |
2310 |
* hand, the file is not really readable. |
2311 |
*/ |
2312 |
if (strlen(var_smtp_tls_CAfile) == 0) |
2313 |
CAfile = NULL; |
2314 |
else |
2315 |
CAfile = var_smtp_tls_CAfile; |
2316 |
if (strlen(var_smtp_tls_CApath) == 0) |
2317 |
CApath = NULL; |
2318 |
else |
2319 |
CApath = var_smtp_tls_CApath; |
2320 |
if (CAfile || CApath) { |
2321 |
if (!SSL_CTX_load_verify_locations(ctx, CAfile, CApath)) { |
2322 |
msg_info("TLS engine: cannot load CA data"); |
2323 |
pfixtls_print_errors(); |
2324 |
return (-1); |
2325 |
} |
2326 |
if (!SSL_CTX_set_default_verify_paths(ctx)) { |
2327 |
msg_info("TLS engine: cannot set verify paths"); |
2328 |
pfixtls_print_errors(); |
2329 |
return (-1); |
2330 |
} |
2331 |
} |
2332 |
|
2333 |
if (strlen(var_smtp_tls_cert_file) == 0) |
2334 |
c_cert_file = NULL; |
2335 |
else |
2336 |
c_cert_file = var_smtp_tls_cert_file; |
2337 |
if (strlen(var_smtp_tls_key_file) == 0) |
2338 |
c_key_file = NULL; |
2339 |
else |
2340 |
c_key_file = var_smtp_tls_key_file; |
2341 |
if (c_cert_file || c_key_file) |
2342 |
if (!set_cert_stuff(ctx, c_cert_file, c_key_file)) { |
2343 |
msg_info("TLS engine: cannot load cert/key data"); |
2344 |
pfixtls_print_errors(); |
2345 |
return (-1); |
2346 |
} |
2347 |
|
2348 |
/* |
2349 |
* Sometimes a temporary RSA key might be needed by the OpenSSL |
2350 |
* library. The OpenSSL doc indicates, that this might happen when |
2351 |
* export ciphers are in use. We have to provide one, so well, we |
2352 |
* just do it. |
2353 |
*/ |
2354 |
SSL_CTX_set_tmp_rsa_callback(ctx, tmp_rsa_cb); |
2355 |
|
2356 |
/* |
2357 |
* Finally, the setup for the server certificate checking, done |
2358 |
* "by the book". |
2359 |
*/ |
2360 |
SSL_CTX_set_verify(ctx, verify_flags, verify_callback); |
2361 |
|
2362 |
/* |
2363 |
* Initialize the session cache. We only want external caching to |
2364 |
* synchronize between server sessions, so we set it to a minimum value |
2365 |
* of 1. If the external cache is disabled, we won't cache at all. |
2366 |
* |
2367 |
* In case of the client, there is no callback used in OpenSSL, so |
2368 |
* we must call the session cache functions manually during the process. |
2369 |
*/ |
2370 |
SSL_CTX_sess_set_cache_size(ctx, 1); |
2371 |
SSL_CTX_set_timeout(ctx, var_smtp_tls_scache_timeout); |
2372 |
|
2373 |
/* |
2374 |
* The session cache is realized by an external database file, that |
2375 |
* must be opened before going to chroot jail. Since the session cache |
2376 |
* data can become quite large, "[n]dbm" cannot be used as it has a |
2377 |
* size limit that is by far to small. |
2378 |
*/ |
2379 |
if (*var_smtp_tls_scache_db) { |
2380 |
/* |
2381 |
* Insert a test against other dbms here, otherwise while writing |
2382 |
* a session (content to large), we will receive a fatal error! |
2383 |
*/ |
2384 |
if (strncmp(var_smtp_tls_scache_db, "sdbm:", 5)) |
2385 |
msg_warn("Only sdbm: type allowed for %s", |
2386 |
var_smtp_tls_scache_db); |
2387 |
else |
2388 |
scache_db = dict_open(var_smtp_tls_scache_db, O_RDWR, |
2389 |
DICT_FLAG_DUP_REPLACE | DICT_FLAG_LOCK | DICT_FLAG_SYNC_UPDATE); |
2390 |
if (!scache_db) |
2391 |
msg_warn("Could not open session cache %s", |
2392 |
var_smtp_tls_scache_db); |
2393 |
/* |
2394 |
* It is practical to have OpenSSL automatically save newly created |
2395 |
* sessions for us by callback. Therefore we have to enable the |
2396 |
* internal session cache for the client side. Disable automatic |
2397 |
* clearing, as smtp has limited lifetime anyway and we can call |
2398 |
* the cleanup routine at will. |
2399 |
*/ |
2400 |
SSL_CTX_set_session_cache_mode(ctx, |
2401 |
SSL_SESS_CACHE_CLIENT|SSL_SESS_CACHE_NO_AUTO_CLEAR); |
2402 |
SSL_CTX_sess_set_new_cb(ctx, new_session_cb); |
2403 |
} |
2404 |
|
2405 |
/* |
2406 |
* Finally create the global index to access TLScontext information |
2407 |
* inside verify_callback. |
2408 |
*/ |
2409 |
TLScontext_index = SSL_get_ex_new_index(0, "TLScontext ex_data index", |
2410 |
NULL, NULL, NULL); |
2411 |
TLSpeername_index = SSL_SESSION_get_ex_new_index(0, |
2412 |
"TLSpeername ex_data index", |
2413 |
new_peername_func, |
2414 |
dup_peername_func, |
2415 |
free_peername_func); |
2416 |
|
2417 |
pfixtls_clientengine = 1; |
2418 |
return (0); |
2419 |
} |
2420 |
|
2421 |
/* |
2422 |
* This is the actual startup routine for the connection. We expect |
2423 |
* that the buffers are flushed and the "220 Ready to start TLS" was |
2424 |
* received by us, so that we can immediately can start the TLS |
2425 |
* handshake process. |
2426 |
*/ |
2427 |
int pfixtls_start_clienttls(VSTREAM *stream, int timeout, |
2428 |
int enforce_peername, |
2429 |
const char *peername, |
2430 |
tls_info_t *tls_info) |
2431 |
{ |
2432 |
int sts; |
2433 |
SSL_SESSION *session, *old_session; |
2434 |
SSL_CIPHER *cipher; |
2435 |
X509 *peer; |
2436 |
int verify_flags; |
2437 |
TLScontext_t *TLScontext; |
2438 |
|
2439 |
if (!pfixtls_clientengine) { /* should never happen */ |
2440 |
msg_info("tls_engine not running"); |
2441 |
return (-1); |
2442 |
} |
2443 |
if (var_smtpd_tls_loglevel >= 1) |
2444 |
msg_info("setting up TLS connection to %s", peername); |
2445 |
|
2446 |
/* |
2447 |
* Allocate a new TLScontext for the new connection and get an SSL |
2448 |
* structure. Add the location of TLScontext to the SSL to later |
2449 |
* retrieve the information inside the verify_callback(). |
2450 |
*/ |
2451 |
TLScontext = (TLScontext_t *)mymalloc(sizeof(TLScontext_t)); |
2452 |
if (!TLScontext) { |
2453 |
msg_fatal("Could not allocate 'TLScontext' with mymalloc"); |
2454 |
} |
2455 |
if ((TLScontext->con = (SSL *) SSL_new(ctx)) == NULL) { |
2456 |
msg_info("Could not allocate 'TLScontext->con' with SSL_new()"); |
2457 |
pfixtls_print_errors(); |
2458 |
myfree((char *)TLScontext); |
2459 |
return (-1); |
2460 |
} |
2461 |
if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) { |
2462 |
msg_info("Could not set application data for 'TLScontext->con'"); |
2463 |
pfixtls_print_errors(); |
2464 |
SSL_free(TLScontext->con); |
2465 |
myfree((char *)TLScontext); |
2466 |
return (-1); |
2467 |
} |
2468 |
|
2469 |
/* |
2470 |
* Set the verification parameters to be checked in verify_callback(). |
2471 |
*/ |
2472 |
if (enforce_peername) { |
2473 |
verify_flags = SSL_VERIFY_PEER; |
2474 |
TLScontext->enforce_verify_errors = 1; |
2475 |
TLScontext->enforce_CN = 1; |
2476 |
SSL_set_verify(TLScontext->con, verify_flags, verify_callback); |
2477 |
} |
2478 |
else { |
2479 |
TLScontext->enforce_verify_errors = 0; |
2480 |
TLScontext->enforce_CN = 0; |
2481 |
} |
2482 |
|
2483 |
/* |
2484 |
* The TLS connection is realized by a BIO_pair, so obtain the pair. |
2485 |
*/ |
2486 |
if (!BIO_new_bio_pair(&TLScontext->internal_bio, BIO_bufsiz, |
2487 |
&TLScontext->network_bio, BIO_bufsiz)) { |
2488 |
msg_info("Could not obtain BIO_pair"); |
2489 |
pfixtls_print_errors(); |
2490 |
SSL_free(TLScontext->con); |
2491 |
myfree((char *)TLScontext); |
2492 |
return (-1); |
2493 |
} |
2494 |
|
2495 |
old_session = NULL; |
2496 |
|
2497 |
/* |
2498 |
* Find out the hashed HostID for the client cache and try to |
2499 |
* load the session from the cache. |
2500 |
*/ |
2501 |
strncpy(TLScontext->peername_save, peername, ID_MAXLENGTH + 1); |
2502 |
TLScontext->peername_save[ID_MAXLENGTH] = '\0'; /* just in case */ |
2503 |
(void)lowercase(TLScontext->peername_save); |
2504 |
if (scache_db) { |
2505 |
old_session = load_clnt_session(peername, enforce_peername); |
2506 |
if (old_session) { |
2507 |
SSL_set_session(TLScontext->con, old_session); |
2508 |
#if (OPENSSL_VERSION_NUMBER < 0x00906011L) || (OPENSSL_VERSION_NUMBER == 0x00907000L) |
2509 |
/* |
2510 |
* Ugly Hack: OpenSSL before 0.9.6a does not store the verify |
2511 |
* result in sessions for the client side. |
2512 |
* We modify the session directly which is version specific, |
2513 |
* but this bug is version specific, too. |
2514 |
* |
2515 |
* READ: 0-09-06-01-1 = 0-9-6-a-beta1: all versions before |
2516 |
* beta1 have this bug, it has been fixed during development |
2517 |
* of 0.9.6a. The development version of 0.9.7 can have this |
2518 |
* bug, too. It has been fixed on 2000/11/29. |
2519 |
*/ |
2520 |
SSL_set_verify_result(TLScontext->con, old_session->verify_result); |
2521 |
#endif |
2522 |
|
2523 |
} |
2524 |
} |
2525 |
|
2526 |
/* |
2527 |
* Before really starting anything, try to seed the PRNG a little bit |
2528 |
* more. |
2529 |
*/ |
2530 |
pfixtls_stir_seed(); |
2531 |
pfixtls_exchange_seed(); |
2532 |
|
2533 |
/* |
2534 |
* Initialize the SSL connection to connect state. This should not be |
2535 |
* necessary anymore since 0.9.3, but the call is still in the library |
2536 |
* and maintaining compatibility never hurts. |
2537 |
*/ |
2538 |
SSL_set_connect_state(TLScontext->con); |
2539 |
|
2540 |
/* |
2541 |
* Connect the SSL-connection with the postfix side of the BIO-pair for |
2542 |
* reading and writing. |
2543 |
*/ |
2544 |
SSL_set_bio(TLScontext->con, TLScontext->internal_bio, |
2545 |
TLScontext->internal_bio); |
2546 |
|
2547 |
/* |
2548 |
* If the debug level selected is high enough, all of the data is |
2549 |
* dumped: 3 will dump the SSL negotiation, 4 will dump everything. |
2550 |
* |
2551 |
* We do have an SSL_set_fd() and now suddenly a BIO_ routine is called? |
2552 |
* Well there is a BIO below the SSL routines that is automatically |
2553 |
* created for us, so we can use it for debugging purposes. |
2554 |
*/ |
2555 |
if (var_smtp_tls_loglevel >= 3) |
2556 |
BIO_set_callback(SSL_get_rbio(TLScontext->con), bio_dump_cb); |
2557 |
|
2558 |
|
2559 |
/* Dump the negotiation for loglevels 3 and 4 */ |
2560 |
if (var_smtp_tls_loglevel >= 3) |
2561 |
do_dump = 1; |
2562 |
|
2563 |
/* |
2564 |
* Now we expect the negotiation to begin. This whole process is like a |
2565 |
* black box for us. We totally have to rely on the routines build into |
2566 |
* the OpenSSL library. The only thing we can do we already have done |
2567 |
* by choosing our own callback certificate verification. |
2568 |
* |
2569 |
* Error handling: |
2570 |
* If the SSL handhake fails, we print out an error message and remove |
2571 |
* everything that might be there. A session has to be removed anyway, |
2572 |
* because RFC2246 requires it. |
2573 |
*/ |
2574 |
sts = do_tls_operation(vstream_fileno(stream), timeout, TLScontext, |
2575 |
SSL_connect, NULL, NULL, NULL, 0); |
2576 |
if (sts <= 0) { |
2577 |
msg_info("SSL_connect error to %s: %d", peername, sts); |
2578 |
pfixtls_print_errors(); |
2579 |
session = SSL_get_session(TLScontext->con); |
2580 |
if (session) { |
2581 |
SSL_CTX_remove_session(ctx, session); |
2582 |
if (var_smtp_tls_loglevel >= 2) |
2583 |
msg_info("SSL session removed"); |
2584 |
} |
2585 |
if ((old_session) && (!SSL_session_reused(TLScontext->con))) |
2586 |
SSL_SESSION_free(old_session); /* Must also be removed */ |
2587 |
SSL_free(TLScontext->con); |
2588 |
myfree((char *)TLScontext); |
2589 |
return (-1); |
2590 |
} |
2591 |
|
2592 |
if (!SSL_session_reused(TLScontext->con)) { |
2593 |
SSL_SESSION_free(old_session); /* Remove unused session */ |
2594 |
} |
2595 |
else if (var_smtp_tls_loglevel >= 3) |
2596 |
msg_info("Reusing old session"); |
2597 |
|
2598 |
/* Only loglevel==4 dumps everything */ |
2599 |
if (var_smtp_tls_loglevel < 4) |
2600 |
do_dump = 0; |
2601 |
|
2602 |
/* |
2603 |
* Lets see, whether a peer certificate is available and what is |
2604 |
* the actual information. We want to save it for later use. |
2605 |
*/ |
2606 |
peer = SSL_get_peer_certificate(TLScontext->con); |
2607 |
if (peer != NULL) { |
2608 |
if (SSL_get_verify_result(TLScontext->con) == X509_V_OK) |
2609 |
tls_info->peer_verified = 1; |
2610 |
|
2611 |
TLScontext->peer_CN[0] = '\0'; |
2612 |
if (!X509_NAME_get_text_by_NID(X509_get_subject_name(peer), |
2613 |
NID_commonName, TLScontext->peer_CN, CCERT_BUFSIZ)) { |
2614 |
msg_info("Could not parse server's subject CN"); |
2615 |
pfixtls_print_errors(); |
2616 |
} |
2617 |
tls_info->peer_CN = TLScontext->peer_CN; |
2618 |
|
2619 |
TLScontext->issuer_CN[0] = '\0'; |
2620 |
if (!X509_NAME_get_text_by_NID(X509_get_issuer_name(peer), |
2621 |
NID_commonName, TLScontext->issuer_CN, CCERT_BUFSIZ)) { |
2622 |
msg_info("Could not parse server's issuer CN"); |
2623 |
pfixtls_print_errors(); |
2624 |
} |
2625 |
if (!TLScontext->issuer_CN[0]) { |
2626 |
/* No issuer CN field, use Organization instead */ |
2627 |
if (!X509_NAME_get_text_by_NID(X509_get_issuer_name(peer), |
2628 |
NID_organizationName, TLScontext->issuer_CN, CCERT_BUFSIZ)) { |
2629 |
msg_info("Could not parse server's issuer Organization"); |
2630 |
pfixtls_print_errors(); |
2631 |
} |
2632 |
} |
2633 |
tls_info->issuer_CN = TLScontext->issuer_CN; |
2634 |
|
2635 |
if (var_smtp_tls_loglevel >= 1) { |
2636 |
if (tls_info->peer_verified) |
2637 |
msg_info("Verified: subject_CN=%s, issuer=%s", |
2638 |
TLScontext->peer_CN, TLScontext->issuer_CN); |
2639 |
else |
2640 |
msg_info("Unverified: subject_CN=%s, issuer=%s", |
2641 |
TLScontext->peer_CN, TLScontext->issuer_CN); |
2642 |
} |
2643 |
X509_free(peer); |
2644 |
} |
2645 |
|
2646 |
/* |
2647 |
* Finally, collect information about protocol and cipher for logging |
2648 |
*/ |
2649 |
tls_info->protocol = SSL_get_version(TLScontext->con); |
2650 |
cipher = SSL_get_current_cipher(TLScontext->con); |
2651 |
tls_info->cipher_name = SSL_CIPHER_get_name(cipher); |
2652 |
tls_info->cipher_usebits = SSL_CIPHER_get_bits(cipher, |
2653 |
&(tls_info->cipher_algbits)); |
2654 |
|
2655 |
pfixtls_clientactive = 1; |
2656 |
|
2657 |
/* |
2658 |
* The TLS engine is active, switch to the pfixtls_timed_read/write() |
2659 |
* functions. |
2660 |
*/ |
2661 |
vstream_control(stream, |
2662 |
VSTREAM_CTL_READ_FN, pfixtls_timed_read, |
2663 |
VSTREAM_CTL_WRITE_FN, pfixtls_timed_write, |
2664 |
VSTREAM_CTL_CONTEXT, (void *)TLScontext, |
2665 |
VSTREAM_CTL_END); |
2666 |
|
2667 |
msg_info("TLS connection established to %s: %s with cipher %s (%d/%d bits)", |
2668 |
peername, |
2669 |
tls_info->protocol, tls_info->cipher_name, |
2670 |
tls_info->cipher_usebits, tls_info->cipher_algbits); |
2671 |
|
2672 |
pfixtls_stir_seed(); |
2673 |
|
2674 |
return (0); |
2675 |
} |
2676 |
|
2677 |
/* |
2678 |
* Shut down the TLS connection, that does mean: remove all the information |
2679 |
* and reset the flags! This is needed if the actual running smtp is to |
2680 |
* be restarted. We do not give back any value, as there is nothing to |
2681 |
* be reported. |
2682 |
* Since our session cache is external, we will remove the session from |
2683 |
* memory in any case. The SSL_CTX_flush_sessions might be redundant here, |
2684 |
* I however want to make sure nothing is left. |
2685 |
* RFC2246 requires us to remove sessions if something went wrong, as |
2686 |
* indicated by the "failure" value,so we remove it from the external |
2687 |
* cache, too. |
2688 |
*/ |
2689 |
int pfixtls_stop_clienttls(VSTREAM *stream, int timeout, int failure, |
2690 |
tls_info_t *tls_info) |
2691 |
{ |
2692 |
TLScontext_t *TLScontext; |
2693 |
int retval; |
2694 |
|
2695 |
if (pfixtls_clientactive) { |
2696 |
TLScontext = (TLScontext_t *)vstream_context(stream); |
2697 |
/* |
2698 |
* Perform SSL_shutdown() twice, as the first attempt may return |
2699 |
* to early: it will only send out the shutdown alert but it will |
2700 |
* not wait for the peer's shutdown alert. Therefore, when we are |
2701 |
* the first party to send the alert, we must call SSL_shutdown() |
2702 |
* again. |
2703 |
* On failure we don't want to resume the session, so we will not |
2704 |
* perform SSL_shutdown() and the session will be removed as being |
2705 |
* bad. |
2706 |
*/ |
2707 |
if (!failure) { |
2708 |
retval = do_tls_operation(vstream_fileno(stream), timeout, |
2709 |
TLScontext, SSL_shutdown, NULL, NULL, NULL, 0); |
2710 |
if (retval == 0) |
2711 |
do_tls_operation(vstream_fileno(stream), timeout, TLScontext, |
2712 |
SSL_shutdown, NULL, NULL, NULL, 0); |
2713 |
} |
2714 |
/* |
2715 |
* Free the SSL structure and the BIOs. Warning: the internal_bio is |
2716 |
* connected to the SSL structure and is automatically freed with |
2717 |
* it. Do not free it again (core dump)!! |
2718 |
* Only free the network_bio. |
2719 |
*/ |
2720 |
SSL_free(TLScontext->con); |
2721 |
BIO_free(TLScontext->network_bio); |
2722 |
myfree((char *)TLScontext); |
2723 |
vstream_control(stream, |
2724 |
VSTREAM_CTL_READ_FN, (VSTREAM_FN) NULL, |
2725 |
VSTREAM_CTL_WRITE_FN, (VSTREAM_FN) NULL, |
2726 |
VSTREAM_CTL_CONTEXT, (void *) NULL, |
2727 |
VSTREAM_CTL_END); |
2728 |
SSL_CTX_flush_sessions(ctx, time(NULL)); |
2729 |
|
2730 |
pfixtls_stir_seed(); |
2731 |
pfixtls_exchange_seed(); |
2732 |
|
2733 |
*tls_info = tls_info_zero; |
2734 |
pfixtls_clientactive = 0; |
2735 |
|
2736 |
} |
2737 |
|
2738 |
return (0); |
2739 |
} |
2740 |
|
2741 |
|
2742 |
#endif /* HAS_SSL */ |