1 /* $NetBSD: ssl.c,v 1.2 2012/12/24 22:12:28 christos Exp $ */
4 * Copyright (c) 1998-2004 Dag-Erling Coïdan Smørgrav
5 * Copyright (c) 2008, 2010 Joerg Sonnenberger <joerg@NetBSD.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer
13 * in this position and unchanged.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. The name of the author may not be used to endorse or promote products
18 * derived from this software without specific prior written permission
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 * $FreeBSD: common.c,v 1.53 2007/12/19 00:26:36 des Exp $
34 #include <sys/cdefs.h>
36 __RCSID("$NetBSD: ssl.c,v 1.2 2012/12/24 22:12:28 christos Exp $");
43 #include <sys/param.h>
44 #include <sys/select.h>
45 #include <sys/socket.h>
48 #include <netinet/tcp.h>
49 #include <netinet/in.h>
50 #include <openssl/crypto.h>
51 #include <openssl/x509.h>
52 #include <openssl/pem.h>
53 #include <openssl/ssl.h>
54 #include <openssl/err.h>
58 extern int quit_time, verbose, ftp_debug;
61 struct fetch_connect {
62 int sd; /* file/socket descriptor */
63 char *buf; /* buffer */
64 size_t bufsize; /* buffer size */
65 size_t bufpos; /* position of buffer */
66 size_t buflen; /* length of buffer contents */
67 struct { /* data cached after an
77 SSL *ssl; /* SSL handle */
81 * Write a vector to a connection w/ timeout
82 * Note: can modify the iovec.
85 fetch_writev(struct fetch_connect *conn, struct iovec *iov, int iovcnt)
87 struct timeval now, timeout, delta;
94 gettimeofday(&timeout, NULL);
95 timeout.tv_sec += quit_time;
100 while (quit_time > 0 && !FD_ISSET(conn->sd, &writefds)) {
101 FD_SET(conn->sd, &writefds);
102 gettimeofday(&now, NULL);
103 delta.tv_sec = timeout.tv_sec - now.tv_sec;
104 delta.tv_usec = timeout.tv_usec - now.tv_usec;
105 if (delta.tv_usec < 0) {
106 delta.tv_usec += 1000000;
109 if (delta.tv_sec < 0) {
114 r = select(conn->sd + 1, NULL, &writefds, NULL, &delta);
122 if (conn->ssl != NULL)
123 len = SSL_write(conn->ssl, iov->iov_base, iov->iov_len);
125 len = writev(conn->sd, iov, iovcnt);
127 /* we consider a short write a failure */
128 /* XXX perhaps we shouldn't in the SSL case */
138 while (iovcnt > 0 && len >= (ssize_t)iov->iov_len) {
145 iov->iov_base = (char *)iov->iov_base + len;
152 * Write to a connection w/ timeout
155 fetch_write(struct fetch_connect *conn, const char *str, size_t len)
159 iov[0].iov_base = __DECONST(char *, str);
160 iov[0].iov_len = len;
161 return fetch_writev(conn, iov, 1);
165 * Send a formatted line; optionally echo to terminal
168 fetch_printf(struct fetch_connect *conn, const char *fmt, ...)
176 len = vasprintf(&msg, fmt, ap);
184 r = fetch_write(conn, msg, len);
190 fetch_fileno(struct fetch_connect *conn)
197 fetch_error(struct fetch_connect *conn)
204 fetch_clearerr(struct fetch_connect *conn)
211 fetch_flush(struct fetch_connect *conn)
218 setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &v, sizeof(v));
221 setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &v, sizeof(v));
227 struct fetch_connect *
228 fetch_open(const char *fname, const char *fmode)
230 struct fetch_connect *conn;
233 fd = open(fname, O_RDONLY); /* XXX: fmode */
237 if ((conn = calloc(1, sizeof(*conn))) == NULL) {
248 struct fetch_connect *
249 fetch_fdopen(int sd, const char *fmode)
251 struct fetch_connect *conn;
252 #if defined(SO_NOSIGPIPE) || defined(TCP_NOPUSH)
256 if ((conn = calloc(1, sizeof(*conn))) == NULL)
261 fcntl(sd, F_SETFD, FD_CLOEXEC);
263 setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
266 setsockopt(sd, IPPROTO_TCP, TCP_NOPUSH, &opt, sizeof(opt));
272 fetch_close(struct fetch_connect *conn)
279 rv = close(conn->sd);
284 free(conn->cache.buf);
291 #define FETCH_READ_WAIT -2
292 #define FETCH_READ_ERROR -1
295 fetch_ssl_read(SSL *ssl, void *buf, size_t len)
300 rlen = SSL_read(ssl, buf, len);
302 ssl_err = SSL_get_error(ssl, rlen);
303 if (ssl_err == SSL_ERROR_WANT_READ ||
304 ssl_err == SSL_ERROR_WANT_WRITE) {
305 return FETCH_READ_WAIT;
307 ERR_print_errors_fp(ttyout);
308 return FETCH_READ_ERROR;
314 fetch_nonssl_read(int sd, void *buf, size_t len)
318 rlen = read(sd, buf, len);
320 if (errno == EAGAIN || errno == EINTR)
321 return FETCH_READ_WAIT;
322 return FETCH_READ_ERROR;
328 * Cache some data that was read from a socket but cannot be immediately
329 * returned because of an interrupted system call.
332 fetch_cache_data(struct fetch_connect *conn, char *src, size_t nbytes)
335 if (conn->cache.size < nbytes) {
336 char *tmp = realloc(conn->cache.buf, nbytes);
340 conn->cache.buf = tmp;
341 conn->cache.size = nbytes;
344 memcpy(conn->cache.buf, src, nbytes);
345 conn->cache.len = nbytes;
351 fetch_read(void *ptr, size_t size, size_t nmemb, struct fetch_connect *conn)
353 struct timeval now, timeout, delta;
360 gettimeofday(&timeout, NULL);
361 timeout.tv_sec += quit_time;
368 if (conn->cache.len > 0) {
370 * The last invocation of fetch_read was interrupted by a
371 * signal after some data had been read from the socket. Copy
372 * the cached data into the supplied buffer before trying to
373 * read from the socket again.
375 total = (conn->cache.len < len) ? conn->cache.len : len;
376 memcpy(buf, conn->cache.buf, total);
378 conn->cache.len -= total;
379 conn->cache.pos += total;
386 * The socket is non-blocking. Instead of the canonical
387 * select() -> read(), we do the following:
389 * 1) call read() or SSL_read().
390 * 2) if an error occurred, return -1.
391 * 3) if we received data but we still expect more,
392 * update our counters and loop.
393 * 4) if read() or SSL_read() signaled EOF, return.
394 * 5) if we did not receive any data but we're not at EOF,
397 * In the SSL case, this is necessary because if we
398 * receive a close notification, we have to call
399 * SSL_read() one additional time after we've read
400 * everything we received.
402 * In the non-SSL case, it may improve performance (very
403 * slightly) when reading small amounts of data.
405 if (conn->ssl != NULL)
406 rlen = fetch_ssl_read(conn->ssl, buf, len);
408 rlen = fetch_nonssl_read(conn->sd, buf, len);
411 } else if (rlen > 0) {
416 } else if (rlen == FETCH_READ_ERROR) {
418 fetch_cache_data(conn, start, total);
422 while (!FD_ISSET(conn->sd, &readfds)) {
423 FD_SET(conn->sd, &readfds);
425 gettimeofday(&now, NULL);
426 if (!timercmp(&timeout, &now, >)) {
430 timersub(&timeout, &now, &delta);
433 if (select(conn->sd + 1, &readfds, NULL, NULL,
434 quit_time > 0 ? &delta : NULL) < 0) {
444 #define MIN_BUF_SIZE 1024
447 * Read a line of text from a connection w/ timeout
450 fetch_getln(char *str, int size, struct fetch_connect *conn)
456 if (conn->buf == NULL) {
457 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
462 conn->bufsize = MIN_BUF_SIZE;
465 if (conn->iserr || conn->iseof)
468 if (conn->buflen - conn->bufpos > 0)
475 len = fetch_read(&c, sizeof(c), 1, conn);
484 conn->buf[conn->buflen++] = c;
485 if (conn->buflen == conn->bufsize) {
486 char *tmp = conn->buf;
487 tmpsize = conn->bufsize * 2 + 1;
488 if ((tmp = realloc(tmp, tmpsize)) == NULL) {
494 conn->bufsize = tmpsize;
498 if (conn->buflen == 0)
501 tmpsize = MIN(size - 1, (int)(conn->buflen - conn->bufpos));
502 memcpy(str, conn->buf + conn->bufpos, tmpsize);
504 conn->bufpos += tmpsize;
509 fetch_getline(struct fetch_connect *conn, char *buf, size_t buflen,
510 const char **errormsg)
515 if (fetch_getln(buf, buflen, conn) == NULL) {
516 if (conn->iseof) { /* EOF */
519 *errormsg = "\nEOF received";
523 *errormsg = "Error encountered";
525 fetch_clearerr(conn);
529 if (buf[len - 1] == '\n') { /* clear any trailing newline */
531 } else if (len == buflen - 1) { /* line too long */
534 ssize_t rlen = fetch_read(&c, sizeof(c), 1, conn);
535 if (rlen <= 0 || c == '\n')
539 *errormsg = "Input line is too long";
540 fetch_clearerr(conn);
549 fetch_start_ssl(int sock)
555 /* Init the SSL library and context */
556 if (!SSL_library_init()){
557 fprintf(ttyout, "SSL library init failed\n");
561 SSL_load_error_strings();
563 ctx = SSL_CTX_new(SSLv23_client_method());
564 SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
568 fprintf(ttyout, "SSL context creation failed\n");
572 SSL_set_fd(ssl, sock);
573 while ((ret = SSL_connect(ssl)) == -1) {
574 ssl_err = SSL_get_error(ssl, ret);
575 if (ssl_err != SSL_ERROR_WANT_READ &&
576 ssl_err != SSL_ERROR_WANT_WRITE) {
577 ERR_print_errors_fp(ttyout);
583 if (ftp_debug && verbose) {
588 fprintf(ttyout, "SSL connection established using %s\n",
589 SSL_get_cipher(ssl));
590 cert = SSL_get_peer_certificate(ssl);
591 name = X509_get_subject_name(cert);
592 str = X509_NAME_oneline(name, 0, 0);
593 fprintf(ttyout, "Certificate subject: %s\n", str);
595 name = X509_get_issuer_name(cert);
596 str = X509_NAME_oneline(name, 0, 0);
597 fprintf(ttyout, "Certificate issuer: %s\n", str);
606 fetch_set_ssl(struct fetch_connect *conn, void *ssl)