1 /* $NetBSD: ssl.c,v 1.3 2015/10/04 04:53:26 lukem Exp $ */
2 /* from NetBSD: ssl.c,v 1.5 2015/09/16 15:32:53 joerg Exp */
5 * Copyright (c) 1998-2004 Dag-Erling Coïdan Smørgrav
6 * Copyright (c) 2008, 2010 Joerg Sonnenberger <joerg@NetBSD.org>
7 * Copyright (c) 2015 Thomas Klausner <wiz@NetBSD.org>
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer
15 * in this position and unchanged.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. The name of the author may not be used to endorse or promote products
20 * derived from this software without specific prior written permission
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 * $FreeBSD: common.c,v 1.53 2007/12/19 00:26:36 des Exp $
40 #include <sys/cdefs.h>
42 __RCSID(" NetBSD: ssl.c,v 1.5 2015/09/16 15:32:53 joerg Exp ");
49 #include <sys/param.h>
50 #include <sys/select.h>
53 #include <netinet/tcp.h>
54 #include <netinet/in.h>
57 #include <openssl/crypto.h>
58 #include <openssl/x509.h>
59 #include <openssl/pem.h>
60 #include <openssl/ssl.h>
61 #include <openssl/err.h>
65 extern int quit_time
, verbose
, ftp_debug
;
68 struct fetch_connect
{
69 int sd
; /* file/socket descriptor */
70 char *buf
; /* buffer */
71 size_t bufsize
; /* buffer size */
72 size_t bufpos
; /* position of buffer */
73 size_t buflen
; /* length of buffer contents */
74 struct { /* data cached after an
84 SSL
*ssl
; /* SSL handle */
88 * Write a vector to a connection w/ timeout
89 * Note: can modify the iovec.
92 fetch_writev(struct fetch_connect
*conn
, struct iovec
*iov
, int iovcnt
)
94 struct timeval now
, timeout
, delta
;
101 gettimeofday(&timeout
, NULL
);
102 timeout
.tv_sec
+= quit_time
;
107 while (quit_time
> 0 && !FD_ISSET(conn
->sd
, &writefds
)) {
108 FD_SET(conn
->sd
, &writefds
);
109 gettimeofday(&now
, NULL
);
110 delta
.tv_sec
= timeout
.tv_sec
- now
.tv_sec
;
111 delta
.tv_usec
= timeout
.tv_usec
- now
.tv_usec
;
112 if (delta
.tv_usec
< 0) {
113 delta
.tv_usec
+= 1000000;
116 if (delta
.tv_sec
< 0) {
121 r
= select(conn
->sd
+ 1, NULL
, &writefds
, NULL
, &delta
);
129 if (conn
->ssl
!= NULL
)
130 len
= SSL_write(conn
->ssl
, iov
->iov_base
, iov
->iov_len
);
132 len
= writev(conn
->sd
, iov
, iovcnt
);
134 /* we consider a short write a failure */
135 /* XXX perhaps we shouldn't in the SSL case */
145 while (iovcnt
> 0 && len
>= (ssize_t
)iov
->iov_len
) {
152 iov
->iov_base
= (char *)iov
->iov_base
+ len
;
159 * Write to a connection w/ timeout
162 fetch_write(struct fetch_connect
*conn
, const char *str
, size_t len
)
166 iov
[0].iov_base
= __DECONST(char *, str
);
167 iov
[0].iov_len
= len
;
168 return fetch_writev(conn
, iov
, 1);
172 * Send a formatted line; optionally echo to terminal
175 fetch_printf(struct fetch_connect
*conn
, const char *fmt
, ...)
183 len
= vasprintf(&msg
, fmt
, ap
);
191 r
= fetch_write(conn
, msg
, len
);
197 fetch_fileno(struct fetch_connect
*conn
)
204 fetch_error(struct fetch_connect
*conn
)
211 fetch_clearerr(struct fetch_connect
*conn
)
218 fetch_flush(struct fetch_connect
*conn
)
225 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NOPUSH
, &v
, sizeof(v
));
228 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NODELAY
, &v
, sizeof(v
));
234 struct fetch_connect
*
235 fetch_open(const char *fname
, const char *fmode
)
237 struct fetch_connect
*conn
;
240 fd
= open(fname
, O_RDONLY
); /* XXX: fmode */
244 if ((conn
= calloc(1, sizeof(*conn
))) == NULL
) {
255 struct fetch_connect
*
256 fetch_fdopen(int sd
, const char *fmode
)
258 struct fetch_connect
*conn
;
259 #if defined(SO_NOSIGPIPE) || defined(TCP_NOPUSH)
263 if ((conn
= calloc(1, sizeof(*conn
))) == NULL
)
268 fcntl(sd
, F_SETFD
, FD_CLOEXEC
);
270 setsockopt(sd
, SOL_SOCKET
, SO_NOSIGPIPE
, &opt
, sizeof(opt
));
273 setsockopt(sd
, IPPROTO_TCP
, TCP_NOPUSH
, &opt
, sizeof(opt
));
279 fetch_close(struct fetch_connect
*conn
)
286 rv
= close(conn
->sd
);
291 free(conn
->cache
.buf
);
298 #define FETCH_READ_WAIT -2
299 #define FETCH_READ_ERROR -1
302 fetch_ssl_read(SSL
*ssl
, void *buf
, size_t len
)
307 rlen
= SSL_read(ssl
, buf
, len
);
309 ssl_err
= SSL_get_error(ssl
, rlen
);
310 if (ssl_err
== SSL_ERROR_WANT_READ
||
311 ssl_err
== SSL_ERROR_WANT_WRITE
) {
312 return FETCH_READ_WAIT
;
314 ERR_print_errors_fp(ttyout
);
315 return FETCH_READ_ERROR
;
321 fetch_nonssl_read(int sd
, void *buf
, size_t len
)
325 rlen
= read(sd
, buf
, len
);
327 if (errno
== EAGAIN
|| errno
== EINTR
)
328 return FETCH_READ_WAIT
;
329 return FETCH_READ_ERROR
;
335 * Cache some data that was read from a socket but cannot be immediately
336 * returned because of an interrupted system call.
339 fetch_cache_data(struct fetch_connect
*conn
, char *src
, size_t nbytes
)
342 if (conn
->cache
.size
< nbytes
) {
343 char *tmp
= realloc(conn
->cache
.buf
, nbytes
);
347 conn
->cache
.buf
= tmp
;
348 conn
->cache
.size
= nbytes
;
351 memcpy(conn
->cache
.buf
, src
, nbytes
);
352 conn
->cache
.len
= nbytes
;
358 fetch_read(void *ptr
, size_t size
, size_t nmemb
, struct fetch_connect
*conn
)
360 struct timeval now
, timeout
, delta
;
367 gettimeofday(&timeout
, NULL
);
368 timeout
.tv_sec
+= quit_time
;
375 if (conn
->cache
.len
> 0) {
377 * The last invocation of fetch_read was interrupted by a
378 * signal after some data had been read from the socket. Copy
379 * the cached data into the supplied buffer before trying to
380 * read from the socket again.
382 total
= (conn
->cache
.len
< len
) ? conn
->cache
.len
: len
;
383 memcpy(buf
, conn
->cache
.buf
, total
);
385 conn
->cache
.len
-= total
;
386 conn
->cache
.pos
+= total
;
393 * The socket is non-blocking. Instead of the canonical
394 * select() -> read(), we do the following:
396 * 1) call read() or SSL_read().
397 * 2) if an error occurred, return -1.
398 * 3) if we received data but we still expect more,
399 * update our counters and loop.
400 * 4) if read() or SSL_read() signaled EOF, return.
401 * 5) if we did not receive any data but we're not at EOF,
404 * In the SSL case, this is necessary because if we
405 * receive a close notification, we have to call
406 * SSL_read() one additional time after we've read
407 * everything we received.
409 * In the non-SSL case, it may improve performance (very
410 * slightly) when reading small amounts of data.
412 if (conn
->ssl
!= NULL
)
413 rlen
= fetch_ssl_read(conn
->ssl
, buf
, len
);
415 rlen
= fetch_nonssl_read(conn
->sd
, buf
, len
);
418 } else if (rlen
> 0) {
423 } else if (rlen
== FETCH_READ_ERROR
) {
425 fetch_cache_data(conn
, start
, total
);
429 while (!FD_ISSET(conn
->sd
, &readfds
)) {
430 FD_SET(conn
->sd
, &readfds
);
432 gettimeofday(&now
, NULL
);
433 if (!timercmp(&timeout
, &now
, >)) {
437 timersub(&timeout
, &now
, &delta
);
440 if (select(conn
->sd
+ 1, &readfds
, NULL
, NULL
,
441 quit_time
> 0 ? &delta
: NULL
) < 0) {
451 #define MIN_BUF_SIZE 1024
454 * Read a line of text from a connection w/ timeout
457 fetch_getln(char *str
, int size
, struct fetch_connect
*conn
)
463 if (conn
->buf
== NULL
) {
464 if ((conn
->buf
= malloc(MIN_BUF_SIZE
)) == NULL
) {
469 conn
->bufsize
= MIN_BUF_SIZE
;
472 if (conn
->iserr
|| conn
->iseof
)
475 if (conn
->buflen
- conn
->bufpos
> 0)
482 len
= fetch_read(&c
, sizeof(c
), 1, conn
);
491 conn
->buf
[conn
->buflen
++] = c
;
492 if (conn
->buflen
== conn
->bufsize
) {
493 char *tmp
= conn
->buf
;
494 tmpsize
= conn
->bufsize
* 2 + 1;
495 if ((tmp
= realloc(tmp
, tmpsize
)) == NULL
) {
501 conn
->bufsize
= tmpsize
;
505 if (conn
->buflen
== 0)
508 tmpsize
= MIN(size
- 1, (int)(conn
->buflen
- conn
->bufpos
));
509 memcpy(str
, conn
->buf
+ conn
->bufpos
, tmpsize
);
511 conn
->bufpos
+= tmpsize
;
516 fetch_getline(struct fetch_connect
*conn
, char *buf
, size_t buflen
,
517 const char **errormsg
)
522 if (fetch_getln(buf
, buflen
, conn
) == NULL
) {
523 if (conn
->iseof
) { /* EOF */
526 *errormsg
= "\nEOF received";
530 *errormsg
= "Error encountered";
532 fetch_clearerr(conn
);
536 if (buf
[len
- 1] == '\n') { /* clear any trailing newline */
538 } else if (len
== buflen
- 1) { /* line too long */
541 ssize_t rlen
= fetch_read(&c
, sizeof(c
), 1, conn
);
542 if (rlen
<= 0 || c
== '\n')
546 *errormsg
= "Input line is too long";
547 fetch_clearerr(conn
);
556 fetch_start_ssl(int sock
, const char *servername
)
562 /* Init the SSL library and context */
563 if (!SSL_library_init()){
564 fprintf(ttyout
, "SSL library init failed\n");
568 SSL_load_error_strings();
570 ctx
= SSL_CTX_new(SSLv23_client_method());
571 SSL_CTX_set_mode(ctx
, SSL_MODE_AUTO_RETRY
);
575 fprintf(ttyout
, "SSL context creation failed\n");
579 SSL_set_fd(ssl
, sock
);
580 if (!SSL_set_tlsext_host_name(ssl
, __UNCONST(servername
))) {
581 fprintf(ttyout
, "SSL hostname setting failed\n");
585 while ((ret
= SSL_connect(ssl
)) == -1) {
586 ssl_err
= SSL_get_error(ssl
, ret
);
587 if (ssl_err
!= SSL_ERROR_WANT_READ
&&
588 ssl_err
!= SSL_ERROR_WANT_WRITE
) {
589 ERR_print_errors_fp(ttyout
);
595 if (ftp_debug
&& verbose
) {
600 fprintf(ttyout
, "SSL connection established using %s\n",
601 SSL_get_cipher(ssl
));
602 cert
= SSL_get_peer_certificate(ssl
);
603 name
= X509_get_subject_name(cert
);
604 str
= X509_NAME_oneline(name
, 0, 0);
605 fprintf(ttyout
, "Certificate subject: %s\n", str
);
607 name
= X509_get_issuer_name(cert
);
608 str
= X509_NAME_oneline(name
, 0, 0);
609 fprintf(ttyout
, "Certificate issuer: %s\n", str
);
618 fetch_set_ssl(struct fetch_connect
*conn
, void *ssl
)