parent
d7873470fd
commit
c3dcf766b3
@ -0,0 +1,111 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
"""
|
||||||
|
cloudscraper.exceptions
|
||||||
|
~~~~~~~~~~~~~~~~~~~
|
||||||
|
This module contains the set of cloudscraper exceptions.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
class CloudflareException(Exception):
|
||||||
|
"""
|
||||||
|
Base exception class for cloudscraper for Cloudflare
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class CloudflareLoopProtection(CloudflareException):
|
||||||
|
"""
|
||||||
|
Raise an exception for recursive depth protection
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class CloudflareCode1020(CloudflareException):
|
||||||
|
"""
|
||||||
|
Raise an exception for Cloudflare code 1020 block
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class CloudflareIUAMError(CloudflareException):
|
||||||
|
"""
|
||||||
|
Raise an error for problem extracting IUAM paramters
|
||||||
|
from Cloudflare payload
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class CloudflareChallengeError(CloudflareException):
|
||||||
|
"""
|
||||||
|
Raise an error when detected new Cloudflare challenge
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class CloudflareSolveError(CloudflareException):
|
||||||
|
"""
|
||||||
|
Raise an error when issue with solving Cloudflare challenge
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class CloudflareReCaptchaError(CloudflareException):
|
||||||
|
"""
|
||||||
|
Raise an error for problem extracting reCaptcha paramters
|
||||||
|
from Cloudflare payload
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class CloudflareReCaptchaProvider(CloudflareException):
|
||||||
|
"""
|
||||||
|
Raise an exception for no reCaptcha provider loaded for Cloudflare.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
class reCaptchaException(Exception):
|
||||||
|
"""
|
||||||
|
Base exception class for cloudscraper reCaptcha Providers
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class reCaptchaServiceUnavailable(reCaptchaException):
|
||||||
|
"""
|
||||||
|
Raise an exception for external services that cannot be reached
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class reCaptchaAPIError(reCaptchaException):
|
||||||
|
"""
|
||||||
|
Raise an error for error from API response.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class reCaptchaAccountError(reCaptchaException):
|
||||||
|
"""
|
||||||
|
Raise an error for reCaptcha provider account problem.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class reCaptchaTimeout(reCaptchaException):
|
||||||
|
"""
|
||||||
|
Raise an exception for reCaptcha provider taking too long.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class reCaptchaParameter(reCaptchaException):
|
||||||
|
"""
|
||||||
|
Raise an exception for bad or missing Parameter.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class reCaptchaBadJobID(reCaptchaException):
|
||||||
|
"""
|
||||||
|
Raise an exception for invalid job id.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class reCaptchaReportError(reCaptchaException):
|
||||||
|
"""
|
||||||
|
Raise an error for reCaptcha provider unable to report bad solve.
|
||||||
|
"""
|
@ -0,0 +1,79 @@
|
|||||||
|
import json
|
||||||
|
import platform
|
||||||
|
import requests
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
import urllib3
|
||||||
|
|
||||||
|
from collections import OrderedDict
|
||||||
|
from . import __version__ as cloudscraper_version
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
def getPossibleCiphers():
|
||||||
|
try:
|
||||||
|
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
|
||||||
|
context.set_ciphers('ALL')
|
||||||
|
return sorted([cipher['name'] for cipher in context.get_ciphers()])
|
||||||
|
except AttributeError:
|
||||||
|
return 'get_ciphers() is unsupported'
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
def _pythonVersion():
|
||||||
|
interpreter = platform.python_implementation()
|
||||||
|
interpreter_version = platform.python_version()
|
||||||
|
|
||||||
|
if interpreter == 'PyPy':
|
||||||
|
interpreter_version = '{}.{}.{}'.format(
|
||||||
|
sys.pypy_version_info.major,
|
||||||
|
sys.pypy_version_info.minor,
|
||||||
|
sys.pypy_version_info.micro
|
||||||
|
)
|
||||||
|
if sys.pypy_version_info.releaselevel != 'final':
|
||||||
|
interpreter_version = '{}{}'.format(
|
||||||
|
interpreter_version,
|
||||||
|
sys.pypy_version_info.releaselevel
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
'name': interpreter,
|
||||||
|
'version': interpreter_version
|
||||||
|
}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
def systemInfo():
|
||||||
|
try:
|
||||||
|
platform_info = {
|
||||||
|
'system': platform.system(),
|
||||||
|
'release': platform.release(),
|
||||||
|
}
|
||||||
|
except IOError:
|
||||||
|
platform_info = {
|
||||||
|
'system': 'Unknown',
|
||||||
|
'release': 'Unknown',
|
||||||
|
}
|
||||||
|
|
||||||
|
return OrderedDict([
|
||||||
|
('platform', platform_info),
|
||||||
|
('interpreter', _pythonVersion()),
|
||||||
|
('cloudscraper', cloudscraper_version),
|
||||||
|
('requests', requests.__version__),
|
||||||
|
('urllib3', urllib3.__version__),
|
||||||
|
('OpenSSL', OrderedDict(
|
||||||
|
[
|
||||||
|
('version', ssl.OPENSSL_VERSION),
|
||||||
|
('ciphers', getPossibleCiphers())
|
||||||
|
]
|
||||||
|
))
|
||||||
|
])
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
print(json.dumps(systemInfo(), indent=4))
|
@ -0,0 +1,103 @@
|
|||||||
|
from __future__ import absolute_import
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import ctypes.util
|
||||||
|
|
||||||
|
from ctypes import c_void_p, c_size_t, byref, create_string_buffer, CDLL
|
||||||
|
|
||||||
|
from . import JavaScriptInterpreter
|
||||||
|
from .encapsulated import template
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
class ChallengeInterpreter(JavaScriptInterpreter):
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super(ChallengeInterpreter, self).__init__('chakracore')
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def eval(self, body, domain):
|
||||||
|
chakraCoreLibrary = None
|
||||||
|
|
||||||
|
# check current working directory.
|
||||||
|
for _libraryFile in ['libChakraCore.so', 'libChakraCore.dylib', 'ChakraCore.dll']:
|
||||||
|
if os.path.isfile(os.path.join(os.getcwd(), _libraryFile)):
|
||||||
|
chakraCoreLibrary = os.path.join(os.getcwd(), _libraryFile)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not chakraCoreLibrary:
|
||||||
|
chakraCoreLibrary = ctypes.util.find_library('ChakraCore')
|
||||||
|
|
||||||
|
if not chakraCoreLibrary:
|
||||||
|
sys.tracebacklimit = 0
|
||||||
|
raise RuntimeError(
|
||||||
|
'ChakraCore library not found in current path or any of your system library paths, '
|
||||||
|
'please download from https://www.github.com/VeNoMouS/cloudscraper/tree/ChakraCore/, '
|
||||||
|
'or https://github.com/Microsoft/ChakraCore/'
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
chakraCore = CDLL(chakraCoreLibrary)
|
||||||
|
except OSError:
|
||||||
|
sys.tracebacklimit = 0
|
||||||
|
raise RuntimeError('There was an error loading the ChakraCore library {}'.format(chakraCoreLibrary))
|
||||||
|
|
||||||
|
if sys.platform != 'win32':
|
||||||
|
chakraCore.DllMain(0, 1, 0)
|
||||||
|
chakraCore.DllMain(0, 2, 0)
|
||||||
|
|
||||||
|
script = create_string_buffer(template(body, domain).encode('utf-16'))
|
||||||
|
|
||||||
|
runtime = c_void_p()
|
||||||
|
chakraCore.JsCreateRuntime(0, 0, byref(runtime))
|
||||||
|
|
||||||
|
context = c_void_p()
|
||||||
|
chakraCore.JsCreateContext(runtime, byref(context))
|
||||||
|
chakraCore.JsSetCurrentContext(context)
|
||||||
|
|
||||||
|
fname = c_void_p()
|
||||||
|
chakraCore.JsCreateString(
|
||||||
|
'iuam-challenge.js',
|
||||||
|
len('iuam-challenge.js'),
|
||||||
|
byref(fname)
|
||||||
|
)
|
||||||
|
|
||||||
|
scriptSource = c_void_p()
|
||||||
|
chakraCore.JsCreateExternalArrayBuffer(
|
||||||
|
script,
|
||||||
|
len(script),
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
byref(scriptSource)
|
||||||
|
)
|
||||||
|
|
||||||
|
jsResult = c_void_p()
|
||||||
|
chakraCore.JsRun(scriptSource, 0, fname, 0x02, byref(jsResult))
|
||||||
|
|
||||||
|
resultJSString = c_void_p()
|
||||||
|
chakraCore.JsConvertValueToString(jsResult, byref(resultJSString))
|
||||||
|
|
||||||
|
stringLength = c_size_t()
|
||||||
|
chakraCore.JsCopyString(resultJSString, 0, 0, byref(stringLength))
|
||||||
|
|
||||||
|
resultSTR = create_string_buffer(stringLength.value + 1)
|
||||||
|
chakraCore.JsCopyString(
|
||||||
|
resultJSString,
|
||||||
|
byref(resultSTR),
|
||||||
|
stringLength.value + 1,
|
||||||
|
0
|
||||||
|
)
|
||||||
|
|
||||||
|
chakraCore.JsDisposeRuntime(runtime)
|
||||||
|
|
||||||
|
return resultSTR.value
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
ChallengeInterpreter()
|
@ -0,0 +1,62 @@
|
|||||||
|
import logging
|
||||||
|
import re
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
def template(body, domain):
|
||||||
|
BUG_REPORT = 'Cloudflare may have changed their technique, or there may be a bug in the script.'
|
||||||
|
|
||||||
|
try:
|
||||||
|
js = re.search(
|
||||||
|
r'setTimeout\(function\(\){\s+(.*?a\.value\s*=\s*\S+toFixed\(10\);)',
|
||||||
|
body,
|
||||||
|
re.M | re.S
|
||||||
|
).group(1)
|
||||||
|
except Exception:
|
||||||
|
raise ValueError('Unable to identify Cloudflare IUAM Javascript on website. {}'.format(BUG_REPORT))
|
||||||
|
|
||||||
|
jsEnv = '''String.prototype.italics=function(str) {{return "<i>" + this + "</i>";}};
|
||||||
|
var subVars= {{{subVars}}};
|
||||||
|
var document = {{
|
||||||
|
createElement: function () {{
|
||||||
|
return {{ firstChild: {{ href: "https://{domain}/" }} }}
|
||||||
|
}},
|
||||||
|
getElementById: function (str) {{
|
||||||
|
return {{"innerHTML": subVars[str]}};
|
||||||
|
}}
|
||||||
|
}};
|
||||||
|
'''
|
||||||
|
|
||||||
|
try:
|
||||||
|
js = js.replace(
|
||||||
|
r"(setInterval(function(){}, 100),t.match(/https?:\/\//)[0]);",
|
||||||
|
r"t.match(/https?:\/\//)[0];"
|
||||||
|
)
|
||||||
|
|
||||||
|
k = re.search(r" k\s*=\s*'(?P<k>\S+)';", body).group('k')
|
||||||
|
r = re.compile(r'<div id="{}(?P<id>\d+)">\s*(?P<jsfuck>[^<>]*)</div>'.format(k))
|
||||||
|
|
||||||
|
subVars = ''
|
||||||
|
for m in r.finditer(body):
|
||||||
|
subVars = '{}\n\t\t{}{}: {},\n'.format(subVars, k, m.group('id'), m.group('jsfuck'))
|
||||||
|
subVars = subVars[:-2]
|
||||||
|
|
||||||
|
except: # noqa
|
||||||
|
logging.error('Error extracting Cloudflare IUAM Javascript. {}'.format(BUG_REPORT))
|
||||||
|
raise
|
||||||
|
|
||||||
|
return '{}{}'.format(
|
||||||
|
re.sub(
|
||||||
|
r'\s{2,}',
|
||||||
|
' ',
|
||||||
|
jsEnv.format(
|
||||||
|
domain=domain,
|
||||||
|
subVars=subVars
|
||||||
|
),
|
||||||
|
re.MULTILINE | re.DOTALL
|
||||||
|
),
|
||||||
|
js
|
||||||
|
)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
@ -0,0 +1,233 @@
|
|||||||
|
from __future__ import absolute_import
|
||||||
|
|
||||||
|
import ast
|
||||||
|
import re
|
||||||
|
import operator as op
|
||||||
|
import pyparsing
|
||||||
|
|
||||||
|
from ..exceptions import CloudflareSolveError
|
||||||
|
from . import JavaScriptInterpreter
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
_OP_MAP = {
|
||||||
|
ast.Add: op.add,
|
||||||
|
ast.Sub: op.sub,
|
||||||
|
ast.Mult: op.mul,
|
||||||
|
ast.Div: op.truediv,
|
||||||
|
ast.Invert: op.neg,
|
||||||
|
}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
class Calc(ast.NodeVisitor):
|
||||||
|
|
||||||
|
def visit_BinOp(self, node):
|
||||||
|
return _OP_MAP[type(node.op)](self.visit(node.left), self.visit(node.right))
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def visit_Num(self, node):
|
||||||
|
return node.n
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def visit_Expr(self, node):
|
||||||
|
return self.visit(node.value)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def doMath(cls, expression):
|
||||||
|
tree = ast.parse(expression)
|
||||||
|
calc = cls()
|
||||||
|
return calc.visit(tree.body[0])
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
class Parentheses(object):
|
||||||
|
|
||||||
|
def fix(self, s):
|
||||||
|
res = []
|
||||||
|
self.visited = set([s])
|
||||||
|
self.dfs(s, self.invalid(s), res)
|
||||||
|
return res
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def dfs(self, s, n, res):
|
||||||
|
if n == 0:
|
||||||
|
res.append(s)
|
||||||
|
return
|
||||||
|
for i in range(len(s)):
|
||||||
|
if s[i] in ['(', ')']:
|
||||||
|
s_new = s[:i] + s[i + 1:]
|
||||||
|
if s_new not in self.visited and self.invalid(s_new) < n:
|
||||||
|
self.visited.add(s_new)
|
||||||
|
self.dfs(s_new, self.invalid(s_new), res)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def invalid(self, s):
|
||||||
|
plus = minus = 0
|
||||||
|
memo = {"(": 1, ")": -1}
|
||||||
|
for c in s:
|
||||||
|
plus += memo.get(c, 0)
|
||||||
|
minus += 1 if plus < 0 else 0
|
||||||
|
plus = max(0, plus)
|
||||||
|
return plus + minus
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
class ChallengeInterpreter(JavaScriptInterpreter):
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super(ChallengeInterpreter, self).__init__('native')
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def eval(self, body, domain):
|
||||||
|
|
||||||
|
operators = {
|
||||||
|
'+': op.add,
|
||||||
|
'-': op.sub,
|
||||||
|
'*': op.mul,
|
||||||
|
'/': op.truediv
|
||||||
|
}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def flatten(lists):
|
||||||
|
return sum(map(flatten, lists), []) if isinstance(lists, list) else [lists]
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def jsfuckToNumber(jsFuck):
|
||||||
|
# "Clean Up" JSFuck
|
||||||
|
jsFuck = jsFuck.replace('!+[]', '1').replace('!![]', '1').replace('[]', '0')
|
||||||
|
jsFuck = jsFuck.lstrip('+').replace('(+', '(').replace(' ', '')
|
||||||
|
jsFuck = Parentheses().fix(jsFuck)[0]
|
||||||
|
|
||||||
|
# Hackery Parser for Math
|
||||||
|
stack = []
|
||||||
|
bstack = []
|
||||||
|
|
||||||
|
for i in flatten(pyparsing.nestedExpr().parseString(jsFuck).asList()):
|
||||||
|
if i == '+':
|
||||||
|
stack.append(bstack)
|
||||||
|
bstack = []
|
||||||
|
continue
|
||||||
|
bstack.append(i)
|
||||||
|
stack.append(bstack)
|
||||||
|
|
||||||
|
return int(''.join([str(Calc.doMath(''.join(i))) for i in stack]))
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def divisorMath(payload, needle, domain):
|
||||||
|
jsfuckMath = payload.split('/')
|
||||||
|
if needle in jsfuckMath[1]:
|
||||||
|
expression = re.findall(r"^(.*?)(.)\(function", jsfuckMath[1])[0]
|
||||||
|
|
||||||
|
expression_value = operators[expression[1]](
|
||||||
|
float(jsfuckToNumber(expression[0])),
|
||||||
|
float(ord(domain[jsfuckToNumber(jsfuckMath[1][
|
||||||
|
jsfuckMath[1].find('"("+p+")")}') + len('"("+p+")")}'):-2
|
||||||
|
])]))
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
expression_value = jsfuckToNumber(jsfuckMath[1])
|
||||||
|
|
||||||
|
expression_value = jsfuckToNumber(jsfuckMath[0]) / float(expression_value)
|
||||||
|
|
||||||
|
return expression_value
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def challengeSolve(body, domain):
|
||||||
|
jschl_answer = 0
|
||||||
|
|
||||||
|
try:
|
||||||
|
jsfuckChallenge = re.search(
|
||||||
|
r"setTimeout\(function\(\){\s+var.*?f,\s*(?P<variable>\w+).*?:(?P<init>\S+)};"
|
||||||
|
r".*?\('challenge-form'\);.*?;(?P<challenge>.*?a\.value)\s*=\s*\S+\.toFixed\(10\);",
|
||||||
|
body,
|
||||||
|
re.DOTALL | re.MULTILINE
|
||||||
|
).groupdict()
|
||||||
|
except AttributeError:
|
||||||
|
raise CloudflareSolveError('There was an issue extracting "jsfuckChallenge" from the Cloudflare challenge.')
|
||||||
|
|
||||||
|
kJSFUCK = re.search(r'(;|)\s*k.=(?P<kJSFUCK>\S+);', jsfuckChallenge['challenge'], re.S | re.M)
|
||||||
|
if kJSFUCK:
|
||||||
|
try:
|
||||||
|
kJSFUCK = jsfuckToNumber(kJSFUCK.group('kJSFUCK'))
|
||||||
|
except IndexError:
|
||||||
|
raise CloudflareSolveError('There was an issue extracting "kJSFUCK" from the Cloudflare challenge.')
|
||||||
|
|
||||||
|
try:
|
||||||
|
kID = re.search(r"\s*k\s*=\s*'(?P<kID>\S+)';", body).group('kID')
|
||||||
|
except IndexError:
|
||||||
|
raise CloudflareSolveError('There was an issue extracting "kID" from the Cloudflare challenge.')
|
||||||
|
|
||||||
|
try:
|
||||||
|
r = re.compile(r'<div id="{}(?P<id>\d+)">\s*(?P<jsfuck>[^<>]*)</div>'.format(kID))
|
||||||
|
|
||||||
|
kValues = {}
|
||||||
|
for m in r.finditer(body):
|
||||||
|
kValues[int(m.group('id'))] = m.group('jsfuck')
|
||||||
|
|
||||||
|
jsfuckChallenge['k'] = kValues[kJSFUCK]
|
||||||
|
except (AttributeError, IndexError):
|
||||||
|
raise CloudflareSolveError('There was an issue extracting "kValues" from the Cloudflare challenge.')
|
||||||
|
|
||||||
|
jsfuckChallenge['challenge'] = re.finditer(
|
||||||
|
r'{}.*?([+\-*/])=(.*?);(?=a\.value|{})'.format(
|
||||||
|
jsfuckChallenge['variable'],
|
||||||
|
jsfuckChallenge['variable']
|
||||||
|
),
|
||||||
|
jsfuckChallenge['challenge']
|
||||||
|
)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
if '/' in jsfuckChallenge['init']:
|
||||||
|
val = jsfuckChallenge['init'].split('/')
|
||||||
|
jschl_answer = jsfuckToNumber(val[0]) / float(jsfuckToNumber(val[1]))
|
||||||
|
else:
|
||||||
|
jschl_answer = jsfuckToNumber(jsfuckChallenge['init'])
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
for expressionMatch in jsfuckChallenge['challenge']:
|
||||||
|
oper, expression = expressionMatch.groups()
|
||||||
|
|
||||||
|
if '/' in expression:
|
||||||
|
expression_value = divisorMath(expression, 'function(p)', domain)
|
||||||
|
else:
|
||||||
|
if 'Element' in expression:
|
||||||
|
expression_value = divisorMath(jsfuckChallenge['k'], '"("+p+")")}', domain)
|
||||||
|
else:
|
||||||
|
expression_value = jsfuckToNumber(expression)
|
||||||
|
|
||||||
|
jschl_answer = operators[oper](jschl_answer, expression_value)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
# if not jsfuckChallenge['k'] and '+ t.length' in body:
|
||||||
|
# jschl_answer += len(domain)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
return '{0:.10f}'.format(jschl_answer)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
return challengeSolve(body, domain)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
ChallengeInterpreter()
|
@ -0,0 +1,33 @@
|
|||||||
|
from __future__ import absolute_import
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
try:
|
||||||
|
import v8eval
|
||||||
|
except ImportError:
|
||||||
|
sys.tracebacklimit = 0
|
||||||
|
raise RuntimeError('Please install the python module v8eval either via pip or download it from https://github.com/sony/v8eval')
|
||||||
|
|
||||||
|
from . import JavaScriptInterpreter
|
||||||
|
from .encapsulated import template
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
class ChallengeInterpreter(JavaScriptInterpreter):
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super(ChallengeInterpreter, self).__init__('v8')
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def eval(self, body, domain):
|
||||||
|
try:
|
||||||
|
return v8eval.V8().eval(template(body, domain))
|
||||||
|
except (TypeError, v8eval.V8Error):
|
||||||
|
RuntimeError('We encountered an error running the V8 Engine.')
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
ChallengeInterpreter()
|
@ -0,0 +1,248 @@
|
|||||||
|
from __future__ import absolute_import
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from ..exceptions import (
|
||||||
|
reCaptchaServiceUnavailable,
|
||||||
|
reCaptchaAPIError,
|
||||||
|
reCaptchaTimeout,
|
||||||
|
reCaptchaParameter,
|
||||||
|
reCaptchaBadJobID,
|
||||||
|
reCaptchaReportError
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
import polling
|
||||||
|
except ImportError:
|
||||||
|
raise ImportError(
|
||||||
|
"Please install the python module 'polling' via pip or download it from "
|
||||||
|
"https://github.com/justiniso/polling/"
|
||||||
|
)
|
||||||
|
|
||||||
|
from . import reCaptcha
|
||||||
|
|
||||||
|
|
||||||
|
class captchaSolver(reCaptcha):
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super(captchaSolver, self).__init__('2captcha')
|
||||||
|
self.host = 'https://2captcha.com'
|
||||||
|
self.session = requests.Session()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def checkErrorStatus(response, request_type):
|
||||||
|
if response.status_code in [500, 502]:
|
||||||
|
raise reCaptchaServiceUnavailable('2Captcha: Server Side Error {}'.format(response.status_code))
|
||||||
|
|
||||||
|
errors = {
|
||||||
|
'in.php': {
|
||||||
|
"ERROR_WRONG_USER_KEY": "You've provided api_key parameter value is in incorrect format, it should contain 32 symbols.",
|
||||||
|
"ERROR_KEY_DOES_NOT_EXIST": "The api_key you've provided does not exists.",
|
||||||
|
"ERROR_ZERO_BALANCE": "You don't have sufficient funds on your account.",
|
||||||
|
"ERROR_PAGEURL": "pageurl parameter is missing in your request.",
|
||||||
|
"ERROR_NO_SLOT_AVAILABLE":
|
||||||
|
"No Slots Available.\nYou can receive this error in two cases:\n"
|
||||||
|
"1. If you solve ReCaptcha: the queue of your captchas that are not distributed to workers is too long. "
|
||||||
|
"Queue limit changes dynamically and depends on total amount of captchas awaiting solution and usually it's between 50 and 100 captchas.\n"
|
||||||
|
"2. If you solve Normal Captcha: your maximum rate for normal captchas is lower than current rate on the server."
|
||||||
|
"You can change your maximum rate in your account's settings.",
|
||||||
|
"ERROR_IP_NOT_ALLOWED": "The request is sent from the IP that is not on the list of your allowed IPs.",
|
||||||
|
"IP_BANNED": "Your IP address is banned due to many frequent attempts to access the server using wrong authorization keys.",
|
||||||
|
"ERROR_BAD_TOKEN_OR_PAGEURL":
|
||||||
|
"You can get this error code when sending ReCaptcha V2. "
|
||||||
|
"That happens if your request contains invalid pair of googlekey and pageurl. "
|
||||||
|
"The common reason for that is that ReCaptcha is loaded inside an iframe hosted on another domain/subdomain.",
|
||||||
|
"ERROR_GOOGLEKEY":
|
||||||
|
"You can get this error code when sending ReCaptcha V2. "
|
||||||
|
"That means that sitekey value provided in your request is incorrect: it's blank or malformed.",
|
||||||
|
"MAX_USER_TURN": "You made more than 60 requests within 3 seconds.Your account is banned for 10 seconds. Ban will be lifted automatically."
|
||||||
|
},
|
||||||
|
'res.php': {
|
||||||
|
"ERROR_CAPTCHA_UNSOLVABLE":
|
||||||
|
"We are unable to solve your captcha - three of our workers were unable solve it "
|
||||||
|
"or we didn't get an answer within 90 seconds (300 seconds for ReCaptcha V2). "
|
||||||
|
"We will not charge you for that request.",
|
||||||
|
"ERROR_WRONG_USER_KEY": "You've provided api_key parameter value in incorrect format, it should contain 32 symbols.",
|
||||||
|
"ERROR_KEY_DOES_NOT_EXIST": "The api_key you've provided does not exists.",
|
||||||
|
"ERROR_WRONG_ID_FORMAT": "You've provided captcha ID in wrong format. The ID can contain numbers only.",
|
||||||
|
"ERROR_WRONG_CAPTCHA_ID": "You've provided incorrect captcha ID.",
|
||||||
|
"ERROR_BAD_DUPLICATES":
|
||||||
|
"Error is returned when 100% accuracy feature is enabled. "
|
||||||
|
"The error means that max numbers of tries is reached but min number of matches not found.",
|
||||||
|
"REPORT_NOT_RECORDED": "Error is returned to your complain request if you already complained lots of correctly solved captchas.",
|
||||||
|
"ERROR_IP_ADDRES":
|
||||||
|
"You can receive this error code when registering a pingback (callback) IP or domain."
|
||||||
|
"That happes if your request is coming from an IP address that doesn't match the IP address of your pingback IP or domain.",
|
||||||
|
"ERROR_TOKEN_EXPIRED": "You can receive this error code when sending GeeTest. That error means that challenge value you provided is expired.",
|
||||||
|
"ERROR_EMPTY_ACTION": "Action parameter is missing or no value is provided for action parameter."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if response.json().get('status') == 0 and response.json().get('request') in errors.get(request_type):
|
||||||
|
raise reCaptchaAPIError(
|
||||||
|
'{} {}'.format(
|
||||||
|
response.json().get('request'),
|
||||||
|
errors.get(request_type).get(response.json().get('request'))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def reportJob(self, jobID):
|
||||||
|
if not jobID:
|
||||||
|
raise reCaptchaBadJobID(
|
||||||
|
"2Captcha: Error bad job id to request reCaptcha."
|
||||||
|
)
|
||||||
|
|
||||||
|
def _checkRequest(response):
|
||||||
|
if response.ok and response.json().get('status') == 1:
|
||||||
|
return response
|
||||||
|
|
||||||
|
self.checkErrorStatus(response, 'res.php')
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
response = polling.poll(
|
||||||
|
lambda: self.session.get(
|
||||||
|
'{}/res.php'.format(self.host),
|
||||||
|
params={
|
||||||
|
'key': self.api_key,
|
||||||
|
'action': 'reportbad',
|
||||||
|
'id': jobID,
|
||||||
|
'json': '1'
|
||||||
|
},
|
||||||
|
timeout=30
|
||||||
|
),
|
||||||
|
check_success=_checkRequest,
|
||||||
|
step=5,
|
||||||
|
timeout=180
|
||||||
|
)
|
||||||
|
|
||||||
|
if response:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
raise reCaptchaReportError(
|
||||||
|
"2Captcha: Error - Failed to report bad reCaptcha solve."
|
||||||
|
)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def requestJob(self, jobID):
|
||||||
|
if not jobID:
|
||||||
|
raise reCaptchaBadJobID("2Captcha: Error bad job id to request reCaptcha.")
|
||||||
|
|
||||||
|
def _checkRequest(response):
|
||||||
|
if response.ok and response.json().get('status') == 1:
|
||||||
|
return response
|
||||||
|
|
||||||
|
self.checkErrorStatus(response, 'res.php')
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
response = polling.poll(
|
||||||
|
lambda: self.session.get(
|
||||||
|
'{}/res.php'.format(self.host),
|
||||||
|
params={
|
||||||
|
'key': self.api_key,
|
||||||
|
'action': 'get',
|
||||||
|
'id': jobID,
|
||||||
|
'json': '1'
|
||||||
|
},
|
||||||
|
timeout=30
|
||||||
|
),
|
||||||
|
check_success=_checkRequest,
|
||||||
|
step=5,
|
||||||
|
timeout=180
|
||||||
|
)
|
||||||
|
|
||||||
|
if response:
|
||||||
|
return response.json().get('request')
|
||||||
|
else:
|
||||||
|
raise reCaptchaTimeout(
|
||||||
|
"2Captcha: Error failed to solve reCaptcha."
|
||||||
|
)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def requestSolve(self, captchaType, url, siteKey):
|
||||||
|
def _checkRequest(response):
|
||||||
|
if response.ok and response.json().get("status") == 1 and response.json().get('request'):
|
||||||
|
return response
|
||||||
|
|
||||||
|
self.checkErrorStatus(response, 'in.php')
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
data = {
|
||||||
|
'key': self.api_key,
|
||||||
|
'pageurl': url,
|
||||||
|
'json': 1,
|
||||||
|
'soft_id': 5507698
|
||||||
|
}
|
||||||
|
|
||||||
|
data.update(
|
||||||
|
{
|
||||||
|
'method': 'userrcaptcha',
|
||||||
|
'googlekey': siteKey
|
||||||
|
} if captchaType == 'reCaptcha' else {
|
||||||
|
'method': 'hcaptcha',
|
||||||
|
'sitekey': siteKey
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
response = polling.poll(
|
||||||
|
lambda: self.session.post(
|
||||||
|
'{}/in.php'.format(self.host),
|
||||||
|
data=data,
|
||||||
|
allow_redirects=False,
|
||||||
|
timeout=30
|
||||||
|
),
|
||||||
|
check_success=_checkRequest,
|
||||||
|
step=5,
|
||||||
|
timeout=180
|
||||||
|
)
|
||||||
|
|
||||||
|
if response:
|
||||||
|
return response.json().get('request')
|
||||||
|
else:
|
||||||
|
raise reCaptchaBadJobID(
|
||||||
|
'2Captcha: Error no job id was returned.'
|
||||||
|
)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def getCaptchaAnswer(self, captchaType, url, siteKey, reCaptchaParams):
|
||||||
|
jobID = None
|
||||||
|
|
||||||
|
if not reCaptchaParams.get('api_key'):
|
||||||
|
raise reCaptchaParameter(
|
||||||
|
"2Captcha: Missing api_key parameter."
|
||||||
|
)
|
||||||
|
|
||||||
|
self.api_key = reCaptchaParams.get('api_key')
|
||||||
|
|
||||||
|
if reCaptchaParams.get('proxy'):
|
||||||
|
self.session.proxies = reCaptchaParams.get('proxies')
|
||||||
|
|
||||||
|
try:
|
||||||
|
jobID = self.requestSolve(captchaType, url, siteKey)
|
||||||
|
return self.requestJob(jobID)
|
||||||
|
except polling.TimeoutException:
|
||||||
|
try:
|
||||||
|
if jobID:
|
||||||
|
self.reportJob(jobID)
|
||||||
|
except polling.TimeoutException:
|
||||||
|
raise reCaptchaTimeout(
|
||||||
|
"2Captcha: reCaptcha solve took to long and also failed reporting the job the job id {}.".format(jobID)
|
||||||
|
)
|
||||||
|
|
||||||
|
raise reCaptchaTimeout(
|
||||||
|
"2Captcha: reCaptcha solve took to long to execute job id {}, aborting.".format(jobID)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
captchaSolver()
|
@ -0,0 +1,212 @@
|
|||||||
|
from __future__ import absolute_import
|
||||||
|
|
||||||
|
import re
|
||||||
|
import requests
|
||||||
|
|
||||||
|
try:
|
||||||
|
import polling
|
||||||
|
except ImportError:
|
||||||
|
raise ImportError(
|
||||||
|
"Please install the python module 'polling' via pip or download it from "
|
||||||
|
"https://github.com/justiniso/polling/"
|
||||||
|
)
|
||||||
|
|
||||||
|
from ..exceptions import (
|
||||||
|
reCaptchaServiceUnavailable,
|
||||||
|
reCaptchaAPIError,
|
||||||
|
reCaptchaTimeout,
|
||||||
|
reCaptchaParameter,
|
||||||
|
reCaptchaBadJobID
|
||||||
|
)
|
||||||
|
|
||||||
|
from . import reCaptcha
|
||||||
|
|
||||||
|
|
||||||
|
class captchaSolver(reCaptcha):
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super(captchaSolver, self).__init__('9kw')
|
||||||
|
self.host = 'https://www.9kw.eu/index.cgi'
|
||||||
|
self.maxtimeout = 180
|
||||||
|
self.session = requests.Session()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def checkErrorStatus(response):
|
||||||
|
if response.status_code in [500, 502]:
|
||||||
|
raise reCaptchaServiceUnavailable(
|
||||||
|
'9kw: Server Side Error {}'.format(response.status_code)
|
||||||
|
)
|
||||||
|
|
||||||
|
error_codes = {
|
||||||
|
1: 'No API Key available.',
|
||||||
|
2: 'No API key found.',
|
||||||
|
3: 'No active API key found.',
|
||||||
|
4: 'API Key has been disabled by the operator. ',
|
||||||
|
5: 'No user found.',
|
||||||
|
6: 'No data found.',
|
||||||
|
7: 'Found No ID.',
|
||||||
|
8: 'found No captcha.',
|
||||||
|
9: 'No image found.',
|
||||||
|
10: 'Image size not allowed.',
|
||||||
|
11: 'credit is not sufficient.',
|
||||||
|
12: 'what was done.',
|
||||||
|
13: 'No answer contain.',
|
||||||
|
14: 'Captcha already been answered.',
|
||||||
|
15: 'Captcha to quickly filed.',
|
||||||
|
16: 'JD check active.',
|
||||||
|
17: 'Unknown problem.',
|
||||||
|
18: 'Found No ID.',
|
||||||
|
19: 'Incorrect answer.',
|
||||||
|
20: 'Do not timely filed (Incorrect UserID).',
|
||||||
|
21: 'Link not allowed.',
|
||||||
|
22: 'Prohibited submit.',
|
||||||
|
23: 'Entering prohibited.',
|
||||||
|
24: 'Too little credit.',
|
||||||
|
25: 'No entry found.',
|
||||||
|
26: 'No Conditions accepted.',
|
||||||
|
27: 'No coupon code found in the database.',
|
||||||
|
28: 'Already unused voucher code.',
|
||||||
|
29: 'maxTimeout under 60 seconds.',
|
||||||
|
30: 'User not found.',
|
||||||
|
31: 'An account is not yet 24 hours in system.',
|
||||||
|
32: 'An account does not have the full rights.',
|
||||||
|
33: 'Plugin needed a update.',
|
||||||
|
34: 'No HTTPS allowed.',
|
||||||
|
35: 'No HTTP allowed.',
|
||||||
|
36: 'Source not allowed.',
|
||||||
|
37: 'Transfer denied.',
|
||||||
|
38: 'Incorrect answer without space',
|
||||||
|
39: 'Incorrect answer with space',
|
||||||
|
40: 'Incorrect answer with not only numbers',
|
||||||
|
41: 'Incorrect answer with not only A-Z, a-z',
|
||||||
|
42: 'Incorrect answer with not only 0-9, A-Z, a-z',
|
||||||
|
43: 'Incorrect answer with not only [0-9,- ]',
|
||||||
|
44: 'Incorrect answer with not only [0-9A-Za-z,- ]',
|
||||||
|
45: 'Incorrect answer with not only coordinates',
|
||||||
|
46: 'Incorrect answer with not only multiple coordinates',
|
||||||
|
47: 'Incorrect answer with not only data',
|
||||||
|
48: 'Incorrect answer with not only rotate number',
|
||||||
|
49: 'Incorrect answer with not only text',
|
||||||
|
50: 'Incorrect answer with not only text and too short',
|
||||||
|
51: 'Incorrect answer with not enough chars',
|
||||||
|
52: 'Incorrect answer with too many chars',
|
||||||
|
53: 'Incorrect answer without no or yes',
|
||||||
|
54: 'Assignment was not found.'
|
||||||
|
}
|
||||||
|
|
||||||
|
if response.text.startswith('{'):
|
||||||
|
if response.json().get('error'):
|
||||||
|
raise reCaptchaAPIError(error_codes.get(int(response.json().get('error'))))
|
||||||
|
else:
|
||||||
|
error_code = int(re.search(r'^00(?P<error_code>\d+)', response.text).groupdict().get('error_code', 0))
|
||||||
|
if error_code:
|
||||||
|
raise reCaptchaAPIError(error_codes.get(error_code))
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def requestJob(self, jobID):
|
||||||
|
if not jobID:
|
||||||
|
raise reCaptchaBadJobID(
|
||||||
|
"9kw: Error bad job id to request reCaptcha against."
|
||||||
|
)
|
||||||
|
|
||||||
|
def _checkRequest(response):
|
||||||
|
if response.ok and response.json().get('answer') != 'NO DATA':
|
||||||
|
return response
|
||||||
|
|
||||||
|
self.checkErrorStatus(response)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
response = polling.poll(
|
||||||
|
lambda: self.session.get(
|
||||||
|
self.host,
|
||||||
|
params={
|
||||||
|
'apikey': self.api_key,
|
||||||
|
'action': 'usercaptchacorrectdata',
|
||||||
|
'id': jobID,
|
||||||
|
'info': 1,
|
||||||
|
'json': 1
|
||||||
|
}
|
||||||
|
),
|
||||||
|
check_success=_checkRequest,
|
||||||
|
step=10,
|
||||||
|
timeout=(self.maxtimeout + 10)
|
||||||
|
)
|
||||||
|
|
||||||
|
if response:
|
||||||
|
return response.json().get('answer')
|
||||||
|
else:
|
||||||
|
raise reCaptchaTimeout("9kw: Error failed to solve reCaptcha.")
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def requestSolve(self, captchaType, url, siteKey):
|
||||||
|
def _checkRequest(response):
|
||||||
|
if response.ok and response.text.startswith('{') and response.json().get('captchaid'):
|
||||||
|
return response
|
||||||
|
|
||||||
|
self.checkErrorStatus(response)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
captchaMap = {
|
||||||
|
'reCaptcha': 'recaptchav2',
|
||||||
|
'hCaptcha': 'hcaptcha'
|
||||||
|
}
|
||||||
|
|
||||||
|
response = polling.poll(
|
||||||
|
lambda: self.session.post(
|
||||||
|
self.host,
|
||||||
|
data={
|
||||||
|
'apikey': self.api_key,
|
||||||
|
'action': 'usercaptchaupload',
|
||||||
|
'interactive': 1,
|
||||||
|
'file-upload-01': siteKey,
|
||||||
|
'oldsource': captchaMap[captchaType],
|
||||||
|
'pageurl': url,
|
||||||
|
'maxtimeout': self.maxtimeout,
|
||||||
|
'json': 1
|
||||||
|
},
|
||||||
|
allow_redirects=False
|
||||||
|
),
|
||||||
|
check_success=_checkRequest,
|
||||||
|
step=5,
|
||||||
|
timeout=(self.maxtimeout + 10)
|
||||||
|
)
|
||||||
|
|
||||||
|
if response:
|
||||||
|
return response.json().get('captchaid')
|
||||||
|
else:
|
||||||
|
raise reCaptchaBadJobID('9kw: Error no valid job id was returned.')
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def getCaptchaAnswer(self, captchaType, url, siteKey, reCaptchaParams):
|
||||||
|
jobID = None
|
||||||
|
|
||||||
|
if not reCaptchaParams.get('api_key'):
|
||||||
|
raise reCaptchaParameter("9kw: Missing api_key parameter.")
|
||||||
|
|
||||||
|
self.api_key = reCaptchaParams.get('api_key')
|
||||||
|
|
||||||
|
if reCaptchaParams.get('maxtimeout'):
|
||||||
|
self.maxtimeout = reCaptchaParams.get('maxtimeout')
|
||||||
|
|
||||||
|
if reCaptchaParams.get('proxy'):
|
||||||
|
self.session.proxies = reCaptchaParams.get('proxies')
|
||||||
|
|
||||||
|
try:
|
||||||
|
jobID = self.requestSolve(captchaType, url, siteKey)
|
||||||
|
return self.requestJob(jobID)
|
||||||
|
except polling.TimeoutException:
|
||||||
|
raise reCaptchaTimeout(
|
||||||
|
"9kw: reCaptcha solve took to long to execute 'captchaid' {}, aborting.".format(jobID)
|
||||||
|
)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
captchaSolver()
|
@ -0,0 +1,46 @@
|
|||||||
|
import abc
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
|
||||||
|
if sys.version_info >= (3, 4):
|
||||||
|
ABC = abc.ABC # noqa
|
||||||
|
else:
|
||||||
|
ABC = abc.ABCMeta('ABC', (), {})
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
captchaSolvers = {}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
class reCaptcha(ABC):
|
||||||
|
@abc.abstractmethod
|
||||||
|
def __init__(self, name):
|
||||||
|
captchaSolvers[name] = self
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def dynamicImport(cls, name):
|
||||||
|
if name not in captchaSolvers:
|
||||||
|
try:
|
||||||
|
__import__('{}.{}'.format(cls.__module__, name))
|
||||||
|
if not isinstance(captchaSolvers.get(name), reCaptcha):
|
||||||
|
raise ImportError('The anti reCaptcha provider was not initialized.')
|
||||||
|
except ImportError:
|
||||||
|
logging.error("Unable to load {} anti reCaptcha provider".format(name))
|
||||||
|
raise
|
||||||
|
|
||||||
|
return captchaSolvers[name]
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def getCaptchaAnswer(self, captchaType, url, siteKey, reCaptchaParams):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def solveCaptcha(self, captchaType, url, siteKey, reCaptchaParams):
|
||||||
|
return self.getCaptchaAnswer(captchaType, url, siteKey, reCaptchaParams)
|
@ -0,0 +1,75 @@
|
|||||||
|
from __future__ import absolute_import
|
||||||
|
from ..exceptions import (
|
||||||
|
reCaptchaParameter,
|
||||||
|
reCaptchaTimeout,
|
||||||
|
reCaptchaAPIError
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
from python_anticaptcha import (
|
||||||
|
AnticaptchaClient,
|
||||||
|
NoCaptchaTaskProxylessTask,
|
||||||
|
HCaptchaTaskProxyless,
|
||||||
|
AnticaptchaException
|
||||||
|
)
|
||||||
|
except ImportError:
|
||||||
|
raise ImportError(
|
||||||
|
"Please install/upgrade the python module 'python_anticaptcha' via "
|
||||||
|
"pip install python-anticaptcha or https://github.com/ad-m/python-anticaptcha/"
|
||||||
|
)
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from . import reCaptcha
|
||||||
|
|
||||||
|
|
||||||
|
class captchaSolver(reCaptcha):
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
if sys.modules['python_anticaptcha'].__version__ < '0.6':
|
||||||
|
raise ImportError(
|
||||||
|
"Please upgrade the python module 'python_anticaptcha' via "
|
||||||
|
"pip install -U python-anticaptcha or https://github.com/ad-m/python-anticaptcha/"
|
||||||
|
)
|
||||||
|
super(captchaSolver, self).__init__('anticaptcha')
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def getCaptchaAnswer(self, captchaType, url, siteKey, reCaptchaParams):
|
||||||
|
if not reCaptchaParams.get('api_key'):
|
||||||
|
raise reCaptchaParameter("anticaptcha: Missing api_key parameter.")
|
||||||
|
|
||||||
|
client = AnticaptchaClient(reCaptchaParams.get('api_key'))
|
||||||
|
|
||||||
|
if reCaptchaParams.get('proxy'):
|
||||||
|
client.session.proxies = reCaptchaParams.get('proxies')
|
||||||
|
|
||||||
|
captchaMap = {
|
||||||
|
'reCaptcha': NoCaptchaTaskProxylessTask,
|
||||||
|
'hCaptcha': HCaptchaTaskProxyless
|
||||||
|
}
|
||||||
|
|
||||||
|
task = captchaMap[captchaType](url, siteKey)
|
||||||
|
|
||||||
|
if not hasattr(client, 'createTaskSmee'):
|
||||||
|
raise NotImplementedError(
|
||||||
|
"Please upgrade 'python_anticaptcha' via pip or download it from "
|
||||||
|
"https://github.com/ad-m/python-anticaptcha/tree/hcaptcha"
|
||||||
|
)
|
||||||
|
|
||||||
|
job = client.createTaskSmee(task, timeout=180)
|
||||||
|
|
||||||
|
try:
|
||||||
|
job.join(maximum_time=180)
|
||||||
|
except (AnticaptchaException) as e:
|
||||||
|
raise reCaptchaTimeout('{}'.format(getattr(e, 'message', e)))
|
||||||
|
|
||||||
|
if 'solution' in job._last_result:
|
||||||
|
return job.get_solution_response()
|
||||||
|
else:
|
||||||
|
raise reCaptchaAPIError('Job did not return `solution` key in payload.')
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
captchaSolver()
|
@ -0,0 +1,233 @@
|
|||||||
|
from __future__ import absolute_import
|
||||||
|
|
||||||
|
import json
|
||||||
|
import requests
|
||||||
|
|
||||||
|
try:
|
||||||
|
import polling
|
||||||
|
except ImportError:
|
||||||
|
raise ImportError(
|
||||||
|
"Please install the python module 'polling' via pip or download it from "
|
||||||
|
"https://github.com/justiniso/polling/"
|
||||||
|
)
|
||||||
|
|
||||||
|
from ..exceptions import (
|
||||||
|
reCaptchaException,
|
||||||
|
reCaptchaServiceUnavailable,
|
||||||
|
reCaptchaAccountError,
|
||||||
|
reCaptchaTimeout,
|
||||||
|
reCaptchaParameter,
|
||||||
|
reCaptchaBadJobID,
|
||||||
|
reCaptchaReportError
|
||||||
|
)
|
||||||
|
|
||||||
|
from . import reCaptcha
|
||||||
|
|
||||||
|
|
||||||
|
class captchaSolver(reCaptcha):
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super(captchaSolver, self).__init__('deathbycaptcha')
|
||||||
|
self.host = 'http://api.dbcapi.me/api'
|
||||||
|
self.session = requests.Session()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def checkErrorStatus(response):
|
||||||
|
errors = dict(
|
||||||
|
[
|
||||||
|
(400, "DeathByCaptcha: 400 Bad Request"),
|
||||||
|
(403, "DeathByCaptcha: 403 Forbidden - Invalid credentails or insufficient credits."),
|
||||||
|
# (500, "DeathByCaptcha: 500 Internal Server Error."),
|
||||||
|
(503, "DeathByCaptcha: 503 Service Temporarily Unavailable.")
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
if response.status_code in errors:
|
||||||
|
raise reCaptchaServiceUnavailable(errors.get(response.status_code))
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def login(self, username, password):
|
||||||
|
self.username = username
|
||||||
|
self.password = password
|
||||||
|
|
||||||
|
def _checkRequest(response):
|
||||||
|
if response.ok:
|
||||||
|
if response.json().get('is_banned'):
|
||||||
|
raise reCaptchaAccountError('DeathByCaptcha: Your account is banned.')
|
||||||
|
|
||||||
|
if response.json().get('balanace') == 0:
|
||||||
|
raise reCaptchaAccountError('DeathByCaptcha: insufficient credits.')
|
||||||
|
|
||||||
|
return response
|
||||||
|
|
||||||
|
self.checkErrorStatus(response)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
response = polling.poll(
|
||||||
|
lambda: self.session.post(
|
||||||
|
'{}/user'.format(self.host),
|
||||||
|
headers={'Accept': 'application/json'},
|
||||||
|
data={
|
||||||
|
'username': self.username,
|
||||||
|
'password': self.password
|
||||||
|
}
|
||||||
|
),
|
||||||
|
check_success=_checkRequest,
|
||||||
|
step=10,
|
||||||
|
timeout=120
|
||||||
|
)
|
||||||
|
|
||||||
|
self.debugRequest(response)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def reportJob(self, jobID):
|
||||||
|
if not jobID:
|
||||||
|
raise reCaptchaBadJobID(
|
||||||
|
"DeathByCaptcha: Error bad job id to report failed reCaptcha."
|
||||||
|
)
|
||||||
|
|
||||||
|
def _checkRequest(response):
|
||||||
|
if response.status_code == 200:
|
||||||
|
return response
|
||||||
|
|
||||||
|
self.checkErrorStatus(response)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
response = polling.poll(
|
||||||
|
lambda: self.session.post(
|
||||||
|
'{}/captcha/{}/report'.format(self.host, jobID),
|
||||||
|
headers={'Accept': 'application/json'},
|
||||||
|
data={
|
||||||
|
'username': self.username,
|
||||||
|
'password': self.password
|
||||||
|
}
|
||||||
|
),
|
||||||
|
check_success=_checkRequest,
|
||||||
|
step=10,
|
||||||
|
timeout=180
|
||||||
|
)
|
||||||
|
|
||||||
|
if response:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
raise reCaptchaReportError(
|
||||||
|
"DeathByCaptcha: Error report failed reCaptcha."
|
||||||
|
)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def requestJob(self, jobID):
|
||||||
|
if not jobID:
|
||||||
|
raise reCaptchaBadJobID(
|
||||||
|
"DeathByCaptcha: Error bad job id to request reCaptcha."
|
||||||
|
)
|
||||||
|
|
||||||
|
def _checkRequest(response):
|
||||||
|
if response.ok and response.json().get('text'):
|
||||||
|
return response
|
||||||
|
|
||||||
|
self.checkErrorStatus(response)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
response = polling.poll(
|
||||||
|
lambda: self.session.get(
|
||||||
|
'{}/captcha/{}'.format(self.host, jobID),
|
||||||
|
headers={'Accept': 'application/json'}
|
||||||
|
),
|
||||||
|
check_success=_checkRequest,
|
||||||
|
step=10,
|
||||||
|
timeout=180
|
||||||
|
)
|
||||||
|
|
||||||
|
if response:
|
||||||
|
return response.json().get('text')
|
||||||
|
else:
|
||||||
|
raise reCaptchaTimeout(
|
||||||
|
"DeathByCaptcha: Error failed to solve reCaptcha."
|
||||||
|
)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def requestSolve(self, url, siteKey):
|
||||||
|
def _checkRequest(response):
|
||||||
|
if response.ok and response.json().get("is_correct") and response.json().get('captcha'):
|
||||||
|
return response
|
||||||
|
|
||||||
|
self.checkErrorStatus(response)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
response = polling.poll(
|
||||||
|
lambda: self.session.post(
|
||||||
|
'{}/captcha'.format(self.host),
|
||||||
|
headers={'Accept': 'application/json'},
|
||||||
|
data={
|
||||||
|
'username': self.username,
|
||||||
|
'password': self.password,
|
||||||
|
'type': '4',
|
||||||
|
'token_params': json.dumps({
|
||||||
|
'googlekey': siteKey,
|
||||||
|
'pageurl': url
|
||||||
|
})
|
||||||
|
},
|
||||||
|
allow_redirects=False
|
||||||
|
),
|
||||||
|
check_success=_checkRequest,
|
||||||
|
step=10,
|
||||||
|
timeout=180
|
||||||
|
)
|
||||||
|
|
||||||
|
if response:
|
||||||
|
return response.json().get('captcha')
|
||||||
|
else:
|
||||||
|
raise reCaptchaBadJobID(
|
||||||
|
'DeathByCaptcha: Error no job id was returned.'
|
||||||
|
)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def getCaptchaAnswer(self, captchaType, url, siteKey, reCaptchaParams):
|
||||||
|
jobID = None
|
||||||
|
|
||||||
|
for param in ['username', 'password']:
|
||||||
|
if not reCaptchaParams.get(param):
|
||||||
|
raise reCaptchaParameter(
|
||||||
|
"DeathByCaptcha: Missing '{}' parameter.".format(param)
|
||||||
|
)
|
||||||
|
setattr(self, param, reCaptchaParams.get(param))
|
||||||
|
|
||||||
|
if captchaType == 'hCaptcha':
|
||||||
|
raise reCaptchaException(
|
||||||
|
'Provider does not support hCaptcha.'
|
||||||
|
)
|
||||||
|
|
||||||
|
if reCaptchaParams.get('proxy'):
|
||||||
|
self.session.proxies = reCaptchaParams.get('proxies')
|
||||||
|
|
||||||
|
try:
|
||||||
|
jobID = self.requestSolve(url, siteKey)
|
||||||
|
return self.requestJob(jobID)
|
||||||
|
except polling.TimeoutException:
|
||||||
|
try:
|
||||||
|
if jobID:
|
||||||
|
self.reportJob(jobID)
|
||||||
|
except polling.TimeoutException:
|
||||||
|
raise reCaptchaTimeout(
|
||||||
|
"DeathByCaptcha: reCaptcha solve took to long and also failed reporting the job id {}.".format(jobID)
|
||||||
|
)
|
||||||
|
|
||||||
|
raise reCaptchaTimeout(
|
||||||
|
"DeathByCaptcha: reCaptcha solve took to long to execute job id {}, aborting.".format(jobID)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
captchaSolver()
|
@ -1,38 +1,117 @@
|
|||||||
import os
|
|
||||||
import json
|
import json
|
||||||
|
import os
|
||||||
import random
|
import random
|
||||||
import logging
|
import re
|
||||||
|
import sys
|
||||||
|
import ssl
|
||||||
|
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
|
|
||||||
##########################################################################################################################################################
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
class User_Agent():
|
class User_Agent():
|
||||||
|
|
||||||
##########################################################################################################################################################
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
self.headers = None
|
self.headers = None
|
||||||
|
self.cipherSuite = []
|
||||||
self.loadUserAgent(*args, **kwargs)
|
self.loadUserAgent(*args, **kwargs)
|
||||||
|
|
||||||
##########################################################################################################################################################
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def loadHeaders(self, user_agents, user_agent_version):
|
||||||
|
if user_agents.get(self.browser).get('releases').get(user_agent_version).get('headers'):
|
||||||
|
self.headers = user_agents.get(self.browser).get('releases').get(user_agent_version).get('headers')
|
||||||
|
else:
|
||||||
|
self.headers = user_agents.get(self.browser).get('default_headers')
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def filterAgents(self, releases):
|
||||||
|
filtered = {}
|
||||||
|
|
||||||
|
for release in releases:
|
||||||
|
if self.mobile and releases[release]['User-Agent']['mobile']:
|
||||||
|
filtered[release] = filtered.get(release, []) + releases[release]['User-Agent']['mobile']
|
||||||
|
|
||||||
|
if self.desktop and releases[release]['User-Agent']['desktop']:
|
||||||
|
filtered[release] = filtered.get(release, []) + releases[release]['User-Agent']['desktop']
|
||||||
|
|
||||||
|
return filtered
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def tryMatchCustom(self, user_agents):
|
||||||
|
for browser in user_agents:
|
||||||
|
for release in user_agents[browser]['releases']:
|
||||||
|
for platform in ['mobile', 'desktop']:
|
||||||
|
if re.search(re.escape(self.custom), ' '.join(user_agents[browser]['releases'][release]['User-Agent'][platform])):
|
||||||
|
self.browser = browser
|
||||||
|
self.loadHeaders(user_agents, release)
|
||||||
|
self.headers['User-Agent'] = self.custom
|
||||||
|
self.cipherSuite = user_agents[self.browser].get('cipherSuite', [])
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------- #
|
||||||
|
|
||||||
def loadUserAgent(self, *args, **kwargs):
|
def loadUserAgent(self, *args, **kwargs):
|
||||||
browser = kwargs.pop('browser', 'chrome')
|
self.browser = kwargs.pop('browser', None)
|
||||||
|
|
||||||
|
if isinstance(self.browser, dict):
|
||||||
|
self.custom = self.browser.get('custom', None)
|
||||||
|
self.desktop = self.browser.get('desktop', True)
|
||||||
|
self.mobile = self.browser.get('mobile', True)
|
||||||
|
self.browser = self.browser.get('browser', None)
|
||||||
|
else:
|
||||||
|
self.custom = kwargs.pop('custom', None)
|
||||||
|
self.desktop = kwargs.pop('desktop', True)
|
||||||
|
self.mobile = kwargs.pop('mobile', True)
|
||||||
|
|
||||||
|
if not self.desktop and not self.mobile:
|
||||||
|
sys.tracebacklimit = 0
|
||||||
|
raise RuntimeError("Sorry you can't have mobile and desktop disabled at the same time.")
|
||||||
|
|
||||||
|
with open(os.path.join(os.path.dirname(__file__), 'browsers.json'), 'r') as fp:
|
||||||
|
user_agents = json.load(
|
||||||
|
fp,
|
||||||
|
object_pairs_hook=OrderedDict
|
||||||
|
)
|
||||||
|
|
||||||
|
if self.custom:
|
||||||
|
if not self.tryMatchCustom(user_agents):
|
||||||
|
self.cipherSuite = [
|
||||||
|
ssl._DEFAULT_CIPHERS,
|
||||||
|
'!AES128-SHA',
|
||||||
|
'!ECDHE-RSA-AES256-SHA',
|
||||||
|
]
|
||||||
|
self.headers = OrderedDict([
|
||||||
|
('User-Agent', self.custom),
|
||||||
|
('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'),
|
||||||
|
('Accept-Language', 'en-US,en;q=0.9'),
|
||||||
|
('Accept-Encoding', 'gzip, deflate, br')
|
||||||
|
])
|
||||||
|
else:
|
||||||
|
if self.browser and not user_agents.get(self.browser):
|
||||||
|
sys.tracebacklimit = 0
|
||||||
|
raise RuntimeError('Sorry "{}" browser User-Agent was not found.'.format(self.browser))
|
||||||
|
|
||||||
|
if not self.browser:
|
||||||
|
self.browser = random.SystemRandom().choice(list(user_agents))
|
||||||
|
|
||||||
|
self.cipherSuite = user_agents.get(self.browser).get('cipherSuite', [])
|
||||||
|
|
||||||
with open(os.path.join(os.path.dirname(__file__), 'browsers.json'), 'r') as file:
|
filteredAgents = self.filterAgents(user_agents.get(self.browser).get('releases'))
|
||||||
user_agents = json.load(file, object_pairs_hook=OrderedDict)
|
|
||||||
|
|
||||||
if not user_agents.get(browser):
|
user_agent_version = random.SystemRandom().choice(list(filteredAgents))
|
||||||
logging.error('Sorry "{}" browser User-Agent was not found.'.format(browser))
|
|
||||||
raise
|
|
||||||
|
|
||||||
user_agent = random.choice(user_agents.get(browser))
|
self.loadHeaders(user_agents, user_agent_version)
|
||||||
|
|
||||||
self.headers = user_agent.get('headers')
|
self.headers['User-Agent'] = random.SystemRandom().choice(filteredAgents[user_agent_version])
|
||||||
self.headers['User-Agent'] = random.choice(user_agent.get('User-Agent'))
|
|
||||||
|
|
||||||
if not kwargs.get('allow_brotli', False):
|
if not kwargs.get('allow_brotli', False) and 'br' in self.headers['Accept-Encoding']:
|
||||||
if 'br' in self.headers['Accept-Encoding']:
|
self.headers['Accept-Encoding'] = ','.join([
|
||||||
self.headers['Accept-Encoding'] = ','.join([encoding for encoding in self.headers['Accept-Encoding'].split(',') if encoding.strip() != 'br']).strip()
|
encoding for encoding in self.headers['Accept-Encoding'].split(',') if encoding.strip() != 'br'
|
||||||
|
]).strip()
|
||||||
|
File diff suppressed because it is too large
Load Diff
Loading…
Reference in new issue