Friday, January 22, 2016

C# .NET Windows UAC - Check if User is in Admin Group

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;

namespace UACStatus
{
    ///
    /// 2011 David Moore
    /// http://www.davidmoore.info/blog/2011/06/20/how-to-check-if-the-current-user-is-an-administrator-even-if-uac-is-on/
    ///
    public class UACSecurity
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        static extern bool GetTokenInformation(IntPtr tokenHandle, TokenInformationClass tokenInformationClass, IntPtr tokenInformation, int tokenInformationLength, out int returnLength);

        ///
        /// Passed to to specify what
        /// information about the token to return.
        ///
        enum TokenInformationClass
        {
            TokenUser = 1,
            TokenGroups,
            TokenPrivileges,
            TokenOwner,
            TokenPrimaryGroup,
            TokenDefaultDacl,
            TokenSource,
            TokenType,
            TokenImpersonationLevel,
            TokenStatistics,
            TokenRestrictedSids,
            TokenSessionId,
            TokenGroupsAndPrivileges,
            TokenSessionReference,
            TokenSandBoxInert,
            TokenAuditPolicy,
            TokenOrigin,
            TokenElevationType,
            TokenLinkedToken,
            TokenElevation,
            TokenHasRestrictions,
            TokenAccessInformation,
            TokenVirtualizationAllowed,
            TokenVirtualizationEnabled,
            TokenIntegrityLevel,
            TokenUiAccess,
            TokenMandatoryPolicy,
            TokenLogonSid,
            MaxTokenInfoClass
        }

        ///
        /// The elevation type for a user token.
        ///
        enum TokenElevationType
        {
            TokenElevationTypeDefault = 1,
            TokenElevationTypeFull,
            TokenElevationTypeLimited
        }

        public bool CurrentUserIsAdminRole()
        {
            var identity = WindowsIdentity.GetCurrent();
            if (identity == null) throw new InvalidOperationException("Couldn't get the current user identity");
            var principal = new WindowsPrincipal(identity);

            // Check if this user has the Administrator role. If they do, return immediately.
            // If UAC is on, and the process is not elevated, then this will actually return false.
            if (principal.IsInRole(WindowsBuiltInRole.Administrator)) return true;

            // If we're not running in Vista onwards, we don't have to worry about checking for UAC.
            if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6)
            {
                // Operating system does not support UAC; skipping elevation check.
                return false;
            }

            int tokenInfLength = Marshal.SizeOf(typeof(int));
            IntPtr tokenInformation = Marshal.AllocHGlobal(tokenInfLength);

            try
            {
                var token = identity.Token;
                var result = GetTokenInformation(token, TokenInformationClass.TokenElevationType, tokenInformation, tokenInfLength, out tokenInfLength);

                if (!result)
                {
                    var exception = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                    throw new InvalidOperationException("Couldn't get token information", exception);
                }

                var elevationType = (TokenElevationType)Marshal.ReadInt32(tokenInformation);

                switch (elevationType)
                {
                    case TokenElevationType.TokenElevationTypeDefault:
                        // TokenElevationTypeDefault - User is not using a split token, so they cannot elevate.
                        return false;
                    case TokenElevationType.TokenElevationTypeFull:
                        // TokenElevationTypeFull - User has a split token, and the process is running elevated. Assuming they're an administrator.
                        return true;
                    case TokenElevationType.TokenElevationTypeLimited:
                        // TokenElevationTypeLimited - User has a split token, but the process is not running elevated. Assuming they're an administrator.
                        return true;
                    default:
                        // Unknown token elevation type.
                        return false;
                }
            }
            finally
            {
                if (tokenInformation != IntPtr.Zero) Marshal.FreeHGlobal(tokenInformation);
            }
        }
    }
}

Wednesday, January 20, 2016

Visual Studio Build Variables

