Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sqlmapproject
GitHub Repository: sqlmapproject/sqlmap
Path: blob/master/lib/request/httpshandler.py
2989 views
1
#!/usr/bin/env python
2
3
"""
4
Copyright (c) 2006-2025 sqlmap developers (https://sqlmap.org)
5
See the file 'LICENSE' for copying permission
6
"""
7
8
import re
9
import socket
10
11
from lib.core.common import filterNone
12
from lib.core.common import getSafeExString
13
from lib.core.compat import LooseVersion
14
from lib.core.compat import xrange
15
from lib.core.data import conf
16
from lib.core.data import kb
17
from lib.core.data import logger
18
from lib.core.exception import SqlmapConnectionException
19
from lib.core.settings import PYVERSION
20
from thirdparty.six.moves import http_client as _http_client
21
from thirdparty.six.moves import urllib as _urllib
22
23
ssl = None
24
try:
25
import ssl as _ssl
26
ssl = _ssl
27
except ImportError:
28
pass
29
30
_protocols = filterNone(getattr(ssl, _, None) for _ in ("PROTOCOL_TLS_CLIENT", "PROTOCOL_TLSv1_2", "PROTOCOL_TLSv1_1", "PROTOCOL_TLSv1", "PROTOCOL_SSLv3", "PROTOCOL_SSLv23", "PROTOCOL_SSLv2"))
31
_lut = dict((getattr(ssl, _), _) for _ in dir(ssl) if _.startswith("PROTOCOL_"))
32
_contexts = {}
33
34
class HTTPSConnection(_http_client.HTTPSConnection):
35
"""
36
Connection class that enables usage of newer SSL protocols.
37
38
Reference: http://bugs.python.org/msg128686
39
40
NOTE: use https://check-tls.akamaized.net/ to check if (e.g.) TLS/SNI is working properly
41
"""
42
43
def __init__(self, *args, **kwargs):
44
# NOTE: Dirty patch for https://bugs.python.org/issue38251 / https://github.com/sqlmapproject/sqlmap/issues/4158
45
if hasattr(ssl, "_create_default_https_context"):
46
if None not in _contexts:
47
_contexts[None] = ssl._create_default_https_context()
48
kwargs["context"] = _contexts[None]
49
50
self.retrying = False
51
52
_http_client.HTTPSConnection.__init__(self, *args, **kwargs)
53
54
def connect(self):
55
def create_sock():
56
sock = socket.create_connection((self.host, self.port), self.timeout)
57
if getattr(self, "_tunnel_host", None):
58
self.sock = sock
59
self._tunnel()
60
return sock
61
62
success = False
63
64
# Reference(s): https://docs.python.org/2/library/ssl.html#ssl.SSLContext
65
# https://www.mnot.net/blog/2014/12/27/python_2_and_tls_sni
66
if hasattr(ssl, "SSLContext"):
67
for protocol in (_ for _ in _protocols if _ >= ssl.PROTOCOL_TLSv1):
68
try:
69
sock = create_sock()
70
if protocol not in _contexts:
71
_contexts[protocol] = ssl.SSLContext(protocol)
72
73
# Disable certificate and hostname validation enabled by default with PROTOCOL_TLS_CLIENT
74
_contexts[protocol].check_hostname = False
75
_contexts[protocol].verify_mode = ssl.CERT_NONE
76
77
if getattr(self, "cert_file", None) and getattr(self, "key_file", None):
78
_contexts[protocol].load_cert_chain(certfile=self.cert_file, keyfile=self.key_file)
79
try:
80
# Reference(s): https://askubuntu.com/a/1263098
81
# https://askubuntu.com/a/1250807
82
# https://git.zknt.org/mirror/bazarr/commit/7f05f932ffb84ba8b9e5630b2adc34dbd77e2b4a?style=split&whitespace=show-all&show-outdated=
83
_contexts[protocol].set_ciphers("ALL@SECLEVEL=0")
84
except (ssl.SSLError, AttributeError):
85
pass
86
result = _contexts[protocol].wrap_socket(sock, do_handshake_on_connect=True, server_hostname=self.host if re.search(r"\A[\d.]+\Z", self.host or "") is None else None)
87
if result:
88
success = True
89
self.sock = result
90
_protocols.remove(protocol)
91
_protocols.insert(0, protocol)
92
break
93
else:
94
sock.close()
95
except (ssl.SSLError, socket.error, _http_client.BadStatusLine, AttributeError) as ex:
96
self._tunnel_host = None
97
logger.debug("SSL connection error occurred for '%s' ('%s')" % (_lut[protocol], getSafeExString(ex)))
98
99
elif hasattr(ssl, "wrap_socket"):
100
for protocol in _protocols:
101
try:
102
sock = create_sock()
103
_ = ssl.wrap_socket(sock, keyfile=getattr(self, "key_file"), certfile=getattr(self, "cert_file"), ssl_version=protocol)
104
if _:
105
success = True
106
self.sock = _
107
_protocols.remove(protocol)
108
_protocols.insert(0, protocol)
109
break
110
else:
111
sock.close()
112
except (ssl.SSLError, socket.error, _http_client.BadStatusLine) as ex:
113
self._tunnel_host = None
114
logger.debug("SSL connection error occurred for '%s' ('%s')" % (_lut[protocol], getSafeExString(ex)))
115
116
if not success:
117
errMsg = "can't establish SSL connection"
118
# Reference: https://docs.python.org/2/library/ssl.html
119
if LooseVersion(PYVERSION) < LooseVersion("2.7.9"):
120
errMsg += " (please retry with Python >= 2.7.9)"
121
122
if kb.sslSuccess and not self.retrying:
123
self.retrying = True
124
125
for _ in xrange(conf.retries):
126
try:
127
self.connect()
128
except SqlmapConnectionException:
129
pass
130
else:
131
return
132
133
raise SqlmapConnectionException(errMsg)
134
else:
135
kb.sslSuccess = True
136
137
class HTTPSHandler(_urllib.request.HTTPSHandler):
138
def https_open(self, req):
139
return self.do_open(HTTPSConnection if ssl else _http_client.HTTPSConnection, req)
140
141