Guest User

ApplicationLauncher.vb

a guest
Feb 5th, 2018
320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 14.25 KB | None | 0 0
  1. Imports System.Runtime.InteropServices
  2. Imports System.Security
  3.  
  4. Friend Class ApplicationLauncher
  5.  
  6.     Public Enum TOKEN_INFORMATION_CLASS
  7.         TokenUser = 1
  8.         TokenGroups
  9.         TokenPrivileges
  10.         TokenOwner
  11.         TokenPrimaryGroup
  12.         TokenDefaultDacl
  13.         TokenSource
  14.         TokenType
  15.         TokenImpersonationLevel
  16.         TokenStatistics
  17.         TokenRestrictedSids
  18.         TokenSessionId
  19.         TokenGroupsAndPrivileges
  20.         TokenSessionReference
  21.         TokenSandBoxInert
  22.         TokenAuditPolicy
  23.         TokenOrigin
  24.         MaxTokenInfoClass
  25.     End Enum
  26.  
  27.     Public Const READ_CONTROL As Integer = 131072
  28.     Public Const STANDARD_RIGHTS_REQUIRED As Integer = 983040
  29.     Public Const STANDARD_RIGHTS_READ As Integer = READ_CONTROL
  30.     Public Const STANDARD_RIGHTS_WRITE As Integer = READ_CONTROL
  31.     Public Const STANDARD_RIGHTS_EXECUTE As Integer = READ_CONTROL
  32.     Public Const STANDARD_RIGHTS_ALL As Integer = 2031616
  33.     Public Const SPECIFIC_RIGHTS_ALL As Integer = 65535
  34.     Public Const TOKEN_ASSIGN_PRIMARY As Integer = 1
  35.     Public Const TOKEN_DUPLICATE As Integer = 2
  36.     Public Const TOKEN_IMPERSONATE As Integer = 4
  37.     Public Const TOKEN_QUERY As Integer = 8
  38.     Public Const TOKEN_QUERY_SOURCE As Integer = 16
  39.     Public Const TOKEN_ADJUST_PRIVILEGES As Integer = 32
  40.     Public Const TOKEN_ADJUST_GROUPS As Integer = 64
  41.     Public Const TOKEN_ADJUST_DEFAULT As Integer = 128
  42.     Public Const TOKEN_ADJUST_SESSIONID As Integer = 256
  43.     Public Const TOKEN_ALL_ACCESS_P As Integer = (STANDARD_RIGHTS_REQUIRED Or TOKEN_ASSIGN_PRIMARY Or TOKEN_DUPLICATE Or TOKEN_IMPERSONATE Or TOKEN_QUERY Or TOKEN_QUERY_SOURCE Or TOKEN_ADJUST_PRIVILEGES Or TOKEN_ADJUST_GROUPS Or TOKEN_ADJUST_DEFAULT)
  44.     Public Const TOKEN_ALL_ACCESS As Integer = TOKEN_ALL_ACCESS_P Or TOKEN_ADJUST_SESSIONID
  45.     Public Const TOKEN_READ As Integer = STANDARD_RIGHTS_READ Or TOKEN_QUERY
  46.     Public Const TOKEN_WRITE As Integer = STANDARD_RIGHTS_WRITE Or TOKEN_ADJUST_PRIVILEGES Or TOKEN_ADJUST_GROUPS Or TOKEN_ADJUST_DEFAULT
  47.     Public Const TOKEN_EXECUTE As Integer = STANDARD_RIGHTS_EXECUTE
  48.     Public Const MAXIMUM_ALLOWED As UInteger = 33554432
  49.     Public Const CREATE_NEW_PROCESS_GROUP As Integer = 512
  50.     Public Const CREATE_UNICODE_ENVIRONMENT As Integer = 1024
  51.     Public Const IDLE_PRIORITY_CLASS As Integer = 64
  52.     Public Const NORMAL_PRIORITY_CLASS As Integer = 32
  53.     Public Const HIGH_PRIORITY_CLASS As Integer = 128
  54.     Public Const REALTIME_PRIORITY_CLASS As Integer = 256
  55.     Public Const CREATE_NEW_CONSOLE As Integer = 16
  56.     Public Const SE_DEBUG_NAME As String = "SeDebugPrivilege"
  57.     Public Const SE_RESTORE_NAME As String = "SeRestorePrivilege"
  58.     Public Const SE_BACKUP_NAME As String = "SeBackupPrivilege"
  59.     Public Const SE_PRIVILEGE_ENABLED As Integer = 2
  60.     Public Const ERROR_NOT_ALL_ASSIGNED As Integer = 1300
  61.     Private Const TH32CS_SNAPPROCESS As UInteger = 2
  62.     Public Shared INVALID_HANDLE_VALUE As Integer = -1
  63.  
  64.     <DllImport("advapi32.dll", SetLastError:=True)>
  65.     Public Shared Function LookupPrivilegeValue(ByVal lpSystemName As IntPtr, ByVal lpname As String, <MarshalAs(UnmanagedType.Struct)> ByRef lpLuid As LUID) As Boolean
  66.     End Function
  67.  
  68.     <DllImport("advapi32.dll", EntryPoint:="CreateProcessAsUser", SetLastError:=True, CharSet:=CharSet.Ansi, CallingConvention:=CallingConvention.StdCall)>
  69.     Public Shared Function CreateProcessAsUser(ByVal hToken As IntPtr, ByVal lpApplicationName As String, ByVal lpCommandLine As String, ByRef lpProcessAttributes As SECURITY_ATTRIBUTES, ByRef lpThreadAttributes As SECURITY_ATTRIBUTES, ByVal bInheritHandle As Boolean, ByVal dwCreationFlags As Integer, ByVal lpEnvironment As IntPtr, ByVal lpCurrentDirectory As String, ByRef lpStartupInfo As STARTUPINFO, <Out> ByRef lpProcessInformation As PROCESS_INFORMATION) As Boolean
  70.     End Function
  71.  
  72.     <DllImport("advapi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
  73.     Public Shared Function DuplicateToken(ByVal ExistingTokenHandle As IntPtr, ByVal SECURITY_IMPERSONATION_LEVEL As Integer, ByRef DuplicateTokenHandle As IntPtr) As Boolean
  74.     End Function
  75.  
  76.     <DllImport("advapi32.dll", EntryPoint:="DuplicateTokenEx")>
  77.     Public Shared Function DuplicateTokenEx(ByVal ExistingTokenHandle As IntPtr, ByVal dwDesiredAccess As UInteger, ByRef lpThreadAttributes As SECURITY_ATTRIBUTES, ByVal TokenType As Integer, ByVal ImpersonationLevel As Integer, ByRef DuplicateTokenHandle As IntPtr) As Boolean
  78.     End Function
  79.  
  80.     <DllImport("advapi32.dll", SetLastError:=True)>
  81.     Public Shared Function AdjustTokenPrivileges(ByVal TokenHandle As IntPtr, ByVal DisableAllPrivileges As Boolean, ByRef NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Integer, ByVal PreviousState As IntPtr, ByVal ReturnLength As IntPtr) As Boolean
  82.     End Function
  83.  
  84.     <DllImport("advapi32.dll", SetLastError:=True)>
  85.     Public Shared Function SetTokenInformation(ByVal TokenHandle As IntPtr, ByVal TokenInformationClass As TOKEN_INFORMATION_CLASS, ByRef TokenInformation As UInteger, ByVal TokenInformationLength As UInteger) As Boolean
  86.     End Function
  87.  
  88.     <DllImport("userenv.dll", SetLastError:=True)>
  89.     Public Shared Function CreateEnvironmentBlock(ByRef lpEnvironment As IntPtr, ByVal hToken As IntPtr, ByVal bInherit As Boolean) As Boolean
  90.     End Function
  91.  
  92.     Public Shared Function CreateProcessInConsoleSession(ByVal CommandLine As String, ByVal bElevate As Boolean) As Boolean
  93.         Dim pi As PROCESS_INFORMATION
  94.         Dim bResult As Boolean = False
  95.         Dim dwSessionId As UInteger, winlogonPid As UInteger = 0
  96.         Dim hUserToken As IntPtr = IntPtr.Zero, hUserTokenDup As IntPtr = IntPtr.Zero, hPToken As IntPtr = IntPtr.Zero, hProcess As IntPtr = IntPtr.Zero
  97.         Debug.Print("CreateProcessInConsoleSession")
  98.         dwSessionId = WTSGetActiveConsoleSessionId()
  99.         Dim procEntry = New PROCESSENTRY32()
  100.         Dim hSnap As UInteger = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
  101.         If hSnap = INVALID_HANDLE_VALUE Then
  102.             Return False
  103.         End If
  104.  
  105.         procEntry.dwSize = CUInt(Marshal.SizeOf(procEntry))
  106.         If Process32First(hSnap, procEntry) = 0 Then
  107.             Return False
  108.         End If
  109.  
  110.         Dim strCmp As String = "explorer.exe"
  111.         Do
  112.             If strCmp.IndexOf(procEntry.szExeFile) = 0 Then
  113.                 Dim winlogonSessId As UInteger = 0
  114.                 If ProcessIdToSessionId(procEntry.th32ProcessID, winlogonSessId) AndAlso winlogonSessId = dwSessionId Then
  115.                     winlogonPid = procEntry.th32ProcessID
  116.                     Exit Do
  117.                 End If
  118.             End If
  119.         Loop While Process32Next(hSnap, procEntry) <> 0
  120.  
  121.         WTSQueryUserToken(dwSessionId, hUserToken)
  122.         Dim si = New STARTUPINFO()
  123.         si.cb = Marshal.SizeOf(si)
  124.         si.lpDesktop = "winsta0\default"
  125.         Dim tp = New TOKEN_PRIVILEGES()
  126.         Dim luid = New LUID()
  127.         hProcess = OpenProcess(MAXIMUM_ALLOWED, False, winlogonPid)
  128.         If Not OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY Or TOKEN_DUPLICATE Or TOKEN_ASSIGN_PRIMARY Or TOKEN_ADJUST_SESSIONID Or TOKEN_READ Or TOKEN_WRITE, hPToken) Then
  129.             Debug.Print(String.Format("CreateProcessInConsoleSession OpenProcessToken error: {0}", Marshal.GetLastWin32Error()))
  130.         End If
  131.  
  132.         If Not LookupPrivilegeValue(IntPtr.Zero, SE_DEBUG_NAME, luid) Then
  133.             Debug.Print(String.Format("CreateProcessInConsoleSession LookupPrivilegeValue error: {0}", Marshal.GetLastWin32Error()))
  134.         End If
  135.  
  136.         Dim sa = New SECURITY_ATTRIBUTES()
  137.         sa.Length = Marshal.SizeOf(sa)
  138.         If Not DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, sa, CInt(SECURITY_IMPERSONATION_LEVEL.SecurityIdentification), CInt(TOKEN_TYPE.TokenPrimary), hUserTokenDup) Then
  139.             Debug.Print(String.Format("CreateProcessInConsoleSession DuplicateTokenEx error: {0} Token does not have the privilege.", Marshal.GetLastWin32Error()))
  140.             CloseHandle(hProcess)
  141.             CloseHandle(hUserToken)
  142.             CloseHandle(hPToken)
  143.             Return False
  144.         End If
  145.  
  146.         If bElevate Then
  147.             tp.PrivilegeCount = 1
  148.             tp.Privileges = New Integer(3) {}
  149.             tp.Privileges(2) = SE_PRIVILEGE_ENABLED
  150.             tp.Privileges(1) = luid.HighPart
  151.             tp.Privileges(0) = luid.LowPart
  152.             If Not SetTokenInformation(hUserTokenDup, TOKEN_INFORMATION_CLASS.TokenSessionId, dwSessionId, CUInt(IntPtr.Size)) Then
  153.                 Debug.Print(String.Format("CreateProcessInConsoleSession SetTokenInformation error: {0} Token does not have the privilege.", Marshal.GetLastWin32Error()))
  154.             End If
  155.  
  156.             If Not AdjustTokenPrivileges(hUserTokenDup, False, tp, Marshal.SizeOf(tp), IntPtr.Zero, IntPtr.Zero) Then
  157.                 Dim nErr As Integer = Marshal.GetLastWin32Error()
  158.                 If nErr = ERROR_NOT_ALL_ASSIGNED Then
  159.                     Debug.Print(String.Format("CreateProcessInConsoleSession AdjustTokenPrivileges error: {0} Token does not have the privilege.", nErr))
  160.                 Else
  161.                     Debug.Print(String.Format("CreateProcessInConsoleSession AdjustTokenPrivileges error: {0}", nErr))
  162.                 End If
  163.             End If
  164.         End If
  165.  
  166.         Dim dwCreationFlags As UInteger = NORMAL_PRIORITY_CLASS Or CREATE_NEW_CONSOLE
  167.         Dim pEnv As IntPtr = IntPtr.Zero
  168.         If CreateEnvironmentBlock(pEnv, hUserTokenDup, True) Then
  169.             dwCreationFlags = dwCreationFlags Or CREATE_UNICODE_ENVIRONMENT
  170.         Else
  171.             pEnv = IntPtr.Zero
  172.         End If
  173.  
  174.         bResult = CreateProcessAsUser(hUserTokenDup, Nothing, CommandLine, sa, sa, False, CInt(dwCreationFlags), pEnv, Nothing, si, pi)
  175.         Dim iResultOfCreateProcessAsUser As Integer = Marshal.GetLastWin32Error()
  176.         CloseHandle(hProcess)
  177.         CloseHandle(hUserToken)
  178.         CloseHandle(hUserTokenDup)
  179.         CloseHandle(hPToken)
  180.         Return If((iResultOfCreateProcessAsUser = 0), True, False)
  181.     End Function
  182.  
  183.     <DllImport("kernel32.dll")>
  184.     Private Shared Function Process32First(ByVal hSnapshot As UInteger, ByRef lppe As PROCESSENTRY32) As Integer
  185.     End Function
  186.  
  187.     <DllImport("kernel32.dll")>
  188.     Private Shared Function Process32Next(ByVal hSnapshot As UInteger, ByRef lppe As PROCESSENTRY32) As Integer
  189.     End Function
  190.  
  191.     <DllImport("kernel32.dll", SetLastError:=True)>
  192.     Private Shared Function CreateToolhelp32Snapshot(ByVal dwFlags As UInteger, ByVal th32ProcessID As UInteger) As UInteger
  193.     End Function
  194.  
  195.     <DllImport("kernel32.dll", SetLastError:=True)>
  196.     Private Shared Function CloseHandle(ByVal hSnapshot As IntPtr) As Boolean
  197.     End Function
  198.  
  199.     <DllImport("kernel32.dll")>
  200.     Private Shared Function WTSGetActiveConsoleSessionId() As UInteger
  201.     End Function
  202.  
  203.     <DllImport("Wtsapi32.dll")>
  204.     Private Shared Function WTSQueryUserToken(ByVal SessionId As UInteger, ByRef phToken As IntPtr) As UInteger
  205.     End Function
  206.  
  207.     <DllImport("kernel32.dll")>
  208.     Private Shared Function ProcessIdToSessionId(ByVal dwProcessId As UInteger, ByRef pSessionId As UInteger) As Boolean
  209.     End Function
  210.  
  211.     <DllImport("kernel32.dll")>
  212.     Private Shared Function OpenProcess(ByVal dwDesiredAccess As UInteger, ByVal bInheritHandle As Boolean, ByVal dwProcessId As UInteger) As IntPtr
  213.     End Function
  214.  
  215.     <DllImport("advapi32", SetLastError:=True)>
  216.     <SuppressUnmanagedCodeSecurity>
  217.     Private Shared Function OpenProcessToken(ByVal ProcessHandle As IntPtr, ByVal DesiredAccess As Integer, ByRef TokenHandle As IntPtr) As Boolean
  218.     End Function
  219.  
  220.     <StructLayout(LayoutKind.Sequential)>
  221.     Friend Structure LUID
  222.         Public LowPart As Integer
  223.         Public HighPart As Integer
  224.     End Structure
  225.  
  226.     <StructLayout(LayoutKind.Sequential)>
  227.     Friend Structure LUID_AND_ATRIBUTES
  228.         Public Luid As LUID
  229.         Public Attributes As Integer
  230.     End Structure
  231.  
  232.     <StructLayout(LayoutKind.Sequential)>
  233.     Private Structure PROCESSENTRY32
  234.         Public dwSize As UInteger
  235.         Public ReadOnly cntUsage As UInteger
  236.         Public ReadOnly th32ProcessID As UInteger
  237.         Public ReadOnly th32DefaultHeapID As IntPtr
  238.         Public ReadOnly th32ModuleID As UInteger
  239.         Public ReadOnly cntThreads As UInteger
  240.         Public ReadOnly th32ParentProcessID As UInteger
  241.         Public ReadOnly pcPriClassBase As Integer
  242.         Public ReadOnly dwFlags As UInteger
  243.         <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)>
  244.         Public ReadOnly szExeFile As String
  245.     End Structure
  246.  
  247.     <StructLayout(LayoutKind.Sequential)>
  248.     Public Structure PROCESS_INFORMATION
  249.         Public hProcess As IntPtr
  250.         Public hThread As IntPtr
  251.         Public dwProcessId As UInteger
  252.         Public dwThreadId As UInteger
  253.     End Structure
  254.  
  255.     <StructLayout(LayoutKind.Sequential)>
  256.     Public Structure SECURITY_ATTRIBUTES
  257.         Public Length As Integer
  258.         Public lpSecurityDescriptor As IntPtr
  259.         Public bInheritHandle As Boolean
  260.     End Structure
  261.  
  262.     Private Enum SECURITY_IMPERSONATION_LEVEL
  263.         SecurityAnonymous = 0
  264.         SecurityIdentification = 1
  265.         SecurityImpersonation = 2
  266.         SecurityDelegation = 3
  267.     End Enum
  268.  
  269.     <StructLayout(LayoutKind.Sequential)>
  270.     Public Structure STARTUPINFO
  271.         Public cb As Integer
  272.         Public lpReserved As String
  273.         Public lpDesktop As String
  274.         Public lpTitle As String
  275.         Public dwX As UInteger
  276.         Public dwY As UInteger
  277.         Public dwXSize As UInteger
  278.         Public dwYSize As UInteger
  279.         Public dwXCountChars As UInteger
  280.         Public dwYCountChars As UInteger
  281.         Public dwFillAttribute As UInteger
  282.         Public dwFlags As UInteger
  283.         Public wShowWindow As Short
  284.         Public cbReserved2 As Short
  285.         Public lpReserved2 As IntPtr
  286.         Public hStdInput As IntPtr
  287.         Public hStdOutput As IntPtr
  288.         Public hStdError As IntPtr
  289.     End Structure
  290.  
  291.     <StructLayout(LayoutKind.Sequential)>
  292.     Friend Structure TOKEN_PRIVILEGES
  293.         Friend PrivilegeCount As Integer
  294.         <MarshalAs(UnmanagedType.ByValArray, SizeConst:=3)>
  295.         Friend Privileges As Integer()
  296.     End Structure
  297.  
  298.     Private Enum TOKEN_TYPE
  299.         TokenPrimary = 1
  300.         TokenImpersonation = 2
  301.     End Enum
  302. End Class
Add Comment
Please, Sign In to add comment