Debian Codegraph @

lib_pypy/_cffi_ssl/_stdssl/error.py

raw symbols SCIP
1 import sys
2 import os
3 import socket
4 import traceback
5 from _pypy_openssl import ffi
6 from _pypy_openssl import lib
7
8 from _cffi_ssl._stdssl.utility import _string_from_asn1, _str_to_ffi_buffer, _str_from_buf
9 from _cffi_ssl._stdssl.errorcodes import _error_codes, _lib_codes
10 from __pypy__ import write_unraisable
11
12 SSL_ERROR_NONE = 0
13 SSL_ERROR_SSL = 1
14 SSL_ERROR_WANT_READ = 2
15 SSL_ERROR_WANT_WRITE = 3
16 SSL_ERROR_WANT_X509_LOOKUP = 4
17 SSL_ERROR_SYSCALL = 5
18 SSL_ERROR_ZERO_RETURN = 6
19 SSL_ERROR_WANT_CONNECT = 7
20 # start of non ssl.h errorcodes
21 SSL_ERROR_EOF = 8 # special case of SSL_ERROR_SYSCALL
22 SSL_ERROR_NO_SOCKET = 9 # socket has been GC'd
23 SSL_ERROR_INVALID_ERROR_CODE = 10
24
25 class SSLError(OSError):
26 """ An error occurred in the SSL implementation. """
27 def __str__(self):
28 if self.strerror and isinstance(self.strerror, str):
29 return self.strerror
30 return str(self.args)
31
32 SSLError.__module__ = "ssl"
33 # these are expected on socket as well
34 socket.sslerror = SSLError
35 for v in [ 'SSL_ERROR_ZERO_RETURN', 'SSL_ERROR_WANT_READ',
36 'SSL_ERROR_WANT_WRITE', 'SSL_ERROR_WANT_X509_LOOKUP', 'SSL_ERROR_SYSCALL',
37 'SSL_ERROR_SSL', 'SSL_ERROR_WANT_CONNECT', 'SSL_ERROR_EOF',
38 'SSL_ERROR_INVALID_ERROR_CODE' ]:
39 setattr(socket, v, locals()[v])
40
41 class SSLCertVerificationError(SSLError, ValueError):
42 """A certificate could not be verified."""
43
44 class SSLZeroReturnError(SSLError):
45 """ SSL/TLS session closed cleanly. """
46
47 class SSLWantReadError(SSLError):
48 """ Non-blocking SSL socket needs to read more data
49 before the requested operation can be completed.
50 """
51
52 class SSLWantWriteError(SSLError):
53 """Non-blocking SSL socket needs to write more data
54 before the requested operation can be completed.
55 """
56
57 class SSLSyscallError(SSLError):
58 """ System error when attempting SSL operation. """
59
60 class SSLEOFError(SSLError):
61 """ SSL/TLS connection terminated abruptly. """
62
63 def ssl_error(errstr, errcode=0):
64 if errstr is None:
65 errcode = lib.ERR_peek_last_error()
66 try:
67 return fill_sslerror(None, SSLError, errcode, errstr, errcode)
68 finally:
69 lib.ERR_clear_error()
70
71 ERR_CODES_TO_NAMES = {}
72 ERR_NAMES_TO_CODES = {}
73 LIB_CODES_TO_NAMES = {}
74
75 for mnemo, library, reason in _error_codes:
76 key = (library, reason)
77 assert mnemo is not None and key is not None
78 ERR_CODES_TO_NAMES[key] = mnemo
79 ERR_NAMES_TO_CODES[mnemo] = key
80
81
82 for mnemo, number in _lib_codes:
83 LIB_CODES_TO_NAMES[number] = mnemo
84
85
86 # the PySSL_SetError equivalent
87 def pyssl_error(obj, ret):
88 errstr = ""
89 errval = 0
90 errtype = SSLError
91 e = lib.ERR_peek_last_error()
92
93 if obj.ssl != ffi.NULL:
94 err = obj.err
95
96 if err.ssl == SSL_ERROR_ZERO_RETURN:
97 errtype = SSLZeroReturnError
98 errstr = "TLS/SSL connection has been closed (EOF)"
99 errval = SSL_ERROR_ZERO_RETURN
100 elif err.ssl == SSL_ERROR_WANT_READ:
101 errtype = SSLWantReadError
102 errstr = "The operation did not complete (read)"
103 errval = SSL_ERROR_WANT_READ
104 elif err.ssl == SSL_ERROR_WANT_WRITE:
105 errtype = SSLWantWriteError
106 errstr = "The operation did not complete (write)"
107 errval = SSL_ERROR_WANT_WRITE
108 elif err.ssl == SSL_ERROR_WANT_X509_LOOKUP:
109 errstr = "The operation did not complete (X509 lookup)"
110 errval = SSL_ERROR_WANT_X509_LOOKUP
111 elif err.ssl == SSL_ERROR_WANT_CONNECT:
112 errstr = "The operation did not complete (connect)"
113 errval = SSL_ERROR_WANT_CONNECT
114 elif err.ssl == SSL_ERROR_SYSCALL:
115 if e == 0:
116 if ret == 0 or obj.socket is None:
117 errtype = SSLEOFError
118 errstr = "EOF occurred in violation of protocol"
119 errval = SSL_ERROR_EOF
120 elif ret == -1 and obj.socket is not None:
121 # the underlying BIO reported an I/0 error
122 lib.ERR_clear_error()
123 # s = obj.get_socket_or_None()
124 if sys.platform == 'win32':
125 if err.ws:
126 return fill_sslerror(obj, OSError, err.ws,
127 os.strerror(err.ws), e)
128 if err.c:
129 ffi.errno = err.c
130 return fill_sslerror(obj, OSError, err.c, os.strerror(err.c), e)
131 else:
132 errtype = SSLSyscallError
133 errstr = "Some I/O error occurred"
134 errval = SSL_ERROR_SYSCALL
135 else:
136 if lib.ERR_GET_LIB(e) == lib.ERR_LIB_SSL:
137 err_lib = lib.ERR_GET_LIB(e)
138 err_reason = lib.ERR_GET_REASON(e)
139 reason_str = ERR_CODES_TO_NAMES.get((err_lib, err_reason), None)
140 if reason_str == 'CERTIFICATE_VERIFY_FAILED':
141 errtype = SSLCertVerificationError
142 if lib.ERR_GET_LIB(e) == lib.ERR_LIB_SYS:
143 # A system error is being reported; reason is set to errno
144 errno = lib.ERR_GET_REASON(e)
145 raise OSError(errno, os.strerror(errno))
146 errstr = _str_from_buf(lib.ERR_lib_error_string(e))
147 errval = SSL_ERROR_SYSCALL
148 elif err.ssl == SSL_ERROR_SSL:
149 errval = SSL_ERROR_SSL
150 if e == 0:
151 errstr = "A failure in the SSL library occurred"
152 else:
153 errstr = _str_from_buf(lib.ERR_lib_error_string(e))
154 err_lib = lib.ERR_GET_LIB(e)
155 err_reason = lib.ERR_GET_REASON(e)
156 reason_str = ERR_CODES_TO_NAMES.get((err_lib, err_reason), None)
157 if (err_lib == lib.ERR_LIB_SSL and
158 reason_str == 'CERTIFICATE_VERIFY_FAILED'):
159 errtype = SSLCertVerificationError
160 if lib.Cryptography_HAS_UNEXPECTED_EOF_WHILE_READING:
161 # OpenSSL 3.0 changed transport EOF from SSL_ERROR_SYSCALL with
162 # zero return value to SSL_ERROR_SSL with a special error code.
163 if (lib.ERR_GET_LIB(e) == lib.ERR_LIB_SSL and
164 err_reason == lib.SSL_R_UNEXPECTED_EOF_WHILE_READING):
165 errval = SSL_ERROR_EOF
166 errtype = SSLEOFError
167 errstr = "EOF occurred in violation of protocol"
168 if lib.ERR_GET_LIB(e) == lib.ERR_LIB_SYS:
169 # A system error is being reported; reason is set to errno
170 errno = lib.ERR_GET_REASON(e)
171 raise OSError(errno, os.strerror(errno))
172 else:
173 errstr = "Invalid error code"
174 errval = SSL_ERROR_INVALID_ERROR_CODE
175 return fill_sslerror(obj, errtype, errval, errstr, e)
176
177
178 def fill_sslerror(obj, errtype, ssl_errno, errstr, errcode):
179 reason_str = None
180 lib_str = None
181 if errcode != 0:
182 err_lib = lib.ERR_GET_LIB(errcode)
183 err_reason = lib.ERR_GET_REASON(errcode)
184 reason_str = ERR_CODES_TO_NAMES.get((err_lib, err_reason), None)
185 lib_str = LIB_CODES_TO_NAMES.get(err_lib, None)
186 # Set last part of msg to a lower-case version of reason_str
187 errstr = _str_from_buf(lib.ERR_reason_error_string(errcode))
188 msg = errstr
189 if not errstr:
190 msg = "unknown error"
191 # verify code for cert validation error
192 verify_str = None
193 if (obj and errtype is SSLCertVerificationError):
194 verify_code = lib.SSL_get_verify_result(obj.ssl)
195 if lib.Cryptography_HAS_102_VERIFICATION_ERROR_CODES:
196 if verify_code == lib.X509_V_ERR_HOSTNAME_MISMATCH:
197 verify_str = ("Hostname mismatch, certificate is not "
198 f"valid for '{obj.server_hostname}'.")
199 elif verify_code == lib.X509_V_ERR_IP_ADDRESS_MISMATCH :
200 verify_str = ("IP address mismatch, certificate is not "
201 f"valid for '{obj.server_hostname}'.")
202 if not verify_str:
203 verify_str = ffi.string(lib.X509_verify_cert_error_string(verify_code)).decode()
204 if verify_str and reason_str and lib_str:
205 msg = f'[{lib_str}: {reason_str}] {errstr}: {verify_str}'
206 elif reason_str and lib_str:
207 msg = f"[{lib_str}: {reason_str}] {errstr}"
208 elif lib_str:
209 msg = f"[{lib_str}] {errstr}"
210
211 err_value = errtype(ssl_errno, msg)
212 err_value.reason = reason_str if reason_str else None
213 err_value.library = lib_str if lib_str else None
214 if (obj and errtype is SSLCertVerificationError):
215 err_value.verify_code = verify_code
216 err_value.verify_message = verify_str
217 return err_value
218
219 def pyerr_write_unraisable(exc, obj):
220 write_unraisable('in ssl', exc, obj)
221
222 SSL_AD_NAMES = [
223 "ACCESS_DENIED",
224 "BAD_CERTIFICATE",
225 "BAD_CERTIFICATE_HASH_VALUE",
226 "BAD_CERTIFICATE_STATUS_RESPONSE",
227 "BAD_RECORD_MAC",
228 "CERTIFICATE_EXPIRED",
229 "CERTIFICATE_REVOKED",
230 "CERTIFICATE_UNKNOWN",
231 "CERTIFICATE_UNOBTAINABLE",
232 "CLOSE_NOTIFY",
233 "DECODE_ERROR",
234 "DECOMPRESSION_FAILURE",
235 "DECRYPT_ERROR",
236 "HANDSHAKE_FAILURE",
237 "ILLEGAL_PARAMETER",
238 "INSUFFICIENT_SECURITY",
239 "INTERNAL_ERROR",
240 "NO_RENEGOTIATION",
241 "PROTOCOL_VERSION",
242 "RECORD_OVERFLOW",
243 "UNEXPECTED_MESSAGE",
244 "UNKNOWN_CA",
245 "UNKNOWN_PSK_IDENTITY",
246 "UNRECOGNIZED_NAME",
247 "UNSUPPORTED_CERTIFICATE",
248 "UNSUPPORTED_EXTENSION",
249 "USER_CANCELLED",
250 ]