-
Notifications
You must be signed in to change notification settings - Fork 164
Expand file tree
/
Copy pathsessions.py
More file actions
517 lines (460 loc) · 18 KB
/
sessions.py
File metadata and controls
517 lines (460 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
from .cffi import request, freeMemory, destroySession
from .cookies import cookiejar_from_dict, merge_cookies, extract_cookies_to_jar
from .exceptions import TLSClientExeption
from .response import build_response, Response
from .settings import ClientIdentifiers
from .structures import CaseInsensitiveDict
from .__version__ import __version__
from typing import Any, Dict, List, Optional, Union
from json import dumps, loads
import urllib.parse
import base64
import ctypes
import uuid
class Session:
def __init__(
self,
client_identifier: ClientIdentifiers = "chrome_120",
ja3_string: Optional[str] = None,
h2_settings: Optional[Dict[str, int]] = None,
h2_settings_order: Optional[List[str]] = None,
supported_signature_algorithms: Optional[List[str]] = None,
supported_delegated_credentials_algorithms: Optional[List[str]] = None,
supported_versions: Optional[List[str]] = None,
key_share_curves: Optional[List[str]] = None,
cert_compression_algo: str = None,
additional_decode: str = None,
pseudo_header_order: Optional[List[str]] = None,
connection_flow: Optional[int] = None,
priority_frames: Optional[list] = None,
header_order: Optional[List[str]] = None,
header_priority: Optional[List[str]] = None,
random_tls_extension_order: Optional = False,
force_http1: Optional = False,
catch_panics: Optional = False,
debug: Optional = False,
certificate_pinning: Optional[Dict[str, List[str]]] = None,
) -> None:
self._session_id = 1
# --- Standard Settings ----------------------------------------------------------------------------------------
# Case-insensitive dictionary of headers, send on each request
self.headers = CaseInsensitiveDict(
{
"User-Agent": f"tls-client/{__version__}",
"Accept-Encoding": "gzip, deflate, br",
"Accept": "*/*",
"Connection": "keep-alive",
}
)
# Example:
# {
# "http": "http://user:pass@ip:port",
# "https": "http://user:pass@ip:port"
# }
self.proxies = {}
# Dictionary of querystring data to attach to each request. The dictionary values may be lists for representing
# multivalued query parameters.
self.params = {}
# CookieJar containing all currently outstanding cookies set on this session
self.cookies = cookiejar_from_dict({})
# Timeout
self.timeout_seconds = 30
# Certificate pinning
self.certificate_pinning = certificate_pinning
# --- Advanced Settings ----------------------------------------------------------------------------------------
# Examples:
# Chrome --> chrome_103, chrome_104, chrome_105, chrome_106
# Firefox --> firefox_102, firefox_104
# Opera --> opera_89, opera_90
# Safari --> safari_15_3, safari_15_6_1, safari_16_0
# iOS --> safari_ios_15_5, safari_ios_15_6, safari_ios_16_0
# iPadOS --> safari_ios_15_6
#
# for all possible client identifiers, check out the settings.py
self.client_identifier = client_identifier
# Set JA3 --> TLSVersion, Ciphers, Extensions, EllipticCurves, EllipticCurvePointFormats
# Example:
# 771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-17513,29-23-24,0
self.ja3_string = ja3_string
# HTTP2 Header Frame Settings
# Possible Settings:
# HEADER_TABLE_SIZE
# SETTINGS_ENABLE_PUSH
# MAX_CONCURRENT_STREAMS
# INITIAL_WINDOW_SIZE
# MAX_FRAME_SIZE
# MAX_HEADER_LIST_SIZE
#
# Example:
# {
# "HEADER_TABLE_SIZE": 65536,
# "MAX_CONCURRENT_STREAMS": 1000,
# "INITIAL_WINDOW_SIZE": 6291456,
# "MAX_HEADER_LIST_SIZE": 262144
# }
self.h2_settings = h2_settings
# HTTP2 Header Frame Settings Order
# Example:
# [
# "HEADER_TABLE_SIZE",
# "MAX_CONCURRENT_STREAMS",
# "INITIAL_WINDOW_SIZE",
# "MAX_HEADER_LIST_SIZE"
# ]
self.h2_settings_order = h2_settings_order
# Supported Signature Algorithms
# Possible Settings:
# PKCS1WithSHA256
# PKCS1WithSHA384
# PKCS1WithSHA512
# PSSWithSHA256
# PSSWithSHA384
# PSSWithSHA512
# ECDSAWithP256AndSHA256
# ECDSAWithP384AndSHA384
# ECDSAWithP521AndSHA512
# PKCS1WithSHA1
# ECDSAWithSHA1
#
# Example:
# [
# "ECDSAWithP256AndSHA256",
# "PSSWithSHA256",
# "PKCS1WithSHA256",
# "ECDSAWithP384AndSHA384",
# "PSSWithSHA384",
# "PKCS1WithSHA384",
# "PSSWithSHA512",
# "PKCS1WithSHA512",
# ]
self.supported_signature_algorithms = supported_signature_algorithms
# Supported Delegated Credentials Algorithms
# Possible Settings:
# PKCS1WithSHA256
# PKCS1WithSHA384
# PKCS1WithSHA512
# PSSWithSHA256
# PSSWithSHA384
# PSSWithSHA512
# ECDSAWithP256AndSHA256
# ECDSAWithP384AndSHA384
# ECDSAWithP521AndSHA512
# PKCS1WithSHA1
# ECDSAWithSHA1
#
# Example:
# [
# "ECDSAWithP256AndSHA256",
# "PSSWithSHA256",
# "PKCS1WithSHA256",
# "ECDSAWithP384AndSHA384",
# "PSSWithSHA384",
# "PKCS1WithSHA384",
# "PSSWithSHA512",
# "PKCS1WithSHA512",
# ]
self.supported_delegated_credentials_algorithms = supported_delegated_credentials_algorithms
# Supported Versions
# Possible Settings:
# GREASE
# 1.3
# 1.2
# 1.1
# 1.0
#
# Example:
# [
# "GREASE",
# "1.3",
# "1.2"
# ]
self.supported_versions = supported_versions
# Key Share Curves
# Possible Settings:
# GREASE
# P256
# P384
# P521
# X25519
#
# Example:
# [
# "GREASE",
# "X25519"
# ]
self.key_share_curves = key_share_curves
# Cert Compression Algorithm
# Examples: "zlib", "brotli", "zstd"
self.cert_compression_algo = cert_compression_algo
# Additional Decode
# Make sure the go code decodes the response body once explicit by provided algorithm.
# Examples: null, "gzip", "br", "deflate"
self.additional_decode = additional_decode
# Pseudo Header Order (:authority, :method, :path, :scheme)
# Example:
# [
# ":method",
# ":authority",
# ":scheme",
# ":path"
# ]
self.pseudo_header_order = pseudo_header_order
# Connection Flow / Window Size Increment
# Example:
# 15663105
self.connection_flow = connection_flow
# Example:
# [
# {
# "streamID": 3,
# "priorityParam": {
# "weight": 201,
# "streamDep": 0,
# "exclusive": false
# }
# },
# {
# "streamID": 5,
# "priorityParam": {
# "weight": 101,
# "streamDep": false,
# "exclusive": 0
# }
# }
# ]
self.priority_frames = priority_frames
# Order of your headers
# Example:
# [
# "key1",
# "key2"
# ]
self.header_order = header_order
# Header Priority
# Example:
# {
# "streamDep": 1,
# "exclusive": true,
# "weight": 1
# }
self.header_priority = header_priority
# randomize tls extension order
self.random_tls_extension_order = random_tls_extension_order
# force HTTP1
self.force_http1 = force_http1
# catch panics
# avoid the tls client to print the whole stacktrace when a panic (critical go error) happens
self.catch_panics = catch_panics
# debugging
self.debug = debug
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def close(self) -> str:
destroy_session_payload = {
"sessionId": self._session_id
}
destroy_session_response = destroySession(dumps(destroy_session_payload).encode('utf-8'))
# we dereference the pointer to a byte array
destroy_session_response_bytes = ctypes.string_at(destroy_session_response)
# convert our byte array to a string (tls client returns json)
destroy_session_response_string = destroy_session_response_bytes.decode('utf-8')
# convert response string to json
destroy_session_response_object = loads(destroy_session_response_string)
freeMemory(destroy_session_response_object['id'].encode('utf-8'))
return destroy_session_response_string
def execute_request(
self,
method: str,
url: str,
params: Optional[dict] = None, # Optional[dict[str, str]]
data: Optional[Union[str, dict]] = None,
headers: Optional[dict] = None, # Optional[dict[str, str]]
cookies: Optional[dict] = None, # Optional[dict[str, str]]
json: Optional[dict] = None, # Optional[dict]
allow_redirects: Optional[bool] = False,
insecure_skip_verify: Optional[bool] = False,
timeout_seconds: Optional[int] = None,
proxy: Optional[dict] = None # Optional[dict[str, str]]
) -> Response:
self._session_id += 1
# --- URL ------------------------------------------------------------------------------------------------------
# Prepare URL - add params to url
if params is not None:
url = f"{url}?{urllib.parse.urlencode(params, doseq=True)}"
# --- Request Body ---------------------------------------------------------------------------------------------
# Prepare request body - build request body
# Data has priority. JSON is only used if data is None.
if data is None and json is not None:
if type(json) in [dict, list]:
json = dumps(json)
request_body = json
content_type = "application/json"
elif data is not None and type(data) not in [str, bytes]:
request_body = urllib.parse.urlencode(data, doseq=True)
content_type = "application/x-www-form-urlencoded"
else:
request_body = data
content_type = None
# set content type if it isn't set
if content_type is not None and "content-type" not in self.headers:
self.headers["Content-Type"] = content_type
# --- Headers --------------------------------------------------------------------------------------------------
if self.headers is None:
headers = CaseInsensitiveDict(headers)
elif headers is None:
headers = self.headers
else:
merged_headers = CaseInsensitiveDict(self.headers)
merged_headers.update(headers)
# Remove items, where the key or value is set to None.
none_keys = [k for (k, v) in merged_headers.items() if v is None or k is None]
for key in none_keys:
del merged_headers[key]
headers = merged_headers
# --- Cookies --------------------------------------------------------------------------------------------------
cookies = cookies or {}
# Merge with session cookies
cookies = merge_cookies(self.cookies, cookies)
# turn cookie jar into dict
# in the cookie value the " gets removed, because the fhttp library in golang doesn't accept the character
if 'cookie' in headers or 'Cookie' in headers:
request_cookies = []
else:
request_cookies = [
{'domain': c.domain, 'expires': c.expires, 'name': c.name, 'path': c.path, 'value': c.value.replace('"', "")}
for c in cookies
]
# --- Proxy ----------------------------------------------------------------------------------------------------
proxy = proxy or self.proxies
if type(proxy) is dict and "http" in proxy:
proxy = proxy["http"]
elif type(proxy) is str:
proxy = proxy
else:
proxy = ""
# --- Timeout --------------------------------------------------------------------------------------------------
# maximum time to wait for a response
timeout_seconds = timeout_seconds or self.timeout_seconds
# --- Certificate pinning --------------------------------------------------------------------------------------
# pins a certificate so that it restricts which certificates are considered valid
certificate_pinning = self.certificate_pinning
# --- Request --------------------------------------------------------------------------------------------------
is_byte_request = isinstance(request_body, (bytes, bytearray))
request_payload = {
"sessionId": str(self._session_id),
"followRedirects": allow_redirects,
"forceHttp1": self.force_http1,
"withDebug": self.debug,
"catchPanics": self.catch_panics,
"headers": dict(headers),
"headerOrder": self.header_order,
"insecureSkipVerify": insecure_skip_verify,
"isByteRequest": is_byte_request,
"additionalDecode": self.additional_decode,
"proxyUrl": proxy,
"requestUrl": url,
"requestMethod": method,
"requestBody": base64.b64encode(request_body).decode() if is_byte_request else request_body,
"requestCookies": request_cookies,
"timeoutSeconds": timeout_seconds,
}
if certificate_pinning:
request_payload["certificatePinningHosts"] = certificate_pinning
if self.client_identifier is None:
request_payload["customTlsClient"] = {
"ja3String": self.ja3_string,
"h2Settings": self.h2_settings,
"h2SettingsOrder": self.h2_settings_order,
"pseudoHeaderOrder": self.pseudo_header_order,
"connectionFlow": self.connection_flow,
"priorityFrames": self.priority_frames,
"headerPriority": self.header_priority,
"certCompressionAlgo": self.cert_compression_algo,
"supportedVersions": self.supported_versions,
"supportedSignatureAlgorithms": self.supported_signature_algorithms,
"supportedDelegatedCredentialsAlgorithms": self.supported_delegated_credentials_algorithms ,
"keyShareCurves": self.key_share_curves,
}
else:
request_payload["tlsClientIdentifier"] = self.client_identifier
request_payload["withRandomTLSExtensionOrder"] = self.random_tls_extension_order
# this is a pointer to the response
response = request(dumps(request_payload).encode('utf-8'))
# dereference the pointer to a byte array
response_bytes = ctypes.string_at(response)
# convert our byte array to a string (tls client returns json)
response_string = response_bytes.decode('utf-8')
# convert response string to json
response_object = loads(response_string)
# free the memory
freeMemory(response_object['id'].encode('utf-8'))
# --- Response -------------------------------------------------------------------------------------------------
# Error handling
if response_object["status"] == 0:
raise TLSClientExeption(response_object["body"])
# Set response cookies
response_cookie_jar = extract_cookies_to_jar(
request_url=url,
request_headers=headers,
cookie_jar=cookies,
response_headers=response_object["headers"]
)
# build response class
return build_response(response_object, response_cookie_jar)
def get(
self,
url: str,
**kwargs: Any
) -> Response:
"""Sends a GET request"""
return self.execute_request(method="GET", url=url, **kwargs)
def options(
self,
url: str,
**kwargs: Any
) -> Response:
"""Sends a OPTIONS request"""
return self.execute_request(method="OPTIONS", url=url, **kwargs)
def head(
self,
url: str,
**kwargs: Any
) -> Response:
"""Sends a HEAD request"""
return self.execute_request(method="HEAD", url=url, **kwargs)
def post(
self,
url: str,
data: Optional[Union[str, dict]] = None,
json: Optional[dict] = None,
**kwargs: Any
) -> Response:
"""Sends a POST request"""
return self.execute_request(method="POST", url=url, data=data, json=json, **kwargs)
def put(
self,
url: str,
data: Optional[Union[str, dict]] = None,
json: Optional[dict] = None,
**kwargs: Any
) -> Response:
"""Sends a PUT request"""
return self.execute_request(method="PUT", url=url, data=data, json=json, **kwargs)
def patch(
self,
url: str,
data: Optional[Union[str, dict]] = None,
json: Optional[dict] = None,
**kwargs: Any
) -> Response:
"""Sends a PATCH request"""
return self.execute_request(method="PATCH", url=url, data=data, json=json, **kwargs)
def delete(
self,
url: str,
**kwargs: Any
) -> Response:
"""Sends a DELETE request"""
return self.execute_request(method="DELETE", url=url, **kwargs)