/// <summary> /// Creates a cache for items of Type 'T' where expired items will purged on a regular interval /// </summary> /// <param name="capacity">The maximum size of the cache in number of items. /// If int.MaxValue is passed then the size is not bound.</param> /// <param name="purgeInterval">The time interval for checking expired items.</param> /// <param name="keyComparer">EqualityComparer for comparing keys.</param> /// <exception cref="ArgumentOutOfRangeException">The input parameter 'capacity' is less than or equal to zero.</exception> /// <exception cref="ArgumentOutOfRangeException">The input parameter 'purgeInterval' is less than or equal to TimeSpan.Zero.</exception> /// <exception cref="ArgumentNullException">The input parameter 'keyComparer' is null.</exception> public BoundedCache(int capacity, TimeSpan purgeInterval, IEqualityComparer <string> keyComparer) { if (capacity <= 0) { throw DiagnosticUtility.ThrowHelperArgumentOutOfRange("capacity", capacity, SR.GetString(SR.ID0002)); } if (purgeInterval <= TimeSpan.Zero) { throw DiagnosticUtility.ThrowHelperArgumentOutOfRange("purgeInterval", purgeInterval, SR.GetString(SR.ID0016)); } if (keyComparer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyComparer"); } _capacity = capacity; _purgeInterval = purgeInterval; _items = new Dictionary <string, ExpirableItem <T> >(keyComparer); _readWriteLock = new ReaderWriterLock(); }
internal static unsafe SafeKeyHandle SafeCryptImportKey(SafeProvHandle provHandle, void *pbDataPtr, int cbData) { bool b = false; int err = 0; SafeKeyHandle keyHandle = null; RuntimeHelpers.PrepareConstrainedRegions(); try { provHandle.DangerousAddRef(ref b); } catch (Exception e) { if (System.Runtime.Fx.IsFatal(e)) { throw; } if (b) { provHandle.DangerousRelease(); b = false; } if (!(e is ObjectDisposedException)) { throw; } } finally { if (b) { b = NativeMethods.CryptImportKey(provHandle, pbDataPtr, (uint)cbData, IntPtr.Zero, 0, out keyHandle); if (!b) { err = Marshal.GetLastWin32Error(); provHandle.DangerousRelease(); } else { // Take ownership of AddRef. Will Release at Close. keyHandle.provHandle = provHandle; } } } if (!b) { Utility.CloseInvalidOutSafeHandle(keyHandle); string reason = (err != 0) ? new Win32Exception(err).Message : String.Empty; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.AESCryptImportKeyFailed, reason))); } return(keyHandle); }
/// <summary> /// ServiceBinding check has the following logic: /// 1. Check PolicyEnforcement - never => return true; /// 1. Check status returned from SecurityContext which is obtained when querying for the serviceBinding /// 2. Check PolicyEnforcement /// a. WhenSupported - valid when OS does not support, null serviceBinding is valid /// b. Always - a non-empty servicebinding must be available /// 3. if serviceBinding is non null, check that an expected value is in the ServiceNameCollection - ignoring case /// note that the empty string must be explicitly specified in the serviceNames. /// </summary> /// <param name="securityContext to ">status Code returned when obtaining serviceBinding from SecurityContext</param> /// <returns>If servicebinding is valid</returns> public void CheckServiceBinding(SafeDeleteContext securityContext, string defaultServiceBinding) { if (_policyEnforcement == PolicyEnforcement.Never) { return; } string serviceBinding = null; int statusCode = SspiWrapper.QuerySpecifiedTarget(securityContext, out serviceBinding); if (statusCode != (int)SecurityStatus.OK) { // only two acceptable non-zero values // client OS not patched: stausCode == TargetUnknown // service OS not patched: statusCode == Unsupported if (statusCode != (int)SecurityStatus.TargetUnknown && statusCode != (int)SecurityStatus.Unsupported) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.InvalidServiceBindingInSspiNegotiationNoServiceBinding))); } // if policyEnforcement is Always we needed to see a TargetName (SPN) if (_policyEnforcement == PolicyEnforcement.Always) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.InvalidServiceBindingInSspiNegotiationNoServiceBinding))); } // in this case we accept because either the client or service is not patched. if (_policyEnforcement == PolicyEnforcement.WhenSupported) { return; } // guard against futures, force failure and fix as necessary throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.InvalidServiceBindingInSspiNegotiationNoServiceBinding))); } switch (_policyEnforcement) { case PolicyEnforcement.WhenSupported: // serviceBinding == null => client is not patched if (serviceBinding == null) { return; } break; case PolicyEnforcement.Always: // serviceBinding == null => client is not patched // serviceBinding == "" => SB was not specified if (string.IsNullOrEmpty(serviceBinding)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.InvalidServiceBindingInSspiNegotiationServiceBindingNotMatched, string.Empty))); } break; } // iff no values were 'user' set, then check the defaultServiceBinding if (_serviceNameCollection == null || _serviceNameCollection.Count < 1) { if (defaultServiceBinding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.InvalidServiceBindingInSspiNegotiationServiceBindingNotMatched, string.Empty))); } if (string.Compare(defaultServiceBinding, serviceBinding, StringComparison.OrdinalIgnoreCase) == 0) { return; } if (string.IsNullOrEmpty(serviceBinding)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.InvalidServiceBindingInSspiNegotiationServiceBindingNotMatched, string.Empty))); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.InvalidServiceBindingInSspiNegotiationServiceBindingNotMatched, serviceBinding))); } } if (_serviceNameCollection != null) { if (_serviceNameCollection.Contains(serviceBinding)) { return; } } if (string.IsNullOrEmpty(serviceBinding)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.InvalidServiceBindingInSspiNegotiationServiceBindingNotMatched, string.Empty))); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.InvalidServiceBindingInSspiNegotiationServiceBindingNotMatched, serviceBinding))); } }
/// <summary> /// Ensures that the maximum size is not exceeded /// </summary> /// <exception cref="LimitExceededException">If the Capacity of the cache has been reached.</exception> void EnforceQuota() { // int.MaxValue => unbounded if (_capacity == int.MaxValue) { return; } if (_items.Count >= _capacity) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new LimitExceededException(SR.GetString(SR.ID0021, _capacity))); } }
static int ConvertHexDigit(Char val) { if (val <= '9' && val >= '0') { return(val - '0'); } else if (val >= 'a' && val <= 'f') { return((val - 'a') + 10); } else if (val >= 'A' && val <= 'F') { return((val - 'A') + 10); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.InvalidHexString))); } }
internal static byte[] DecodeHexString(string hexString) { hexString = hexString.Trim(); bool spaceSkippingMode = false; int i = 0; int length = hexString.Length; if ((length >= 2) && (hexString[0] == '0') && ((hexString[1] == 'x') || (hexString[1] == 'X'))) { length = hexString.Length - 2; i = 2; } if (length < 2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.InvalidHexString))); } byte[] sArray; if (length >= 3 && hexString[i + 2] == ' ') { if (length % 3 != 2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.InvalidHexString))); } spaceSkippingMode = true; // Each hex digit will take three spaces, except the first (hence the plus 1). sArray = DiagnosticUtility.Utility.AllocateByteArray(length / 3 + 1); } else { if (length % 2 != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.InvalidHexString))); } spaceSkippingMode = false; // Each hex digit will take two spaces sArray = DiagnosticUtility.Utility.AllocateByteArray(length / 2); } int digit; int rawdigit; for (int j = 0; i < hexString.Length; i += 2, j++) { rawdigit = ConvertHexDigit(hexString[i]); digit = ConvertHexDigit(hexString[i + 1]); sArray[j] = (byte)(digit | (rawdigit << 4)); if (spaceSkippingMode) { i++; } } return(sArray); }
internal static byte[] DecryptKey(SecurityToken unwrappingToken, string encryptionMethod, byte[] wrappedKey, out SecurityKey unwrappingSecurityKey) { unwrappingSecurityKey = null; if (unwrappingToken.SecurityKeys != null) { for (int i = 0; i < unwrappingToken.SecurityKeys.Count; ++i) { if (unwrappingToken.SecurityKeys[i].IsSupportedAlgorithm(encryptionMethod)) { unwrappingSecurityKey = unwrappingToken.SecurityKeys[i]; break; } } } if (unwrappingSecurityKey == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SecurityMessageSerializationException(SR.GetString(SR.CannotFindMatchingCrypto, encryptionMethod))); } return(unwrappingSecurityKey.DecryptKey(encryptionMethod, wrappedKey)); }
internal static byte[] ReadContentAsBase64(XmlDictionaryReader reader, long maxBufferSize) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } // Code cloned from System.Xml.XmlDictionaryReder. byte[][] buffers = new byte[32][]; byte[] buffer; // Its best to read in buffers that are a multiple of 3 so we don't break base64 boundaries when converting text int count = 384; int bufferCount = 0; int totalRead = 0; while (true) { buffer = new byte[count]; buffers[bufferCount++] = buffer; int read = 0; while (read < buffer.Length) { int actual = reader.ReadContentAsBase64(buffer, read, buffer.Length - read); if (actual == 0) { break; } read += actual; } if (totalRead > maxBufferSize - read) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new LimitExceededException(SR.GetString(SR.BufferQuotaExceededReadingBase64, maxBufferSize))); } totalRead += read; if (read < buffer.Length) { break; } count = count * 2; } buffer = new byte[totalRead]; int offset = 0; for (int i = 0; i < bufferCount - 1; i++) { Buffer.BlockCopy(buffers[i], 0, buffer, offset, buffers[i].Length); offset += buffers[i].Length; } Buffer.BlockCopy(buffers[bufferCount - 1], 0, buffer, offset, totalRead - offset); return(buffer); }
internal static AuthorizationContext CreateDefaultAuthorizationContext(IList <IAuthorizationPolicy> authorizationPolicies) { AuthorizationContext authorizationContext; // This is faster than Policy evaluation. if (authorizationPolicies != null && authorizationPolicies.Count == 1 && authorizationPolicies[0] is UnconditionalPolicy) { authorizationContext = new SimpleAuthorizationContext(authorizationPolicies); } // degenerate case else if (authorizationPolicies == null || authorizationPolicies.Count <= 0) { return(DefaultAuthorizationContext.Empty); } else { // there are some policies, run them until they are all done DefaultEvaluationContext evaluationContext = new DefaultEvaluationContext(); object[] policyState = new object[authorizationPolicies.Count]; object done = new object(); int oldContextCount; do { oldContextCount = evaluationContext.Generation; for (int i = 0; i < authorizationPolicies.Count; i++) { if (policyState[i] == done) { continue; } IAuthorizationPolicy policy = authorizationPolicies[i]; if (policy == null) { policyState[i] = done; continue; } if (policy.Evaluate(evaluationContext, ref policyState[i])) { policyState[i] = done; if (DiagnosticUtility.ShouldTraceVerbose) { TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.AuthorizationPolicyEvaluated, SR.GetString(SR.AuthorizationPolicyEvaluated, policy.Id)); } } } } while (oldContextCount < evaluationContext.Generation); authorizationContext = new DefaultAuthorizationContext(evaluationContext); } if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.AuthorizationContextCreated, SR.GetString(SR.AuthorizationContextCreated, authorizationContext.Id)); } return(authorizationContext); }