コード例 #1
0
        public void TypeDefValidator_Should_Validate_Method_Using_Denied_Nested_Array_Element()
        {
            const string source = @"
using System; 
using System.Collections.Generic;

public class Test 
{
    public void A()
    { 
        var b = new [] { new [] { ""a"" } };
    }
}";

            var typeDefinition = CompileToTypeDef(source);

            var policy = new WhitelistPolicy()
                         .Namespace("System", AccessPolicy.Denied, t =>
                                    t.Type(nameof(Boolean), AccessPolicy.Allowed)
                                    .Type("Object", AccessPolicy.Allowed)
                                    .Type("Void", AccessPolicy.Allowed)
                                    .Type("String", AccessPolicy.Denied))
                         .Namespace("System.Collections.Generic", AccessPolicy.Allowed);

            var validationPolicy = new ValidationPolicy()
                                   .WhitelistValidator(policy);

            var validator = new TypePolicyValidator(validationPolicy);

            var result = validator.Validate(typeDefinition).ToList();

            Assert.True(result.All(r => r is WhitelistValidator.DeniedTypeValidationResult));
        }
コード例 #2
0
        public void TypeDefValidator_Should_Validate_Method_Using_Denied_New_Type()
        {
            const string source = @"
using System; 
public class Test 
{
    public void A()
    { 
        var b = new DateTime();
    }
}";

            var typeDefinition = CompileToTypeDef(source);

            var policy = new WhitelistPolicy()
                         .Namespace("System", AccessPolicy.Denied, t =>
                                    t.Type("Object", AccessPolicy.Allowed)
                                    .Type("Void", AccessPolicy.Allowed)
                                    .Type("String", AccessPolicy.Denied));

            var validationPolicy = new ValidationPolicy()
                                   .WhitelistValidator(policy);

            var validator = new TypePolicyValidator(validationPolicy);

            var result = validator.Validate(typeDefinition).ToList();

            Assert.Single(result);
        }
コード例 #3
0
        public void TypeDefValidator_Should_Allow_References_To_Own_Methods()
        {
            const string source = @"
using System; 

public class Test 
{
    public void A() {
    }

    public void B() {
        A();
    }
}";

            var typeDefinition = CompileToTypeDef(source);

            var policy = new WhitelistPolicy()
                         .Namespace("System", AccessPolicy.Denied, t =>
                                    t.Type("Object", AccessPolicy.Allowed)
                                    .Type("Void", AccessPolicy.Allowed)
                                    .Type("String", AccessPolicy.Denied));

            var validationPolicy = new ValidationPolicy()
                                   .WhitelistValidator(policy);

            var validator = new TypePolicyValidator(validationPolicy);

            var result = validator.Validate(typeDefinition).ToList();

            Assert.Empty(result);
        }
コード例 #4
0
        public void TypePolicyValidator_Should_Validate_Own_Methods()
        {
            const string source = @"
using System; 

public class Test 
{
    static extern uint A();

    public void B() {
        var dt = DateTime.Now;
    }
}";

            var typeDefinition = CompileToTypeDef(source);

            var policy = new WhitelistPolicy()
                         .Namespace("System", AccessPolicy.Denied, t =>
                                    t.Type("Object", AccessPolicy.Allowed)
                                    .Type("Void", AccessPolicy.Allowed)
                                    .Type("String", AccessPolicy.Denied));

            var validationPolicy = new ValidationPolicy()
                                   .WhitelistValidator(policy);

            var validator = new TypePolicyValidator(validationPolicy);

            var result = validator.Validate(typeDefinition).ToList();

            Assert.True(result.Any());
            Assert.True(result.All(r => r is WhitelistValidator.WhitelistValidationResult));
        }
コード例 #5
0
        public bool isValidCertificate(ECertificate certificate)
        {
            try
            {
                ValidationPolicy validationPolicy = CertValidationPolicyManager.getInstance().getValidationPolicy();
                ValidationSystem vs = CertificateValidation.createValidationSystem(validationPolicy);
                vs.setBaseValidationTime(DateTime.UtcNow);
                CertificateStatusInfo csi = CertificateValidation.validateCertificate(vs, certificate);
                CertificateStatus     certificateStatus = csi.getCertificateStatus();
                string statusText = certificateStatus.textAl();
                //System.Console.WriteLine("Doğrulama Sonucu");
                //System.Console.WriteLine(statusText);
                //System.Console.WriteLine(csi.checkResultsToString());
                //System.Console.WriteLine(csi.getDetailedMessage());
                Program.HataMesaji = "\n\r" + csi.checkResultsToString() + "\n\r" + csi.getDetailedMessage();

                return(certificateStatus == CertificateStatus.VALID);
            }
            catch (Exception exc)
            {
                // System.Console.WriteLine(exc.Message);
                Program.HataMesaji = exc.Message;
                return(false);
            }
        }
コード例 #6
0
ファイル: ESignUtil.cs プロジェクト: poolsoft/eimza-1
        public byte[] signWithPfxFile(string pfxFile, string pinCode, byte[] tobeSignBytes)
        {
            BaseSignedData bs = new BaseSignedData();

            tr.gov.tubitak.uekae.esya.api.cmssignature.ISignable content = new SignableByteArray(tobeSignBytes);
            bs.addContent(content);

            //Since SigningTime attribute is optional,add it to optional attributes list
            List <IAttribute> optionalAttributes = new List <IAttribute>();

            optionalAttributes.Add(new SigningTimeAttr(DateTime.UtcNow));

            Dictionary <string, object> params_ = new Dictionary <string, object>();
            ValidationPolicy            policy  = getPolicy();

            //necessary for certificate validation.By default,certificate validation is done
            params_[EParameters.P_CERT_VALIDATION_POLICY] = policy;

            //if the user does not want certificate validation,he can add
            //P_VALIDATE_CERTIFICATE_BEFORE_SIGNING parameter with its value set to false
            params_[EParameters.P_VALIDATE_CERTIFICATE_BEFORE_SIGNING] = false;
            PfxSigner    signer = new PfxSigner(SignatureAlg.RSA_SHA256.getName(), pfxFile, pinCode);
            ECertificate signatureCertificate = signer.getSignersCertificate();

            bs.addSigner(ESignatureType.TYPE_BES, signatureCertificate, signer, optionalAttributes, params_);
            return(bs.getEncoded());
        }
