/**
         * Builds a certificate reference expression that is an {@link ExtensionField}.
         * @param token The token used to build the field.
         * @return An {@link ExtensionField} object that represents the token.  Returns null if the token does not represent an {@link ExtensionField}.
         * @throws PolicyParseException
         */
        public IPolicyExpression BuildExtensionField(String token) //throws PolicyParseException
        {
            IPolicyExpression   retVal    = null;
            ExtensionIdentifier fieldType = ExtensionIdentifier.FromToken(token);
            bool required = token.EndsWith("+");

            if (fieldType != null)
            {
                try
                {
                    Type retType = fieldType.GetReferenceClass(token, required);
                    if (retType == null)
                    {
                        throw new PolicyParseException("ExtensionField with token name " + token + " has not been implemented yet.");
                    }
                    var ctor = retType.Ctor <bool, IPolicyExpression>();
                    retVal = ctor(required);
                }
                catch (PolicyParseException ex)
                {
                    throw ex;
                }
                catch (Exception e)
                {
                    throw new PolicyParseException("Error building ExtensionField", e);
                }
            }
            return(retVal);
        }
示例#2
0
        public void TestBuildX509Field_UnknownField_AssertNull()
        {
            var parser = new SimpleTextV1LexiconPolicyParser();
            IPolicyExpression field = parser.BuildX509Field("X509.Bogus");

            Assert.Null(field);
        }
示例#3
0
 public void Add(string domain, IPolicyExpression policyExpression)
 {
     lock (m_policyExpressions)
     {
         m_policyExpressions.Add(domain, policyExpression);
     }
 }
示例#4
0
        public void TestBuildX509Field_SignatureAlgorithm_AssertBuilt()
        {
            var parser = new SimpleTextV1LexiconPolicyParser();

            IPolicyExpression field = parser.BuildX509Field("X509.Algorithm");

            Assert.NotNull(field);
            field.GetType().Should().Be(typeof(SignatureAlgorithmField));
        }
示例#5
0
        public void Serialize(IPolicyExpression expression, TextWriter writer)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }
            XmlSerializer xmlSerializer = new XmlSerializer(expression.GetType());

            xmlSerializer.Serialize(writer, expression);
        }
示例#6
0
        public bool IsCompliant(X509Certificate2 cert, IPolicyExpression expression)
        {
            if (m_compiler == null)
                throw new InvalidOperationException("Compiler cannot be null");

            if (m_executionEngine == null)
                throw new InvalidOperationException("Execution engine cannot be null");

            IList<IOpCode> opcodes = m_compiler.Compile(cert, expression);
            var compliant = m_executionEngine.Evaluate(opcodes);
            return compliant;
        }
示例#7
0
        public string Serialize(IPolicyExpression expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            using (StringWriter writer = new StringWriter())
            {
                Serialize(expression, writer);
                return(writer.ToString());
            }
        }
示例#8
0
        public bool IsCompliant(X509Certificate2 cert, IPolicyExpression expression)
        {
            if (m_compiler == null)
            {
                throw new InvalidOperationException("Compiler cannot be null");
            }

            StackMachine    executionEngine = new StackMachine();
            IList <IOpCode> opcodes         = m_compiler.Compile(cert, expression);
            var             compliant       = executionEngine.Evaluate(opcodes);

            return(compliant);
        }
示例#9
0
 public IPolicyExpression GetPolicyExpression(byte[] policy)
 {
     try
     {
         //might get parser from policy.Lexicon in the future
         var parser = new SimpleTextV1LexiconPolicyParser();
         IPolicyExpression expression = parser.Parse(policy.ToMemoryStream());
         return(expression);
     }
     catch (Exception)
     {
         return(null);
     }
 }
示例#10
0
        public IList <IOpCode> Compile(X509Certificate2 cert, IPolicyExpression expression)
        {
            IList <String> report = m_compilerReport.Value;

            if (report != null)
            {
                report.Clear();
            }

            IList <IOpCode> entries = new List <IOpCode>();

            entries.Add(Compile(entries, cert, expression));
            return(entries);
        }
