Example #1
0
 public static TempFileStream CreateInstance(string prefix, bool deleteOnClose)
 {
     var securityAttributes = new NativeMethods.SecurityAttributes(false);
     var path = TempFileStream.Path;
     new System.Security.Permissions.FileIOPermission(System.Security.Permissions.FileIOPermissionAccess.Write, path).Demand();
     var error = 0;
     var num1 = 10;
     string str;
     Microsoft.Win32.SafeHandles.SafeFileHandle file;
     do {
         var num2 = (uint) System.Threading.Interlocked.Increment(ref nextId);
         str = System.IO.Path.Combine(path, prefix + num2.ToString("X5") + ".tmp");
         var num3 = deleteOnClose ? 67108864U : 0U;
         file = NativeMethods.CreateFile(str, 1180063U, 0U, ref securityAttributes, 1U, (uint) (256 | (int) num3 | 8192), System.IntPtr.Zero);
         --num1;
         if (file.IsInvalid) {
             error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
             if (error == 80)
                 ++num1;
             using (var currentProcess = System.Diagnostics.Process.GetCurrentProcess())
                 System.Threading.Interlocked.Add(ref nextId, currentProcess.Id);
         } else
             num1 = 0;
     } while (num1 > 0);
     if (file.IsInvalid) {
         var fileFailed = Resources.SharedStrings.CreateFileFailed(str);
         throw new System.IO.IOException(fileFailed, new System.ComponentModel.Win32Exception(error, fileFailed));
     }
     return new TempFileStream(file) {
         FilePath = str
     };
 }
Example #2
0
        private void CreateStandardPipe(out SafeFileHandle readHandle, out SafeFileHandle writeHandle, int standardHandle, bool isInput, bool redirect)
        {
            if (redirect)
            {
                NativeMethods.SecurityAttributes security = new NativeMethods.SecurityAttributes {
                    bInheritHandle = true
                };

                bool success = NativeMethods.CreatePipe(out readHandle, out writeHandle, security, 4096);

                if (success)
                {
                    success = NativeMethods.SetHandleInformation(isInput ? writeHandle : readHandle, HANDLE_FLAG_INHERIT, 0);
                }

                if (!success)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error(), "ImpersonationProcess: could not create standard pipe");
                }
            }
            else
            {
                if (isInput)
                {
                    writeHandle = new SafeFileHandle(IntPtr.Zero, false);
                    readHandle  = NativeMethods.GetStdHandle(standardHandle);
                }
                else
                {
                    readHandle  = new SafeFileHandle(IntPtr.Zero, false);
                    writeHandle = NativeMethods.GetStdHandle(standardHandle);
                }
            }
        }
Example #3
0
        private static bool CreatePrimaryToken(IntPtr impersonationToken, out IntPtr primaryToken)
        {
            // Convert the impersonation token into Primary token
            NativeMethods.SecurityAttributes sa = new NativeMethods.SecurityAttributes();

            bool retVal = NativeMethods.DuplicateTokenEx(
                impersonationToken,
                NativeMethods.TokenAccess.AssignPrimary | NativeMethods.TokenAccess.Duplicate | NativeMethods.TokenAccess.Query,
                sa,
                NativeMethods.SecurityImpersonationLevel.Identification,
                NativeMethods.TokenType.Primary,
                out primaryToken);

            // Close the Token that was previously opened.
            NativeMethods.CloseHandle(impersonationToken);
            return(retVal);
        }
