webull-openapi-python-sdk 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (295) hide show
  1. samples/__init__.py +1 -0
  2. samples/data/__init__.py +1 -0
  3. samples/data/data_client.py +57 -0
  4. samples/data/data_streaming_client.py +86 -0
  5. samples/data/data_streaming_client_async.py +101 -0
  6. samples/trade/__init__.py +0 -0
  7. samples/trade/trade_client.py +163 -0
  8. samples/trade/trade_client_v2.py +181 -0
  9. samples/trade/trade_event_client.py +47 -0
  10. webull/__init__.py +1 -0
  11. webull/core/__init__.py +12 -0
  12. webull/core/auth/__init__.py +0 -0
  13. webull/core/auth/algorithm/__init__.py +0 -0
  14. webull/core/auth/algorithm/sha_hmac1.py +65 -0
  15. webull/core/auth/algorithm/sha_hmac256.py +75 -0
  16. webull/core/auth/composer/__init__.py +0 -0
  17. webull/core/auth/composer/default_signature_composer.py +125 -0
  18. webull/core/auth/credentials.py +46 -0
  19. webull/core/auth/signers/__init__.py +0 -0
  20. webull/core/auth/signers/app_key_signer.py +72 -0
  21. webull/core/auth/signers/signer.py +48 -0
  22. webull/core/auth/signers/signer_factory.py +58 -0
  23. webull/core/cache/__init__.py +225 -0
  24. webull/core/client.py +410 -0
  25. webull/core/common/__init__.py +0 -0
  26. webull/core/common/api_type.py +19 -0
  27. webull/core/common/easy_enum.py +35 -0
  28. webull/core/common/region.py +7 -0
  29. webull/core/compat.py +85 -0
  30. webull/core/context/__init__.py +0 -0
  31. webull/core/context/request_context_holder.py +33 -0
  32. webull/core/data/endpoints.json +22 -0
  33. webull/core/data/retry_config.json +15 -0
  34. webull/core/endpoint/__init__.py +8 -0
  35. webull/core/endpoint/chained_endpoint_resolver.py +57 -0
  36. webull/core/endpoint/default_endpoint_resolver.py +60 -0
  37. webull/core/endpoint/local_config_regional_endpoint_resolver.py +77 -0
  38. webull/core/endpoint/resolver_endpoint_request.py +46 -0
  39. webull/core/endpoint/user_customized_endpoint_resolver.py +55 -0
  40. webull/core/exception/__init__.py +0 -0
  41. webull/core/exception/error_code.py +23 -0
  42. webull/core/exception/error_msg.py +21 -0
  43. webull/core/exception/exceptions.py +53 -0
  44. webull/core/headers.py +57 -0
  45. webull/core/http/__init__.py +0 -0
  46. webull/core/http/initializer/__init__.py +0 -0
  47. webull/core/http/initializer/client_initializer.py +79 -0
  48. webull/core/http/initializer/token/__init__.py +0 -0
  49. webull/core/http/initializer/token/bean/__init__.py +0 -0
  50. webull/core/http/initializer/token/bean/access_token.py +40 -0
  51. webull/core/http/initializer/token/bean/check_token_request.py +44 -0
  52. webull/core/http/initializer/token/bean/create_token_request.py +45 -0
  53. webull/core/http/initializer/token/bean/refresh_token_request.py +44 -0
  54. webull/core/http/initializer/token/token_manager.py +208 -0
  55. webull/core/http/initializer/token/token_operation.py +72 -0
  56. webull/core/http/method_type.py +43 -0
  57. webull/core/http/protocol_type.py +43 -0
  58. webull/core/http/request.py +121 -0
  59. webull/core/http/response.py +166 -0
  60. webull/core/request.py +278 -0
  61. webull/core/retry/__init__.py +0 -0
  62. webull/core/retry/backoff_strategy.py +102 -0
  63. webull/core/retry/retry_condition.py +214 -0
  64. webull/core/retry/retry_policy.py +63 -0
  65. webull/core/retry/retry_policy_context.py +51 -0
  66. webull/core/utils/__init__.py +0 -0
  67. webull/core/utils/common.py +62 -0
  68. webull/core/utils/data.py +25 -0
  69. webull/core/utils/desensitize.py +33 -0
  70. webull/core/utils/validation.py +49 -0
  71. webull/core/vendored/__init__.py +0 -0
  72. webull/core/vendored/requests/__init__.py +94 -0
  73. webull/core/vendored/requests/__version__.py +28 -0
  74. webull/core/vendored/requests/_internal_utils.py +56 -0
  75. webull/core/vendored/requests/adapters.py +539 -0
  76. webull/core/vendored/requests/api.py +166 -0
  77. webull/core/vendored/requests/auth.py +307 -0
  78. webull/core/vendored/requests/certs.py +34 -0
  79. webull/core/vendored/requests/compat.py +85 -0
  80. webull/core/vendored/requests/cookies.py +555 -0
  81. webull/core/vendored/requests/exceptions.py +136 -0
  82. webull/core/vendored/requests/help.py +134 -0
  83. webull/core/vendored/requests/hooks.py +48 -0
  84. webull/core/vendored/requests/models.py +960 -0
  85. webull/core/vendored/requests/packages/__init__.py +17 -0
  86. webull/core/vendored/requests/packages/certifi/__init__.py +17 -0
  87. webull/core/vendored/requests/packages/certifi/__main__.py +16 -0
  88. webull/core/vendored/requests/packages/certifi/cacert.pem +4433 -0
  89. webull/core/vendored/requests/packages/certifi/core.py +51 -0
  90. webull/core/vendored/requests/packages/chardet/__init__.py +53 -0
  91. webull/core/vendored/requests/packages/chardet/big5freq.py +400 -0
  92. webull/core/vendored/requests/packages/chardet/big5prober.py +61 -0
  93. webull/core/vendored/requests/packages/chardet/chardistribution.py +247 -0
  94. webull/core/vendored/requests/packages/chardet/charsetgroupprober.py +120 -0
  95. webull/core/vendored/requests/packages/chardet/charsetprober.py +159 -0
  96. webull/core/vendored/requests/packages/chardet/cli/__init__.py +1 -0
  97. webull/core/vendored/requests/packages/chardet/cli/chardetect.py +99 -0
  98. webull/core/vendored/requests/packages/chardet/codingstatemachine.py +102 -0
  99. webull/core/vendored/requests/packages/chardet/compat.py +48 -0
  100. webull/core/vendored/requests/packages/chardet/cp949prober.py +63 -0
  101. webull/core/vendored/requests/packages/chardet/enums.py +90 -0
  102. webull/core/vendored/requests/packages/chardet/escprober.py +115 -0
  103. webull/core/vendored/requests/packages/chardet/escsm.py +260 -0
  104. webull/core/vendored/requests/packages/chardet/eucjpprober.py +106 -0
  105. webull/core/vendored/requests/packages/chardet/euckrfreq.py +209 -0
  106. webull/core/vendored/requests/packages/chardet/euckrprober.py +61 -0
  107. webull/core/vendored/requests/packages/chardet/euctwfreq.py +401 -0
  108. webull/core/vendored/requests/packages/chardet/euctwprober.py +60 -0
  109. webull/core/vendored/requests/packages/chardet/gb2312freq.py +297 -0
  110. webull/core/vendored/requests/packages/chardet/gb2312prober.py +60 -0
  111. webull/core/vendored/requests/packages/chardet/hebrewprober.py +306 -0
  112. webull/core/vendored/requests/packages/chardet/jisfreq.py +339 -0
  113. webull/core/vendored/requests/packages/chardet/jpcntx.py +247 -0
  114. webull/core/vendored/requests/packages/chardet/langbulgarianmodel.py +242 -0
  115. webull/core/vendored/requests/packages/chardet/langcyrillicmodel.py +347 -0
  116. webull/core/vendored/requests/packages/chardet/langgreekmodel.py +239 -0
  117. webull/core/vendored/requests/packages/chardet/langhebrewmodel.py +214 -0
  118. webull/core/vendored/requests/packages/chardet/langhungarianmodel.py +239 -0
  119. webull/core/vendored/requests/packages/chardet/langthaimodel.py +213 -0
  120. webull/core/vendored/requests/packages/chardet/langturkishmodel.py +207 -0
  121. webull/core/vendored/requests/packages/chardet/latin1prober.py +159 -0
  122. webull/core/vendored/requests/packages/chardet/mbcharsetprober.py +105 -0
  123. webull/core/vendored/requests/packages/chardet/mbcsgroupprober.py +68 -0
  124. webull/core/vendored/requests/packages/chardet/mbcssm.py +586 -0
  125. webull/core/vendored/requests/packages/chardet/sbcharsetprober.py +146 -0
  126. webull/core/vendored/requests/packages/chardet/sbcsgroupprober.py +87 -0
  127. webull/core/vendored/requests/packages/chardet/sjisprober.py +106 -0
  128. webull/core/vendored/requests/packages/chardet/universaldetector.py +300 -0
  129. webull/core/vendored/requests/packages/chardet/utf8prober.py +96 -0
  130. webull/core/vendored/requests/packages/chardet/version.py +23 -0
  131. webull/core/vendored/requests/packages/urllib3/__init__.py +114 -0
  132. webull/core/vendored/requests/packages/urllib3/_collections.py +346 -0
  133. webull/core/vendored/requests/packages/urllib3/connection.py +405 -0
  134. webull/core/vendored/requests/packages/urllib3/connectionpool.py +910 -0
  135. webull/core/vendored/requests/packages/urllib3/contrib/__init__.py +0 -0
  136. webull/core/vendored/requests/packages/urllib3/contrib/_appengine_environ.py +44 -0
  137. webull/core/vendored/requests/packages/urllib3/contrib/_securetransport/__init__.py +0 -0
  138. webull/core/vendored/requests/packages/urllib3/contrib/_securetransport/bindings.py +607 -0
  139. webull/core/vendored/requests/packages/urllib3/contrib/_securetransport/low_level.py +360 -0
  140. webull/core/vendored/requests/packages/urllib3/contrib/appengine.py +303 -0
  141. webull/core/vendored/requests/packages/urllib3/contrib/ntlmpool.py +125 -0
  142. webull/core/vendored/requests/packages/urllib3/contrib/pyopenssl.py +484 -0
  143. webull/core/vendored/requests/packages/urllib3/contrib/securetransport.py +818 -0
  144. webull/core/vendored/requests/packages/urllib3/contrib/socks.py +206 -0
  145. webull/core/vendored/requests/packages/urllib3/exceptions.py +260 -0
  146. webull/core/vendored/requests/packages/urllib3/fields.py +192 -0
  147. webull/core/vendored/requests/packages/urllib3/filepost.py +112 -0
  148. webull/core/vendored/requests/packages/urllib3/packages/__init__.py +19 -0
  149. webull/core/vendored/requests/packages/urllib3/packages/backports/__init__.py +0 -0
  150. webull/core/vendored/requests/packages/urllib3/packages/backports/makefile.py +67 -0
  151. webull/core/vendored/requests/packages/urllib3/packages/ordered_dict.py +273 -0
  152. webull/core/vendored/requests/packages/urllib3/packages/six.py +882 -0
  153. webull/core/vendored/requests/packages/urllib3/packages/socks.py +887 -0
  154. webull/core/vendored/requests/packages/urllib3/packages/ssl_match_hostname/__init__.py +19 -0
  155. webull/core/vendored/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py +170 -0
  156. webull/core/vendored/requests/packages/urllib3/poolmanager.py +467 -0
  157. webull/core/vendored/requests/packages/urllib3/request.py +164 -0
  158. webull/core/vendored/requests/packages/urllib3/response.py +721 -0
  159. webull/core/vendored/requests/packages/urllib3/util/__init__.py +68 -0
  160. webull/core/vendored/requests/packages/urllib3/util/connection.py +148 -0
  161. webull/core/vendored/requests/packages/urllib3/util/queue.py +35 -0
  162. webull/core/vendored/requests/packages/urllib3/util/request.py +132 -0
  163. webull/core/vendored/requests/packages/urllib3/util/response.py +101 -0
  164. webull/core/vendored/requests/packages/urllib3/util/retry.py +426 -0
  165. webull/core/vendored/requests/packages/urllib3/util/selectors.py +601 -0
  166. webull/core/vendored/requests/packages/urllib3/util/ssl_.py +396 -0
  167. webull/core/vendored/requests/packages/urllib3/util/timeout.py +256 -0
  168. webull/core/vendored/requests/packages/urllib3/util/url.py +252 -0
  169. webull/core/vendored/requests/packages/urllib3/util/wait.py +164 -0
  170. webull/core/vendored/requests/packages.py +28 -0
  171. webull/core/vendored/requests/sessions.py +750 -0
  172. webull/core/vendored/requests/status_codes.py +105 -0
  173. webull/core/vendored/requests/structures.py +119 -0
  174. webull/core/vendored/requests/utils.py +916 -0
  175. webull/core/vendored/six.py +905 -0
  176. webull/data/__init__.py +3 -0
  177. webull/data/common/__init__.py +0 -0
  178. webull/data/common/category.py +26 -0
  179. webull/data/common/connect_ack.py +29 -0
  180. webull/data/common/direction.py +25 -0
  181. webull/data/common/exchange_code.py +33 -0
  182. webull/data/common/exercise_style.py +22 -0
  183. webull/data/common/expiration_cycle.py +26 -0
  184. webull/data/common/instrument_status.py +23 -0
  185. webull/data/common/option_type.py +20 -0
  186. webull/data/common/subscribe_type.py +22 -0
  187. webull/data/common/timespan.py +29 -0
  188. webull/data/data_client.py +35 -0
  189. webull/data/data_streaming_client.py +89 -0
  190. webull/data/internal/__init__.py +0 -0
  191. webull/data/internal/default_retry_policy.py +84 -0
  192. webull/data/internal/exceptions.py +60 -0
  193. webull/data/internal/quotes_client.py +314 -0
  194. webull/data/internal/quotes_decoder.py +40 -0
  195. webull/data/internal/quotes_payload_decoder.py +35 -0
  196. webull/data/internal/quotes_topic.py +36 -0
  197. webull/data/quotes/__init__.py +0 -0
  198. webull/data/quotes/instrument.py +33 -0
  199. webull/data/quotes/market_data.py +187 -0
  200. webull/data/quotes/market_streaming_data.py +66 -0
  201. webull/data/quotes/subscribe/__init__.py +0 -0
  202. webull/data/quotes/subscribe/ask_bid_result.py +49 -0
  203. webull/data/quotes/subscribe/basic_result.py +45 -0
  204. webull/data/quotes/subscribe/broker_result.py +33 -0
  205. webull/data/quotes/subscribe/message_pb2.py +37 -0
  206. webull/data/quotes/subscribe/order_result.py +30 -0
  207. webull/data/quotes/subscribe/payload_type.py +19 -0
  208. webull/data/quotes/subscribe/quote_decoder.py +28 -0
  209. webull/data/quotes/subscribe/quote_result.py +47 -0
  210. webull/data/quotes/subscribe/snapshot_decoder.py +30 -0
  211. webull/data/quotes/subscribe/snapshot_result.py +69 -0
  212. webull/data/quotes/subscribe/tick_decoder.py +29 -0
  213. webull/data/quotes/subscribe/tick_result.py +47 -0
  214. webull/data/request/__init__.py +0 -0
  215. webull/data/request/get_batch_historical_bars_request.py +43 -0
  216. webull/data/request/get_corp_action_request.py +47 -0
  217. webull/data/request/get_eod_bars_request.py +32 -0
  218. webull/data/request/get_historical_bars_request.py +43 -0
  219. webull/data/request/get_instruments_request.py +30 -0
  220. webull/data/request/get_quotes_request.py +35 -0
  221. webull/data/request/get_snapshot_request.py +38 -0
  222. webull/data/request/get_tick_request.py +37 -0
  223. webull/data/request/subscribe_request.py +43 -0
  224. webull/data/request/unsubscribe_request.py +42 -0
  225. webull/trade/__init__.py +2 -0
  226. webull/trade/common/__init__.py +0 -0
  227. webull/trade/common/account_type.py +22 -0
  228. webull/trade/common/category.py +29 -0
  229. webull/trade/common/combo_ticker_type.py +23 -0
  230. webull/trade/common/combo_type.py +31 -0
  231. webull/trade/common/currency.py +24 -0
  232. webull/trade/common/forbid_reason.py +27 -0
  233. webull/trade/common/instrument_type.py +27 -0
  234. webull/trade/common/markets.py +27 -0
  235. webull/trade/common/order_entrust_type.py +21 -0
  236. webull/trade/common/order_side.py +23 -0
  237. webull/trade/common/order_status.py +25 -0
  238. webull/trade/common/order_tif.py +24 -0
  239. webull/trade/common/order_type.py +30 -0
  240. webull/trade/common/trade_policy.py +22 -0
  241. webull/trade/common/trading_date_type.py +24 -0
  242. webull/trade/common/trailing_type.py +23 -0
  243. webull/trade/events/__init__.py +0 -0
  244. webull/trade/events/default_retry_policy.py +64 -0
  245. webull/trade/events/events_pb2.py +43 -0
  246. webull/trade/events/events_pb2_grpc.py +66 -0
  247. webull/trade/events/signature_composer.py +61 -0
  248. webull/trade/events/types.py +21 -0
  249. webull/trade/request/__init__.py +0 -0
  250. webull/trade/request/cancel_order_request.py +28 -0
  251. webull/trade/request/get_account_balance_request.py +28 -0
  252. webull/trade/request/get_account_positions_request.py +30 -0
  253. webull/trade/request/get_account_profile_request.py +26 -0
  254. webull/trade/request/get_app_subscriptions.py +28 -0
  255. webull/trade/request/get_open_orders_request.py +30 -0
  256. webull/trade/request/get_order_detail_request.py +27 -0
  257. webull/trade/request/get_today_orders_request.py +31 -0
  258. webull/trade/request/get_trade_calendar_request.py +30 -0
  259. webull/trade/request/get_trade_instrument_detail_request.py +24 -0
  260. webull/trade/request/get_trade_security_detail_request.py +42 -0
  261. webull/trade/request/get_tradeable_instruments_request.py +27 -0
  262. webull/trade/request/palce_order_request.py +91 -0
  263. webull/trade/request/place_order_request_v2.py +58 -0
  264. webull/trade/request/replace_order_request.py +73 -0
  265. webull/trade/request/replace_order_request_v2.py +38 -0
  266. webull/trade/request/v2/__init__.py +0 -0
  267. webull/trade/request/v2/cancel_option_request.py +28 -0
  268. webull/trade/request/v2/cancel_order_request.py +28 -0
  269. webull/trade/request/v2/get_account_balance_request.py +28 -0
  270. webull/trade/request/v2/get_account_list.py +23 -0
  271. webull/trade/request/v2/get_account_positions_request.py +24 -0
  272. webull/trade/request/v2/get_order_detail_request.py +26 -0
  273. webull/trade/request/v2/get_order_history_request.py +35 -0
  274. webull/trade/request/v2/palce_order_request.py +87 -0
  275. webull/trade/request/v2/place_option_request.py +64 -0
  276. webull/trade/request/v2/preview_option_request.py +28 -0
  277. webull/trade/request/v2/preview_order_request.py +59 -0
  278. webull/trade/request/v2/replace_option_request.py +28 -0
  279. webull/trade/request/v2/replace_order_request.py +57 -0
  280. webull/trade/trade/__init__.py +0 -0
  281. webull/trade/trade/account_info.py +83 -0
  282. webull/trade/trade/order_operation.py +246 -0
  283. webull/trade/trade/trade_calendar.py +37 -0
  284. webull/trade/trade/trade_instrument.py +72 -0
  285. webull/trade/trade/v2/__init__.py +0 -0
  286. webull/trade/trade/v2/account_info_v2.py +55 -0
  287. webull/trade/trade/v2/order_operation_v2.py +206 -0
  288. webull/trade/trade_client.py +43 -0
  289. webull/trade/trade_events_client.py +233 -0
  290. webull_openapi_python_sdk-1.0.0.dist-info/METADATA +28 -0
  291. webull_openapi_python_sdk-1.0.0.dist-info/RECORD +295 -0
  292. webull_openapi_python_sdk-1.0.0.dist-info/WHEEL +5 -0
  293. webull_openapi_python_sdk-1.0.0.dist-info/licenses/LICENSE +202 -0
  294. webull_openapi_python_sdk-1.0.0.dist-info/licenses/NOTICE +56 -0
  295. webull_openapi_python_sdk-1.0.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,818 @@