コード例 #7
0
        public void TypeDefValidator_Should_Validate_Method_Using_Denied_Field()
        {
            const string source = @"
using System; 

public class Test 
{
    public void A()
    { 
        var b = BitConverter.IsLittleEndian;
    }
}";

            var typeDefinition = CompileToTypeDef(source);

            var policy = new WhitelistPolicy()
                         .Namespace("System", AccessPolicy.Denied, t =>
                                    t.Type(nameof(Boolean), AccessPolicy.Allowed)
                                    .Type(nameof(BitConverter), AccessPolicy.Allowed,
                                          m => m.Member(nameof(BitConverter.IsLittleEndian), AccessPolicy.Denied))
                                    .Type("Object", AccessPolicy.Allowed)
                                    .Type("Void", AccessPolicy.Allowed)
                                    .Type("String", AccessPolicy.Denied));

            var validationPolicy = new ValidationPolicy()
                                   .WhitelistValidator(policy);

            var validator = new TypePolicyValidator(validationPolicy);

            var result = validator.Validate(typeDefinition).ToList();

            Assert.Single(result);
        }
コード例 #8
0
        public sealed override async Task ExecuteAsync(TRequestArgument argument, CancellationToken cancellationToken, bool captureContext = false)
        {
            IReadOnlyList <IValidatorResult> result = await ValidationPolicy.ValidateArgumentAsync(argument, cancellationToken, captureContext).ConfigureAwait(captureContext);

            if (result.Count == 0)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }

                await base.ExecuteAsync(argument, cancellationToken, captureContext);

                return;
            }

            foreach (IValidatorResult validationResult in result)
            {
                foreach (IValidatorResultMessage message in validationResult.Messages)
                {
                    LogService.Error?.Write($"{message.Property} -> {message.Message}");
                }
            }

            ForceStatusToFinish();
        }
コード例 #9
0
 private void init()
 {
     if (validationPolicy == null)
     {
         string currentDirectory = Directory.GetCurrentDirectory();
         string policyFilePath   = currentDirectory + "\\certval-policy.xml";
         validationPolicy = PolicyReader.readValidationPolicy(policyFilePath);
     }
 }
コード例 #10
0
        /// <summary>
        /// Create a ValidatorFixture to use the given policy. Set the default
        /// face_.processInterest_ to use the cache_ to respond to expressInterest. To
        /// change this behavior, you can set face_.processInterest_ to your callback,
        /// or to null to always time out.
        /// </summary>
        ///
        /// <param name="policy">The ValidationPolicy used by validator_.</param>
        public ValidatorFixture(ValidationPolicy policy)
        {
            this.face_  = new ValidatorFixture.TestFace();
            this.cache_ = new CertificateCacheV2(
                100 * 24 * 3600 * 1000.0d);
            validator_ = new Validator(policy, new CertificateFetcherFromNetwork(
                                           face_));
            policy_ = policy;

            face_.processInterest_ = new ValidatorFixture.Anonymous_C0(this);
        }
コード例 #11
0
        /**
         * Generic validate function. Validates known types of xml signature.
         * @param fileName name of the signature file to be validated
         */
        public static void validate(String fileName)
        {
            Context context = new Context(Conn.ROOT_DIR + "efatura\\config\\");

            // add external resolver to resolve policies
            context.addExternalResolver(getPolicyResolver());

            XMLSignature signature = XMLSignature.parse(
                new FileDocument(new FileInfo(fileName)),
                context);

            ECertificate     cert = signature.SigningCertificate;
            ValidationSystem vs;

            if (cert.isMaliMuhurCertificate())
            {
                ValidationPolicy policy     = new ValidationPolicy();
                String           policyPath = Conn.ROOT_DIR + "efatura\\config\\certval-policy-malimuhur.xml";
                policy = PolicyReader.readValidationPolicy(policyPath);
                vs     = CertificateValidation.createValidationSystem(policy);
                context.setCertValidationSystem(vs);
            }
            else
            {
                ValidationPolicy policy     = new ValidationPolicy();
                String           policyPath = Conn.ROOT_DIR + "efatura\\config\\certval-policy.xml";
                policy = PolicyReader.readValidationPolicy(policyPath);
                vs     = CertificateValidation.createValidationSystem(policy);
                context.setCertValidationSystem(vs);
            }

            // no params, use the certificate in key info
            ValidationResult result = signature.verify();
            String           sonuc  = result.toXml();

            Console.WriteLine(result.toXml());
            // Assert.True(result.Type == ValidationResultType.VALID,"Cant verify " + fileName);

            UnsignedSignatureProperties usp = signature.QualifyingProperties.UnsignedSignatureProperties;

            if (usp != null)
            {
                IList <XMLSignature> counterSignatures = usp.AllCounterSignatures;
                foreach (XMLSignature counterSignature in counterSignatures)
                {
                    ValidationResult counterResult = signature.verify();

                    Console.WriteLine(counterResult.toXml());

                    //Assert.True(counterResult.Type == ValidationResultType.VALID,
                    //    "Cant verify counter signature" + fileName + " : "+counterSignature.Id);
                }
            }
        }