https://msdn.microsoft.com/en-us/library/c02as0cs.aspx
Macro
Description
$(RemoteMachine)
Set to the value of the Remote Machine property on the Debug property page. See Changing Project Settings for a C/C++ Debug Configuration for more information.
$(Configuration)
The name of the current project configuration (for example, "Debug").
$(Platform)
The name of current project platform (for example, "Win32").
$(ParentName)
(Deprecated.) Name of the item containing this project item. This will be the parent folder name, or project name.
$(RootNameSpace)
The namespace, if any, containing the application.
$(IntDir)
Path to the directory specified for intermediate files. If this is a relative path, intermediate files go to this path appended to the project directory. This path should have a trailing slash. This resolves to the value for theIntermediate Directory property. Do not use $(OutDir) to define this property.
$(OutDir)
Path to the output file directory. If this is a relative path, output files go to this path appended to the project directory. This path should have a trailing slash. This resolves to the value for the Output Directory property. Do not use $(IntDir) to define this property.
$(DevEnvDir)
The installation directory of Visual Studio (defined as drive + path); includes the trailing backslash '\'.
$(InputDir)
(Deprecated; migrated.) The directory of the input file (defined as drive + path); includes the trailing backslash '\'. If the project is the input, then this macro is equivalent to $(ProjectDir).
$(InputPath)
(Deprecated; migrated.) The absolute path name of the input file (defined as drive + path + base name + file extension). If the project is the input, then this macro is equivalent to $(ProjectPath).
$(InputName)
(Deprecated; migrated.) The base name of the input file. If the project is the input, then this macro is equivalent to$(ProjectName).
$(InputFileName)
(Deprecated; migrated.) The file name of the input file (defined as base name + file extension). If the project is the input, then this macro is equivalent to $(ProjectFileName).
$(InputExt)
(Deprecated; migrated.) The file extension of the input file. It includes the '.' before the file extension. If the project is the input, then this macro is equivalent to $(ProjectExt).
$(ProjectDir)
The directory of the project (defined as drive + path); includes the trailing backslash '\'.
$(ProjectPath)
The absolute path name of the project (defined as drive + path + base name + file extension).
$(ProjectName)
The base name of the project.
$(ProjectFileName)
The file name of the project (defined as base name + file extension).
$(ProjectExt)
The file extension of the project. It includes the '.' before the file extension.
$(SolutionDir)
The directory of the solution (defined as drive + path); includes the trailing backslash '\'.
$(SolutionPath)
The absolute path name of the solution (defined as drive + path + base name + file extension).
$(SolutionName)
The base name of the solution.
$(SolutionFileName)
The file name of the solution (defined as base name + file extension).
$(SolutionExt)
The file extension of the solution. It includes the '.' before the file extension.
$(TargetDir)
The directory of the primary output file for the build (defined as drive + path); includes the trailing backslash '\'.
$(TargetPath)
The absolute path name of the primary output file for the build (defined as drive + path + base name + file extension).
$(TargetName)
The base name of the primary output file for the build.
$(TargetFileName)
The file name of the primary output file for the build (defined as base name + file extension).
$(TargetExt)
The file extension of the primary output file for the build. It includes the '.' before the file extension.
$(VSInstallDir)
The directory into which you installed Visual Studio. 
This property contains the version of the targeted Visual Studio, which might be different that the host Visual Studio. For example, when building with $(PlatformToolset) = v110$(VSInstallDir) contains the path to the Visual Studio 2012 installation.
$(VCInstallDir)
The directory into which you installed Visual C++. 
This property contains the version of the targeted Visual C++, which might be different that the host Visual Studio. For example, when building with $(PlatformToolset) = v90$(VCInstallDir) contains the path to the Visual C++ 2008 installation.
$(FrameworkDir)
The directory into which the .NET Framework was installed.
$(FrameworkVersion)
The version of the .NET Framework used by Visual Studio. Combined with $(FrameworkDir), the full path to the version of the .NET Framework use by Visual Studio.
$(FrameworkSDKDir)
The directory into which you installed the .NET Framework. The .NET Framework could have been installed as part of Visual Studio or separately.
$(WebDeployPath)
The relative path from the web deployment root to where the project outputs belong. Returns the same value asRelativePath.
$(WebDeployRoot)
The absolute path to the location of . For example, c:\inetpub\wwwroot.
$(SafeParentName)
(Deprecated.) The name of the immediate parent in valid name format. For example, a form is the parent of a .resx file.
$(SafeInputName)
(Deprecated.) The name of the file as a valid class name, minus file extension.
$(SafeRootNamespace)
(Deprecated.) The namespace name in which the project wizards will add code. This namespace name will only contain characters that would be permitted in a valid C++ identifier.
$(FxCopDir)
The path to the fxcop.cmd file. The fxcop.cmd file is not installed with all Visual C++ editions.

Friday, January 15, 2016

Get Windows .DLL Information via The Command Line / Powershell

get public key using sn.exe = strong name util

"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\sn.exe" -Tp "path_to_dll"

get version info, from the powershell prompt

[System.Reflection.Assembly]::LoadFrom("path_to_dll").GetName().Version