1 # Copyright (c) Meta Platforms, Inc. and affiliates.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 from cython
.operator cimport dereference
as deref
16 from libcpp
.memory cimport make_shared
21 init
() # folly::ssl::init()
24 class SSLVersion
(Enum
):
25 TLSv1_2
= <int> (cTLSv1_2
)
28 class SSLVerifyOption
(Enum
):
29 VERIFY
= <int> (cVERIFY
)
30 VERIFY_REQ_CLIENT_CERT
= <int> (cVERIFY_REQ_CLIENT_CERT
)
31 NO_VERIFY
= <int> (cNO_VERIFY
)
34 cdef class SSLContext
:
35 def __cinit__
(self, version
=SSLVersion
.TLSv1_2
):
36 cdef cSSLVersion cversion
37 if version
is SSLVersion
.TLSv1_2
:
40 raise TypeError(f
"{version} is not an {SSLVersion}.")
41 self._cpp_obj
= move
(make_shared
[cSSLContext
](cversion
))
42 self.set_verify_option
(SSLVerifyOption
.VERIFY_REQ_CLIENT_CERT
)
44 def set_verify_option
(self, option
):
45 cdef cSSLVerifyPeerEnum coption
46 if option
is SSLVerifyOption
.VERIFY_REQ_CLIENT_CERT
:
47 coption
= cVERIFY_REQ_CLIENT_CERT
48 elif option
is SSLVerifyOption
.VERIFY
:
50 elif option
is SSLVerifyOption
.NO_VERIFY
:
53 raise TypeError(f
"{option} is not an {SSLVerifyOption}.")
54 deref
(self._cpp_obj
).setVerificationOption
(coption
)
57 def needs_peer_verify
(self):
58 return deref
(self._cpp_obj
).needsPeerVerification
()
60 def load_cert_chain
(self, *, certfile
not None
, keyfile
not None
):
61 cdef bytes cert
= os
.fsencode
(certfile
)
62 cdef bytes key
= os
.fsencode
(keyfile
)
64 deref
(self._cpp_obj
).loadCertKeyPairFromFiles
(cert
, key
)
66 def load_verify_locations
(self, *, cafile
not None
):
67 cdef bytes ca
= os
.fsencode
(cafile
)
68 deref
(self._cpp_obj
).loadTrustedCertificates
(ca
)
70 def authenticate
(self, *, bint peer_cert
, bint peer_name
):
71 deref
(self._cpp_obj
).authenticate
(peer_cert
, peer_name
)