Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/scrapy/utils/ssl.py: 2%

44 statements  

« prev     ^ index     » next       coverage.py v7.4.1, created at 2024-02-07 06:38 +0000

1from typing import Any, Optional 

2 

3import OpenSSL._util as pyOpenSSLutil # type: ignore[import-untyped] 

4import OpenSSL.SSL 

5import OpenSSL.version 

6from OpenSSL.crypto import X509Name 

7 

8from scrapy.utils.python import to_unicode 

9 

10 

11def ffi_buf_to_string(buf: Any) -> str: 

12 return to_unicode(pyOpenSSLutil.ffi.string(buf)) 

13 

14 

15def x509name_to_string(x509name: X509Name) -> str: 

16 # from OpenSSL.crypto.X509Name.__repr__ 

17 result_buffer: Any = pyOpenSSLutil.ffi.new("char[]", 512) 

18 pyOpenSSLutil.lib.X509_NAME_oneline( 

19 x509name._name, result_buffer, len(result_buffer) # type: ignore[attr-defined] 

20 ) 

21 

22 return ffi_buf_to_string(result_buffer) 

23 

24 

25def get_temp_key_info(ssl_object: Any) -> Optional[str]: 

26 # adapted from OpenSSL apps/s_cb.c::ssl_print_tmp_key() 

27 if not hasattr(pyOpenSSLutil.lib, "SSL_get_server_tmp_key"): 

28 # removed in cryptography 40.0.0 

29 return None 

30 temp_key_p = pyOpenSSLutil.ffi.new("EVP_PKEY **") 

31 if not pyOpenSSLutil.lib.SSL_get_server_tmp_key(ssl_object, temp_key_p): 

32 return None 

33 temp_key = temp_key_p[0] 

34 if temp_key == pyOpenSSLutil.ffi.NULL: 

35 return None 

36 temp_key = pyOpenSSLutil.ffi.gc(temp_key, pyOpenSSLutil.lib.EVP_PKEY_free) 

37 key_info = [] 

38 key_type = pyOpenSSLutil.lib.EVP_PKEY_id(temp_key) 

39 if key_type == pyOpenSSLutil.lib.EVP_PKEY_RSA: 

40 key_info.append("RSA") 

41 elif key_type == pyOpenSSLutil.lib.EVP_PKEY_DH: 

42 key_info.append("DH") 

43 elif key_type == pyOpenSSLutil.lib.EVP_PKEY_EC: 

44 key_info.append("ECDH") 

45 ec_key = pyOpenSSLutil.lib.EVP_PKEY_get1_EC_KEY(temp_key) 

46 ec_key = pyOpenSSLutil.ffi.gc(ec_key, pyOpenSSLutil.lib.EC_KEY_free) 

47 nid = pyOpenSSLutil.lib.EC_GROUP_get_curve_name( 

48 pyOpenSSLutil.lib.EC_KEY_get0_group(ec_key) 

49 ) 

50 cname = pyOpenSSLutil.lib.EC_curve_nid2nist(nid) 

51 if cname == pyOpenSSLutil.ffi.NULL: 

52 cname = pyOpenSSLutil.lib.OBJ_nid2sn(nid) 

53 key_info.append(ffi_buf_to_string(cname)) 

54 else: 

55 key_info.append(ffi_buf_to_string(pyOpenSSLutil.lib.OBJ_nid2sn(key_type))) 

56 key_info.append(f"{pyOpenSSLutil.lib.EVP_PKEY_bits(temp_key)} bits") 

57 return ", ".join(key_info) 

58 

59 

60def get_openssl_version() -> str: 

61 system_openssl_bytes = OpenSSL.SSL.SSLeay_version(OpenSSL.SSL.SSLEAY_VERSION) 

62 system_openssl = system_openssl_bytes.decode("ascii", errors="replace") 

63 return f"{OpenSSL.version.__version__} ({system_openssl})"