public static ProcessStartResult StartProcess(string exe, string[] args = null, bool isHidden = false, bool waitForExit = false, uint waitTimeout = 0) { string command; var startupInfo = CreateStartupInfo(exe, args, isHidden, out command); ProcessInformation processInfo; var processSecAttributes = new SecurityAttributes(); processSecAttributes.Length = Marshal.SizeOf(processSecAttributes); var threadSecAttributes = new SecurityAttributes(); threadSecAttributes.Length = Marshal.SizeOf(threadSecAttributes); CreationFlags creationFlags = 0; if (isHidden) { creationFlags = CreationFlags.CreateNoWindow; } var started = Win32Api.CreateProcess(exe, command, ref processSecAttributes, ref threadSecAttributes, false, Convert.ToInt32(creationFlags), IntPtr.Zero, null, ref startupInfo, out processInfo); var result = CreateProcessStartResult(waitForExit, waitTimeout, processInfo, started); return(result); }
internal static extern bool DuplicateTokenEx( IntPtr existingToken, uint desiredAccess, ref SecurityAttributes threadAttributes, int impersonationLevel, int tokenType, ref IntPtr newToken);
private static SafeFileHandle CreateFileInternal(string path, uint access, FileShare share, FileMode mode, uint attributes) { var securityAttributes = new SecurityAttributes(); securityAttributes.Length = Marshal.SizeOf(securityAttributes); securityAttributes.SecurityDescriptor = IntPtr.Zero; securityAttributes.InheritHandle = false; if (share.HasFlag(FileShare.Inheritable)) { share &= ~FileShare.Inheritable; securityAttributes.InheritHandle = true; } SafeFileHandle fileHandle = CreateFileNative(path, access, share, ref securityAttributes, mode, attributes, IntPtr.Zero); if (fileHandle.IsInvalid) { fileHandle.Close(); int hResult = Marshal.GetHRForLastWin32Error(); Marshal.ThrowExceptionForHR(hResult); } return(fileHandle); }
public static extern bool DuplicateTokenEx( SafeFileHandle hExistingToken, uint dwDesiredAccess, SecurityAttributes lpTokenAttributes, SecurityImpersonationLevel impersonationLevel, TokenType tokenType, out IntPtr hNewToken);
/// <summary> /// A clone of Process.CreatePipe. This is only implemented because reflection with /// out parameters are a pain. /// Note: This is only finished for w2k and higher machines. /// </summary> /// <param name="parentHandle"></param> /// <param name="childHandle"></param> /// <param name="parentInputs">Specifies whether the parent will be performing the writes.</param> public static void MyCreatePipe(out IntPtr parentHandle, out IntPtr childHandle, bool parentInputs) { string pipename = @"\\.\pipe\Global\" + Guid.NewGuid(); var attributes2 = new SecurityAttributes { bInheritHandle = false }; parentHandle = CreateNamedPipe(pipename, 0x40000003, 0, 0xff, 0x1000, 0x1000, 0, attributes2); if (parentHandle == _invalidHandleValue) { throw new Win32Exception(); } var attributes3 = new SecurityAttributes { bInheritHandle = true }; int num1 = 0x40000000; if (parentInputs) { num1 = -2147483648; } childHandle = CreateFile(pipename, num1, 3, attributes3, 3, 0x40000080, NullHandleRef); if (childHandle == _invalidHandleValue) { throw new Win32Exception(); } }
public static extern bool DuplicateTokenEx( IntPtr hExistingToken, TokenAccess dwDesiredAccess, SecurityAttributes lpThreadAttributes, SecurityImpersonationLevel impersonationLevel, TokenType dwTokenType, out IntPtr phNewToken);
public static extern bool DuplicateTokenEx( IntPtr hExistingToken, Int32 dwDesiredAccess, ref SecurityAttributes lpThreadAttributes, Int32 ImpersonationLevel, Int32 dwTokenType, ref IntPtr phNewToken);
public void CopyTo(MethodDeclaration copy) { copy._name = _name; copy._sigType = _sigType; copy._flags = _flags; copy._implFlags = _implFlags; if (PInvoke != null) { PInvoke.CopyTo(copy.CreatePInvoke()); } ReturnType.CopyTo(copy.ReturnType); Parameters.CopyTo(copy.Parameters); GenericParameters.CopyTo(copy.GenericParameters); Overrides.CopyTo(copy.Overrides); CustomAttributes.CopyTo(copy.CustomAttributes); SecurityAttributes.CopyTo(copy.SecurityAttributes); if (MethodBody.IsValid(this)) { var methodBody = MethodBody.Load(this); methodBody.Build(copy); } }
private static extern bool DuplicateTokenEx( IntPtr hExistingToken, uint dwDesiredAccess, ref SecurityAttributes lpThreadAttributes, int tokenType, int impersonationLevel, ref IntPtr phNewToken);
static extern public int CreateFile(String fileName, uint desiredAccess, uint shareMode, SecurityAttributes securityAttributes, uint creationDisposition, uint flagsAndAttributes, uint templateFile);
private static ProcessInfo RunProcess(ref StartInfoExtended sInfoEx, string commandLine) { int securityAttributeSize = Marshal.SizeOf <SecurityAttributes>(); var pSec = new SecurityAttributes { nLength = securityAttributeSize }; var tSec = new SecurityAttributes { nLength = securityAttributeSize }; var success = ProcessApi.CreateProcess( lpApplicationName: null, lpCommandLine: commandLine, lpProcessAttributes: ref pSec, lpThreadAttributes: ref tSec, bInheritHandles: false, dwCreationFlags: Constants.EXTENDED_STARTUPINFO_PRESENT, lpEnvironment: IntPtr.Zero, lpCurrentDirectory: null, lpStartupInfo: ref sInfoEx, lpProcessInformation: out ProcessInfo pInfo ); if (!success) { throw InteropException.CreateWithInnerHResultException("Could not create process."); } return(pInfo); }
public static extern IntPtr CreateDesktop( [MarshalAs(UnmanagedType.LPWStr)] string desktopName, [MarshalAs(UnmanagedType.LPWStr)] string device, // must be null. [MarshalAs(UnmanagedType.LPWStr)] string deviceMode, // must be null, [MarshalAs(UnmanagedType.U4)] int flags, // use 0 [MarshalAs(UnmanagedType.U4)] ACCESS_MASK accessMask, [MarshalAs(UnmanagedType.LPStruct)] SecurityAttributes attributes);
public static extern int CreateFile(String lpFileName, // file name uint dwDesiredAccess, // access mode uint dwShareMode, // share mode SecurityAttributes attr, // SD uint dwCreationDisposition, // how to create uint dwFlagsAndAttributes, // file attributes uint hTemplateFile); // handle to template file
static extern public int CreateFile(String fileName, uint desiredAccess, uint shareMode, SecurityAttributes securityAttributes, uint creationDisposition, uint flagsAndAttributes, uint templateFile);
// AnonymousPipeServerStream owner; public unsafe Win32AnonymousPipeServer(AnonymousPipeServerStream owner, PipeDirection direction, HandleInheritability inheritability, int bufferSize, PipeSecurity pipeSecurity) { IntPtr r, w; byte[] securityDescriptor = null; if (pipeSecurity != null) { securityDescriptor = pipeSecurity.GetSecurityDescriptorBinaryForm(); fixed(byte *securityDescriptorPtr = securityDescriptor) { SecurityAttributes att = new SecurityAttributes(inheritability, (IntPtr)securityDescriptorPtr); if (!Win32Marshal.CreatePipe(out r, out w, ref att, bufferSize)) { throw Win32PipeError.GetException(); } } var rh = new SafePipeHandle(r, true); var wh = new SafePipeHandle(w, true); if (direction == PipeDirection.Out) { server_handle = wh; client_handle = rh; } else { server_handle = rh; client_handle = wh; } }
internal static extern IntPtr CreateFileMapping( IntPtr hFile, ref SecurityAttributes lpAttributes, FileMapProtection flProtect, Int32 dwMaxSizeHi, Int32 dwMaxSizeLow, string lpName);
public static extern bool DuplicateTokenEx( SafeFileHandle hExistingToken, uint dwDesiredAccess, SecurityAttributes lpTokenAttributes, SecurityImpersonationLevel impersonationLevel, TokenType tokenType, out IntPtr hNewToken);
public static extern IntPtr CreateFile( String lpFileName, // file name uint dwDesiredAccess, // access mode uint dwShareMode, // share mode SecurityAttributes attr, // SD uint dwCreationDisposition, // how to create uint dwFlagsAndAttributes, // file attributes uint hTemplateFile); // handle to template file
private static extern IntPtr CreateNamedPipe(string pipeName, int openMode, int pipeMode, int maxInstances, int outBufferSize, int inBufferSize, int defaultTimeout, SecurityAttributes securityAttributes);
internal static extern bool DuplicateTokenEx( /* _In_ HANDLE */ [In] SafeTokenHandle existingToken, /* _In_ DWORD */ [In] TokenAccessRight desiredAccess, /* _In_opt_ LPSECURITY_ATTRIBUTES */ [In][Out] ref SecurityAttributes threadAttributes, /* _In_ SECURITY_IMPERSONATION_LEVEL */ [In] SecurityImpersonationLevel impersonationLevel, /* _In_ TOKEN_TYPE */ [In] TokenType tokenType, /* _Outptr_ PHANDLE */ [Out] out SafeTokenHandle newToken );
public static extern IntPtr CreateFile( string Filename, UInt32 DesiredAccess, UInt32 ShareMode, SecurityAttributes SecAttr, UInt32 CreationDisposition, UInt32 FlagsAndAttributes, IntPtr TemplateFile);
private SecurityAttributes GetSecurityAttributes() { var sa = new SecurityAttributes(); sa.Length = Marshal.SizeOf(sa); return(sa); }
public Pipe(SecurityAttributes securityAttributes) { if (!ConsoleApi.CreatePipe(out read, out write, ref securityAttributes, 0)) { throw new InteropException("Failed to create pipe.", Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error())); } }
public static extern SafeFileHandle CreateFile( [MarshalAs(UnmanagedType.LPWStr)] string lpFileName, uint dwDesiredAccess, int dwShareMode, [MarshalAs(UnmanagedType.LPStruct)] SecurityAttributes lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
private static extern SafeFileHandle CreateFileNative( [MarshalAs(UnmanagedType.LPWStr)] string path, [MarshalAs(UnmanagedType.U4)] uint access, [MarshalAs(UnmanagedType.U4)] FileShare share, [In] ref SecurityAttributes securityAttributes, [MarshalAs(UnmanagedType.U4)] FileMode mode, [MarshalAs(UnmanagedType.U4)] uint attributes, IntPtr templateFile);
public static extern SafeKernelTransactionHandle CreateTransaction( [MarshalAs(UnmanagedType.LPStruct)] SecurityAttributes lpTransactionAttributes, IntPtr uow, [MarshalAs(UnmanagedType.U4)] uint createOptions, [MarshalAs(UnmanagedType.U4)] uint isolationLevel, [MarshalAs(UnmanagedType.U4)] uint isolationFlags, [MarshalAs(UnmanagedType.U4)] int timeout, [MarshalAs(UnmanagedType.LPWStr)] string description);
internal static extern SafeFileHandle CreateFile( [In] string filename, [In] uint accessMode, [In] uint shareMode, ref SecurityAttributes securityAttributes, [In] uint creationDisposition, [In] uint flags, [In] IntPtr templateFileHandle);
public static extern IntPtr CreateFile( [In] string lpFileName, // file name [In] int dwDesiredAccess, // accessMode mode [In] int dwShareMode, // share mode [In] SecurityAttributes attr, // security attributes [In] int dwCreation, // how to create [In] int dwFlagsAndAttributes, // file attributes [In] IntPtr hTemplateFile // handle to template file );
public static extern UInt32 CreateFile( string lpFileName, // file name UInt32 dwDesiredAccess, // access mode UInt32 dwShareMode, // share mode SecurityAttributes lpSecurityAttributes, // SD UInt32 dwCreationDisposition, // how to create UInt32 dwFlagsAndAttributes, // file attributes UInt32 hTemplateFile // handle to template file );
public static extern UInt32 CreateFile( string lpFileName, // file name UInt32 dwDesiredAccess, // access mode UInt32 dwShareMode, // share mode SecurityAttributes lpSecurityAttributes, // SD UInt32 dwCreationDisposition, // how to create UInt32 dwFlagsAndAttributes, // file attributes UInt32 hTemplateFile // handle to template file );
public static bool launch(string game, string arguments) { String binPath; String exe; String dll; //Lets get our games straight if (game == "ETS2") { Environment.SetEnvironmentVariable("SteamGameId", "227300"); Environment.SetEnvironmentVariable("SteamAppID", "227300"); binPath = Launcher.ETS2Location + "\\bin\\win_x64"; exe = "\\eurotrucks2.exe"; dll = "\\core_ets2mp.dll"; arguments += " -64bit"; } else if (game == "ATS") { Environment.SetEnvironmentVariable("SteamGameId", "270880"); Environment.SetEnvironmentVariable("SteamAppID", "270880"); binPath = Launcher.ATSLocation + "\\bin\\win_x64"; exe = "\\amtrucks.exe"; dll = "\\core_atsmp.dll"; arguments += " -64bit"; } else { return(false); //Invalid game, lets not do this } //Intialize variables 'n stuff ProcessInformation processInformation = default(ProcessInformation); Startupinfo startupinfo = default(Startupinfo); SecurityAttributes securityAttributes = default(SecurityAttributes); SecurityAttributes securityAttributes2 = default(SecurityAttributes); startupinfo.cb = Marshal.SizeOf(startupinfo); securityAttributes.nLength = Marshal.SizeOf(securityAttributes); securityAttributes2.nLength = Marshal.SizeOf(securityAttributes2); //Lets run the game! if (!CreateProcess(binPath + exe, arguments, ref securityAttributes, ref securityAttributes2, false, 4u, IntPtr.Zero, binPath, ref startupinfo, out processInformation)) { return(false); } if (!Inject(processInformation.hProcess, Launcher.TruckersMPLocation + dll)) { return(false); } ResumeThread(processInformation.hThread); return(true); }
public static extern IntPtr CreateFile( string fileName, FileAccess desiredAccess, FileShare shareMode, ref SecurityAttributes securityAttributes, FileCreateDisposition creationDisposition, FileAttributes flagsAndAttributes, IntPtr templateFile );
public static extern IntPtr CreateNamedPipe( [In] string lpPipeName, // pipe name [In] int dwOpenMode, // pipe open mode [In] int dwPipeMode, // pipe-specific modes [In] int nMaxInstances, // maximum number of instances [In] int nOutBufferSize, // output buffer size [In] int nInBufferSize, // input buffer size [In] int nDefaultTimeOut, // time-out interval [In] SecurityAttributes attr // security attributes );
static extern int RegCreateKeyEx( IntPtr hKey, string lpSubKey, int Reserved, string lpClass, RegOption dwOptions, RegSAM samDesired, SecurityAttributes lpSecurityAttributes, out IntPtr phkResult, out RegResult lpdwDisposition);
/// <summary> /// A clone of Process.CreatePipe. This is only implemented because reflection with /// out parameters are a pain. /// Note: This is only finished for w2k and higher machines. /// </summary> /// <param name="parentHandle"></param> /// <param name="childHandle"></param> /// <param name="parentInputs">Specifies whether the parent will be performing the writes.</param> public static void MyCreatePipe(out IntPtr parentHandle, out IntPtr childHandle, bool parentInputs) { string pipename = @"\\.\pipe\Global\" + Guid.NewGuid(); var attributes2 = new SecurityAttributes{bInheritHandle = false}; parentHandle = CreateNamedPipe(pipename, 0x40000003, 0, 0xff, 0x1000, 0x1000, 0, attributes2); if (parentHandle == _invalidHandleValue){ throw new Win32Exception(); } var attributes3 = new SecurityAttributes{bInheritHandle = true}; int num1 = 0x40000000; if (parentInputs){ num1 = -2147483648; } childHandle = CreateFile(pipename, num1, 3, attributes3, 3, 0x40000080, NullHandleRef); if (childHandle == _invalidHandleValue){ throw new Win32Exception(); } }
internal static extern Microsoft.Win32.SafeHandles.SafeFileHandle CreateFile( [System.Runtime.InteropServices.In] string filename, [System.Runtime.InteropServices.In] uint accessMode, [System.Runtime.InteropServices.In] uint shareMode, ref SecurityAttributes securityAttributes, [System.Runtime.InteropServices.In] uint creationDisposition, [System.Runtime.InteropServices.In] uint flags, [System.Runtime.InteropServices.In] System.IntPtr templateFileHandle);
private static extern SafeFileHandle CreateFileW( string lpFileName, [MarshalAs(UnmanagedType.U4)] FileSystemRights dwDesiredAccess, [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode, SecurityAttributes lpSecurityAttributes, [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition, [MarshalAs(UnmanagedType.U4)] FileOptions dwFlagsAndAttributes, IntPtr hTemplateFile);
public static extern bool CreatePipe(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, SecurityAttributes lpPipeAttributes, int nSize);
//Change the security settings of the pipe so the SYSTEM ACCOUNT can interact with user accounts private static IntPtr CreateSecurity() { var ptrSec = IntPtr.Zero; var securityAttribute = new SecurityAttributes(); SecurityDescriptor securityDescription; if (!InitializeSecurityDescriptor(out securityDescription, 1)) return ptrSec; if (!SetSecurityDescriptorDacl(ref securityDescription, true, IntPtr.Zero, false)) return ptrSec; securityAttribute.lpSecurityDescriptor = Marshal.AllocHGlobal(Marshal.SizeOf(typeof (SecurityDescriptor))); Marshal.StructureToPtr(securityDescription, securityAttribute.lpSecurityDescriptor, false); securityAttribute.bInheritHandle = false; securityAttribute.nLength = Marshal.SizeOf(typeof (SecurityAttributes)); ptrSec = Marshal.AllocHGlobal(Marshal.SizeOf(typeof (SecurityAttributes))); Marshal.StructureToPtr(securityAttribute, ptrSec, false); return ptrSec; }
public static extern bool CreateDirectoryEx( string lpTemplateDirectory, string lpNewDirectory, SecurityAttributes lpSecurityAttributes = null);
public static extern bool DuplicateTokenEx( IntPtr hExistingToken, TokenAccess dwDesiredAccess, SecurityAttributes lpThreadAttributes, SecurityImpersonationLevel impersonationLevel, TokenType dwTokenType, out IntPtr phNewToken);
// TODO-Linux: Implement if needed public static IntPtr CreateSemaphore(ref SecurityAttributes securityAttributes, int initialCount, int maximumCount, string name) { Console.WriteLine("Warning using unimplemented method CreateSemaphore"); return IntPtr.Zero; }
private void CreatePipeWithSecurityAttributes(out SafeFileHandle readPipe, out SafeFileHandle writePipe, SecurityAttributes pipeAttributes, int size) { if (!NativeMethods.CreatePipe(out readPipe, out writePipe, pipeAttributes, size) || readPipe.IsInvalid || writePipe.IsInvalid) { throw new Win32Exception(); } }
public static extern bool CreatePipe(out IntPtr hReadPipe, out IntPtr hWritePipe, SecurityAttributes lpPipeAttributes, int nSize);
async Task CheckForUpdates() { try { // Remove any old ClickOnce installs try { var uninstallInfo = UninstallInfo.Find("IPFilter Updater"); if (uninstallInfo != null) { Trace.TraceWarning("Old ClickOnce app installed! Trying to remove..."); var uninstaller = new Uninstaller(); uninstaller.Uninstall(uninstallInfo); Trace.TraceInformation("Successfully removed ClickOnce app"); } } catch (Exception ex) { Trace.TraceError("Failed to remove old ClickOnce app: " + ex); telemetryClient?.TrackException(ex); } Trace.TraceInformation("Checking for software updates..."); progress.Report(new ProgressModel(UpdateState.Downloading, "Checking for software updates...", -1)); var updater = new Updater(); var result = await updater.CheckForUpdateAsync(); var currentVersion = new Version(Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion); var latestVersion = new Version(result.Version); Update.IsUpdateAvailable = latestVersion > currentVersion; if (Update.IsUpdateAvailable) { Update.AvailableVersion = latestVersion; Update.IsUpdateRequired = true; Update.MinimumRequiredVersion = latestVersion; Update.UpdateSizeBytes = 2000000; } Trace.TraceInformation("Current version: {0}", Update.CurrentVersion); Trace.TraceInformation("Available version: {0}", Update.AvailableVersion?.ToString() ?? "<no updates>"); if (!Update.IsUpdateAvailable ) return; if (MessageBoxHelper.Show(dispatcher, "Update Available", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes, "An update to version {0} is available. Would you like to update now?", Update.AvailableVersion) != MessageBoxResult.Yes) { return; } Trace.TraceInformation("Starting application update..."); // If we're not "installed", then don't check for updates. This is so the // executable can be stand-alone. Stand-alone self-update to come later. using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\IPFilter")) { var installPath = (string) key?.GetValue("InstallPath"); if (installPath == null) { using (var process = new Process()) { process.StartInfo = new ProcessStartInfo("https://davidmoore.github.io/ipfilter/") { UseShellExecute = true }; process.Start(); return; } } } var msiPath = Path.Combine(Path.GetTempPath(), "IPFilter.msi"); // Download the installer using (var handler = new WebRequestHandler()) { handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; var uri = new Uri($"{result.Uri}?{DateTime.Now.ToString("yyyyMMddHHmmss")}"); using (var httpClient = new HttpClient(handler)) using (var response = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken.Token)) { if (cancellationToken.IsCancellationRequested) { progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100)); Update.IsUpdating = false; return; } var length = response.Content.Headers.ContentLength; double lengthInMb = !length.HasValue ? -1 : (double)length.Value / 1024 / 1024; double bytesDownloaded = 0; using(var stream = await response.Content.ReadAsStreamAsync()) using(var msi = File.Open( msiPath, FileMode.Create, FileAccess.Write, FileShare.Read)) { var buffer = new byte[65535 * 4]; int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token); while (bytesRead != 0) { await msi.WriteAsync(buffer, 0, bytesRead, cancellationToken.Token); bytesDownloaded += bytesRead; if (length.HasValue) { double downloadedMegs = bytesDownloaded / 1024 / 1024; var percent = (int)Math.Floor((bytesDownloaded / length.Value) * 100); var status = string.Format(CultureInfo.CurrentUICulture, "Downloaded {0:F2} MB of {1:F2} MB", downloadedMegs, lengthInMb); Update.IsUpdating = true; Update.DownloadPercentage = percent; progress.Report(new ProgressModel(UpdateState.Downloading, status, percent)); } if (cancellationToken.IsCancellationRequested) { progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100)); Update.IsUpdating = false; return; } bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token); } } } } progress.Report(new ProgressModel(UpdateState.Ready, "Launching update...", 100)); Update.IsUpdating = false; // Now run the installer var sb = new StringBuilder("msiexec.exe "); // Enable logging for the installer sb.AppendFormat(" /l*v \"{0}\"", Path.Combine(Path.GetTempPath(), "IPFilter.log")); sb.AppendFormat(" /i \"{0}\"", msiPath); //sb.Append(" /passive"); ProcessInformation processInformation = new ProcessInformation(); StartupInfo startupInfo = new StartupInfo(); SecurityAttributes processSecurity = new SecurityAttributes(); SecurityAttributes threadSecurity = new SecurityAttributes(); processSecurity.nLength = Marshal.SizeOf(processSecurity); threadSecurity.nLength = Marshal.SizeOf(threadSecurity); const int NormalPriorityClass = 0x0020; if (!ProcessManager.CreateProcess(null, sb, processSecurity, threadSecurity, false, NormalPriorityClass, IntPtr.Zero, null, startupInfo, processInformation)) { throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()); } try { //dispatcher.Invoke(DispatcherPriority.Normal, new Action(Application.Current.Shutdown)); Application.Current.Shutdown(); } catch (Exception ex) { Trace.TraceError("Exception when shutting down app for update: " + ex); Update.ErrorMessage = "Couldn't shutdown the app to apply update."; telemetryClient?.TrackException(ex); } } catch (Exception ex) { Trace.TraceWarning("Application update check failed: " + ex); telemetryClient?.TrackException(ex); telemetryClient?.Flush(); } finally { progress.Report(new ProgressModel(UpdateState.Ready, "Ready", 0)); } }
public static void IntCreatePipe(out IntPtr hReadPipe, out IntPtr hWritePipe, SecurityAttributes lpPipeAttributes, int nSize) { bool ret = CreatePipe(out hReadPipe, out hWritePipe, lpPipeAttributes, nSize); if (!ret || hReadPipe == INVALID_HANDLE_VALUE || hWritePipe == INVALID_HANDLE_VALUE) throw new Win32Exception(); }
public extern static bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref SecurityAttributes lpProcessAttributes, ref SecurityAttributes lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref Startupinfo lpStartupInfo, out ProcessInformation lpProcessInformation);
public static extern bool CreateDirectory(string lpPathName, SecurityAttributes lpSecurityAttributes = null);
public RestrictedProcess(string fileName, string workingDirectory, IEnumerable<string> arguments = null, int bufferSize = 4096) { // Initialize fields this.fileName = fileName; this.IsDisposed = false; // Prepare startup info and redirect standard IO handles var startupInfo = new StartupInfo(); this.RedirectStandardIoHandles(ref startupInfo, bufferSize); // Create restricted token var restrictedToken = this.CreateRestrictedToken(); // Set mandatory label this.SetTokenMandatoryLabel(restrictedToken, SecurityMandatoryLabel.Low); var processSecurityAttributes = new SecurityAttributes(); var threadSecurityAttributes = new SecurityAttributes(); this.processInformation = new ProcessInformation(); const uint CreationFlags = (uint)( CreateProcessFlags.CREATE_SUSPENDED | CreateProcessFlags.CREATE_BREAKAWAY_FROM_JOB | CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT | CreateProcessFlags.CREATE_NEW_PROCESS_GROUP | CreateProcessFlags.DETACHED_PROCESS | // http://stackoverflow.com/questions/6371149/what-is-the-difference-between-detach-process-and-create-no-window-process-creat CreateProcessFlags.CREATE_NO_WINDOW) | (uint)ProcessPriorityClass.High; string commandLine; if (arguments != null) { var commandLineBuilder = new StringBuilder(); commandLineBuilder.AppendFormat("\"{0}\"", fileName); foreach (var argument in arguments) { commandLineBuilder.Append(' '); commandLineBuilder.Append(argument); } commandLine = commandLineBuilder.ToString(); } else { commandLine = fileName; } if (!NativeMethods.CreateProcessAsUser( restrictedToken, null, commandLine, processSecurityAttributes, threadSecurityAttributes, true, // In order to standard input, output and error redirection work, the handles must be inheritable and the CreateProcess() API must specify that inheritable handles are to be inherited by the child process by specifying TRUE in the bInheritHandles parameter. CreationFlags, IntPtr.Zero, workingDirectory, startupInfo, out this.processInformation)) { throw new Win32Exception(); } this.safeProcessHandle = new SafeProcessHandle(this.processInformation.Process); // This is a very important line! Without disposing the startupInfo handles, reading the standard output (or error) will hang forever. // Same problem described here: http://social.msdn.microsoft.com/Forums/vstudio/en-US/3c25a2e8-b1ea-4fc4-927b-cb865d435147/how-does-processstart-work-in-getting-output startupInfo.Dispose(); NativeMethods.CloseHandle(restrictedToken); }
extern public static IntPtr CreateSemaphore(ref SecurityAttributes securityAttributes, int initialCount, int maximumCount, string name);
private void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle childHandle, bool parentInputs, int bufferSize) { var securityAttributesParent = new SecurityAttributes { InheritHandle = true }; SafeFileHandle tempHandle = null; try { if (parentInputs) { this.CreatePipeWithSecurityAttributes(out childHandle, out tempHandle, securityAttributesParent, bufferSize); } else { this.CreatePipeWithSecurityAttributes(out tempHandle, out childHandle, securityAttributesParent, bufferSize); } // Duplicate the parent handle to be non-inheritable so that the child process // doesn't have access. This is done for correctness sake, exact reason is unclear. // One potential theory is that child process can do something brain dead like // closing the parent end of the pipe and there by getting into a blocking situation // as parent will not be draining the pipe at the other end anymore. // Create a duplicate of the output write handle for the std error write handle. // This is necessary in case the child application closes one of its std output handles. if (!NativeMethods.DuplicateHandle( new HandleRef(this, NativeMethods.GetCurrentProcess()), tempHandle, new HandleRef(this, NativeMethods.GetCurrentProcess()), out parentHandle, // Address of new handle. 0, false, // Make it un-inheritable. (int)DuplicateOptions.DUPLICATE_SAME_ACCESS)) { throw new Win32Exception(); } } finally { // Close inheritable copies of the handles you do not want to be inherited. if (tempHandle != null && !tempHandle.IsInvalid) { tempHandle.Close(); } } }
private void CreateStandardPipe(out SafeFileHandle readHandle, out SafeFileHandle writeHandle, StdHandle standardHandle, bool isInput, bool redirect) { if (redirect) { var security = new SecurityAttributes { bInheritHandle = true }; if (!CreatePipe(out readHandle, out writeHandle, security, DEFAULT_PIPE_BUFFER_SIZE)) { var error = Marshal.GetLastWin32Error(); _debugLogger.Error("AsyncImpersonationProcess ({0}): CreatePipe failed. ErrorCode: {1} ({2})", StartInfo.FileName, error, new Win32Exception(error).Message); return; } if (!SetHandleInformation(isInput ? writeHandle : readHandle, HandleFlags.Inherit, HandleFlags.None)) { var error = Marshal.GetLastWin32Error(); _debugLogger.Error("AsyncImpersonationProcess ({0}): SetHandleInformation failed. ErrorCode: {1} ({2})", StartInfo.FileName, error, new Win32Exception(error).Message); } } else { if (isInput) { writeHandle = new SafeFileHandle(IntPtr.Zero, false); readHandle = GetStdHandle(standardHandle); var error = Marshal.GetLastWin32Error(); // Error code 1008 means "An attempt was made to reference a token that does not exist". This is the case // in particular in the server process because a Windows service does not have a standard output or standard error stream. // This is expected behaviour - not an error. if (error != 0 && error != 1008) _debugLogger.Error("AsyncImpersonationProcess ({0}): GetStdHandle failed. ErrorCode: {1} ({2})", StartInfo.FileName, error, new Win32Exception(error).Message); } else { readHandle = new SafeFileHandle(IntPtr.Zero, false); writeHandle = GetStdHandle(standardHandle); var error = Marshal.GetLastWin32Error(); // Error code 1008 means "An attempt was made to reference a token that does not exist". This is the case // in particular in the server process because a Windows service does not have a standard output or standard error stream. // This is expected behaviour - not an error. if (error != 0 && error != 1008) _debugLogger.Error("AsyncImpersonationProcess ({0}): GetStdHandle failed. ErrorCode: {1} ({2})", StartInfo.FileName, error, new Win32Exception(error).Message); } } }
public static extern bool CreateProcess( string lpApplicationName, // LPCTSTR [In] StringBuilder lpCommandLine, // LPTSTR - note: CreateProcess might insert a null somewhere in this string SecurityAttributes lpProcessAttributes, // LPSECURITY_ATTRIBUTES SecurityAttributes lpThreadAttributes, // LPSECURITY_ATTRIBUTES bool bInheritHandles, // BOOL int dwCreationFlags, // DWORD IntPtr lpEnvironment, // LPVOID string lpCurrentDirectory, // LPCTSTR CreateProcessStartupInfo lpStartupInfo, // LPSTARTUPINFO CreateProcessProcessInformation lpProcessInformation // LPPROCESS_INFORMATION );
public static extern bool CreateDirectoryTransacted( string lpTemplateDirectory, string lpNewDirectory, SecurityAttributes lpSecurityAttributes, IntPtr hTransaction);
/// <summary> /// Launches the given application with full admin rights, and in addition bypasses the Vista UAC prompt /// </summary> /// <param name="applicationName">The name of the application to launch</param> /// <param name="procInfo">Process information regarding the launched application that gets returned to the caller</param> /// <returns></returns> public static bool StartProcessAndBypassUac(String applicationName, out ProcessInformation procInfo) { uint winlogonPid = 0; IntPtr hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero; procInfo = new ProcessInformation(); // obtain the currently active session id; every logged on user in the system has a unique session id uint dwSessionId = WTSGetActiveConsoleSessionId(); // obtain the process id of the winlogon process that is running within the currently active session Process[] processes = Process.GetProcessesByName("winlogon"); foreach (Process p in processes) { if ((uint)p.SessionId == dwSessionId) { winlogonPid = (uint)p.Id; } } // obtain a handle to the winlogon process IntPtr hProcess = OpenProcess(MaximumAllowed, false, winlogonPid); // obtain a handle to the access token of the winlogon process if (!OpenProcessToken(hProcess, TokenDuplicate, ref hPToken)) { CloseHandle(hProcess); return false; } // Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser // I would prefer to not have to use a security attribute variable and to just // simply pass null and inherit (by default) the security attributes // of the existing token. However, in C# structures are value types and therefore // cannot be assigned the null value. var sa = new SecurityAttributes(); sa.Length = Marshal.SizeOf(sa); // copy the access token of the winlogon process; the newly created token will be a primary token if (!DuplicateTokenEx(hPToken, MaximumAllowed, ref sa, (int)SecurityImpersonationLevel.SecurityIdentification, (int)TokenType.TokenPrimary, ref hUserTokenDup)) { CloseHandle(hProcess); CloseHandle(hPToken); return false; } // By default CreateProcessAsUser creates a process on a non-interactive window station, meaning // the window station has a desktop that is invisible and the process is incapable of receiving // user input. To remedy this we set the lpDesktop parameter to indicate we want to enable user // interaction with the new process. var si = new Startupinfo(); si.cb = Marshal.SizeOf(si); si.lpDesktop = @"winsta0\default"; // interactive window station parameter; basically this indicates that the process created can display a GUI on the desktop // flags that specify the priority and creation method of the process const int dwCreationFlags = NormalPriorityClass | CreateNewConsole; // create a new process in the current user's logon session bool result = CreateProcessAsUser(hUserTokenDup, // client's access token null, // file to execute applicationName, // command line ref sa, // pointer to process SECURITY_ATTRIBUTES ref sa, // pointer to thread SECURITY_ATTRIBUTES false, // handles are not inheritable dwCreationFlags, // creation flags IntPtr.Zero, // pointer to new environment block null, // name of current directory ref si, // pointer to STARTUPINFO structure out procInfo // receives information about new process ); // invalidate the handles CloseHandle(hProcess); CloseHandle(hPToken); CloseHandle(hUserTokenDup); return result; // return the result }
public static extern bool DuplicateTokenEx(IntPtr existingTokenHandle, uint dwDesiredAccess, ref SecurityAttributes lpThreadAttributes, int tokenType, int impersonationLevel, ref IntPtr duplicateTokenHandle);
internal static extern IntPtr CreateFileMapping(uint hFile, SecurityAttributes lpAttributes, uint flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName);
public static extern bool DuplicateTokenEx(HandleRef hToken, int access, SecurityAttributes tokenAttributes, int impersonationLevel, int tokenType, ref IntPtr hNewToken);
internal static extern uint CreateSemaphore(SecurityAttributes auth, int initialCount, int maximumCount, string name);
public static extern bool CreateProcessAsUserW(IntPtr token, [MarshalAs(UnmanagedType.LPTStr)] string lpApplicationName, [MarshalAs(UnmanagedType.LPTStr)] string lpCommandLine, SecurityAttributes lpProcessAttributes, SecurityAttributes lpThreadAttributes, bool bInheritHandles, int dwCreationFlags, IntPtr lpEnvironment, [MarshalAs(UnmanagedType.LPTStr)] string lpCurrentDirectory, CreateProcessStartupInfo lpStartupInfo, CreateProcessProcessInformation lpProcessInformation);