コード例 #12
0
        internal bool Validate(ValidationPolicy policy)
        {
            bool valid = false;

            // Retrieve the signing key having the given digest and originating
            // from the given authority. Retrieval may occur from another authority
            // than the one owning the signing key.
            if (!valid && (ValidationPolicy.AllSignaturesMustMatch == policy))
            {
                throw new TorSecurityException();
            }
            return(valid);
        }
コード例 #13
0
        private async Task <bool> RunValidCheckOnName(object target, CommerceContext commerceContext)
        {
            ValidationPolicy     validationPolicy     = new ValidationPolicy();
            List <Model>         models               = validationPolicy.Models;
            ValidationAttributes validationAttributes = new ValidationAttributes();

            validationAttributes.Name                    = "Name";
            validationAttributes.MaxLength               = 50;
            validationAttributes.RegexValidator          = "^[\\w\\s]*$";
            validationAttributes.RegexValidatorErrorCode = "AlphanumericOnly_NameValidationError";
            models.Add(validationAttributes);

            return(await validationPolicy.ValidateModels(target, commerceContext.PipelineContext).ConfigureAwait(false));
        }
コード例 #14
0
        public void adds_validation_action_filter_for_lofi_endpoints()
        {
            var call = ActionCall.For <SampleInputModel>(x => x.Test(null));

            var chain = new BehaviorChain();

            chain.AddToEnd(call);

            ValidationPolicy.ApplyValidation(call, new ValidationSettings());

            var nodes = chain.ToArray();
            var node  = nodes[0].As <IHaveValidation>();

            node.As <ActionFilter>().HandlerType.ShouldBe(typeof(ValidationActionFilter <string>));
        }
コード例 #15
0
        public void adds_ajax_validation_action_filter_for_ajax_endpoints()
        {
            var call = ActionCall.For <SampleAjaxModel>(x => x.post_model(null));

            var chain = new BehaviorChain();

            chain.AddToEnd(call);

            ValidationPolicy.ApplyValidation(call, new ValidationSettings());

            var nodes = chain.ToArray();
            var node  = nodes[0].As <IHaveValidation>();

            node.ShouldBeOfType <AjaxValidationNode>();
        }
コード例 #16
0
        private void SetPolicy()
        {
            using (var File = new FileStream(_config.PolicyXmlPath, FileMode.Open))
            {
                this._policy = PolicyReader.readValidationPolicy(File);
            }


            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters["storepath"] = _config.SertifikaDeposuPath;
            _policy.bulmaPolitikasiAl().addTrustedCertificateFinder("tr.gov.tubitak.uekae.esya.api.certificate.validation.find.certificate.trusted.TrustedCertificateFinderFromXml",
                                                                    parameters);
            _policy.bulmaPolitikasiAl().addCertificateFinder("tr.gov.tubitak.uekae.esya.api.certificate.validation.find.certificate.CertificateFinderFromXml", parameters);
        }
コード例 #17
0
        public override async Task <Party> RunAsync(Party arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires <Party>(arg).IsNotNull(base.Name + ": The argument cannot be null.");
            var validationPolicy = ValidationPolicy.GetValidationPolicy(context.CommerceContext, typeof(Party));

            //Update CountryCode by Country
            await UpdateCountryAndCountryCode(arg, context);

            var result = await validationPolicy.ValidateModels(arg, context);

            if (result)
            {
                return(arg);
            }

            return(null);
        }
コード例 #18
0
        public HierarchicalValidatorFixture(ValidationPolicy policy) : base(policy)
        {
            identity_    = addIdentity(new Name("/Security/V2/ValidatorFixture"));
            subIdentity_ = addSubCertificate(new Name(
                                                 "/Security/V2/ValidatorFixture/Sub1"), identity_);
            subSelfSignedIdentity_ = addIdentity(new Name(
                                                     "/Security/V2/ValidatorFixture/Sub1/Sub2"));
            otherIdentity_ = addIdentity(new Name("/Security/V2/OtherIdentity"));

            validator_.loadAnchor("", new CertificateV2(identity_.getDefaultKey()
                                                        .getDefaultCertificate()));

            cache_.insert(identity_.getDefaultKey().getDefaultCertificate());
            cache_.insert(subIdentity_.getDefaultKey().getDefaultCertificate());
            cache_.insert(subSelfSignedIdentity_.getDefaultKey()
                          .getDefaultCertificate());
            cache_.insert(otherIdentity_.getDefaultKey().getDefaultCertificate());
        }
コード例 #19
0
ファイル: ESignUtil.cs プロジェクト: poolsoft/eimza-1
 ValidationPolicy getPolicy()
 {
     if (policy == null)
     {
         try
         {
             policy = PolicyReader.readValidationPolicy(new FileStream(policyFile, FileMode.Open));
             //For UEKAE Test Environment, we add our test roots.
             //Dictionary<String, Object> parameters = new Dictionary<String, Object>();
             //parameters["dizin"] = DIRECTORY + @"\sertifika deposu\test kok sertifika\";
             //POLICY.bulmaPolitikasiAl().addTrustedCertificateFinder("tr.gov.tubitak.uekae.esya.api.certificate.validation.find.certificate.trusted.TrustedCertificateFinderFromFileSystem",
             //        parameters);
         }
         catch (FileNotFoundException e)
         {
             throw new SystemException("Policy file could not be found", e);
         }
     }
     return(policy);
 }
