private static Interop.LUID GetLogonAuthId(SafeAccessTokenHandle safeTokenHandle) { using (SafeLocalAllocHandle pStatistics = GetTokenInformation(safeTokenHandle, TokenInformationClass.TokenStatistics)) { Interop.TOKEN_STATISTICS statistics = pStatistics.Read <Interop.TOKEN_STATISTICS>(0); return(statistics.AuthenticationId); } }
internal SignerInfo(SignedCms signedCms, SafeLocalAllocHandle pbCmsgSignerInfo) { this.m_signedCms = signedCms; this.m_parentSignerInfo = (SignerInfo)null; this.m_encodedSignerInfo = (byte[])null; this.m_pbCmsgSignerInfo = pbCmsgSignerInfo; this.m_cmsgSignerInfo = (CAPI.CMSG_SIGNER_INFO)Marshal.PtrToStructure(pbCmsgSignerInfo.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_INFO)); }
internal KeyAgreeRecipientInfo(SafeLocalAllocHandle pRecipientInfo, CAPI.CMSG_KEY_AGREE_PUBLIC_KEY_RECIPIENT_INFO publicKeyRecipient, uint index, uint subIndex) : base(RecipientInfoType.KeyAgreement, RecipientSubType.PublicKeyAgreement, pRecipientInfo, publicKeyRecipient, index) { checked { IntPtr pEncryptedKeyInfo = Marshal.ReadIntPtr(new IntPtr((long)publicKeyRecipient.rgpRecipientEncryptedKeys + (long)(subIndex * Marshal.SizeOf(typeof(IntPtr))))); CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_INFO encryptedKeyInfo = (CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_INFO)Marshal.PtrToStructure(pEncryptedKeyInfo, typeof(CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_INFO)); Reset(CAPI.CMSG_KEY_AGREE_ORIGINATOR_PUBLIC_KEY, publicKeyRecipient.dwVersion, encryptedKeyInfo, subIndex); } }
// Releases the unmanaged memory after ping completion. private void FreeUnmanagedStructures() { if (_requestBuffer != null) { _requestBuffer.Dispose(); _requestBuffer = null; } }
internal static extern bool CryptDecodeObjectEx(CertificateEncodingType encodingType, [MarshalAs(UnmanagedType.LPStr)] string lpszStructType, IntPtr pbEncoded, // BYTE[cbEncoded] int cbEncoded, DecodeObjectFlags flags, IntPtr pDecodPara, // PCRYPT_DECODE_PARA [Out] out SafeLocalAllocHandle pvStructInfo, [In, Out] ref int pcbStructInfo);
internal static NetworkInterface[] GetNetworkInterfaces() { Contract.Ensures(Contract.Result <NetworkInterface[]>() != null); AddressFamily family = AddressFamily.Unspecified; uint bufferSize = 0; SafeLocalAllocHandle buffer = null; // TODO: #2485: This will probably require changes in the PAL for HostInformation. Interop.IpHlpApi.FIXED_INFO fixedInfo = HostInformationPal.GetFixedInfo(); List <SystemNetworkInterface> interfaceList = new List <SystemNetworkInterface>(); Interop.IpHlpApi.GetAdaptersAddressesFlags flags = Interop.IpHlpApi.GetAdaptersAddressesFlags.IncludeGateways | Interop.IpHlpApi.GetAdaptersAddressesFlags.IncludeWins; // Figure out the right buffer size for the adapter information. uint result = Interop.IpHlpApi.GetAdaptersAddresses( family, (uint)flags, IntPtr.Zero, SafeLocalAllocHandle.Zero, ref bufferSize); while (result == Interop.IpHlpApi.ERROR_BUFFER_OVERFLOW) { // Allocate the buffer and get the adapter info. using (buffer = SafeLocalAllocHandle.LocalAlloc((int)bufferSize)) { result = Interop.IpHlpApi.GetAdaptersAddresses( family, (uint)flags, IntPtr.Zero, buffer, ref bufferSize); // If succeeded, we're going to add each new interface. if (result == Interop.IpHlpApi.ERROR_SUCCESS) { // Linked list of interfaces. IntPtr ptr = buffer.DangerousGetHandle(); while (ptr != IntPtr.Zero) { // Traverse the list, marshal in the native structures, and create new NetworkInterfaces. Interop.IpHlpApi.IpAdapterAddresses adapterAddresses = Marshal.PtrToStructure <Interop.IpHlpApi.IpAdapterAddresses>(ptr); interfaceList.Add(new SystemNetworkInterface(fixedInfo, adapterAddresses)); ptr = adapterAddresses.next; } } } } // If we don't have any interfaces detected, return empty. if (result == Interop.IpHlpApi.ERROR_NO_DATA || result == Interop.IpHlpApi.ERROR_INVALID_PARAMETER) { return(new SystemNetworkInterface[0]); } // Otherwise we throw on an error. if (result != Interop.IpHlpApi.ERROR_SUCCESS) { throw new NetworkInformationException((int)result); } return(interfaceList.ToArray()); }
internal static extern bool CryptDecodeObjectEx( [In] uint dwCertEncodingType, [In] IntPtr lpszStructType, [In] byte[] pbEncoded, [In] uint cbEncoded, [In] uint dwFlags, [In] IntPtr pDecodePara, [Out] out SafeLocalAllocHandle pvStructInfo, [Out] out uint pcbStructInfo);
/// <summary>Allocates unmanaged memory.</summary> /// <param name="size">Number of bytes to allocate.</param> /// <returns>A handle to the newly allocated memory object.</returns> public static SafeLocalAllocHandle LocalAlloc(int size) { SafeLocalAllocHandle handle = LocalAlloc(0, new IntPtr(size)); if (handle.IsInvalid) { throw new OutOfMemoryException(); } return(handle); }
// Copies _requestBuffer into unmanaged memory for async icmpsendecho APIs. private unsafe void SetUnmanagedStructures(byte[] buffer) { _requestBuffer = SafeLocalAllocHandle.LocalAlloc(buffer.Length); byte *dst = (byte *)_requestBuffer.DangerousGetHandle(); for (int i = 0; i < buffer.Length; ++i) { dst[i] = buffer[i]; } }
internal SignerInfo(SignedCms signedCms, SafeLocalAllocHandle pbCmsgSignerInfo) { // Sanity check. Debug.Assert(signedCms != null && pbCmsgSignerInfo != null && !pbCmsgSignerInfo.IsInvalid); m_signedCms = signedCms; m_parentSignerInfo = null; m_encodedSignerInfo = null; m_pbCmsgSignerInfo = pbCmsgSignerInfo; m_cmsgSignerInfo = (CAPI.CMSG_SIGNER_INFO)Marshal.PtrToStructure(pbCmsgSignerInfo.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_INFO)); }
private static SafeLocalAllocHandle SafeLocalAlloc(int uFlags, uint size) { SafeLocalAllocHandle result = LocalAlloc(uFlags, (UIntPtr)size); if (result == null || result.IsInvalid) { throw new OutOfMemoryException(); } result.Initialize(size); return(result); }
internal RecipientInfo(RecipientInfoType recipientInfoType, RecipientSubType recipientSubType, SafeLocalAllocHandle pCmsgRecipientInfo, object cmsgRecipientInfo, uint index) { if (recipientInfoType < RecipientInfoType.Unknown || recipientInfoType > RecipientInfoType.KeyAgreement) recipientInfoType = RecipientInfoType.Unknown; if (recipientSubType < RecipientSubType.Unknown || recipientSubType > RecipientSubType.PublicKeyAgreement) recipientSubType = RecipientSubType.Unknown; this.m_recipentInfoType = recipientInfoType; this.m_recipientSubType = recipientSubType; this.m_pCmsgRecipientInfo = pCmsgRecipientInfo; this.m_cmsgRecipientInfo = cmsgRecipientInfo; this.m_index = index; }
/// <summary> /// Get a property from the current token /// </summary> private T GetTokenInformation <T>(TokenInformationClass tokenInformationClass) where T : struct { Debug.Assert(!_safeTokenHandle.IsInvalid && !_safeTokenHandle.IsClosed, "!m_safeTokenHandle.IsInvalid && !m_safeTokenHandle.IsClosed"); using (SafeLocalAllocHandle information = GetTokenInformation(_safeTokenHandle, tokenInformationClass)) { Debug.Assert(information.ByteLength >= (ulong)Marshal.SizeOf <T>(), "information.ByteLength >= (ulong)Marshal.SizeOf(typeof(T))"); return(information.Read <T>(0)); } }
[System.Security.SecurityCritical] // auto-generated internal UNICODE_INTPTR_STRING(int stringBytes, SafeLocalAllocHandle buffer) { Debug.Assert(buffer == null || (stringBytes >= 0 && (ulong)stringBytes <= buffer.ByteLength), "buffer == null || (stringBytes >= 0 && stringBytes <= buffer.ByteLength)"); this.Length = (ushort)stringBytes; this.MaxLength = (ushort)buffer.ByteLength; // Marshaling with a SafePointer does not work correctly, so unfortunately we need to extract // the raw handle here. this.Buffer = buffer.DangerousGetHandle(); }
// Private callback invoked when icmpsendecho APIs succeed. private void PingCallback() { TaskCompletionSource <PingReply> tcs = _taskCompletionSource; _taskCompletionSource = null; PingReply reply = null; Exception error = null; try { lock (_lockObject) { // Parse reply buffer. SafeLocalAllocHandle buffer = _replyBuffer; // Marshals and constructs new reply. if (_ipv6) { Interop.IpHlpApi.Icmp6EchoReply icmp6Reply = Marshal.PtrToStructure <Interop.IpHlpApi.Icmp6EchoReply>(buffer.DangerousGetHandle()); reply = CreatePingReplyFromIcmp6EchoReply(icmp6Reply, buffer.DangerousGetHandle(), _sendSize); } else { Interop.IpHlpApi.IcmpEchoReply icmpReply = Marshal.PtrToStructure <Interop.IpHlpApi.IcmpEchoReply>(buffer.DangerousGetHandle()); reply = CreatePingReplyFromIcmpEchoReply(icmpReply); } } } catch (Exception e) { // In case of failure, create a failed event arg. error = new PingException(SR.net_ping, e); } finally { FreeUnmanagedStructures(); UnregisterWaitHandle(); Finish(); } // Once we've called Finish, complete the task if (reply != null) { tcs.SetResult(reply); } else { Debug.Assert(error != null); tcs.SetException(error); } }
/// <summary> /// Convert each Oid's value to an ASCII string, then create an unmanaged array of "numOids" LPSTR pointers, one for each Oid. /// "numOids" is the number of LPSTR pointers. This is normally the same as oids.Count, except in the case where a malicious caller /// appends to the OidCollection while this method is in progress. In such a case, this method guarantees only that this won't create /// an unmanaged buffer overflow condition. /// </summary> public static SafeHandle ToLpstrArray(this OidCollection?oids, out int numOids) { if (oids == null || oids.Count == 0) { numOids = 0; return(SafeLocalAllocHandle.InvalidHandle); } // Copy the oid strings to a local array to prevent a security race condition where // the OidCollection or individual oids can be modified by another thread and // potentially cause a buffer overflow var oidStrings = new string[oids.Count]; for (int i = 0; i < oidStrings.Length; i++) { oidStrings[i] = oids[i].Value !; } unsafe { int allocationSize = checked (oidStrings.Length * sizeof(void *)); foreach (string oidString in oidStrings) { checked { allocationSize += oidString.Length + 1; // Encoding.ASCII doesn't have a fallback, so it's fine to use String.Length } } SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.Create(allocationSize); byte **pOidPointers = (byte **)(safeLocalAllocHandle.DangerousGetHandle()); byte * pOidContents = (byte *)(pOidPointers + oidStrings.Length); for (int i = 0; i < oidStrings.Length; i++) { string oidString = oidStrings[i]; pOidPointers[i] = pOidContents; int bytesWritten = Encoding.ASCII.GetBytes(oidString, new Span <byte>(pOidContents, oidString.Length)); Debug.Assert(bytesWritten == oidString.Length); pOidContents[oidString.Length] = 0; pOidContents += oidString.Length + 1; } numOids = oidStrings.Length; return(safeLocalAllocHandle); } }
// Any exceptions that escape synchronously will be caught by the caller and wrapped in a PingException. // We do not need to or want to capture such exceptions into the returned task. private Task <PingReply> DoSendPingCore(IPAddress address, byte[] buffer, int timeout, PingOptions?options, bool isAsync) { TaskCompletionSource <PingReply>?tcs = null; if (isAsync) { _taskCompletionSource = tcs = new TaskCompletionSource <PingReply>(); } _ipv6 = (address.AddressFamily == AddressFamily.InterNetworkV6); _sendSize = buffer.Length; // Cache correct handle. InitialiseIcmpHandle(); if (_replyBuffer == null) { _replyBuffer = SafeLocalAllocHandle.LocalAlloc(MaxUdpPacket); } int error; try { if (isAsync) { RegisterWaitHandle(); } SetUnmanagedStructures(buffer); error = SendEcho(address, buffer, timeout, options, isAsync); } catch { Cleanup(isAsync); throw; } if (error == 0) { error = Marshal.GetLastWin32Error(); // Only skip Async IO Pending error value. if (!isAsync || error != Interop.IpHlpApi.ERROR_IO_PENDING) { Cleanup(isAsync); IPStatus status = GetStatusFromCode(error); return(Task.FromResult(new PingReply(address, default, status, default, Array.Empty <byte>())));
private PingReply CreatePingReply() { SafeLocalAllocHandle buffer = _replyBuffer; // Marshals and constructs new reply. if (_ipv6) { Interop.IpHlpApi.Icmp6EchoReply icmp6Reply = Marshal.PtrToStructure <Interop.IpHlpApi.Icmp6EchoReply>(buffer.DangerousGetHandle()); return(CreatePingReplyFromIcmp6EchoReply(icmp6Reply, buffer.DangerousGetHandle(), _sendSize)); } Interop.IpHlpApi.IcmpEchoReply icmpReply = Marshal.PtrToStructure <Interop.IpHlpApi.IcmpEchoReply>(buffer.DangerousGetHandle()); return(CreatePingReplyFromIcmpEchoReply(icmpReply)); }
// Private callback invoked when icmpsendecho APIs succeed. private static void PingCallback(object state, bool signaled) { Ping ping = (Ping)state; PingCompletedEventArgs eventArgs = null; AsyncOperation asyncOp = null; SendOrPostCallback onPingCompletedDelegate = null; try { lock (ping._lockObject) { asyncOp = ping._asyncOp; onPingCompletedDelegate = ping._onPingCompletedDelegate; // Parse reply buffer. SafeLocalAllocHandle buffer = ping._replyBuffer; // Marshals and constructs new reply. PingReply reply; if (ping._ipv6) { Interop.IpHlpApi.Icmp6EchoReply icmp6Reply = Marshal.PtrToStructure <Interop.IpHlpApi.Icmp6EchoReply>(buffer.DangerousGetHandle()); reply = CreatePingReplyFromIcmp6EchoReply(icmp6Reply, buffer.DangerousGetHandle(), ping._sendSize); } else { Interop.IpHlpApi.IcmpEchoReply icmpReply = Marshal.PtrToStructure <Interop.IpHlpApi.IcmpEchoReply>(buffer.DangerousGetHandle()); reply = CreatePingReplyFromIcmpEchoReply(icmpReply); } eventArgs = new PingCompletedEventArgs(reply, null, false, asyncOp.UserSuppliedState); } } catch (Exception e) { // In case of failure, create a failed event arg. PingException pe = new PingException(SR.net_ping, e); eventArgs = new PingCompletedEventArgs(null, pe, false, asyncOp.UserSuppliedState); } finally { ping.FreeUnmanagedStructures(); ping.UnregisterWaitHandle(); ping.Finish(); } asyncOp.PostOperationCompleted(onPingCompletedDelegate, eventArgs); }
internal KeyTransRecipientInfo(SafeLocalAllocHandle pRecipientInfo, CAPI.CERT_INFO certInfo, uint index) : base(RecipientInfoType.KeyTransport, RecipientSubType.Pkcs7KeyTransport, pRecipientInfo, (object)certInfo, index) { int version = 2; byte* numPtr = (byte*)(void*)certInfo.SerialNumber.pbData; for (int index1 = 0; (long)index1 < (long)certInfo.SerialNumber.cbData; ++index1) { if ((int)*numPtr++ != 0) { version = 0; break; } } this.Reset(version); }
internal SignerInfo(SignedCms signedCms, SignerInfo parentSignerInfo, byte[] encodedSignerInfo) { uint cbDecodedValue = 0U; SafeLocalAllocHandle decodedValue = SafeLocalAllocHandle.InvalidHandle; fixed (byte* numPtr = &encodedSignerInfo[0]) { if (!CAPI.DecodeObject(new IntPtr(500L), new IntPtr((void*)numPtr), (uint)encodedSignerInfo.Length, out decodedValue, out cbDecodedValue)) throw new CryptographicException(Marshal.GetLastWin32Error()); } this.m_signedCms = signedCms; this.m_parentSignerInfo = parentSignerInfo; this.m_encodedSignerInfo = (byte[])encodedSignerInfo.Clone(); this.m_pbCmsgSignerInfo = decodedValue; this.m_cmsgSignerInfo = (CAPI.CMSG_SIGNER_INFO)Marshal.PtrToStructure(decodedValue.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_INFO)); }
internal AlgorithmIdentifier(CAPI.CERT_PUBLIC_KEY_INFO keyInfo) { SafeLocalAllocHandle pKeyInfo = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(Marshal.SizeOf(typeof(CAPI.CERT_PUBLIC_KEY_INFO)))); Marshal.StructureToPtr(keyInfo, pKeyInfo.DangerousGetHandle(), false); int keyLength = (int)CAPI.CAPISafe.CertGetPublicKeyLength(CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, pKeyInfo.DangerousGetHandle()); byte[] parameters = new byte[keyInfo.Algorithm.Parameters.cbData]; if (parameters.Length > 0) { Marshal.Copy(keyInfo.Algorithm.Parameters.pbData, parameters, 0, parameters.Length); } Marshal.DestroyStructure(pKeyInfo.DangerousGetHandle(), typeof(CAPI.CERT_PUBLIC_KEY_INFO)); pKeyInfo.Dispose(); Reset(Oid.FromOidValue(keyInfo.Algorithm.pszObjId, OidGroup.PublicKeyAlgorithm), keyLength, parameters); }
internal unsafe KeyTransRecipientInfo(SafeLocalAllocHandle pRecipientInfo, CAPI.CERT_INFO certInfo, uint index) : base(RecipientInfoType.KeyTransport, RecipientSubType.Pkcs7KeyTransport, pRecipientInfo, certInfo, index) { // If serial number is 0, then it is the special SKI encoding. int version = 2; byte *pb = (byte *)certInfo.SerialNumber.pbData; for (int i = 0; i < certInfo.SerialNumber.cbData; i++) { if (*pb++ != (byte)0) { version = 0; break; } } Reset(version); }
private static byte[] Encode(DateTime signingTime) { long ft = signingTime.ToFileTimeUtc(); SafeLocalAllocHandle pbSigningTime = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(Marshal.SizeOf(typeof(Int64)))); Marshal.WriteInt64(pbSigningTime.DangerousGetHandle(), ft); byte[] encodedSigningTime = new byte[0]; if (!CAPI.EncodeObject(CAPI.szOID_RSA_signingTime, pbSigningTime.DangerousGetHandle(), out encodedSigningTime)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } pbSigningTime.Dispose(); return(encodedSigningTime); }
private static SafeLocalAllocHandle GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass) { SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle; uint dwLength = (uint)sizeof(uint); bool result = Interop.Advapi32.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, safeLocalAllocHandle, 0, out dwLength); int dwErrorCode = Marshal.GetLastWin32Error(); switch (dwErrorCode) { case Interop.Errors.ERROR_BAD_LENGTH: // special case for TokenSessionId. Falling through case Interop.Errors.ERROR_INSUFFICIENT_BUFFER: // ptrLength is an [In] param to LocalAlloc UIntPtr ptrLength = new UIntPtr(dwLength); safeLocalAllocHandle.Dispose(); safeLocalAllocHandle = Interop.Kernel32.LocalAlloc(0, ptrLength); if (safeLocalAllocHandle == null || safeLocalAllocHandle.IsInvalid) { throw new OutOfMemoryException(); } safeLocalAllocHandle.Initialize(dwLength); result = Interop.Advapi32.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, safeLocalAllocHandle, dwLength, out dwLength); if (!result) { throw new SecurityException(new Win32Exception().Message); } break; case Interop.Errors.ERROR_INVALID_HANDLE: throw new ArgumentException(SR.Argument_InvalidImpersonationToken); default: throw new SecurityException(new Win32Exception(dwErrorCode).Message); } return(safeLocalAllocHandle); }
internal RecipientInfo(RecipientInfoType recipientInfoType, RecipientSubType recipientSubType, SafeLocalAllocHandle pCmsgRecipientInfo, Object cmsgRecipientInfo, uint index) { if (recipientInfoType < RecipientInfoType.Unknown || recipientInfoType > RecipientInfoType.KeyAgreement) { recipientInfoType = RecipientInfoType.Unknown; } if (recipientSubType < RecipientSubType.Unknown || recipientSubType > RecipientSubType.PublicKeyAgreement) { recipientSubType = RecipientSubType.Unknown; } m_recipentInfoType = recipientInfoType; m_recipientSubType = recipientSubType; m_pCmsgRecipientInfo = pCmsgRecipientInfo; m_cmsgRecipientInfo = cmsgRecipientInfo; m_index = index; }
internal unsafe SignerInfoCollection(SignedCms signedCms) { uint dwSigners = 0; uint cbCount = (uint)Marshal.SizeOf(typeof(uint)); SafeCryptMsgHandle safeCryptMsgHandle = signedCms.GetCryptMsgHandle(); if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle, CAPI.CMSG_SIGNER_COUNT_PARAM, 0, new IntPtr(&dwSigners), new IntPtr(&cbCount))) { throw new CryptographicException(Marshal.GetLastWin32Error()); } SignerInfo[] signerInfos = new SignerInfo[dwSigners]; for (int index = 0; index < dwSigners; index++) { uint cbCmsgSignerInfo = 0; if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle, CAPI.CMSG_SIGNER_INFO_PARAM, (uint)index, IntPtr.Zero, new IntPtr(&cbCmsgSignerInfo))) { throw new CryptographicException(Marshal.GetLastWin32Error()); } SafeLocalAllocHandle pbCmsgSignerInfo = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbCmsgSignerInfo)); if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle, CAPI.CMSG_SIGNER_INFO_PARAM, (uint)index, pbCmsgSignerInfo, new IntPtr(&cbCmsgSignerInfo))) { throw new CryptographicException(Marshal.GetLastWin32Error()); } signerInfos[index] = new SignerInfo(signedCms, pbCmsgSignerInfo); } m_signerInfos = signerInfos; }
// Cancels pending async requests, closes the handles. private void InternalDispose() { _disposeRequested = true; if (Interlocked.CompareExchange(ref _status, Disposed, Free) != Free) { // Already disposed, or Finish will call Dispose again once Free. return; } if (_handlePingV4 != null) { _handlePingV4.Dispose(); _handlePingV4 = null; } if (_handlePingV6 != null) { _handlePingV6.Dispose(); _handlePingV6 = null; } UnregisterWaitHandle(); if (pingEvent != null) { pingEvent.Dispose(); pingEvent = null; } if (_replyBuffer != null) { _replyBuffer.Dispose(); _replyBuffer = null; } if (_asyncFinished != null) { _asyncFinished.Dispose(); _asyncFinished = null; } }
/// <summary>Dispose of the instance.</summary> public void Dispose() { if (_mediaDetector != null) { // Free the frame buffer _frameBuffer.Dispose(); _frameBuffer = null; // Free the media type if (_mediaType.cbFormat != 0) { Marshal.FreeCoTaskMem(new IntPtr(_mediaType.cbFormat)); } _mediaType = new _AMMediaType(); // Release the media detector Marshal.ReleaseComObject(_mediaDetector); _mediaDetector = null; } }
private void Decode() { uint cbDecoded = 0; SafeLocalAllocHandle pbDecoded = null; if (!CAPI.DecodeObject(new IntPtr(CAPI.PKCS_UTC_TIME), RawData, out pbDecoded, out cbDecoded)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } long signingTime = Marshal.ReadInt64(pbDecoded.DangerousGetHandle()); pbDecoded.Dispose(); m_signingTime = DateTime.FromFileTimeUtc(signingTime); m_decoded = true; }
internal static NetworkInterface[] GetNetworkInterfaces() { AddressFamily family = AddressFamily.Unspecified; uint outBufLen = 0; Interop.FIXED_INFO fixedInfo = HostInformationPal.GetFixedInfo(); List <SystemNetworkInterface> networkInterfaceList = new List <SystemNetworkInterface>(); Interop.GetAdaptersAddressesFlags adaptersAddressesFlags = Interop.GetAdaptersAddressesFlags.IncludeWins | Interop.GetAdaptersAddressesFlags.IncludeGateways | Interop.GetAdaptersAddressesFlags.IncludeAllInterfaces; uint adaptersAddresses = Interop.GetAdaptersAddresses(family, (uint)adaptersAddressesFlags, IntPtr.Zero, SafeLocalAllocHandle.Zero, ref outBufLen); while ((int)adaptersAddresses == 111) { SafeLocalAllocHandle adapterAddresses; using (adapterAddresses = SafeLocalAllocHandle.LocalAlloc((int)outBufLen)) { adaptersAddresses = Interop.GetAdaptersAddresses(family, (uint)adaptersAddressesFlags, IntPtr.Zero, adapterAddresses, ref outBufLen); Interop.IpAdapterAddresses structure; if ((int)adaptersAddresses == 0) { for (IntPtr ptr = adapterAddresses.DangerousGetHandle(); ptr != IntPtr.Zero; ptr = structure.next) { structure = Marshal.PtrToStructure <Interop.IpAdapterAddresses>(ptr); var a = new SystemNetworkInterface(fixedInfo, structure); networkInterfaceList.Add(a); } } } } if ((int)adaptersAddresses == 232 || (int)adaptersAddresses == 87) { return((NetworkInterface[])Array.Empty <SystemNetworkInterface>()); } if ((int)adaptersAddresses != 0) { throw new NetworkInformationException((int)adaptersAddresses); } return((NetworkInterface[])networkInterfaceList.ToArray()); }
/// <summary>Initialize the VideoFrameReader.</summary> /// <param name="path">The path to the video to load.</param> public VideoFrameReader(string path) { if (path == null) { throw new ArgumentNullException(path); } // Load the video, determine the size of a frame in the video, // determine the length of the video, and calculate the number of frames in it. _mediaDetector = LoadVideo(path, out _mediaType); _frameSize = GetFrameSize(_mediaType); _streamLength = _mediaDetector.StreamLength; _numberOfFrames = (int)(_streamLength * _mediaDetector.FrameRate); // Create an unmanaged buffer to use in the frame extraction process. // We need a buffer large enough to store three bytes per pixel (RGB) // plus the size of a BITMAPINFOHEADER structure. _headerSize = Marshal.SizeOf(typeof(BITMAPINFOHEADER)); _bufferSize = (_frameSize.Width * _frameSize.Height * 3) + _headerSize; _frameBuffer = SafeLocalAllocHandle.LocalAlloc(_bufferSize); }
internal static SafeLocalAllocHandle DecodeExtension(CERT_EXTENSION extension) { SafeLocalAllocHandle decodedExtension = null; int decodedSize = 0; bool decoded = UnsafeNativeMethods.CryptDecodeObjectEx(CertificateEncodingType.Pkcs7AsnEncoding | CertificateEncodingType.X509AsnEncoding, extension.pszObjId, extension.Value.pbData, extension.Value.cbData, DecodeObjectFlags.AllocateMemory | DecodeObjectFlags.NoCopy | DecodeObjectFlags.ShareOidStrings, IntPtr.Zero, out decodedExtension, ref decodedSize); if (!decoded) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } return(decodedExtension); }
public static IList <X509AlternateName> GetAlternateNames(this X509Certificate certificate, Oid2 alternateNameExtensionOid) { if (alternateNameExtensionOid == null) { throw new ArgumentNullException("alternateNameExtensionOid"); } List <X509AlternateName> alternateNames = new List <X509AlternateName>(); using (SafeCertContextHandle certContext = certificate.GetCertificateContext()) { // Make sure we have the extension requested if (X509Native.HasExtension(certContext, alternateNameExtensionOid.Value)) { // If so, get it from the certificate, and decode it into a buffer X509Native.CERT_EXTENSION alternateNameExtension = X509Native.FindExtension(certContext, alternateNameExtensionOid.Value); using (SafeLocalAllocHandle decodedBuffer = X509Native.DecodeExtension(alternateNameExtension)) { // This buffer contains CERT_ALT_NAME_INFO which points us at the alternate names we // were looking for X509Native.CERT_ALT_NAME_INFO altNameInfo = decodedBuffer.Read <X509Native.CERT_ALT_NAME_INFO>(0); for (int i = 0; i < altNameInfo.cAltEntry; ++i) { unsafe { X509Native.CERT_ALT_NAME_ENTRY *pAltNameEntry = (X509Native.CERT_ALT_NAME_ENTRY *)altNameInfo.rgAltEntry; alternateNames.Add(X509AlternateName.FromAltNameEntry(pAltNameEntry[i])); } } } } } return(alternateNames); }
internal static unsafe bool DecodeObject(IntPtr pszStructType, byte[] pbEncoded, out SafeLocalAllocHandle decodedValue, out uint cbDecodedValue) { decodedValue = SafeLocalAllocHandle.InvalidHandle; cbDecodedValue = 0U; uint num = 0U; SafeLocalAllocHandle invalidHandle = SafeLocalAllocHandle.InvalidHandle; if (!CAPI.CAPISafe.CryptDecodeObject(65537U, pszStructType, pbEncoded, (uint)pbEncoded.Length, 0U, invalidHandle, new IntPtr((void*)&num))) return false; SafeLocalAllocHandle pvStructInfo = CAPI.LocalAlloc(0U, new IntPtr((long)num)); if (!CAPI.CAPISafe.CryptDecodeObject(65537U, pszStructType, pbEncoded, (uint)pbEncoded.Length, 0U, pvStructInfo, new IntPtr((void*)&num))) return false; decodedValue = pvStructInfo; cbDecodedValue = num; return true; }
bool DecodeObject(IntPtr pszStructType, byte[] pbEncoded, out SafeLocalAllocHandle decodedValue, out uint cbDecodedValue) { // Initialize out parameters decodedValue = SafeLocalAllocHandle.InvalidHandle; cbDecodedValue = 0; // Decode uint cbDecoded = 0; SafeLocalAllocHandle pbDecoded = SafeLocalAllocHandle.InvalidHandle; if (!CAPIMethods.CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, pszStructType, pbEncoded, (uint) pbEncoded.Length, 0, pbDecoded, new IntPtr(&cbDecoded))) return false; pbDecoded = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbDecoded)); if (!CAPIMethods.CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, pszStructType, pbEncoded, (uint) pbEncoded.Length, 0, pbDecoded, new IntPtr(&cbDecoded))) return false; // Return decoded values decodedValue = pbDecoded; cbDecodedValue = cbDecoded; return true; }
bool DecodeObject(IntPtr pszStructType, IntPtr pbEncoded, uint cbEncoded, out SafeLocalAllocHandle decodedValue, out uint cbDecodedValue) { // Initialize out parameters decodedValue = SafeLocalAllocHandle.InvalidHandle; cbDecodedValue = 0; // Decode uint cbDecoded = 0; SafeLocalAllocHandle ptr = SafeLocalAllocHandle.InvalidHandle; bool result = CAPIMethods.CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, pszStructType, pbEncoded, cbEncoded, 0, ptr, new IntPtr(&cbDecoded)); if (result == false) return false; ptr = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbDecoded)); result = CAPIMethods.CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, pszStructType, pbEncoded, cbEncoded, 0, ptr, new IntPtr(&cbDecoded)); if (result == false) return false; // Return decoded values decodedValue = ptr; cbDecodedValue = cbDecoded; return true; }
internal KeyTransRecipientInfo(SafeLocalAllocHandle pRecipientInfo, CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO keyTrans, uint index) : base(RecipientInfoType.KeyTransport, RecipientSubType.CmsKeyTransport, pRecipientInfo, (object)keyTrans, index) { this.Reset((int)keyTrans.dwVersion); }
internal KeyAgreeRecipientInfo(SafeLocalAllocHandle pRecipientInfo, CAPI.CMSG_KEY_AGREE_PUBLIC_KEY_RECIPIENT_INFO publicKeyRecipient, uint index, uint subIndex) : base(RecipientInfoType.KeyAgreement, RecipientSubType.PublicKeyAgreement, pRecipientInfo, (object)publicKeyRecipient, index) { CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_INFO encryptedKeyInfo = (CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_INFO)Marshal.PtrToStructure(Marshal.ReadIntPtr(new IntPtr((long)publicKeyRecipient.rgpRecipientEncryptedKeys + (long)subIndex * (long)Marshal.SizeOf(typeof(IntPtr)))), typeof(CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_INFO)); this.Reset(2U, publicKeyRecipient.dwVersion, encryptedKeyInfo, subIndex); }
public static SafeLocalAllocHandle Alloc(int cb) { SafeLocalAllocHandle handle = new SafeLocalAllocHandle(); handle.AllocCore(cb); return handle; }
internal UNICODE_INTPTR_STRING(int stringBytes, SafeLocalAllocHandle buffer) { Length = (ushort)stringBytes; MaxLength = (ushort)buffer.ByteLength; Buffer = buffer.DangerousGetHandle(); }