1
+ # Copyright 2022 Webull
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ SecureTranport support for urllib3 via ctypes.
17
+
18
+ This makes platform-native TLS available to urllib3 users on macOS without the
19
+ use of a compiler. This is an important feature because the Python Package
20
+ Index is moving to become a TLSv1.2-or-higher server, and the default OpenSSL
21
+ that ships with macOS is not capable of doing TLSv1.2. The only way to resolve
22
+ this is to give macOS users an alternative solution to the problem, and that
23
+ solution is to use SecureTransport.
24
+
25
+ We use ctypes here because this solution must not require a compiler. That's
26
+ because pip is not allowed to require a compiler either.
27
+
28
+ This is not intended to be a seriously long-term solution to this problem.
29
+ The hope is that PEP 543 will eventually solve this issue for us, at which
30
+ point we can retire this contrib module. But in the short term, we need to
31
+ solve the impending tire fire that is Python on Mac without this kind of
32
+ contrib module. So...here we are.
33
+
34
+ To use this module, simply import and inject it::
35
+
36
+ import urllib3.contrib.securetransport
37
+ urllib3.contrib.securetransport.inject_into_urllib3()
38
+
39
+ Happy TLSing!
40
+ """
41
+ from __future__ import absolute_import
42
+
43
+ import contextlib
44
+ import ctypes
45
+ import errno
46
+ import os.path
47
+ import shutil
48
+ import socket
49
+ import ssl
50
+ import threading
51
+ import weakref
52
+
53
+ from ._securetransport.bindings import (
54
+ Security, SecurityConst, CoreFoundation
55
+ )
56
+ from ._securetransport.low_level import (
57
+ _assert_no_error, _cert_array_from_pem, _temporary_keychain,
58
+ _load_client_cert_chain
59
+ )
60
+ from .. import util
61
+
62
+ try: # Platform-specific: Python 2
63
+ from socket import _fileobject
64
+ except ImportError: # Platform-specific: Python 3
65
+ _fileobject = None
66
+ from ..packages.backports.makefile import backport_makefile
67
+
68
+ __all__ = ['inject_into_urllib3', 'extract_from_urllib3']
69
+
70
+ # SNI always works
71
+ HAS_SNI = True
72
+
73
+ orig_util_HAS_SNI = util.HAS_SNI
74
+ orig_util_SSLContext = util.ssl_.SSLContext
75
+
76
+ # This dictionary is used by the read callback to obtain a handle to the
77
+ # calling wrapped socket. This is a pretty silly approach, but for now it'll
78
+ # do. I feel like I should be able to smuggle a handle to the wrapped socket
79
+ # directly in the SSLConnectionRef, but for now this approach will work I
80
+ # guess.
81
+ #
82
+ # We need to lock around this structure for inserts, but we don't do it for
83
+ # reads/writes in the callbacks. The reasoning here goes as follows:
84
+ #
85
+ # 1. It is not possible to call into the callbacks before the dictionary is
86
+ # populated, so once in the callback the id must be in the dictionary.
87
+ # 2. The callbacks don't mutate the dictionary, they only read from it, and
88
+ # so cannot conflict with any of the insertions.
89
+ #
90
+ # This is good: if we had to lock in the callbacks we'd drastically slow down
91
+ # the performance of this code.
92
+ _connection_refs = weakref.WeakValueDictionary()
93
+ _connection_ref_lock = threading.Lock()
94
+
95
+ # Limit writes to 16kB. This is OpenSSL's limit, but we'll cargo-cult it over
96
+ # for no better reason than we need *a* limit, and this one is right there.
97
+ SSL_WRITE_BLOCKSIZE = 16384
98
+
99
+ # This is our equivalent of util.ssl_.DEFAULT_CIPHERS, but expanded out to
100
+ # individual cipher suites. We need to do this because this is how
101
+ # SecureTransport wants them.
102
+ CIPHER_SUITES = [
103
+ SecurityConst.TLS_AES_256_GCM_SHA384,
104
+ SecurityConst.TLS_CHACHA20_POLY1305_SHA256,
105
+ SecurityConst.TLS_AES_128_GCM_SHA256,
106
+ SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
107
+ SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
108
+ SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
109
+ SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
110
+ SecurityConst.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384,
111
+ SecurityConst.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
112
+ SecurityConst.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,
113
+ SecurityConst.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
114
+ SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
115
+ SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
116
+ SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
117
+ SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
118
+ SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
119
+ SecurityConst.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256,
120
+ SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
121
+ SecurityConst.TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
122
+ SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
123
+ SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
124
+ SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
125
+ SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
126
+ SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
127
+ SecurityConst.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,
128
+ SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
129
+ SecurityConst.TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
130
+ SecurityConst.TLS_RSA_WITH_AES_256_GCM_SHA384,
131
+ SecurityConst.TLS_RSA_WITH_AES_128_GCM_SHA256,
132
+ SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA256,
133
+ SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA256,
134
+ SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA,
135
+ SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA,
136
+ ]
137
+
138
+ # Basically this is simple: for PROTOCOL_SSLv23 we turn it into a low of
139
+ # TLSv1 and a high of TLSv1.2. For everything else, we pin to that version.
140
+ _protocol_to_min_max = {
141
+ ssl.PROTOCOL_SSLv23: (SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol12),
142
+ }
143
+
144
+ if hasattr(ssl, "PROTOCOL_SSLv2"):
145
+ _protocol_to_min_max[ssl.PROTOCOL_SSLv2] = (
146
+ SecurityConst.kSSLProtocol2, SecurityConst.kSSLProtocol2
147
+ )
148
+ if hasattr(ssl, "PROTOCOL_SSLv3"):
149
+ _protocol_to_min_max[ssl.PROTOCOL_SSLv3] = (
150
+ SecurityConst.kSSLProtocol3, SecurityConst.kSSLProtocol3
151
+ )
152
+ if hasattr(ssl, "PROTOCOL_TLSv1"):
153
+ _protocol_to_min_max[ssl.PROTOCOL_TLSv1] = (
154
+ SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol1
155
+ )
156
+ if hasattr(ssl, "PROTOCOL_TLSv1_1"):
157
+ _protocol_to_min_max[ssl.PROTOCOL_TLSv1_1] = (
158
+ SecurityConst.kTLSProtocol11, SecurityConst.kTLSProtocol11
159
+ )
160
+ if hasattr(ssl, "PROTOCOL_TLSv1_2"):
161
+ _protocol_to_min_max[ssl.PROTOCOL_TLSv1_2] = (
162
+ SecurityConst.kTLSProtocol12, SecurityConst.kTLSProtocol12
163
+ )
164
+ if hasattr(ssl, "PROTOCOL_TLS"):
165
+ _protocol_to_min_max[ssl.PROTOCOL_TLS] = _protocol_to_min_max[ssl.PROTOCOL_SSLv23]
166
+
167
+
168
+
169
+ def inject_into_urllib3():
170
+ """
171
+ Monkey-patch urllib3 with SecureTransport-backed SSL-support.
172
+ """
173
+ util.ssl_.SSLContext = SecureTransportContext
174
+ util.HAS_SNI = HAS_SNI
175
+ util.ssl_.HAS_SNI = HAS_SNI
176
+ util.IS_SECURETRANSPORT = True
177
+ util.ssl_.IS_SECURETRANSPORT = True
178
+
179
+
180
+ def extract_from_urllib3():
181
+ """
182
+ Undo monkey-patching by :func:`inject_into_urllib3`.
183
+ """
184
+ util.ssl_.SSLContext = orig_util_SSLContext
185
+ util.HAS_SNI = orig_util_HAS_SNI
186
+ util.ssl_.HAS_SNI = orig_util_HAS_SNI
187
+ util.IS_SECURETRANSPORT = False
188
+ util.ssl_.IS_SECURETRANSPORT = False
189
+
190
+
191
+ def _read_callback(connection_id, data_buffer, data_length_pointer):
192
+ """
193
+ SecureTransport read callback. This is called by ST to request that data
194
+ be returned from the socket.
195
+ """
196
+ wrapped_socket = None
197
+ try:
198
+ wrapped_socket = _connection_refs.get(connection_id)
199
+ if wrapped_socket is None:
200
+ return SecurityConst.errSSLInternal
201
+ base_socket = wrapped_socket.socket
202
+
203
+ requested_length = data_length_pointer[0]
204
+
205
+ timeout = wrapped_socket.gettimeout()
206
+ error = None
207
+ read_count = 0
208
+
209
+ try:
210
+ while read_count < requested_length:
211
+ if timeout is None or timeout >= 0:
212
+ if not util.wait_for_read(base_socket, timeout):
213
+ raise socket.error(errno.EAGAIN, 'timed out')
214
+
215
+ remaining = requested_length - read_count
216
+ buffer = (ctypes.c_char * remaining).from_address(
217
+ data_buffer + read_count
218
+ )
219
+ chunk_size = base_socket.recv_into(buffer, remaining)
220
+ read_count += chunk_size
221
+ if not chunk_size:
222
+ if not read_count:
223
+ return SecurityConst.errSSLClosedGraceful
224
+ break
225
+ except (socket.error) as e:
226
+ error = e.errno
227
+
228
+ if error is not None and error != errno.EAGAIN:
229
+ data_length_pointer[0] = read_count
230
+ if error == errno.ECONNRESET or error == errno.EPIPE:
231
+ return SecurityConst.errSSLClosedAbort
232
+ raise
233
+
234
+ data_length_pointer[0] = read_count
235
+
236
+ if read_count != requested_length:
237
+ return SecurityConst.errSSLWouldBlock
238
+
239
+ return 0
240
+ except Exception as e:
241
+ if wrapped_socket is not None:
242
+ wrapped_socket._exception = e
243
+ return SecurityConst.errSSLInternal
244
+
245
+
246
+ def _write_callback(connection_id, data_buffer, data_length_pointer):
247
+ """
248
+ SecureTransport write callback. This is called by ST to request that data
249
+ actually be sent on the network.
250
+ """
251
+ wrapped_socket = None
252
+ try:
253
+ wrapped_socket = _connection_refs.get(connection_id)
254
+ if wrapped_socket is None:
255
+ return SecurityConst.errSSLInternal
256
+ base_socket = wrapped_socket.socket
257
+
258
+ bytes_to_write = data_length_pointer[0]
259
+ data = ctypes.string_at(data_buffer, bytes_to_write)
260
+
261
+ timeout = wrapped_socket.gettimeout()
262
+ error = None
263
+ sent = 0
264
+
265
+ try:
266
+ while sent < bytes_to_write:
267
+ if timeout is None or timeout >= 0:
268
+ if not util.wait_for_write(base_socket, timeout):
269
+ raise socket.error(errno.EAGAIN, 'timed out')
270
+ chunk_sent = base_socket.send(data)
271
+ sent += chunk_sent
272
+
273
+ # This has some needless copying here, but I'm not sure there's
274
+ # much value in optimising this data path.
275
+ data = data[chunk_sent:]
276
+ except (socket.error) as e:
277
+ error = e.errno
278
+
279
+ if error is not None and error != errno.EAGAIN:
280
+ data_length_pointer[0] = sent
281
+ if error == errno.ECONNRESET or error == errno.EPIPE:
282
+ return SecurityConst.errSSLClosedAbort
283
+ raise
284
+
285
+ data_length_pointer[0] = sent
286
+
287
+ if sent != bytes_to_write:
288
+ return SecurityConst.errSSLWouldBlock
289
+
290
+ return 0
291
+ except Exception as e:
292
+ if wrapped_socket is not None:
293
+ wrapped_socket._exception = e
294
+ return SecurityConst.errSSLInternal
295
+
296
+
297
+ # We need to keep these two objects references alive: if they get GC'd while
298
+ # in use then SecureTransport could attempt to call a function that is in freed
299
+ # memory. That would be...uh...bad. Yeah, that's the word. Bad.
300
+ _read_callback_pointer = Security.SSLReadFunc(_read_callback)
301
+ _write_callback_pointer = Security.SSLWriteFunc(_write_callback)
302
+
303
+
304
+ class WrappedSocket(object):
305
+ """
306
+ API-compatibility wrapper for Python's OpenSSL wrapped socket object.
307
+
308
+ Note: _makefile_refs, _drop(), and _reuse() are needed for the garbage
309
+ collector of PyPy.
310
+ """
311
+ def __init__(self, socket):
312
+ self.socket = socket
313
+ self.context = None
314
+ self._makefile_refs = 0
315
+ self._closed = False
316
+ self._exception = None
317
+ self._keychain = None
318
+ self._keychain_dir = None
319
+ self._client_cert_chain = None
320
+
321
+ # We save off the previously-configured timeout and then set it to
322
+ # zero. This is done because we use select and friends to handle the
323
+ # timeouts, but if we leave the timeout set on the lower socket then
324
+ # Python will "kindly" call select on that socket again for us. Avoid
325
+ # that by forcing the timeout to zero.
326
+ self._timeout = self.socket.gettimeout()
327
+ self.socket.settimeout(0)
328
+
329
+ @contextlib.contextmanager
330
+ def _raise_on_error(self):
331
+ """
332
+ A context manager that can be used to wrap calls that do I/O from
333
+ SecureTransport. If any of the I/O callbacks hit an exception, this
334
+ context manager will correctly propagate the exception after the fact.
335
+ This avoids silently swallowing those exceptions.
336
+
337
+ It also correctly forces the socket closed.
338
+ """
339
+ self._exception = None
340
+
341
+ # We explicitly don't catch around this yield because in the unlikely
342
+ # event that an exception was hit in the block we don't want to swallow
343
+ # it.
344
+ yield
345
+ if self._exception is not None:
346
+ exception, self._exception = self._exception, None
347
+ self.close()
348
+ raise exception
349
+
350
+ def _set_ciphers(self):
351
+ """
352
+ Sets up the allowed ciphers. By default this matches the set in
353
+ util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done
354
+ custom and doesn't allow changing at this time, mostly because parsing
355
+ OpenSSL cipher strings is going to be a freaking nightmare.
356
+ """
357
+ ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES)
358
+ result = Security.SSLSetEnabledCiphers(
359
+ self.context, ciphers, len(CIPHER_SUITES)
360
+ )
361
+ _assert_no_error(result)
362
+
363
+ def _custom_validate(self, verify, trust_bundle):
364
+ """
365
+ Called when we have set custom validation. We do this in two cases:
366
+ first, when cert validation is entirely disabled; and second, when
367
+ using a custom trust DB.
368
+ """
369
+ # If we disabled cert validation, just say: cool.
370
+ if not verify:
371
+ return
372
+
373
+ # We want data in memory, so load it up.
374
+ if os.path.isfile(trust_bundle):
375
+ with open(trust_bundle, 'rb') as f:
376
+ trust_bundle = f.read()
377
+
378
+ cert_array = None
379
+ trust = Security.SecTrustRef()
380
+
381
+ try:
382
+ # Get a CFArray that contains the certs we want.
383
+ cert_array = _cert_array_from_pem(trust_bundle)
384
+
385
+ # Ok, now the hard part. We want to get the SecTrustRef that ST has
386
+ # created for this connection, shove our CAs into it, tell ST to
387
+ # ignore everything else it knows, and then ask if it can build a
388
+ # chain. This is a buuuunch of code.
389
+ result = Security.SSLCopyPeerTrust(
390
+ self.context, ctypes.byref(trust)
391
+ )
392
+ _assert_no_error(result)
393
+ if not trust:
394
+ raise ssl.SSLError("Failed to copy trust reference")
395
+
396
+ result = Security.SecTrustSetAnchorCertificates(trust, cert_array)
397
+ _assert_no_error(result)
398
+
399
+ result = Security.SecTrustSetAnchorCertificatesOnly(trust, True)
400
+ _assert_no_error(result)
401
+
402
+ trust_result = Security.SecTrustResultType()
403
+ result = Security.SecTrustEvaluate(
404
+ trust, ctypes.byref(trust_result)
405
+ )
406
+ _assert_no_error(result)
407
+ finally:
408
+ if trust:
409
+ CoreFoundation.CFRelease(trust)
410
+
411
+ if cert_array is not None:
412
+ CoreFoundation.CFRelease(cert_array)
413
+
414
+ # Ok, now we can look at what the result was.
415
+ successes = (
416
+ SecurityConst.kSecTrustResultUnspecified,
417
+ SecurityConst.kSecTrustResultProceed
418
+ )
419
+ if trust_result.value not in successes:
420
+ raise ssl.SSLError(
421
+ "certificate verify failed, error code: %d" %
422
+ trust_result.value
423
+ )
424
+
425
+ def handshake(self,
426
+ server_hostname,
427
+ verify,
428
+ trust_bundle,
429
+ min_version,
430
+ max_version,
431
+ client_cert,
432
+ client_key,
433
+ client_key_passphrase):
434
+ """
435
+ Actually performs the TLS handshake. This is run automatically by
436
+ wrapped socket, and shouldn't be needed in user code.
437
+ """
438
+ # First, we do the initial bits of connection setup. We need to create
439
+ # a context, set its I/O funcs, and set the connection reference.
440
+ self.context = Security.SSLCreateContext(
441
+ None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType
442
+ )
443
+ result = Security.SSLSetIOFuncs(
444
+ self.context, _read_callback_pointer, _write_callback_pointer
445
+ )
446
+ _assert_no_error(result)
447
+
448
+ # Here we need to compute the handle to use. We do this by taking the
449
+ # id of self modulo 2**31 - 1. If this is already in the dictionary, we
450
+ # just keep incrementing by one until we find a free space.
451
+ with _connection_ref_lock:
452
+ handle = id(self) % 2147483647
453
+ while handle in _connection_refs:
454
+ handle = (handle + 1) % 2147483647
455
+ _connection_refs[handle] = self
456
+
457
+ result = Security.SSLSetConnection(self.context, handle)
458
+ _assert_no_error(result)
459
+
460
+ # If we have a server hostname, we should set that too.
461
+ if server_hostname:
462
+ if not isinstance(server_hostname, bytes):
463
+ server_hostname = server_hostname.encode('utf-8')
464
+
465
+ result = Security.SSLSetPeerDomainName(
466
+ self.context, server_hostname, len(server_hostname)
467
+ )
468
+ _assert_no_error(result)
469
+
470
+ # Setup the ciphers.
471
+ self._set_ciphers()
472
+
473
+ # Set the minimum and maximum TLS versions.
474
+ result = Security.SSLSetProtocolVersionMin(self.context, min_version)
475
+ _assert_no_error(result)
476
+ result = Security.SSLSetProtocolVersionMax(self.context, max_version)
477
+ _assert_no_error(result)
478
+
479
+ # If there's a trust DB, we need to use it. We do that by telling
480
+ # SecureTransport to break on server auth. We also do that if we don't
481
+ # want to validate the certs at all: we just won't actually do any
482
+ # authing in that case.
483
+ if not verify or trust_bundle is not None:
484
+ result = Security.SSLSetSessionOption(
485
+ self.context,
486
+ SecurityConst.kSSLSessionOptionBreakOnServerAuth,
487
+ True
488
+ )
489
+ _assert_no_error(result)
490
+
491
+ # If there's a client cert, we need to use it.
492
+ if client_cert:
493
+ self._keychain, self._keychain_dir = _temporary_keychain()
494
+ self._client_cert_chain = _load_client_cert_chain(
495
+ self._keychain, client_cert, client_key
496
+ )
497
+ result = Security.SSLSetCertificate(
498
+ self.context, self._client_cert_chain
499
+ )
500
+ _assert_no_error(result)
501
+
502
+ while True:
503
+ with self._raise_on_error():
504
+ result = Security.SSLHandshake(self.context)
505
+
506
+ if result == SecurityConst.errSSLWouldBlock:
507
+ raise socket.timeout("handshake timed out")
508
+ elif result == SecurityConst.errSSLServerAuthCompleted:
509
+ self._custom_validate(verify, trust_bundle)
510
+ continue
511
+ else:
512
+ _assert_no_error(result)
513
+ break
514
+
515
+ def fileno(self):
516
+ return self.socket.fileno()
517
+
518
+ # Copy-pasted from Python 3.5 source code
519
+ def _decref_socketios(self):
520
+ if self._makefile_refs > 0:
521
+ self._makefile_refs -= 1
522
+ if self._closed:
523
+ self.close()
524
+
525
+ def recv(self, bufsiz):
526
+ buffer = ctypes.create_string_buffer(bufsiz)
527
+ bytes_read = self.recv_into(buffer, bufsiz)
528
+ data = buffer[:bytes_read]
529
+ return data
530
+
531
+ def recv_into(self, buffer, nbytes=None):
532
+ # Read short on EOF.
533
+ if self._closed:
534
+ return 0
535
+
536
+ if nbytes is None:
537
+ nbytes = len(buffer)
538
+
539
+ buffer = (ctypes.c_char * nbytes).from_buffer(buffer)
540
+ processed_bytes = ctypes.c_size_t(0)
541
+
542
+ with self._raise_on_error():
543
+ result = Security.SSLRead(
544
+ self.context, buffer, nbytes, ctypes.byref(processed_bytes)
545
+ )
546
+
547
+ # There are some result codes that we want to treat as "not always
548
+ # errors". Specifically, those are errSSLWouldBlock,
549
+ # errSSLClosedGraceful, and errSSLClosedNoNotify.
550
+ if (result == SecurityConst.errSSLWouldBlock):
551
+ # If we didn't process any bytes, then this was just a time out.
552
+ # However, we can get errSSLWouldBlock in situations when we *did*
553
+ # read some data, and in those cases we should just read "short"
554
+ # and return.
555
+ if processed_bytes.value == 0:
556
+ # Timed out, no data read.
557
+ raise socket.timeout("recv timed out")
558
+ elif result in (SecurityConst.errSSLClosedGraceful, SecurityConst.errSSLClosedNoNotify):
559
+ # The remote peer has closed this connection. We should do so as
560
+ # well. Note that we don't actually return here because in
561
+ # principle this could actually be fired along with return data.
562
+ # It's unlikely though.
563
+ self.close()
564
+ else:
565
+ _assert_no_error(result)
566
+
567
+ # Ok, we read and probably succeeded. We should return whatever data
568
+ # was actually read.
569
+ return processed_bytes.value
570
+
571
+ def settimeout(self, timeout):
572
+ self._timeout = timeout
573
+
574
+ def gettimeout(self):
575
+ return self._timeout
576
+
577
+ def send(self, data):
578
+ processed_bytes = ctypes.c_size_t(0)
579
+
580
+ with self._raise_on_error():
581
+ result = Security.SSLWrite(
582
+ self.context, data, len(data), ctypes.byref(processed_bytes)
583
+ )
584
+
585
+ if result == SecurityConst.errSSLWouldBlock and processed_bytes.value == 0:
586
+ # Timed out
587
+ raise socket.timeout("send timed out")
588
+ else:
589
+ _assert_no_error(result)
590
+
591
+ # We sent, and probably succeeded. Tell them how much we sent.
592
+ return processed_bytes.value
593
+
594
+ def sendall(self, data):
595
+ total_sent = 0
596
+ while total_sent < len(data):
597
+ sent = self.send(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE])
598
+ total_sent += sent
599
+
600
+ def shutdown(self):
601
+ with self._raise_on_error():
602
+ Security.SSLClose(self.context)
603
+
604
+ def close(self):
605
+ # TODO: should I do clean shutdown here? Do I have to?
606
+ if self._makefile_refs < 1:
607
+ self._closed = True
608
+ if self.context:
609
+ CoreFoundation.CFRelease(self.context)
610
+ self.context = None
611
+ if self._client_cert_chain:
612
+ CoreFoundation.CFRelease(self._client_cert_chain)
613
+ self._client_cert_chain = None
614
+ if self._keychain:
615
+ Security.SecKeychainDelete(self._keychain)
616
+ CoreFoundation.CFRelease(self._keychain)
617
+ shutil.rmtree(self._keychain_dir)
618
+ self._keychain = self._keychain_dir = None
619
+ return self.socket.close()
620
+ else:
621
+ self._makefile_refs -= 1
622
+
623
+ def getpeercert(self, binary_form=False):
624
+ # Urgh, annoying.
625
+ #
626
+ # Here's how we do this:
627
+ #
628
+ # 1. Call SSLCopyPeerTrust to get hold of the trust object for this
629
+ # connection.
630
+ # 2. Call SecTrustGetCertificateAtIndex for index 0 to get the leaf.
631
+ # 3. To get the CN, call SecCertificateCopyCommonName and process that
632
+ # string so that it's of the appropriate type.
633
+ # 4. To get the SAN, we need to do something a bit more complex:
634
+ # a. Call SecCertificateCopyValues to get the data, requesting
635
+ # kSecOIDSubjectAltName.
636
+ # b. Mess about with this dictionary to try to get the SANs out.
637
+ #
638
+ # This is gross. Really gross. It's going to be a few hundred LoC extra
639
+ # just to repeat something that SecureTransport can *already do*. So my
640
+ # operating assumption at this time is that what we want to do is
641
+ # instead to just flag to urllib3 that it shouldn't do its own hostname
642
+ # validation when using SecureTransport.
643
+ if not binary_form:
644
+ raise ValueError(
645
+ "SecureTransport only supports dumping binary certs"
646
+ )
647
+ trust = Security.SecTrustRef()
648
+ certdata = None
649
+ der_bytes = None
650
+
651
+ try:
652
+ # Grab the trust store.
653
+ result = Security.SSLCopyPeerTrust(
654
+ self.context, ctypes.byref(trust)
655
+ )
656
+ _assert_no_error(result)
657
+ if not trust:
658
+ # Probably we haven't done the handshake yet. No biggie.
659
+ return None
660
+
661
+ cert_count = Security.SecTrustGetCertificateCount(trust)
662
+ if not cert_count:
663
+ # Also a case that might happen if we haven't handshaked.
664
+ # Handshook? Handshaken?
665
+ return None
666
+
667
+ leaf = Security.SecTrustGetCertificateAtIndex(trust, 0)
668
+ assert leaf
669
+
670
+ # Ok, now we want the DER bytes.
671
+ certdata = Security.SecCertificateCopyData(leaf)
672
+ assert certdata
673
+
674
+ data_length = CoreFoundation.CFDataGetLength(certdata)
675
+ data_buffer = CoreFoundation.CFDataGetBytePtr(certdata)
676
+ der_bytes = ctypes.string_at(data_buffer, data_length)
677
+ finally:
678
+ if certdata:
679
+ CoreFoundation.CFRelease(certdata)
680
+ if trust:
681
+ CoreFoundation.CFRelease(trust)
682
+
683
+ return der_bytes
684
+
685
+ def _reuse(self):
686
+ self._makefile_refs += 1
687
+
688
+ def _drop(self):
689
+ if self._makefile_refs < 1:
690
+ self.close()
691
+ else:
692
+ self._makefile_refs -= 1
693
+
694
+
695
+ if _fileobject: # Platform-specific: Python 2
696
+ def makefile(self, mode, bufsize=-1):
697
+ self._makefile_refs += 1
698
+ return _fileobject(self, mode, bufsize, close=True)
699
+ else: # Platform-specific: Python 3
700
+ def makefile(self, mode="r", buffering=0, *args, **kwargs):
701
+ # We disable buffering with SecureTransport because it conflicts with
702
+ # the buffering that ST does internally (see issue #1153 for more).
703
+ return backport_makefile(self, mode, buffering, *args, **kwargs)
704
+
705
+ WrappedSocket.makefile = makefile
706
+
707
+
708
+ class SecureTransportContext(object):
709
+ """
710
+ I am a wrapper class for the SecureTransport library, to translate the
711
+ interface of the standard library ``SSLContext`` object to calls into
712
+ SecureTransport.
713
+ """
714
+ def __init__(self, protocol):
715
+ self._min_version, self._max_version = _protocol_to_min_max[protocol]
716
+ self._options = 0
717
+ self._verify = False
718
+ self._trust_bundle = None
719
+ self._client_cert = None
720
+ self._client_key = None
721
+ self._client_key_passphrase = None
722
+
723
+ @property
724
+ def check_hostname(self):
725
+ """
726
+ SecureTransport cannot have its hostname checking disabled. For more,
727
+ see the comment on getpeercert() in this file.
728
+ """
729
+ return True
730
+
731
+ @check_hostname.setter
732
+ def check_hostname(self, value):
733
+ """
734
+ SecureTransport cannot have its hostname checking disabled. For more,
735
+ see the comment on getpeercert() in this file.
736
+ """
737
+ pass
738
+
739
+ @property
740
+ def options(self):
741
+ # TODO: Well, crap.
742
+ #
743
+ # So this is the bit of the code that is the most likely to cause us
744
+ # trouble. Essentially we need to enumerate all of the SSL options that
745
+ # users might want to use and try to see if we can sensibly translate
746
+ # them, or whether we should just ignore them.
747
+ return self._options
748
+
749
+ @options.setter
750
+ def options(self, value):
751
+ # TODO: Update in line with above.
752
+ self._options = value
753
+
754
+ @property
755
+ def verify_mode(self):
756
+ return ssl.CERT_REQUIRED if self._verify else ssl.CERT_NONE
757
+
758
+ @verify_mode.setter
759
+ def verify_mode(self, value):
760
+ self._verify = True if value == ssl.CERT_REQUIRED else False
761
+
762
+ def set_default_verify_paths(self):
763
+ # So, this has to do something a bit weird. Specifically, what it does
764
+ # is nothing.
765
+ #
766
+ # This means that, if we had previously had load_verify_locations
767
+ # called, this does not undo that. We need to do that because it turns
768
+ # out that the rest of the urllib3 code will attempt to load the
769
+ # default verify paths if it hasn't been told about any paths, even if
770
+ # the context itself was sometime earlier. We resolve that by just
771
+ # ignoring it.
772
+ pass
773
+
774
+ def load_default_certs(self):
775
+ return self.set_default_verify_paths()
776
+
777
+ def set_ciphers(self, ciphers):
778
+ # For now, we just require the default cipher string.
779
+ if ciphers != util.ssl_.DEFAULT_CIPHERS:
780
+ raise ValueError(
781
+ "SecureTransport doesn't support custom cipher strings"
782
+ )
783
+
784
+ def load_verify_locations(self, cafile=None, capath=None, cadata=None):
785
+ # OK, we only really support cadata and cafile.
786
+ if capath is not None:
787
+ raise ValueError(
788
+ "SecureTransport does not support cert directories"
789
+ )
790
+
791
+ self._trust_bundle = cafile or cadata
792
+
793
+ def load_cert_chain(self, certfile, keyfile=None, password=None):
794
+ self._client_cert = certfile
795
+ self._client_key = keyfile
796
+ self._client_cert_passphrase = password
797
+
798
+ def wrap_socket(self, sock, server_side=False,
799
+ do_handshake_on_connect=True, suppress_ragged_eofs=True,
800
+ server_hostname=None):
801
+ # So, what do we do here? Firstly, we assert some properties. This is a
802
+ # stripped down shim, so there is some functionality we don't support.
803
+ # See PEP 543 for the real deal.
804
+ assert not server_side
805
+ assert do_handshake_on_connect
806
+ assert suppress_ragged_eofs
807
+
808
+ # Ok, we're good to go. Now we want to create the wrapped socket object
809
+ # and store it in the appropriate place.
810
+ wrapped_socket = WrappedSocket(sock)
811
+
812
+ # Now we can handshake
813
+ wrapped_socket.handshake(
814
+ server_hostname, self._verify, self._trust_bundle,
815
+ self._min_version, self._max_version, self._client_cert,
816
+ self._client_key, self._client_key_passphrase
817
+ )
818
+ return wrapped_socket