From 681dcf356f5fadfd2ec784f30f0c0a6d16b28fa2 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Tue, 18 Apr 2017 19:35:30 +0200 Subject: [PATCH] Initial import --- .gitattributes | 63 +++++ .gitignore | 261 ++++++++++++++++++ .../NetOnlyImpersonation.sln | 22 ++ .../NetOnlyImpersonation.csproj | 45 +++ .../NetOnlyImpersonation.psd1 | 25 ++ .../NetOnlyImpersonationContext.cs | 113 ++++++++ .../Properties/AssemblyInfo.cs | 15 + 7 files changed, 544 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 src/NetOnlyImpersonation/NetOnlyImpersonation.sln create mode 100644 src/NetOnlyImpersonation/NetOnlyImpersonation/NetOnlyImpersonation.csproj create mode 100644 src/NetOnlyImpersonation/NetOnlyImpersonation/NetOnlyImpersonation.psd1 create mode 100644 src/NetOnlyImpersonation/NetOnlyImpersonation/NetOnlyImpersonationContext.cs create mode 100644 src/NetOnlyImpersonation/NetOnlyImpersonation/Properties/AssemblyInfo.cs diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3c4efe2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,261 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +project.fragment.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +#*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc \ No newline at end of file diff --git a/src/NetOnlyImpersonation/NetOnlyImpersonation.sln b/src/NetOnlyImpersonation/NetOnlyImpersonation.sln new file mode 100644 index 0000000..54dda00 --- /dev/null +++ b/src/NetOnlyImpersonation/NetOnlyImpersonation.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26403.7 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetOnlyImpersonation", "NetOnlyImpersonation\NetOnlyImpersonation.csproj", "{0E2F9140-AC90-43CC-BA9E-39F206B486CA}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0E2F9140-AC90-43CC-BA9E-39F206B486CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0E2F9140-AC90-43CC-BA9E-39F206B486CA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0E2F9140-AC90-43CC-BA9E-39F206B486CA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0E2F9140-AC90-43CC-BA9E-39F206B486CA}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/src/NetOnlyImpersonation/NetOnlyImpersonation/NetOnlyImpersonation.csproj b/src/NetOnlyImpersonation/NetOnlyImpersonation/NetOnlyImpersonation.csproj new file mode 100644 index 0000000..7f3f7a1 --- /dev/null +++ b/src/NetOnlyImpersonation/NetOnlyImpersonation/NetOnlyImpersonation.csproj @@ -0,0 +1,45 @@ + + + + + Debug + AnyCPU + {0E2F9140-AC90-43CC-BA9E-39F206B486CA} + Library + Properties + NetOnlyImpersonation + NetOnlyImpersonation + v4.5.2 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + PreserveNewest + + + + \ No newline at end of file diff --git a/src/NetOnlyImpersonation/NetOnlyImpersonation/NetOnlyImpersonation.psd1 b/src/NetOnlyImpersonation/NetOnlyImpersonation/NetOnlyImpersonation.psd1 new file mode 100644 index 0000000..6a101fd --- /dev/null +++ b/src/NetOnlyImpersonation/NetOnlyImpersonation/NetOnlyImpersonation.psd1 @@ -0,0 +1,25 @@ +@{ + ModuleVersion = '1.0.0' + GUID = '4716A58C-8609-4E33-8D8E-56C8C695B77C' + Author = 'Alberto Spelta' + Copyright = '(c) 2017 Alberto Spelta. All rights reserved.' + Description = 'This module allows using windows identity impersonation to access to access protected resources on remote systems as a different user without any trust. Credentials are only used on the remote system, locally you are still using the identity of the process.' + PowerShellVersion = '4.0' + DotNetFrameworkVersion = '4.0' + CLRVersion = '4.0' + ProcessorArchitecture = 'None' + RequiredAssemblies = @() + ScriptsToProcess = @() + TypesToProcess = @() + FormatsToProcess = @() + NestedModules = @("NetOnlyImpersonation.dll") + FunctionsToExport = '*' + CmdletsToExport = '*' + VariablesToExport = '*' + AliasesToExport = '*' + PrivateData = @{ + PSData = @{ + ProjectUri = 'https://github.com/albertospelta/azure-automation-netonlyimpersonation' + } + } +} diff --git a/src/NetOnlyImpersonation/NetOnlyImpersonation/NetOnlyImpersonationContext.cs b/src/NetOnlyImpersonation/NetOnlyImpersonation/NetOnlyImpersonationContext.cs new file mode 100644 index 0000000..68d3454 --- /dev/null +++ b/src/NetOnlyImpersonation/NetOnlyImpersonation/NetOnlyImpersonationContext.cs @@ -0,0 +1,113 @@ +/// +/// +/// +namespace NetOnlyImpersonation +{ + using System; + using System.ComponentModel; + using System.Runtime.InteropServices; + using System.Security.Permissions; + using System.Security.Principal; + + /// + /// This module allows using windows identity impersonation to access protected resources on remote systems as a different user without any trust. + /// Credentials are only used on the remote system, locally you are still using the identity of the process. + /// + /// + /// + public class NetOnlyImpersonationContext : IDisposable + { + #region Interop + + [DllImport("advapi32.dll", SetLastError = true)] + public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); + + [DllImport("kernel32.dll", CharSet = CharSet.Auto)] + public extern static bool CloseHandle(IntPtr handle); + + #endregion + + #region Const + + private const string LOCAL_ACCOUNT_DATABASE = "."; + private const int LOGON32_LOGON_NEW_CREDENTIALS = 9; + private const int LOGON32_PROVIDER_WINNT50 = 3; + + #endregion + + private WindowsImpersonationContext _context = null; + private WindowsIdentity _identity = null; + private IntPtr _token = IntPtr.Zero; + private bool _disposed = false; + + public WindowsIdentity Identity + { + get + { + return _identity; + } + } + + [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] + public NetOnlyImpersonationContext(string username, string password) + : this(LOCAL_ACCOUNT_DATABASE, username, password) + { + } + + [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] + public NetOnlyImpersonationContext(string domain, string username, string password) + { + var hresult = LogonUser(username, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, ref _token); + if (hresult == false) + throw new Win32Exception(error: Marshal.GetLastWin32Error()); + + _identity = new WindowsIdentity(_token); + _context = _identity.Impersonate(); + } + + #region IDisposable + + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + if (_identity != null) + { + _identity.Dispose(); + _identity = null; + } + } + + if (_context != null) + { + _context.Undo(); + _context.Dispose(); + _context = null; + } + + if (_token != IntPtr.Zero) + { + CloseHandle(_token); + _token = IntPtr.Zero; + } + + _disposed = true; + } + } + + ~NetOnlyImpersonationContext() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + #endregion + } +} diff --git a/src/NetOnlyImpersonation/NetOnlyImpersonation/Properties/AssemblyInfo.cs b/src/NetOnlyImpersonation/NetOnlyImpersonation/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..6c22931 --- /dev/null +++ b/src/NetOnlyImpersonation/NetOnlyImpersonation/Properties/AssemblyInfo.cs @@ -0,0 +1,15 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("NetOnlyImpersonation")] +[assembly: AssemblyDescription("This module allows using windows identity impersonation to access protected resources on remote systems as a different user without any trust. Credentials are only used on the remote system, locally you are still using the identity of the process.")] +[assembly: AssemblyProduct("NetOnlyImpersonation")] +[assembly: AssemblyCopyright("Copyright © 2017 Alberto Spelta")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +[assembly: ComVisible(false)] +[assembly: Guid("4402953d-ff28-4952-b7f2-47c475b31b24")] + +[assembly: AssemblyVersion("1.0.0")] +[assembly: AssemblyFileVersion("1.0.0")]