netutil.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. #
  2. # Copyright 2011 Facebook
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. """Miscellaneous network utility code."""
  16. import asyncio
  17. import concurrent.futures
  18. import errno
  19. import os
  20. import sys
  21. import socket
  22. import ssl
  23. import stat
  24. from tornado.concurrent import dummy_executor, run_on_executor
  25. from tornado.ioloop import IOLoop
  26. from tornado.util import Configurable, errno_from_exception
  27. from typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional
  28. # Note that the naming of ssl.Purpose is confusing; the purpose
  29. # of a context is to authenticate the opposite side of the connection.
  30. _client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  31. _server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  32. if hasattr(ssl, "OP_NO_COMPRESSION"):
  33. # See netutil.ssl_options_to_context
  34. _client_ssl_defaults.options |= ssl.OP_NO_COMPRESSION
  35. _server_ssl_defaults.options |= ssl.OP_NO_COMPRESSION
  36. # ThreadedResolver runs getaddrinfo on a thread. If the hostname is unicode,
  37. # getaddrinfo attempts to import encodings.idna. If this is done at
  38. # module-import time, the import lock is already held by the main thread,
  39. # leading to deadlock. Avoid it by caching the idna encoder on the main
  40. # thread now.
  41. "foo".encode("idna")
  42. # For undiagnosed reasons, 'latin1' codec may also need to be preloaded.
  43. "foo".encode("latin1")
  44. # Default backlog used when calling sock.listen()
  45. _DEFAULT_BACKLOG = 128
  46. def bind_sockets(
  47. port: int,
  48. address: Optional[str] = None,
  49. family: socket.AddressFamily = socket.AF_UNSPEC,
  50. backlog: int = _DEFAULT_BACKLOG,
  51. flags: Optional[int] = None,
  52. reuse_port: bool = False,
  53. ) -> List[socket.socket]:
  54. """Creates listening sockets bound to the given port and address.
  55. Returns a list of socket objects (multiple sockets are returned if
  56. the given address maps to multiple IP addresses, which is most common
  57. for mixed IPv4 and IPv6 use).
  58. Address may be either an IP address or hostname. If it's a hostname,
  59. the server will listen on all IP addresses associated with the
  60. name. Address may be an empty string or None to listen on all
  61. available interfaces. Family may be set to either `socket.AF_INET`
  62. or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise
  63. both will be used if available.
  64. The ``backlog`` argument has the same meaning as for
  65. `socket.listen() <socket.socket.listen>`.
  66. ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like
  67. ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.
  68. ``reuse_port`` option sets ``SO_REUSEPORT`` option for every socket
  69. in the list. If your platform doesn't support this option ValueError will
  70. be raised.
  71. """
  72. if reuse_port and not hasattr(socket, "SO_REUSEPORT"):
  73. raise ValueError("the platform doesn't support SO_REUSEPORT")
  74. sockets = []
  75. if address == "":
  76. address = None
  77. if not socket.has_ipv6 and family == socket.AF_UNSPEC:
  78. # Python can be compiled with --disable-ipv6, which causes
  79. # operations on AF_INET6 sockets to fail, but does not
  80. # automatically exclude those results from getaddrinfo
  81. # results.
  82. # http://bugs.python.org/issue16208
  83. family = socket.AF_INET
  84. if flags is None:
  85. flags = socket.AI_PASSIVE
  86. bound_port = None
  87. unique_addresses = set() # type: set
  88. for res in sorted(
  89. socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, flags),
  90. key=lambda x: x[0],
  91. ):
  92. if res in unique_addresses:
  93. continue
  94. unique_addresses.add(res)
  95. af, socktype, proto, canonname, sockaddr = res
  96. if (
  97. sys.platform == "darwin"
  98. and address == "localhost"
  99. and af == socket.AF_INET6
  100. and sockaddr[3] != 0 # type: ignore
  101. ):
  102. # Mac OS X includes a link-local address fe80::1%lo0 in the
  103. # getaddrinfo results for 'localhost'. However, the firewall
  104. # doesn't understand that this is a local address and will
  105. # prompt for access (often repeatedly, due to an apparent
  106. # bug in its ability to remember granting access to an
  107. # application). Skip these addresses.
  108. continue
  109. try:
  110. sock = socket.socket(af, socktype, proto)
  111. except OSError as e:
  112. if errno_from_exception(e) == errno.EAFNOSUPPORT:
  113. continue
  114. raise
  115. if os.name != "nt":
  116. try:
  117. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  118. except OSError as e:
  119. if errno_from_exception(e) != errno.ENOPROTOOPT:
  120. # Hurd doesn't support SO_REUSEADDR.
  121. raise
  122. if reuse_port:
  123. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  124. if af == socket.AF_INET6:
  125. # On linux, ipv6 sockets accept ipv4 too by default,
  126. # but this makes it impossible to bind to both
  127. # 0.0.0.0 in ipv4 and :: in ipv6. On other systems,
  128. # separate sockets *must* be used to listen for both ipv4
  129. # and ipv6. For consistency, always disable ipv4 on our
  130. # ipv6 sockets and use a separate ipv4 socket when needed.
  131. #
  132. # Python 2.x on windows doesn't have IPPROTO_IPV6.
  133. if hasattr(socket, "IPPROTO_IPV6"):
  134. sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  135. # automatic port allocation with port=None
  136. # should bind on the same port on IPv4 and IPv6
  137. host, requested_port = sockaddr[:2]
  138. if requested_port == 0 and bound_port is not None:
  139. sockaddr = tuple([host, bound_port] + list(sockaddr[2:]))
  140. sock.setblocking(False)
  141. try:
  142. sock.bind(sockaddr)
  143. except OSError as e:
  144. if (
  145. errno_from_exception(e) == errno.EADDRNOTAVAIL
  146. and address == "localhost"
  147. and sockaddr[0] == "::1"
  148. ):
  149. # On some systems (most notably docker with default
  150. # configurations), ipv6 is partially disabled:
  151. # socket.has_ipv6 is true, we can create AF_INET6
  152. # sockets, and getaddrinfo("localhost", ...,
  153. # AF_PASSIVE) resolves to ::1, but we get an error
  154. # when binding.
  155. #
  156. # Swallow the error, but only for this specific case.
  157. # If EADDRNOTAVAIL occurs in other situations, it
  158. # might be a real problem like a typo in a
  159. # configuration.
  160. sock.close()
  161. continue
  162. else:
  163. raise
  164. bound_port = sock.getsockname()[1]
  165. sock.listen(backlog)
  166. sockets.append(sock)
  167. return sockets
  168. if hasattr(socket, "AF_UNIX"):
  169. def bind_unix_socket(
  170. file: str, mode: int = 0o600, backlog: int = _DEFAULT_BACKLOG
  171. ) -> socket.socket:
  172. """Creates a listening unix socket.
  173. If a socket with the given name already exists, it will be deleted.
  174. If any other file with that name exists, an exception will be
  175. raised.
  176. Returns a socket object (not a list of socket objects like
  177. `bind_sockets`)
  178. """
  179. sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  180. try:
  181. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  182. except OSError as e:
  183. if errno_from_exception(e) != errno.ENOPROTOOPT:
  184. # Hurd doesn't support SO_REUSEADDR
  185. raise
  186. sock.setblocking(False)
  187. # File names comprising of an initial null-byte denote an abstract
  188. # namespace, on Linux, and therefore are not subject to file system
  189. # orientated processing.
  190. if not file.startswith("\0"):
  191. try:
  192. st = os.stat(file)
  193. except FileNotFoundError:
  194. pass
  195. else:
  196. if stat.S_ISSOCK(st.st_mode):
  197. os.remove(file)
  198. else:
  199. raise ValueError("File %s exists and is not a socket", file)
  200. sock.bind(file)
  201. os.chmod(file, mode)
  202. else:
  203. sock.bind(file)
  204. sock.listen(backlog)
  205. return sock
  206. def add_accept_handler(
  207. sock: socket.socket, callback: Callable[[socket.socket, Any], None]
  208. ) -> Callable[[], None]:
  209. """Adds an `.IOLoop` event handler to accept new connections on ``sock``.
  210. When a connection is accepted, ``callback(connection, address)`` will
  211. be run (``connection`` is a socket object, and ``address`` is the
  212. address of the other end of the connection). Note that this signature
  213. is different from the ``callback(fd, events)`` signature used for
  214. `.IOLoop` handlers.
  215. A callable is returned which, when called, will remove the `.IOLoop`
  216. event handler and stop processing further incoming connections.
  217. .. versionchanged:: 5.0
  218. The ``io_loop`` argument (deprecated since version 4.1) has been removed.
  219. .. versionchanged:: 5.0
  220. A callable is returned (``None`` was returned before).
  221. """
  222. io_loop = IOLoop.current()
  223. removed = [False]
  224. def accept_handler(fd: socket.socket, events: int) -> None:
  225. # More connections may come in while we're handling callbacks;
  226. # to prevent starvation of other tasks we must limit the number
  227. # of connections we accept at a time. Ideally we would accept
  228. # up to the number of connections that were waiting when we
  229. # entered this method, but this information is not available
  230. # (and rearranging this method to call accept() as many times
  231. # as possible before running any callbacks would have adverse
  232. # effects on load balancing in multiprocess configurations).
  233. # Instead, we use the (default) listen backlog as a rough
  234. # heuristic for the number of connections we can reasonably
  235. # accept at once.
  236. for i in range(_DEFAULT_BACKLOG):
  237. if removed[0]:
  238. # The socket was probably closed
  239. return
  240. try:
  241. connection, address = sock.accept()
  242. except BlockingIOError:
  243. # EWOULDBLOCK indicates we have accepted every
  244. # connection that is available.
  245. return
  246. except ConnectionAbortedError:
  247. # ECONNABORTED indicates that there was a connection
  248. # but it was closed while still in the accept queue.
  249. # (observed on FreeBSD).
  250. continue
  251. callback(connection, address)
  252. def remove_handler() -> None:
  253. io_loop.remove_handler(sock)
  254. removed[0] = True
  255. io_loop.add_handler(sock, accept_handler, IOLoop.READ)
  256. return remove_handler
  257. def is_valid_ip(ip: str) -> bool:
  258. """Returns ``True`` if the given string is a well-formed IP address.
  259. Supports IPv4 and IPv6.
  260. """
  261. if not ip or "\x00" in ip:
  262. # getaddrinfo resolves empty strings to localhost, and truncates
  263. # on zero bytes.
  264. return False
  265. try:
  266. res = socket.getaddrinfo(
  267. ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST
  268. )
  269. return bool(res)
  270. except socket.gaierror as e:
  271. if e.args[0] == socket.EAI_NONAME:
  272. return False
  273. raise
  274. except UnicodeError:
  275. # `socket.getaddrinfo` will raise a UnicodeError from the
  276. # `idna` decoder if the input is longer than 63 characters,
  277. # even for socket.AI_NUMERICHOST. See
  278. # https://bugs.python.org/issue32958 for discussion
  279. return False
  280. return True
  281. class Resolver(Configurable):
  282. """Configurable asynchronous DNS resolver interface.
  283. By default, a blocking implementation is used (which simply calls
  284. `socket.getaddrinfo`). An alternative implementation can be
  285. chosen with the `Resolver.configure <.Configurable.configure>`
  286. class method::
  287. Resolver.configure('tornado.netutil.ThreadedResolver')
  288. The implementations of this interface included with Tornado are
  289. * `tornado.netutil.DefaultLoopResolver`
  290. * `tornado.netutil.DefaultExecutorResolver` (deprecated)
  291. * `tornado.netutil.BlockingResolver` (deprecated)
  292. * `tornado.netutil.ThreadedResolver` (deprecated)
  293. * `tornado.netutil.OverrideResolver`
  294. * `tornado.platform.caresresolver.CaresResolver` (deprecated)
  295. .. versionchanged:: 5.0
  296. The default implementation has changed from `BlockingResolver` to
  297. `DefaultExecutorResolver`.
  298. .. versionchanged:: 6.2
  299. The default implementation has changed from `DefaultExecutorResolver` to
  300. `DefaultLoopResolver`.
  301. """
  302. @classmethod
  303. def configurable_base(cls) -> Type["Resolver"]:
  304. return Resolver
  305. @classmethod
  306. def configurable_default(cls) -> Type["Resolver"]:
  307. return DefaultLoopResolver
  308. def resolve(
  309. self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
  310. ) -> Awaitable[List[Tuple[int, Any]]]:
  311. """Resolves an address.
  312. The ``host`` argument is a string which may be a hostname or a
  313. literal IP address.
  314. Returns a `.Future` whose result is a list of (family,
  315. address) pairs, where address is a tuple suitable to pass to
  316. `socket.connect <socket.socket.connect>` (i.e. a ``(host,
  317. port)`` pair for IPv4; additional fields may be present for
  318. IPv6). If a ``callback`` is passed, it will be run with the
  319. result as an argument when it is complete.
  320. :raises IOError: if the address cannot be resolved.
  321. .. versionchanged:: 4.4
  322. Standardized all implementations to raise `IOError`.
  323. .. versionchanged:: 6.0 The ``callback`` argument was removed.
  324. Use the returned awaitable object instead.
  325. """
  326. raise NotImplementedError()
  327. def close(self) -> None:
  328. """Closes the `Resolver`, freeing any resources used.
  329. .. versionadded:: 3.1
  330. """
  331. pass
  332. def _resolve_addr(
  333. host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
  334. ) -> List[Tuple[int, Any]]:
  335. # On Solaris, getaddrinfo fails if the given port is not found
  336. # in /etc/services and no socket type is given, so we must pass
  337. # one here. The socket type used here doesn't seem to actually
  338. # matter (we discard the one we get back in the results),
  339. # so the addresses we return should still be usable with SOCK_DGRAM.
  340. addrinfo = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM)
  341. results = []
  342. for fam, socktype, proto, canonname, address in addrinfo:
  343. results.append((fam, address))
  344. return results # type: ignore
  345. class DefaultExecutorResolver(Resolver):
  346. """Resolver implementation using `.IOLoop.run_in_executor`.
  347. .. versionadded:: 5.0
  348. .. deprecated:: 6.2
  349. Use `DefaultLoopResolver` instead.
  350. """
  351. async def resolve(
  352. self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
  353. ) -> List[Tuple[int, Any]]:
  354. result = await IOLoop.current().run_in_executor(
  355. None, _resolve_addr, host, port, family
  356. )
  357. return result
  358. class DefaultLoopResolver(Resolver):
  359. """Resolver implementation using `asyncio.loop.getaddrinfo`."""
  360. async def resolve(
  361. self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
  362. ) -> List[Tuple[int, Any]]:
  363. # On Solaris, getaddrinfo fails if the given port is not found
  364. # in /etc/services and no socket type is given, so we must pass
  365. # one here. The socket type used here doesn't seem to actually
  366. # matter (we discard the one we get back in the results),
  367. # so the addresses we return should still be usable with SOCK_DGRAM.
  368. return [
  369. (fam, address)
  370. for fam, _, _, _, address in await asyncio.get_running_loop().getaddrinfo(
  371. host, port, family=family, type=socket.SOCK_STREAM
  372. )
  373. ]
  374. class ExecutorResolver(Resolver):
  375. """Resolver implementation using a `concurrent.futures.Executor`.
  376. Use this instead of `ThreadedResolver` when you require additional
  377. control over the executor being used.
  378. The executor will be shut down when the resolver is closed unless
  379. ``close_resolver=False``; use this if you want to reuse the same
  380. executor elsewhere.
  381. .. versionchanged:: 5.0
  382. The ``io_loop`` argument (deprecated since version 4.1) has been removed.
  383. .. deprecated:: 5.0
  384. The default `Resolver` now uses `asyncio.loop.getaddrinfo`;
  385. use that instead of this class.
  386. """
  387. def initialize(
  388. self,
  389. executor: Optional[concurrent.futures.Executor] = None,
  390. close_executor: bool = True,
  391. ) -> None:
  392. if executor is not None:
  393. self.executor = executor
  394. self.close_executor = close_executor
  395. else:
  396. self.executor = dummy_executor
  397. self.close_executor = False
  398. def close(self) -> None:
  399. if self.close_executor:
  400. self.executor.shutdown()
  401. self.executor = None # type: ignore
  402. @run_on_executor
  403. def resolve(
  404. self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
  405. ) -> List[Tuple[int, Any]]:
  406. return _resolve_addr(host, port, family)
  407. class BlockingResolver(ExecutorResolver):
  408. """Default `Resolver` implementation, using `socket.getaddrinfo`.
  409. The `.IOLoop` will be blocked during the resolution, although the
  410. callback will not be run until the next `.IOLoop` iteration.
  411. .. deprecated:: 5.0
  412. The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead
  413. of this class.
  414. """
  415. def initialize(self) -> None: # type: ignore
  416. super().initialize()
  417. class ThreadedResolver(ExecutorResolver):
  418. """Multithreaded non-blocking `Resolver` implementation.
  419. The thread pool size can be configured with::
  420. Resolver.configure('tornado.netutil.ThreadedResolver',
  421. num_threads=10)
  422. .. versionchanged:: 3.1
  423. All ``ThreadedResolvers`` share a single thread pool, whose
  424. size is set by the first one to be created.
  425. .. deprecated:: 5.0
  426. The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead
  427. of this class.
  428. """
  429. _threadpool = None # type: ignore
  430. _threadpool_pid = None # type: int
  431. def initialize(self, num_threads: int = 10) -> None: # type: ignore
  432. threadpool = ThreadedResolver._create_threadpool(num_threads)
  433. super().initialize(executor=threadpool, close_executor=False)
  434. @classmethod
  435. def _create_threadpool(
  436. cls, num_threads: int
  437. ) -> concurrent.futures.ThreadPoolExecutor:
  438. pid = os.getpid()
  439. if cls._threadpool_pid != pid:
  440. # Threads cannot survive after a fork, so if our pid isn't what it
  441. # was when we created the pool then delete it.
  442. cls._threadpool = None
  443. if cls._threadpool is None:
  444. cls._threadpool = concurrent.futures.ThreadPoolExecutor(num_threads)
  445. cls._threadpool_pid = pid
  446. return cls._threadpool
  447. class OverrideResolver(Resolver):
  448. """Wraps a resolver with a mapping of overrides.
  449. This can be used to make local DNS changes (e.g. for testing)
  450. without modifying system-wide settings.
  451. The mapping can be in three formats::
  452. {
  453. # Hostname to host or ip
  454. "example.com": "127.0.1.1",
  455. # Host+port to host+port
  456. ("login.example.com", 443): ("localhost", 1443),
  457. # Host+port+address family to host+port
  458. ("login.example.com", 443, socket.AF_INET6): ("::1", 1443),
  459. }
  460. .. versionchanged:: 5.0
  461. Added support for host-port-family triplets.
  462. """
  463. def initialize(self, resolver: Resolver, mapping: dict) -> None:
  464. self.resolver = resolver
  465. self.mapping = mapping
  466. def close(self) -> None:
  467. self.resolver.close()
  468. def resolve(
  469. self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
  470. ) -> Awaitable[List[Tuple[int, Any]]]:
  471. if (host, port, family) in self.mapping:
  472. host, port = self.mapping[(host, port, family)]
  473. elif (host, port) in self.mapping:
  474. host, port = self.mapping[(host, port)]
  475. elif host in self.mapping:
  476. host = self.mapping[host]
  477. return self.resolver.resolve(host, port, family)
  478. # These are the keyword arguments to ssl.wrap_socket that must be translated
  479. # to their SSLContext equivalents (the other arguments are still passed
  480. # to SSLContext.wrap_socket).
  481. _SSL_CONTEXT_KEYWORDS = frozenset(
  482. ["ssl_version", "certfile", "keyfile", "cert_reqs", "ca_certs", "ciphers"]
  483. )
  484. def ssl_options_to_context(
  485. ssl_options: Union[Dict[str, Any], ssl.SSLContext],
  486. server_side: Optional[bool] = None,
  487. ) -> ssl.SSLContext:
  488. """Try to convert an ``ssl_options`` dictionary to an
  489. `~ssl.SSLContext` object.
  490. The ``ssl_options`` argument may be either an `ssl.SSLContext` object or a dictionary containing
  491. keywords to be passed to ``ssl.SSLContext.wrap_socket``. This function converts the dict form
  492. to its `~ssl.SSLContext` equivalent, and may be used when a component which accepts both forms
  493. needs to upgrade to the `~ssl.SSLContext` version to use features like SNI or ALPN.
  494. .. versionchanged:: 6.2
  495. Added server_side argument. Omitting this argument will result in a DeprecationWarning on
  496. Python 3.10.
  497. """
  498. if isinstance(ssl_options, ssl.SSLContext):
  499. return ssl_options
  500. assert isinstance(ssl_options, dict)
  501. assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options
  502. # TODO: Now that we have the server_side argument, can we switch to
  503. # create_default_context or would that change behavior?
  504. default_version = ssl.PROTOCOL_TLS
  505. if server_side:
  506. default_version = ssl.PROTOCOL_TLS_SERVER
  507. elif server_side is not None:
  508. default_version = ssl.PROTOCOL_TLS_CLIENT
  509. context = ssl.SSLContext(ssl_options.get("ssl_version", default_version))
  510. if "certfile" in ssl_options:
  511. context.load_cert_chain(
  512. ssl_options["certfile"], ssl_options.get("keyfile", None)
  513. )
  514. if "cert_reqs" in ssl_options:
  515. if ssl_options["cert_reqs"] == ssl.CERT_NONE:
  516. # This may have been set automatically by PROTOCOL_TLS_CLIENT but is
  517. # incompatible with CERT_NONE so we must manually clear it.
  518. context.check_hostname = False
  519. context.verify_mode = ssl_options["cert_reqs"]
  520. if "ca_certs" in ssl_options:
  521. context.load_verify_locations(ssl_options["ca_certs"])
  522. if "ciphers" in ssl_options:
  523. context.set_ciphers(ssl_options["ciphers"])
  524. if hasattr(ssl, "OP_NO_COMPRESSION"):
  525. # Disable TLS compression to avoid CRIME and related attacks.
  526. # This constant depends on openssl version 1.0.
  527. # TODO: Do we need to do this ourselves or can we trust
  528. # the defaults?
  529. context.options |= ssl.OP_NO_COMPRESSION
  530. return context
  531. def ssl_wrap_socket(
  532. socket: socket.socket,
  533. ssl_options: Union[Dict[str, Any], ssl.SSLContext],
  534. server_hostname: Optional[str] = None,
  535. server_side: Optional[bool] = None,
  536. **kwargs: Any,
  537. ) -> ssl.SSLSocket:
  538. """Returns an ``ssl.SSLSocket`` wrapping the given socket.
  539. ``ssl_options`` may be either an `ssl.SSLContext` object or a
  540. dictionary (as accepted by `ssl_options_to_context`). Additional
  541. keyword arguments are passed to `ssl.SSLContext.wrap_socket`.
  542. .. versionchanged:: 6.2
  543. Added server_side argument. Omitting this argument will
  544. result in a DeprecationWarning on Python 3.10.
  545. """
  546. context = ssl_options_to_context(ssl_options, server_side=server_side)
  547. if server_side is None:
  548. server_side = False
  549. assert ssl.HAS_SNI
  550. # TODO: add a unittest for hostname validation (python added server-side SNI support in 3.4)
  551. # In the meantime it can be manually tested with
  552. # python3 -m tornado.httpclient https://sni.velox.ch
  553. return context.wrap_socket(
  554. socket, server_hostname=server_hostname, server_side=server_side, **kwargs
  555. )