コード例 #20
0
        public void no_modifications_from_the_settings()
        {
            var call = ActionCall.For <SampleInputModel>(x => x.Test(null));

            var chain = new BehaviorChain();

            chain.AddToEnd(call);

            var settings = new ValidationSettings();

            settings.ForInputType <int>(x =>
            {
                x.Clear();
                x.RegisterStrategy(RenderingStrategies.Inline);
            });

            ValidationPolicy.ApplyValidation(call, settings);

            chain.ValidationNode().ShouldHaveTheSameElementsAs(RenderingStrategies.Summary, RenderingStrategies.Highlight);
        }
コード例 #21
0
        /**
         * Validates given certificate
         */
        public static Boolean validateCertificate(ECertificate certificate)
        {
            try
            {
                ValidationSystem vs;
                // generate policy which going to be used in validation
                if (certificate.isMaliMuhurCertificate())
                {
                    ValidationPolicy policy     = new ValidationPolicy();
                    String           policyPath = Conn.ROOT_DIR + "efatura\\config\\certval-policy-malimuhur.xml";
                    policy = PolicyReader.readValidationPolicy(policyPath);
                    vs     = CertificateValidation.createValidationSystem(policy);
                }
                else
                {
                    ValidationPolicy policy     = new ValidationPolicy();
                    String           policyPath = Conn.ROOT_DIR + "efatura\\config\\certval-policy.xml";
                    policy = PolicyReader.readValidationPolicy(policyPath);
                    vs     = CertificateValidation.createValidationSystem(policy);
                }
                vs.setBaseValidationTime(DateTime.UtcNow);

                // validate certificate
                CertificateStatusInfo csi = CertificateValidation.validateCertificate(vs, certificate);

                // return true if certificate is valid, false otherwise
                if (csi.getCertificateStatus() != CertificateStatus.VALID)
                {
                    return(false);
                }
                else if (csi.getCertificateStatus() == CertificateStatus.VALID)
                {
                    return(true);
                }
            }
            catch (Exception e)
            {
                throw new Exception("An error occured while validating certificate", e);
            }
            return(false);
        }
コード例 #22
0
        public void TypeDefValidator_Should_Validate_Method_Allowed_Return_Type()
        {
            const string source = @"public class Test {public string A(){return ""a"";}}";

            var typeDefinition = CompileToTypeDef(source);

            var policy = new WhitelistPolicy()
                         .Namespace("System", AccessPolicy.Denied, t =>
                                    t.Type("Object", AccessPolicy.Allowed)
                                    .Type("Void", AccessPolicy.Allowed)
                                    .Type("String", AccessPolicy.Allowed));

            var validationPolicy = new ValidationPolicy()
                                   .WhitelistValidator(policy);

            var validator = new TypePolicyValidator(validationPolicy);

            var result = validator.Validate(typeDefinition).ToList();

            Assert.Empty(result);
        }
コード例 #23
0
        protected override void beforeEach()
        {
            theGraph = BehaviorGraph.BuildFrom(x => x.Actions.IncludeType <ValidationSummaryTargetEndpoint>());
            Services.Inject <IChainResolver>(new ChainResolutionCache(theGraph));


            theRequest = new FormRequest(new ChainSearch {
                Type = typeof(ValidationSummaryTarget)
            },
                                         new ValidationSummaryTarget());
            theRequest.Attach(new StructureMapServiceLocator(Services.Container));

            ValidationPolicy.ApplyValidation(theRequest.Chain.FirstCall(), new ValidationSettings());
            theRequest.Chain.ValidationNode().Clear();
            theRequest.Chain.ValidationNode().RegisterStrategy(RenderingStrategies.Summary);

            var theForm = new FormTag("test");

            theForm.Append(new HtmlTag("input").Attr("type", "text").Attr("name", "Name"));

            theRequest.ReplaceTag(theForm);

            MockFor <IPartialInvoker>().Stub(x => x.Invoke <ValidationSummary>()).Return(theValidationSummary.ToCompletionTask());
        }
