コード例 #1
0
ファイル: Capturer.cs プロジェクト: resonancellc/Adit
        private void SwitchDesktops()
        {
            AditClient.DesktopSwitchPending = true;
            Utilities.WriteToLog($"Desktop switch initiated to {desktopName}.");

            var procInfo  = new ADVAPI32.PROCESS_INFORMATION();
            var sessionID = Guid.NewGuid().ToString();

            if (ADVAPI32.OpenInteractiveProcess(Path.Combine(Utilities.ProgramFolder, "Adit.exe") + $" -upgrade {AditClient.SessionID}", desktopName, out procInfo))
            {
                AditClient.SocketMessageHandler.SendDesktopSwitch();
                return;
            }
            else
            {
                var error = Marshal.GetLastWin32Error();
                if (error == 6)
                {
                    Utilities.WriteToLog("Desktop switch failed during a Windows session change.");
                }
                else
                {
                    Utilities.WriteToLog(new Exception("Failed to switch desktops.  Error: " + error.ToString()));
                }
                return;
            }
        }
コード例 #2
0
ファイル: SECUR32.cs プロジェクト: xhorizont/Remotely
 public TOKEN_SOURCE(string name)
 {
     SourceName = new byte[8];
     System.Text.Encoding.GetEncoding(1252).GetBytes(name, 0, name.Length, SourceName, 0);
     if (!ADVAPI32.AllocateLocallyUniqueId(out SourceIdentifier))
     {
         throw new System.ComponentModel.Win32Exception();
     }
 }
コード例 #3
0
ファイル: SECUR32.cs プロジェクト: michaelhull/Remotely
    public static void CreateNewSession()
    {
        var kli = new SECUR32.KERB_INTERACTIVE_LOGON()
        {
            MessageType = SECUR32.KERB_LOGON_SUBMIT_TYPE.KerbInteractiveLogon,
            UserName    = "",
            Password    = ""
        };
        IntPtr pluid;
        IntPtr lsaHan;
        uint   authPackID;
        IntPtr kerbLogInfo;

        SECUR32.LSA_STRING logonProc = new SECUR32.LSA_STRING()
        {
            Buffer        = Marshal.StringToHGlobalAuto("InstaLogon"),
            Length        = (ushort)Marshal.SizeOf(Marshal.StringToHGlobalAuto("InstaLogon")),
            MaximumLength = (ushort)Marshal.SizeOf(Marshal.StringToHGlobalAuto("InstaLogon"))
        };
        SECUR32.LSA_STRING originName = new SECUR32.LSA_STRING()
        {
            Buffer        = Marshal.StringToHGlobalAuto("InstaLogon"),
            Length        = (ushort)Marshal.SizeOf(Marshal.StringToHGlobalAuto("InstaLogon")),
            MaximumLength = (ushort)Marshal.SizeOf(Marshal.StringToHGlobalAuto("InstaLogon"))
        };
        SECUR32.LSA_STRING authPackage = new SECUR32.LSA_STRING()
        {
            Buffer        = Marshal.StringToHGlobalAuto("MICROSOFT_KERBEROS_NAME_A"),
            Length        = (ushort)Marshal.SizeOf(Marshal.StringToHGlobalAuto("MICROSOFT_KERBEROS_NAME_A")),
            MaximumLength = (ushort)Marshal.SizeOf(Marshal.StringToHGlobalAuto("MICROSOFT_KERBEROS_NAME_A"))
        };
        IntPtr hLogonProc = Marshal.AllocHGlobal(Marshal.SizeOf(logonProc));

        Marshal.StructureToPtr(logonProc, hLogonProc, false);
        ADVAPI32.AllocateLocallyUniqueId(out pluid);
        LsaConnectUntrusted(out lsaHan);
        //SECUR32.LsaRegisterLogonProcess(hLogonProc, out lsaHan, out secMode);
        SECUR32.LsaLookupAuthenticationPackage(lsaHan, ref authPackage, out authPackID);

        kerbLogInfo = Marshal.AllocHGlobal(Marshal.SizeOf(kli));
        Marshal.StructureToPtr(kli, kerbLogInfo, false);

        var    ts = new SECUR32.TOKEN_SOURCE("Insta");
        IntPtr profBuf;
        uint   profBufLen;
        long   logonID;
        IntPtr logonToken;

        SECUR32.QUOTA_LIMITS   quotas;
        SECUR32.WinStatusCodes subStatus;
        SECUR32.LsaLogonUser(lsaHan, ref originName, SECUR32.SecurityLogonType.Interactive, authPackID, kerbLogInfo, (uint)Marshal.SizeOf(kerbLogInfo), IntPtr.Zero, ref ts, out profBuf, out profBufLen, out logonID, out logonToken, out quotas, out subStatus);
    }
