2 * socket.c -- socket library functions
4 * Copyright 1998, 2004 by Eric S. Raymond.
5 * Copyright 2004, 2013 by Matthias Andree.
7 * For license terms, see the file COPYING in this directory.
14 #include <ctype.h> /* isspace() */
15 #include <sys/types.h>
17 #include <sys/socket.h>
19 #include <netinet/in.h>
20 #include <arpa/inet.h>
29 #include "fetchmail.h"
30 #include "getaddrinfo.h"
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)
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__ */
46 /* We need to define h_errno only if it is not already */
48 # if !HAVE_DECL_H_ERRNO
51 #endif /* ndef h_errno */
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;
57 static char *const *parse_plugin(const char *plugin, const char *host, const char *service)
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);
69 for (c = p = plugin; *c; c++)
70 { if (isspace((unsigned char)*c) && !isspace((unsigned char)*p))
72 if (*p == '%' && *c == 'h')
74 if (*p == '%' && *c == 'p')
79 plugin_copy_len = plugin_len + host_len * host_count + service_len * service_count;
80 plugin_copy = (char *)malloc(plugin_copy_len + 1);
83 report(stderr, GT_("fetchmail: malloc failed\n"));
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);
91 plugin_copy_offset += host_len;
93 else if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'p'))
94 { strcpy(plugin_copy + plugin_copy_offset, service);
96 plugin_copy_offset += service_len;
99 { plugin_copy[plugin_copy_offset] = plugin[plugin_offset];
101 plugin_copy_offset++;
104 plugin_copy[plugin_copy_len] = 0;
106 argvec = (char **)malloc(s);
110 report(stderr, GT_("fetchmail: malloc failed\n"));
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))) {
121 for (cp = plugin_copy; *cp; cp++)
122 { if (isspace((unsigned char)*cp))
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 */
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.
140 if (socketpair(AF_UNIX,SOCK_STREAM,0,fds))
142 report(stderr, GT_("fetchmail: socketpair failed\n"));
148 report(stderr, GT_("fetchmail: fork failed\n"));
151 /* fds[1] is the parent's end; close it for proper EOF
153 (void) close(fds[1]);
154 if ( (dup2(fds[0],0) == -1) || (dup2(fds[0],1) == -1) ) {
155 report(stderr, GT_("dup2 failed\n"));
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);
165 execvp(*argvec, argvec);
166 report(stderr, GT_("execvp(%s) failed\n"), *argvec);
169 default: /* parent */
173 /* fds[0] is the child's end; close it for proper EOF detection */
174 (void) close(fds[0]);
178 /** Set socket to SO_KEEPALIVE. \return 0 for success. */
179 int SockKeepalive(int sock) {
181 return setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof keepalive);
184 int UnixOpen(const char *path)
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);
192 sock = socket( AF_UNIX, SOCK_STREAM, 0 );
199 /* Socket opened saved. Useful if connect timeout
200 * because it can be closed.
202 mailserver_socket_temp = sock;
204 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
207 fm_close(sock); /* don't use SockClose, no traffic yet */
213 /* No connect timeout, then no need to set mailserver_socket_temp */
214 mailserver_socket_temp = -1;
219 int SockOpen(const char *host, const char *service,
220 const char *plugin, struct addrinfo **ai0)
222 struct addrinfo *ai, req;
225 char errbuf[8192] = "";
228 return handle_plugin(host,service,plugin);
230 memset(&req, 0, sizeof(struct addrinfo));
231 req.ai_socktype = SOCK_STREAM;
233 req.ai_flags = AI_ADDRCONFIG;
236 i = fm_getaddrinfo(host, service, &req, ai0);
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"));
245 /* NOTE a Linux bug here - getaddrinfo will happily return 127.0.0.1
246 * twice if no IPv6 is configured */
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 */
253 gnie = getnameinfo(ai->ai_addr, ai->ai_addrlen, buf, sizeof(buf), NULL, 0, NI_NUMERICHOST);
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);
258 snprintf(pb, sizeof(pb), GT_("unknown (%s)"), gai_strerror(gnie));
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);
265 /* mask EAFNOSUPPORT errors, they confuse users for
266 * multihomed hosts */
267 if (errno != EAFNOSUPPORT)
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));
278 /* Save socket descriptor.
279 * Used to close the socket after connect timeout. */
280 mailserver_socket_temp = i;
282 if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
285 /* additionally, suppress IPv4 network unreach errors */
286 if (e != EAFNOSUPPORT)
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));
298 if (outlevel >= O_VERBOSE)
299 report_complete(stdout, GT_("connected.\n"));
302 /* No connect timeout, then no need to set mailserver_socket_temp */
303 mailserver_socket_temp = -1;
308 fm_freeaddrinfo(*ai0);
312 report(stderr, GT_("Connection errors for this poll:\n%s"), errbuf);
319 int SockPrintf(int sock, const char* format, ...)
324 va_start(ap, format) ;
325 vsnprintf(buf, sizeof(buf), format, ap);
327 return SockWrite(sock, buf, strlen(buf));
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>
338 static void report_SSL_errors(FILE *stream)
342 while (0ul != (err = ERR_get_error())) {
343 char *errstr = ERR_error_string(err, NULL);
344 report(stream, GT_("OpenSSL reported: %s\n"), errstr);
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))
352 static SSL_CTX *_ctx[FD_SETSIZE];
353 static SSL *_ssl_context[FD_SETSIZE];
355 static SSL *SSLGetContext( int );
356 #endif /* SSL_ENABLE */
358 int SockWrite(int sock, const char *buf, int len)
368 if( NULL != ( ssl = SSLGetContext( sock ) ) )
369 n = SSL_write(ssl, buf, len);
371 #endif /* SSL_ENABLE */
372 n = fm_write(sock, buf, len);
382 int SockRead(int sock, char *buf, int len)
384 char *newline, *bp = buf;
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.
400 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
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);
418 /* SSL_peek says no data... Does he mean no data
419 or did the connection blow up? If we got an error
421 if (0 != SSL_get_error(ssl, n)) {
424 /* We didn't get an error so read at least one
425 character at this point and loop */
427 /* Make sure newline start out NULL!
428 * We don't have a string to pass through
429 * the strchr at this point yet */
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))) {
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 */
451 #endif /* SSL_ENABLE */
454 if ((n = fm_peek(sock, bp, len)) <= 0)
456 if ((newline = (char *)memchr(bp, '\n', n)) != NULL)
457 n = newline - bp + 1;
458 if ((n = fm_read(sock, bp, n)) == -1)
470 int SockPeek(int sock)
471 /* peek at the next socket character without actually reading it */
480 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
481 n = SSL_peek(ssl, &ch, 1);
483 (void)SSL_get_error(ssl, 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... */
492 /* SSL_peek says 0... Does that mean no data
493 or did the connection blow up? If we got an error
495 if(0 != SSL_get_error(ssl, n)) {
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"... */
505 return 0; /* Give him a '\0' character */
509 #endif /* SSL_ENABLE */
510 n = fm_peek(sock, &ch, 1);
519 struct ssl_callback_data {
520 char *ssl_server_cname;
531 typedef struct ssl_callback_data t_ssl_callback_data;
533 SSL *SSLGetContext( int sock )
535 if( sock < 0 || (unsigned)sock > FD_SETSIZE )
537 if( _ctx[sock] == NULL )
539 return _ssl_context[sock];
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)
547 #define SSLverbose (((outlevel) >= O_DEBUG) || ((outlevel) >= O_VERBOSE && (depth) == 0))
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;
557 t_ssl_callback_data *mydata;
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);
566 subj = X509_get_subject_name(x509_cert);
567 issuer = X509_get_issuer_name(x509_cert);
569 if (outlevel >= O_VERBOSE) {
570 if (depth == 0 && SSLverbose)
571 report(stdout, GT_("Server certificate:\n"));
573 if (mydata->firstrun) {
574 mydata->firstrun = 0;
576 report(stdout, GT_("Certificate chain, from root to peer, starting at depth %d:\n"), depth);
579 report(stdout, GT_("Certificate at depth %d:\n"), depth);
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)));
587 if ((size_t)i >= sizeof(buf) - 1)
588 report(stdout, GT_("Warning: Issuer Organization Name too long (possibly truncated).\n"));
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)));
594 if ((size_t)i >= sizeof(buf) - 1)
595 report(stdout, GT_("Warning: Issuer CommonName too long (possibly truncated).\n"));
597 report(stdout, GT_("Unknown Issuer CommonName\n"));
601 if ((i = X509_NAME_get_text_by_NID(subj, NID_commonName, buf, sizeof(buf))) != -1) {
603 report(stdout, GT_("Subject CommonName: %s\n"), (tt = sdump(buf, i)));
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"));
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"));
620 if (depth == 0) { /* peer certificate */
621 if (!mydata->depth0ck) {
622 mydata->depth0ck = 1;
625 if ((i = X509_NAME_get_text_by_NID(subj, NID_commonName, buf, sizeof(buf))) != -1) {
626 if (mydata->ssl_server_cname != NULL) {
628 char *p2 = mydata->ssl_server_cname;
630 STACK_OF(GENERAL_NAME) *gens;
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);
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)));
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);
653 if (name_match(pp1, pp2)) {
658 GENERAL_NAMES_free(gens);
660 if (name_match(p1, p2)) {
664 if (mydata->strict_mode || SSLverbose) {
666 GT_("Server CommonName mismatch: %s != %s\n"),
667 (tt = sdump(buf, i)), mydata->ssl_server_cname);
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);
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"));
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) {
689 mydata->check_fp = -1;
690 digest_tp = EVP_md5();
691 if (digest_tp == NULL) {
692 report(stderr, GT_("EVP_md5() failed!\n"));
695 if (!X509_digest(x509_cert, digest_tp, digest, &dsz)) {
696 report(stderr, GT_("Out of memory!\n"));
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"));
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);
716 report(stderr, GT_("%s fingerprints do not match!\n"), mydata->server_label);
719 } /* if (_check_digest != NULL) */
720 } /* if (_check_fp) */
721 } /* if (depth == 0 && !_depth0ck) */
723 if (err != X509_V_OK && err != mydata->prev_err && !(mydata->check_fp != 0 && mydata->check_digest && !mydata->strict_mode)) {
726 mydata->prev_err = err;
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 */
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:
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))));
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"));
750 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
751 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
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))));
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"));
768 * If not in strict checking mode (--sslcertck), override this
769 * and pretend that verification had succeeded.
771 mydata->verify_ok &= ok_return;
772 if (!mydata->strict_mode)
777 /* get commonName from certificate set in file.
778 * commonName is stored in buffer namebuffer, limited with namebufferlen
780 static const char *SSLCertGetCN(const char *mycert,
781 char *namebuffer, size_t namebufferlen)
783 const char *ret = NULL;
785 X509 *x509_cert = NULL;
786 X509_NAME *certname = NULL;
788 if (namebuffer && namebufferlen > 0) {
789 namebuffer[0] = 0x00;
790 certBio = BIO_new_file(mycert,"r");
792 x509_cert = PEM_read_bio_X509(certBio,NULL,NULL,NULL);
796 certname = X509_get_subject_name(x509_cert);
798 X509_NAME_get_text_by_NID(certname, NID_commonName,
799 namebuffer, namebufferlen) > 0)
801 X509_free(x509_cert);
807 /* performs initial SSL handshake over the connected socket
808 * uses SSL *ssl global variable, which is currently defined
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)
815 struct stat randstat;
818 static int ssl_lib_init = 0;
821 SSL_load_error_strings();
823 OpenSSL_add_all_algorithms(); /* see Debian Bug#576430 and manpage */
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;
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) {
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);
849 if( sock < 0 || (unsigned)sock > FD_SETSIZE ) {
850 report(stderr, GT_("File descriptor out of range for SSL") );
854 /* Make sure a connection referring to an older context is not left */
855 _ssl_context[sock] = NULL;
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)) {
864 report(stderr,GT_("Invalid SSL protocol '%s' specified, using default (SSLv23).\n"), myproto);
869 _ctx[sock] = SSL_CTX_new(SSLv23_client_method());
871 if(_ctx[sock] == NULL) {
872 ERR_print_errors_fp(stderr);
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);
879 /* Check which trusted X.509 CA certificate store(s) to load */
882 int want_default_cacerts = 0;
884 /* Load user locations if any is given */
885 if (certpath || cacertfile)
886 SSL_CTX_load_verify_locations(_ctx[sock],
887 cacertfile, certpath);
889 want_default_cacerts = 1;
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]);
897 _ssl_context[sock] = SSL_new(_ctx[sock]);
899 if(_ssl_context[sock] == NULL) {
900 ERR_print_errors_fp(stderr);
901 SSL_CTX_free(_ctx[sock]);
906 t_ssl_callback_data mydata;
907 memset(&mydata, 0, sizeof(mydata));
909 /* This data is for the verify callback */
910 mydata.ssl_server_cname = servercname;
911 mydata.server_label = label;
913 mydata.check_digest = fingerprint;
916 mydata.verify_ok = 1;
917 mydata.prev_err = -1;
918 mydata.strict_mode = certck;
920 if( mycert || mykey ) {
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.
933 if ((!*remotename || !**remotename) && SSLCertGetCN(mycert, buffer, sizeof(buffer))) {
935 *remotename = xstrdup(buffer);
937 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
938 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
941 SSL_set_ex_data(_ssl_context[sock], global_mydata_index, &mydata);
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]);
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"));
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]);
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"));
979 int SockClose(int sock)
980 /* close a socket gracefully */
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]);
993 /* if there's an error closing at this point, not much we can do */
994 return(fm_close(sock)); /* this is guarded */
999 * Workaround Microsoft Winsock recv/WSARecv(..., MSG_PEEK) bug.
1000 * See http://sources.redhat.com/ml/cygwin/2001-08/msg00628.html
1003 static ssize_t cygwin_read(int sock, void *buf, size_t count)
1005 char *bp = (char *)buf;
1008 if ((n = read(sock, bp, count)) == (size_t)-1)
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"));
1024 #endif /* __CYGWIN__ */