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