示例#11
0
        private async void CallLexiconParser(string lexicon, RichTextBox rtxBox)
        {
            try
            {
                IPolicyExpression expression = await ParseLexicon(lexicon);

                var textRange = new TextRange(rtxBox.Document.ContentStart, rtxBox.Document.ContentEnd);
                textRange.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);
            }
            catch (PolicyGrammarException)
            {
                var textRange = new TextRange(rtxBox.Document.ContentStart, rtxBox.Document.ContentEnd);
                textRange.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
            }
        }
示例#12
0
        public bool IsCompliant(X509Certificate2 cert, IPolicyExpression expression)
        {
            if (m_compiler == null)
            {
                throw new InvalidOperationException("Compiler cannot be null");
            }

            if (m_executionEngine == null)
            {
                throw new InvalidOperationException("Execution engine cannot be null");
            }

            IList <IOpCode> opcodes = m_compiler.Compile(cert, expression);

            return(m_executionEngine.Evaluate(opcodes));
        }
示例#13
0
        public void Serialize(IPolicyExpression expression, Stream stream)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            XmlSerializer xmlSerializer = new XmlSerializer(expression.GetType());

            xmlSerializer.Serialize(stream, expression);
        }
示例#14
0
        public void Combine(IPolicyExpressionRoot right, PolicyOperator @operator)
        {
            if (right == null)
            {
                throw new ArgumentNullException(nameof(right));
            }

            PolicyExpressionWithOperator exp = new PolicyExpressionWithOperator(@operator, expression, right.Expression);

            if (isPolicyOnly)
            {
                isPolicyOnly = false;
                policyName   = null;
            }
            expression = exp;
            result     = exp.Result;
        }
        protected IPolicyExpression BuildCertificateReferenceField(String token) //throws PolicyParseException
        {
            IPolicyExpression checkObj = BuildX509Field(token);

            // check to see if its an X509Field
            if (checkObj == null)
            {
                // check to see if TBSFieldName
                checkObj = BuildTBSField(token);
                if (checkObj == null)
                {
                    // check for extension field
                    checkObj = BuildExtensionField(token);
                }
            }

            return(checkObj);
        }
        public void TestExtensionBasicContraint_CA_AssertTrue()
        {
            var parser = new SimpleTextV1LexiconPolicyParser();

            using (Stream stream = ("X509.TBS.EXTENSION.BasicConstraints.CA = true").ToStream())
            {
                IList <SimpleTextV1LexiconPolicyParser.TokenTypeAssociation> tokens = parser.ParseToTokens(stream);
                tokens.Count.Should().Be(3);
            }

            using (Stream stream = ("X509.TBS.EXTENSION.BasicConstraints.CA = true").ToStream())
            {
                IPolicyExpression expression = parser.Parse(stream);
                expression.Should().BeAssignableTo <OperationPolicyExpression>();

                var operationPolicyExpression = expression as OperationPolicyExpression;
                operationPolicyExpression.GetOperands().Count.Should().Be(2);
            }
        }
示例#17
0
        public PolicyExpressionWithOperator(PolicyOperator @operator, IPolicyExpression left, IPolicyExpression right)
        {
            this.@operator = @operator;
            this.left      = left;
            this.right     = right;
            PolicyResult leftResult  = left.Result;
            PolicyResult rightResult = right.Result;

            switch (@operator)
            {
            case PolicyOperator.And:
                this.result = AndOperation[(int)leftResult, (int)rightResult];
                break;

            case PolicyOperator.Or:
            default:
                this.result = OrOperation[(int)leftResult, (int)rightResult];
                break;
            }
        }
        public override IPolicyExpression Parse(Stream stream)
        {
            IList <TokenTypeAssociation> tokens = ParseToTokens(stream);

            ResetLevel();

            IPolicyExpression retExpression = BuildExpression(tokens.GetEnumerator());

            if (GetLevel() != 0)
            {
                throw new PolicyGrammarException("Group not closed.");
            }

            if (retExpression.GetExpressionType() != PolicyExpressionType.OPERATION)
            {
                throw new PolicyGrammarException("Expression must evaluate to an operation");
            }

            return(retExpression);
        }
