public void Win32Exception_CodeAndMessage() { int error = unchecked((int)NTStatus.RPC_NT_CALL_FAILED); var ex = new Win32Exception(error, "msg"); Assert.Equal(error, ex.NativeErrorCode); Assert.Equal("msg", ex.Message); }
public static void InstantiateException() { int error = 5; string message = "This is an error message."; Exception innerException = new FormatException(); // Test each of the constructors and validate the properties of the resulting instance Win32Exception ex = new Win32Exception(); Assert.Equal(expected: E_FAIL, actual: ex.HResult); ex = new Win32Exception(error); Assert.Equal(expected: E_FAIL, actual: ex.HResult); Assert.Equal(expected: error, actual: ex.NativeErrorCode); ex = new Win32Exception(message); Assert.Equal(expected: E_FAIL, actual: ex.HResult); Assert.Equal(expected: message, actual: ex.Message); ex = new Win32Exception(error, message); Assert.Equal(expected: E_FAIL, actual: ex.HResult); Assert.Equal(expected: error, actual: ex.NativeErrorCode); Assert.Equal(expected: message, actual: ex.Message); ex = new Win32Exception(message, innerException); Assert.Equal(expected: E_FAIL, actual: ex.HResult); Assert.Equal(expected: message, actual: ex.Message); Assert.Same(expected: innerException, actual: ex.InnerException); }
public void Win32Exception_CodeAndMessage() { Win32ErrorCode error = Win32ErrorCode.ERROR_ALREADY_FIBER; var ex = new Win32Exception(error, "msg"); Assert.Equal(error, ex.NativeErrorCode); Assert.Equal("msg", ex.Message); }
public void WriteValue(string strSection, string strKey, string strValue) { int res = WritePrivateProfileString(strSection, strKey, strValue, this.m_fileName); if (res == 0) { Win32Exception wexp = new Win32Exception(Marshal.GetLastWin32Error()); throw new IniFileParsingException("win32:" + wexp.Message); } }
public void Win32Exception_MessageNotFound() { Win32ErrorCode error = (Win32ErrorCode)0x11111111; var ex = new Win32Exception(error); #if DESKTOP Assert.Equal("Unknown error (0x11111111)", ex.Message); #else Assert.Equal("Unknown Win32 error (0x11111111)", ex.Message); #endif }
public void Win32Exception_Serializable() { var exception = new Win32Exception(Win32ErrorCode.DNS_ERROR_AXFR, "It works, yo"); var formatter = new BinaryFormatter(); var ms = new MemoryStream(); formatter.Serialize(ms, exception); ms.Position = 0; var deserializedException = (Win32Exception)formatter.Deserialize(ms); Assert.Equal(exception.Message, deserializedException.Message); Assert.Equal(exception.NativeErrorCode, deserializedException.NativeErrorCode); }
static void Main () { // // All this test does is instantiate two Win32Exceptions // one with no known text, so it triggers a linear search // And one with a known message, to trigger a validation // // If stderr gets any output, there is a sorting error // in mono/io-layer/messages.c // Exception a = new Win32Exception (99999); a = new Win32Exception (9805); check (2, "Cannot find the specified file"); }
/// <devdoc> /// <para>Provides the main entry point for an executable that /// contains multiple associated services. Loads the specified services into memory so they can be /// started.</para> /// </devdoc> public static void Run(ServiceBase[] services) { if (services == null || services.Length == 0) { throw new ArgumentException(SR.NoServices); } int sizeOfSERVICE_TABLE_ENTRY = Marshal.SizeOf <SERVICE_TABLE_ENTRY>(); IntPtr entriesPointer = Marshal.AllocHGlobal(checked ((services.Length + 1) * sizeOfSERVICE_TABLE_ENTRY)); SERVICE_TABLE_ENTRY[] entries = new SERVICE_TABLE_ENTRY[services.Length]; bool multipleServices = services.Length > 1; IntPtr structPtr; for (int index = 0; index < services.Length; ++index) { services[index].Initialize(multipleServices); entries[index] = services[index].GetEntry(); structPtr = entriesPointer + sizeOfSERVICE_TABLE_ENTRY * index; Marshal.StructureToPtr(entries[index], structPtr, fDeleteOld: false); } SERVICE_TABLE_ENTRY lastEntry = new SERVICE_TABLE_ENTRY(); lastEntry.callback = null; lastEntry.name = (IntPtr)0; structPtr = entriesPointer + sizeOfSERVICE_TABLE_ENTRY * services.Length; Marshal.StructureToPtr(lastEntry, structPtr, fDeleteOld: false); // While the service is running, this function will never return. It will return when the service // is stopped. // After it returns, SCM might terminate the process at any time // (so subsequent code is not guaranteed to run). bool res = StartServiceCtrlDispatcher(entriesPointer); foreach (ServiceBase service in services) { if (service._startFailedException != null) { // Propagate exceptions throw during OnStart. // Note that this same exception is also thrown from ServiceMainCallback // (so SCM can see it as well). service._startFailedException.Throw(); } } string errorMessage = ""; if (!res) { errorMessage = new Win32Exception().Message; Console.WriteLine(SR.CantStartFromCommandLine); } foreach (ServiceBase service in services) { service.Dispose(); if (!res) { service.WriteLogEntry(SR.Format(SR.StartFailed, errorMessage), true); } } }
internal static int Decrypt( SafeDeleteContext securityContext, byte[]?buffer, int offset, int count, bool isConfidential, bool isNtlm, out int newOffset, uint sequenceNumber) { if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length)) { Debug.Fail("Argument 'offset' out of range."); throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset)) { Debug.Fail("Argument 'count' out of range."); throw new ArgumentOutOfRangeException(nameof(count)); } if (isNtlm) { return(DecryptNtlm(securityContext, buffer, offset, count, isConfidential, out newOffset, sequenceNumber)); } // // Kerberos and up // TwoSecurityBuffers buffers = default; var securityBuffer = MemoryMarshal.CreateSpan(ref buffers._item0, 2); securityBuffer[0] = new SecurityBuffer(buffer, offset, count, SecurityBufferType.SECBUFFER_STREAM); securityBuffer[1] = new SecurityBuffer(0, SecurityBufferType.SECBUFFER_DATA); int errorCode; if (isConfidential) { errorCode = SSPIWrapper.DecryptMessage(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber); } else { errorCode = SSPIWrapper.VerifySignature(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber); } if (errorCode != 0) { Exception e = new Win32Exception(errorCode); if (NetEventSource.Log.IsEnabled()) { NetEventSource.Error(null, e); } throw e; } if (securityBuffer[1].type != SecurityBufferType.SECBUFFER_DATA) { throw new InternalException(securityBuffer[1].type); } newOffset = securityBuffer[1].offset; return(securityBuffer[1].size); }
public static void EnablePrivilege(SecurityEntity securityEntity) { if (!Enum.IsDefined(typeof(SecurityEntity), securityEntity)) { throw new InvalidEnumArgumentException("securityEntity", (int)securityEntity, typeof(SecurityEntity)); } var securityEntityValue = GetSecurityEntityValue(securityEntity); try { var locallyUniqueIdentifier = new NativeMethods.LUID(); if (NativeMethods.LookupPrivilegeValue(null, securityEntityValue, ref locallyUniqueIdentifier)) { var TOKEN_PRIVILEGES = new NativeMethods.TOKEN_PRIVILEGES(); TOKEN_PRIVILEGES.PrivilegeCount = 1; TOKEN_PRIVILEGES.Attributes = NativeMethods.SE_PRIVILEGE_ENABLED; TOKEN_PRIVILEGES.Luid = locallyUniqueIdentifier; var tokenHandle = IntPtr.Zero; try { var currentProcess = NativeMethods.GetCurrentProcess(); if (NativeMethods.OpenProcessToken(currentProcess, NativeMethods.TOKEN_ADJUST_PRIVILEGES | NativeMethods.TOKEN_QUERY, out tokenHandle)) { if (NativeMethods.AdjustTokenPrivileges(tokenHandle, false, ref TOKEN_PRIVILEGES, 1024, IntPtr.Zero, IntPtr.Zero)) { var lastError = Marshal.GetLastWin32Error(); if (lastError == NativeMethods.ERROR_NOT_ALL_ASSIGNED) { var win32Exception = new Win32Exception(); throw new InvalidOperationException("AdjustTokenPrivileges failed.", win32Exception); } } else { var win32Exception = new Win32Exception(); throw new InvalidOperationException("AdjustTokenPrivileges failed.", win32Exception); } } else { var win32Exception = new Win32Exception(); var exceptionMessage = string.Format(CultureInfo.InvariantCulture, "OpenProcessToken failed. CurrentProcess: {0}", currentProcess.ToInt32()); throw new InvalidOperationException(exceptionMessage, win32Exception); } } finally { if (tokenHandle != IntPtr.Zero) { NativeMethods.CloseHandle(tokenHandle); } } } else { var win32Exception = new Win32Exception(); var exceptionMessage = string.Format(CultureInfo.InvariantCulture, "LookupPrivilegeValue failed. SecurityEntityValue: {0}", securityEntityValue); throw new InvalidOperationException(exceptionMessage, win32Exception); } } catch (Exception e) { var exceptionMessage = string.Format(CultureInfo.InvariantCulture, "GrandPrivilege failed. SecurityEntity: {0}", securityEntity); throw new InvalidOperationException(exceptionMessage, e); } }
internal static bool IsLogonDeniedException(Exception exception) { Win32Exception win32exception = exception as Win32Exception; return((win32exception != null) && (win32exception.NativeErrorCode == (int)SecurityStatusPalErrorCode.LogonDenied)); }
/// <summary> /// Invokes the Win32Shutdown command on provided target computer using WSMan /// over a CIMSession. The flags parameter determines the type of shutdown operation /// such as shutdown, reboot, force etc. /// </summary> /// <param name="cmdlet">Cmdlet host for reporting errors</param> /// <param name="isLocalhost">True if local host computer</param> /// <param name="computerName">Target computer</param> /// <param name="flags">Win32Shutdown flags</param> /// <param name="credential">Optional credential</param> /// <param name="authentication">Optional authentication</param> /// <param name="formatErrorMessage">Error message format string that takes two parameters</param> /// <param name="ErrorFQEID">Fully qualified error Id</param> /// <param name="cancelToken">Cancel token</param> /// <returns>True on success</returns> internal static bool InvokeWin32ShutdownUsingWsman( PSCmdlet cmdlet, bool isLocalhost, string computerName, object[] flags, PSCredential credential, string authentication, string formatErrorMessage, string ErrorFQEID, CancellationToken cancelToken) { Dbg.Diagnostics.Assert(flags.Length == 2, "Caller need to verify the flags passed in"); bool isSuccess = false; string targetMachine = isLocalhost ? "localhost" : computerName; string authInUse = isLocalhost ? null : authentication; PSCredential credInUse = isLocalhost ? null : credential; var currentPrivilegeState = new PlatformInvokes.TOKEN_PRIVILEGE(); var operationOptions = new CimOperationOptions { Timeout = TimeSpan.FromMilliseconds(10000), CancellationToken = cancelToken, //This prefix works against all versions of the WinRM server stack, both win8 and win7 ResourceUriPrefix = new Uri(ComputerWMIHelper.CimUriPrefix) }; try { if (!(isLocalhost && PlatformInvokes.EnableTokenPrivilege(ComputerWMIHelper.SE_SHUTDOWN_NAME, ref currentPrivilegeState)) && !(!isLocalhost && PlatformInvokes.EnableTokenPrivilege(ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME, ref currentPrivilegeState))) { string message = StringUtil.Format(ComputerResources.PrivilegeNotEnabled, computerName, isLocalhost ? ComputerWMIHelper.SE_SHUTDOWN_NAME : ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME); ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(message), "PrivilegeNotEnabled", ErrorCategory.InvalidOperation, null); cmdlet.WriteError(errorRecord); return false; } using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(targetMachine, credInUse, authInUse, cancelToken, cmdlet)) { var methodParameters = new CimMethodParametersCollection(); methodParameters.Add(CimMethodParameter.Create( "Flags", flags[0], Microsoft.Management.Infrastructure.CimType.SInt32, CimFlags.None)); methodParameters.Add(CimMethodParameter.Create( "Reserved", flags[1], Microsoft.Management.Infrastructure.CimType.SInt32, CimFlags.None)); CimMethodResult result = cimSession.InvokeMethod( ComputerWMIHelper.CimOperatingSystemNamespace, ComputerWMIHelper.WMI_Class_OperatingSystem, ComputerWMIHelper.CimOperatingSystemShutdownMethod, methodParameters, operationOptions); int retVal = Convert.ToInt32(result.ReturnValue.Value, CultureInfo.CurrentCulture); if (retVal != 0) { var ex = new Win32Exception(retVal); string errMsg = StringUtil.Format(formatErrorMessage, computerName, ex.Message); ErrorRecord error = new ErrorRecord( new InvalidOperationException(errMsg), ErrorFQEID, ErrorCategory.OperationStopped, computerName); cmdlet.WriteError(error); } else { isSuccess = true; } } } catch (CimException ex) { string errMsg = StringUtil.Format(formatErrorMessage, computerName, ex.Message); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), ErrorFQEID, ErrorCategory.OperationStopped, computerName); cmdlet.WriteError(error); } catch (Exception ex) { CommandProcessorBase.CheckForSevereException(ex); string errMsg = StringUtil.Format(formatErrorMessage, computerName, ex.Message); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), ErrorFQEID, ErrorCategory.OperationStopped, computerName); cmdlet.WriteError(error); } finally { // Restore the previous privilege state if something unexpected happened PlatformInvokes.RestoreTokenPrivilege( isLocalhost ? ComputerWMIHelper.SE_SHUTDOWN_NAME : ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME, ref currentPrivilegeState); } return isSuccess; }
//////////////////////////////////////////////////////////////////////// /// <summary> /// get a string result...like the Win32 FormatMessage() function. /// </summary> /// <param name="error">a numeric win32 error code</param> /// <returns>a localized string corresponding to the given error code</returns> //////////////////////////////////////////////////////////////////////// public static string Win32ErrorString(int error) { string errorString = new Win32Exception(error).Message; return(errorString); }
public static void SerializeDeserialize(Win32Exception exception) { BinaryFormatterHelpers.AssertRoundtrips(exception, e => e.NativeErrorCode, e => e.ErrorCode); }
public static void GetObjectData_InvalidArgs_Throws() { var e = new Win32Exception(); Assert.Throws <ArgumentNullException>("info", () => e.GetObjectData(null, default(StreamingContext))); }
public static void SerializeDeserialize(Win32Exception exception) { BinaryFormatterHelpers.AssertRoundtrips(exception, e => e.NativeErrorCode, e => e.ErrorCode); }
/// <summary> /// Receive a packet synchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="timeoutInMilliseconds">Timeout in Milliseconds</param> /// <returns>SNI error code</returns> public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) { SNIPacket errorPacket; lock (this) { packet = null; try { if (timeoutInMilliseconds > 0) { _socket.ReceiveTimeout = timeoutInMilliseconds; } else if (timeoutInMilliseconds == -1) { // SqlCient internally represents infinite timeout by -1, and for TcpClient this is translated to a timeout of 0 _socket.ReceiveTimeout = 0; } else { // otherwise it is timeout for 0 or less than -1 ReportTcpSNIError(0, SNICommon.ConnTimeoutError, string.Empty); return(TdsEnums.SNI_WAIT_TIMEOUT); } packet = new SNIPacket(headerSize: 0, dataSize: _bufferSize); packet.ReadFromStream(_stream); if (packet.Length == 0) { errorPacket = packet; packet = null; var e = new Win32Exception(); return(ReportErrorAndReleasePacket(errorPacket, (uint)e.NativeErrorCode, 0, e.Message)); } return(TdsEnums.SNI_SUCCESS); } catch (ObjectDisposedException ode) { errorPacket = packet; packet = null; return(ReportErrorAndReleasePacket(errorPacket, ode)); } catch (SocketException se) { errorPacket = packet; packet = null; return(ReportErrorAndReleasePacket(errorPacket, se)); } catch (IOException ioe) { errorPacket = packet; packet = null; uint errorCode = ReportErrorAndReleasePacket(errorPacket, ioe); if (ioe.InnerException is SocketException socketException && socketException.SocketErrorCode == SocketError.TimedOut) { errorCode = TdsEnums.SNI_WAIT_TIMEOUT; } return(errorCode); } finally { _socket.ReceiveTimeout = 0; } } }
/// <summary> /// Writes the value of 'LicenseString' as an encrypted stream to the file:stream specified /// by 'currentFile'. /// </summary> /// <param name="currentFile">Fully qualified path to the alternate stream</param> /// <param name="LicenseString">The string value to encrypt and write to the alternate stream</param> public static void WriteAlternateStreamEncrypted(string currentFile, string LicenseString) { RC2CryptoServiceProvider rc2 = null; CryptoStream cs = null; MemoryStream ms = null; uint count = 0; IntPtr buffer = IntPtr.Zero; IntPtr hFile = IntPtr.Zero; try { Encoding enc = Encoding.Unicode; byte[] ba = enc.GetBytes(LicenseString); ms = new MemoryStream(); rc2 = new RC2CryptoServiceProvider(); rc2.Key = GetBytesFromHexString("7a6823a42a3a3ae27057c647db812d0"); rc2.IV = GetBytesFromHexString("827d961224d99b2d"); cs = new CryptoStream(ms, rc2.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(ba, 0, ba.Length); cs.FlushFinalBlock(); buffer = Marshal.AllocHGlobal(1000 * sizeof(char)); ZeroMemory(buffer, 1000 * sizeof(char)); uint nBytes = (uint)ms.Length; Marshal.Copy(ms.GetBuffer(), 0, buffer, (int)nBytes); DeleteFile(currentFile); hFile = CreateFile(currentFile, GENERIC_WRITE, 0, IntPtr.Zero, CREATE_ALWAYS, 0, IntPtr.Zero); if (-1 != hFile.ToInt32()) { bool bRtn = WriteFile(hFile, buffer, nBytes, out count, 0); } else { Exception excptn = new Win32Exception(Marshal.GetLastWin32Error()); if (!excptn.Message.Contains("cannot find the file")) { throw excptn; } } } catch (Exception exception) { Console.WriteLine("WriteAlternateStreamEncrypted()"); Console.WriteLine(exception.Message); } finally { CloseHandle(hFile); hFile = IntPtr.Zero; if (cs != null) { cs.Close(); cs.Dispose(); } rc2 = null; if (ms != null) { ms.Close(); ms.Dispose(); } if (buffer != IntPtr.Zero) { Marshal.FreeHGlobal(buffer); } } }
public static string GetLastWin32ErrorToString() { int lastWin32Error = Marshal.GetLastWin32Error(); string message = new Win32Exception(lastWin32Error).Message; return string.Format("{0}(Error Code : {1})", message, lastWin32Error); }
public static void InstantiateExceptionWithLongErrorString() { // This test checks that Win32Exception supports error strings greater than 256 characters. // Since we will have to rely on a message associated with an error code, // we try to reduce the flakiness by doing the following. // 1. Call FormatMessage to check whether the exception resource length >256 chars. // 2. If true, we validate that Win32Exception class can retrieve the complete resource string. // 3. If not we skip testing. int errorCode = 0x268; if (IsExceptionMessageLong(errorCode)) // Localized error string for 0x268 is not guaranteed to be >256 chars. { Win32Exception ex = new Win32Exception(errorCode); Assert.NotEqual("Unknown error (0x268)", ex.Message); Assert.True(ex.Message.Length > FirstPassBufferSize); ex = new Win32Exception(0x23); Assert.Equal(expected: "Unknown error (0x23)", actual: ex.Message); } }
public void Win32Exception_NativeErrorCode() { Win32ErrorCode error = Win32ErrorCode.ERROR_ALREADY_FIBER; var ex = new Win32Exception(error); Assert.Equal(error, ex.NativeErrorCode); }
public void Win32Exception_Message() { int error = unchecked((int)NTStatus.RPC_NT_CALL_FAILED); var ex = new Win32Exception(error); Assert.Equal("Unknown error (0xc002001b)", ex.Message); }
private static unsafe int ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine) { IntSecurity.UnmanagedCode.Demand(); FileStream output; FileStream error; int retValue = 0; if (outputName == null || outputName.Length == 0) { outputName = tempFiles.AddExtension("out"); } if (errorName == null || errorName.Length == 0) { errorName = tempFiles.AddExtension("err"); } // Create the files output = CreateInheritedFile(outputName); error = CreateInheritedFile(errorName); bool success = false; SafeNativeMethods.PROCESS_INFORMATION pi = new SafeNativeMethods.PROCESS_INFORMATION(); SafeProcessHandle procSH = new SafeProcessHandle(); SafeThreadHandle threadSH = new SafeThreadHandle(); SafeUserTokenHandle primaryToken = null; try { // Output the command line... StreamWriter sw = new StreamWriter(output, Encoding.UTF8); sw.Write(currentDir); sw.Write("> "); // 'true' command line is used in case the command line points to // a response file sw.WriteLine(trueCmdLine != null ? trueCmdLine : cmd); sw.WriteLine(); sw.WriteLine(); sw.Flush(); NativeMethods.STARTUPINFO si = new NativeMethods.STARTUPINFO(); si.cb = Marshal.SizeOf(si); #if FEATURE_PAL si.dwFlags = NativeMethods.STARTF_USESTDHANDLES; #else //!FEATURE_PAL si.dwFlags = NativeMethods.STARTF_USESTDHANDLES | NativeMethods.STARTF_USESHOWWINDOW; si.wShowWindow = NativeMethods.SW_HIDE; #endif //!FEATURE_PAL si.hStdOutput = output.SafeFileHandle; si.hStdError = error.SafeFileHandle; si.hStdInput = new SafeFileHandle(UnsafeNativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE), false); // // Prepare the environment // #if PLATFORM_UNIX StringDictionary environment = new CaseSensitiveStringDictionary(); #else StringDictionary environment = new StringDictionary(); #endif // PLATFORM_UNIX // Add the current environment foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables()) { environment[(string)entry.Key] = (string)entry.Value; } // Add the flag to indicate restricted security in the process environment["_ClrRestrictSecAttributes"] = "1"; #if DEBUG environment["OANOCACHE"] = "1"; #endif // set up the environment block parameter byte[] environmentBytes = EnvironmentBlock.ToByteArray(environment, false); fixed(byte *environmentBytesPtr = environmentBytes) { IntPtr environmentPtr = new IntPtr((void *)environmentBytesPtr); if (userToken == null || userToken.IsInvalid) { RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { success = NativeMethods.CreateProcess( null, // String lpApplicationName, new StringBuilder(cmd), // String lpCommandLine, null, // SECURITY_ATTRIBUTES lpProcessAttributes, null, // SECURITY_ATTRIBUTES lpThreadAttributes, true, // bool bInheritHandles, 0, // int dwCreationFlags, environmentPtr, // IntPtr lpEnvironment, currentDir, // String lpCurrentDirectory, si, // STARTUPINFO lpStartupInfo, pi); // PROCESS_INFORMATION lpProcessInformation); if (pi.hProcess != (IntPtr)0 && pi.hProcess != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) { procSH.InitialSetHandle(pi.hProcess); } if (pi.hThread != (IntPtr)0 && pi.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) { threadSH.InitialSetHandle(pi.hThread); } } } else { #if FEATURE_PAL throw new NotSupportedException(); #else success = SafeUserTokenHandle.DuplicateTokenEx( userToken, NativeMethods.TOKEN_ALL_ACCESS, null, NativeMethods.IMPERSONATION_LEVEL_SecurityImpersonation, NativeMethods.TOKEN_TYPE_TokenPrimary, out primaryToken ); if (success) { RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { success = NativeMethods.CreateProcessAsUser( primaryToken, // int token, null, // String lpApplicationName, cmd, // String lpCommandLine, null, // SECURITY_ATTRIBUTES lpProcessAttributes, null, // SECURITY_ATTRIBUTES lpThreadAttributes, true, // bool bInheritHandles, 0, // int dwCreationFlags, new HandleRef(null, environmentPtr), // IntPtr lpEnvironment, currentDir, // String lpCurrentDirectory, si, // STARTUPINFO lpStartupInfo, pi); // PROCESS_INFORMATION lpProcessInformation); if (pi.hProcess != (IntPtr)0 && pi.hProcess != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) { procSH.InitialSetHandle(pi.hProcess); } if (pi.hThread != (IntPtr)0 && pi.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) { threadSH.InitialSetHandle(pi.hThread); } } } #endif // !FEATURE_PAL } } } finally { // Close the file handles if (!success && (primaryToken != null && !primaryToken.IsInvalid)) { primaryToken.Close(); primaryToken = null; } output.Close(); error.Close(); } if (success) { try { bool signaled; ProcessWaitHandle pwh = null; try { pwh = new ProcessWaitHandle(procSH); signaled = pwh.WaitOne(ProcessTimeOut, false); } finally { if (pwh != null) { pwh.Close(); } } // Check for timeout if (!signaled) { throw new ExternalException(SR.GetString(SR.ExecTimeout, cmd), NativeMethods.WAIT_TIMEOUT); } // Check the process's exit code int status = NativeMethods.STILL_ACTIVE; if (!NativeMethods.GetExitCodeProcess(procSH, out status)) { throw new ExternalException(SR.GetString(SR.ExecCantGetRetCode, cmd), Marshal.GetLastWin32Error()); } retValue = status; } finally { procSH.Close(); threadSH.Close(); if (primaryToken != null && !primaryToken.IsInvalid) { primaryToken.Close(); } } } else { int err = Marshal.GetLastWin32Error(); if (err == NativeMethods.ERROR_NOT_ENOUGH_MEMORY) { throw new OutOfMemoryException(); } Win32Exception win32Exception = new Win32Exception(err); ExternalException ex = new ExternalException(SR.GetString(SR.ExecCantExec, cmd), win32Exception); throw ex; } return(retValue); }
public static void GetBackupKey(string system, string outFile = "") { // retrieves a DPAPI backup key from the given system (DC) specified // saving the key to the specified output file Interop.LSA_UNICODE_STRING aSystemName = new Interop.LSA_UNICODE_STRING(system); uint aWinErrorCode = 0; // initialize a pointer for the policy handle IntPtr LsaPolicyHandle = IntPtr.Zero; // these attributes are not used, but LsaOpenPolicy wants them to exists Interop.LSA_OBJECT_ATTRIBUTES aObjectAttributes = new Interop.LSA_OBJECT_ATTRIBUTES(); aObjectAttributes.Length = 0; aObjectAttributes.RootDirectory = IntPtr.Zero; aObjectAttributes.Attributes = 0; aObjectAttributes.SecurityDescriptor = IntPtr.Zero; aObjectAttributes.SecurityQualityOfService = IntPtr.Zero; // get a policy handle to the target server's LSA w/ 'POLICY_GET_PRIVATE_INFORMATION' rights uint aOpenPolicyResult = Interop.LsaOpenPolicy(ref aSystemName, ref aObjectAttributes, (uint)Interop.LSA_AccessPolicy.POLICY_GET_PRIVATE_INFORMATION, out LsaPolicyHandle); aWinErrorCode = Interop.LsaNtStatusToWinError(aOpenPolicyResult); if (aWinErrorCode == 0x00000000) { IntPtr PrivateData = IntPtr.Zero; // the DPAPI secret name we need to resolve to the actual key name Interop.LSA_UNICODE_STRING secretName = new Interop.LSA_UNICODE_STRING("G$BCKUPKEY_PREFERRED"); // grab the GUID of the G$BCKUPKEY_PREFERRED key uint ntsResult = Interop.LsaRetrievePrivateData(LsaPolicyHandle, ref secretName, out PrivateData); if (ntsResult != 0) { uint winErrorCode = Interop.LsaNtStatusToWinError(ntsResult); string errorMessage = new Win32Exception((int)winErrorCode).Message; Console.WriteLine(" [X] Error calling LsaRetrievePrivateData {0} : {1}", winErrorCode, errorMessage); return; } // copy out the GUID bytes Interop.LSA_UNICODE_STRING lusSecretData = (Interop.LSA_UNICODE_STRING)Marshal.PtrToStructure(PrivateData, typeof(Interop.LSA_UNICODE_STRING)); byte[] guidBytes = new byte[lusSecretData.Length]; Marshal.Copy(lusSecretData.buffer, guidBytes, 0, lusSecretData.Length); Guid backupKeyGuid = new Guid(guidBytes); Console.WriteLine("[*] Preferred backupkey Guid : {0}", backupKeyGuid.ToString()); // build the full name of the actual backup key string backupKeyName = String.Format("G$BCKUPKEY_{0}", backupKeyGuid.ToString()); Console.WriteLine("[*] Full preferred backupKeyName : {0}", backupKeyName); Interop.LSA_UNICODE_STRING backupKeyLSA = new Interop.LSA_UNICODE_STRING(backupKeyName); // retrieve the bytes of the full DPAPI private backup key IntPtr PrivateDataKey = IntPtr.Zero; uint ntsResult2 = Interop.LsaRetrievePrivateData(LsaPolicyHandle, ref backupKeyLSA, out PrivateDataKey); if (ntsResult2 != 0) { uint winErrorCode = Interop.LsaNtStatusToWinError(ntsResult2); string errorMessage = new Win32Exception((int)winErrorCode).Message; Console.WriteLine("\r\n[X] Error calling LsaRetrievePrivateData ({0}) : {1}\r\n", winErrorCode, errorMessage); return; } Interop.LSA_UNICODE_STRING backupKeyBytes = (Interop.LSA_UNICODE_STRING)Marshal.PtrToStructure(PrivateDataKey, typeof(Interop.LSA_UNICODE_STRING)); /* backup key format -> https://github.com/gentilkiwi/mimikatz/blob/3134be808f1f591974180b4578a43aef1696089f/mimikatz/modules/kuhl_m_lsadump.h#L34-L39 * typedef struct _KIWI_BACKUP_KEY { * DWORD version; * DWORD keyLen; * DWORD certLen; * BYTE data[ANYSIZE_ARRAY]; * } KIWI_BACKUP_KEY, *PKIWI_BACKUP_KEY; */ byte[] backupKey = new byte[backupKeyBytes.Length]; Marshal.Copy(backupKeyBytes.buffer, backupKey, 0, backupKeyBytes.Length); byte[] versionArray = new byte[4]; Array.Copy(backupKey, 0, versionArray, 0, 4); int version = BitConverter.ToInt32(versionArray, 0); byte[] keyLenArray = new byte[4]; Array.Copy(backupKey, 4, keyLenArray, 0, 4); int keyLen = BitConverter.ToInt32(keyLenArray, 0); byte[] certLenArray = new byte[4]; Array.Copy(backupKey, 8, certLenArray, 0, 4); int certLen = BitConverter.ToInt32(certLenArray, 0); byte[] backupKeyPVK = new byte[keyLen + 24]; Array.Copy(backupKey, 12, backupKeyPVK, 24, keyLen); // PVK_FILE_HDR pvkHeader = { PVK_MAGIC, PVK_FILE_VERSION_0, keySpec, PVK_NO_ENCRYPT, 0, byteLen }; // reference - https://github.com/gentilkiwi/mimikatz/blob/432276f23d7d2af12597e7847e268b751cc89dc5/mimilib/sekurlsadbg/kwindbg.h#L85-L92 // PVK_MAGIC backupKeyPVK[0] = 0x1E; backupKeyPVK[1] = 0xF1; backupKeyPVK[2] = 0xB5; backupKeyPVK[3] = 0xB0; // AT_KEYEXCHANGE == 1 backupKeyPVK[8] = 1; byte[] lenBytes = BitConverter.GetBytes((uint)keyLen); Array.Copy(lenBytes, 0, backupKeyPVK, 20, 4); if (String.IsNullOrEmpty(outFile)) { // base64 output string base64Key = Convert.ToBase64String(backupKeyPVK); Console.WriteLine("[*] Key :"); foreach (string line in Helpers.Split(base64Key, 80)) { Console.WriteLine(" {0}", line); } } else { FileStream fs = File.Create(outFile); BinaryWriter bw = new BinaryWriter(fs); bw.Write(backupKeyPVK); bw.Close(); fs.Close(); Console.WriteLine("[*] Backup key written to : {0}", outFile); } Interop.LsaFreeMemory(PrivateData); Interop.LsaClose(LsaPolicyHandle); } else { string errorMessage = new Win32Exception((int)aWinErrorCode).Message; Console.WriteLine("\r\n[X] Error calling LsaOpenPolicy ({0}) : {1}\r\n", aWinErrorCode, errorMessage); } }
public void ThrowIfFailed(string message) { if (this.Failed) { if (string.IsNullOrEmpty(message)) { message = this.ToString(); } #if DEBUG else { message += " (" + this.ToString() + ")"; } #endif // Wow. Reflection in a throw call. Later on this may turn out to have been a bad idea. // If you're throwing an exception I assume it's OK for me to take some time to give it back. // I want to convert the HRESULT to a more appropriate exception type than COMException. // Marshal.ThrowExceptionForHR does this for me, but the general call uses GetErrorInfo // if it's set, and then ignores the HRESULT that I've provided. This makes it so this // call works the first time but you get burned on the second. To avoid this, I use // the overload that explicitly ignores the IErrorInfo. // In addition, the function doesn't allow me to set the Message unless I go through // the process of implementing an IErrorInfo and then use that. There's no stock // implementations of IErrorInfo available and I don't think it's worth the maintenance // overhead of doing it, nor would it have significant value over this approach. Exception e = Marshal.GetExceptionForHR((int)this.value, new IntPtr(-1)); Assert.IsNotNull(e); // ArgumentNullException doesn't have the right constructor parameters, // (nor does Win32Exception...) // but E_POINTER gets mapped to NullReferenceException, // so I don't think it will ever matter. Assert.IsFalse(e is ArgumentNullException); // If we're not getting anything better than a COMException from Marshal, // then at least check the facility and attempt to do better ourselves. if (e.GetType() == typeof(COMException)) { switch (this.Facility) { case Facility.Win32: e = new Win32Exception(this.Code, message); break; default: e = new COMException(message, (int)this.value); break; } } else { ConstructorInfo cons = e.GetType().GetConstructor(new[] { typeof(string) }); if (null != cons) { e = cons.Invoke(new object[] { message }) as Exception; Assert.IsNotNull(e); } } throw e; } }
/// <summary> /// Throw out terminating error for LSA function invocations /// </summary> /// <param name="ret"></param> /// <param name="cmdlet"></param> private static void ThrowOutLsaError(uint ret, PSCmdlet cmdlet) { var ex = new Win32Exception(SAMAPI.LsaNtStatusToWinError((int)ret)); string errMsg = StringUtil.Format(ComputerResources.FailToResetPasswordOnLocalMachine, ex.Message); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToResetPasswordOnLocalMachine", ErrorCategory.OperationStopped, Dns.GetHostName()); cmdlet.ThrowTerminatingError(error); }
public Exception GetException(string message) { if (!Failed) { return(null); } // If you're throwing an exception I assume it's OK for me to take some time to give it back. // I want to convert the HRESULT to a more appropriate exception type than COMException. // Marshal.ThrowExceptionForHR does this for me, but the general call uses GetErrorInfo // if it's set, and then ignores the HRESULT that I've provided. This makes it so this // call works the first time but you get burned on the second. To avoid this, I use // the overload that explicitly ignores the IErrorInfo. // In addition, the function doesn't allow me to set the Message unless I go through // the process of implementing an IErrorInfo and then use that. There's no stock // implementations of IErrorInfo available and I don't think it's worth the maintenance // overhead of doing it, nor would it have significant value over this approach. Exception e = Marshal.GetExceptionForHR((int)_value, new IntPtr(-1)); Debug.Assert(e != null); // ArgumentNullException doesn't have the right constructor parameters, // (nor does Win32Exception...) // but E_POINTER gets mapped to NullReferenceException, // so I don't think it will ever matter. Debug.Assert(!(e is ArgumentNullException)); // If we're not getting anything better than a COMException from Marshal, // then at least check the facility and attempt to do better ourselves. if (e.GetType() == typeof(COMException)) { switch (Facility) { case Facility.Win32: // Win32Exception generates default messages based on the error type. // Don't override this behavior if the caller didn't explicitly // specify something more appropriate. if (string.IsNullOrEmpty(message)) { e = new Win32Exception(Code); } else { e = new Win32Exception(Code, message); } break; default: e = new COMException(message ?? e.Message, (int)_value); break; } } else { // Replace the message if we have something better. if (!string.IsNullOrEmpty(message)) { ConstructorInfo cons = e.GetType().GetConstructor(new[] { typeof(string) }); if (null != cons) { e = cons.Invoke(new object[] { message }) as Exception; Debug.Assert(e != null); } } } return(e); }
public static NET_DISPLAY_USER[] QueryDisplayInfoUser(string server_name) { List <NET_DISPLAY_USER> ret_list = new List <NET_DISPLAY_USER>(); IntPtr net_buffer = IntPtr.Zero; int res = 0; int free_res = 0; int request_index = 0; int max_request_entries = 100; int return_entries = 0; do { if ((server_name == null) || (server_name == string.Empty)) { res = WinApiNET.NetQueryDisplayInformation (IntPtr.Zero, NetqueryDisplayInfoLevel.User, request_index, max_request_entries, WinApiNET.MAX_PREFERRED_LENGTH, ref return_entries, ref net_buffer); } else { res = WinApiNET.NetQueryDisplayInformation (server_name, NetqueryDisplayInfoLevel.User, request_index, max_request_entries, WinApiNET.MAX_PREFERRED_LENGTH, ref return_entries, ref net_buffer); } if (res == WinApiNET.NERR_Success) { //success, add entries to return list ret_list.AddRange(NET_DISPLAY_USER.FromPtr(net_buffer, return_entries)); //free net buffer free_res = WinApiNET.NetApiBufferFree(net_buffer); if (free_res != WinApiNET.NERR_Success) { throw new Win32Exception(free_res); } //and break cycle break; } if (res == WinApiNET.ERROR_MORE_DATA) { //success, but more entries available ret_list.AddRange(NET_DISPLAY_USER.FromPtr(net_buffer, return_entries)); //free buffer free_res = WinApiNET.NetApiBufferFree(net_buffer); if (free_res != WinApiNET.NERR_Success) { throw new Win32Exception(free_res); } //set request_index (that is last member of ret_list) request_index = ret_list[ret_list.Count - 1].usri1_next_index; //and continue cycle continue; } //now res is error code Win32Exception win_ex = new Win32Exception(res); throw win_ex; } while (true); return(ret_list.ToArray()); }
public static SHARE_INFO_0[] GetShareInfos_0(string server_name) { List <SHARE_INFO_0> ret_list = new List <SHARE_INFO_0>(); IntPtr net_buffer = IntPtr.Zero; int entries_readed = 0; int entries_total = 0; uint resume_handle = 0; int res = 0; int res_free = 0; do { if ((server_name == null) || (server_name == string.Empty)) { res = WinApiNET.NetShareEnum (IntPtr.Zero, NET_INFO_LEVEL.LEVEL_0, ref net_buffer, WinApiNET.MAX_PREFERRED_LENGTH, ref entries_readed, ref entries_total, ref resume_handle); } else { res = WinApiNET.NetShareEnum (server_name, NET_INFO_LEVEL.LEVEL_0, ref net_buffer, WinApiNET.MAX_PREFERRED_LENGTH, ref entries_readed, ref entries_total, ref resume_handle); } //check result if (res == WinApiNET.NERR_Success) { //success, add to result list ret_list.AddRange(SHARE_INFO_0.FromBuffer(net_buffer, entries_readed)); //free buffer res_free = WinApiNET.NetApiBufferFree(net_buffer); if (res_free != WinApiNET.NERR_Success) { throw new Win32Exception(res_free); } //break cycle break; } if (res == WinApiNET.ERROR_MORE_DATA) { //success, but more data available ret_list.AddRange(SHARE_INFO_0.FromBuffer(net_buffer, entries_readed)); //free buffer res_free = WinApiNET.NetApiBufferFree(net_buffer); if (res_free != WinApiNET.NERR_Success) { throw new Win32Exception(res_free); } //continue cycle continue; } //now res is error code Win32Exception win_ex = new Win32Exception(res); throw win_ex; } while (true); return(ret_list.ToArray()); }
protected override void ProcessRecord() { string sddlForm; ObjectSecurity objectSecurity = this.securityDescriptor as ObjectSecurity; if (this.inputObject == null) { if (this.Path != null) { if (objectSecurity != null) { if ((this.CentralAccessPolicy != null || this.ClearCentralAccessPolicy) && !DownLevelHelper.IsWin8AndAbove()) { Exception parameterBindingException = new ParameterBindingException(); base.WriteError(new ErrorRecord(parameterBindingException, "SetAcl_OperationNotSupported", ErrorCategory.InvalidArgument, null)); return; } else { if (this.CentralAccessPolicy == null || !this.ClearCentralAccessPolicy) { IntPtr zero = IntPtr.Zero; NativeMethods.TOKEN_PRIVILEGE tOKENPRIVILEGE = new NativeMethods.TOKEN_PRIVILEGE(); try { if (this.CentralAccessPolicy == null) { if (this.ClearCentralAccessPolicy) { zero = this.GetEmptySacl(); if (zero == IntPtr.Zero) { SystemException systemException = new SystemException(UtilsStrings.GetEmptySaclFail); base.WriteError(new ErrorRecord(systemException, "SetAcl_ClearCentralAccessPolicy", ErrorCategory.InvalidResult, null)); return; } } } else { zero = this.GetSaclWithCapId(this.CentralAccessPolicy); if (zero == IntPtr.Zero) { SystemException systemException1 = new SystemException(UtilsStrings.GetSaclWithCapIdFail); base.WriteError(new ErrorRecord(systemException1, "SetAcl_CentralAccessPolicy", ErrorCategory.InvalidResult, null)); return; } } string[] path = this.Path; for (int i = 0; i < (int)path.Length; i++) { string str = path[i]; Collection <PathInfo> pathInfos = new Collection <PathInfo>(); CmdletProviderContext cmdletProviderContext = base.CmdletProviderContext; cmdletProviderContext.PassThru = this.Passthru; if (!this.isLiteralPath) { pathInfos = base.SessionState.Path.GetResolvedPSPathFromPSPath(str, base.CmdletProviderContext); } else { ProviderInfo providerInfo = null; PSDriveInfo pSDriveInfo = null; string unresolvedProviderPathFromPSPath = base.SessionState.Path.GetUnresolvedProviderPathFromPSPath(str, out providerInfo, out pSDriveInfo); pathInfos.Add(new PathInfo(pSDriveInfo, providerInfo, unresolvedProviderPathFromPSPath, base.SessionState)); cmdletProviderContext.SuppressWildcardExpansion = true; } foreach (PathInfo pathInfo in pathInfos) { if (!base.ShouldProcess(pathInfo.Path)) { continue; } try { base.InvokeProvider.SecurityDescriptor.Set(pathInfo.Path, objectSecurity, cmdletProviderContext); if (this.CentralAccessPolicy != null || this.ClearCentralAccessPolicy) { if (pathInfo.Provider.NameEquals(base.Context.ProviderNames.FileSystem)) { IntPtr tokenWithEnabledPrivilege = this.GetTokenWithEnabledPrivilege("SeSecurityPrivilege", tOKENPRIVILEGE); if (tokenWithEnabledPrivilege != IntPtr.Zero) { int num = NativeMethods.SetNamedSecurityInfo(pathInfo.ProviderPath, NativeMethods.SeObjectType.SE_FILE_OBJECT, NativeMethods.SecurityInformation.SCOPE_SECURITY_INFORMATION, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, zero); if (tokenWithEnabledPrivilege != IntPtr.Zero) { NativeMethods.TOKEN_PRIVILEGE tOKENPRIVILEGE1 = new NativeMethods.TOKEN_PRIVILEGE(); uint num1 = 0; NativeMethods.AdjustTokenPrivileges(tokenWithEnabledPrivilege, false, ref tOKENPRIVILEGE, Marshal.SizeOf(tOKENPRIVILEGE1), ref tOKENPRIVILEGE1, ref num1); NativeMethods.CloseHandle(tokenWithEnabledPrivilege); } if (num != 0) { SystemException win32Exception = new Win32Exception(num, UtilsStrings.SetCentralAccessPolicyFail); base.WriteError(new ErrorRecord(win32Exception, "SetAcl_SetNamedSecurityInfo", ErrorCategory.InvalidResult, null)); } } else { SystemException systemException2 = new SystemException(UtilsStrings.GetTokenWithEnabledPrivilegeFail); base.WriteError(new ErrorRecord(systemException2, "SetAcl_AdjustTokenPrivileges", ErrorCategory.InvalidResult, null)); return; } } else { Exception argumentException = new ArgumentException("Path"); base.WriteError(new ErrorRecord(argumentException, "SetAcl_Path", ErrorCategory.InvalidArgument, this.AclObject)); continue; } } } catch (NotSupportedException notSupportedException) { object[] objArray = new object[1]; objArray[0] = pathInfo.Path; ErrorRecord errorRecord = SecurityUtils.CreateNotSupportedErrorRecord(UtilsStrings.OperationNotSupportedOnPath, "SetAcl_OperationNotSupported", objArray); base.WriteError(errorRecord); } } } return; } finally { Marshal.FreeHGlobal(zero); } } else { Exception exception = new ArgumentException(UtilsStrings.InvalidCentralAccessPolicyParameters); ErrorRecord errorRecord1 = SecurityUtils.CreateInvalidArgumentErrorRecord(exception, "SetAcl_OperationNotSupported"); base.WriteError(errorRecord1); return; } } } else { Exception argumentException1 = new ArgumentException("AclObject"); base.WriteError(new ErrorRecord(argumentException1, "SetAcl_AclObject", ErrorCategory.InvalidArgument, this.AclObject)); return; } } else { Exception exception1 = new ArgumentException("Path"); base.WriteError(new ErrorRecord(exception1, "SetAcl_Path", ErrorCategory.InvalidArgument, this.AclObject)); } } else { PSMethodInfo item = this.inputObject.Methods["SetSecurityDescriptor"]; if (item == null) { ErrorRecord errorRecord2 = SecurityUtils.CreateNotSupportedErrorRecord(UtilsStrings.SetMethodNotFound, "SetAcl_OperationNotSupported", new object[0]); base.WriteError(errorRecord2); return; } else { CommonSecurityDescriptor commonSecurityDescriptor = this.securityDescriptor as CommonSecurityDescriptor; if (objectSecurity == null) { if (commonSecurityDescriptor == null) { Exception argumentException2 = new ArgumentException("AclObject"); base.WriteError(new ErrorRecord(argumentException2, "SetAcl_AclObject", ErrorCategory.InvalidArgument, this.AclObject)); return; } else { sddlForm = commonSecurityDescriptor.GetSddlForm(AccessControlSections.All); } } else { sddlForm = objectSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All); } try { object[] objArray1 = new object[1]; objArray1[0] = sddlForm; item.Invoke(objArray1); return; } catch (Exception exception3) { Exception exception2 = exception3; CommandProcessorBase.CheckForSevereException(exception2); ErrorRecord errorRecord3 = SecurityUtils.CreateNotSupportedErrorRecord(UtilsStrings.MethodInvokeFail, "SetAcl_OperationNotSupported", new object[0]); base.WriteError(errorRecord3); } } } }
/// <summary> /// /// </summary> /// <param name="aPrefix"></param> static private void CheckLastError(string aPrefix) { string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message; Debug.WriteLine(aPrefix + Marshal.GetLastWin32Error().ToString() + ": " + errorMessage); }
/// <summary> /// Receive a packet synchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="timeoutInMilliseconds">Timeout in Milliseconds</param> /// <returns>SNI error code</returns> public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) { SNIPacket errorPacket; lock (this) { packet = null; try { if (timeoutInMilliseconds > 0) { _socket.ReceiveTimeout = timeoutInMilliseconds; } else if (timeoutInMilliseconds == -1) { // SqlClient internally represents infinite timeout by -1, and for TcpClient this is translated to a timeout of 0 _socket.ReceiveTimeout = 0; } else { // otherwise it is timeout for 0 or less than -1 SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.ERR, "Connection Id {0}, Error 258, Timeout error occurred.", args0: _connectionId); ReportTcpSNIError(0, SNICommon.ConnTimeoutError, Strings.SNI_ERROR_11); return(TdsEnums.SNI_WAIT_TIMEOUT); } packet = RentPacket(headerSize: 0, dataSize: _bufferSize); packet.ReadFromStream(_stream); if (packet.Length == 0) { errorPacket = packet; packet = null; var e = new Win32Exception(); SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.ERR, "Connection Id {0}, Win32 exception occurred: {1}", args0: _connectionId, args1: e?.Message); return(ReportErrorAndReleasePacket(errorPacket, (uint)e.NativeErrorCode, 0, e.Message)); } SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.INFO, "Connection Id {0}, Data read from stream synchronously", args0: _connectionId); return(TdsEnums.SNI_SUCCESS); } catch (ObjectDisposedException ode) { errorPacket = packet; packet = null; SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.ERR, "Connection Id {0}, ObjectDisposedException occurred: {1}", args0: _connectionId, args1: ode?.Message); return(ReportErrorAndReleasePacket(errorPacket, ode)); } catch (SocketException se) { errorPacket = packet; packet = null; SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.ERR, "Connection Id {0}, Socket exception occurred: {1}", args0: _connectionId, args1: se?.Message); return(ReportErrorAndReleasePacket(errorPacket, se)); } catch (IOException ioe) { errorPacket = packet; packet = null; uint errorCode = ReportErrorAndReleasePacket(errorPacket, ioe); if (ioe.InnerException is SocketException socketException && socketException.SocketErrorCode == SocketError.TimedOut) { SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.ERR, "Connection Id {0}, IO exception occurred with Wait Timeout (error 258): {1}", args0: _connectionId, args1: ioe?.Message); errorCode = TdsEnums.SNI_WAIT_TIMEOUT; } SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.ERR, "Connection Id {0}, IO exception occurred: {1}", args0: _connectionId, args1: ioe?.Message); return(errorCode); } finally { _socket.ReceiveTimeout = 0; } } }
private CompilerResults CompileFromFileBatch(CompilerParameters options, string[] fileNames) { if (null == options) { throw new ArgumentNullException("options"); } if (null == fileNames) { throw new ArgumentNullException("fileNames"); } CompilerResults results = new CompilerResults(options.TempFiles); Process mcs = new Process(); // FIXME: these lines had better be platform independent. if (Path.DirectorySeparatorChar == '\\') { mcs.StartInfo.FileName = windowsMonoPath; mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " + BuildArgs(options, fileNames, ProviderOptions); } else { mcs.StartInfo.FileName = unixMcsCommand; mcs.StartInfo.Arguments = BuildArgs(options, fileNames, ProviderOptions); } mcsOutput = new StringCollection(); mcsOutMutex = new Mutex(); /* * string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH"); * if (monoPath != null) * monoPath = String.Empty; * * string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; * if (privateBinPath != null && privateBinPath.Length > 0) * monoPath = String.Format ("{0}:{1}", privateBinPath, monoPath); * * if (monoPath.Length > 0) { * StringDictionary dict = mcs.StartInfo.EnvironmentVariables; * if (dict.ContainsKey ("MONO_PATH")) * dict ["MONO_PATH"] = monoPath; * else * dict.Add ("MONO_PATH", monoPath); * } */ /* * reset MONO_GC_PARAMS - we are invoking compiler possibly with another GC that * may not handle some of the options causing compilation failure */ mcs.StartInfo.EnvironmentVariables ["MONO_GC_PARAMS"] = String.Empty; mcs.StartInfo.CreateNoWindow = true; mcs.StartInfo.UseShellExecute = false; mcs.StartInfo.RedirectStandardOutput = true; mcs.StartInfo.RedirectStandardError = true; mcs.ErrorDataReceived += new DataReceivedEventHandler(McsStderrDataReceived); try { mcs.Start(); } catch (Exception e) { Win32Exception exc = e as Win32Exception; if (exc != null) { throw new SystemException(String.Format("Error running {0}: {1}", mcs.StartInfo.FileName, Win32Exception.W32ErrorMessage(exc.NativeErrorCode))); } throw; } try { mcs.BeginOutputReadLine(); mcs.BeginErrorReadLine(); mcs.WaitForExit(); results.NativeCompilerReturnValue = mcs.ExitCode; } finally { mcs.CancelErrorRead(); mcs.CancelOutputRead(); mcs.Close(); } StringCollection sc = mcsOutput; bool loadIt = true; foreach (string error_line in mcsOutput) { CompilerError error = CreateErrorFromString(error_line); if (error != null) { results.Errors.Add(error); if (!error.IsWarning) { loadIt = false; } } } if (sc.Count > 0) { sc.Insert(0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine); results.Output = sc; } if (loadIt) { if (!File.Exists(options.OutputAssembly)) { StringBuilder sb = new StringBuilder(); foreach (string s in sc) { sb.Append(s + Environment.NewLine); } throw new Exception("Compiler failed to produce the assembly. Output: '" + sb.ToString() + "'"); } if (options.GenerateInMemory) { using (FileStream fs = File.OpenRead(options.OutputAssembly)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); results.CompiledAssembly = Assembly.Load(buffer, null); fs.Close(); } } else { // Avoid setting CompiledAssembly right now since the output might be a netmodule results.PathToAssembly = options.OutputAssembly; } } else { results.CompiledAssembly = null; } return(results); }
internal static int Encrypt( SafeDeleteContext securityContext, ReadOnlySpan <byte> buffer, bool isConfidential, bool isNtlm, [NotNull] ref byte[]?output, uint sequenceNumber) { SecPkgContext_Sizes sizes = default; bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_SIZES, ref sizes); Debug.Assert(success); int maxCount = checked (int.MaxValue - 4 - sizes.cbBlockSize - sizes.cbSecurityTrailer); if (buffer.Length > maxCount) { throw new ArgumentOutOfRangeException(nameof(buffer.Length), SR.Format(SR.net_io_out_range, maxCount)); } int resultSize = buffer.Length + sizes.cbSecurityTrailer + sizes.cbBlockSize; if (output == null || output.Length < resultSize + 4) { output = new byte[resultSize + 4]; } // Make a copy of user data for in-place encryption. buffer.CopyTo(output.AsSpan(4 + sizes.cbSecurityTrailer)); // Prepare buffers TOKEN(signature), DATA and Padding. ThreeSecurityBuffers buffers = default; var securityBuffer = MemoryMarshal.CreateSpan(ref buffers._item0, 3); securityBuffer[0] = new SecurityBuffer(output, 4, sizes.cbSecurityTrailer, SecurityBufferType.SECBUFFER_TOKEN); securityBuffer[1] = new SecurityBuffer(output, 4 + sizes.cbSecurityTrailer, buffer.Length, SecurityBufferType.SECBUFFER_DATA); securityBuffer[2] = new SecurityBuffer(output, 4 + sizes.cbSecurityTrailer + buffer.Length, sizes.cbBlockSize, SecurityBufferType.SECBUFFER_PADDING); int errorCode; if (isConfidential) { errorCode = SSPIWrapper.EncryptMessage(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber); } else { if (isNtlm) { securityBuffer[1].type |= SecurityBufferType.SECBUFFER_READONLY; } errorCode = SSPIWrapper.MakeSignature(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, 0); } if (errorCode != 0) { Exception e = new Win32Exception(errorCode); if (NetEventSource.Log.IsEnabled()) { NetEventSource.Error(null, e); } throw e; } // Compacting the result. resultSize = securityBuffer[0].size; bool forceCopy = false; if (resultSize != sizes.cbSecurityTrailer) { forceCopy = true; Buffer.BlockCopy(output, securityBuffer[1].offset, output, 4 + resultSize, securityBuffer[1].size); } resultSize += securityBuffer[1].size; if (securityBuffer[2].size != 0 && (forceCopy || resultSize != (buffer.Length + sizes.cbSecurityTrailer))) { Buffer.BlockCopy(output, securityBuffer[2].offset, output, 4 + resultSize, securityBuffer[2].size); } resultSize += securityBuffer[2].size; unchecked { output[0] = (byte)((resultSize) & 0xFF); output[1] = (byte)(((resultSize) >> 8) & 0xFF); output[2] = (byte)(((resultSize) >> 16) & 0xFF); output[3] = (byte)(((resultSize) >> 24) & 0xFF); } return(resultSize + 4); }
bool StartWithCreateProcess(ProcessStartInfo startInfo) { if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput) { throw new InvalidOperationException(SR.GetString(SR.StandardOutputEncodingNotAllowed)); } if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError) { throw new InvalidOperationException(SR.GetString(SR.StandardErrorEncodingNotAllowed)); } if (this.disposed) { throw new ObjectDisposedException(GetType().Name); } var proc_info = new ProcInfo(); if (startInfo.HaveEnvVars) { string [] strs = new string [startInfo.EnvironmentVariables.Count]; startInfo.EnvironmentVariables.Keys.CopyTo(strs, 0); proc_info.envKeys = strs; strs = new string [startInfo.EnvironmentVariables.Count]; startInfo.EnvironmentVariables.Values.CopyTo(strs, 0); proc_info.envValues = strs; } MonoIOError error; IntPtr stdin_read = IntPtr.Zero, stdin_write = IntPtr.Zero; IntPtr stdout_read = IntPtr.Zero, stdout_write = IntPtr.Zero; IntPtr stderr_read = IntPtr.Zero, stderr_write = IntPtr.Zero; try { if (startInfo.RedirectStandardInput) { CreatePipe(out stdin_read, out stdin_write, true); } else { stdin_read = MonoIO.ConsoleInput; stdin_write = IntPtr.Zero; } if (startInfo.RedirectStandardOutput) { CreatePipe(out stdout_read, out stdout_write, false); } else { stdout_read = IntPtr.Zero; stdout_write = MonoIO.ConsoleOutput; } if (startInfo.RedirectStandardError) { CreatePipe(out stderr_read, out stderr_write, false); } else { stderr_read = IntPtr.Zero; stderr_write = MonoIO.ConsoleError; } FillUserInfo(startInfo, ref proc_info); // // FIXME: For redirected pipes we need to send descriptors of // stdin_write, stdout_read, stderr_read to child process and // close them there (fork makes exact copy of parent's descriptors) // if (!CreateProcess_internal(startInfo, stdin_read, stdout_write, stderr_write, ref proc_info)) { throw new Win32Exception(-proc_info.pid, "ApplicationName='" + startInfo.FileName + "', CommandLine='" + startInfo.Arguments + "', CurrentDirectory='" + startInfo.WorkingDirectory + "', Native error= " + Win32Exception.W32ErrorMessage(-proc_info.pid)); } } catch { if (startInfo.RedirectStandardInput) { if (stdin_read != IntPtr.Zero) { MonoIO.Close(stdin_read, out error); } if (stdin_write != IntPtr.Zero) { MonoIO.Close(stdin_write, out error); } } if (startInfo.RedirectStandardOutput) { if (stdout_read != IntPtr.Zero) { MonoIO.Close(stdout_read, out error); } if (stdout_write != IntPtr.Zero) { MonoIO.Close(stdout_write, out error); } } if (startInfo.RedirectStandardError) { if (stderr_read != IntPtr.Zero) { MonoIO.Close(stderr_read, out error); } if (stderr_write != IntPtr.Zero) { MonoIO.Close(stderr_write, out error); } } throw; } finally { if (proc_info.Password != IntPtr.Zero) { Marshal.ZeroFreeBSTR(proc_info.Password); proc_info.Password = IntPtr.Zero; } } SetProcessHandle(new SafeProcessHandle(proc_info.process_handle, true)); SetProcessId(proc_info.pid); if (startInfo.RedirectStandardInput) { // // FIXME: The descriptor needs to be closed but due to wapi io-layer // not coping with duplicated descriptors any StandardInput write fails // // MonoIO.Close (stdin_read, out error); #if MOBILE var stdinEncoding = Encoding.Default; #else var stdinEncoding = Console.InputEncoding; #endif standardInput = new StreamWriter(new FileStream(stdin_write, FileAccess.Write, true, 8192), stdinEncoding) { AutoFlush = true }; } if (startInfo.RedirectStandardOutput) { MonoIO.Close(stdout_write, out error); Encoding stdoutEncoding = startInfo.StandardOutputEncoding ?? Console.Out.Encoding; standardOutput = new StreamReader(new FileStream(stdout_read, FileAccess.Read, true, 8192), stdoutEncoding, true); } if (startInfo.RedirectStandardError) { MonoIO.Close(stderr_write, out error); Encoding stderrEncoding = startInfo.StandardErrorEncoding ?? Console.Out.Encoding; standardError = new StreamReader(new FileStream(stderr_read, FileAccess.Read, true, 8192), stderrEncoding, true); } return(true); }
public unsafe void ServiceMainCallback(int argCount, IntPtr argPointer) { fixed(SERVICE_STATUS *pStatus = &_status) { string[] args = null; if (argCount > 0) { char **argsAsPtr = (char **)argPointer.ToPointer(); //Lets read the arguments // the first arg is always the service name. We don't want to pass that in. args = new string[argCount - 1]; for (int index = 0; index < args.Length; ++index) { // we increment the pointer first so we skip over the first argument. argsAsPtr++; args[index] = Marshal.PtrToStringUni((IntPtr)(*argsAsPtr)); } } // If we are being hosted, then Run will not have been called, since the EXE's Main entrypoint is not called. if (!_initialized) { Initialize(true); } _statusHandle = RegisterServiceCtrlHandlerEx(ServiceName, _commandCallbackEx, (IntPtr)0); _nameFrozen = true; if (_statusHandle == (IntPtr)0) { string errorMessage = new Win32Exception().Message; WriteLogEntry(SR.Format(SR.StartFailed, errorMessage), true); } _status.controlsAccepted = _acceptedCommands; _commandPropsFrozen = true; if ((_status.controlsAccepted & AcceptOptions.ACCEPT_STOP) != 0) { _status.controlsAccepted = _status.controlsAccepted | AcceptOptions.ACCEPT_SHUTDOWN; } _status.currentState = ServiceControlStatus.STATE_START_PENDING; bool statusOK = SetServiceStatus(_statusHandle, pStatus); if (!statusOK) { return; } // Need to execute the start method on a thread pool thread. // Most applications will start asynchronous operations in the // OnStart method. If such a method is executed in the current // thread, the async operations might get canceled immediately // since NT will terminate this thread right after this function // finishes. _startCompletedSignal = new ManualResetEvent(false); _startFailedException = null; ThreadPool.QueueUserWorkItem(new WaitCallback(this.ServiceQueuedMainCallback), args); _startCompletedSignal.WaitOne(); if (_startFailedException != null) { // Inform SCM that the service could not be started successfully. // (Unless the service has already provided another failure exit code) if (_status.win32ExitCode == 0) { _status.win32ExitCode = ServiceControlStatus.ERROR_EXCEPTION_IN_SERVICE; } } statusOK = SetServiceStatus(_statusHandle, pStatus); if (!statusOK) { WriteLogEntry(SR.Format(SR.StartFailed, new Win32Exception().Message), true); _status.currentState = ServiceControlStatus.STATE_STOPPED; SetServiceStatus(_statusHandle, pStatus); } } }
public DesktopInfo() { using (var searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")) { using (var collection = searcher.Get()) { var s = ((string)collection.Cast <ManagementBaseObject>().First()["UserName"]).Split('\\'); if (s.Length > 1) { Username = s.LastOrDefault(); } else { Username = s.FirstOrDefault(); } } } _Users_DesktopPath = @"c:\users\" + Username + @"\desktop\"; InputMouseEvent = Desktop_Sharing_Shared.Mouse.PInvoke.SendMouseEvent; InputKeyEvent = Desktop_Sharing_Shared.Keyboard.PInvoke.KeyEvent; m_hCurWinsta = new StationHandle(PInvoke.GetProcessWindowStation()); if (m_hCurWinsta.IsInvalid) { var er = new Win32Exception(Marshal.GetLastWin32Error()); throw er; } m_hWinsta = new StationHandle(PInvoke.OpenWindowStation("winsta0", false, ACCESS_MASK.WINSTA_ENUMDESKTOPS | ACCESS_MASK.WINSTA_READATTRIBUTES | ACCESS_MASK.WINSTA_ACCESSCLIPBOARD | ACCESS_MASK.WINSTA_CREATEDESKTOP | ACCESS_MASK.WINSTA_WRITEATTRIBUTES | ACCESS_MASK.WINSTA_ACCESSGLOBALATOMS | ACCESS_MASK.WINSTA_EXITWINDOWS | ACCESS_MASK.WINSTA_ENUMERATE | ACCESS_MASK.WINSTA_READSCREEN)); if (m_hWinsta.IsInvalid) { var er = new Win32Exception(Marshal.GetLastWin32Error()); throw er; } if (!PInvoke.SetProcessWindowStation(m_hWinsta.Handle)) { var er = new Win32Exception(Marshal.GetLastWin32Error()); throw er; } m_hDesk = new DesktopHandle(PInvoke.OpenDesktop("default", 0, false, ACCESS_MASK.DESKTOP_CREATEMENU | ACCESS_MASK.DESKTOP_CREATEWINDOW | ACCESS_MASK.DESKTOP_ENUMERATE | ACCESS_MASK.DESKTOP_HOOKCONTROL | ACCESS_MASK.DESKTOP_JOURNALPLAYBACK | ACCESS_MASK.DESKTOP_JOURNALRECORD | ACCESS_MASK.DESKTOP_READOBJECTS | ACCESS_MASK.DESKTOP_SWITCHDESKTOP | ACCESS_MASK.DESKTOP_WRITEOBJECTS)); if (m_hDesk.IsInvalid) { var er = new Win32Exception(Marshal.GetLastWin32Error()); throw er; } if (!PInvoke.SetThreadDesktop(m_hDesk.Handle)) { var er = new Win32Exception(Marshal.GetLastWin32Error()); throw er; } Current_Desktop = GetDesktop(m_hDesk); }
public void Win32Exception_Message() { Win32ErrorCode error = Win32ErrorCode.ERROR_INVALID_LABEL; var ex = new Win32Exception(error); Assert.Equal("Indicates a particular Security ID may not be assigned as the label of an object", ex.Message); }
private bool UsBMethod(string VID, string PID) { HidD_GetHidGuid(ref guidHID); hDevInfo = SetupDiGetClassDevs(ref guidHID, 0, IntPtr.Zero, DIGCF.DIGCF_PRESENT | DIGCF.DIGCF_DEVICEINTERFACE); { int errCode = Marshal.GetLastWin32Error(); string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message; Debug.LogError(errorMessage); } int bufferSize = 0; ArrayList HIDUSBAddress = new ArrayList(); int index = 0; while (true) { //获取设备,true获取到 SP_DEVICE_INTERFACE_DATA DeviceInterfaceData = new SP_DEVICE_INTERFACE_DATA(); DeviceInterfaceData.cbSize = Marshal.SizeOf(DeviceInterfaceData); bool result = false; result = SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guidHID, (UInt32)index, ref DeviceInterfaceData); if (!result) { int errCode = Marshal.GetLastWin32Error(); string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message; Debug.LogError(errorMessage); } //第一次调用出错,但可以返回正确的Size SP_DEVINFO_DATA strtInterfaceData = new SP_DEVINFO_DATA(); strtInterfaceData.cbSize = Marshal.SizeOf(strtInterfaceData); result = SetupDiGetDeviceInterfaceDetail(hDevInfo, ref DeviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, strtInterfaceData); //第二次调用传递返回值,调用即可成功 IntPtr detailDataBuffer = Marshal.AllocHGlobal(bufferSize); SP_DEVICE_INTERFACE_DETAIL_DATA detailData = new SP_DEVICE_INTERFACE_DETAIL_DATA(); detailData.cbSize = Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DETAIL_DATA)); //detailData.cbSize = 4 + Marshal.SystemDefaultCharSize; // 64位平台下,cbSize为8 if (IntPtr.Size == 8) { detailData.cbSize = 8; } Marshal.StructureToPtr(detailData, detailDataBuffer, false); result = SetupDiGetDeviceInterfaceDetail(hDevInfo, ref DeviceInterfaceData, detailDataBuffer, bufferSize, ref bufferSize, strtInterfaceData); if (!result) { int errCode = Marshal.GetLastWin32Error(); string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message; Debug.LogError(errorMessage); } //获取设备路径访 IntPtr pdevicePathName = (IntPtr)((int)detailDataBuffer + 4); devicePathName = Marshal.PtrToStringAuto(pdevicePathName); Debug.Log(devicePathName); if (CheckDeviceName(devicePathName, VID, PID)) // if (devicePathName.IndexOf(DriveName.ToLower()) > 0) { InDriveName = devicePathName; HIDUSBAddress.Add(devicePathName); break; } //HIDUSBAddress.Add(devicePathName); index++; if (index > 10) { break; } } //连接设备文件 int aa = CT_CreateFile(devicePathName); if (HIDUSBAddress.Count > 0 && aa == 1) { return(true); } else { return(false); } }
public void Win32Exception_NativeErrorCode() { int error = unchecked((int)NTStatus.RPC_NT_CALL_FAILED); var ex = new Win32Exception(error); Assert.Equal(error, ex.NativeErrorCode); }
bool StartWithCreateProcess(ProcessStartInfo startInfo) { if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput) { throw new InvalidOperationException(SR.GetString(SR.StandardOutputEncodingNotAllowed)); } if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError) { throw new InvalidOperationException(SR.GetString(SR.StandardErrorEncodingNotAllowed)); } if (this.disposed) { throw new ObjectDisposedException(GetType().Name); } var procInfo = new ProcInfo(); if (startInfo.HaveEnvVars) { List <string> envVariables = null; StringBuilder sb = null; foreach (DictionaryEntry de in startInfo.EnvironmentVariables) { if (de.Value == null) { continue; } if (envVariables == null) { envVariables = new List <string> (); } if (sb == null) { sb = new StringBuilder(); } else { sb.Clear(); } sb.Append((string)de.Key); sb.Append('='); sb.Append((string)de.Value); envVariables.Add(sb.ToString()); } procInfo.envVariables = envVariables?.ToArray(); } MonoIOError error; IntPtr stdin_read = IntPtr.Zero, stdin_write = IntPtr.Zero; IntPtr stdout_read = IntPtr.Zero, stdout_write = IntPtr.Zero; IntPtr stderr_read = IntPtr.Zero, stderr_write = IntPtr.Zero; try { if (startInfo.RedirectStandardInput) { CreatePipe(out stdin_read, out stdin_write, true); } else { stdin_read = MonoIO.ConsoleInput; stdin_write = IntPtr.Zero; } if (startInfo.RedirectStandardOutput) { CreatePipe(out stdout_read, out stdout_write, false); } else { stdout_read = IntPtr.Zero; stdout_write = MonoIO.ConsoleOutput; } if (startInfo.RedirectStandardError) { CreatePipe(out stderr_read, out stderr_write, false); } else { stderr_read = IntPtr.Zero; stderr_write = MonoIO.ConsoleError; } FillUserInfo(startInfo, ref procInfo); // // FIXME: For redirected pipes we need to send descriptors of // stdin_write, stdout_read, stderr_read to child process and // close them there (fork makes exact copy of parent's descriptors) // if (!CreateProcess_internal(startInfo, stdin_read, stdout_write, stderr_write, ref procInfo)) { throw new Win32Exception(-procInfo.pid, "ApplicationName='" + startInfo.FileName + "', CommandLine='" + startInfo.Arguments + "', CurrentDirectory='" + startInfo.WorkingDirectory + "', Native error= " + Win32Exception.GetErrorMessage(-procInfo.pid)); } } catch { if (startInfo.RedirectStandardInput) { if (stdin_read != IntPtr.Zero) { MonoIO.Close(stdin_read, out error); } if (stdin_write != IntPtr.Zero) { MonoIO.Close(stdin_write, out error); } } if (startInfo.RedirectStandardOutput) { if (stdout_read != IntPtr.Zero) { MonoIO.Close(stdout_read, out error); } if (stdout_write != IntPtr.Zero) { MonoIO.Close(stdout_write, out error); } } if (startInfo.RedirectStandardError) { if (stderr_read != IntPtr.Zero) { MonoIO.Close(stderr_read, out error); } if (stderr_write != IntPtr.Zero) { MonoIO.Close(stderr_write, out error); } } throw; } finally { if (procInfo.Password != IntPtr.Zero) { Marshal.ZeroFreeBSTR(procInfo.Password); procInfo.Password = IntPtr.Zero; } } SetProcessHandle(new SafeProcessHandle(procInfo.process_handle, true)); SetProcessId(procInfo.pid); #pragma warning disable 618 if (startInfo.RedirectStandardInput) { MonoIO.Close(stdin_read, out error); #if MOBILE var stdinEncoding = Encoding.Default; #else var stdinEncoding = Console.InputEncoding; #endif standardInput = new StreamWriter(new FileStream(stdin_write, FileAccess.Write, true, 8192), stdinEncoding) { AutoFlush = true }; } if (startInfo.RedirectStandardOutput) { MonoIO.Close(stdout_write, out error); Encoding stdoutEncoding = startInfo.StandardOutputEncoding ?? Console.Out.Encoding; standardOutput = new StreamReader(new FileStream(stdout_read, FileAccess.Read, true, 8192), stdoutEncoding, true); } if (startInfo.RedirectStandardError) { MonoIO.Close(stderr_write, out error); Encoding stderrEncoding = startInfo.StandardErrorEncoding ?? Console.Out.Encoding; standardError = new StreamReader(new FileStream(stderr_read, FileAccess.Read, true, 8192), stderrEncoding, true); } #pragma warning restore return(true); }
public static void GetObjectData_InvalidArgs_Throws() { var e = new Win32Exception(); Assert.Throws<ArgumentNullException>("info", () => e.GetObjectData(null, default(StreamingContext))); }
public List<string> GetCategories() { string returnString = new string(' ', MAXCATEGORIESLENGTH); int res = GetPrivateProfileString(null, null, null, returnString, MAXCATEGORIESLENGTH, this.m_fileName); if (res == 0) { Win32Exception wexp = new Win32Exception(Marshal.GetLastWin32Error()); throw new IniFileParsingException("win32:no categories. " + wexp.Message); } if (res == MAXCATEGORIESLENGTH - 2) //see docs: means buffer is full { throw new IniFileParsingException("data in categories is too long. must be <" + MAXCATEGORIESLENGTH); } List<string> result = new List<string>(returnString.Split('\0')); result.RemoveRange(result.Count - 2, 2); //removes the last 2 entries. return result; }
private static void ThrowWin32Error(string message, int err) { var win32Message = new Win32Exception(err).Message; throw new PcapException($"{message}\n{win32Message} (Error Code: {err})"); }
public unsafe void ServiceMainCallback(int argCount, IntPtr argPointer) { fixed(NativeMethods.SERVICE_STATUS *ptr = &this.status) { string[] array = null; if (argCount > 0) { char **ptr2 = (char **)argPointer.ToPointer(); array = new string[argCount - 1]; for (int i = 0; i < array.Length; i++) { ptr2 += sizeof(char *) / sizeof(char *); array[i] = Marshal.PtrToStringUni((IntPtr)(*(IntPtr *)ptr2)); } } if (!this.initialized) { this.isServiceHosted = true; this.Initialize(true); } if (Environment.OSVersion.Version.Major >= 5) { this.statusHandle = NativeMethods.RegisterServiceCtrlHandlerEx(this.ServiceName, this.commandCallbackEx, (IntPtr)0); } else { this.statusHandle = NativeMethods.RegisterServiceCtrlHandler(this.ServiceName, this.commandCallback); } this.nameFrozen = true; if (this.statusHandle == (IntPtr)0) { string message = new Win32Exception().Message; ReplayEventLogConstants.Tuple_StartFailed.LogEvent(null, new object[] { message }); } this.status.controlsAccepted = this.acceptedCommands; this.commandPropsFrozen = true; if ((this.status.controlsAccepted & 1) != 0) { this.status.controlsAccepted = (this.status.controlsAccepted | 256); } if (Environment.OSVersion.Version.Major < 5) { this.status.controlsAccepted = (this.status.controlsAccepted & -65); } this.status.currentState = 2; if (NativeMethods.SetServiceStatus(this.statusHandle, ptr)) { this.startCompletedSignal = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem(new WaitCallback(this.ServiceQueuedMainCallback), array); this.startCompletedSignal.WaitOne(); if (!NativeMethods.SetServiceStatus(this.statusHandle, ptr)) { ReplayEventLogConstants.Tuple_StartFailed.LogEvent(null, new object[] { new Win32Exception().Message }); this.status.currentState = 1; NativeMethods.SetServiceStatus(this.statusHandle, ptr); } ptr = null; } } }
private bool VerifySecureChannel(string domain, string localMachineName) { IntPtr queryInfo = IntPtr.Zero; IntPtr domainPtr = Marshal.StringToCoTaskMemAuto(domain); bool scInGoodState = false; try { int errorCode = SAMAPI.I_NetLogonControl2(null, NETLOGON_CONTROL_TC_QUERY, NETLOGON_INFO_2, ref domainPtr, out queryInfo); if (errorCode != 0) { var ex = new Win32Exception(errorCode); string errMsg = StringUtil.Format(ComputerResources.FailToTestSecureChannel, ex.Message); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToTestSecureChannel", ErrorCategory.OperationStopped, localMachineName); ThrowTerminatingError(error); } var infoData = (SAMAPI.NetLogonInfo2)Marshal.PtrToStructure(queryInfo, typeof(SAMAPI.NetLogonInfo2)); scInGoodState = infoData.PdcConnectionStatus == 0; } finally { if (domainPtr != IntPtr.Zero) { Marshal.FreeCoTaskMem(domainPtr); } if (queryInfo != IntPtr.Zero) { int freeResult = SAMAPI.NetApiBufferFree(queryInfo); Dbg.Diagnostics.Assert(freeResult == 0, "NetApiBufferFree returned non-zero value"); } } return scInGoodState; }
protected override void Run() { log.DebugFormat("Enabling AD on pool '{0}'", Helpers.GetName(Pool).Ellipsise(50)); Dictionary <string, string> config = new Dictionary <string, string>(); config["domain"] = domain; // NB this line is now redundant, it is here to support the old now-superseded way of passing in the domain config["user"] = user; config["pass"] = password; try { try { //CA-48122: Call disable just in case it was not disabled properly Pool.disable_external_auth(Session, Pool.opaque_ref, new Dictionary <string, string>()); } catch (Exception ex) { log.Debug("Tried to disable AD before enabling it, but it has failed. Ignoring it, because in this case we are executing disable on best effort basis only.", ex); } XenAPI.Pool.enable_external_auth(Session, Pool.opaque_ref, config, domain, Auth.AUTH_TYPE_AD); } catch (Failure f) { // CA-37255 CA-38369 CA-39485 // We can get errors from likewise that correspond to an error in WinError.h // By and large they are useless to the user so we log the details for support and show something more friendly. if (f.ErrorDescription[0] == Failure.AUTH_ENABLE_FAILED && f.ErrorDescription.Count > 2) { Match m = AuthFailedReg.Match(f.ErrorDescription[2]); if (!m.Success) { throw f; } int errorId; if (!int.TryParse(m.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out errorId)) { throw f; } Win32Exception winErr = new Win32Exception(errorId); log.ErrorFormat("Received error from likewise when attempting to join domain: {0}", winErr); } XenRef <Host> hostref = new XenRef <Host>(f.ErrorDescription[1]); Host host = Connection.Resolve(hostref); if (host == null) { throw f; } else if (f.ErrorDescription[0] == Failure.POOL_AUTH_ENABLE_FAILED_WRONG_CREDENTIALS) { throw new CredentialsFailure(f.ErrorDescription); } else { throw new Exception(string.Format(Messages.AD_FAILURE_WITH_HOST, f.Message, host.Name)); } } Description = Messages.COMPLETED; }
internal static void WriteNonTerminatingError(int errorcode, PSCmdlet cmdlet, string computername) { Win32Exception ex = new Win32Exception(errorcode); string additionalmessage = String.Empty; if (ex.NativeErrorCode.Equals(0x00000035)) { additionalmessage = StringUtil.Format(ComputerResources.NetworkPathNotFound, computername); } string message = StringUtil.Format(ComputerResources.OperationFailed, ex.Message, computername, additionalmessage); ErrorRecord er = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, computername); cmdlet.WriteError(er); }
/// <summary> /// Initializes a new instance of the <see cref="Win32ErrorWrapper"/> class. /// </summary> /// <param name="win32Error"> /// The win 32 error. /// </param> public Win32ErrorWrapper(int win32Error) { _win32Error = win32Error; Exception = new Win32Exception(win32Error); }
protected override void BeginProcessing() { string str; if (this.compname.Equals("localhost", StringComparison.CurrentCultureIgnoreCase) || this.compname.Equals(".", StringComparison.OrdinalIgnoreCase)) { str = "localhost"; } else { str = this.compname; } try { if (EventLog.SourceExists(this._source, this.compname)) { if (EventLog.Exists(this._logName, this.compname)) { EventLog eventLog = new EventLog(this._logName, this.compname, this._source); eventLog.WriteEntry(this._message, this._entryType, this._eventId, this._category, this._rawData); } else { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, this._logName, str)), null, ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord); } } else { object[] objArray = new object[3]; objArray[1] = str; objArray[2] = this._source; ErrorRecord errorRecord1 = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.SourceDoesNotExist, objArray)), null, ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord1); } } catch (ArgumentException argumentException1) { ArgumentException argumentException = argumentException1; this.WriteNonTerminatingError(argumentException, argumentException.Message, argumentException.Message, ErrorCategory.InvalidOperation); } catch (InvalidOperationException invalidOperationException1) { InvalidOperationException invalidOperationException = invalidOperationException1; object[] objArray1 = new object[3]; objArray1[0] = this._logName; objArray1[2] = this._source; this.WriteNonTerminatingError(invalidOperationException, "AccessDenied", StringUtil.Format(EventlogResources.AccessDenied, objArray1), ErrorCategory.PermissionDenied); } catch (Win32Exception win32Exception1) { Win32Exception win32Exception = win32Exception1; object[] objArray2 = new object[3]; this.WriteNonTerminatingError(win32Exception, "OSWritingError", StringUtil.Format(EventlogResources.OSWritingError, objArray2), ErrorCategory.WriteError); } catch (IOException oException1) { IOException oException = oException1; object[] objArray3 = new object[3]; objArray3[1] = this.compname; this.WriteNonTerminatingError(oException, "PathDoesNotExist", StringUtil.Format(EventlogResources.PathDoesNotExist, objArray3), ErrorCategory.InvalidOperation); } }
private static void showWin32Error(int errorcode) { Win32Exception myEx = new Win32Exception(errorcode); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error code:\t 0x{0:X}", myEx.ErrorCode); Console.WriteLine("Error message:\t {0}\n", myEx.Message); Console.ForegroundColor = ConsoleColor.Gray; }