Example #4
0
        public void Open(string path, FileAccess mode, uint timeout)
        {
            IntPtr nativeHandle;

            for (;;)
            {
                NativeMethods.SecurityAttributes security = new NativeMethods.SecurityAttributes();
                security.inheritHandle = true;
                security.Length        = Marshal.SizeOf(security);

                nativeHandle = NativeMethods.CreateFile(path, NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE,
                                                        0, security, NativeMethods.OPEN_EXISTING, NativeMethods.FILE_FLAG_OVERLAPPED, 0);

                if (nativeHandle != IntPtr.Zero)
                {
                    break;
                }

                if (Marshal.GetLastWin32Error() != ERROR_PIPE_BUSY)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error(),
                                             "Error opening pipe");
                }
                MySql.Data.Common.LowResolutionStopwatch sw = MySql.Data.Common.LowResolutionStopwatch.StartNew();
                bool success = NativeMethods.WaitNamedPipe(path, timeout);
                sw.Stop();
                if (!success)
                {
                    if (timeout < sw.ElapsedMilliseconds ||
                        Marshal.GetLastWin32Error() == ERROR_SEM_TIMEOUT)
                    {
                        throw new TimeoutException("Timeout waiting for named pipe");
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error(),
                                                 "Error waiting for pipe");
                    }
                }
                timeout -= (uint)sw.ElapsedMilliseconds;
            }
            handle     = new SafeFileHandle(nativeHandle, true);
            fileStream = new FileStream(handle, mode, 4096, true);
        }
Example #5
0
 private void CreatePipe(out IntPtr parentHandle, out IntPtr childHandle, bool parentInputs)
 {
     NativeMethods.SecurityAttributes securityAttributesParent = new NativeMethods.SecurityAttributes();
     securityAttributesParent.bInheritHandle = true;
     if (parentInputs)
     {
         NativeMethods.IntCreatePipe(out childHandle,
                                     out parentHandle,
                                     securityAttributesParent,
                                     0);
     }
     else
     {
         NativeMethods.IntCreatePipe(out parentHandle,
                                     out childHandle,
                                     securityAttributesParent,
                                     0);
     }
 }
        public bool Start()
        {
            processInfo = new NativeMethods.ProcessInformation();
            var startInfo = new NativeMethods.StartupInfo();
            var success   = false;

            SafeFileHandle hToken, hReadOut, hWriteOut, hReadErr, hWriteErr, hReadIn, hWriteIn;

            var securityAttributes = new NativeMethods.SecurityAttributes();

            securityAttributes.bInheritHandle = true;

            success = NativeMethods.CreatePipe(out hReadOut, out hWriteOut, securityAttributes, 0);
            if (!success)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            success = NativeMethods.CreatePipe(out hReadErr, out hWriteErr, securityAttributes, 0);
            if (!success)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            success = NativeMethods.CreatePipe(out hReadIn, out hWriteIn, securityAttributes, 0);
            if (!success)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            success = NativeMethods.SetHandleInformation(hReadOut, NativeMethods.Constants.HANDLE_FLAG_INHERIT, 0);
            if (!success)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            // Logon user
            success = NativeMethods.LogonUser(
                runSpec.Credentials.UserName,
                runSpec.Credentials.Domain,
                runSpec.Credentials.Password,
                NativeMethods.LogonType.LOGON32_LOGON_BATCH,
                NativeMethods.LogonProvider.LOGON32_PROVIDER_DEFAULT,
                out hToken
                );
            if (!success)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            NativeMethods.LUID privilegeLuid;
            if (!NativeMethods.LookupPrivilegeValue(null, "SeImpersonatePrivilege", out privilegeLuid))
            {
                int lastError = Marshal.GetLastWin32Error();
                throw new Win32Exception(lastError, "Error calling LookupPrivilegeValue: " + lastError);
            }

            var tokenPrivileges = new NativeMethods.TOKEN_PRIVILEGES();

            tokenPrivileges.PrivilegeCount = 1;
            tokenPrivileges.Attributes     = 1;
            tokenPrivileges.Luid           = privilegeLuid;
            if (!NativeMethods.AdjustTokenPrivileges(hToken, false,
                                                     ref tokenPrivileges,
                                                     1024, IntPtr.Zero, IntPtr.Zero))
            {
                var lastError = Marshal.GetLastWin32Error();
                throw new Win32Exception(lastError, "Error calling AdjustTokenPrivileges: " + lastError);
            }

            IntPtr unmanagedEnv;

            if (!NativeMethods.CreateEnvironmentBlock(out unmanagedEnv, hToken.DangerousGetHandle(), false))
            {
                int lastError = Marshal.GetLastWin32Error();
                throw new Win32Exception(lastError, "Error calling CreateEnvironmentBlock: " + lastError);
            }

            // Create process
            startInfo.cb         = Marshal.SizeOf(startInfo);
            startInfo.dwFlags    = NativeMethods.Constants.STARTF_USESTDHANDLES;
            startInfo.hStdOutput = hWriteOut;
            startInfo.hStdError  = hWriteErr;
            startInfo.hStdInput  = hReadIn;

            success = NativeMethods.CreateProcessWithTokenW(
                hToken,
                NativeMethods.LogonFlags.WithProfile,
                null,
                CommandLine(),
                NativeMethods.CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT,
                unmanagedEnv,
                null,
                ref startInfo,
                out processInfo
                );

            if (!success)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            NativeMethods.DestroyEnvironmentBlock(unmanagedEnv);
            NativeMethods.CloseHandle(processInfo.hThread);

            Handle = processInfo.hProcess;

            startInfo.hStdOutput.Close();
            startInfo.hStdError.Close();
            startInfo.hStdInput.Close();
            StandardOutput = new StreamReader(new FileStream(hReadOut, FileAccess.Read), Console.OutputEncoding);
            StandardError  = new StreamReader(new FileStream(hReadErr, FileAccess.Read), Console.OutputEncoding);
            StandardInput  = new StreamWriter(new FileStream(hWriteIn, FileAccess.Write), Console.InputEncoding)
            {
                AutoFlush = true
            };

            WaitForExitAsync();

            return(success);
        }