示例#19
0
        public PolicyExpressionRoot(IPolicyExpression expression)
        {
            this.expression = expression;
            result          = expression.Result;

            switch (expression)
            {
            case IPolicyOnlyExpression policyOnly:
                isPolicyOnly = true;
                policyName   = policyOnly.Policy;
                break;

            case IPolicyExpressionWithOperator withOperator:
                isPolicyOnly = false;
                policyName   = null;
                break;

            default:
                throw new Exception($"expression of type {expression.GetType()} is not supported");
            }
        }
        private string GetOperandType(IPolicyExpression policyExpression)
        {
            try
            {
                IEnumerable <Type> genericInterfaces =
                    policyExpression.GetType().GetInterfaces().Where(i => i.GenericTypeArguments.Any()).ToArray();

                // IPolicyExpression is a IOperationPolicyExpression
                if (!genericInterfaces.Any())
                {
                    var policyOpertor = policyExpression as IOperationPolicyExpression;
                    if (policyOpertor == null)
                    {
                        return(null);
                    }
                    var returnName = policyOpertor.GetPolicyOperator().ExecuteRef.Method.ReturnType.Name;
                    return(returnName);
                }
                //if (genericInterfaces //Looing for ITBSField<IEnumerable<String>>
                //        .Any(i => i.GetGenericTypeDefinition() == typeof(ITBSField<>) &&  i.GetGenericArguments()
                //            .Any(a => a.GetInterfaces()
                //                .Any(ai => ai.IsGenericType && ai.GetGenericTypeDefinition() == typeof(IEnumerable<>)))))
                //{
                //    return "String";
                //}
                var rdnType = genericInterfaces.FirstOrDefault(i => i.GetGenericTypeDefinition() == typeof(IRdn <>));
                if (rdnType != null)
                {
                    return(rdnType.GetGenericArguments().First().Name);
                }
                var args = genericInterfaces.First().GetGenericArguments();
                return(args[0].Name);
            }
            catch (Exception ex)
            {
                throw new PolicyParseException("Error getting operand type for: " + policyExpression, ex);
            }
        }
        public bool MoveNext()
        {
            if (policyOnly != null)
            {
                if (current == policyOnly)
                {
                    return(false);
                }
                current = policyOnly;
                return(true);
            }

            if (stack.Count <= 0)
            {
                return(false);
            }

            IPolicyExpression top = stack.Pop();

            while (true)
            {
                switch (top)
                {
                case IPolicyExpressionWithOperator op:
                    stack.Push(op.Right);
                    top = op.Left;
                    break;

                case IPolicyOnlyExpression policyOnly:
                    current = policyOnly;
                    return(true);

                default:
                    throw new Exception($"unsupported expression node of type {top.GetType()}");
                }
            }
        }
        private string GetOperandType(IPolicyExpression policyExpression)
        {
            try
            {
                IEnumerable<Type> genericInterfaces =
                    policyExpression.GetType().GetInterfaces().Where(i => i.GenericTypeArguments.Any()).ToArray();

                // IPolicyExpression is a IOperationPolicyExpression
                if (!genericInterfaces.Any())
                {
                    var policyOpertor = policyExpression as IOperationPolicyExpression;
                    if (policyOpertor == null)
                    {
                        return null;
                    }
                    var returnName = policyOpertor.GetPolicyOperator().ExecuteRef.Method.ReturnType.Name;
                    return returnName;
                }
                //if (genericInterfaces //Looing for ITBSField<IEnumerable<String>>
                //        .Any(i => i.GetGenericTypeDefinition() == typeof(ITBSField<>) &&  i.GetGenericArguments()
                //            .Any(a => a.GetInterfaces()
                //                .Any(ai => ai.IsGenericType && ai.GetGenericTypeDefinition() == typeof(IEnumerable<>)))))
                //{
                //    return "String";
                //}
                var rdnType = genericInterfaces.FirstOrDefault(i => i.GetGenericTypeDefinition() == typeof (IRdn<>));
                if(rdnType != null)
                {
                    return rdnType.GetGenericArguments().First().Name;
                }
                var args = genericInterfaces.First().GetGenericArguments();
                return args[0].Name;
            }
            catch (Exception ex)
            {
                throw new PolicyParseException("Error getting operand type for: " + policyExpression, ex);
            }
        }
        /**
         * Builds an aggregated {@link PolicyExpression} from a parsed list of tokens.
         * @param tokens Parsed list of tokens used to build the {@link PolicyExpression}.
         * @param level Used for keeping track of depth of operations.
         * @return A {@link PolicyExpression} built from the parsed list of tokens.
         * @throws PolicyParseException
         */
        protected IPolicyExpression BuildExpression(IEnumerator <TokenTypeAssociation> tokens, bool operandFrame)
        {
            if (!tokens.MoveNext())
            {
                return(null);
            }

            IList <IPolicyExpression> builtOperandExpressions = new List <IPolicyExpression>();

            do
            {
                TokenTypeAssociation assos = tokens.Current;
                switch (assos.GetTokenType())
                {
                case TokenType.START_LEVEL:
                {
                    IncrementLevel();
                    IPolicyExpression expression = BuildExpression(tokens);
                    if (operandFrame)
                    {
                        return(expression);
                    }

                    builtOperandExpressions.Add(expression);
                    break;
                }

                case TokenType.END_LEVEL:
                    if (GetLevel() == 0)
                    {
                        throw new PolicyGrammarException("To many \")\" tokens.  Delete this token");
                    }

                    if (builtOperandExpressions.Count == 0)
                    {
                        throw new PolicyGrammarException("Group must contain at least one expression.");
                    }

                    DecrementLevel();
                    return(builtOperandExpressions[0]);

                case TokenType.OPERATOR_BINARY_EXPRESSION:
                case TokenType.OPERATOR_UNARY_EXPRESSION:
                {
                    // regardless if this is a unary or binary expression, then next set of tokens should consist
                    // of a parameter to this operator
                    IPolicyExpression subExpression = BuildExpression(tokens, true);

                    int tokenHashCode = 0;

                    if (subExpression != null)
                    {
                        //TODO Refactor
                        if (assos.GetTokenType() == TokenType.OPERATOR_UNARY_EXPRESSION)
                        {
                            tokenHashCode = (assos.GetToken() + "_" + GetOperandType(subExpression)).GetHashCode();
                        }
                        if (assos.GetTokenType() == TokenType.OPERATOR_BINARY_EXPRESSION)
                        {
                            string leftOperandType  = GetOperandType(builtOperandExpressions.First());
                            string rightOperandType = GetOperandType(subExpression);
                            tokenHashCode = (assos.GetToken() + "_" + leftOperandType + "_" + rightOperandType).GetHashCode();
                        }
                    }
                    else     //(subExpression == null)
                    {
                        throw new PolicyGrammarException("Missing parameter.  Operator must be followed by an expression.");
                    }

                    builtOperandExpressions.Add(subExpression);



                    // get the operator for this token
                    OperatorBase operatorBase = PolicyOperator.FromToken(tokenHashCode);

                    // now add the parameters to the operator
                    if (builtOperandExpressions.Count == 1 && operatorBase is BinaryOperator)
                    {
                        throw new PolicyGrammarException("Missing parameter.  Binary operators require two parameters.");
                    }

                    IPolicyExpression operatorExpression = new OperationPolicyExpression(operatorBase, builtOperandExpressions);

                    if (operandFrame)
                    {
                        return(operatorExpression);
                    }

                    builtOperandExpressions = new List <IPolicyExpression>();
                    builtOperandExpressions.Add(operatorExpression);

                    break;
                }

                case TokenType.LITERAL_EXPRESSION:
                {
                    IPolicyExpression expression = new LiteralPolicyExpression <string>(new PolicyValue <string>(assos.GetToken()));
                    if (operandFrame)
                    {
                        return(expression);                             // exit this operand frame
                    }
                    builtOperandExpressions.Add(expression);
                    break;
                }

                case TokenType.CERTIFICATE_REFERENCE_EXPRESSION:
                {
                    IPolicyExpression expression = BuildCertificateReferenceField(assos.GetToken());

                    if (operandFrame)
                    {
                        return(expression);                             // exit this operand frame
                    }
                    builtOperandExpressions.Add(expression);
                    break;
                }
                }
            } while(tokens.MoveNext());

            if (builtOperandExpressions.Count > 1)
            {
                throw new PolicyGrammarException("Erroneous expression.");
            }

            return(builtOperandExpressions[0]);
        }
