| 1 |
import warnings |
| 2 |
import base64 |
| 3 |
import textwrap |
| 4 |
from _pypy_openssl import ffi |
| 5 |
from _pypy_openssl import lib |
| 6 |
from _cffi_ssl._stdssl.utility import _string_from_asn1, _str_with_len, _bytes_with_len |
| 7 |
from _cffi_ssl._stdssl.error import ssl_error, pyssl_error |
| 8 |
|
| 9 |
X509_NAME_MAXLEN = 256 |
| 10 |
PY_SSL_ENCODING_PEM = lib.SSL_FILETYPE_PEM |
| 11 |
PY_SSL_ENCODING_PEM_AUX = PY_SSL_ENCODING_PEM + 0x100 |
| 12 |
PY_SSL_ENCODING_DER = lib.SSL_FILETYPE_ASN1 |
| 13 |
|
| 14 |
|
| 15 |
def _PySSL_BytesFromBio(bio): |
| 16 |
data = ffi.new("char **") |
| 17 |
size = lib.BIO_get_mem_data(bio, data) |
| 18 |
if not data[0] or size < 0: |
| 19 |
raise ValueError("Not a memory BIO") |
| 20 |
return _bytes_with_len(data[0], size) |
| 21 |
|
| 22 |
def _PySSL_UnicodeFromBio(bio): |
| 23 |
data = ffi.new("char **") |
| 24 |
size = lib.BIO_get_mem_data(bio, data) |
| 25 |
if not data[0] or size < 0: |
| 26 |
raise ValueError("Not a memory BIO") |
| 27 |
return _str_with_len(data[0], size) |
| 28 |
|
| 29 |
class Certificate: |
| 30 |
def __new__(self, *args, **kwargs): |
| 31 |
raise TypeError("cannot create '_ssl.Certificate' instances") |
| 32 |
|
| 33 |
def __del__(self): |
| 34 |
if self._cert: |
| 35 |
lib.X509_free(self._cert) |
| 36 |
self._cert = None |
| 37 |
|
| 38 |
def _finalize(self): |
| 39 |
if self._cert: |
| 40 |
lib.X509_free(self._cert) |
| 41 |
self._cert = None |
| 42 |
|
| 43 |
def __init__(self, cert, upref): |
| 44 |
self._cert = cert |
| 45 |
self._hash = -1 |
| 46 |
if upref == 1: |
| 47 |
lib.X509_up_ref(cert) |
| 48 |
|
| 49 |
def public_bytes(self, format=PY_SSL_ENCODING_PEM): |
| 50 |
bio = lib.BIO_new(lib.BIO_s_mem()) |
| 51 |
if format == PY_SSL_ENCODING_PEM: |
| 52 |
retcode = lib.PEM_write_bio_X509(bio, self._cert) |
| 53 |
elif format == PY_SSL_ENCODING_PEM_AUX: |
| 54 |
retcode = lib.PEM_write_bio_X509_AUX(bio, self._cert) |
| 55 |
elif format == PY_SSL_ENCODING_DER: |
| 56 |
retcode = lib.i2d_X509_bio(bio, self._cert) |
| 57 |
else: |
| 58 |
lib.BIO_free(bio) |
| 59 |
raise ValueError("Unsupported format") |
| 60 |
try: |
| 61 |
if retcode != 1: |
| 62 |
raise ssl_error(None) |
| 63 |
if format == PY_SSL_ENCODING_DER: |
| 64 |
return _PySSL_BytesFromBio(bio) |
| 65 |
else: |
| 66 |
return _PySSL_UnicodeFromBio(bio) |
| 67 |
finally: |
| 68 |
lib.BIO_free(bio) |
| 69 |
|
| 70 |
def get_info(self): |
| 71 |
return _decode_certificate(self._cert) |
| 72 |
|
| 73 |
def __repr__(self): |
| 74 |
|
| 75 |
osubject = _x509name_print( |
| 76 |
lib.X509_get_subject_name(self._cert), |
| 77 |
0, |
| 78 |
lib.XN_FLAG_RFC2253 |
| 79 |
) |
| 80 |
return "<Certificate '%s'>" % osubject |
| 81 |
|
| 82 |
def __hash__(self): |
| 83 |
if self._hash == -1: |
| 84 |
_hash = lib.X509_subject_name_hash(self._cert) |
| 85 |
if _hash == -1: |
| 86 |
self._hash = -2 |
| 87 |
else: |
| 88 |
self._hash = _hash |
| 89 |
return self._hash |
| 90 |
|
| 91 |
def __eq__(self, other): |
| 92 |
if not type(other) is Certificate: |
| 93 |
return NotImplemented |
| 94 |
cmp = lib.X509_cmp(self._cert, other._cert) |
| 95 |
return cmp == 0 |
| 96 |
|
| 97 |
def _x509name_print(name, indent, flags): |
| 98 |
bio = lib.BIO_new(lib.BIO_s_mem()) |
| 99 |
try: |
| 100 |
if lib.X509_NAME_print_ex(bio, name, indent, flags) <=0: |
| 101 |
raise ssl_error(None) |
| 102 |
return _PySSL_UnicodeFromBio(bio) |
| 103 |
finally: |
| 104 |
lib.BIO_free(bio) |
| 105 |
|
| 106 |
def newCertificate(cert, upref): |
| 107 |
self = object.__new__(Certificate) |
| 108 |
self.__init__(cert, upref) |
| 109 |
return self |
| 110 |
|
| 111 |
|
| 112 |
def _PySSL_CertificateFromX509Stack(stack, upref): |
| 113 |
len = lib.sk_X509_num(stack) |
| 114 |
result = [None] * len |
| 115 |
for i in range(len): |
| 116 |
cert = lib.sk_X509_value(stack, i) |
| 117 |
result[i] = newCertificate(cert, upref) |
| 118 |
return result |
| 119 |
|
| 120 |
def _create_tuple_for_attribute(name, value): |
| 121 |
buf = ffi.new("char[]", X509_NAME_MAXLEN) |
| 122 |
length = lib.OBJ_obj2txt(buf, X509_NAME_MAXLEN, name, 0) |
| 123 |
if length < 0: |
| 124 |
raise ssl_error(None) |
| 125 |
name = _str_with_len(buf, length) |
| 126 |
|
| 127 |
buf_ptr = ffi.new("unsigned char**") |
| 128 |
length = lib.ASN1_STRING_to_UTF8(buf_ptr, value) |
| 129 |
if length < 0: |
| 130 |
raise ssl_error(None) |
| 131 |
try: |
| 132 |
value = _str_with_len(buf_ptr[0], length) |
| 133 |
finally: |
| 134 |
lib.OPENSSL_free(buf_ptr[0]) |
| 135 |
return (name, value) |
| 136 |
|
| 137 |
def _get_aia_uri(certificate, nid): |
| 138 |
info = lib.X509_get_ext_d2i(certificate, lib.NID_info_access, ffi.NULL, ffi.NULL) |
| 139 |
if (info == ffi.NULL): |
| 140 |
return None; |
| 141 |
if lib.sk_ACCESS_DESCRIPTION_num(info) == 0: |
| 142 |
lib.AUTHORITY_INFO_ACCESS_free(info) |
| 143 |
return None |
| 144 |
|
| 145 |
lst = [] |
| 146 |
count = lib.sk_ACCESS_DESCRIPTION_num(info) |
| 147 |
for i in range(count): |
| 148 |
ad = lib.sk_ACCESS_DESCRIPTION_value(info, i) |
| 149 |
|
| 150 |
if lib.OBJ_obj2nid(ad.method) != nid or \ |
| 151 |
ad.location.type != lib.GEN_URI: |
| 152 |
continue |
| 153 |
uri = ad.location.d.uniformResourceIdentifier |
| 154 |
ostr = _str_with_len(uri.data, uri.length) |
| 155 |
lst.append(ostr) |
| 156 |
lib.AUTHORITY_INFO_ACCESS_free(info) |
| 157 |
|
| 158 |
|
| 159 |
if len(lst) == 0: return None |
| 160 |
return tuple(lst) |
| 161 |
|
| 162 |
def _get_peer_alt_names(certificate): |
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
peer_alt_names = [] |
| 169 |
|
| 170 |
if certificate == ffi.NULL: |
| 171 |
return None |
| 172 |
|
| 173 |
|
| 174 |
biobuf = lib.BIO_new(lib.BIO_s_mem()); |
| 175 |
try: |
| 176 |
i = -1 |
| 177 |
while True: |
| 178 |
i = lib.X509_get_ext_by_NID(certificate, lib.NID_subject_alt_name, i) |
| 179 |
if i < 0: |
| 180 |
break |
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
ext = lib.X509_get_ext(certificate, i); |
| 185 |
method = lib.X509V3_EXT_get(ext) |
| 186 |
if method is ffi.NULL: |
| 187 |
raise ssl_error("No method for internalizing subjectAltName!") |
| 188 |
|
| 189 |
ext_data = lib.X509_EXTENSION_get_data(ext) |
| 190 |
ext_data_len = ext_data.length |
| 191 |
ext_data_value = ffi.new("unsigned char**", ffi.NULL) |
| 192 |
ext_data_value[0] = ext_data.data |
| 193 |
|
| 194 |
if method.it != ffi.NULL: |
| 195 |
names = lib.ASN1_item_d2i(ffi.NULL, ext_data_value, ext_data_len, lib.ASN1_ITEM_ptr(method.it)) |
| 196 |
else: |
| 197 |
names = method.d2i(ffi.NULL, ext_data_value, ext_data_len) |
| 198 |
|
| 199 |
names = ffi.cast("GENERAL_NAMES*", names) |
| 200 |
count = lib.sk_GENERAL_NAME_num(names) |
| 201 |
for j in range(count): |
| 202 |
|
| 203 |
name = lib.sk_GENERAL_NAME_value(names, j); |
| 204 |
_type = name.type |
| 205 |
if _type == lib.GEN_DIRNAME: |
| 206 |
|
| 207 |
|
| 208 |
v = _create_tuple_for_X509_NAME(name.d.dirn) |
| 209 |
peer_alt_names.append(("DirName", v)) |
| 210 |
|
| 211 |
|
| 212 |
elif _type == lib.GEN_EMAIL: |
| 213 |
v = _string_from_asn1(name.d.rfc822Name) |
| 214 |
peer_alt_names.append(("email", v)) |
| 215 |
elif _type == lib.GEN_DNS: |
| 216 |
v = _string_from_asn1(name.d.dNSName) |
| 217 |
peer_alt_names.append(("DNS", v)) |
| 218 |
elif _type == lib.GEN_URI: |
| 219 |
v = _string_from_asn1(name.d.uniformResourceIdentifier) |
| 220 |
peer_alt_names.append(("URI", v)) |
| 221 |
elif _type == lib.GEN_RID: |
| 222 |
v = "Registered ID" |
| 223 |
buf = ffi.new("char[2048]") |
| 224 |
|
| 225 |
length = lib.OBJ_obj2txt(buf, 2047, name.d.rid, 0) |
| 226 |
if length < 0: |
| 227 |
|
| 228 |
raise NotImplementedError |
| 229 |
elif length >= 2048: |
| 230 |
v = "<INVALID>" |
| 231 |
else: |
| 232 |
v = _str_with_len(buf, length) |
| 233 |
peer_alt_names.append(("Registered ID", v)) |
| 234 |
else: |
| 235 |
|
| 236 |
if _type not in (lib.GEN_OTHERNAME, lib.GEN_X400, \ |
| 237 |
lib.GEN_EDIPARTY, lib.GEN_IPADD, lib.GEN_RID): |
| 238 |
warnings.warn("Unknown general type %d" % _type, RuntimeWarning) |
| 239 |
continue |
| 240 |
lib.BIO_reset(biobuf); |
| 241 |
lib.GENERAL_NAME_print(biobuf, name); |
| 242 |
v = _bio_get_str(biobuf) |
| 243 |
idx = v.find(":") |
| 244 |
if idx == -1: |
| 245 |
raise ValueError("Invalid value %s", v) |
| 246 |
peer_alt_names.append((v[:idx], v[idx+1:])) |
| 247 |
|
| 248 |
free_func_addr = ffi.addressof(lib, "GENERAL_NAME_free") |
| 249 |
lib.sk_GENERAL_NAME_pop_free(names, free_func_addr); |
| 250 |
finally: |
| 251 |
lib.BIO_free(biobuf) |
| 252 |
if peer_alt_names is not None: |
| 253 |
return tuple(peer_alt_names) |
| 254 |
return peer_alt_names |
| 255 |
|
| 256 |
def _create_tuple_for_X509_NAME(xname): |
| 257 |
dn = [] |
| 258 |
rdn = [] |
| 259 |
rdn_level = -1 |
| 260 |
entry_count = lib.X509_NAME_entry_count(xname); |
| 261 |
for index_counter in range(entry_count): |
| 262 |
entry = lib.X509_NAME_get_entry(xname, index_counter); |
| 263 |
|
| 264 |
|
| 265 |
_set = lib.Cryptography_X509_NAME_ENTRY_set(entry) |
| 266 |
if rdn_level >= 0: |
| 267 |
if rdn_level != _set: |
| 268 |
dn.append(tuple(rdn)) |
| 269 |
rdn = [] |
| 270 |
rdn_level = _set |
| 271 |
|
| 272 |
|
| 273 |
name = lib.X509_NAME_ENTRY_get_object(entry); |
| 274 |
value = lib.X509_NAME_ENTRY_get_data(entry); |
| 275 |
attr = _create_tuple_for_attribute(name, value); |
| 276 |
if attr == ffi.NULL: |
| 277 |
raise NotImplementedError |
| 278 |
rdn.append(attr) |
| 279 |
|
| 280 |
|
| 281 |
if rdn and len(rdn) > 0: |
| 282 |
dn.append(tuple(rdn)) |
| 283 |
|
| 284 |
return tuple(dn) |
| 285 |
|
| 286 |
def _bio_get_str(biobuf): |
| 287 |
bio_buf = ffi.new("char[]", 2048) |
| 288 |
length = lib.BIO_gets(biobuf, bio_buf, len(bio_buf)-1) |
| 289 |
if length < 0: |
| 290 |
if biobuf: lib.BIO_free(biobuf) |
| 291 |
raise ssl_error(None) |
| 292 |
return _str_with_len(bio_buf, length) |
| 293 |
|
| 294 |
def _decode_certificate(certificate): |
| 295 |
retval = {} |
| 296 |
if not certificate: |
| 297 |
raise ssl_error("Error decoding PEM-encoded file") |
| 298 |
|
| 299 |
peer = _create_tuple_for_X509_NAME(lib.X509_get_subject_name(certificate)); |
| 300 |
if not peer: |
| 301 |
return None |
| 302 |
retval["subject"] = peer |
| 303 |
|
| 304 |
issuer = _create_tuple_for_X509_NAME(lib.X509_get_issuer_name(certificate)); |
| 305 |
if not issuer: |
| 306 |
return None |
| 307 |
retval["issuer"] = issuer |
| 308 |
|
| 309 |
version = lib.X509_get_version(certificate) + 1 |
| 310 |
if version == 0: |
| 311 |
return None |
| 312 |
retval["version"] = version |
| 313 |
|
| 314 |
biobuf = lib.BIO_new(lib.BIO_s_mem()); |
| 315 |
try: |
| 316 |
lib.BIO_reset(biobuf); |
| 317 |
serialNumber = lib.X509_get_serialNumber(certificate); |
| 318 |
|
| 319 |
lib.i2a_ASN1_INTEGER(biobuf, serialNumber) |
| 320 |
buf = ffi.new("char[]", 2048) |
| 321 |
length = lib.BIO_gets(biobuf, buf, len(buf)-1) |
| 322 |
if length < 0: |
| 323 |
raise ssl_error(None) |
| 324 |
retval["serialNumber"] = _str_with_len(buf, length) |
| 325 |
|
| 326 |
lib.BIO_reset(biobuf); |
| 327 |
notBefore = lib.X509_get_notBefore(certificate); |
| 328 |
lib.ASN1_TIME_print(biobuf, notBefore); |
| 329 |
length = lib.BIO_gets(biobuf, buf, len(buf)-1); |
| 330 |
if length < 0: |
| 331 |
raise ssl_error(None) |
| 332 |
retval["notBefore"] = _str_with_len(buf, length) |
| 333 |
|
| 334 |
lib.BIO_reset(biobuf); |
| 335 |
notAfter = lib.X509_get_notAfter(certificate); |
| 336 |
lib.ASN1_TIME_print(biobuf, notAfter); |
| 337 |
length = lib.BIO_gets(biobuf, buf, len(buf)-1); |
| 338 |
if length < 0: |
| 339 |
raise ssl_error(None) |
| 340 |
retval["notAfter"] = _str_with_len(buf, length) |
| 341 |
|
| 342 |
|
| 343 |
peer_alt_names = _get_peer_alt_names(certificate); |
| 344 |
if peer_alt_names is None: |
| 345 |
return None |
| 346 |
if len(peer_alt_names) > 0: |
| 347 |
retval["subjectAltName"] = peer_alt_names |
| 348 |
|
| 349 |
|
| 350 |
obj = _get_aia_uri(certificate, lib.NID_ad_OCSP) |
| 351 |
if obj: |
| 352 |
retval["OCSP"] = obj |
| 353 |
|
| 354 |
obj = _get_aia_uri(certificate, lib.NID_ad_ca_issuers) |
| 355 |
if obj: |
| 356 |
retval["caIssuers"] = obj |
| 357 |
|
| 358 |
|
| 359 |
obj = _get_crl_dp(certificate) |
| 360 |
if obj: |
| 361 |
retval["crlDistributionPoints"] = obj |
| 362 |
finally: |
| 363 |
lib.BIO_free(biobuf) |
| 364 |
|
| 365 |
return retval |
| 366 |
|
| 367 |
|
| 368 |
def _get_crl_dp(certificate): |
| 369 |
if lib.OPENSSL_VERSION_NUMBER >= 0x10001000: |
| 370 |
lib.X509_check_ca(certificate) |
| 371 |
dps = lib.X509_get_ext_d2i(certificate, lib.NID_crl_distribution_points, ffi.NULL, ffi.NULL) |
| 372 |
if dps is ffi.NULL: |
| 373 |
return None |
| 374 |
|
| 375 |
lst = [] |
| 376 |
count = lib.sk_DIST_POINT_num(dps) |
| 377 |
for i in range(count): |
| 378 |
dp = lib.sk_DIST_POINT_value(dps, i); |
| 379 |
if not dp.distpoint: |
| 380 |
continue |
| 381 |
gns = dp.distpoint.name.fullname; |
| 382 |
|
| 383 |
jcount = lib.sk_GENERAL_NAME_num(gns) |
| 384 |
for j in range(jcount): |
| 385 |
gn = lib.sk_GENERAL_NAME_value(gns, j) |
| 386 |
if gn.type != lib.GEN_URI: |
| 387 |
continue |
| 388 |
|
| 389 |
uri = gn.d.uniformResourceIdentifier; |
| 390 |
ouri = _str_with_len(uri.data, uri.length) |
| 391 |
lst.append(ouri) |
| 392 |
|
| 393 |
lib.CRL_DIST_POINTS_free(dps); |
| 394 |
|
| 395 |
if len(lst) == 0: return None |
| 396 |
return tuple(lst) |
| 397 |
|
| 398 |
def _test_decode_cert(path): |
| 399 |
cert = lib.BIO_new(lib.BIO_s_file()) |
| 400 |
if cert is ffi.NULL: |
| 401 |
lib.BIO_free(cert) |
| 402 |
raise ssl_error("Can't malloc memory to read file") |
| 403 |
try: |
| 404 |
epath = str(path).encode() |
| 405 |
if lib.BIO_read_filename(cert, epath) <= 0: |
| 406 |
raise ssl_error("Can't open file") |
| 407 |
|
| 408 |
x = lib.PEM_read_bio_X509(cert, ffi.NULL, ffi.NULL, ffi.NULL) |
| 409 |
if x is ffi.NULL: |
| 410 |
raise ssl_error("Error decoding PEM-encoded file") |
| 411 |
|
| 412 |
try: |
| 413 |
retval = _decode_certificate(x) |
| 414 |
finally: |
| 415 |
lib.X509_free(x); |
| 416 |
|
| 417 |
finally: |
| 418 |
lib.BIO_free(cert) |
| 419 |
return retval |
| 420 |
|
| 421 |
PEM_HEADER = "-----BEGIN CERTIFICATE-----" |
| 422 |
PEM_FOOTER = "-----END CERTIFICATE-----" |
| 423 |
|
| 424 |
def PEM_cert_to_DER_cert(pem_cert_string): |
| 425 |
"""Takes a certificate in ASCII PEM format and returns the |
| 426 |
DER-encoded version of it as a byte sequence""" |
| 427 |
|
| 428 |
if not pem_cert_string.startswith(PEM_HEADER): |
| 429 |
raise ValueError("Invalid PEM encoding; must start with %s" |
| 430 |
% PEM_HEADER) |
| 431 |
if not pem_cert_string.strip().endswith(PEM_FOOTER): |
| 432 |
raise ValueError("Invalid PEM encoding; must end with %s" |
| 433 |
% PEM_FOOTER) |
| 434 |
d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)] |
| 435 |
return base64.decodebytes(d.encode('ASCII', 'strict')) |
| 436 |
|
| 437 |
def DER_cert_to_PEM_cert(der_cert_bytes): |
| 438 |
"""Takes a certificate in binary DER format and returns the |
| 439 |
PEM version of it as a string.""" |
| 440 |
|
| 441 |
f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict') |
| 442 |
return (PEM_HEADER + '\n' + |
| 443 |
textwrap.fill(f, 64) + '\n' + |
| 444 |
PEM_FOOTER + '\n') |
| 445 |
|
| 446 |
def _certificate_to_der(certificate): |
| 447 |
buf_ptr = ffi.new("unsigned char**") |
| 448 |
buf_ptr[0] = ffi.NULL |
| 449 |
length = lib.i2d_X509(certificate, buf_ptr) |
| 450 |
if length < 0: |
| 451 |
raise ssl_error(None) |
| 452 |
try: |
| 453 |
return _bytes_with_len(ffi.cast("char*",buf_ptr[0]), length) |
| 454 |
finally: |
| 455 |
lib.OPENSSL_free(buf_ptr[0]) |