]> Pileus Git - ~andy/fetchmail/blob - socket.c
Merge branch 'legacy_63'
[~andy/fetchmail] / socket.c
1 /*
2  * socket.c -- socket library functions
3  *
4  * Copyright 1998, 2004 by Eric S. Raymond.
5  * Copyright 2004, 2013 by Matthias Andree.
6  *
7  * For license terms, see the file COPYING in this directory.
8  */
9
10 #include "config.h"
11 #include <stdio.h>
12 #include <errno.h>
13 #include <string.h>
14 #include <ctype.h> /* isspace() */
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <sys/socket.h>
18 #include <sys/un.h>
19 #include <netinet/in.h>
20 #include <arpa/inet.h>
21 #include <netdb.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <stdarg.h>
25 #include <sys/time.h>
26 #include <time.h>
27
28 #include "socket.h"
29 #include "fetchmail.h"
30 #include "getaddrinfo.h"
31 #include "gettext.h"
32 #include "sdump.h"
33
34 /* Defines to allow Cygwin to play nice... */
35 #define fm_close(a)      close(a)
36 #define fm_write(a,b,c)  write(a,b,c)
37 #define fm_peek(a,b,c)   recv(a,b,c, MSG_PEEK)
38
39 #ifdef __CYGWIN__
40 #define fm_read(a,b,c)   cygwin_read(a,b,c)
41 static ssize_t cygwin_read(int sock, void *buf, size_t count);
42 #else /* ! __CYGWIN__ */
43 #define fm_read(a,b,c)   read(a,b,c)
44 #endif /* __CYGWIN__ */
45
46 /* We need to define h_errno only if it is not already */
47 #ifndef h_errno
48 # if !HAVE_DECL_H_ERRNO
49 extern int h_errno;
50 # endif
51 #endif /* ndef h_errno */
52
53 /* used by SSL_get_ex_new_index, SSL_set_ex_data, SSL_get_ex_data, to communicate
54    options and state with the verify callback */
55 static int global_mydata_index = -2;
56
57 static char *const *parse_plugin(const char *plugin, const char *host, const char *service)
58 {
59         char **argvec;
60         const char *c, *p;
61         char *cp, *plugin_copy;
62         unsigned int plugin_copy_len;
63         unsigned int plugin_offset = 0, plugin_copy_offset = 0;
64         unsigned int i, s = 2 * sizeof(char*), host_count = 0, service_count = 0;
65         unsigned int plugin_len = strlen(plugin);
66         unsigned int host_len = strlen(host);
67         unsigned int service_len = strlen(service);
68
69         for (c = p = plugin; *c; c++)
70         {       if (isspace((unsigned char)*c) && !isspace((unsigned char)*p))
71                         s += sizeof(char*);
72                 if (*p == '%' && *c == 'h')
73                         host_count++;
74                 if (*p == '%' && *c == 'p')
75                         service_count++;
76                 p = c;
77         }
78
79         plugin_copy_len = plugin_len + host_len * host_count + service_len * service_count;
80         plugin_copy = (char *)malloc(plugin_copy_len + 1);
81         if (!plugin_copy)
82         {
83                 report(stderr, GT_("fetchmail: malloc failed\n"));
84                 return NULL;
85         }
86
87         while (plugin_copy_offset < plugin_copy_len)
88         {       if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'h'))
89                 {       strcpy(plugin_copy + plugin_copy_offset, host);
90                         plugin_offset += 2;
91                         plugin_copy_offset += host_len;
92                 }
93                 else if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'p'))
94                 {       strcpy(plugin_copy + plugin_copy_offset, service);
95                         plugin_offset += 2;
96                         plugin_copy_offset += service_len;
97                 }
98                 else
99                 {       plugin_copy[plugin_copy_offset] = plugin[plugin_offset];
100                         plugin_offset++;
101                         plugin_copy_offset++;
102                 }
103         }
104         plugin_copy[plugin_copy_len] = 0;
105
106         argvec = (char **)malloc(s);
107         if (!argvec)
108         {
109                 free(plugin_copy);
110                 report(stderr, GT_("fetchmail: malloc failed\n"));
111                 return NULL;
112         }
113         memset(argvec, 0, s);
114         for (p = cp = plugin_copy, i = 0; *cp; cp++)
115         {       if ((!isspace((unsigned char)*cp)) && (cp == p ? 1 : isspace((unsigned char)*p))) {
116                         argvec[i] = cp;
117                         i++;
118                 }
119                 p = cp;
120         }
121         for (cp = plugin_copy; *cp; cp++)
122         {       if (isspace((unsigned char)*cp))
123                         *cp = 0;
124         }
125         return argvec;
126 }
127
128 static int handle_plugin(const char *host,
129                          const char *service, const char *plugin)
130 /* get a socket mediated through a given external command */
131 {
132     int fds[2];
133     char *const *argvec;
134
135     /*
136      * The author of this code, Felix von Leitner <felix@convergence.de>, says:
137      * he chose socketpair() instead of pipe() because socketpair creates 
138      * bidirectional sockets while allegedly some pipe() implementations don't.
139      */
140     if (socketpair(AF_UNIX,SOCK_STREAM,0,fds))
141     {
142         report(stderr, GT_("fetchmail: socketpair failed\n"));
143         return -1;
144     }
145     switch (fork()) {
146         case -1:
147                 /* error */
148                 report(stderr, GT_("fetchmail: fork failed\n"));
149                 return -1;
150         case 0: /* child */
151                 /* fds[1] is the parent's end; close it for proper EOF
152                 ** detection */
153                 (void) close(fds[1]);
154                 if ( (dup2(fds[0],0) == -1) || (dup2(fds[0],1) == -1) ) {
155                         report(stderr, GT_("dup2 failed\n"));
156                         _exit(EXIT_FAILURE);
157                 }
158                 /* fds[0] is now connected to 0 and 1; close it */
159                 (void) close(fds[0]);
160                 if (outlevel >= O_VERBOSE)
161                     report(stderr, GT_("running %s (host %s service %s)\n"), plugin, host, service);
162                 argvec = parse_plugin(plugin,host,service);
163                 if (argvec == NULL)
164                         _exit(EXIT_FAILURE);
165                 execvp(*argvec, argvec);
166                 report(stderr, GT_("execvp(%s) failed\n"), *argvec);
167                 _exit(EXIT_FAILURE);
168                 break;
169         default:        /* parent */
170                 /* NOP */
171                 break;
172     }
173     /* fds[0] is the child's end; close it for proper EOF detection */
174     (void) close(fds[0]);
175     return fds[1];
176 }
177
178 /** Set socket to SO_KEEPALIVE. \return 0 for success. */
179 int SockKeepalive(int sock) {
180     int keepalive = 1;
181     return setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof keepalive);
182 }
183
184 int UnixOpen(const char *path)
185 {
186     int sock = -1;
187     struct sockaddr_un ad;
188     memset(&ad, 0, sizeof(ad));
189     ad.sun_family = AF_UNIX;
190     strncpy(ad.sun_path, path, sizeof(ad.sun_path)-1);
191
192     sock = socket( AF_UNIX, SOCK_STREAM, 0 );
193     if (sock < 0)
194     {
195         h_errno = 0;
196         return -1;
197     }
198
199     /* Socket opened saved. Useful if connect timeout
200      * because it can be closed.
201      */
202     mailserver_socket_temp = sock;
203
204     if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
205     {
206         int olderr = errno;
207         fm_close(sock); /* don't use SockClose, no traffic yet */
208         h_errno = 0;
209         errno = olderr;
210         sock = -1;
211     }
212
213     /* No connect timeout, then no need to set mailserver_socket_temp */
214     mailserver_socket_temp = -1;
215
216     return sock;
217 }
218
219 int SockOpen(const char *host, const char *service,
220              const char *plugin, struct addrinfo **ai0)
221 {
222     struct addrinfo *ai, req;
223     int i, acterr = 0;
224     int ord;
225     char errbuf[8192] = "";
226
227     if (plugin)
228         return handle_plugin(host,service,plugin);
229
230     memset(&req, 0, sizeof(struct addrinfo));
231     req.ai_socktype = SOCK_STREAM;
232 #ifdef AI_ADDRCONFIG
233     req.ai_flags = AI_ADDRCONFIG;
234 #endif
235
236     i = fm_getaddrinfo(host, service, &req, ai0);
237     if (i) {
238         report(stderr, GT_("getaddrinfo(\"%s\",\"%s\") error: %s\n"),
239                 host, service, gai_strerror(i));
240         if (i == EAI_SERVICE)
241             report(stderr, GT_("Try adding the --service option (see also FAQ item R12).\n"));
242         return -1;
243     }
244
245     /* NOTE a Linux bug here - getaddrinfo will happily return 127.0.0.1
246      * twice if no IPv6 is configured */
247     i = -1;
248     for (ord = 0, ai = *ai0; ai; ord++, ai = ai->ai_next) {
249         char buf[256]; /* hostname */
250         char pb[256];  /* service name */
251         int gnie;      /* getnameinfo result code */
252
253         gnie = getnameinfo(ai->ai_addr, ai->ai_addrlen, buf, sizeof(buf), NULL, 0, NI_NUMERICHOST);
254         if (gnie)
255             snprintf(buf, sizeof(buf), GT_("unknown (%s)"), gai_strerror(gnie));
256         gnie = getnameinfo(ai->ai_addr, ai->ai_addrlen, NULL, 0, pb, sizeof(pb), NI_NUMERICSERV);
257         if (gnie)
258             snprintf(pb, sizeof(pb), GT_("unknown (%s)"), gai_strerror(gnie));
259
260         if (outlevel >= O_VERBOSE)
261             report_build(stdout, GT_("Trying to connect to %s/%s..."), buf, pb);
262         i = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
263         if (i < 0) {
264             int e = errno;
265             /* mask EAFNOSUPPORT errors, they confuse users for
266              * multihomed hosts */
267             if (errno != EAFNOSUPPORT)
268                 acterr = errno;
269             if (outlevel >= O_VERBOSE)
270                 report_complete(stdout, GT_("cannot create socket: %s\n"), strerror(e));
271             snprintf(errbuf+strlen(errbuf), sizeof(errbuf)-strlen(errbuf),\
272                      GT_("name %d: cannot create socket family %d type %d: %s\n"), ord, ai->ai_family, ai->ai_socktype, strerror(e));
273             continue;
274         }
275
276         SockKeepalive(i);
277
278         /* Save socket descriptor.
279          * Used to close the socket after connect timeout. */
280         mailserver_socket_temp = i;
281
282         if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
283             int e = errno;
284
285             /* additionally, suppress IPv4 network unreach errors */
286             if (e != EAFNOSUPPORT)
287                 acterr = errno;
288
289             if (outlevel >= O_VERBOSE)
290                 report_complete(stdout, GT_("connection failed.\n"));
291             if (outlevel >= O_VERBOSE)
292                 report(stderr, GT_("connection to %s:%s [%s/%s] failed: %s.\n"), host, service, buf, pb, strerror(e));
293             snprintf(errbuf+strlen(errbuf), sizeof(errbuf)-strlen(errbuf), GT_("name %d: connection to %s:%s [%s/%s] failed: %s.\n"), ord, host, service, buf, pb, strerror(e));
294             fm_close(i);
295             i = -1;
296             continue;
297         } else {
298             if (outlevel >= O_VERBOSE)
299                 report_complete(stdout, GT_("connected.\n"));
300         }
301
302         /* No connect timeout, then no need to set mailserver_socket_temp */
303         mailserver_socket_temp = -1;
304
305         break;
306     }
307
308     fm_freeaddrinfo(*ai0);
309     *ai0 = NULL;
310
311     if (i == -1) {
312         report(stderr, GT_("Connection errors for this poll:\n%s"), errbuf);
313         errno = acterr;
314     }
315
316     return i;
317 }
318
319 int SockPrintf(int sock, const char* format, ...)
320 {
321     va_list ap;
322     char buf[8192];
323
324     va_start(ap, format) ;
325     vsnprintf(buf, sizeof(buf), format, ap);
326     va_end(ap);
327     return SockWrite(sock, buf, strlen(buf));
328 }
329
330 #ifdef SSL_ENABLE
331 #define OPENSSL_NO_SSL_INTERN 1
332 #include <openssl/ssl.h>
333 #include <openssl/err.h>
334 #include <openssl/pem.h>
335 #include <openssl/x509v3.h>
336 #include <openssl/rand.h>
337
338 static void report_SSL_errors(FILE *stream)
339 {
340     unsigned long err;
341
342     while (0ul != (err = ERR_get_error())) {
343         char *errstr = ERR_error_string(err, NULL);
344         report(stream, GT_("OpenSSL reported: %s\n"), errstr);
345     }
346 }
347
348 /* override ERR_print_errors_fp to our own implementation */
349 #undef ERR_print_errors_fp
350 #define ERR_print_errors_fp(stream) report_SSL_errors((stream))
351
352 static  SSL_CTX *_ctx[FD_SETSIZE];
353 static  SSL *_ssl_context[FD_SETSIZE];
354
355 static SSL      *SSLGetContext( int );
356 #endif /* SSL_ENABLE */
357
358 int SockWrite(int sock, const char *buf, int len)
359 {
360     int n, wrlen = 0;
361 #ifdef  SSL_ENABLE
362     SSL *ssl;
363 #endif
364
365     while (len)
366     {
367 #ifdef SSL_ENABLE
368         if( NULL != ( ssl = SSLGetContext( sock ) ) )
369                 n = SSL_write(ssl, buf, len);
370         else
371 #endif /* SSL_ENABLE */
372             n = fm_write(sock, buf, len);
373         if (n <= 0)
374             return -1;
375         len -= n;
376         wrlen += n;
377         buf += n;
378     }
379     return wrlen;
380 }
381
382 int SockRead(int sock, char *buf, int len)
383 {
384     char *newline, *bp = buf;
385     int n;
386 #ifdef  SSL_ENABLE
387     SSL *ssl;
388 #endif
389
390     if (--len < 1)
391         return(-1);
392     do {
393         /* 
394          * The reason for these gymnastics is that we want two things:
395          * (1) to read \n-terminated lines,
396          * (2) to return the true length of data read, even if the
397          *     data coming in has embedded NULS.
398          */
399 #ifdef  SSL_ENABLE
400         if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
401                 /* Hack alert! */
402                 /* OK...  SSL_peek works a little different from MSG_PEEK
403                         Problem is that SSL_peek can return 0 if there
404                         is no data currently available.  If, on the other
405                         hand, we lose the socket, we also get a zero, but
406                         the SSL_read then SEGFAULTS!  To deal with this,
407                         we'll check the error code any time we get a return
408                         of zero from SSL_peek.  If we have an error, we bail.
409                         If we don't, we read one character in SSL_read and
410                         loop.  This should continue to work even if they
411                         later change the behavior of SSL_peek
412                         to "fix" this problem...  :-(   */
413                 if ((n = SSL_peek(ssl, bp, len)) < 0) {
414                         (void)SSL_get_error(ssl, n);
415                         return(-1);
416                 }
417                 if( 0 == n ) {
418                         /* SSL_peek says no data...  Does he mean no data
419                         or did the connection blow up?  If we got an error
420                         then bail! */
421                         if (0 != SSL_get_error(ssl, n)) {
422                                 return -1;
423                         }
424                         /* We didn't get an error so read at least one
425                                 character at this point and loop */
426                         n = 1;
427                         /* Make sure newline start out NULL!
428                          * We don't have a string to pass through
429                          * the strchr at this point yet */
430                         newline = NULL;
431                 } else if ((newline = (char *)memchr(bp, '\n', n)) != NULL)
432                         n = newline - bp + 1;
433                 /* Matthias Andree: SSL_read can return 0, in that case
434                  * we must call SSL_get_error to figure if there was
435                  * an error or just a "no data" condition */
436                 if ((n = SSL_read(ssl, bp, n)) <= 0) {
437                         if ((n = SSL_get_error(ssl, n))) {
438                                 return(-1);
439                         }
440                 }
441                 /* Check for case where our single character turned out to
442                  * be a newline...  (It wasn't going to get caught by
443                  * the strchr above if it came from the hack...  ). */
444                 if( NULL == newline && 1 == n && '\n' == *bp ) {
445                         /* Got our newline - this will break
446                                 out of the loop now */
447                         newline = bp;
448                 }
449         }
450         else
451 #endif /* SSL_ENABLE */
452         {
453
454             if ((n = fm_peek(sock, bp, len)) <= 0)
455                 return (-1);
456             if ((newline = (char *)memchr(bp, '\n', n)) != NULL)
457                 n = newline - bp + 1;
458             if ((n = fm_read(sock, bp, n)) == -1)
459                 return(-1);
460         }
461         bp += n;
462         len -= n;
463     } while 
464             (!newline && len);
465     *bp = '\0';
466
467     return bp - buf;
468 }
469
470 int SockPeek(int sock)
471 /* peek at the next socket character without actually reading it */
472 {
473     int n;
474     char ch;
475 #ifdef  SSL_ENABLE
476     SSL *ssl;
477 #endif
478
479 #ifdef  SSL_ENABLE
480         if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
481                 n = SSL_peek(ssl, &ch, 1);
482                 if (n < 0) {
483                         (void)SSL_get_error(ssl, n);
484                         return -1;
485                 }
486                 if( 0 == n ) {
487                         /* This code really needs to implement a "hold back"
488                          * to simulate a functioning SSL_peek()...  sigh...
489                          * Has to be coordinated with the read code above.
490                          * Next on the list todo...     */
491
492                         /* SSL_peek says 0...  Does that mean no data
493                         or did the connection blow up?  If we got an error
494                         then bail! */
495                         if(0 != SSL_get_error(ssl, n)) {
496                                 return -1;
497                         }
498
499                         /* Haven't seen this case actually occur, but...
500                            if the problem in SockRead can occur, this should
501                            be possible...  Just not sure what to do here.
502                            This should be a safe "punt" the "peek" but don't
503                            "punt" the "session"... */
504
505                         return 0;       /* Give him a '\0' character */
506                 }
507         }
508         else
509 #endif /* SSL_ENABLE */
510             n = fm_peek(sock, &ch, 1);
511         if (n == -1)
512                 return -1;
513
514     return(ch);
515 }
516
517 #ifdef SSL_ENABLE
518
519 struct ssl_callback_data {
520     char *ssl_server_cname;
521     char *check_digest;
522     char *server_label;
523     int check_fp;
524     int depth0ck;
525     int firstrun;
526     int prev_err;
527     int verify_ok;
528     int strict_mode;
529 };
530
531 typedef struct ssl_callback_data t_ssl_callback_data;
532
533 SSL *SSLGetContext( int sock )
534 {
535         if( sock < 0 || (unsigned)sock > FD_SETSIZE )
536                 return NULL;
537         if( _ctx[sock] == NULL )
538                 return NULL;
539         return _ssl_context[sock];
540 }
541
542 /* ok_return (preverify_ok) is 1 if this stage of certificate verification
543    passed, or 0 if it failed. This callback lets us display informative
544    errors, and perform additional validation (e.g. CN matches) */
545 static int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx)
546 {
547 #define SSLverbose (((outlevel) >= O_DEBUG) || ((outlevel) >= O_VERBOSE && (depth) == 0)) 
548         char buf[257];
549         X509 *x509_cert;
550         int err, depth, i;
551         unsigned char digest[EVP_MAX_MD_SIZE];
552         char text[EVP_MAX_MD_SIZE * 3 + 1], *tp, *te;
553         const EVP_MD *digest_tp;
554         unsigned int dsz, esz;
555         X509_NAME *subj, *issuer;
556         char *tt;
557         t_ssl_callback_data *mydata;
558         SSL *ssl;
559
560         ssl = (SSL *)X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
561         mydata = (t_ssl_callback_data *)SSL_get_ex_data(ssl, global_mydata_index);
562         x509_cert = X509_STORE_CTX_get_current_cert(ctx);
563         err = X509_STORE_CTX_get_error(ctx);
564         depth = X509_STORE_CTX_get_error_depth(ctx);
565
566         subj = X509_get_subject_name(x509_cert);
567         issuer = X509_get_issuer_name(x509_cert);
568
569         if (outlevel >= O_VERBOSE) {
570                 if (depth == 0 && SSLverbose)
571                         report(stdout, GT_("Server certificate:\n"));
572                 else {
573                         if (mydata->firstrun) {
574                                 mydata->firstrun = 0;
575                                 if (SSLverbose)
576                                         report(stdout, GT_("Certificate chain, from root to peer, starting at depth %d:\n"), depth);
577                         } else {
578                                 if (SSLverbose)
579                                         report(stdout, GT_("Certificate at depth %d:\n"), depth);
580                         }
581                 }
582
583                 if (SSLverbose) {
584                         if ((i = X509_NAME_get_text_by_NID(issuer, NID_organizationName, buf, sizeof(buf))) != -1) {
585                                 report(stdout, GT_("Issuer Organization: %s\n"), (tt = sdump(buf, i)));
586                                 xfree(tt);
587                                 if ((size_t)i >= sizeof(buf) - 1)
588                                         report(stdout, GT_("Warning: Issuer Organization Name too long (possibly truncated).\n"));
589                         } else
590                                 report(stdout, GT_("Unknown Organization\n"));
591                         if ((i = X509_NAME_get_text_by_NID(issuer, NID_commonName, buf, sizeof(buf))) != -1) {
592                                 report(stdout, GT_("Issuer CommonName: %s\n"), (tt = sdump(buf, i)));
593                                 xfree(tt);
594                                 if ((size_t)i >= sizeof(buf) - 1)
595                                         report(stdout, GT_("Warning: Issuer CommonName too long (possibly truncated).\n"));
596                         } else
597                                 report(stdout, GT_("Unknown Issuer CommonName\n"));
598                 }
599         }
600
601         if ((i = X509_NAME_get_text_by_NID(subj, NID_commonName, buf, sizeof(buf))) != -1) {
602                 if (SSLverbose) {
603                         report(stdout, GT_("Subject CommonName: %s\n"), (tt = sdump(buf, i)));
604                         xfree(tt);
605                 }
606                 if ((size_t)i >= sizeof(buf) - 1) {
607                         /* Possible truncation. In this case, this is a DNS name, so this
608                          * is really bad. We do not tolerate this even in the non-strict case. */
609                         report(stderr, GT_("Bad certificate: Subject CommonName too long!\n"));
610                         return (0);
611                 }
612                 if ((size_t)i > strlen(buf)) {
613                         /* Name contains embedded NUL characters, so we complain. This is likely
614                          * a certificate spoofing attack. */
615                         report(stderr, GT_("Bad certificate: Subject CommonName contains NUL, aborting!\n"));
616                         return 0;
617                 }
618         }
619
620         if (depth == 0) { /* peer certificate */
621                 if (!mydata->depth0ck) {
622                         mydata->depth0ck = 1;
623                 }
624
625                 if ((i = X509_NAME_get_text_by_NID(subj, NID_commonName, buf, sizeof(buf))) != -1) {
626                         if (mydata->ssl_server_cname != NULL) {
627                                 char *p1 = buf;
628                                 char *p2 = mydata->ssl_server_cname;
629                                 int matched = 0;
630                                 STACK_OF(GENERAL_NAME) *gens;
631
632                                 /* RFC 2595 section 2.4: find a matching name
633                                  * first find a match among alternative names */
634                                 gens = (STACK_OF(GENERAL_NAME) *)X509_get_ext_d2i(x509_cert, NID_subject_alt_name, NULL, NULL);
635                                 if (gens) {
636                                         int j, r;
637                                         for (j = 0, r = sk_GENERAL_NAME_num(gens); j < r; ++j) {
638                                                 const GENERAL_NAME *gn = sk_GENERAL_NAME_value(gens, j);
639                                                 if (gn->type == GEN_DNS) {
640                                                         char *pp1 = (char *)gn->d.ia5->data;
641                                                         char *pp2 = mydata->ssl_server_cname;
642                                                         if (outlevel >= O_VERBOSE) {
643                                                                 report(stdout, GT_("Subject Alternative Name: %s\n"), (tt = sdump(pp1, (size_t)gn->d.ia5->length)));
644                                                                 xfree(tt);
645                                                         }
646                                                         /* Name contains embedded NUL characters, so we complain. This
647                                                          * is likely a certificate spoofing attack. */
648                                                         if ((size_t)gn->d.ia5->length != strlen(pp1)) {
649                                                                 report(stderr, GT_("Bad certificate: Subject Alternative Name contains NUL, aborting!\n"));
650                                                                 sk_GENERAL_NAME_free(gens);
651                                                                 return 0;
652                                                         }
653                                                         if (name_match(pp1, pp2)) {
654                                                             matched = 1;
655                                                         }
656                                                 }
657                                         }
658                                         GENERAL_NAMES_free(gens);
659                                 }
660                                 if (name_match(p1, p2)) {
661                                         matched = 1;
662                                 }
663                                 if (!matched) {
664                                         if (mydata->strict_mode || SSLverbose) {
665                                                 report(stderr,
666                                                                 GT_("Server CommonName mismatch: %s != %s\n"),
667                                                                 (tt = sdump(buf, i)), mydata->ssl_server_cname);
668                                                 xfree(tt);
669                                         }
670                                         ok_return = 0;
671                                 }
672                         } else if (ok_return) {
673                                 report(stderr, GT_("Server name not set, could not verify certificate!\n"));
674                                 if (mydata->strict_mode) return (0);
675                         }
676                 } else {
677                         if (outlevel >= O_VERBOSE)
678                                 report(stdout, GT_("Unknown Server CommonName\n"));
679                         if (ok_return && mydata->strict_mode) {
680                                 report(stderr, GT_("Server name not specified in certificate!\n"));
681                                 return (0);
682                         }
683                 }
684                 /* Print the finger print. Note that on errors, we might print it more than once
685                  * normally; we kluge around that by using a global variable. */
686                 if (1 == mydata->check_fp) {
687                         unsigned dp;
688
689                         mydata->check_fp = -1;
690                         digest_tp = EVP_md5();
691                         if (digest_tp == NULL) {
692                                 report(stderr, GT_("EVP_md5() failed!\n"));
693                                 return (0);
694                         }
695                         if (!X509_digest(x509_cert, digest_tp, digest, &dsz)) {
696                                 report(stderr, GT_("Out of memory!\n"));
697                                 return (0);
698                         }
699                         tp = text;
700                         te = text + sizeof(text);
701                         for (dp = 0; dp < dsz; dp++) {
702                                 esz = snprintf(tp, te - tp, dp > 0 ? ":%02X" : "%02X", digest[dp]);
703                                 if (esz >= (size_t)(te - tp)) {
704                                         report(stderr, GT_("Digest text buffer too small!\n"));
705                                         return (0);
706                                 }
707                                 tp += esz;
708                         }
709                         if (outlevel > O_NORMAL)
710                             report(stdout, GT_("%s certificate MD5 fingerprint: %s\n"), mydata->server_label, text);
711                         if (mydata->check_digest != NULL) {
712                                 if (strcasecmp(text, mydata->check_digest) == 0) {
713                                     if (outlevel > O_NORMAL)
714                                         report(stdout, GT_("%s fingerprints match.\n"), mydata->server_label);
715                                 } else {
716                                     report(stderr, GT_("%s fingerprints do not match!\n"), mydata->server_label);
717                                     return (0);
718                                 }
719                         } /* if (_check_digest != NULL) */
720                 } /* if (_check_fp) */
721         } /* if (depth == 0 && !_depth0ck) */
722
723         if (err != X509_V_OK && err != mydata->prev_err && !(mydata->check_fp != 0 && mydata->check_digest && !mydata->strict_mode)) {
724                 char *tmp;
725                 int did_rep_err = 0;
726                 mydata->prev_err = err;
727
728                 report(stderr, GT_("Server certificate verification error: %s\n"), X509_verify_cert_error_string(err));
729                 /* We gave the error code, but maybe we can add some more details for debugging */
730
731                 switch (err) {
732                 /* actually we do not want to lump these together, but
733                  * since OpenSSL flipped the meaning of these error
734                  * codes in the past, and they do hardly make a
735                  * practical difference because servers need not provide
736                  * the root signing certificate, we don't bother telling
737                  * users the difference:
738                  */
739                 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
740                 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
741                         X509_NAME_oneline(issuer, buf, sizeof(buf));
742                         buf[sizeof(buf) - 1] = '\0';
743                         report(stderr, GT_("Broken certification chain at: %s\n"), (tmp = sdump(buf, strlen(buf))));
744                         xfree(tmp);
745                         report(stderr, GT_(     "This could mean that the server did not provide the intermediate CA's certificate(s), "
746                                                 "which is nothing fetchmail could do anything about.  For details, "
747                                                 "please see the README.SSL-SERVER document that ships with fetchmail.\n"));
748                         did_rep_err = 1;
749                         /* FALLTHROUGH */
750                 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
751                 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
752                         if (!did_rep_err) {
753                             X509_NAME_oneline(issuer, buf, sizeof(buf));
754                             buf[sizeof(buf) - 1] = '\0';
755                             report(stderr, GT_("Missing trust anchor certificate: %s\n"), (tmp = sdump(buf, strlen(buf))));
756                             xfree(tmp);
757                         }
758                         report(stderr, GT_(     "This could mean that the root CA's signing certificate is not in the "
759                                                 "trusted CA certificate location, or that c_rehash needs to be run "
760                                                 "on the certificate directory. For details, please "
761                                                 "see the documentation of --sslcertpath and --sslcertfile in the manual page.\n"));
762                         break;
763                 default:
764                         break;
765                 }
766         }
767         /*
768          * If not in strict checking mode (--sslcertck), override this
769          * and pretend that verification had succeeded.
770          */
771         mydata->verify_ok &= ok_return;
772         if (!mydata->strict_mode)
773                 ok_return = 1;
774         return ok_return;
775 }
776
777 /* get commonName from certificate set in file.
778  * commonName is stored in buffer namebuffer, limited with namebufferlen
779  */
780 static const char *SSLCertGetCN(const char *mycert,
781                                 char *namebuffer, size_t namebufferlen)
782 {
783         const char *ret       = NULL;
784         BIO        *certBio   = NULL;
785         X509       *x509_cert = NULL;
786         X509_NAME  *certname  = NULL;
787
788         if (namebuffer && namebufferlen > 0) {
789                 namebuffer[0] = 0x00;
790                 certBio = BIO_new_file(mycert,"r");
791                 if (certBio) {
792                         x509_cert = PEM_read_bio_X509(certBio,NULL,NULL,NULL);
793                         BIO_free(certBio);
794                 }
795                 if (x509_cert) {
796                         certname = X509_get_subject_name(x509_cert);
797                         if (certname &&
798                             X509_NAME_get_text_by_NID(certname, NID_commonName,
799                                                       namebuffer, namebufferlen) > 0)
800                                 ret = namebuffer;
801                         X509_free(x509_cert);
802                 }
803         }
804         return ret;
805 }
806
807 /* performs initial SSL handshake over the connected socket
808  * uses SSL *ssl global variable, which is currently defined
809  * in this file
810  */
811 int SSLOpen(int sock, char *mycert, char *mykey, const char *myproto, int certck,
812     char *cacertfile, char *certpath,
813     char *fingerprint, char *servercname, char *label, char **remotename)
814 {
815         struct stat randstat;
816         int i;
817
818         static int ssl_lib_init = 0;
819
820         if (!ssl_lib_init) {
821             SSL_load_error_strings();
822             SSL_library_init();
823             OpenSSL_add_all_algorithms(); /* see Debian Bug#576430 and manpage */
824             ssl_lib_init = 1;
825         }
826
827         if (-2 == global_mydata_index) {
828             char tmp[] = "fetchmail SSL callback data";
829             global_mydata_index = SSL_get_ex_new_index(0, tmp, NULL, NULL, NULL);
830             if (-1 == global_mydata_index) return PS_UNDEFINED;
831         }
832
833         if (stat("/dev/random", &randstat)  &&
834             stat("/dev/urandom", &randstat)) {
835           /* Neither /dev/random nor /dev/urandom are present, so add
836              entropy to the SSL PRNG a hard way. */
837           for (i = 0; i < 10000  &&  ! RAND_status (); ++i) {
838             char buf[4];
839             struct timeval tv;
840             gettimeofday (&tv, 0);
841             buf[0] = tv.tv_usec & 0xF;
842             buf[2] = (tv.tv_usec & 0xF0) >> 4;
843             buf[3] = (tv.tv_usec & 0xF00) >> 8;
844             buf[1] = (tv.tv_usec & 0xF000) >> 12;
845             RAND_add (buf, sizeof buf, 0.1);
846           }
847         }
848
849         if( sock < 0 || (unsigned)sock > FD_SETSIZE ) {
850                 report(stderr, GT_("File descriptor out of range for SSL") );
851                 return( -1 );
852         }
853
854         /* Make sure a connection referring to an older context is not left */
855         _ssl_context[sock] = NULL;
856         if(myproto) {
857                 if(!strcasecmp("ssl3",myproto)) {
858                         _ctx[sock] = SSL_CTX_new(SSLv3_client_method());
859                 } else if(!strcasecmp("tls1",myproto)) {
860                         _ctx[sock] = SSL_CTX_new(TLSv1_client_method());
861                 } else if (!strcasecmp("ssl23",myproto)) {
862                         myproto = NULL;
863                 } else {
864                         report(stderr,GT_("Invalid SSL protocol '%s' specified, using default (SSLv23).\n"), myproto);
865                         myproto = NULL;
866                 }
867         }
868         if(!myproto) {
869                 _ctx[sock] = SSL_CTX_new(SSLv23_client_method());
870         }
871         if(_ctx[sock] == NULL) {
872                 ERR_print_errors_fp(stderr);
873                 return(-1);
874         }
875
876         SSL_CTX_set_options(_ctx[sock], (SSL_OP_ALL | SSL_OP_NO_SSLv2) & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
877         SSL_CTX_set_verify(_ctx[sock], SSL_VERIFY_PEER, SSL_verify_callback);
878
879         /* Check which trusted X.509 CA certificate store(s) to load */
880         {
881                 char *tmp;
882                 int want_default_cacerts = 0;
883
884                 /* Load user locations if any is given */
885                 if (certpath || cacertfile)
886                         SSL_CTX_load_verify_locations(_ctx[sock],
887                                                 cacertfile, certpath);
888                 else
889                         want_default_cacerts = 1;
890
891                 tmp = getenv("FETCHMAIL_INCLUDE_DEFAULT_X509_CA_CERTS");
892                 if (want_default_cacerts || (tmp && tmp[0])) {
893                         SSL_CTX_set_default_verify_paths(_ctx[sock]);
894                 }
895         }
896         
897         _ssl_context[sock] = SSL_new(_ctx[sock]);
898         
899         if(_ssl_context[sock] == NULL) {
900                 ERR_print_errors_fp(stderr);
901                 SSL_CTX_free(_ctx[sock]);
902                 _ctx[sock] = NULL;
903                 return(-1);
904         }
905         
906         t_ssl_callback_data mydata;
907         memset(&mydata, 0, sizeof(mydata));
908
909         /* This data is for the verify callback */
910         mydata.ssl_server_cname = servercname;
911         mydata.server_label = label;
912         mydata.check_fp = 1;
913         mydata.check_digest = fingerprint;
914         mydata.depth0ck = 0;
915         mydata.firstrun = 1;
916         mydata.verify_ok = 1;
917         mydata.prev_err = -1;
918         mydata.strict_mode = certck;
919
920         if( mycert || mykey ) {
921
922         /* Ok...  He has a certificate file defined, so lets declare it.  If
923          * he does NOT have a separate certificate and private key file then
924          * assume that it's a combined key and certificate file.
925          */
926                 char buffer[256];
927                 
928                 if( !mykey )
929                         mykey = mycert;
930                 if( !mycert )
931                         mycert = mykey;
932
933                 if ((!*remotename || !**remotename) && SSLCertGetCN(mycert, buffer, sizeof(buffer))) {
934                         free(*remotename);
935                         *remotename = xstrdup(buffer);
936                 }
937                 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
938                 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
939         }
940
941         SSL_set_ex_data(_ssl_context[sock], global_mydata_index, &mydata);
942
943         if (SSL_set_fd(_ssl_context[sock], sock) == 0 
944             || SSL_connect(_ssl_context[sock]) < 1) {
945                 ERR_print_errors_fp(stderr);
946                 SSL_free( _ssl_context[sock] );
947                 _ssl_context[sock] = NULL;
948                 SSL_CTX_free(_ctx[sock]);
949                 _ctx[sock] = NULL;
950                 return(-1);
951         }
952
953         /* Paranoia: was the callback not called as we expected? */
954         if (!mydata.depth0ck) {
955                 report(stderr, GT_("Certificate/fingerprint verification was somehow skipped!\n"));
956
957                 if (fingerprint != NULL || certck) {
958                         if( NULL != SSLGetContext( sock ) ) {
959                                 /* Clean up the SSL stack */
960                                 SSL_shutdown( _ssl_context[sock] );
961                                 SSL_free( _ssl_context[sock] );
962                                 _ssl_context[sock] = NULL;
963                                 SSL_CTX_free(_ctx[sock]);
964                                 _ctx[sock] = NULL;
965                         }
966                         return(-1);
967                 }
968         }
969
970         if (!certck && !fingerprint &&
971                 (SSL_get_verify_result(_ssl_context[sock]) != X509_V_OK || !mydata.verify_ok)) {
972                 report(stderr, GT_("Warning: the connection is insecure, continuing anyways. (Better use --sslcertck!)\n"));
973         }
974
975         return(0);
976 }
977 #endif
978
979 int SockClose(int sock)
980 /* close a socket gracefully */
981 {
982 #ifdef  SSL_ENABLE
983     if( NULL != SSLGetContext( sock ) ) {
984         /* Clean up the SSL stack */
985         SSL_shutdown( _ssl_context[sock] );
986         SSL_free( _ssl_context[sock] );
987         _ssl_context[sock] = NULL;
988         SSL_CTX_free(_ctx[sock]);
989         _ctx[sock] = NULL;
990     }
991 #endif
992
993     /* if there's an error closing at this point, not much we can do */
994     return(fm_close(sock));     /* this is guarded */
995 }
996
997 #ifdef __CYGWIN__
998 /*
999  * Workaround Microsoft Winsock recv/WSARecv(..., MSG_PEEK) bug.
1000  * See http://sources.redhat.com/ml/cygwin/2001-08/msg00628.html
1001  * for more details.
1002  */
1003 static ssize_t cygwin_read(int sock, void *buf, size_t count)
1004 {
1005     char *bp = (char *)buf;
1006     size_t n = 0;
1007
1008     if ((n = read(sock, bp, count)) == (size_t)-1)
1009         return(-1);
1010
1011     if (n != count) {
1012         size_t n2 = 0;
1013         if (outlevel >= O_VERBOSE)
1014             report(stdout, GT_("Cygwin socket read retry\n"));
1015         n2 = read(sock, bp + n, count - n);
1016         if (n2 == (size_t)-1 || n + n2 != count) {
1017             report(stderr, GT_("Cygwin socket read retry failed!\n"));
1018             return(-1);
1019         }
1020     }
1021
1022     return count;
1023 }
1024 #endif /* __CYGWIN__ */