Exemplo n.º 1
0
        /// <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();
        }
Exemplo n.º 2
0
 /// <summary>
 /// Add a DateTime and a non-negative TimeSpan.
 /// The maximum time is DateTime.MaxTime.  It is not an error if time + timespan > MaxTime.
 /// Just return MaxTime. If TimeSpan is &lt; TimeSpan.Zero, throw exception.
 /// </summary>
 /// <param name="time"></param>
 /// <param name="timespan"></param>
 /// <returns></returns>
 public static DateTime AddNonNegative(DateTime time, TimeSpan timespan)
 {
     if (timespan <= TimeSpan.Zero)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2082)));
     }
     return(Add(time, timespan));
 }
Exemplo n.º 3
0
        /// <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)));
            }
        }
Exemplo n.º 4
0
        /// <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)));
            }
        }
Exemplo n.º 5
0
 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)));
     }
 }
Exemplo n.º 6
0
        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);
        }
Exemplo n.º 7
0
 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));
 }
Exemplo n.º 8
0
        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);
        }
Exemplo n.º 9
0
        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);
        }