示例#24
0
 public virtual IPolicyExpression Parse(Stream stream)
 {
     m_policyExpression = Deserialize <IPolicyExpression>(stream);
     return(m_policyExpression);
 }
示例#25
0
 /// <summary>
 /// Create a new XMLLexiconPolicyParser
 /// </summary>
 public XMLLexiconPolicyParser(IPolicyExpression policyExpression)
 {
     m_policyExpression = policyExpression;
 }
示例#26
0
        public bool IsCompliant(X509Certificate2 cert, Stream policyStream)
        {
            IPolicyExpression expression = m_parser.Parse(policyStream);

            return(IsCompliant(cert, expression));
        }
示例#27
0
        protected StackMachineEntry <OperationPolicyExpression> Compile(IList <IOpCode> entries, X509Certificate2 cert, IPolicyExpression expression)
        {
            switch (expression.GetExpressionType())
            {
            //case PolicyExpressionType.LITERAL:
            //    return new StackMachineEntry(((LiteralPolicyExpression < ?  >)
            //    expression).
            //    GetPolicyValue())
            //    ;

            //case PolicyExpressionType.REFERENCE:
            //{
            //    object refExpression = GetRefExpressionType(expression);

            //    //IReferencePolicyExpression<X509Certificate2, object> refExpression = null;
            //    EvaluateReferenceExpression(cert, refExpression);

            //    return new ReferenceMachineEntry<IReferencePolicyExpression<X509Certificate2,T>>(expression);
            //}

            case PolicyExpressionType.OPERATION:
            {
                OperationPolicyExpression opExpression = (OperationPolicyExpression)expression;
                foreach (IPolicyExpression policyExpression in opExpression.GetOperands())
                {
                    if (policyExpression is IReferencePolicyExpression <X509Certificate2, String> )
                    {
                        var refExpression = policyExpression as IReferencePolicyExpression <X509Certificate2, String>;
                        EvaluateReferenceExpression(cert, refExpression);
                        entries.Add(Compile(refExpression));
                    }
                    else if (policyExpression is IReferencePolicyExpression <X509Certificate2, Int32> )
                    {
                        var refExpression = policyExpression as IReferencePolicyExpression <X509Certificate2, Int32>;
                        EvaluateReferenceExpression(cert, refExpression);
                        entries.Add(Compile(refExpression));
                    }
                    else if (policyExpression is IReferencePolicyExpression <X509Certificate2, Int64> )
                    {
                        var refExpression = policyExpression as IReferencePolicyExpression <X509Certificate2, Int64>;
                        EvaluateReferenceExpression(cert, refExpression);
                        entries.Add(Compile(refExpression));
                    }
                    else if (policyExpression is IReferencePolicyExpression <X509Certificate2, IList <String> > )
                    {
                        var refExpression = policyExpression as IReferencePolicyExpression <X509Certificate2, IList <String> >;
                        EvaluateReferenceExpression(cert, refExpression);
                        entries.Add(Compile(refExpression));
                    }
                    else if (policyExpression is IReferencePolicyExpression <X509Certificate2, Boolean> )
                    {
                        var refExpression = policyExpression as IReferencePolicyExpression <X509Certificate2, Boolean>;
                        EvaluateReferenceExpression(cert, refExpression);
                        entries.Add(Compile(refExpression));
                    }
                    else if (policyExpression is ILiteralPolicyExpression <String> )
                    {
                        entries.Add(Compile(policyExpression as ILiteralPolicyExpression <String>));
                    }
                    else
                    {
                        entries.Add(Compile(entries, cert, policyExpression));
                    }
                }
                return(new StackMachineEntry <OperationPolicyExpression>(opExpression.GetPolicyOperator()));
            }

            default:
                return(null);
            }
        }