PageRenderTime 54ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/fetchmail-6.3.21/socket.c

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