Example #7
0
        private void ServiceMain()
        {
            const string testFile = @"C:\tmp\test-it.ps1";

            File.Delete(testFile);
            File.WriteAllText(testFile, testPowershellScript);

            var permissionManager = new DesktopPermissionManager(userName);

            var    startupInfo       = new NativeMethods.StartupInfo();
            string lpApplicationName = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
            var    cmdLine           = new StringBuilder(1024);

            cmdLine.AppendFormat(@" -InputFormat None -NoLogo -NoProfile -NonInteractive -File {0}", testFile);

            permissionManager.AddDesktopPermission();

            using (var jobObject = new JobObject("StartProcessServiceJobObject"))
            {
                jobObject.KillProcessesOnJobClose = true;

                while (!ct.IsCancellationRequested)
                {
                    try
                    {
                        log.Debug("Executing command: '{0}'", cmdLine);

                        // Now create the process as the user
                        NativeMethods.ProcessInformation pi;

                        var saProcessAttributes = new NativeMethods.SecurityAttributes();
                        var saThreadAttributes  = new NativeMethods.SecurityAttributes();

                        var createProcessFlags =
                            NativeMethods.CreateProcessFlags.CREATE_NO_WINDOW |
                            NativeMethods.CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT;

                        IntPtr primaryToken = Utils.LogonAndGetPrimaryToken(userName, password);

                        if (NativeMethods.CreateProcessAsUser(primaryToken,
                                                              lpApplicationName,
                                                              cmdLine,
                                                              saProcessAttributes,
                                                              saThreadAttributes,
                                                              false,
                                                              createProcessFlags,
                                                              IntPtr.Zero,
                                                              workingDir,
                                                              startupInfo,
                                                              out pi))
                        {
                            log.Debug("created process: '{0}' pid: '{1}'", cmdLine.ToString(), pi.dwProcessId);
                            jobObject.AddProcess(pi.hProcess);
                            log.Debug("job object has '{0}' processes in it.", jobObject.GetJobProcesses().Count());
                            NativeMethods.CloseHandle(pi.hProcess);
                            NativeMethods.CloseHandle(pi.hThread);
                        }
                        else
                        {
                            int err = Marshal.GetLastWin32Error();
                            log.Error("Error '{0}' creating process.", err);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.ErrorException("Exception creating process.", ex);
                    }
                    finally
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(10));
                    }
                }
            }

            permissionManager.RemoveDesktopPermission();
        }
