Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sqlmapproject
GitHub Repository: sqlmapproject/sqlmap
Path: blob/master/lib/request/httpshandler.py
3556 views
1
#!/usr/bin/env python
2
3
"""
4
Copyright (c) 2006-2026 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
sock = None
69
try:
70
sock = create_sock()
71
if protocol not in _contexts:
72
_contexts[protocol] = ssl.SSLContext(protocol)
73
74
# Disable certificate and hostname validation enabled by default with PROTOCOL_TLS_CLIENT
75
_contexts[protocol].check_hostname = False
76
_contexts[protocol].verify_mode = ssl.CERT_NONE
77
78
if getattr(self, "cert_file", None) and getattr(self, "key_file", None):
79
_contexts[protocol].load_cert_chain(certfile=self.cert_file, keyfile=self.key_file)
80
try:
81
# Reference(s): https://askubuntu.com/a/1263098
82
# https://askubuntu.com/a/1250807
83
# https://git.zknt.org/mirror/bazarr/commit/7f05f932ffb84ba8b9e5630b2adc34dbd77e2b4a?style=split&whitespace=show-all&show-outdated=
84
_contexts[protocol].set_ciphers("ALL@SECLEVEL=0")
85
except (ssl.SSLError, AttributeError):
86
pass
87
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)
88
if result:
89
success = True
90
self.sock = result
91
_protocols.remove(protocol)
92
_protocols.insert(0, protocol)
93
break
94
else:
95
sock.close()
96
except (ssl.SSLError, socket.error, _http_client.BadStatusLine, AttributeError) as ex:
97
self._tunnel_host = None
98
if sock:
99
sock.close()
100
logger.debug("SSL connection error occurred for '%s' ('%s')" % (_lut[protocol], getSafeExString(ex)))
101
102
elif hasattr(ssl, "wrap_socket"):
103
for protocol in _protocols:
104
try:
105
sock = create_sock()
106
_ = ssl.wrap_socket(sock, keyfile=getattr(self, "key_file"), certfile=getattr(self, "cert_file"), ssl_version=protocol)
107
if _:
108
success = True
109
self.sock = _
110
_protocols.remove(protocol)
111
_protocols.insert(0, protocol)
112
break
113
else:
114
sock.close()
115
except (ssl.SSLError, socket.error, _http_client.BadStatusLine) as ex:
116
self._tunnel_host = None
117
logger.debug("SSL connection error occurred for '%s' ('%s')" % (_lut[protocol], getSafeExString(ex)))
118
119
if not success:
120
errMsg = "can't establish SSL connection"
121
# Reference: https://docs.python.org/2/library/ssl.html
122
if LooseVersion(PYVERSION) < LooseVersion("2.7.9"):
123
errMsg += " (please retry with Python >= 2.7.9)"
124
125
if kb.sslSuccess and not self.retrying:
126
self.retrying = True
127
128
for _ in xrange(conf.retries):
129
try:
130
self.connect()
131
except SqlmapConnectionException:
132
pass
133
else:
134
return
135
136
raise SqlmapConnectionException(errMsg)
137
else:
138
kb.sslSuccess = True
139
140
class HTTPSHandler(_urllib.request.HTTPSHandler):
141
def https_open(self, req):
142
return self.do_open(HTTPSConnection if ssl else _http_client.HTTPSConnection, req)
143
144