1 /* Copyright (c) 2014, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14 
15 #include <openssl/base.h>
16 
17 #include <string>
18 #include <vector>
19 
20 #include <errno.h>
21 #include <stddef.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/types.h>
25 
26 #if !defined(OPENSSL_WINDOWS)
27 #include <arpa/inet.h>
28 #include <fcntl.h>
29 #include <netdb.h>
30 #include <netinet/in.h>
31 #include <sys/select.h>
32 #include <sys/socket.h>
33 #include <unistd.h>
34 #else
35 #include <io.h>
36 #pragma warning(push, 3)
37 #include <winsock2.h>
38 #include <ws2tcpip.h>
39 #pragma warning(pop)
40 
41 typedef int ssize_t;
42 #pragma comment(lib, "Ws2_32.lib")
43 #endif
44 
45 #include <openssl/err.h>
46 #include <openssl/ssl.h>
47 
48 #include "internal.h"
49 
50 
51 #if !defined(OPENSSL_WINDOWS)
closesocket(int sock)52 static int closesocket(int sock) {
53   return close(sock);
54 }
55 #endif
56 
InitSocketLibrary()57 bool InitSocketLibrary() {
58 #if defined(OPENSSL_WINDOWS)
59   WSADATA wsaData;
60   int err = WSAStartup(MAKEWORD(2, 2), &wsaData);
61   if (err != 0) {
62     fprintf(stderr, "WSAStartup failed with error %d\n", err);
63     return false;
64   }
65 #endif
66   return true;
67 }
68 
69 // Connect sets |*out_sock| to be a socket connected to the destination given
70 // in |hostname_and_port|, which should be of the form "www.example.com:123".
71 // It returns true on success and false otherwise.
Connect(int * out_sock,const std::string & hostname_and_port)72 bool Connect(int *out_sock, const std::string &hostname_and_port) {
73   const size_t colon_offset = hostname_and_port.find_last_of(':');
74   std::string hostname, port;
75 
76   if (colon_offset == std::string::npos) {
77     hostname = hostname_and_port;
78     port = "443";
79   } else {
80     hostname = hostname_and_port.substr(0, colon_offset);
81     port = hostname_and_port.substr(colon_offset + 1);
82   }
83 
84   struct addrinfo hint, *result;
85   memset(&hint, 0, sizeof(hint));
86   hint.ai_family = AF_UNSPEC;
87   hint.ai_socktype = SOCK_STREAM;
88 
89   int ret = getaddrinfo(hostname.c_str(), port.c_str(), &hint, &result);
90   if (ret != 0) {
91     fprintf(stderr, "getaddrinfo returned: %s\n", gai_strerror(ret));
92     return false;
93   }
94 
95   bool ok = false;
96   char buf[256];
97 
98   *out_sock =
99       socket(result->ai_family, result->ai_socktype, result->ai_protocol);
100   if (*out_sock < 0) {
101     perror("socket");
102     goto out;
103   }
104 
105   switch (result->ai_family) {
106     case AF_INET: {
107       struct sockaddr_in *sin =
108           reinterpret_cast<struct sockaddr_in *>(result->ai_addr);
109       fprintf(stderr, "Connecting to %s:%d\n",
110               inet_ntop(result->ai_family, &sin->sin_addr, buf, sizeof(buf)),
111               ntohs(sin->sin_port));
112       break;
113     }
114     case AF_INET6: {
115       struct sockaddr_in6 *sin6 =
116           reinterpret_cast<struct sockaddr_in6 *>(result->ai_addr);
117       fprintf(stderr, "Connecting to [%s]:%d\n",
118               inet_ntop(result->ai_family, &sin6->sin6_addr, buf, sizeof(buf)),
119               ntohs(sin6->sin6_port));
120       break;
121     }
122   }
123 
124   if (connect(*out_sock, result->ai_addr, result->ai_addrlen) != 0) {
125     perror("connect");
126     goto out;
127   }
128   ok = true;
129 
130 out:
131   freeaddrinfo(result);
132   return ok;
133 }
134 
Accept(int * out_sock,const std::string & port)135 bool Accept(int *out_sock, const std::string &port) {
136   struct sockaddr_in addr, cli_addr;
137   socklen_t cli_addr_len = sizeof(cli_addr);
138   memset(&addr, 0, sizeof(addr));
139 
140   addr.sin_family = AF_INET;
141   addr.sin_addr.s_addr = INADDR_ANY;
142   addr.sin_port = htons(atoi(port.c_str()));
143 
144   bool ok = false;
145   int server_sock = -1;
146 
147   server_sock =
148       socket(addr.sin_family, SOCK_STREAM, 0);
149   if (server_sock < 0) {
150     perror("socket");
151     goto out;
152   }
153 
154   if (bind(server_sock, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
155     perror("connect");
156     goto out;
157   }
158   listen(server_sock, 1);
159   *out_sock = accept(server_sock, (struct sockaddr*)&cli_addr, &cli_addr_len);
160 
161   ok = true;
162 
163 out:
164   closesocket(server_sock);
165   return ok;
166 }
167 
PrintConnectionInfo(const SSL * ssl)168 void PrintConnectionInfo(const SSL *ssl) {
169   const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
170 
171   fprintf(stderr, "  Version: %s\n", SSL_get_version(ssl));
172   fprintf(stderr, "  Cipher: %s\n", SSL_CIPHER_get_name(cipher));
173   fprintf(stderr, "  Secure renegotiation: %s\n",
174           SSL_get_secure_renegotiation_support(ssl) ? "yes" : "no");
175 
176   const uint8_t *next_proto;
177   unsigned next_proto_len;
178   SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
179   fprintf(stderr, "  Next protocol negotiated: %.*s\n", next_proto_len,
180           next_proto);
181 
182   const uint8_t *alpn;
183   unsigned alpn_len;
184   SSL_get0_alpn_selected(ssl, &alpn, &alpn_len);
185   fprintf(stderr, "  ALPN protocol: %.*s\n", alpn_len, alpn);
186 }
187 
SocketSetNonBlocking(int sock,bool is_non_blocking)188 bool SocketSetNonBlocking(int sock, bool is_non_blocking) {
189   bool ok;
190 
191 #if defined(OPENSSL_WINDOWS)
192   u_long arg = is_non_blocking;
193   ok = 0 == ioctlsocket(sock, FIONBIO, &arg);
194 #else
195   int flags = fcntl(sock, F_GETFL, 0);
196   if (flags < 0) {
197     return false;
198   }
199   if (is_non_blocking) {
200     flags |= O_NONBLOCK;
201   } else {
202     flags &= ~O_NONBLOCK;
203   }
204   ok = 0 == fcntl(sock, F_SETFL, flags);
205 #endif
206   if (!ok) {
207     fprintf(stderr, "Failed to set socket non-blocking.\n");
208   }
209   return ok;
210 }
211 
212 // PrintErrorCallback is a callback function from OpenSSL's
213 // |ERR_print_errors_cb| that writes errors to a given |FILE*|.
PrintErrorCallback(const char * str,size_t len,void * ctx)214 int PrintErrorCallback(const char *str, size_t len, void *ctx) {
215   fwrite(str, len, 1, reinterpret_cast<FILE*>(ctx));
216   return 1;
217 }
218 
TransferData(SSL * ssl,int sock)219 bool TransferData(SSL *ssl, int sock) {
220   bool stdin_open = true;
221 
222   fd_set read_fds;
223   FD_ZERO(&read_fds);
224 
225   if (!SocketSetNonBlocking(sock, true)) {
226     return false;
227   }
228 
229   for (;;) {
230     if (stdin_open) {
231       FD_SET(0, &read_fds);
232     }
233     FD_SET(sock, &read_fds);
234 
235     int ret = select(sock + 1, &read_fds, NULL, NULL, NULL);
236     if (ret <= 0) {
237       perror("select");
238       return false;
239     }
240 
241     if (FD_ISSET(0, &read_fds)) {
242       uint8_t buffer[512];
243       ssize_t n;
244 
245       do {
246         n = read(0, buffer, sizeof(buffer));
247       } while (n == -1 && errno == EINTR);
248 
249       if (n == 0) {
250         FD_CLR(0, &read_fds);
251         stdin_open = false;
252 #if !defined(OPENSSL_WINDOWS)
253         shutdown(sock, SHUT_WR);
254 #else
255         shutdown(sock, SD_SEND);
256 #endif
257         continue;
258       } else if (n < 0) {
259         perror("read from stdin");
260         return false;
261       }
262 
263       if (!SocketSetNonBlocking(sock, false)) {
264         return false;
265       }
266       int ssl_ret = SSL_write(ssl, buffer, n);
267       if (!SocketSetNonBlocking(sock, true)) {
268         return false;
269       }
270 
271       if (ssl_ret <= 0) {
272         int ssl_err = SSL_get_error(ssl, ssl_ret);
273         fprintf(stderr, "Error while writing: %d\n", ssl_err);
274         ERR_print_errors_cb(PrintErrorCallback, stderr);
275         return false;
276       } else if (ssl_ret != n) {
277         fprintf(stderr, "Short write from SSL_write.\n");
278         return false;
279       }
280     }
281 
282     if (FD_ISSET(sock, &read_fds)) {
283       uint8_t buffer[512];
284       int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
285 
286       if (ssl_ret < 0) {
287         int ssl_err = SSL_get_error(ssl, ssl_ret);
288         if (ssl_err == SSL_ERROR_WANT_READ) {
289           continue;
290         }
291         fprintf(stderr, "Error while reading: %d\n", ssl_err);
292         ERR_print_errors_cb(PrintErrorCallback, stderr);
293         return false;
294       } else if (ssl_ret == 0) {
295         return true;
296       }
297 
298       ssize_t n;
299       do {
300         n = write(1, buffer, ssl_ret);
301       } while (n == -1 && errno == EINTR);
302 
303       if (n != ssl_ret) {
304         fprintf(stderr, "Short write to stderr.\n");
305         return false;
306       }
307     }
308   }
309 }
310