Example #8
0
        private static NativeMethods.ProcessInformation DoCreateProcessAsUser()
        {
            var startupInfo = new NativeMethods.StartupInfo();

            string lpApplicationName = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
            // string lpApplicationName = @"C:\Windows\System32\cmd.exe";

            var cmdLine = new StringBuilder(1024);

            // NB: /k will keep window open. Try running powershell from the window and you won't see any modules available. Weird.
            // This works, however: runas /user:test_user /noprofile /savecred "powershell -NoExit"
            // cmdLine.Append(@" /k set");

            // Other commands to try:
            // cmdLine.Append(@" -NoExit -Command ""dir env:"""); // Look at the environment
            // cmdLine.Append(@"powershell.exe -InputFormat None -NoLogo -NoProfile -NonInteractive -Command ""echo 'START'; Start-Sleep -s 15; echo 'STOP'""");
            // cmdLine.Append(@"cmd /c ping 127.0.0.1 -n 15 -w 1000"); // Useful for "sleep"
            cmdLine.Append(@" -InputFormat None -NoLogo -NoProfile -NonInteractive -Command ""Add-Content -Path C:\tmp\test.txt -Value FOO""");

            // Create structs
            var saProcessAttributes = new NativeMethods.SecurityAttributes();
            var saThreadAttributes  = new NativeMethods.SecurityAttributes();

            // Now create the process as the user
            NativeMethods.ProcessInformation pi;

            var createProcessFlags =
                NativeMethods.CreateProcessFlags.CREATE_NO_WINDOW |
                NativeMethods.CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT;
            // NativeMethods.CreateProcessFlags.CREATE_NEW_CONSOLE; // Remove this to have a hidden window. Having this here allows you to see output

            IntPtr primaryToken = Utils.LogonAndGetPrimaryToken(userName, password);

            /*
             * uint sessionId = 1;
             * if (NativeMethods.SetTokenInformation(primaryToken,
             *  NativeMethods.TokenInformationClass.TokenSessionId,
             *  ref sessionId, (uint)Marshal.SizeOf(sessionId)))
             * {
             */
            if (NativeMethods.CreateProcessWithToken(primaryToken, NativeMethods.LogonFlags.LOGON_WITH_PROFILE,
                                                     lpApplicationName, cmdLine.ToString(), createProcessFlags, IntPtr.Zero, workingDir,
                                                     startupInfo, out pi))
            {
                Console.WriteLine("create-process-with-token cmd: '{0}' pid: '{1}'", cmdLine.ToString(), pi.dwProcessId);
                return(pi);
            }
            else
            {
                throw new Win32Exception();
            }

            /*
             * }
             * else
             * {
             *  throw new Win32Exception();
             * }
             */

            /*
             * var profileInfo = new NativeMethods.ProfileInfo();
             * profileInfo.lpUserName = userName;
             *
             * if (NativeMethods.LoadUserProfile(primaryToken, profileInfo))
             * {
             *  IntPtr envBlock = IntPtr.Zero;
             *  if (NativeMethods.CreateEnvironmentBlock(out envBlock, primaryToken, false))
             *  {
             *      // http://odetocode.com/blogs/scott/archive/2004/10/29/createprocessasuser.aspx
             *      if (NativeMethods.CreateProcessAsUser(
             *          primaryToken,
             *          lpApplicationName,
             *          cmdLine, // lpCommandLine
             *          saProcessAttributes,
             *          saThreadAttributes,
             *          false, // bInheritHandles
             *          createProcessFlags,
             *          envBlock,
             *          workingDir,
             *          startupInfo,
             *          out pi))
             *      {
             *          Console.WriteLine("create-process-as-user cmd: '{0}' pid: '{1}'", cmdLine.ToString(), pi.dwProcessId);
             *          return pi;
             *      }
             *      else
             *      {
             *          throw new Win32Exception();
             *      }
             *  }
             *  else
             *  {
             *      throw new Win32Exception();
             *  }
             * }
             * else
             * {
             *  throw new Win32Exception();
             * }
             */
        }