コード例 #4
0
        public static bool ShutdownLocalhost(ShutdownEnum.ExitWindows options, ShutdownEnum.ShutdownReason reason)
        {
            TokPriv1Luid tp;
            IntPtr       hproc   = KERNEL32.getCurrentProcess();
            IntPtr       zeroPtr = IntPtr.Zero;

            ADVAPI32.OpenProcessToken(hproc, ADVAPI32.TOKEN_ADJUST_PRIVILEGES | ADVAPI32.TOKEN_QUERY, ref zeroPtr);
            tp.Count = 1;
            tp.Luid  = 0;
            tp.Attr  = ADVAPI32.SE_PRIVILEGE_ENABLED;
            ADVAPI32.LookupPrivilegeValue(null, ADVAPI32.SE_SHUTDOWN_NAME, ref tp.Luid);
            ADVAPI32.AdjustTokenPrivileges(zeroPtr, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
            return(USER32.exitWindowsEx(options, reason));
        }
コード例 #5
0
        static void adjustToken()
        {
            IntPtr processhandle = Kernel32.GetCurrentProcess();
            IntPtr tokenHandle;

            ADVAPI32.OpenProcessToken(processhandle, (TOKEN.ADJUST_PRIVILEGES | TOKEN.QUERY), out tokenHandle);
            var newState = new TOKEN_PRIVILEGES();

            newState.Privileges.Attributes = SE.PRIVILEGE_ENABLED;
            newState.PrivilegeCount        = 1;
            ADVAPI32.LookupPrivilegeValue(null, SE.SHUTDOWN_NAME, out newState.Privileges.Luid);
            ADVAPI32.AdjustTokenPrivileges(tokenHandle, false, ref newState, 0, IntPtr.Zero, IntPtr.Zero);
            Kernel32.CloseHandle(tokenHandle);
        }
コード例 #6
0
        private void ReceiveRequestForElevatedClient(dynamic jsonData)
        {
            var sessionID     = Guid.NewGuid().ToString();
            var desktopName   = User32.GetCurrentDesktop();
            var procInfo      = new ADVAPI32.PROCESS_INFORMATION();
            var processResult = ADVAPI32.OpenInteractiveProcess(Path.Combine(Utilities.ProgramFolder, "Adit.exe") + $" -upgrade {sessionID}", desktopName, out procInfo);

            if (processResult == false)
            {
                jsonData["Status"] = "failed";
                SendJSON(jsonData);
                Utilities.WriteToLog(new Exception("Error opening interactive process.  Error Code: " + Marshal.GetLastWin32Error().ToString()));
            }
            else
            {
                jsonData["Status"]          = "ok";
                jsonData["ClientSessionID"] = sessionID;
                SendJSON(jsonData);
            }
        }
コード例 #7
0
        public void Impersonate(string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider)
        {
            UndoImpersonation();

            IntPtr logonToken          = IntPtr.Zero;
            IntPtr logonTokenDuplicate = IntPtr.Zero;

            try
            {
                _wic = WindowsIdentity.Impersonate(IntPtr.Zero);

                if (ADVAPI32.LogonUser(userName, domainName, password, (int)logonType, (int)logonProvider, ref logonToken) != 0)
                {
                    if (ADVAPI32.DuplicateToken(logonToken, (int)ImpersonationLevel.SecurityIdentification, ref logonTokenDuplicate) != 0)
                    {
                        var wi = new WindowsIdentity(logonTokenDuplicate);
                        wi.Impersonate();
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                if (logonToken != IntPtr.Zero)
                {
                    KERNEL32.CloseHandle(logonToken);
                }

                if (logonTokenDuplicate != IntPtr.Zero)
                {
                    KERNEL32.CloseHandle(logonTokenDuplicate);
                }
            }
        }
コード例 #8
0
        private void AdjustToken(IntPtr hToken, string privilege)
        {
            ADVAPI32.TokPriv1Luid tokenPriv1Luid = new ADVAPI32.TokPriv1Luid()
            {
                Count = 1, Attr = ADVAPI32.SE_PRIVILEGE_ENABLED, Luid = 0
            };
            bool lookupResult = ADVAPI32.LookupPrivilegeValue(null, privilege, ref tokenPriv1Luid.Luid);

            if (!lookupResult)
            {
                int win32Error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                ThrowTerminatingError(new ErrorRecord(new InstanceNotFoundException(string.Format("Privilege lookup failed for '{1}': {0}", win32Error, privilege)), "100", ErrorCategory.ResourceUnavailable, null));
            }

            bool adjustTokenResult = ADVAPI32.AdjustTokenPrivileges(hToken, false, ref tokenPriv1Luid, 12, IntPtr.Zero, IntPtr.Zero);

            if (!adjustTokenResult)
            {
                int win32Error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(string.Format("Cannot adjust token privilege '{1}': {0}", win32Error, privilege)), "100", ErrorCategory.AuthenticationError, null));
            }
        }
コード例 #9
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            IntPtr hToken           = IntPtr.Zero;
            bool   openProcessToken = ADVAPI32.OpenProcessToken(ADVAPI32.GetCurrentProcess(), ADVAPI32.TOKEN_ALL_ACCESS, ref hToken);

            if (!openProcessToken)
            {
                int win32Error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(string.Format("Cannot open process token: {0}", win32Error)), "100", ErrorCategory.ResourceUnavailable, null));
            }



            Process lsassProcess = null;

            try
            {
                switch (this.ParameterSetName)
                {
                case "ById":
                    lsassProcess = Process.GetProcessById(processId);
                    break;

                case "ByName":
                    lsassProcess = Process.GetProcessesByName(processName)[0];
                    break;

                case "ProcessObject":
                    lsassProcess = processObject;
                    break;
                }
            }
            catch
            {
                ThrowTerminatingError(new ErrorRecord(new FileNotFoundException("Specified cannot be located."), "100", ErrorCategory.ObjectNotFound, null));
            }

            IntPtr lsaToken    = IntPtr.Zero;
            bool   processOpen = ADVAPI32.OpenProcessToken(lsassProcess.Handle, ADVAPI32.TOKEN_IMPERSONATE | ADVAPI32.TOKEN_DUPLICATE | ADVAPI32.TOKEN_QUERY, ref lsaToken);

            if (!processOpen)
            {
                int win32Error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                ThrowTerminatingError(new ErrorRecord(new FileNotFoundException(string.Format("Cannot open process: {0}", win32Error)), "100", ErrorCategory.ConnectionError, null));
            }

            try
            {
                WindowsIdentity newId = new WindowsIdentity(hToken);
                using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                {
                    IntPtr dupeToken        = IntPtr.Zero;
                    int    tokenDuplication = ADVAPI32.DuplicateToken(lsaToken, 2, ref dupeToken);
                    if (tokenDuplication < 0)
                    {
                        int win32Error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                        ThrowTerminatingError(new ErrorRecord(new OperationCallFailedException(string.Format("Could not duplicate token: {0}", win32Error)), "100", ErrorCategory.SecurityError, null));
                    }
                    AdjustToken(hToken, "SeIncreaseQuotaPrivilege");
                    AdjustToken(hToken, "SeSecurityPrivilege");
                    AdjustToken(hToken, "SeTakeOwnershipPrivilege");
                    AdjustToken(hToken, "SeLoadDriverPrivilege");
                    AdjustToken(hToken, "SeSystemProfilePrivilege");
                    AdjustToken(hToken, "SeSystemtimePrivilege");
                    AdjustToken(hToken, "SeProfileSingleProcessPrivilege");
                    AdjustToken(hToken, "SeIncreaseBasePriorityPrivilege");
                    AdjustToken(hToken, "SeCreatePagefilePrivilege");
                    AdjustToken(hToken, "SeBackupPrivilege");
                    AdjustToken(hToken, "SeRestorePrivilege");
                    AdjustToken(hToken, "SeShutdownPrivilege");
                    AdjustToken(hToken, "SeDebugPrivilege");
                    AdjustToken(hToken, "SeSystemEnvironmentPrivilege");
                    AdjustToken(hToken, "SeChangeNotifyPrivilege");
                    AdjustToken(hToken, "SeRemoteShutdownPrivilege");
                    AdjustToken(hToken, "SeUndockPrivilege");
                    AdjustToken(hToken, "SeManageVolumePrivilege");
                    AdjustToken(hToken, "SeImpersonatePrivilege");
                    AdjustToken(hToken, "SeCreateGlobalPrivilege");
                    AdjustToken(hToken, "SeTimeZonePrivilege");
                    AdjustToken(hToken, "SeCreateSymbolicLinkPrivilege");
                    AdjustToken(hToken, "SeIncreaseWorkingSetPrivilege");


                    bool setToken = ADVAPI32.SetThreadToken(IntPtr.Zero, dupeToken);
                    if (!setToken)
                    {
                        int win32Error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                        ThrowTerminatingError(new ErrorRecord(new SecurityAccessDeniedException(string.Format("Could not set thread token: {0}", win32Error)), "100", ErrorCategory.SecurityError, null));
                    }


                    try
                    {
                        Collection <PSObject> results = scriptBlock.Invoke();
                        WriteObject(results, true);
                    }
                    catch (Exception ex)
                    {
                        ThrowTerminatingError(new ErrorRecord(new ApplicationException(string.Format("An internal error occured", ex.Message), ex), "200", ErrorCategory.NotSpecified, null));
                    }
                }
            }
            catch (Exception)
            {
                ThrowTerminatingError(new ErrorRecord(new SecurityException(string.Format("Could not change identity")), "100", ErrorCategory.SecurityError, null));
            }
        }