DangerousGetHandle() private method

private DangerousGetHandle ( ) : IntPtr
return IntPtr
        /*
            This is to support SSL with no client cert.
            Important: safeHandle should not be Disposed during construction of this object.
           
            _SecPkgInfoW in sspi.h
         */
        internal SecurityPackageInfoClass(SafeHandle safeHandle, int index)
        {
            if (safeHandle.IsInvalid)
            {
                GlobalLog.Print("SecurityPackageInfoClass::.ctor() the pointer is invalid: " + (safeHandle.DangerousGetHandle()).ToString("x"));
                return;
            }

            IntPtr unmanagedAddress = IntPtrHelper.Add(safeHandle.DangerousGetHandle(), SecurityPackageInfo.Size * index);
            GlobalLog.Print("SecurityPackageInfoClass::.ctor() unmanagedPointer: " + ((long)unmanagedAddress).ToString("x"));

            // TODO (Issue #3114): replace with Marshal.PtrToStructure.
            Capabilities = Marshal.ReadInt32(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Capabilities"));
            Version = Marshal.ReadInt16(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Version"));
            RPCID = Marshal.ReadInt16(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("RPCID"));
            MaxToken = Marshal.ReadInt32(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("MaxToken"));

            IntPtr unmanagedString;

            unmanagedString = Marshal.ReadIntPtr(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Name"));
            if (unmanagedString != IntPtr.Zero)
            {
                Name = Marshal.PtrToStringUni(unmanagedString);
                GlobalLog.Print("Name: " + Name);
            }

            unmanagedString = Marshal.ReadIntPtr(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Comment"));
            if (unmanagedString != IntPtr.Zero)
            {
                Comment = Marshal.PtrToStringUni(unmanagedString);
                GlobalLog.Print("Comment: " + Comment);
            }

            GlobalLog.Print("SecurityPackageInfoClass::.ctor(): " + ToString());
        }
        internal NegotiationInfoClass(SafeHandle safeHandle, int negotiationState)
        {
            if (safeHandle.IsInvalid)
            {
                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.Print("NegotiationInfoClass::.ctor() the handle is invalid:" + (safeHandle.DangerousGetHandle()).ToString("x"));
                }
                return;
            }

            IntPtr packageInfo = safeHandle.DangerousGetHandle();
            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Print("NegotiationInfoClass::.ctor() packageInfo:" + packageInfo.ToString("x8") + " negotiationState:" + negotiationState.ToString("x8"));
            }

            if (negotiationState == Interop.SspiCli.SECPKG_NEGOTIATION_COMPLETE
                || negotiationState == Interop.SspiCli.SECPKG_NEGOTIATION_OPTIMISTIC)
            {
                IntPtr unmanagedString = Marshal.ReadIntPtr(packageInfo, SecurityPackageInfo.NameOffest);
                string name = null;
                if (unmanagedString != IntPtr.Zero)
                {
                    name = Marshal.PtrToStringUni(unmanagedString);
                }

                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.Print("NegotiationInfoClass::.ctor() packageInfo:" + packageInfo.ToString("x8") + " negotiationState:" + negotiationState.ToString("x8") + " name:" + LoggingHash.ObjectToString(name));
                }

                // An optimization for future string comparisons.
                if (string.Compare(name, Kerberos, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    AuthenticationPackage = Kerberos;
                }
                else if (string.Compare(name, NTLM, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    AuthenticationPackage = NTLM;
                }
                else if (string.Compare(name, WDigest, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    AuthenticationPackage = WDigest;
                }
                else
                {
                    AuthenticationPackage = name;
                }
            }
        }
 internal NegotiationInfoClass(SafeHandle safeHandle, int negotiationState)
 {
     if (!safeHandle.IsInvalid)
     {
         IntPtr handle = safeHandle.DangerousGetHandle();
         if ((negotiationState == 0) || (negotiationState == 1))
         {
             IntPtr ptr = Marshal.ReadIntPtr(handle, SecurityPackageInfo.NameOffest);
             string strA = null;
             if (ptr != IntPtr.Zero)
             {
                 strA = ComNetOS.IsWin9x ? Marshal.PtrToStringAnsi(ptr) : Marshal.PtrToStringUni(ptr);
             }
             if (string.Compare(strA, "Kerberos", StringComparison.OrdinalIgnoreCase) == 0)
             {
                 this.AuthenticationPackage = "Kerberos";
             }
             else if (string.Compare(strA, "NTLM", StringComparison.OrdinalIgnoreCase) == 0)
             {
                 this.AuthenticationPackage = "NTLM";
             }
             else if (string.Compare(strA, "WDigest", StringComparison.OrdinalIgnoreCase) == 0)
             {
                 this.AuthenticationPackage = "WDigest";
             }
             else
             {
                 this.AuthenticationPackage = strA;
             }
         }
     }
 }
Esempio n. 4
0
        /*
            This is to support SSL with no client cert.
            Important: safeHandle should not be Disposed during construction of this object.
           
            _SecPkgInfoW in sspi.h
         */
        internal SecurityPackageInfoClass(SafeHandle safeHandle, int index)
        {
            if (safeHandle.IsInvalid)
            {
                if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Invalid handle: {safeHandle}");
                return;
            }

            IntPtr unmanagedAddress = IntPtrHelper.Add(safeHandle.DangerousGetHandle(), SecurityPackageInfo.Size * index);
            if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"unmanagedAddress: {unmanagedAddress}");

            // TODO (Issue #3114): replace with Marshal.PtrToStructure.
            Capabilities = Marshal.ReadInt32(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Capabilities"));
            Version = Marshal.ReadInt16(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Version"));
            RPCID = Marshal.ReadInt16(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("RPCID"));
            MaxToken = Marshal.ReadInt32(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("MaxToken"));

            IntPtr unmanagedString;

            unmanagedString = Marshal.ReadIntPtr(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Name"));
            if (unmanagedString != IntPtr.Zero)
            {
                Name = Marshal.PtrToStringUni(unmanagedString);
                if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Name: {Name}");
            }

            unmanagedString = Marshal.ReadIntPtr(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Comment"));
            if (unmanagedString != IntPtr.Zero)
            {
                Comment = Marshal.PtrToStringUni(unmanagedString);
                if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Comment: {Comment}");
            }

            if (NetEventSource.IsEnabled) NetEventSource.Info(this, this.ToString());
        }
 internal SecurityPackageInfoClass(SafeHandle safeHandle, int index)
 {
     if (!safeHandle.IsInvalid)
     {
         IntPtr ptr = IntPtrHelper.Add(safeHandle.DangerousGetHandle(), SecurityPackageInfo.Size * index);
         this.Capabilities = Marshal.ReadInt32(ptr, (int) Marshal.OffsetOf(typeof(SecurityPackageInfo), "Capabilities"));
         this.Version = Marshal.ReadInt16(ptr, (int) Marshal.OffsetOf(typeof(SecurityPackageInfo), "Version"));
         this.RPCID = Marshal.ReadInt16(ptr, (int) Marshal.OffsetOf(typeof(SecurityPackageInfo), "RPCID"));
         this.MaxToken = Marshal.ReadInt32(ptr, (int) Marshal.OffsetOf(typeof(SecurityPackageInfo), "MaxToken"));
         IntPtr ptr2 = Marshal.ReadIntPtr(ptr, (int) Marshal.OffsetOf(typeof(SecurityPackageInfo), "Name"));
         if (ptr2 != IntPtr.Zero)
         {
             if (ComNetOS.IsWin9x)
             {
                 this.Name = Marshal.PtrToStringAnsi(ptr2);
             }
             else
             {
                 this.Name = Marshal.PtrToStringUni(ptr2);
             }
         }
         ptr2 = Marshal.ReadIntPtr(ptr, (int) Marshal.OffsetOf(typeof(SecurityPackageInfo), "Comment"));
         if (ptr2 != IntPtr.Zero)
         {
             if (ComNetOS.IsWin9x)
             {
                 this.Comment = Marshal.PtrToStringAnsi(ptr2);
             }
             else
             {
                 this.Comment = Marshal.PtrToStringUni(ptr2);
             }
         }
     }
 }
Esempio n. 6
0
        /// <summary>
        /// Gets the Win32 handle for a given RegistryKey.
        /// </summary>
        /// <param name="registryKey">registry key you want the handle for</param>
        /// <returns>Desired handle</returns>
        public static int getRegistryHandle(RegistryKey registryKey)
        {
            Type      type      = registryKey.GetType();
            FieldInfo fieldInfo = type.GetField("hkey", BindingFlags.Instance | BindingFlags.NonPublic);

            System.Runtime.InteropServices.SafeHandle i = (System.Runtime.InteropServices.SafeHandle)fieldInfo.GetValue(registryKey);
            return(((IntPtr)i.DangerousGetHandle()).ToInt32());
        }
		protected EntryPage(SafeHandle handle, uint capacity)
		{
			Contract.Requires(handle != null && !handle.IsInvalid && !handle.IsClosed);

			m_handle = handle;
			m_capacity = capacity;
			m_start = (byte*) handle.DangerousGetHandle();
			m_end = m_start + capacity;
			m_current = m_start;
			CheckInvariants();
		}
      public static ArbitraryWaitHandle FromSafeHandle(SafeHandle safeHandle) {
         Contract.Requires(safeHandle != null);
         Boolean success = false;
         try {
            safeHandle.DangerousAddRef(ref success);
            if (!success) throw new InvalidOperationException("Couldn't AddRef");

            return new ArbitraryWaitHandle(safeHandle.DangerousGetHandle());
         }
         finally {
            safeHandle.DangerousRelease();
         }
      }
Esempio n. 9
0
        internal SafePipeHandle(Socket namedPipeSocket) : base(ownsHandle: true)
        {
            Debug.Assert(namedPipeSocket != null);
            _namedPipeSocket = namedPipeSocket;

            // TODO: Issue https://github.com/dotnet/corefx/issues/6807
            // This is unfortunately the only way of getting at the Socket's file descriptor right now, until #6807 is implemented.
            PropertyInfo safeHandleProperty = s_safeHandleProperty ?? (s_safeHandleProperty = typeof(Socket).GetTypeInfo().GetDeclaredProperty("SafeHandle"));
            Debug.Assert(safeHandleProperty != null, "Socket.SafeHandle could not be found.");
            _namedPipeSocketHandle = (SafeHandle)safeHandleProperty?.GetValue(namedPipeSocket, null);

            bool ignored = false;
            _namedPipeSocketHandle.DangerousAddRef(ref ignored);
            SetHandle(_namedPipeSocketHandle.DangerousGetHandle());
        }
Esempio n. 10
0
        public static SafeHandle DuplicateTokenAsPrimaryToken(SafeHandle originalToken)
        {
            IntPtr duplicatedToken = Constants.INVALID_HANDLE_VALUE;

            if (!AdvApi32PInvoke.DuplicateTokenEx(originalToken.DangerousGetHandle(),
                AdvApi32PInvoke.TOKEN_QUERY
                | AdvApi32PInvoke.TOKEN_DUPLICATE
                | AdvApi32PInvoke.TOKEN_ASSIGN_PRIMARY
                | AdvApi32PInvoke.TOKEN_ADJUST_DEFAULT
                | AdvApi32PInvoke.TOKEN_ADJUST_SESSIONID,
                Constants.NULL,
                AdvApi32PInvoke.SECURITY_IMPERSONATION_LEVEL.SecurityDelegation,
                AdvApi32PInvoke.TOKEN_TYPE.TokenPrimary,
                out duplicatedToken))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            return new SafeFileHandle(duplicatedToken, true);
        }
Esempio n. 11
0
		public static bool DuplicateHandle(HandleRef hSourceProcessHandle, SafeHandle hSourceHandle, HandleRef hTargetProcess,
			out SafeWaitHandle targetHandle, int dwDesiredAccess, bool bInheritHandle, int dwOptions)
		{
			bool release = false;
			try {
				hSourceHandle.DangerousAddRef (ref release);

				MonoIOError error;
				IntPtr nakedTargetHandle;
				bool ret = MonoIO.DuplicateHandle (hSourceProcessHandle.Handle, hSourceHandle.DangerousGetHandle (), hTargetProcess.Handle,
					out nakedTargetHandle, dwDesiredAccess, bInheritHandle ? 1 : 0, dwOptions, out error);

				if (error != MonoIOError.ERROR_SUCCESS)
					throw MonoIO.GetException (error);

				targetHandle = new SafeWaitHandle (nakedTargetHandle, true);
				return ret;
			} finally {
				if (release)
					hSourceHandle.DangerousRelease ();
			}
		}
Esempio n. 12
0
        private bool CheckPrivilege(string exectedPrivilege, SafeHandle currentUserToken)
        {
            AdvApi32PInvoke.LUID luid = default(AdvApi32PInvoke.LUID);

            expect(() => get_privilege_identifier(exectedPrivilege, out luid));

            AdvApi32PInvoke.PRIVILEGE_SET privilegeSet = new AdvApi32PInvoke.PRIVILEGE_SET();
            privilegeSet.PrivilegeCount = 1;
            privilegeSet.Control = AdvApi32PInvoke.PRIVILEGE_SET.PRIVILEGE_SET_ALL_NECESSARY;
            privilegeSet.Privilege = new AdvApi32PInvoke.LUID_AND_ATTRIBUTES[1];
            privilegeSet.Privilege[0].Luid = luid;
            privilegeSet.Privilege[0].Attributes = AdvApi32PInvoke.LUID_AND_ATTRIBUTES.SE_PRIVILEGE_REMOVED;

            bool privilegeCheckResult;

            bool executionResult = AdvApi32PInvoke.PrivilegeCheck(currentUserToken.DangerousGetHandle(),
                ref privilegeSet, out privilegeCheckResult);

            expect(() => executionResult);

            return privilegeCheckResult;
        }
        private static IEnumerable<RecipientInfo> ToRecipientInfosForThisIndex(SafeHandle pCmsgCmsRecipientInfoMemory, int index)
        {
            bool mustRelease = false;
            pCmsgCmsRecipientInfoMemory.DangerousAddRef(ref mustRelease);
            try
            {
                unsafe
                {
                    CMSG_CMS_RECIPIENT_INFO* pCMsgCmsRecipientInfo = (CMSG_CMS_RECIPIENT_INFO*)(pCmsgCmsRecipientInfoMemory.DangerousGetHandle());
                    switch (pCMsgCmsRecipientInfo->dwRecipientChoice)
                    {
                        case CMsgCmsRecipientChoice.CMSG_KEY_TRANS_RECIPIENT:
                            return new KeyTransRecipientInfo[] { new KeyTransRecipientInfo(new KeyTransRecipientInfoPalWindows(pCmsgCmsRecipientInfoMemory, index)) };

                        case CMsgCmsRecipientChoice.CMSG_KEY_AGREE_RECIPIENT:
                            {
                                CMSG_KEY_AGREE_RECIPIENT_INFO* pCmsKeyAgreeRecipientInfo = pCMsgCmsRecipientInfo->KeyAgree;
                                int numKeys = pCmsKeyAgreeRecipientInfo->cRecipientEncryptedKeys;
                                KeyAgreeRecipientInfo[] recipients = new KeyAgreeRecipientInfo[numKeys];
                                for (int subIndex = 0; subIndex < numKeys; subIndex++)
                                {
                                    recipients[subIndex] = new KeyAgreeRecipientInfo(new KeyAgreeRecipientInfoPalWindows(pCmsgCmsRecipientInfoMemory, index, subIndex));
                                }
                                return recipients;
                            }

                        default:
                            throw ErrorCode.E_NOTIMPL.ToCryptographicException();
                    }
                }
            }
            finally
            {
                if (mustRelease)
                {
                    pCmsgCmsRecipientInfoMemory.DangerousRelease();
                }
            }
        }
Esempio n. 14
0
        internal NegotiationInfoClass(SafeHandle safeHandle, int negotiationState)
        {
            if (safeHandle.IsInvalid)
            {
                if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Invalid handle:{safeHandle}");
                return;
            }

            IntPtr packageInfo = safeHandle.DangerousGetHandle();
            if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"packageInfo:{packageInfo} negotiationState:{negotiationState:x}");

            if (negotiationState == Interop.SspiCli.SECPKG_NEGOTIATION_COMPLETE
                || negotiationState == Interop.SspiCli.SECPKG_NEGOTIATION_OPTIMISTIC)
            {
                IntPtr unmanagedString = Marshal.ReadIntPtr(packageInfo, SecurityPackageInfo.NameOffest);
                string name = null;
                if (unmanagedString != IntPtr.Zero)
                {
                    name = Marshal.PtrToStringUni(unmanagedString);
                }

                if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"packageInfo:{packageInfo} negotiationState:{negotiationState:x} name:{name}");

                // An optimization for future string comparisons.
                if (string.Compare(name, Kerberos, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    AuthenticationPackage = Kerberos;
                }
                else if (string.Compare(name, NTLM, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    AuthenticationPackage = NTLM;
                }
                else
                {
                    AuthenticationPackage = name;
                }
            }
        }
 public static bool BindHandle(SafeHandle osHandle)
 {
     if (osHandle == null)
     {
         throw new ArgumentNullException("osHandle");
     }
     bool flag = false;
     bool success = false;
     RuntimeHelpers.PrepareConstrainedRegions();
     try
     {
         osHandle.DangerousAddRef(ref success);
         flag = BindIOCompletionCallbackNative(osHandle.DangerousGetHandle());
     }
     finally
     {
         if (success)
         {
             osHandle.DangerousRelease();
         }
     }
     return flag;
 }
Esempio n. 16
0
 /// <summary>
 /// Initialises the device
 /// </summary>
 /// <param name="strPath">Path to the device</param>
 private void Initialise(string strPath)
 {
     // Create the file from the device path
     m_hHandle = Kernel32.CreateFile(strPath, Kernel32.GENERIC_READ | Kernel32.GENERIC_WRITE, 0, IntPtr.Zero, Kernel32.OPEN_EXISTING, Kernel32.FILE_FLAG_OVERLAPPED, 0);
     
     if (!m_hHandle.IsInvalid)	// if the open worked...
     {
         IntPtr lpData;
         if (Hid.HidD_GetPreparsedData(m_hHandle, out lpData))	// get windows to read the device data into an internal buffer
         {
             try
             {
                 HIDP_CAPS oCaps;
                 Hid.HidP_GetCaps(lpData, out oCaps);	// extract the device capabilities from the internal buffer
                 m_nInputReportLength = oCaps.InputReportByteLength;	// get the input...
                 m_nOutputReportLength = oCaps.OutputReportByteLength;	// ... and output report lengths
                 //m_oFile = new FileStream(m_hHandle, FileAccess.Read | FileAccess.Write, true, m_nInputReportLength, true);	// wrap the file handle in a .Net file stream
                 m_oFile = new FileStream(new SafeFileHandle(m_hHandle.DangerousGetHandle(), false), FileAccess.Read | FileAccess.Write, m_nInputReportLength, true);	// wrap the file handle in a .Net file stream
                 BeginAsyncRead();	// kick off the first asynchronous read
             }
             finally
             {
                 Hid.HidD_FreePreparsedData(lpData);	// before we quit the funtion, we must free the internal buffer reserved in GetPreparsedData
             }
         }
         else	// GetPreparsedData failed? Chuck an exception
         {
             throw HIDDeviceException.GenerateWithWinError("GetPreparsedData failed");
         }
     }
     else	// File open failed? Chuck an exception
     {
         m_hHandle.SetHandleAsInvalid();
         throw HIDDeviceException.GenerateWithWinError("Failed to create device file");
     }
 }
Esempio n. 17
0
		public int RunAsToken(string executablePath, string executableParameters, TextWriter standardOutputWriter, TextWriter errorOutputWriter, SafeHandle impersonationToken)
		{
			string logFileRoot = Guid.NewGuid().ToString();
			string stdoutLogFile = Path.Combine(Environment.CurrentDirectory, logFileRoot + ".stdout.log");
			string stderrLogFile = Path.Combine(Environment.CurrentDirectory, logFileRoot + ".stderr.log");
			string currentDirectory = Environment.CurrentDirectory;
			var primaryToken = new IntPtr();
			try
			{
				#region security attributes
				SECURITY_ATTRIBUTES processAttributes = new SECURITY_ATTRIBUTES();

				SECURITY_DESCRIPTOR sd = new SECURITY_DESCRIPTOR();
				IntPtr ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(sd));
				Marshal.StructureToPtr(sd, ptr, false);
				InitializeSecurityDescriptor(ptr, SECURITY_DESCRIPTOR_REVISION);
				sd = (SECURITY_DESCRIPTOR)Marshal.PtrToStructure(ptr, typeof(SECURITY_DESCRIPTOR));

				bool result = SetSecurityDescriptorDacl(ref sd, true, IntPtr.Zero, false);
				if (!result)
				{
					throw new Win32Exception();
				}

				result = DuplicateTokenEx(impersonationToken.DangerousGetHandle(), 0, ref processAttributes, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out primaryToken);
				if (!result)
				{
					throw new Win32Exception();
				}
				processAttributes.SecurityDescriptor = ptr;
				processAttributes.Length = (uint)Marshal.SizeOf(sd);
				processAttributes.InheritHandle = true;
				#endregion

				SECURITY_ATTRIBUTES threadAttributes = new SECURITY_ATTRIBUTES();
				threadAttributes.SecurityDescriptor = IntPtr.Zero;
				threadAttributes.Length = 0;
				threadAttributes.InheritHandle = false;

				bool inheritHandles = true;
				//CreationFlags creationFlags = CreationFlags.CREATE_DEFAULT_ERROR_MODE;
				IntPtr environment = IntPtr.Zero;

				STARTUPINFO startupInfo = new STARTUPINFO();
				startupInfo.Desktop = "";

				PROCESS_INFORMATION processInformation;

				string cmdPath = Environment.GetEnvironmentVariable("COMSPEC");
				string cmdArguments = string.Format("/c {0} {1} > \"{2}\" 2> \"{3}\"", executablePath, executableParameters, stdoutLogFile, stderrLogFile);
				result = CreateProcessAsUser(primaryToken, cmdPath, cmdArguments, ref processAttributes, ref threadAttributes, inheritHandles, 16, environment, currentDirectory, ref startupInfo, out processInformation);
				if (!result)
				{
					long win32Code = Marshal.GetHRForLastWin32Error();
					if (win32Code == 0x80070522 )
					{
						//Log on as a service
						//Act as part of the operating system
						//Adjust memory quotas for a process
						//Replace a process level token

						//Impersonate a client after authentication?
						//Create token object?
						throw new Exception("privilges not set", new Win32Exception());
					}
					throw new Win32Exception();
				}
				WaitForSingleObject(processInformation.Process, INFINITE);

				if (File.Exists(stdoutLogFile))
				{
					standardOutputWriter.Write(File.ReadAllText(stdoutLogFile));
				}
				if (File.Exists(stderrLogFile))
				{
					errorOutputWriter.Write(File.ReadAllText(stderrLogFile));
				}

				uint exitCode;
				result = GetExitCodeProcess(processInformation.Process, out exitCode);
				if(!result)
				{
					throw new Win32Exception();
				}
				return (int)exitCode;
			}
			finally
			{
				if (primaryToken != IntPtr.Zero)
				{
					var result = CloseHandle(primaryToken);
					if (result == 0)
						throw new Win32Exception();
				}
			}
		}
Esempio n. 18
0
		public static void Unlock (SafeHandle safeHandle,
						  long position, long length,
						  out MonoIOError error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				Unlock (safeHandle.DangerousGetHandle (), position, length, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 19
0
		public static bool SetFileTime (SafeHandle safeHandle,
						       long creation_time,
						       long last_access_time,
						       long last_write_time,
						       out MonoIOError error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				return SetFileTime (safeHandle.DangerousGetHandle (), creation_time, last_access_time, last_write_time, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 20
0
 public SafeSelectObjectHandle(SafeDCHandle hdc, SafeHandle newHandle)
     : base(true)
 {
     this.hdc = hdc;
     SetHandle(SelectObject(hdc.DangerousGetHandle(), newHandle.DangerousGetHandle()));
 }
Esempio n. 21
0
		public static long Seek (SafeHandle safeHandle, long offset,
						SeekOrigin origin,
						out MonoIOError error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				return Seek (safeHandle.DangerousGetHandle (), offset, origin, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 22
0
		public static int Write (SafeHandle safeHandle, byte [] src,
						int src_offset, int count,
						out MonoIOError error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				return Write (safeHandle.DangerousGetHandle (), src, src_offset, count, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 23
0
        private static SystemEnforcementMode GetWldpPolicy(string path, SafeHandle handle)
        {
            // If the WLDP assembly is missing (such as windows 7 or down OS), return default/None to skip WLDP validation
            if (s_hadMissingWldpAssembly || !IO.File.Exists(IO.Path.Combine(Environment.SystemDirectory, "wldp.dll")))
            {
                s_hadMissingWldpAssembly = true;
                return s_cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None);
            }

            // If path is NULL, see if we have the cached system-wide lockdown policy.
            if (String.IsNullOrEmpty(path))
            {
                if ((s_cachedWldpSystemPolicy != null) && (!InternalTestHooks.BypassAppLockerPolicyCaching))
                {
                    return s_cachedWldpSystemPolicy.Value;
                }
            }

            try
            {
                WLDP_HOST_INFORMATION hostInformation = new WLDP_HOST_INFORMATION();
                hostInformation.dwRevision = WldpNativeConstants.WLDP_HOST_INFORMATION_REVISION;
                hostInformation.dwHostId = WLDP_HOST_ID.WLDP_HOST_ID_POWERSHELL;

                if (!String.IsNullOrEmpty(path))
                {
                    hostInformation.szSource = path;

                    if (handle != null)
                    {
                        IntPtr fileHandle = IntPtr.Zero;
                        fileHandle = handle.DangerousGetHandle();
                        hostInformation.hSource = fileHandle;
                    }
                }

                uint pdwLockdownState = 0;
                int result = WldpNativeMethods.WldpGetLockdownPolicy(ref hostInformation, ref pdwLockdownState, 0);
                if (result >= 0)
                {
                    SystemEnforcementMode resultingLockdownPolicy = GetLockdownPolicyForResult(pdwLockdownState);

                    // If this is a query for the system-wide lockdown policy, cache it.
                    if (String.IsNullOrEmpty(path))
                    {
                        s_cachedWldpSystemPolicy = resultingLockdownPolicy;
                    }

                    return resultingLockdownPolicy;
                }
                else
                {
                    // API failure?
                    return SystemEnforcementMode.Enforce;
                }
            }
            catch (DllNotFoundException)
            {
                s_hadMissingWldpAssembly = true;
                return s_cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None);
            }
        }
        void EnsureRecordBuffer(uint bytes)
        {
            if (bytes <= currentBufferSize)
            {
                return;
            }

            bufferHandle.Close();
            currentBufferSize = bytes;
            bufferHandle = SafeHGlobalHandleCritical.AllocHGlobal(currentBufferSize);

            record.pbMDData = bufferHandle.DangerousGetHandle();
            record.dwMDDataLen = currentBufferSize;
        }
Esempio n. 25
0
		public static bool Flush (SafeHandle safeHandle,
						 out MonoIOError error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				return Flush (safeHandle.DangerousGetHandle (), out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
 /// <summary>Asserts that the handle's inheritability matches the specified value.</summary>
 protected static void AssertInheritability(SafeHandle handle, HandleInheritability inheritability)
 {
     if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
     {
         uint flags;
         Assert.True(GetHandleInformation(handle.DangerousGetHandle(), out flags));
         Assert.Equal(inheritability == HandleInheritability.Inheritable, (flags & HANDLE_FLAG_INHERIT) != 0);
     }
 }
Esempio n. 27
0
		public static bool SetLength (SafeHandle safeHandle,
						     long length,
						     out MonoIOError error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				return SetLength (safeHandle.DangerousGetHandle (), length, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 28
0
    internal void RegisterDeviceRemoval(SafeHandle deviceHandle)
    {
      DeviceBroadcastHandle dbh = new DeviceBroadcastHandle();

      dbh.Size = Marshal.SizeOf(dbh);
      dbh.DeviceType = 0x6;
      dbh.Handle = deviceHandle.DangerousGetHandle();

      _deviceHandle = deviceHandle;
      try
      {
        _handleDeviceRemoval = new SafeFileHandle(RegisterDeviceNotification(Handle, ref dbh, 0), true);
      }
      catch
      {
        MceRemoteReceiver.LogInfo("DeviceWatcher.RegisterDeviceRemoval: Error={0}.", Marshal.GetLastWin32Error());
      }

      if (_handleDeviceRemoval.IsInvalid)
      {
        throw new Exception(string.Format("Failed in call to RegisterDeviceNotification ({0})", GetLastError()));
      }
    }
Esempio n. 29
0
		static int WaitOneNative (SafeHandle waitableSafeHandle, uint millisecondsTimeout, bool hasThreadAffinity, bool exitContext)
		{
			bool release = false;
			try {
#if !DISABLE_REMOTING
				if (exitContext)
					SynchronizationAttribute.ExitContext ();
#endif

				waitableSafeHandle.DangerousAddRef (ref release);

				return WaitOne_internal (waitableSafeHandle.DangerousGetHandle (), (int) millisecondsTimeout);
			} finally {
				if (release)
					waitableSafeHandle.DangerousRelease ();

#if !DISABLE_REMOTING
				if (exitContext)
					SynchronizationAttribute.EnterContext ();
#endif
			}
		}
        internal void Bind(OciStatementHandle statementHandle, NativeBuffer parameterBuffer, OracleConnection connection, ref bool mustRelease, ref SafeHandle handleToBind)
        {
            if (IsDirection(this.Parameter, ParameterDirection.Output) || (this.Parameter.Value != null))
            {
                int num2;
                IntPtr ptr2;
                string parameterName = this.Parameter.ParameterName;
                OciErrorHandle errorHandle = connection.ErrorHandle;
                OciServiceContextHandle serviceContextHandle = connection.ServiceContextHandle;
                int num = 0;
                OCI.INDICATOR oK = OCI.INDICATOR.OK;
                OCI.DATATYPE ociType = this._bindingMetaType.OciType;
                IntPtr dataPtr = parameterBuffer.DangerousGetDataPtr(this._indicatorOffset);
                IntPtr alenp = parameterBuffer.DangerousGetDataPtr(this._lengthOffset);
                IntPtr valuep = parameterBuffer.DangerousGetDataPtr(this._valueOffset);
                OciHandle.SafeDispose(ref this._dateTimeDescriptor);
                if (IsDirection(this.Parameter, ParameterDirection.Input))
                {
                    if (System.Data.Common.ADP.IsNull(this._coercedValue))
                    {
                        oK = OCI.INDICATOR.ISNULL;
                        switch (ociType)
                        {
                            case OCI.DATATYPE.INT_TIMESTAMP:
                            case OCI.DATATYPE.INT_TIMESTAMP_TZ:
                            case OCI.DATATYPE.INT_TIMESTAMP_LTZ:
                                this._dateTimeDescriptor = OracleDateTime.CreateEmptyDescriptor(ociType, connection);
                                handleToBind = this._dateTimeDescriptor;
                                break;
                        }
                    }
                    else
                    {
                        num = this.PutOracleValue(this._coercedValue, parameterBuffer, this._valueOffset, this._bindingMetaType, connection, ref handleToBind);
                    }
                }
                else
                {
                    if (this._bindingMetaType.IsVariableLength)
                    {
                        num = 0;
                    }
                    else
                    {
                        num = this._bufferLength;
                    }
                    OciLobLocator.SafeDispose(ref this._locator);
                    OciHandle.SafeDispose(ref this._descriptor);
                    switch (ociType)
                    {
                        case OCI.DATATYPE.CLOB:
                        case OCI.DATATYPE.BLOB:
                        case OCI.DATATYPE.BFILE:
                            this._locator = new OciLobLocator(connection, this._bindingMetaType.OracleType);
                            handleToBind = this._locator.Descriptor;
                            break;

                        case OCI.DATATYPE.RSET:
                            this._descriptor = new OciStatementHandle(serviceContextHandle);
                            handleToBind = this._descriptor;
                            break;

                        case OCI.DATATYPE.INT_TIMESTAMP:
                        case OCI.DATATYPE.INT_TIMESTAMP_TZ:
                        case OCI.DATATYPE.INT_TIMESTAMP_LTZ:
                            this._dateTimeDescriptor = OracleDateTime.CreateEmptyDescriptor(ociType, connection);
                            handleToBind = this._dateTimeDescriptor;
                            break;
                    }
                }
                if (handleToBind != null)
                {
                    handleToBind.DangerousAddRef(ref mustRelease);
                    parameterBuffer.WriteIntPtr(this._valueOffset, handleToBind.DangerousGetHandle());
                }
                parameterBuffer.WriteInt16(this._indicatorOffset, (short) oK);
                if ((OCI.DATATYPE.LONGVARCHAR == ociType) || (OCI.DATATYPE.LONGVARRAW == ociType))
                {
                    alenp = IntPtr.Zero;
                }
                else if (this._bindAsUCS2)
                {
                    parameterBuffer.WriteInt32(this._lengthOffset, num / System.Data.Common.ADP.CharSize);
                }
                else
                {
                    parameterBuffer.WriteInt32(this._lengthOffset, num);
                }
                if (IsDirection(this.Parameter, ParameterDirection.Output))
                {
                    num2 = this._bufferLength;
                }
                else
                {
                    num2 = num;
                }
                OCI.DATATYPE dty = ociType;
                switch (ociType)
                {
                    case OCI.DATATYPE.INT_TIMESTAMP:
                        dty = OCI.DATATYPE.TIMESTAMP;
                        break;

                    case OCI.DATATYPE.INT_TIMESTAMP_TZ:
                        dty = OCI.DATATYPE.TIMESTAMP_TZ;
                        break;

                    case OCI.DATATYPE.INT_TIMESTAMP_LTZ:
                        dty = OCI.DATATYPE.TIMESTAMP_LTZ;
                        break;
                }
                int rc = TracedNativeMethods.OCIBindByName(statementHandle, out ptr2, errorHandle, parameterName, parameterName.Length, valuep, num2, dty, dataPtr, alenp, OCI.MODE.OCI_DEFAULT);
                if (rc != 0)
                {
                    this._command.Connection.CheckError(errorHandle, rc);
                }
                this._bindHandle = new OciBindHandle(statementHandle, ptr2);
                if (this._bindingMetaType.IsCharacterType)
                {
                    if (OCI.ClientVersionAtLeastOracle9i && IsDirection(this.Parameter, ParameterDirection.Output))
                    {
                        this._bindHandle.SetAttribute(OCI.ATTR.OCI_ATTR_MAXCHAR_SIZE, this._bindSize, errorHandle);
                    }
                    if ((num2 > (this._bindingMetaType.MaxBindSize / System.Data.Common.ADP.CharSize)) || (!OCI.ClientVersionAtLeastOracle9i && this._bindingMetaType.UsesNationalCharacterSet))
                    {
                        this._bindHandle.SetAttribute(OCI.ATTR.OCI_ATTR_MAXDATA_SIZE, this._bindingMetaType.MaxBindSize, errorHandle);
                    }
                    if (this._bindingMetaType.UsesNationalCharacterSet)
                    {
                        this._bindHandle.SetAttribute(OCI.ATTR.OCI_ATTR_CHARSET_FORM, 2, errorHandle);
                    }
                    if (this._bindAsUCS2)
                    {
                        this._bindHandle.SetAttribute(OCI.ATTR.OCI_ATTR_CHARSET_ID, 0x3e8, errorHandle);
                    }
                }
                GC.KeepAlive(parameterBuffer);
            }
        }
Esempio n. 31
0
		public static int Read (SafeHandle safeHandle, byte [] dest,
					       int dest_offset, int count,
					       out MonoIOError error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				return Read (safeHandle.DangerousGetHandle (), dest, dest_offset, count, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}