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 ev_tstamp 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 std::shared_ptr<std::vector<uint8_t>> ocsp_data; 76 77 // Path to certificate file 78 const char *cert_file; 79 }; 80 81 // Create server side SSL_CTX 82 SSL_CTX *create_ssl_context(const char *private_key_file, const char *cert_file, 83 const std::vector<uint8_t> &sct_data 84 85 #ifdef HAVE_NEVERBLEED 86 , 87 neverbleed_t *nb 88 #endif // HAVE_NEVERBLEED 89 ); 90 91 // Create client side SSL_CTX. This does not configure ALPN settings. 92 // |next_proto_select_cb| is for NPN. 93 SSL_CTX *create_ssl_client_context( 94 #ifdef HAVE_NEVERBLEED 95 neverbleed_t *nb, 96 #endif // HAVE_NEVERBLEED 97 const StringRef &cacert, const StringRef &cert_file, 98 const StringRef &private_key_file, 99 int (*next_proto_select_cb)(SSL *s, unsigned char **out, 100 unsigned char *outlen, const unsigned char *in, 101 unsigned int inlen, void *arg)); 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 struct WildcardRevPrefix { WildcardRevPrefixWildcardRevPrefix114 WildcardRevPrefix(const StringRef &prefix, size_t idx) 115 : prefix(std::begin(prefix), std::end(prefix)), idx(idx) {} 116 117 // "Prefix" of wildcard pattern. It is reversed from original form. 118 // For example, if the original wildcard is "test*.nghttp2.org", 119 // prefix would be "tset". 120 ImmutableString prefix; 121 // The index of SSL_CTX. See ConnectionHandler::get_ssl_ctx(). 122 size_t idx; 123 }; 124 125 struct WildcardPattern { 126 // Wildcard host sharing only suffix is probably rare, so we just do 127 // linear search. 128 std::vector<WildcardRevPrefix> rev_prefix; 129 }; 130 131 class CertLookupTree { 132 public: 133 CertLookupTree(); 134 135 // Adds hostname pattern |hostname| to the lookup tree, associating 136 // value |index|. When the queried host matches this pattern, 137 // |index| is returned. We support wildcard pattern. The left most 138 // '*' is considered as wildcard character, and it must match at 139 // least one character. If the same pattern has been already added, 140 // this function does not alter the tree, and returns the existing 141 // matching index. 142 // 143 // The caller should lower-case |hostname| since this function does 144 // do that, and lookup function performs case-sensitive match. 145 // 146 // TODO Treat wildcard pattern described as RFC 6125. 147 // 148 // This function returns the index. It returns -1 if it fails 149 // (e.g., hostname is too long). If the returned index equals to 150 // |index|, then hostname is added to the tree with the value 151 // |index|. If it is not -1, and does not equal to |index|, same 152 // hostname has already been added to the tree. 153 ssize_t add_cert(const StringRef &hostname, size_t index); 154 155 // Looks up index using the given |hostname|. The exact match takes 156 // precedence over wildcard match. For wildcard match, longest 157 // match (sum of matched suffix and prefix length in bytes) is 158 // preferred, breaking a tie with longer suffix. 159 // 160 // The caller should lower-case |hostname| since this function 161 // performs case-sensitive match. 162 ssize_t lookup(const StringRef &hostname); 163 164 // Dumps the contents of this lookup tree to stderr. 165 void dump() const; 166 167 private: 168 // Exact match 169 Router router_; 170 // Wildcard reversed suffix match. The returned index is into 171 // wildcard_patterns_. 172 Router rev_wildcard_router_; 173 // Stores wildcard suffix patterns. 174 std::vector<WildcardPattern> wildcard_patterns_; 175 }; 176 177 // Adds hostnames in certificate in |ssl_ctx| to lookup tree |lt|. 178 // The subjectAltNames and commonName are considered as eligible 179 // hostname. If there is at least one dNSName in subjectAltNames, 180 // commonName is not considered. |ssl_ctx| is also added to 181 // |indexed_ssl_ctx|. This function returns 0 if it succeeds, or -1. 182 int cert_lookup_tree_add_ssl_ctx( 183 CertLookupTree *lt, std::vector<std::vector<SSL_CTX *>> &indexed_ssl_ctx, 184 SSL_CTX *ssl_ctx); 185 186 // Returns true if |proto| is included in the 187 // protocol list |protos|. 188 bool in_proto_list(const std::vector<StringRef> &protos, 189 const StringRef &proto); 190 191 // Returns true if security requirement for HTTP/2 is fulfilled. 192 bool check_http2_requirement(SSL *ssl); 193 194 // Returns SSL/TLS option mask to disable SSL/TLS protocol version not 195 // included in |tls_proto_list|. The returned mask can be directly 196 // passed to SSL_CTX_set_options(). 197 long int create_tls_proto_mask(const std::vector<StringRef> &tls_proto_list); 198 199 int set_alpn_prefs(std::vector<unsigned char> &out, 200 const std::vector<StringRef> &protos); 201 202 // Setups server side SSL_CTX. This function inspects get_config() 203 // and if upstream_no_tls is true, returns nullptr. Otherwise 204 // construct default SSL_CTX. If subcerts are available 205 // (get_config()->subcerts), caller should provide CertLookupTree 206 // object as |cert_tree| parameter, otherwise SNI does not work. All 207 // the created SSL_CTX is stored into |all_ssl_ctx|. They are also 208 // added to |indexed_ssl_ctx|. |cert_tree| uses its index to 209 // associate hostname to the SSL_CTX. 210 SSL_CTX * 211 setup_server_ssl_context(std::vector<SSL_CTX *> &all_ssl_ctx, 212 std::vector<std::vector<SSL_CTX *>> &indexed_ssl_ctx, 213 CertLookupTree *cert_tree 214 #ifdef HAVE_NEVERBLEED 215 , 216 neverbleed_t *nb 217 #endif // HAVE_NEVERBLEED 218 ); 219 220 // Setups client side SSL_CTX. 221 SSL_CTX *setup_downstream_client_ssl_context( 222 #ifdef HAVE_NEVERBLEED 223 neverbleed_t *nb 224 #endif // HAVE_NEVERBLEED 225 ); 226 227 // Sets ALPN settings in |SSL| suitable for HTTP/2 use. 228 void setup_downstream_http2_alpn(SSL *ssl); 229 // Sets ALPN settings in |SSL| suitable for HTTP/1.1 use. 230 void setup_downstream_http1_alpn(SSL *ssl); 231 232 // Creates CertLookupTree. If frontend is configured not to use TLS, 233 // this function returns nullptr. 234 std::unique_ptr<CertLookupTree> create_cert_lookup_tree(); 235 236 SSL *create_ssl(SSL_CTX *ssl_ctx); 237 238 // Returns true if SSL/TLS is enabled on upstream 239 bool upstream_tls_enabled(const ConnectionConfig &connconf); 240 241 // Performs TLS hostname match. |pattern| can contain wildcard 242 // character '*', which matches prefix of target hostname. There are 243 // several restrictions to make wildcard work. The matching algorithm 244 // is based on RFC 6125. 245 bool tls_hostname_match(const StringRef &pattern, const StringRef &hostname); 246 247 // Caches |session|. |session| is serialized into ASN1 248 // representation, and stored. |t| is used as a time stamp. 249 // Depending on the existing cache's time stamp, |session| might not 250 // be cached. 251 void try_cache_tls_session(TLSSessionCache *cache, SSL_SESSION *session, 252 ev_tstamp t); 253 254 // Returns cached session associated |addr|. If no cache entry is 255 // found associated to |addr|, nullptr will be returned. 256 SSL_SESSION *reuse_tls_session(const TLSSessionCache &addr); 257 258 // Loads certificate form file |filename|. The caller should delete 259 // the returned object using X509_free(). 260 X509 *load_certificate(const char *filename); 261 262 // Returns TLS version from |v|. The returned value is defined in 263 // OpenSSL header file. This function returns -1 if |v| is not valid 264 // TLS version string. 265 int proto_version_from_string(const StringRef &v); 266 267 // Verifies OCSP response |ocsp_resp| of length |ocsp_resplen|. This 268 // function returns 0 if it succeeds, or -1. 269 int verify_ocsp_response(SSL_CTX *ssl_ctx, const uint8_t *ocsp_resp, 270 size_t ocsp_resplen); 271 272 // Stores fingerprint of |x| in |dst| of length |dstlen|. |md| 273 // specifies hash function to use, and |dstlen| must be large enough 274 // to include hash value (e.g., 32 bytes for SHA-256). This function 275 // returns the number of bytes written in |dst|, or -1. 276 ssize_t get_x509_fingerprint(uint8_t *dst, size_t dstlen, const X509 *x, 277 const EVP_MD *md); 278 279 // Returns subject name of |x|. If this function fails to get subject 280 // name, it returns an empty string. 281 StringRef get_x509_subject_name(BlockAllocator &balloc, X509 *x); 282 283 // Returns issuer name of |x|. If this function fails to get issuer 284 // name, it returns an empty string. 285 StringRef get_x509_issuer_name(BlockAllocator &balloc, X509 *x); 286 287 // Returns serial number of |x|. If this function fails to get serial 288 // number, it returns an empty string. number 289 StringRef get_x509_serial(BlockAllocator &balloc, X509 *x); 290 291 // Fills NotBefore of |x| in |t|. This function returns 0 if it 292 // succeeds, or -1. 293 int get_x509_not_before(time_t &t, X509 *x); 294 295 // Fills NotAfter of |x| in |t|. This function returns 0 if it 296 // succeeds, or -1. 297 int get_x509_not_after(time_t &t, X509 *x); 298 299 } // namespace tls 300 301 } // namespace shrpx 302 303 #endif // SHRPX_TLS_H 304