[
  {
    "path": ".gitattributes",
    "content": "###############################################################################\n# Set default behavior to automatically normalize line endings.\n###############################################################################\n* text=auto\n\n###############################################################################\n# Set default behavior for command prompt diff.\n#\n# This is need for earlier builds of msysgit that does not have it on by\n# default for csharp files.\n# Note: This is only used by command line\n###############################################################################\n#*.cs     diff=csharp\n\n###############################################################################\n# Set the merge driver for project and solution files\n#\n# Merging from the command prompt will add diff markers to the files if there\n# are conflicts (Merging from VS is not affected by the settings below, in VS\n# the diff markers are never inserted). Diff markers may cause the following \n# file extensions to fail to load in VS. An alternative would be to treat\n# these files as binary and thus will always conflict and require user\n# intervention with every merge. To do so, just uncomment the entries below\n###############################################################################\n#*.sln       merge=binary\n#*.csproj    merge=binary\n#*.vbproj    merge=binary\n#*.vcxproj   merge=binary\n#*.vcproj    merge=binary\n#*.dbproj    merge=binary\n#*.fsproj    merge=binary\n#*.lsproj    merge=binary\n#*.wixproj   merge=binary\n#*.modelproj merge=binary\n#*.sqlproj   merge=binary\n#*.wwaproj   merge=binary\n\n###############################################################################\n# behavior for image files\n#\n# image files are treated as binary by default.\n###############################################################################\n#*.jpg   binary\n#*.png   binary\n#*.gif   binary\n\n###############################################################################\n# diff behavior for common document formats\n# \n# Convert binary document formats to text before diffing them. This feature\n# is only available from the command line. Turn it on by uncommenting the \n# entries below.\n###############################################################################\n#*.doc   diff=astextplain\n#*.DOC   diff=astextplain\n#*.docx  diff=astextplain\n#*.DOCX  diff=astextplain\n#*.dot   diff=astextplain\n#*.DOT   diff=astextplain\n#*.pdf   diff=astextplain\n#*.PDF   diff=astextplain\n#*.rtf   diff=astextplain\n#*.RTF   diff=astextplain\n"
  },
  {
    "path": ".gitignore",
    "content": "## Ignore Visual Studio temporary files, build results, and\n## files generated by popular Visual Studio add-ons.\n##\n## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore\n\n# User-specific files\n*.rsuser\n*.suo\n*.user\n*.userosscache\n*.sln.docstates\n\n# User-specific files (MonoDevelop/Xamarin Studio)\n*.userprefs\n\n# Build results\n[Dd]ebug/\n[Dd]ebugPublic/\n[Rr]elease/\n[Rr]eleases/\nx64/\nx86/\n[Aa][Rr][Mm]/\n[Aa][Rr][Mm]64/\nbld/\n[Bb]in/\n[Oo]bj/\n[Ll]og/\n\n# Visual Studio 2015/2017 cache/options directory\n.vs/\n# Uncomment if you have tasks that create the project's static files in wwwroot\n#wwwroot/\n\n# Visual Studio 2017 auto generated files\nGenerated\\ Files/\n\n# MSTest test Results\n[Tt]est[Rr]esult*/\n[Bb]uild[Ll]og.*\n\n# NUNIT\n*.VisualState.xml\nTestResult.xml\n\n# Build Results of an ATL Project\n[Dd]ebugPS/\n[Rr]eleasePS/\ndlldata.c\n\n# Benchmark Results\nBenchmarkDotNet.Artifacts/\n\n# .NET Core\nproject.lock.json\nproject.fragment.lock.json\nartifacts/\n\n# StyleCop\nStyleCopReport.xml\n\n# Files built by Visual Studio\n*_i.c\n*_p.c\n*_h.h\n*.ilk\n*.meta\n*.obj\n*.iobj\n*.pch\n*.pdb\n*.ipdb\n*.pgc\n*.pgd\n*.rsp\n*.sbr\n*.tlb\n*.tli\n*.tlh\n*.tmp\n*.tmp_proj\n*_wpftmp.csproj\n*.log\n*.vspscc\n*.vssscc\n.builds\n*.pidb\n*.svclog\n*.scc\n\n# Chutzpah Test files\n_Chutzpah*\n\n# Visual C++ cache files\nipch/\n*.aps\n*.ncb\n*.opendb\n*.opensdf\n*.sdf\n*.cachefile\n*.VC.db\n*.VC.VC.opendb\n\n# Visual Studio profiler\n*.psess\n*.vsp\n*.vspx\n*.sap\n\n# Visual Studio Trace Files\n*.e2e\n\n# TFS 2012 Local Workspace\n$tf/\n\n# Guidance Automation Toolkit\n*.gpState\n\n# ReSharper is a .NET coding add-in\n_ReSharper*/\n*.[Rr]e[Ss]harper\n*.DotSettings.user\n\n# JustCode is a .NET coding add-in\n.JustCode\n\n# TeamCity is a build add-in\n_TeamCity*\n\n# DotCover is a Code Coverage Tool\n*.dotCover\n\n# AxoCover is a Code Coverage Tool\n.axoCover/*\n!.axoCover/settings.json\n\n# Visual Studio code coverage results\n*.coverage\n*.coveragexml\n\n# NCrunch\n_NCrunch_*\n.*crunch*.local.xml\nnCrunchTemp_*\n\n# MightyMoose\n*.mm.*\nAutoTest.Net/\n\n# Web workbench (sass)\n.sass-cache/\n\n# Installshield output folder\n[Ee]xpress/\n\n# DocProject is a documentation generator add-in\nDocProject/buildhelp/\nDocProject/Help/*.HxT\nDocProject/Help/*.HxC\nDocProject/Help/*.hhc\nDocProject/Help/*.hhk\nDocProject/Help/*.hhp\nDocProject/Help/Html2\nDocProject/Help/html\n\n# Click-Once directory\npublish/\n\n# Publish Web Output\n*.[Pp]ublish.xml\n*.azurePubxml\n# Note: Comment the next line if you want to checkin your web deploy settings,\n# but database connection strings (with potential passwords) will be unencrypted\n*.pubxml\n*.publishproj\n\n# Microsoft Azure Web App publish settings. Comment the next line if you want to\n# checkin your Azure Web App publish settings, but sensitive information contained\n# in these scripts will be unencrypted\nPublishScripts/\n\n# NuGet Packages\n*.nupkg\n# The packages folder can be ignored because of Package Restore\n**/[Pp]ackages/*\n# except build/, which is used as an MSBuild target.\n!**/[Pp]ackages/build/\n# Uncomment if necessary however generally it will be regenerated when needed\n#!**/[Pp]ackages/repositories.config\n# NuGet v3's project.json files produces more ignorable files\n*.nuget.props\n*.nuget.targets\n\n# Microsoft Azure Build Output\ncsx/\n*.build.csdef\n\n# Microsoft Azure Emulator\necf/\nrcf/\n\n# Windows Store app package directories and files\nAppPackages/\nBundleArtifacts/\nPackage.StoreAssociation.xml\n_pkginfo.txt\n*.appx\n\n# Visual Studio cache files\n# files ending in .cache can be ignored\n*.[Cc]ache\n# but keep track of directories ending in .cache\n!?*.[Cc]ache/\n\n# Others\nClientBin/\n~$*\n*~\n*.dbmdl\n*.dbproj.schemaview\n*.jfm\n*.pfx\n*.publishsettings\norleans.codegen.cs\n\n# Including strong name files can present a security risk\n# (https://github.com/github/gitignore/pull/2483#issue-259490424)\n#*.snk\n\n# Since there are multiple workflows, uncomment next line to ignore bower_components\n# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)\n#bower_components/\n\n# RIA/Silverlight projects\nGenerated_Code/\n\n# Backup & report files from converting an old project file\n# to a newer Visual Studio version. Backup files are not needed,\n# because we have git ;-)\n_UpgradeReport_Files/\nBackup*/\nUpgradeLog*.XML\nUpgradeLog*.htm\nServiceFabricBackup/\n*.rptproj.bak\n\n# SQL Server files\n*.mdf\n*.ldf\n*.ndf\n\n# Business Intelligence projects\n*.rdl.data\n*.bim.layout\n*.bim_*.settings\n*.rptproj.rsuser\n*- Backup*.rdl\n\n# Microsoft Fakes\nFakesAssemblies/\n\n# GhostDoc plugin setting file\n*.GhostDoc.xml\n\n# Node.js Tools for Visual Studio\n.ntvs_analysis.dat\nnode_modules/\n\n# Visual Studio 6 build log\n*.plg\n\n# Visual Studio 6 workspace options file\n*.opt\n\n# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)\n*.vbw\n\n# Visual Studio LightSwitch build output\n**/*.HTMLClient/GeneratedArtifacts\n**/*.DesktopClient/GeneratedArtifacts\n**/*.DesktopClient/ModelManifest.xml\n**/*.Server/GeneratedArtifacts\n**/*.Server/ModelManifest.xml\n_Pvt_Extensions\n\n# Paket dependency manager\n.paket/paket.exe\npaket-files/\n\n# FAKE - F# Make\n.fake/\n\n# JetBrains Rider\n.idea/\n*.sln.iml\n\n# CodeRush personal settings\n.cr/personal\n\n# Python Tools for Visual Studio (PTVS)\n__pycache__/\n*.pyc\n\n# Cake - Uncomment if you are using it\n# tools/**\n# !tools/packages.config\n\n# Tabs Studio\n*.tss\n\n# Telerik's JustMock configuration file\n*.jmconfig\n\n# BizTalk build output\n*.btp.cs\n*.btm.cs\n*.odx.cs\n*.xsd.cs\n\n# OpenCover UI analysis results\nOpenCover/\n\n# Azure Stream Analytics local run output\nASALocalRun/\n\n# MSBuild Binary and Structured Log\n*.binlog\n\n# NVidia Nsight GPU debugger configuration file\n*.nvuser\n\n# MFractors (Xamarin productivity tool) working folder\n.mfractor/\n\n# Local History for Visual Studio\n.localhistory/\n\n# BeatPulse healthcheck temp database\nhealthchecksdb"
  },
  {
    "path": "LICENSE.md",
    "content": "GNU General Public License\n==========================\n\n_Version 3, 29 June 2007_  \n_Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_\n\nEveryone is permitted to copy and distribute verbatim copies of this license\ndocument, but changing it is not allowed.\n\n## Preamble\n\nThe GNU General Public License is a free, copyleft license for software and other\nkinds of works.\n\nThe licenses for most software and other practical works are designed to take away\nyour freedom to share and change the works. By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change all versions of a\nprogram--to make sure it remains free software for all its users. We, the Free\nSoftware Foundation, use the GNU General Public License for most of our software; it\napplies also to any other work released this way by its authors. You can apply it to\nyour programs, too.\n\nWhen we speak of free software, we are referring to freedom, not price. Our General\nPublic Licenses are designed to make sure that you have the freedom to distribute\ncopies of free software (and charge for them if you wish), that you receive source\ncode or can get it if you want it, that you can change the software or use pieces of\nit in new free programs, and that you know you can do these things.\n\nTo protect your rights, we need to prevent others from denying you these rights or\nasking you to surrender the rights. Therefore, you have certain responsibilities if\nyou distribute copies of the software, or if you modify it: responsibilities to\nrespect the freedom of others.\n\nFor example, if you distribute copies of such a program, whether gratis or for a fee,\nyou must pass on to the recipients the same freedoms that you received. You must make\nsure that they, too, receive or can get the source code. And you must show them these\nterms so they know their rights.\n\nDevelopers that use the GNU GPL protect your rights with two steps: **(1)** assert\ncopyright on the software, and **(2)** offer you this License giving you legal permission\nto copy, distribute and/or modify it.\n\nFor the developers' and authors' protection, the GPL clearly explains that there is\nno warranty for this free software. For both users' and authors' sake, the GPL\nrequires that modified versions be marked as changed, so that their problems will not\nbe attributed erroneously to authors of previous versions.\n\nSome devices are designed to deny users access to install or run modified versions of\nthe software inside them, although the manufacturer can do so. This is fundamentally\nincompatible with the aim of protecting users' freedom to change the software. The\nsystematic pattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable. Therefore, we have designed\nthis version of the GPL to prohibit the practice for those products. If such problems\narise substantially in other domains, we stand ready to extend this provision to\nthose domains in future versions of the GPL, as needed to protect the freedom of\nusers.\n\nFinally, every program is threatened constantly by software patents. States should\nnot allow patents to restrict development and use of software on general-purpose\ncomputers, but in those that do, we wish to avoid the special danger that patents\napplied to a free program could make it effectively proprietary. To prevent this, the\nGPL assures that patents cannot be used to render the program non-free.\n\nThe precise terms and conditions for copying, distribution and modification 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\nTo “modify” a work means to copy from or adapt all or part of the work in\na fashion requiring copyright permission, other than the making of an exact copy. The\nresulting work is called a “modified version” of the earlier work or a\nwork “based on” the earlier work.\n\nA “covered work” means either the unmodified Program or a work based on\nthe Program.\n\nTo “propagate” a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for infringement under\napplicable copyright law, except executing it on a computer or modifying a private\ncopy. Propagation includes copying, distribution (with or without modification),\nmaking available to the public, and in some countries other activities as well.\n\nTo “convey” a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user through a computer\nnetwork, with no transfer of a copy, is not conveying.\n\nAn interactive user interface displays “Appropriate Legal Notices” to the\nextent that it includes a convenient and prominently visible feature that **(1)**\ndisplays an appropriate copyright notice, and **(2)** tells the user that there is no\nwarranty for the work (except to the extent that warranties are provided), that\nlicensees may convey the work under this License, and how to view a copy of this\nLicense. If the 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\nThe “source code” for a work means the preferred form of the work for\nmaking modifications to it. “Object code” means any non-source form of a\nwork.\n\nA “Standard Interface” means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of interfaces\nspecified for a particular programming language, one that is widely used among\ndevelopers working in that language.\n\nThe “System Libraries” of an executable work include anything, other than\nthe work as a whole, that **(a)** is included in the normal form of packaging a Major\nComponent, but which is not part of that Major Component, and **(b)** serves only to\nenable use of the work with that Major Component, or to implement a Standard\nInterface for which an implementation is available to the public in source code form.\nA “Major Component”, in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system (if any) on which\nthe executable work runs, or a compiler used to produce the work, or an object code\ninterpreter used to run it.\n\nThe “Corresponding Source” for a work in object code form means all the\nsource code needed to generate, install, and (for an executable work) run the object\ncode and to modify the work, including scripts to control those activities. However,\nit does not include the work's System Libraries, or general-purpose tools or\ngenerally available free programs which are used unmodified in performing those\nactivities but which are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for the work, and\nthe source code for shared libraries and dynamically linked subprograms that the work\nis specifically designed to require, such as by intimate data communication or\ncontrol flow between those subprograms and other parts of the work.\n\nThe Corresponding Source need not include anything that users can regenerate\nautomatically from other parts of the Corresponding Source.\n\nThe Corresponding Source for a work in source code form is that same work.\n\n### 2. Basic Permissions\n\nAll rights granted under this License are granted for the term of copyright on the\nProgram, and are irrevocable provided the stated conditions are met. This License\nexplicitly affirms your unlimited permission to run the unmodified Program. The\noutput from running a covered work is covered by this License only if the output,\ngiven its content, constitutes a covered work. This License acknowledges your rights\nof fair use or other equivalent, as provided by copyright law.\n\nYou may make, run and propagate covered works that you do not convey, without\nconditions so long as your license otherwise remains in force. You may convey covered\nworks to others for the sole purpose of having them make modifications exclusively\nfor you, or provide you with facilities for running those works, provided that you\ncomply with the terms of this License in conveying all material for which you do not\ncontrol copyright. Those thus making or running the covered works for you must do so\nexclusively on your behalf, under your direction and control, on terms that prohibit\nthem from making any copies of your copyrighted material outside their relationship\nwith you.\n\nConveying under any other circumstances is permitted solely under the conditions\nstated below. Sublicensing is not allowed; section 10 makes it unnecessary.\n\n### 3. Protecting Users' Legal Rights From Anti-Circumvention Law\n\nNo covered work shall be deemed part of an effective technological measure under any\napplicable law fulfilling obligations under article 11 of the WIPO copyright treaty\nadopted on 20 December 1996, or similar laws prohibiting or restricting circumvention\nof such measures.\n\nWhen you convey a covered work, you waive any legal power to forbid circumvention of\ntechnological measures to the extent such circumvention is effected by exercising\nrights under this License with respect to the covered work, and you disclaim any\nintention to limit operation or modification of the work as a means of enforcing,\nagainst the work's users, your or third parties' legal rights to forbid circumvention\nof technological measures.\n\n### 4. Conveying Verbatim Copies\n\nYou may convey verbatim copies of the Program's source code as you receive it, in any\nmedium, provided that you conspicuously and appropriately publish on each copy an\nappropriate copyright notice; keep intact all notices stating that this License and\nany non-permissive terms added in accord with section 7 apply to the code; keep\nintact all notices of the absence of any warranty; and give all recipients a copy of\nthis License along with the Program.\n\nYou may charge any price or no price for each copy that you convey, and you may offer\nsupport or warranty protection for a fee.\n\n### 5. Conveying Modified Source Versions\n\nYou may convey a work based on the Program, or the modifications to produce it from\nthe Program, in the form of source code under the terms of section 4, provided that\nyou also meet all of these conditions:\n\n* **a)** The work must carry prominent notices stating that you modified it, and giving a\nrelevant date.\n* **b)** The work must carry prominent notices stating that it is released under this\nLicense and any conditions added under section 7. This requirement modifies the\nrequirement in section 4 to “keep intact all notices”.\n* **c)** You must license the entire work, as a whole, under this License to anyone who\ncomes into possession of a copy. This License will therefore apply, along with any\napplicable section 7 additional terms, to the whole of the work, and all its parts,\nregardless of how they are packaged. This License gives no permission to license the\nwork in any other way, but it does not invalidate such permission if you have\nseparately received it.\n* **d)** If the work has interactive user interfaces, each must display Appropriate Legal\nNotices; however, if the Program has interactive interfaces that do not display\nAppropriate Legal Notices, your work need not make them do so.\n\nA compilation of a covered work with other separate and independent works, which are\nnot by their nature extensions of the covered work, and which are not combined with\nit such as to form a larger program, in or on a volume of a storage or distribution\nmedium, is called an “aggregate” if the compilation and its resulting\ncopyright are not used to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit. Inclusion of a covered work in an aggregate\ndoes not cause this License to apply to the other parts of the aggregate.\n\n### 6. Conveying Non-Source Forms\n\nYou may convey a covered work in object code form under the terms of sections 4 and\n5, provided that you also convey the machine-readable Corresponding Source under the\nterms of this License, in one of these ways:\n\n* **a)** Convey the object code in, or embodied in, a physical product (including a\nphysical distribution medium), accompanied by the Corresponding Source fixed on a\ndurable physical medium customarily used for software interchange.\n* **b)** Convey the object code in, or embodied in, a physical product (including a\nphysical distribution medium), accompanied by a written offer, valid for at least\nthree years and valid for as long as you offer spare parts or customer support for\nthat product model, to give anyone who possesses the object code either **(1)** a copy of\nthe Corresponding Source for all the software in the product that is covered by this\nLicense, on a durable physical medium customarily used for software interchange, for\na price no more than your reasonable cost of physically performing this conveying of\nsource, or **(2)** access to copy the Corresponding Source from a network server at no\ncharge.\n* **c)** Convey individual copies of the object code with a copy of the written offer to\nprovide the Corresponding Source. This alternative is allowed only occasionally and\nnoncommercially, and only if you received the object code with such an offer, in\naccord with subsection 6b.\n* **d)** Convey the object code by offering access from a designated place (gratis or for\na charge), and offer equivalent access to the Corresponding Source in the same way\nthrough the same place at no further charge. You need not require recipients to copy\nthe Corresponding Source along with the object code. If the place to copy the object\ncode is a network server, the Corresponding Source may be on a different server\n(operated by you or a third party) that supports equivalent copying facilities,\nprovided you maintain clear directions next to the object code saying where to find\nthe Corresponding Source. Regardless of what server hosts the Corresponding Source,\nyou remain obligated to ensure that it is available for as long as needed to satisfy\nthese requirements.\n* **e)** Convey the object code using peer-to-peer transmission, provided you inform\nother peers where the object code and Corresponding Source of the work are being\noffered to the general public at no charge under subsection 6d.\n\nA separable portion of the object code, whose source code is excluded from the\nCorresponding Source as a System Library, need not be included in conveying the\nobject code work.\n\nA “User Product” is either **(1)** a “consumer product”, which\nmeans any tangible personal property which is normally used for personal, family, or\nhousehold purposes, or **(2)** anything designed or sold for incorporation into a\ndwelling. In determining whether a product is a consumer product, doubtful cases\nshall be resolved in favor of coverage. For a particular product received by a\nparticular user, “normally used” refers to a typical or common use of\nthat class of product, regardless of the status of the particular user or of the way\nin which the particular user actually uses, or expects or is expected to use, the\nproduct. A product is a consumer product regardless of whether the product has\nsubstantial commercial, 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 and execute\nmodified versions of a covered work in that User Product from a modified version of\nits Corresponding Source. The information must suffice to ensure that the continued\nfunctioning of the modified object code is in no case prevented or interfered with\nsolely because modification has been made.\n\nIf you convey an object code work under this section in, or with, or specifically for\nuse in, a User Product, and the conveying occurs as part of a transaction in which\nthe right of possession and use of the User Product is transferred to the recipient\nin perpetuity or for a fixed term (regardless of how the transaction is\ncharacterized), the Corresponding Source conveyed under this section must be\naccompanied by the Installation Information. But this requirement does not apply if\nneither you nor any third party retains the ability to install modified object code\non the User Product (for example, the work has been installed in ROM).\n\nThe requirement to provide Installation Information does not include a requirement to\ncontinue to provide support service, warranty, or updates for a work that has been\nmodified or installed by the recipient, or for the User Product in which it has been\nmodified or installed. Access to a network may be denied when the modification itself\nmaterially and adversely affects the operation of the network or violates the rules\nand protocols for communication across the network.\n\nCorresponding Source conveyed, and Installation Information provided, in accord with\nthis section must be in a format that is publicly documented (and with an\nimplementation available to the public in source code form), and must require no\nspecial password or key for unpacking, 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. Additional\npermissions that are applicable to the entire Program shall be treated as though they\nwere included in this License, to the extent that they are valid under applicable\nlaw. If additional permissions apply only to part of the Program, that part may be\nused separately under those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\nWhen you convey a copy of a covered work, you may at your option remove any\nadditional permissions from that copy, or from any part of it. (Additional\npermissions may be written to require their own removal in certain cases when you\nmodify the work.) You may place additional permissions on material, added by you to a\ncovered work, for which you have or can give appropriate copyright permission.\n\nNotwithstanding any other provision of this License, for material you add to a\ncovered work, you may (if authorized by the copyright holders of that material)\nsupplement the terms of this License with terms:\n\n* **a)** Disclaiming warranty or limiting liability differently from the terms of\nsections 15 and 16 of this License; or\n* **b)** Requiring preservation of specified reasonable legal notices or author\nattributions in that material or in the Appropriate Legal Notices displayed by works\ncontaining it; or\n* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that\nmodified versions of such material be marked in reasonable ways as different from the\noriginal version; or\n* **d)** Limiting the use for publicity purposes of names of licensors or authors of the\nmaterial; or\n* **e)** Declining to grant rights under trademark law for use of some trade names,\ntrademarks, or service marks; or\n* **f)** Requiring indemnification of licensors and authors of that material by anyone\nwho conveys the material (or modified versions of it) with contractual assumptions of\nliability to the recipient, for any liability that these contractual assumptions\ndirectly impose on those licensors and authors.\n\nAll other non-permissive additional terms are considered “further\nrestrictions” within the meaning of section 10. If the Program as you received\nit, or any part of it, contains a notice stating that it is governed by this License\nalong with a term that is a further restriction, you may remove that term. If a\nlicense document contains a further restriction but permits relicensing or conveying\nunder this License, you may add to a covered work material governed by the terms of\nthat license document, provided that the further restriction does not survive such\nrelicensing or conveying.\n\nIf you add terms to a covered work in accord with this section, you must place, in\nthe relevant source files, a statement of the additional terms that apply to those\nfiles, or a notice indicating where to find the applicable terms.\n\nAdditional terms, permissive or non-permissive, may be stated in the form of a\nseparately written license, or stated as exceptions; the above requirements apply\neither way.\n\n### 8. Termination\n\nYou may not propagate or modify a covered work except as expressly provided under\nthis License. Any attempt otherwise to propagate or modify it is void, and will\nautomatically terminate your rights under this License (including any patent licenses\ngranted under the third paragraph of section 11).\n\nHowever, if you cease all violation of this License, then your license from a\nparticular copyright holder is reinstated **(a)** provisionally, unless and until the\ncopyright holder explicitly and finally terminates your license, and **(b)** permanently,\nif the copyright holder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\nMoreover, your license from a particular copyright holder is reinstated permanently\nif the copyright holder notifies you of the violation by some reasonable means, this\nis the first time you have received notice of violation of this License (for any\nwork) from that copyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\nTermination of your rights under this section does not terminate the licenses of\nparties who have received copies or rights from you under this License. If your\nrights have been terminated and not permanently reinstated, you do not qualify to\nreceive new licenses for the same material under section 10.\n\n### 9. Acceptance Not Required for Having Copies\n\nYou are not required to accept this License in order to receive or run a copy of the\nProgram. Ancillary propagation of a covered work occurring solely as a consequence of\nusing peer-to-peer transmission to receive a copy likewise does not require\nacceptance. However, nothing other than this License grants you permission to\npropagate or modify any covered work. These actions infringe copyright if you do not\naccept this License. Therefore, by modifying or propagating a covered work, you\nindicate your acceptance of this License to do so.\n\n### 10. Automatic Licensing of Downstream Recipients\n\nEach time you convey a covered work, the recipient automatically receives a license\nfrom the original licensors, to run, modify and propagate that work, subject to this\nLicense. You are not responsible for enforcing compliance by third parties with this\nLicense.\n\nAn “entity transaction” is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an organization, or\nmerging organizations. If propagation of a covered work results from an entity\ntransaction, each party to that transaction who receives a copy of the work also\nreceives whatever licenses to the work the party's predecessor in interest had or\ncould give under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if the predecessor\nhas it or can get it with reasonable efforts.\n\nYou may not impose any further restrictions on the exercise of the rights granted or\naffirmed under this License. For example, you may not impose a license fee, royalty,\nor other charge for exercise of rights granted under this License, and you may not\ninitiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging\nthat any patent claim is infringed by making, using, selling, offering for sale, or\nimporting the Program or any portion of it.\n\n### 11. Patents\n\nA “contributor” is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The work thus\nlicensed is called the contributor's “contributor version”.\n\nA contributor's “essential patent claims” are all patent claims owned or\ncontrolled by the contributor, whether already acquired or hereafter acquired, that\nwould be infringed by some manner, permitted by this License, of making, using, or\nselling its contributor version, but do not include claims that would be infringed\nonly as a consequence of further modification of the contributor version. For\npurposes of this definition, “control” includes the right to grant patent\nsublicenses in a manner consistent with the requirements of this License.\n\nEach contributor grants you a non-exclusive, worldwide, royalty-free patent license\nunder the contributor's essential patent claims, to make, use, sell, offer for sale,\nimport and otherwise run, modify and propagate the contents of its contributor\nversion.\n\nIn the following three paragraphs, a “patent license” is any express\nagreement or commitment, however denominated, not to enforce a patent (such as an\nexpress permission to practice a patent or covenant not to sue for patent\ninfringement). To “grant” such a patent license to a party means to make\nsuch an agreement or commitment not to enforce a patent against the party.\n\nIf you convey a covered work, knowingly relying on a patent license, and the\nCorresponding Source of the work is not available for anyone to copy, free of charge\nand under the terms of this License, through a publicly available network server or\nother readily accessible means, then you must either **(1)** cause the Corresponding\nSource to be so available, or **(2)** arrange to deprive yourself of the benefit of the\npatent license for this particular work, or **(3)** arrange, in a manner consistent with\nthe requirements of this License, to extend the patent license to downstream\nrecipients. “Knowingly relying” means you have actual knowledge that, but\nfor the patent license, your conveying the covered work in a country, or your\nrecipient's use of the covered work in a country, would infringe one or more\nidentifiable patents in that country that you have reason to believe are valid.\n\nIf, pursuant to or in connection with a single transaction or arrangement, you\nconvey, or propagate by procuring conveyance of, a covered work, and grant a patent\nlicense to some of the parties receiving the covered work authorizing them to use,\npropagate, modify or convey a specific copy of the covered work, then the patent\nlicense you grant is automatically extended to all recipients of the covered work and\nworks based on it.\n\nA patent license is “discriminatory” if it does not include within the\nscope of its coverage, prohibits the exercise of, or is conditioned on the\nnon-exercise of one or more of the rights that are specifically granted under this\nLicense. You may not convey a covered work if you are a party to an arrangement with\na third party that is in the business of distributing software, under which you make\npayment to the third party based on the extent of your activity of conveying the\nwork, and under which the third party grants, to any of the parties who would receive\nthe covered work from you, a discriminatory patent license **(a)** in connection with\ncopies of the covered work conveyed by you (or copies made from those copies), or **(b)**\nprimarily for and in connection with specific products or compilations that contain\nthe covered work, unless you entered into that arrangement, or that patent license\nwas granted, prior to 28 March 2007.\n\nNothing in this License shall be construed as excluding or limiting any implied\nlicense or other defenses to infringement that may otherwise be available to you\nunder applicable patent law.\n\n### 12. No Surrender of Others' Freedom\n\nIf conditions are imposed on you (whether by court order, agreement or otherwise)\nthat contradict the conditions of this License, they do not excuse you from the\nconditions of this License. If you cannot convey a covered work so as to satisfy\nsimultaneously your obligations under this License and any other pertinent\nobligations, then as a consequence you may not convey it at all. For example, if you\nagree to terms that obligate you to collect a royalty for further conveying from\nthose to whom you convey the Program, the only way you could satisfy both those terms\nand this License would be to refrain entirely from conveying the Program.\n\n### 13. Use with the GNU Affero General Public License\n\nNotwithstanding any other provision of this License, you have permission to link or\ncombine any covered work with a work licensed under version 3 of the GNU Affero\nGeneral Public License into a single combined work, and to convey the resulting work.\nThe terms of this License will continue to apply to the part which is the covered\nwork, but the special requirements of the GNU Affero General Public License, section\n13, concerning interaction through a network will apply to the combination as such.\n\n### 14. Revised Versions of this License\n\nThe Free Software Foundation may publish revised and/or new versions of the GNU\nGeneral Public License from time to time. Such new versions will be similar in spirit\nto the present version, but may differ in detail to address new problems or concerns.\n\nEach version is given a distinguishing version number. If the Program specifies that\na certain numbered version of the GNU General Public License “or any later\nversion” applies to it, you have the option of following the terms and\nconditions either of that numbered version or of any later version published by the\nFree Software Foundation. If the Program does not specify a version number of the GNU\nGeneral Public License, you may choose any version ever published by the Free\nSoftware Foundation.\n\nIf the Program specifies that a proxy can decide which future versions of the GNU\nGeneral Public License can be used, that proxy's public statement of acceptance of a\nversion permanently authorizes you to choose that version for the Program.\n\nLater license versions may give you additional or different permissions. However, no\nadditional obligations are imposed on any author or copyright holder as a result of\nyour choosing to follow a later version.\n\n### 15. Disclaimer of Warranty\n\nTHERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.\nEXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER\nEXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE\nQUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE\nDEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n### 16. Limitation of Liability\n\nIN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY\nCOPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS\nPERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,\nINCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE\nPROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE\nOR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE\nWITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n### 17. Interpretation of Sections 15 and 16\n\nIf the disclaimer of warranty and limitation of liability provided above cannot be\ngiven local legal effect according to their terms, reviewing courts shall apply local\nlaw that most closely approximates an absolute waiver of all civil liability in\nconnection with the Program, unless a warranty or assumption of liability accompanies\na copy 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\nIf you develop a new program, and you want it to be of the greatest possible use to\nthe public, the best way to achieve this is to make it free software which everyone\ncan redistribute and change under these terms.\n\nTo do so, attach the following notices to the program. It is safest to attach them\nto the start of each source file to most effectively state the exclusion of warranty;\nand each file should have at least the “copyright” line and a pointer to\nwhere 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 <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program does terminal interaction, make it output a short notice like this\nwhen 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 parts of\nthe General Public License. Of course, your program's commands might be different;\nfor a GUI interface, you would use an “about box”.\n\nYou should also get your employer (if you work as a programmer) or school, if any, to\nsign a “copyright disclaimer” for the program, if necessary. For more\ninformation on this, and how to apply and follow the GNU GPL, see\n&lt;<http://www.gnu.org/licenses/>&gt;.\n\nThe GNU General Public License does not permit incorporating your program into\nproprietary programs. If your program is a subroutine library, you may consider it\nmore useful to permit linking proprietary applications with the library. If this is\nwhat you want to do, use the GNU Lesser General Public License instead of this\nLicense. But first, please read\n&lt;<http://www.gnu.org/philosophy/why-not-lgpl.html>&gt;.\n"
  },
  {
    "path": "Origami.sln",
    "content": "\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio Version 16\nVisualStudioVersion = 16.0.30114.105\nMinimumVisualStudioVersion = 10.0.40219.1\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Origami\", \"src\\Origami.csproj\", \"{3140478B-D5E1-455C-8CDB-B1CDA7A6FA94}\"\n\tProjectSection(ProjectDependencies) = postProject\n\t\t{760EF471-90B1-416D-8517-303FA04D49E1} = {760EF471-90B1-416D-8517-303FA04D49E1}\n\t\t{15B5CDAF-C6BE-45F7-9BC0-83E571161000} = {15B5CDAF-C6BE-45F7-9BC0-83E571161000}\n\tEndProjectSection\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Runtime\", \"Runtime\\Runtime.csproj\", \"{15B5CDAF-C6BE-45F7-9BC0-83E571161000}\"\nEndProject\nGlobal\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n\t\tDebug|Any CPU = Debug|Any CPU\n\t\tRelease|Any CPU = Release|Any CPU\n\tEndGlobalSection\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n\t\t{3140478B-D5E1-455C-8CDB-B1CDA7A6FA94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{3140478B-D5E1-455C-8CDB-B1CDA7A6FA94}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{3140478B-D5E1-455C-8CDB-B1CDA7A6FA94}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{3140478B-D5E1-455C-8CDB-B1CDA7A6FA94}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{15B5CDAF-C6BE-45F7-9BC0-83E571161000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{15B5CDAF-C6BE-45F7-9BC0-83E571161000}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{15B5CDAF-C6BE-45F7-9BC0-83E571161000}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{15B5CDAF-C6BE-45F7-9BC0-83E571161000}.Release|Any CPU.Build.0 = Release|Any CPU\n\tEndGlobalSection\n\tGlobalSection(SolutionProperties) = preSolution\n\t\tHideSolutionNode = FALSE\n\tEndGlobalSection\n\tGlobalSection(ExtensibilityGlobals) = postSolution\n\t\tSolutionGuid = {67324794-F67D-4BED-9E6C-405B60FA8C7C}\n\tEndGlobalSection\nEndGlobal\n"
  },
  {
    "path": "README.md",
    "content": "# <img width=\"64\" height=\"64\" valign=\"bottom\" src=\"https://img.icons8.com/color/96/000000/origami.png\">Origami \n**Packer compressing .net assemblies, (ab)using the PE format for data storage**\n\n## Usage\n\n       Origami.exe <file>\n       Origami.exe <file> <mode>\n#### Available modes:\n> **-dbg**\nUse PE headers debug directory for data storage\n\n> **-pes** Use additional PE Section (.origami) for data storage\n\n## How it works\n\nOrigami takes an input module (payload) which gets compressed and encrypted. The payload is then inserted into a, newly created, stub module along with a runtime loader for payload extraction. Depending on the chosen mode the payload is either placed in a new section along side the stubs metadata or hidden in the debug data entries of the stub. The new loader uses a direct pointer (VirtualAddress) to the payloads location, instead of traversing the PE header at runtime. To make the direct access possible I utilize Base Relocations and a customized module building routine in AsmResolver.\n\n\nSome improvements made in version 2:\n- NET Core support\n- Costura support\n- Simplified loader\n\n\n*This blog post is based on an [older release of origami](https://github.com/dr4k0nia/Origami/tree/parsing-runtime) which uses a different runtime and packing process. I will write an updated blog post when I find the time*\n<br>\n~For a detailed explanation of the stub code check out [my blog post](https://dr4k0nia.github.io/posts/Writing-a-Packer/)~\n\n\n## Dependencies\n- [AsmResolver](https://github.com/Washi1337/AsmResolver) by Washi\n\n*Logo by [icons8](https://icons8.com)*\n"
  },
  {
    "path": "Runtime/RelocLoader.cs",
    "content": "﻿using System.Diagnostics.CodeAnalysis;\nusing System.IO.Compression;\nusing System.Reflection;\n\nnamespace Runtime\n{\n    [SuppressMessage(\"ReSharper\", \"InconsistentNaming\")]\n    internal static unsafe class RelocLoader\n    {\n        [STAThread]\n        private static void Main(string[] args)\n        {\n            // Placeholder for relocated VirtualAddress\n            byte* basePtr = (byte*) 6969696969L;\n\n            // Placeholder for payload size\n            byte[] buffer = new byte[0x1337c0de];\n\n            string key = typeof(RelocLoader).Assembly.EntryPoint.Name;\n\n            fixed (byte* rawData = &buffer[0])\n            {\n                for (int i = 0; i < buffer.Length; i++)\n                {\n                    *(rawData + i) = (byte) (*(basePtr + i) ^ key[i % key.Length]);\n                }\n            }\n\n            // Decompress data from the buffer\n            using var origin = new MemoryStream(buffer);\n            using var destination = new MemoryStream();\n            using var deflateStream = new DeflateStream(origin, CompressionMode.Decompress);\n            deflateStream.CopyTo(destination);\n\n            // Load assembly using the previously decompressed data\n            var asm = Assembly.Load(destination.GetBuffer());\n\n            MethodBase entryPoint = asm.EntryPoint ??\n                                    throw new EntryPointNotFoundException(\n                                        \"Origami could not find a valid EntryPoint to invoke\");\n\n            object[] parameters = new object[entryPoint.GetParameters().Length];\n            if (parameters.Length != 0)\n                parameters[0] = args;\n            entryPoint.Invoke(null, parameters);\n        }\n    }\n}\n"
  },
  {
    "path": "Runtime/Runtime.csproj",
    "content": "<Project Sdk=\"Microsoft.NET.Sdk\">\n\n    <PropertyGroup>\n        <TargetFramework>netstandard2.0</TargetFramework>\n        <ImplicitUsings>enable</ImplicitUsings>\n        <Nullable>enable</Nullable>\n        <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n        <LangVersion>latest</LangVersion>\n    </PropertyGroup>\n\n    <PropertyGroup Condition=\" '$(Configuration)' == 'Debug' \">\n      <OutputPath>bin\\Debug\\</OutputPath>\n    </PropertyGroup>\n\n    <ItemGroup>\n      <Compile Remove=\"src\\**\" />\n    </ItemGroup>\n\n    <ItemGroup>\n      <EmbeddedResource Remove=\"src\\**\" />\n    </ItemGroup>\n\n    <ItemGroup>\n      <None Remove=\"src\\**\" />\n    </ItemGroup>\n\n</Project>\n"
  },
  {
    "path": "src/App.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n    <startup> \n        <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.7.2\" />\n    </startup>\n</configuration>"
  },
  {
    "path": "src/Origami.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n\n    <PropertyGroup>\n        <OutputType>Exe</OutputType>\n        <TargetFramework>net472</TargetFramework>\n        <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n        <LangVersion>latest</LangVersion>\n    </PropertyGroup>\n\n   <PropertyGroup>\n    <StartupObject>Origami.Program</StartupObject>\n  </PropertyGroup>\n\n    <ItemGroup>\n      <Folder Include=\"Properties\" />\n    </ItemGroup>\n\n    <ItemGroup>\n      <PackageReference Include=\"AsmResolver.DotNet\" Version=\"4.11.2\" />\n    </ItemGroup>\n\n</Project>"
  },
  {
    "path": "src/Packers/CustomManagedPEFileBuilder.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing AsmResolver;\nusing AsmResolver.PE;\nusing AsmResolver.PE.Debug;\nusing AsmResolver.PE.Debug.CodeView;\nusing AsmResolver.PE.DotNet;\nusing AsmResolver.PE.DotNet.Builder;\nusing AsmResolver.PE.DotNet.Cil;\nusing AsmResolver.PE.DotNet.Metadata.Tables;\nusing AsmResolver.PE.DotNet.Metadata.Tables.Rows;\nusing AsmResolver.PE.File;\nusing AsmResolver.PE.File.Headers;\nusing AsmResolver.PE.Imports;\nusing AsmResolver.PE.Relocations;\n\nnamespace Origami.Packers;\n\npublic sealed class CustomManagedPEFileBuilder : ManagedPEFileBuilder\n{\n    private readonly Mode _mode;\n    private readonly DataSegment _payload;\n    private readonly MetadataToken _token;\n    private readonly RelocPacker.Patches _patches;\n\n    public CustomManagedPEFileBuilder(Mode mode, DataSegment payload, MetadataToken token, RelocPacker.Patches patches)\n    {\n        _mode = mode;\n        _payload = payload;\n        _token = token;\n        _patches = patches;\n    }\n\n\n    // Modified to add Base Relocations and patch RVAs in the CIL method body of the loader\n    public override PEFile CreateFile(IPEImage image)\n    {\n        // Get raw method body of the loader entrypoint\n        var rawBody = (CilRawMethodBody) image.DotNetDirectory.Metadata\n            .GetStream<TablesStream>()\n            .GetTable<MethodDefinitionRow>()\n            .GetByRid(_token.Rid)\n            .Body\n            .GetSegment();\n\n        var oldBody = rawBody.Code;\n\n        var newBody = new DataSegment(oldBody.CreateReader().ReadToEnd());\n        rawBody.Code = newBody;\n\n        // Add BaseRelocation to use VirtualAddress\n        var reloc = image.PEKind == OptionalHeaderMagic.Pe32\n            ? new BaseRelocation(RelocationType.HighLow, newBody.ToReference(_patches.OffsetVA))\n            : new BaseRelocation(RelocationType.Dir64, newBody.ToReference(_patches.OffsetVA));\n        image.Relocations.Add(reloc);\n\n        var file = base.CreateFile(image);\n        file.AlignSections();\n\n        byte[] body = newBody.Data;\n\n        // Patch placeholder for VirtualAddress of payload\n        BitConverter.GetBytes(_payload.Rva + image.ImageBase).CopyTo(body, _patches.OffsetVA);\n\n        // Patch placeholder for size of buffer\n        BitConverter.GetBytes(_payload.GetPhysicalSize()).CopyTo(body, _patches.OffsetSize);\n\n        return file;\n    }\n\n    private PESection CreatePackerSection(IPEImage image, ManagedPEBuilderContext context)\n    {\n        ProcessRvasInMetadataTables(context);\n        var contents = new SegmentBuilder();\n\n        contents.Add(_payload);\n\n        contents.Add(context.DotNetSegment);\n\n        return new PESection(\".origami\",\n            SectionFlags.ContentInitializedData | SectionFlags.MemoryRead)\n        {\n            Contents = contents\n        };\n    }\n\n    protected override PESection CreateTextSection(IPEImage image, ManagedPEBuilderContext context)\n    {\n        CreateImportDirectory(image, context);\n        CreateDebugDirectory(image, context);\n\n        var contents = new SegmentBuilder();\n        if (context.ImportDirectory.Count > 0)\n            contents.Add(context.ImportDirectory.ImportAddressDirectory);\n\n        // Add the DotNetSegment normally when using the DebugDataEntry payload\n        if (_mode == Mode.DebugDataEntry)\n            contents.Add(context.DotNetSegment);\n\n        if (context.ImportDirectory.Count > 0)\n            contents.Add(context.ImportDirectory);\n\n        if (!context.ExportDirectory.IsEmpty)\n            contents.Add(context.ExportDirectory);\n\n        if (!context.DebugDirectory.IsEmpty)\n        {\n            contents.Add(context.DebugDirectory);\n            contents.Add(context.DebugDirectory.ContentsTable);\n        }\n\n        if (context.Bootstrapper.HasValue)\n            contents.Add(context.Bootstrapper.Value.Segment);\n\n        if (image.Exports is {Entries: {Count: > 0} entries})\n        {\n            for (int i = 0; i < entries.Count; i++)\n            {\n                var export = entries[i];\n                if (export.Address.IsBounded && export.Address.GetSegment() is { } segment)\n                    contents.Add(segment, 4);\n            }\n        }\n\n        return new PESection(\".text\",\n            SectionFlags.ContentCode | SectionFlags.MemoryExecute | SectionFlags.MemoryRead)\n        {\n            Contents = contents\n        };\n    }\n\n\n    // Add packer section injection\n    protected override IEnumerable<PESection> CreateSections(IPEImage image, ManagedPEBuilderContext context)\n    {\n        // Always create .text section.\n        var sections = new List<PESection>\n        {\n            CreateTextSection(image, context),\n        };\n\n        // Add .sdata section when necessary.\n        if (image.Exports is not null || image.DotNetDirectory?.VTableFixups is not null)\n            sections.Add(CreateSDataSection(image, context));\n\n        // Add .rsrc section when necessary.\n        if (image.Resources is not null && image.Resources.Entries.Count > 0)\n            sections.Add(CreateRsrcSection(image, context));\n\n        // Inject packer section if PESection payload was chosen\n        if (_mode == Mode.PESection)\n            sections.Add(CreatePackerSection(image, context));\n\n        // Collect all base relocations.\n        // Since the PE is rebuild in its entirety, all relocations that were originally in the PE are invalidated.\n        // Therefore, we filter out all relocations that were added by the reader.\n        var relocations = image.Relocations\n            .Where(r => r.Location is not PESegmentReference)\n            .ToList();\n\n        // Add relocations of the bootstrapper stub if necessary.\n        if (context.Bootstrapper.HasValue)\n            relocations.AddRange(context.Bootstrapper.Value.Relocations);\n\n        // Add .reloc section when necessary.\n        if (relocations.Count > 0)\n            sections.Add(CreateRelocSection(context, relocations));\n\n        return sections;\n    }\n\n    private static void CreateImportDirectory(IPEImage image, ManagedPEBuilderContext context)\n    {\n        bool importEntrypointRequired = context.Platform.IsClrBootstrapperRequired\n                                        || (image.DotNetDirectory!.Flags & DotNetDirectoryFlags.ILOnly) == 0;\n        string entrypointName = (image.Characteristics & Characteristics.Dll) != 0\n            ? \"_CorDllMain\"\n            : \"_CorExeMain\";\n\n        var modules = CollectImportedModules(image, importEntrypointRequired, entrypointName, out var entrypointSymbol);\n\n        foreach (var module in modules)\n            context.ImportDirectory.AddModule(module);\n\n        if (importEntrypointRequired)\n        {\n            if (entrypointSymbol is null)\n                throw new InvalidOperationException(\"Entrypoint symbol was required but not imported.\");\n\n            context.Bootstrapper = context.Platform.CreateThunkStub(image.ImageBase, entrypointSymbol);\n        }\n    }\n\n    private static List<IImportedModule> CollectImportedModules(\n        IPEImage image,\n        bool entryRequired,\n        string mscoreeEntryName,\n        out ImportedSymbol? entrypointSymbol)\n    {\n        var modules = new List<IImportedModule>();\n\n        IImportedModule? mscoreeModule = null;\n        entrypointSymbol = null;\n\n        foreach (var module in image.Imports)\n        {\n            // Check if the CLR entrypoint is already imported.\n            if (module.Name == \"mscoree.dll\")\n            {\n                mscoreeModule = module;\n\n                // Find entrypoint in this imported module.\n                if (entryRequired)\n                    entrypointSymbol = mscoreeModule.Symbols.FirstOrDefault(s => s.Name == mscoreeEntryName);\n\n                // Only include mscoree.dll if necessary.\n                if (entryRequired || module.Symbols.Count > 1)\n                    modules.Add(module);\n            }\n            else\n            {\n                // Imported module is some other module. Just add in its entirety.\n                modules.Add(module);\n            }\n        }\n\n        if (entryRequired)\n        {\n            // Add mscoree.dll if it wasn't imported yet.\n            if (mscoreeModule is null)\n            {\n                mscoreeModule = new ImportedModule(\"mscoree.dll\");\n                modules.Add(mscoreeModule);\n            }\n\n            // Add entrypoint sumbol if it wasn't imported yet.\n            if (entrypointSymbol is null)\n            {\n                entrypointSymbol = new ImportedSymbol(0, mscoreeEntryName);\n                mscoreeModule.Symbols.Add(entrypointSymbol);\n            }\n        }\n\n        return modules;\n    }\n\n\n    // Modified to inject fake RSDS DebugDataEntry and payload as custom DebugDataEntry\n    private void CreateDebugDirectory(IPEImage image, ManagedPEBuilderContext context)\n    {\n        for (int i = 0; i < image.DebugData.Count; i++)\n            context.DebugDirectory.AddEntry(image.DebugData[i]);\n\n        // Dont inject DebugData when PESection is used\n        if (_mode == Mode.PESection)\n            return;\n\n        // Add fake debug entry to hide the payload\n        var data = new RsdsDataSegment\n        {\n            // TODO randomization\n            Path = \"C:/Users/GLaDOS/The/Cake/Is/A/Lie.pdb\",\n            Guid = Guid.NewGuid(),\n            Age = 1\n        };\n        var entry = new DebugDataEntry(data)\n        {\n            TimeDateStamp = Utils.GetRandomTimestamp()\n        };\n        context.DebugDirectory.AddEntry(entry);\n\n        // Process RVAs and inject payload as custom DebugDataEntry\n        ProcessRvasInMetadataTables(context);\n        var segment = new CustomDebugDataSegment(DebugDataType.Unknown, _payload);\n        var payload = new DebugDataEntry(segment);\n\n        context.DebugDirectory.AddEntry(payload);\n    }\n\n    /// <summary>\n    /// Creates the .sdata section containing the exports and vtables directory of the new .NET PE file.\n    /// </summary>\n    /// <param name=\"image\">The image to build.</param>\n    /// <param name=\"context\">The working space of the builder.</param>\n    /// <returns>The section.</returns>\n    private PESection CreateSDataSection(IPEImage image, ManagedPEBuilderContext context)\n    {\n        var contents = new SegmentBuilder();\n\n        if (image.DotNetDirectory?.VTableFixups is { } fixups)\n        {\n            for (int i = 0; i < fixups.Count; i++)\n                contents.Add(fixups[i].Tokens);\n        }\n\n        if (image.Exports is {Entries: {Count: > 0}} exports)\n        {\n            context.ExportDirectory.AddDirectory(exports);\n            contents.Add(context.ExportDirectory, 4);\n        }\n\n        return new PESection(\n            \".sdata\",\n            SectionFlags.MemoryRead | SectionFlags.MemoryWrite | SectionFlags.ContentInitializedData,\n            contents);\n    }\n\n    private static void ProcessRvasInMetadataTables(ManagedPEBuilderContext context)\n    {\n        var dotNetSegment = context.DotNetSegment;\n        var tablesStream = dotNetSegment.DotNetDirectory.Metadata?.GetStream<TablesStream>();\n        if (tablesStream is null)\n            throw new ArgumentException(\"Image does not have a .NET metadata tables stream.\");\n\n        AddMethodBodiesToTable(dotNetSegment.MethodBodyTable, tablesStream);\n        AddFieldRvasToTable(context);\n    }\n\n    private static void AddMethodBodiesToTable(MethodBodyTableBuffer table, TablesStream tablesStream)\n    {\n        var methodTable = tablesStream.GetTable<MethodDefinitionRow>();\n        for (int i = 0; i < methodTable.Count; i++)\n        {\n            var methodRow = methodTable[i];\n\n            var bodySegment = GetMethodBodySegment(methodRow);\n            if (bodySegment is CilRawMethodBody cilBody)\n                table.AddCilBody(cilBody);\n            else if (bodySegment is not null)\n                table.AddNativeBody(bodySegment, 4); // TODO: maybe make customizable?\n            else\n                continue;\n\n            methodTable[i] = new MethodDefinitionRow(\n                bodySegment.ToReference(),\n                methodRow.ImplAttributes,\n                methodRow.Attributes,\n                methodRow.Name,\n                methodRow.Signature,\n                methodRow.ParameterList);\n        }\n    }\n\n    private static ISegment? GetMethodBodySegment(MethodDefinitionRow methodRow)\n    {\n        if (methodRow.Body.IsBounded)\n            return methodRow.Body.GetSegment();\n\n        if (methodRow.Body.CanRead)\n        {\n            if ((methodRow.ImplAttributes & MethodImplAttributes.CodeTypeMask) == MethodImplAttributes.IL)\n            {\n                var reader = methodRow.Body.CreateReader();\n                return CilRawMethodBody.FromReader(ThrowErrorListener.Instance, ref reader);\n            }\n\n            throw new NotImplementedException(\"Native unbounded method bodies cannot be reassembled yet.\");\n        }\n\n        return null;\n    }\n\n    private static void AddFieldRvasToTable(ManagedPEBuilderContext context)\n    {\n        var metadata = context.DotNetSegment.DotNetDirectory.Metadata;\n        var fieldRvaTable = metadata\n            !.GetStream<TablesStream>()\n            !.GetTable<FieldRvaRow>(TableIndex.FieldRva);\n\n        if (fieldRvaTable.Count == 0)\n            return;\n\n        var table = context.DotNetSegment.FieldRvaTable;\n        var reader = context.FieldRvaDataReader;\n\n        for (int i = 0; i < fieldRvaTable.Count; i++)\n        {\n            var data = reader.ResolveFieldData(ThrowErrorListener.Instance, metadata, fieldRvaTable[i]);\n            if (data is null)\n                continue;\n\n            table.Add(data);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Packers/IPacker.cs",
    "content": "﻿using System;\nusing System.Linq;\nusing AsmResolver.DotNet;\nusing AsmResolver.DotNet.Cloning;\nusing AsmResolver.PE.File.Headers;\n\nnamespace Origami.Packers\n{\n    public interface IPacker\n    {\n        void Execute();\n    }\n\n    public abstract class Packer : IPacker\n    {\n        protected Packer(byte[] payload, string outputPath)\n        {\n            Payload = payload;\n            OutputPath = outputPath;\n        }\n\n        protected byte[] Payload\n        {\n            get;\n        }\n\n        protected string OutputPath\n        {\n            get;\n        }\n\n        protected static ModuleDefinition CreateStub(ModuleDefinition originModule)\n        {\n            var stubModule =\n                new ModuleDefinition(originModule.Name,\n                    originModule.CorLibTypeFactory.CorLibScope.GetAssembly() as AssemblyReference);\n\n            bool isCoreApp = originModule.OriginalTargetRuntime.Name == \".NETCoreApp\";\n\n            originModule.Assembly.Modules.Insert(0, stubModule);\n\n            stubModule.FileCharacteristics = originModule.FileCharacteristics;\n            stubModule.DllCharacteristics = originModule.DllCharacteristics;\n            stubModule.EncBaseId = originModule.EncBaseId;\n            stubModule.EncId = originModule.EncId;\n            stubModule.Generation = originModule.Generation;\n\n            // For .NETCoreApp consider installed runtime bitness, reasonable to assume 64bit installation of .NET (Core)\n            stubModule.PEKind = isCoreApp ? OptionalHeaderMagic.Pe32Plus :  originModule.PEKind;\n            stubModule.MachineType = isCoreApp ? MachineType.Amd64 : originModule.MachineType;\n            stubModule.IsBit32Required = !isCoreApp && originModule.IsBit32Required;\n            stubModule.IsBit32Preferred = !isCoreApp && originModule.IsBit32Preferred;\n\n            stubModule.RuntimeVersion = originModule.RuntimeVersion;\n            stubModule.SubSystem = originModule.SubSystem;\n\n            // Copy NativeResourceDirectory preserves icons and manifest\n            if (originModule.NativeResourceDirectory != null)\n            {\n                stubModule.NativeResourceDirectory = originModule.NativeResourceDirectory;\n            }\n\n            stubModule.ImportAssemblyTypeReferences(originModule);\n\n            return stubModule;\n        }\n\n        protected static void InjectLoader(ModuleDefinition targetModule, Type loaderClass)\n        {\n            var sourceModule = ModuleDefinition.FromFile(typeof(Packer).Assembly.Location);\n            var cloner = new MemberCloner(targetModule);\n            var loader = (TypeDefinition) sourceModule.LookupMember(loaderClass.MetadataToken);\n            cloner.Include(loader, true);\n            var result = cloner.Clone();\n\n            foreach (var clonedType in result.ClonedTopLevelTypes)\n                targetModule.TopLevelTypes.Add(clonedType);\n\n            result.GetClonedMember(loader).Namespace = \"\";\n\n            var entryPoint = (MethodDefinition) result.ClonedMembers.First(m => m.Name == \"Main\");\n            entryPoint.Name = \".origami\";\n            entryPoint.DeclaringType.Name = \"<Origami>\";\n\n            targetModule.ManagedEntrypoint = entryPoint;\n        }\n\n        public abstract void Execute();\n    }\n\n    public enum Mode\n    {\n        PESection = 0x0,\n        DebugDataEntry = 0x1\n    }\n}\n"
  },
  {
    "path": "src/Packers/RelocPacker.cs",
    "content": "﻿using System;\nusing System.IO;\nusing System.Linq;\nusing System.Security.Cryptography;\nusing AsmResolver;\nusing AsmResolver.DotNet;\nusing AsmResolver.DotNet.Builder;\nusing AsmResolver.DotNet.Cloning;\nusing AsmResolver.PE.DotNet.Cil;\n\nnamespace Origami.Packers\n{\n    public sealed class RelocPacker : Packer\n    {\n        private readonly Mode _mode;\n        private readonly ModuleDefinition _stubModule;\n\n        private string _key;\n\n        public RelocPacker(Mode mode, byte[] payload, string outputPath)\n            : base(payload, outputPath)\n        {\n            _mode = mode;\n            _stubModule = CreateStub(ModuleDefinition.FromBytes(payload));\n        }\n\n        public override void Execute()\n        {\n            _key = RandomString();\n            InjectLoader(_stubModule, out var oldToken);\n            _stubModule.IsILOnly = false;\n\n            var patches = GetOffsets();\n\n            var imageBuilder = new ManagedPEImageBuilder();\n\n            var imageResult = imageBuilder.CreateImage(_stubModule);\n\n            imageResult.TokenMapping.TryGetNewToken(oldToken, out var newToken);\n\n            var payload = new DataSegment(Payload.Compress(_key));\n\n            var fileBuilder = new CustomManagedPEFileBuilder(_mode, payload, newToken, patches);\n            var peImage = imageResult.ConstructedImage;\n            var peFile = fileBuilder.CreateFile(imageResult.ConstructedImage);\n\n            peFile.Write(OutputPath);\n        }\n\n        private void InjectLoader(ModuleDefinition targetModule, out IMetadataMember offset)\n        {\n            string baseDirectory = AppContext.BaseDirectory;\n            var sourceModule = ModuleDefinition.FromFile(Path.Combine(baseDirectory, \"Runtime.dll\"));\n            var cloner = new MemberCloner(targetModule);\n            var loader = sourceModule.GetAllTypes().First(t => t.Name == \"RelocLoader\");\n            cloner.Include(loader, true);\n            var result = cloner.Clone();\n\n            foreach (var clonedType in result.ClonedTopLevelTypes)\n                targetModule.TopLevelTypes.Add(clonedType);\n\n            var member = result.GetClonedMember(loader);\n\n            member.Namespace = \"\";\n\n            offset = member.Methods.First(m => m.Name == \"Main\");\n\n            var entryPoint = (MethodDefinition) result.ClonedMembers.First(m => m.Name == \"Main\");\n            entryPoint.Name = _key;\n            entryPoint.DeclaringType!.Name = \"<Origami>\";\n\n            targetModule.ManagedEntrypoint = entryPoint;\n        }\n\n        private Patches GetOffsets()\n        {\n            var patches = new Patches();\n\n            var entryPoint = _stubModule.ManagedEntrypointMethod;\n\n            var instructions = entryPoint!.CilMethodBody?.Instructions;\n\n\n            var target = instructions.First(i => i.OpCode == CilOpCodes.Ldc_I8);\n            patches.OffsetVA = target.Offset + target.OpCode.Size;\n\n            target = instructions.First(i => i.IsLdcI4() && i.GetLdcI4Constant() == 0x1337c0de);\n            patches.OffsetSize = target.Offset + target.OpCode.Size;\n\n            return patches;\n        }\n\n        private string RandomString()\n        {\n            using var cryptoProvider = new RNGCryptoServiceProvider();\n            byte[] bytes = new byte[64];\n            cryptoProvider.GetBytes(bytes);\n\n            return BitConverter.ToString(bytes).Replace(\"-\", string.Empty);\n        }\n\n        public struct Patches\n        {\n            public int OffsetVA;\n            public int OffsetSize;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Program.cs",
    "content": "﻿using System;\nusing System.IO;\nusing Origami.Packers;\n\nnamespace Origami\n{\n    internal static class Program\n    {\n        private static void Main(string[] args)\n        {\n            Console.WriteLine(\"Origami by drakonia - https://github.com/dr4k0nia/Origami \\r\\n\");\n            if (args.Length == 0)\n            {\n                Console.WriteLine(\"Usage: Origami.exe <file> <mode> or Origami.exe <file>\");\n                Console.WriteLine(\n                    \"Available modes:\\n-pes: Uses additional PE section for the payload data\\n-dbg: Uses PE Debug Directory for the payload data\");\n                Console.WriteLine(\"Default mode: -pes\");\n                Console.ReadKey();\n                return;\n            }\n\n            string file = args[0];\n\n            if (!File.Exists(file))\n                throw new FileNotFoundException($\"Could not find file: {file}\");\n\n            // Prepare initialization parameters payloadData that will get packed, and output path of packed file.\n            byte[] payloadData = File.ReadAllBytes(file);\n            string outputPath = file.Insert(file.Length - 4, \"_origami\");\n\n            IPacker packer;\n            if (args.Length > 1)\n            {\n                packer = args[1] switch\n                {\n                    \"-dbg\" => new RelocPacker(Mode.DebugDataEntry, payloadData, outputPath),\n                    \"-pes\" => new RelocPacker(Mode.PESection, payloadData, outputPath),\n                    _ => throw new InvalidDataException(\n                        \"Invalid mode argument: Available modes:\\n-pes: Uses additional PE section for the payload data\\n-dbg: Uses PE Debug Directory for the payload data\")\n                };\n            }\n            else\n            {\n                packer = new RelocPacker(Mode.PESection, payloadData, outputPath);\n            }\n\n            // Run packer\n            packer.Execute();\n\n\n            Console.WriteLine(\"Saving packed module: {0}\", outputPath);\n            Console.ForegroundColor = ConsoleColor.Green;\n            Console.WriteLine(\"Finished\");\n\n            Console.ReadKey();\n        }\n    }\n}\n"
  },
  {
    "path": "src/Utils.cs",
    "content": "﻿using System;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Linq;\nusing System.Text;\nusing AsmResolver.DotNet;\n\nnamespace Origami\n{\n    public static class Utils\n    {\n        private static byte[] Xor(this byte[] data, string name)\n        {\n            for (int i = 0; i < data.Length; i++)\n            {\n                data[i] ^= (byte) name[i % name.Length];\n            }\n\n            return data;\n        }\n\n        public static byte[] Compress(this byte[] data, string key)\n        {\n            using var mStream = new MemoryStream();\n            using (var dStream = new DeflateStream(mStream, CompressionLevel.Optimal))\n                dStream.Write(data, 0, data.Length);\n            return mStream.ToArray().Xor(key);\n        }\n\n        public static void ImportAssemblyTypeReferences(this ModuleDefinition target, ModuleDefinition origin)\n        {\n            var assembly = origin.Assembly;\n            var importer = new ReferenceImporter(target);\n            foreach (var ca in assembly.CustomAttributes.Where(ca => ca.Constructor.Module == origin))\n                ca.Constructor = (ICustomAttributeType) importer.ImportMethod(ca.Constructor);\n        }\n\n        public static uint GetRandomTimestamp()\n        {\n            var rnd = new Random();\n\n            var from = new DateTime(DateTime.Today.Year - 5, 1, 1);\n            var to = DateTime.Today;\n            var range = to - from;\n\n            var randTimeSpan = new TimeSpan((long) (rnd.NextDouble() * range.Ticks));\n\n            return (uint) (from + randTimeSpan).Subtract(new DateTime(1970, 1, 1)).TotalSeconds;\n        }\n    }\n}\n"
  }
]