1 /* 2 * nghttp2 - HTTP/2 C Library 3 * 4 * Copyright (c) 2012 Tatsuhiro Tsujikawa 5 * 6 * Permission is hereby granted, free of charge, to any person obtaining 7 * a copy of this software and associated documentation files (the 8 * "Software"), to deal in the Software without restriction, including 9 * without limitation the rights to use, copy, modify, merge, publish, 10 * distribute, sublicense, and/or sell copies of the Software, and to 11 * permit persons to whom the Software is furnished to do so, subject to 12 * the following conditions: 13 * 14 * The above copyright notice and this permission notice shall be 15 * included in all copies or substantial portions of the Software. 16 * 17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 */ 25 #ifndef SHRPX_TLS_H 26 #define SHRPX_TLS_H 27 28 #include "shrpx.h" 29 30 #include <vector> 31 #include <mutex> 32 33 #include <openssl/ssl.h> 34 #include <openssl/err.h> 35 36 #include <ev.h> 37 38 #ifdef HAVE_NEVERBLEED 39 # include <neverbleed.h> 40 #endif // HAVE_NEVERBLEED 41 42 #include "network.h" 43 #include "shrpx_config.h" 44 #include "shrpx_router.h" 45 46 namespace shrpx { 47 48 class ClientHandler; 49 class Worker; 50 class DownstreamConnectionPool; 51 struct DownstreamAddr; 52 struct UpstreamAddr; 53 54 namespace tls { 55 56 struct TLSSessionCache { 57 // ASN1 representation of SSL_SESSION object. See 58 // i2d_SSL_SESSION(3SSL). 59 std::vector<uint8_t> session_data; 60 // The last time stamp when this cache entry is created or updated. 61 std::chrono::steady_clock::time_point last_updated; 62 }; 63 64 // This struct stores the additional information per SSL_CTX. This is 65 // attached to SSL_CTX using SSL_CTX_set_app_data(). 66 struct TLSContextData { 67 // SCT data formatted so that this can be directly sent as 68 // extension_data of signed_certificate_timestamp. 69 std::vector<uint8_t> sct_data; 70 #ifndef HAVE_ATOMIC_STD_SHARED_PTR 71 // Protects ocsp_data; 72 std::mutex mu; 73 #endif // !HAVE_ATOMIC_STD_SHARED_PTR 74 // OCSP response 75 #ifdef HAVE_ATOMIC_STD_SHARED_PTR 76 std::atomic<std::shared_ptr<std::vector<uint8_t>>> ocsp_data; 77 #else // !HAVE_ATOMIC_STD_SHARED_PTR 78 std::shared_ptr<std::vector<uint8_t>> ocsp_data; 79 #endif // !HAVE_ATOMIC_STD_SHARED_PTR 80 81 // Path to certificate file 82 const char *cert_file; 83 }; 84 85 // Create server side SSL_CTX 86 SSL_CTX *create_ssl_context(const char *private_key_file, const char *cert_file, 87 const std::vector<uint8_t> &sct_data 88 89 #ifdef HAVE_NEVERBLEED 90 , 91 neverbleed_t *nb 92 #endif // HAVE_NEVERBLEED 93 ); 94 95 // Create client side SSL_CTX. This does not configure ALPN settings. 96 SSL_CTX *create_ssl_client_context( 97 #ifdef HAVE_NEVERBLEED 98 neverbleed_t *nb, 99 #endif // HAVE_NEVERBLEED 100 const StringRef &cacert, const StringRef &cert_file, 101 const StringRef &private_key_file); 102 103 ClientHandler *accept_connection(Worker *worker, int fd, sockaddr *addr, 104 int addrlen, const UpstreamAddr *faddr); 105 106 // Check peer's certificate against given |address| and |host|. 107 int check_cert(SSL *ssl, const Address *addr, const StringRef &host); 108 // Check peer's certificate against given host name described in 109 // |addr| and numeric address in |raddr|. Note that |raddr| might not 110 // point to &addr->addr. 111 int check_cert(SSL *ssl, const DownstreamAddr *addr, const Address *raddr); 112 113 // Verify |cert| using numeric IP address. |hostname| and |addr| 114 // should contain the same numeric IP address. This function returns 115 // 0 if it succeeds, or -1. 116 int verify_numeric_hostname(X509 *cert, const StringRef &hostname, 117 const Address *addr); 118 119 // Verify |cert| using DNS name hostname. This function returns 0 if 120 // it succeeds, or -1. 121 int verify_dns_hostname(X509 *cert, const StringRef &hostname); 122 123 struct WildcardRevPrefix { WildcardRevPrefixWildcardRevPrefix124 WildcardRevPrefix(const StringRef &prefix, size_t idx) 125 : prefix(std::begin(prefix), std::end(prefix)), idx(idx) {} 126 127 // "Prefix" of wildcard pattern. It is reversed from original form. 128 // For example, if the original wildcard is "test*.nghttp2.org", 129 // prefix would be "tset". 130 ImmutableString prefix; 131 // The index of SSL_CTX. See ConnectionHandler::get_ssl_ctx(). 132 size_t idx; 133 }; 134 135 struct WildcardPattern { 136 // Wildcard host sharing only suffix is probably rare, so we just do 137 // linear search. 138 std::vector<WildcardRevPrefix> rev_prefix; 139 }; 140 141 class CertLookupTree { 142 public: 143 CertLookupTree(); 144 145 // Adds hostname pattern |hostname| to the lookup tree, associating 146 // value |index|. When the queried host matches this pattern, 147 // |index| is returned. We support wildcard pattern. The left most 148 // '*' is considered as wildcard character, and it must match at 149 // least one character. If the same pattern has been already added, 150 // this function does not alter the tree, and returns the existing 151 // matching index. 152 // 153 // The caller should lower-case |hostname| since this function does 154 // do that, and lookup function performs case-sensitive match. 155 // 156 // TODO Treat wildcard pattern described as RFC 6125. 157 // 158 // This function returns the index. It returns -1 if it fails 159 // (e.g., hostname is too long). If the returned index equals to 160 // |index|, then hostname is added to the tree with the value 161 // |index|. If it is not -1, and does not equal to |index|, same 162 // hostname has already been added to the tree. 163 ssize_t add_cert(const StringRef &hostname, size_t index); 164 165 // Looks up index using the given |hostname|. The exact match takes 166 // precedence over wildcard match. For wildcard match, longest 167 // match (sum of matched suffix and prefix length in bytes) is 168 // preferred, breaking a tie with longer suffix. 169 // 170 // The caller should lower-case |hostname| since this function 171 // performs case-sensitive match. 172 ssize_t lookup(const StringRef &hostname); 173 174 // Dumps the contents of this lookup tree to stderr. 175 void dump() const; 176 177 private: 178 // Exact match 179 Router router_; 180 // Wildcard reversed suffix match. The returned index is into 181 // wildcard_patterns_. 182 Router rev_wildcard_router_; 183 // Stores wildcard suffix patterns. 184 std::vector<WildcardPattern> wildcard_patterns_; 185 }; 186 187 // Adds hostnames in certificate in |ssl_ctx| to lookup tree |lt|. 188 // The subjectAltNames and commonName are considered as eligible 189 // hostname. If there is at least one dNSName in subjectAltNames, 190 // commonName is not considered. |ssl_ctx| is also added to 191 // |indexed_ssl_ctx|. This function returns 0 if it succeeds, or -1. 192 int cert_lookup_tree_add_ssl_ctx( 193 CertLookupTree *lt, std::vector<std::vector<SSL_CTX *>> &indexed_ssl_ctx, 194 SSL_CTX *ssl_ctx); 195 196 // Returns true if |proto| is included in the 197 // protocol list |protos|. 198 bool in_proto_list(const std::vector<StringRef> &protos, 199 const StringRef &proto); 200 201 // Returns true if security requirement for HTTP/2 is fulfilled. 202 bool check_http2_requirement(SSL *ssl); 203 204 // Returns SSL/TLS option mask to disable SSL/TLS protocol version not 205 // included in |tls_proto_list|. The returned mask can be directly 206 // passed to SSL_CTX_set_options(). 207 long int create_tls_proto_mask(const std::vector<StringRef> &tls_proto_list); 208 209 int set_alpn_prefs(std::vector<unsigned char> &out, 210 const std::vector<StringRef> &protos); 211 212 // Setups server side SSL_CTX. This function inspects get_config() 213 // and if upstream_no_tls is true, returns nullptr. Otherwise 214 // construct default SSL_CTX. If subcerts are available 215 // (get_config()->subcerts), caller should provide CertLookupTree 216 // object as |cert_tree| parameter, otherwise SNI does not work. All 217 // the created SSL_CTX is stored into |all_ssl_ctx|. They are also 218 // added to |indexed_ssl_ctx|. |cert_tree| uses its index to 219 // associate hostname to the SSL_CTX. 220 SSL_CTX * 221 setup_server_ssl_context(std::vector<SSL_CTX *> &all_ssl_ctx, 222 std::vector<std::vector<SSL_CTX *>> &indexed_ssl_ctx, 223 CertLookupTree *cert_tree 224 #ifdef HAVE_NEVERBLEED 225 , 226 neverbleed_t *nb 227 #endif // HAVE_NEVERBLEED 228 ); 229 230 #ifdef ENABLE_HTTP3 231 SSL_CTX *setup_quic_server_ssl_context( 232 std::vector<SSL_CTX *> &all_ssl_ctx, 233 std::vector<std::vector<SSL_CTX *>> &indexed_ssl_ctx, 234 CertLookupTree *cert_tree 235 # ifdef HAVE_NEVERBLEED 236 , 237 neverbleed_t *nb 238 # endif // HAVE_NEVERBLEED 239 ); 240 #endif // ENABLE_HTTP3 241 242 // Setups client side SSL_CTX. 243 SSL_CTX *setup_downstream_client_ssl_context( 244 #ifdef HAVE_NEVERBLEED 245 neverbleed_t *nb 246 #endif // HAVE_NEVERBLEED 247 ); 248 249 // Sets ALPN settings in |SSL| suitable for HTTP/2 use. 250 void setup_downstream_http2_alpn(SSL *ssl); 251 // Sets ALPN settings in |SSL| suitable for HTTP/1.1 use. 252 void setup_downstream_http1_alpn(SSL *ssl); 253 254 // Creates CertLookupTree. If frontend is configured not to use TLS, 255 // this function returns nullptr. 256 std::unique_ptr<CertLookupTree> create_cert_lookup_tree(); 257 258 SSL *create_ssl(SSL_CTX *ssl_ctx); 259 260 // Returns true if SSL/TLS is enabled on upstream 261 bool upstream_tls_enabled(const ConnectionConfig &connconf); 262 263 // Performs TLS hostname match. |pattern| can contain wildcard 264 // character '*', which matches prefix of target hostname. There are 265 // several restrictions to make wildcard work. The matching algorithm 266 // is based on RFC 6125. 267 bool tls_hostname_match(const StringRef &pattern, const StringRef &hostname); 268 269 // Caches |session|. |session| is serialized into ASN1 270 // representation, and stored. |t| is used as a time stamp. 271 // Depending on the existing cache's time stamp, |session| might not 272 // be cached. 273 void try_cache_tls_session(TLSSessionCache *cache, SSL_SESSION *session, 274 const std::chrono::steady_clock::time_point &t); 275 276 // Returns cached session associated |addr|. If no cache entry is 277 // found associated to |addr|, nullptr will be returned. 278 SSL_SESSION *reuse_tls_session(const TLSSessionCache &addr); 279 280 // Loads certificate form file |filename|. The caller should delete 281 // the returned object using X509_free(). 282 X509 *load_certificate(const char *filename); 283 284 // Returns TLS version from |v|. The returned value is defined in 285 // OpenSSL header file. This function returns -1 if |v| is not valid 286 // TLS version string. 287 int proto_version_from_string(const StringRef &v); 288 289 // Verifies OCSP response |ocsp_resp| of length |ocsp_resplen|. This 290 // function returns 0 if it succeeds, or -1. 291 int verify_ocsp_response(SSL_CTX *ssl_ctx, const uint8_t *ocsp_resp, 292 size_t ocsp_resplen); 293 294 // Stores fingerprint of |x| in |dst| of length |dstlen|. |md| 295 // specifies hash function to use, and |dstlen| must be large enough 296 // to include hash value (e.g., 32 bytes for SHA-256). This function 297 // returns the number of bytes written in |dst|, or -1. 298 ssize_t get_x509_fingerprint(uint8_t *dst, size_t dstlen, const X509 *x, 299 const EVP_MD *md); 300 301 // Returns subject name of |x|. If this function fails to get subject 302 // name, it returns an empty string. 303 StringRef get_x509_subject_name(BlockAllocator &balloc, X509 *x); 304 305 // Returns issuer name of |x|. If this function fails to get issuer 306 // name, it returns an empty string. 307 StringRef get_x509_issuer_name(BlockAllocator &balloc, X509 *x); 308 309 // Returns serial number of |x|. If this function fails to get serial 310 // number, it returns an empty string. number 311 StringRef get_x509_serial(BlockAllocator &balloc, X509 *x); 312 313 // Fills NotBefore of |x| in |t|. This function returns 0 if it 314 // succeeds, or -1. 315 int get_x509_not_before(time_t &t, X509 *x); 316 317 // Fills NotAfter of |x| in |t|. This function returns 0 if it 318 // succeeds, or -1. 319 int get_x509_not_after(time_t &t, X509 *x); 320 321 } // namespace tls 322 323 } // namespace shrpx 324 325 #endif // SHRPX_TLS_H 326