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 <openssl/err.h>
18 #include <openssl/rand.h>
19 #include <openssl/ssl.h>
20 
21 #include "internal.h"
22 #include "transport_common.h"
23 
24 
25 static const struct argument kArguments[] = {
26     {
27         "-accept", kRequiredArgument,
28         "The port of the server to bind on; eg 45102",
29     },
30     {
31         "-cipher", kOptionalArgument,
32         "An OpenSSL-style cipher suite string that configures the offered "
33         "ciphers",
34     },
35     {
36         "-max-version", kOptionalArgument,
37         "The maximum acceptable protocol version",
38     },
39     {
40         "-min-version", kOptionalArgument,
41         "The minimum acceptable protocol version",
42     },
43     {
44         "-key", kOptionalArgument,
45         "PEM-encoded file containing the private key, leaf certificate and "
46         "optional certificate chain. A self-signed certificate is generated "
47         "at runtime if this argument is not provided.",
48     },
49     {
50         "-ocsp-response", kOptionalArgument, "OCSP response file to send",
51     },
52     {
53         "-loop", kBooleanArgument,
54         "The server will continue accepting new sequential connections.",
55     },
56     {
57         "-early-data", kBooleanArgument, "Allow early data",
58     },
59     {
60         "", kOptionalArgument, "",
61     },
62 };
63 
LoadOCSPResponse(SSL_CTX * ctx,const char * filename)64 static bool LoadOCSPResponse(SSL_CTX *ctx, const char *filename) {
65   void *data = NULL;
66   bool ret = false;
67   size_t bytes_read;
68   long length;
69 
70   FILE *f = fopen(filename, "rb");
71 
72   if (f == NULL ||
73       fseek(f, 0, SEEK_END) != 0) {
74     goto out;
75   }
76 
77   length = ftell(f);
78   if (length < 0) {
79     goto out;
80   }
81 
82   data = malloc(length);
83   if (data == NULL) {
84     goto out;
85   }
86   rewind(f);
87 
88   bytes_read = fread(data, 1, length, f);
89   if (ferror(f) != 0 ||
90       bytes_read != (size_t)length ||
91       !SSL_CTX_set_ocsp_response(ctx, (uint8_t*)data, bytes_read)) {
92     goto out;
93   }
94 
95   ret = true;
96 out:
97   if (f != NULL) {
98       fclose(f);
99   }
100   free(data);
101   return ret;
102 }
103 
MakeKeyPairForSelfSignedCert()104 static bssl::UniquePtr<EVP_PKEY> MakeKeyPairForSelfSignedCert() {
105   bssl::UniquePtr<EC_KEY> ec_key(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
106   if (!ec_key || !EC_KEY_generate_key(ec_key.get())) {
107     fprintf(stderr, "Failed to generate key pair.\n");
108     return nullptr;
109   }
110   bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
111   if (!evp_pkey || !EVP_PKEY_assign_EC_KEY(evp_pkey.get(), ec_key.release())) {
112     fprintf(stderr, "Failed to assign key pair.\n");
113     return nullptr;
114   }
115   return evp_pkey;
116 }
117 
MakeSelfSignedCert(EVP_PKEY * evp_pkey,const int valid_days)118 static bssl::UniquePtr<X509> MakeSelfSignedCert(EVP_PKEY *evp_pkey,
119                                                 const int valid_days) {
120   bssl::UniquePtr<X509> x509(X509_new());
121   uint32_t serial;
122   RAND_bytes(reinterpret_cast<uint8_t*>(&serial), sizeof(serial));
123   ASN1_INTEGER_set(X509_get_serialNumber(x509.get()), serial >> 1);
124   X509_gmtime_adj(X509_get_notBefore(x509.get()), 0);
125   X509_gmtime_adj(X509_get_notAfter(x509.get()), 60 * 60 * 24 * valid_days);
126 
127   X509_NAME* subject = X509_get_subject_name(x509.get());
128   X509_NAME_add_entry_by_txt(subject, "C", MBSTRING_ASC,
129                              reinterpret_cast<const uint8_t *>("US"), -1, -1,
130                              0);
131   X509_NAME_add_entry_by_txt(subject, "O", MBSTRING_ASC,
132                              reinterpret_cast<const uint8_t *>("BoringSSL"), -1,
133                              -1, 0);
134   X509_set_issuer_name(x509.get(), subject);
135 
136   if (!X509_set_pubkey(x509.get(), evp_pkey)) {
137     fprintf(stderr, "Failed to set public key.\n");
138     return nullptr;
139   }
140   if (!X509_sign(x509.get(), evp_pkey, EVP_sha256())) {
141     fprintf(stderr, "Failed to sign certificate.\n");
142     return nullptr;
143   }
144   return x509;
145 }
146 
Server(const std::vector<std::string> & args)147 bool Server(const std::vector<std::string> &args) {
148   if (!InitSocketLibrary()) {
149     return false;
150   }
151 
152   std::map<std::string, std::string> args_map;
153 
154   if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
155     PrintUsage(kArguments);
156     return false;
157   }
158 
159   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
160   SSL_CTX_set_options(ctx.get(), SSL_OP_NO_SSLv3);
161 
162   // Server authentication is required.
163   if (args_map.count("-key") != 0) {
164     std::string key_file = args_map["-key"];
165     if (!SSL_CTX_use_PrivateKey_file(ctx.get(), key_file.c_str(), SSL_FILETYPE_PEM)) {
166       fprintf(stderr, "Failed to load private key: %s\n", key_file.c_str());
167       return false;
168     }
169     if (!SSL_CTX_use_certificate_chain_file(ctx.get(), key_file.c_str())) {
170       fprintf(stderr, "Failed to load cert chain: %s\n", key_file.c_str());
171       return false;
172     }
173   } else {
174     bssl::UniquePtr<EVP_PKEY> evp_pkey = MakeKeyPairForSelfSignedCert();
175     if (!evp_pkey) {
176       return false;
177     }
178     bssl::UniquePtr<X509> cert =
179         MakeSelfSignedCert(evp_pkey.get(), 365 /* valid_days */);
180     if (!cert) {
181       return false;
182     }
183     if (!SSL_CTX_use_PrivateKey(ctx.get(), evp_pkey.get())) {
184       fprintf(stderr, "Failed to set private key.\n");
185       return false;
186     }
187     if (!SSL_CTX_use_certificate(ctx.get(), cert.get())) {
188       fprintf(stderr, "Failed to set certificate.\n");
189       return false;
190     }
191   }
192 
193   if (args_map.count("-cipher") != 0 &&
194       !SSL_CTX_set_strict_cipher_list(ctx.get(), args_map["-cipher"].c_str())) {
195     fprintf(stderr, "Failed setting cipher list\n");
196     return false;
197   }
198 
199   uint16_t max_version = TLS1_3_VERSION;
200   if (args_map.count("-max-version") != 0 &&
201       !VersionFromString(&max_version, args_map["-max-version"])) {
202     fprintf(stderr, "Unknown protocol version: '%s'\n",
203             args_map["-max-version"].c_str());
204     return false;
205   }
206 
207   if (!SSL_CTX_set_max_proto_version(ctx.get(), max_version)) {
208     return false;
209   }
210 
211   if (args_map.count("-min-version") != 0) {
212     uint16_t version;
213     if (!VersionFromString(&version, args_map["-min-version"])) {
214       fprintf(stderr, "Unknown protocol version: '%s'\n",
215               args_map["-min-version"].c_str());
216       return false;
217     }
218     if (!SSL_CTX_set_min_proto_version(ctx.get(), version)) {
219       return false;
220     }
221   }
222 
223   if (args_map.count("-ocsp-response") != 0 &&
224       !LoadOCSPResponse(ctx.get(), args_map["-ocsp-response"].c_str())) {
225     fprintf(stderr, "Failed to load OCSP response: %s\n", args_map["-ocsp-response"].c_str());
226     return false;
227   }
228 
229   if (args_map.count("-early-data") != 0) {
230     SSL_CTX_set_early_data_enabled(ctx.get(), 1);
231   }
232 
233   bool result = true;
234   do {
235     int sock = -1;
236     if (!Accept(&sock, args_map["-accept"])) {
237       return false;
238     }
239 
240     BIO *bio = BIO_new_socket(sock, BIO_CLOSE);
241     bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
242     SSL_set_bio(ssl.get(), bio, bio);
243 
244     int ret = SSL_accept(ssl.get());
245     if (ret != 1) {
246       int ssl_err = SSL_get_error(ssl.get(), ret);
247       fprintf(stderr, "Error while connecting: %d\n", ssl_err);
248       ERR_print_errors_cb(PrintErrorCallback, stderr);
249       return false;
250     }
251 
252     fprintf(stderr, "Connected.\n");
253     PrintConnectionInfo(ssl.get());
254 
255     result = TransferData(ssl.get(), sock);
256   } while (result && args_map.count("-loop") != 0);
257 
258   return result;
259 }
260