コード例 #24
0
        protected virtual async Task PopulateDetails(EntityView view, Customer customer, bool isAddAction, bool isEditAction, CommercePipelineExecutionContext context)
        {
            if (view == null)
            {
                return;
            }
            ValidationPolicy         validationPolicy        = ValidationPolicy.GetValidationPolicy(context.CommerceContext, typeof(Customer));
            ValidationPolicy         detailsValidationPolicy = ValidationPolicy.GetValidationPolicy(context.CommerceContext, typeof(CustomerDetailsComponent));
            CustomerPropertiesPolicy propertiesPolicy        = context.GetPolicy <CustomerPropertiesPolicy>();
            EntityView details = (EntityView)null;

            if (customer != null && customer.HasComponent <CustomerDetailsComponent>())
            {
                details = customer.GetComponent <CustomerDetailsComponent>().View.ChildViews.FirstOrDefault <Model>((Func <Model, bool>)(v => v.Name.Equals("Details", StringComparison.OrdinalIgnoreCase))) as EntityView;
            }
            List <string> languages = new List <string>();
            Shop          shop      = context.CommerceContext.GetObjects <Shop>().FirstOrDefault <Shop>();

            if (shop != null && shop.Languages.Any <string>())
            {
                languages = shop.Languages;
            }
            foreach (string detailsProperty in propertiesPolicy?.DetailsProperties)
            {
                string propertyName = detailsProperty;
                if (!isAddAction || !propertyName.Equals(propertiesPolicy?.AccountNumber, StringComparison.OrdinalIgnoreCase))
                {
                    ValidationAttributes validationAttributes = validationPolicy.Models.FirstOrDefault <Model>((Func <Model, bool>)(m => m.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase))) as ValidationAttributes;
                    if (propertyName.Equals(propertiesPolicy?.AccountStatus, StringComparison.OrdinalIgnoreCase))
                    {
                        KnownCustomersStatusesPolicy statusesPolicy = context.GetPolicy <KnownCustomersStatusesPolicy>();
                        List <Selection>             statuses       = new List <Selection>();
                        string currentStatus = customer?.AccountStatus ?? string.Empty;
                        if (isAddAction | isEditAction)
                        {
                            PropertyInfo[] propertyInfoArray = typeof(KnownCustomersStatusesPolicy).GetProperties();
                            for (int index = 0; index < propertyInfoArray.Length; ++index)
                            {
                                PropertyInfo propertyInfo = propertyInfoArray[index];
                                if (!propertyInfo.Name.Equals("PolicyId", StringComparison.OrdinalIgnoreCase) && !propertyInfo.Name.Equals("Models", StringComparison.OrdinalIgnoreCase))
                                {
                                    string status = propertyInfo.GetValue((object)statusesPolicy, (object[])null) as string;
                                    if (!string.IsNullOrEmpty(status))
                                    {
                                        LocalizedTerm localizedTerm = await this._getLocalizedCustomerStatusPipeline.Run(new LocalizedCustomerStatusArgument(status, (object[])null), context);

                                        List <Selection> selectionList = statuses;
                                        Selection        selection     = new Selection();
                                        selection.DisplayName = localizedTerm?.Value;
                                        selection.Name        = status;
                                        selectionList.Add(selection);
                                        status = (string)null;
                                    }
                                }
                            }
                            propertyInfoArray = (PropertyInfo[])null;
                        }
                        else if (!string.IsNullOrEmpty(currentStatus))
                        {
                            LocalizedTerm localizedTerm = await this._getLocalizedCustomerStatusPipeline.Run(new LocalizedCustomerStatusArgument(currentStatus, (object[])null), context);

                            if (!string.IsNullOrEmpty(localizedTerm?.Value))
                            {
                                currentStatus = localizedTerm?.Value;
                            }
                        }
                        List <ViewProperty> properties   = view.Properties;
                        ViewProperty        viewProperty = new ViewProperty();
                        viewProperty.Name       = propertiesPolicy?.AccountStatus;
                        viewProperty.RawValue   = (object)currentStatus;
                        viewProperty.IsReadOnly = !isAddAction && !isEditAction;
                        ValidationAttributes validationAttributes1 = validationAttributes;
                        viewProperty.IsRequired = validationAttributes1 != null && validationAttributes1.MinLength > 0;
                        viewProperty.Policies   = (IList <Policy>) new List <Policy>()
                        {
                            (Policy) new AvailableSelectionsPolicy()
                            {
                                List = statuses
                            }
                        };
                        properties.Add(viewProperty);
                    }
                    else if (propertyName.Equals(propertiesPolicy?.LoginName, StringComparison.OrdinalIgnoreCase))
                    {
                        List <ViewProperty> properties   = view.Properties;
                        ViewProperty        viewProperty = new ViewProperty();
                        viewProperty.Name       = propertiesPolicy?.LoginName;
                        viewProperty.RawValue   = (object)(customer?.LoginName ?? string.Empty);
                        viewProperty.IsReadOnly = !isAddAction;
                        viewProperty.IsRequired = true;
                        List <Policy> policyList;
                        if (isAddAction)
                        {
                            ValidationAttributes validationAttributes1 = validationAttributes;
                            if ((validationAttributes1 != null ? (validationAttributes1.MaxLength > 0 ? 1 : 0) : 0) != 0)
                            {
                                policyList = new List <Policy>()
                                {
                                    (Policy) new MaxLengthPolicy()
                                    {
                                        MaxLengthAllow = validationAttributes.MaxLength
                                    }
                                };
                                goto label_28;
                            }
                        }
                        policyList = new List <Policy>();
label_28:
                        viewProperty.Policies = (IList <Policy>)policyList;
                        properties.Add(viewProperty);
                    }
                    else if (propertyName.Equals(propertiesPolicy?.Domain, StringComparison.OrdinalIgnoreCase))
                    {
                        List <ViewProperty> properties   = view.Properties;
                        ViewProperty        viewProperty = new ViewProperty();
                        viewProperty.Name       = propertiesPolicy?.Domain;
                        viewProperty.RawValue   = (object)(customer?.Domain ?? string.Empty);
                        viewProperty.IsReadOnly = !isAddAction;
                        viewProperty.IsRequired = true;
                        List <Policy> policyList;
                        if (!isAddAction)
                        {
                            policyList = new List <Policy>();
                        }
                        else
                        {
                            policyList = new List <Policy>();
                            AvailableSelectionsPolicy selectionsPolicy = new AvailableSelectionsPolicy();
                            List <Selection>          selectionList;
                            if (propertiesPolicy?.Domains == null || !propertiesPolicy.Domains.Any <string>() || !(isAddAction | isEditAction))
                            {
                                selectionList = new List <Selection>();
                            }
                            else
                            {
                                CustomerPropertiesPolicy propertiesPolicy1 = propertiesPolicy;
                                selectionList = propertiesPolicy1 != null?propertiesPolicy1.Domains.Select <string, Selection>((Func <string, Selection>)(s =>
                                {
                                    return(new Selection()
                                    {
                                        DisplayName = s,
                                        Name = s
                                    });
                                })).ToList <Selection>() : (List <Selection>)null;
                            }
                            selectionsPolicy.List = selectionList;
                            policyList.Add((Policy)selectionsPolicy);
                        }
                        viewProperty.Policies = (IList <Policy>)policyList;
                        properties.Add(viewProperty);
                    }
                    else if (propertyName.Equals(propertiesPolicy?.UserName, StringComparison.OrdinalIgnoreCase))
                    {
                        if (!isAddAction)
                        {
                            List <ViewProperty> properties   = view.Properties;
                            ViewProperty        viewProperty = new ViewProperty();
                            viewProperty.Name       = propertiesPolicy?.UserName;
                            viewProperty.RawValue   = (object)(customer?.UserName ?? string.Empty);
                            viewProperty.IsReadOnly = !isAddAction;
                            viewProperty.IsRequired = true;
                            List <Policy> policyList;
                            if (isAddAction)
                            {
                                ValidationAttributes validationAttributes1 = validationAttributes;
                                if ((validationAttributes1 != null ? (validationAttributes1.MaxLength > 0 ? 1 : 0) : 0) != 0)
                                {
                                    policyList = new List <Policy>()
                                    {
                                        (Policy) new MaxLengthPolicy()
                                        {
                                            MaxLengthAllow = validationAttributes.MaxLength
                                        }
                                    };
                                    goto label_43;
                                }
                            }
                            policyList = new List <Policy>();
label_43:
                            viewProperty.Policies = (IList <Policy>)policyList;
                            properties.Add(viewProperty);
                        }
                    }
                    else if (propertyName.Equals(propertiesPolicy?.Language, StringComparison.OrdinalIgnoreCase))
                    {
                        object obj = details?.GetPropertyValue(propertiesPolicy?.Language) ?? (((languages == null ? 0 : (languages.Any <string>() ? 1 : 0)) & (isAddAction ? 1 : 0)) != 0 ? (object)languages.FirstOrDefault <string>() : (object)string.Empty);
                        List <ViewProperty> properties   = view.Properties;
                        ViewProperty        viewProperty = new ViewProperty();
                        viewProperty.Name       = propertiesPolicy?.Language;
                        viewProperty.RawValue   = obj ?? (object)string.Empty;
                        viewProperty.IsReadOnly = !isAddAction && !isEditAction;
                        ValidationAttributes validationAttributes1 = validationAttributes;
                        viewProperty.IsRequired = validationAttributes1 != null && validationAttributes1.MinLength > 0;
                        viewProperty.Policies   = (IList <Policy>) new List <Policy>()
                        {
                            (Policy) new AvailableSelectionsPolicy()
                            {
                                List = (languages == null || !languages.Any <string>() || !(isAddAction | isEditAction) ? new List <Selection>() : languages.Select <string, Selection>((Func <string, Selection>)(s =>
                                {
                                    return(new Selection()
                                    {
                                        DisplayName = s,
                                        Name = s
                                    });
                                })).ToList <Selection>())
                            }
                        };
                        properties.Add(viewProperty);
                    }
                    else if (propertyName.Equals("IsCompany", StringComparison.OrdinalIgnoreCase))
                    {
                        ViewProperty viewProperty = _registrationHelper.SetCustomViewProperty(details, propertyName, !isAddAction, false.GetType(), true);
                        if (viewProperty != null)
                        {
                            view.Properties.Add(viewProperty);
                        }
                    }
                    else if (propertyName.Equals("ConsentRegulation", StringComparison.OrdinalIgnoreCase))
                    {
                        ViewProperty viewProperty = _registrationHelper.SetCustomViewProperty(details, propertyName, false, false.GetType(), true);
                        if (viewProperty != null)
                        {
                            view.Properties.Add(viewProperty);
                        }
                    }
                    else if (propertyName.Equals("ConsentProcessingContactData", StringComparison.OrdinalIgnoreCase))
                    {
                        ViewProperty viewProperty = _registrationHelper.SetCustomViewProperty(details, propertyName, false, false.GetType(), true);
                        if (viewProperty != null)
                        {
                            view.Properties.Add(viewProperty);
                        }
                    }
                    else if (propertyName.Equals("CanPurchase", StringComparison.OrdinalIgnoreCase))
                    {
                        ViewProperty viewProperty = _registrationHelper.SetCustomViewProperty(details, propertyName, false, false.GetType(), true);
                        if (viewProperty != null)
                        {
                            view.Properties.Add(viewProperty);
                        }
                    }
                    else if (propertyName.Equals("CanCreateOrders", StringComparison.OrdinalIgnoreCase))
                    {
                        ViewProperty viewProperty = _registrationHelper.SetCustomViewProperty(details, propertyName, false, false.GetType(), true);
                        if (viewProperty != null)
                        {
                            view.Properties.Add(viewProperty);
                        }
                    }
                    else if (propertyName.Equals("CanSeeDiscountPrices", StringComparison.OrdinalIgnoreCase))
                    {
                        ViewProperty viewProperty = _registrationHelper.SetCustomViewProperty(details, propertyName, false, false.GetType(), true);
                        if (viewProperty != null)
                        {
                            view.Properties.Add(viewProperty);
                        }
                    }
                    else
                    {
                        PropertyInfo property = typeof(Customer).GetProperty(propertyName);
                        if (property != (PropertyInfo)null)
                        {
                            List <ViewProperty> properties   = view.Properties;
                            ViewProperty        viewProperty = new ViewProperty();
                            viewProperty.Name       = propertyName;
                            viewProperty.RawValue   = customer == null ? (object)string.Empty : property.GetValue((object)customer, (object[])null);
                            viewProperty.IsReadOnly = !isAddAction && !isEditAction || propertyName.Equals(propertiesPolicy?.AccountNumber, StringComparison.OrdinalIgnoreCase);
                            ValidationAttributes validationAttributes1 = validationAttributes;
                            viewProperty.IsRequired = validationAttributes1 != null && validationAttributes1.MinLength > 0;
                            List <Policy> policyList;
                            if (isAddAction | isEditAction)
                            {
                                ValidationAttributes validationAttributes2 = validationAttributes;
                                if ((validationAttributes2 != null ? (validationAttributes2.MaxLength > 0 ? 1 : 0) : 0) != 0)
                                {
                                    policyList = new List <Policy>()
                                    {
                                        (Policy) new MaxLengthPolicy()
                                        {
                                            MaxLengthAllow = validationAttributes.MaxLength
                                        }
                                    };
                                    goto label_51;
                                }
                            }
                            policyList = new List <Policy>();
label_51:
                            viewProperty.Policies = (IList <Policy>)policyList;
                            properties.Add(viewProperty);
                        }
                        else
                        {
                            object propertyValue = details?.GetPropertyValue(propertyName);
                            ValidationAttributes validationAttributes1 = detailsValidationPolicy.Models.FirstOrDefault <Model>((Func <Model, bool>)(m => m.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase))) as ValidationAttributes;
                            List <ViewProperty>  properties            = view.Properties;
                            ViewProperty         viewProperty          = new ViewProperty();
                            viewProperty.Name       = propertyName;
                            viewProperty.RawValue   = propertyValue ?? (object)string.Empty;
                            viewProperty.IsReadOnly = !isAddAction && !isEditAction;
                            viewProperty.IsRequired = validationAttributes1 != null && validationAttributes1.MinLength > 0;
                            List <Policy> policyList;
                            if (!(isAddAction | isEditAction) || validationAttributes1 == null || validationAttributes1.MaxLength <= 0)
                            {
                                policyList = new List <Policy>();
                            }
                            else
                            {
                                policyList = new List <Policy>()
                                {
                                    (Policy) new MaxLengthPolicy()
                                    {
                                        MaxLengthAllow = validationAttributes1.MaxLength
                                    }
                                }
                            };
                            viewProperty.Policies = (IList <Policy>)policyList;
                            properties.Add(viewProperty);
                            validationAttributes = (ValidationAttributes)null;
                        }
                    }
                }
            }
            List <string> stringList1 = new List <string>();

            if (customer?.Tags != null && customer.Tags.Any <Tag>())
            {
                List <string>        stringList2 = stringList1;
                Customer             customer1   = customer;
                IEnumerable <string> collection  = (customer1 != null ? customer1.Tags.Where <Tag>((Func <Tag, bool>)(t => !t.Excluded)) : (IEnumerable <Tag>)null).Select <Tag, string>((Func <Tag, string>)(tag => tag.Name));
                stringList2.AddRange(collection);
            }
            if (isAddAction)
            {
                return;
            }
            List <ViewProperty> properties1   = view.Properties;
            ViewProperty        viewProperty1 = new ViewProperty();

            viewProperty1.Name         = "IncludedTags";
            viewProperty1.RawValue     = (object)stringList1.ToArray();
            viewProperty1.IsReadOnly   = !isAddAction && !isEditAction;
            viewProperty1.IsRequired   = false;
            viewProperty1.Policies     = (IList <Policy>) new List <Policy>();
            viewProperty1.UiType       = isEditAction ? "Tags" : "List";
            viewProperty1.OriginalType = "List";
            properties1.Add(viewProperty1);
        }
    }
