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 <memory>
18 
19 #include <openssl/err.h>
20 #include <openssl/rand.h>
21 #include <openssl/ssl.h>
22 
23 #include "internal.h"
24 #include "transport_common.h"
25 
26 
27 static const struct argument kArguments[] = {
28     {
29         "-accept", kRequiredArgument,
30         "The port of the server to bind on; eg 45102",
31     },
32     {
33         "-cipher", kOptionalArgument,
34         "An OpenSSL-style cipher suite string that configures the offered "
35         "ciphers",
36     },
37     {
38         "-curves", kOptionalArgument,
39         "An OpenSSL-style ECDH curves list that configures the offered curves",
40     },
41     {
42         "-max-version", kOptionalArgument,
43         "The maximum acceptable protocol version",
44     },
45     {
46         "-min-version", kOptionalArgument,
47         "The minimum acceptable protocol version",
48     },
49     {
50         "-key", kOptionalArgument,
51         "PEM-encoded file containing the private key. A self-signed "
52         "certificate is generated at runtime if this argument is not provided.",
53     },
54     {
55         "-cert", kOptionalArgument,
56         "PEM-encoded file containing the leaf certificate and optional "
57         "certificate chain. This is taken from the -key argument if this "
58         "argument is not provided.",
59     },
60     {
61         "-ocsp-response", kOptionalArgument, "OCSP response file to send",
62     },
63     {
64         "-loop", kBooleanArgument,
65         "The server will continue accepting new sequential connections.",
66     },
67     {
68         "-early-data", kBooleanArgument, "Allow early data",
69     },
70     {
71         "-www", kBooleanArgument,
72         "The server will print connection information in response to a "
73         "HTTP GET request.",
74     },
75     {
76         "-debug", kBooleanArgument,
77         "Print debug information about the handshake",
78     },
79     {
80         "-require-any-client-cert", kBooleanArgument,
81         "The server will require a client certificate.",
82     },
83     {
84         "-jdk11-workaround", kBooleanArgument,
85         "Enable the JDK 11 workaround",
86     },
87     {
88         "", kOptionalArgument, "",
89     },
90 };
91 
LoadOCSPResponse(SSL_CTX * ctx,const char * filename)92 static bool LoadOCSPResponse(SSL_CTX *ctx, const char *filename) {
93   ScopedFILE f(fopen(filename, "rb"));
94   std::vector<uint8_t> data;
95   if (f == nullptr ||
96       !ReadAll(&data, f.get())) {
97     fprintf(stderr, "Error reading %s.\n", filename);
98     return false;
99   }
100 
101   if (!SSL_CTX_set_ocsp_response(ctx, data.data(), data.size())) {
102     return false;
103   }
104 
105   return true;
106 }
107 
MakeKeyPairForSelfSignedCert()108 static bssl::UniquePtr<EVP_PKEY> MakeKeyPairForSelfSignedCert() {
109   bssl::UniquePtr<EC_KEY> ec_key(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
110   if (!ec_key || !EC_KEY_generate_key(ec_key.get())) {
111     fprintf(stderr, "Failed to generate key pair.\n");
112     return nullptr;
113   }
114   bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
115   if (!evp_pkey || !EVP_PKEY_assign_EC_KEY(evp_pkey.get(), ec_key.release())) {
116     fprintf(stderr, "Failed to assign key pair.\n");
117     return nullptr;
118   }
119   return evp_pkey;
120 }
121 
MakeSelfSignedCert(EVP_PKEY * evp_pkey,const int valid_days)122 static bssl::UniquePtr<X509> MakeSelfSignedCert(EVP_PKEY *evp_pkey,
123                                                 const int valid_days) {
124   bssl::UniquePtr<X509> x509(X509_new());
125   uint32_t serial;
126   RAND_bytes(reinterpret_cast<uint8_t*>(&serial), sizeof(serial));
127   ASN1_INTEGER_set(X509_get_serialNumber(x509.get()), serial >> 1);
128   X509_gmtime_adj(X509_get_notBefore(x509.get()), 0);
129   X509_gmtime_adj(X509_get_notAfter(x509.get()), 60 * 60 * 24 * valid_days);
130 
131   X509_NAME* subject = X509_get_subject_name(x509.get());
132   X509_NAME_add_entry_by_txt(subject, "C", MBSTRING_ASC,
133                              reinterpret_cast<const uint8_t *>("US"), -1, -1,
134                              0);
135   X509_NAME_add_entry_by_txt(subject, "O", MBSTRING_ASC,
136                              reinterpret_cast<const uint8_t *>("BoringSSL"), -1,
137                              -1, 0);
138   X509_set_issuer_name(x509.get(), subject);
139 
140   if (!X509_set_pubkey(x509.get(), evp_pkey)) {
141     fprintf(stderr, "Failed to set public key.\n");
142     return nullptr;
143   }
144   if (!X509_sign(x509.get(), evp_pkey, EVP_sha256())) {
145     fprintf(stderr, "Failed to sign certificate.\n");
146     return nullptr;
147   }
148   return x509;
149 }
150 
InfoCallback(const SSL * ssl,int type,int value)151 static void InfoCallback(const SSL *ssl, int type, int value) {
152   switch (type) {
153     case SSL_CB_HANDSHAKE_START:
154       fprintf(stderr, "Handshake started.\n");
155       break;
156     case SSL_CB_HANDSHAKE_DONE:
157       fprintf(stderr, "Handshake done.\n");
158       break;
159     case SSL_CB_ACCEPT_LOOP:
160       fprintf(stderr, "Handshake progress: %s\n", SSL_state_string_long(ssl));
161       break;
162   }
163 }
164 
165 static FILE *g_keylog_file = nullptr;
166 
KeyLogCallback(const SSL * ssl,const char * line)167 static void KeyLogCallback(const SSL *ssl, const char *line) {
168   fprintf(g_keylog_file, "%s\n", line);
169   fflush(g_keylog_file);
170 }
171 
HandleWWW(SSL * ssl)172 static bool HandleWWW(SSL *ssl) {
173   bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
174   if (!bio) {
175     fprintf(stderr, "Cannot create BIO for response\n");
176     return false;
177   }
178 
179   BIO_puts(bio.get(), "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n");
180   PrintConnectionInfo(bio.get(), ssl);
181 
182   char request[4];
183   size_t request_len = 0;
184   while (request_len < sizeof(request)) {
185     int ssl_ret =
186         SSL_read(ssl, request + request_len, sizeof(request) - request_len);
187     if (ssl_ret <= 0) {
188       int ssl_err = SSL_get_error(ssl, ssl_ret);
189       PrintSSLError(stderr, "Error while reading", ssl_err, ssl_ret);
190       return false;
191     }
192     request_len += static_cast<size_t>(ssl_ret);
193   }
194 
195   // Assume simple HTTP request, print status.
196   if (memcmp(request, "GET ", 4) == 0) {
197     const uint8_t *response;
198     size_t response_len;
199     if (BIO_mem_contents(bio.get(), &response, &response_len)) {
200       SSL_write(ssl, response, response_len);
201     }
202   }
203   return true;
204 }
205 
Server(const std::vector<std::string> & args)206 bool Server(const std::vector<std::string> &args) {
207   if (!InitSocketLibrary()) {
208     return false;
209   }
210 
211   std::map<std::string, std::string> args_map;
212 
213   if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
214     PrintUsage(kArguments);
215     return false;
216   }
217 
218   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
219 
220   const char *keylog_file = getenv("SSLKEYLOGFILE");
221   if (keylog_file) {
222     g_keylog_file = fopen(keylog_file, "a");
223     if (g_keylog_file == nullptr) {
224       perror("fopen");
225       return false;
226     }
227     SSL_CTX_set_keylog_callback(ctx.get(), KeyLogCallback);
228   }
229 
230   // Server authentication is required.
231   if (args_map.count("-key") != 0) {
232     std::string key = args_map["-key"];
233     if (!SSL_CTX_use_PrivateKey_file(ctx.get(), key.c_str(),
234                                      SSL_FILETYPE_PEM)) {
235       fprintf(stderr, "Failed to load private key: %s\n", key.c_str());
236       return false;
237     }
238     const std::string &cert =
239         args_map.count("-cert") != 0 ? args_map["-cert"] : key;
240     if (!SSL_CTX_use_certificate_chain_file(ctx.get(), cert.c_str())) {
241       fprintf(stderr, "Failed to load cert chain: %s\n", cert.c_str());
242       return false;
243     }
244   } else {
245     bssl::UniquePtr<EVP_PKEY> evp_pkey = MakeKeyPairForSelfSignedCert();
246     if (!evp_pkey) {
247       return false;
248     }
249     bssl::UniquePtr<X509> cert =
250         MakeSelfSignedCert(evp_pkey.get(), 365 /* valid_days */);
251     if (!cert) {
252       return false;
253     }
254     if (!SSL_CTX_use_PrivateKey(ctx.get(), evp_pkey.get())) {
255       fprintf(stderr, "Failed to set private key.\n");
256       return false;
257     }
258     if (!SSL_CTX_use_certificate(ctx.get(), cert.get())) {
259       fprintf(stderr, "Failed to set certificate.\n");
260       return false;
261     }
262   }
263 
264   if (args_map.count("-cipher") != 0 &&
265       !SSL_CTX_set_strict_cipher_list(ctx.get(), args_map["-cipher"].c_str())) {
266     fprintf(stderr, "Failed setting cipher list\n");
267     return false;
268   }
269 
270   if (args_map.count("-curves") != 0 &&
271       !SSL_CTX_set1_curves_list(ctx.get(), args_map["-curves"].c_str())) {
272     fprintf(stderr, "Failed setting curves list\n");
273     return false;
274   }
275 
276   uint16_t max_version = TLS1_3_VERSION;
277   if (args_map.count("-max-version") != 0 &&
278       !VersionFromString(&max_version, args_map["-max-version"])) {
279     fprintf(stderr, "Unknown protocol version: '%s'\n",
280             args_map["-max-version"].c_str());
281     return false;
282   }
283 
284   if (!SSL_CTX_set_max_proto_version(ctx.get(), max_version)) {
285     return false;
286   }
287 
288   if (args_map.count("-min-version") != 0) {
289     uint16_t version;
290     if (!VersionFromString(&version, args_map["-min-version"])) {
291       fprintf(stderr, "Unknown protocol version: '%s'\n",
292               args_map["-min-version"].c_str());
293       return false;
294     }
295     if (!SSL_CTX_set_min_proto_version(ctx.get(), version)) {
296       return false;
297     }
298   }
299 
300   if (args_map.count("-ocsp-response") != 0 &&
301       !LoadOCSPResponse(ctx.get(), args_map["-ocsp-response"].c_str())) {
302     fprintf(stderr, "Failed to load OCSP response: %s\n", args_map["-ocsp-response"].c_str());
303     return false;
304   }
305 
306   if (args_map.count("-early-data") != 0) {
307     SSL_CTX_set_early_data_enabled(ctx.get(), 1);
308   }
309 
310   if (args_map.count("-debug") != 0) {
311     SSL_CTX_set_info_callback(ctx.get(), InfoCallback);
312   }
313 
314   if (args_map.count("-require-any-client-cert") != 0) {
315     SSL_CTX_set_verify(
316         ctx.get(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
317     SSL_CTX_set_cert_verify_callback(
318         ctx.get(), [](X509_STORE_CTX *store, void *arg) -> int { return 1; },
319         nullptr);
320   }
321 
322   Listener listener;
323   if (!listener.Init(args_map["-accept"])) {
324     return false;
325   }
326 
327   bool result = true;
328   do {
329     int sock = -1;
330     if (!listener.Accept(&sock)) {
331       return false;
332     }
333 
334     BIO *bio = BIO_new_socket(sock, BIO_CLOSE);
335     bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
336     SSL_set_bio(ssl.get(), bio, bio);
337 
338     if (args_map.count("-jdk11-workaround") != 0) {
339       SSL_set_jdk11_workaround(ssl.get(), 1);
340     }
341 
342     int ret = SSL_accept(ssl.get());
343     if (ret != 1) {
344       int ssl_err = SSL_get_error(ssl.get(), ret);
345       PrintSSLError(stderr, "Error while connecting", ssl_err, ret);
346       result = false;
347       continue;
348     }
349 
350     fprintf(stderr, "Connected.\n");
351     bssl::UniquePtr<BIO> bio_stderr(BIO_new_fp(stderr, BIO_NOCLOSE));
352     PrintConnectionInfo(bio_stderr.get(), ssl.get());
353 
354     if (args_map.count("-www") != 0) {
355       result = HandleWWW(ssl.get());
356     } else {
357       result = TransferData(ssl.get(), sock);
358     }
359   } while (args_map.count("-loop") != 0);
360 
361   return result;
362 }
363