コード例 #25
0
 public void reset()
 {
     validationPolicy = null;
 }
コード例 #26
0
        public static bool createEnvelopedBes(string pinNo, string signXML, String outXML, bool bInTest)
        {
            bool res = false;

            cardPinNo = pinNo;
            TestEnvelopedSignatureInitialize();
            try
            {
                // here is our custom envelope xml
                //  XmlDocument envelopeDoc = newEnvelope("edefter.xml");


                XmlDocument envelopeDoc = Conn.newEnvelope(signXML);
                XmlElement  exts        = (XmlElement)envelopeDoc.GetElementsByTagName("ext:UBLExtensions").Item(0);
                XmlElement  ext         = (XmlElement)exts.GetElementsByTagName("ext:UBLExtension").Item(0);
                XmlElement  extContent  = (XmlElement)ext.GetElementsByTagName("ext:ExtensionContent").Item(0);
                UriBuilder  ub          = new UriBuilder(Conn.ROOT_DIR + "efatura\\config\\");
                // create context with working dir
                Context context = new Context(ub.Uri);

                //UriBuilder ub2 = new UriBuilder(Conn.ROOT_DIR + "efatura\\config\\xmlsignature-config.xml");
                context.Config = new Config(Conn.ROOT_DIR + "efatura\\config\\xmlsignature-config.xml");

                // define where signature belongs to
                context.Document = envelopeDoc;

                // create signature according to context,
                // with default type (XADES_BES)
                XMLSignature signature = new XMLSignature(context, false);

                String setID = "Signature_" + envelopeDoc.GetElementsByTagName("cbc:ID").Item(0).InnerText;
                signature.Id          = setID;
                signature.SigningTime = DateTime.Now;

                // attach signature to envelope
                //envelopeDoc.DocumentElement.AppendChild(signature.Element);
                extContent.AppendChild(signature.Element);

                //add transforms for efatura
                Transforms transforms = new Transforms(context);
                transforms.addTransform(new Transform(context, TransformType.ENVELOPED.Url));


                // add document as reference,
                //signature.addDocument("#data1", "text/xml", false);
                signature.addDocument("", "text/xml", transforms, DigestMethod.SHA_256, false);

                ECertificate certificate = SmartCardManager.getInstance().getEInvoiceCertificate(cardPinNo);// getSignatureCertificate(true, false);
                if (certificate.isMaliMuhurCertificate())
                {
                    ValidationPolicy policy     = new ValidationPolicy();
                    String           policyPath = Conn.ROOT_DIR + "efatura\\config\\certval-policy-malimuhur.xml";
                    policy = PolicyReader.readValidationPolicy(policyPath);
                    ValidationSystem vs = CertificateValidation.createValidationSystem(policy);
                    context.setCertValidationSystem(vs);
                }
                else
                {
                    ValidationPolicy policy     = new ValidationPolicy();
                    String           policyPath = Conn.ROOT_DIR + "efatura\\config\\certval-policy.xml";
                    policy = PolicyReader.readValidationPolicy(policyPath);
                    ValidationSystem vs = CertificateValidation.createValidationSystem(policy);
                    context.setCertValidationSystem(vs);
                }

                if (CertValidation.validateCertificate(certificate) || bInTest)
                {
                    BaseSigner signer = SmartCardManager.getInstance().getSigner(cardPinNo, certificate);

                    X509Certificate2 msCert = certificate.asX509Certificate2();
                    signature.addKeyInfo(msCert.PublicKey.Key);
                    signature.addKeyInfo(certificate);

                    KeyInfo keyInfo      = signature.createOrGetKeyInfo();
                    int     elementCount = keyInfo.ElementCount;
                    for (int k = 0; k < elementCount; k++)
                    {
                        KeyInfoElement kiElement = keyInfo.get(k);
                        if (kiElement.GetType().IsAssignableFrom(typeof(X509Data)))
                        {
                            X509Data        x509Data        = (X509Data)kiElement;
                            X509SubjectName x509SubjectName = new X509SubjectName(context,
                                                                                  certificate.getSubject().stringValue());
                            x509Data.add(x509SubjectName);
                            break;
                        }
                    }

                    //signature.addKeyInfo(certificate);

                    signature.SignedInfo.CanonicalizationMethod = C14nMethod.EXCLUSIVE_WITH_COMMENTS;

                    signature.sign(signer);

                    // this time we dont use signature.write because we need to write
                    // whole document instead of signature
                    using (Stream s = new FileStream(outXML, FileMode.Create))
                    {
                        try
                        {
                            envelopeDoc.Save(s);
                            s.Flush();
                            s.Close();

                            res = true;
                        }
                        catch (Exception e)
                        {
                            res = false;
                            MessageBox.Show("Dosya kaydedilirken hata oluştu " + e.Message.ToString());
                            s.Close();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                res = false;
                MessageBox.Show("Hata Oluştu \r\n" + e.Message.ToString());
            }

            return(res);
        }
コード例 #27
0
        /// <summary>
        /// Validates a certificate by walking the certificate chain for all trust anchor chain, validating the leaf certificate against the chain.
        /// </summary>
        /// <remarks>
        /// Chain buiding is implemented with P/Invoke to create a custom chain engine allowing CRL checking without installing the anchor was in a trusted location in the Windows certificate store.
        /// </remarks>
        /// <param name="certificate">The leaf <see cref="X509Certificate2"/> to validate</param>
        /// <param name="trustedRoots">The collection of certificates representing anchors or roots of trust.</param>
        /// <returns><c>true</c> if at least one anchor has a valid chain of certs that verify trust in the leaf certificate,
        /// <c>false</c> if no anchors validate trust in the leaf cert.</returns>
        public bool IsTrustedCertificate(X509Certificate2 certificate, X509Certificate2Collection trustedRoots)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException("certificate");
            }

            // if there are no anchors we should always fail
            if (CollectionExtensions.IsNullOrEmpty(trustedRoots))
            {
                this.NotifyUntrusted(certificate);
                return(false);
            }

            try
            {
                var chainPolicy = ValidationPolicy.Clone();

                chainPolicy.ExtraStore.Add(trustedRoots);
                if (this.HasCertificateResolver)
                {
                    this.ResolveIntermediateIssuers(certificate, chainPolicy.ExtraStore);
                }

                X509Chain chainBuilder;

                if (IsNewerThanWin2008R2())
                {
                    using (X509ChainEngine secureChainEngine = new X509ChainEngine(trustedRoots.Enumerate()))
                    {
                        secureChainEngine.BuildChain(certificate, chainPolicy, out chainBuilder);
                    }
                }
                else
                {
                    chainBuilder             = new X509Chain();
                    chainBuilder.ChainPolicy = chainPolicy;
                    chainBuilder.Build(certificate);
                }

                // We're using the system class as a helper to build the chain
                // However, we will review each item in the chain ourselves, because we have our own rules...
                X509ChainElementCollection chainElements = chainBuilder.ChainElements;

                // If we don't have a trust chain, then we obviously have a problem...
                if (chainElements.IsNullOrEmpty())
                {
                    this.NotifyUntrusted(certificate);
                    return(false);
                }

                bool foundAnchor = false;

                // walk the chain starting at the leaf and see if we hit any issues before the anchor
                foreach (X509ChainElement chainElement in chainElements)
                {
                    bool isAnchor = trustedRoots.FindByThumbprint(chainElement.Certificate.Thumbprint) != null;
                    if (isAnchor)
                    {
                        // Found a valid anchor!
                        // Because we found an anchor we trust, we can skip trust
                        foundAnchor = true;
                        continue;
                    }

                    if (this.ChainElementHasProblems(chainElement))
                    {
                        this.NotifyProblem(chainElement);

                        // Whoops... problem with at least one cert in the chain. Stop immediately
                        return(false);
                    }
                }

                return(foundAnchor);
            }
            catch (Exception ex)
            {
                this.NotifyError(certificate, ex);
                // just eat it and drop out to return false
            }

            this.NotifyUntrusted(certificate);
            return(false);
        }