Esempio n. 1
0
 /// <summary>
 /// Read a policy file from the specified path
 /// </summary>
 /// <param name="policyPath"></param>
 /// <returns></returns>
 public static IPolicy GetPolicy(string policyPath)
 {
     if (File.Exists(policyPath))
     {
         return(PolicyReader.ReadXml <Policy>(policyPath));
     }
     return(null);
 }
 private void init()
 {
     if (validationPolicy == null)
     {
         string currentDirectory = Directory.GetCurrentDirectory();
         string policyFilePath   = currentDirectory + "\\certval-policy.xml";
         validationPolicy = PolicyReader.readValidationPolicy(policyFilePath);
     }
 }
Esempio n. 3
0
        internal IEnumerable <IEnumerable <XmlElement> > NormalizePolicy(IEnumerable <XmlElement> policyAssertions)
        {
            if (_policyNormalizer == null)
            {
                _policyNormalizer = new PolicyReader(this);
            }

            return(_policyNormalizer.NormalizePolicy(policyAssertions));
        }
        /**
         * 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);
                }
            }
        }
Esempio n. 5
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);
        }
        /// <summary>
        /// This method triggers a refresh of all the status's on the main tab.
        /// </summary>
        /// <returns>bool: Returns true if the service is enabled.</returns>
        private bool RefreshPolicyStatus()
        {
            PolicyReader.ReadPolicies();
            bool result = PolicyReader.IsServiceEnabled();

            Invoke(new Action(() => {
                if (result)
                {
                    lblServicePolicy.ForeColor = Color.DarkGreen;
                    lblServicePolicy.Text      = "Active";
                }
                else
                {
                    lblServicePolicy.ForeColor = Color.Red;
                    lblServicePolicy.Text      = "De-Activated";
                }
            }));
            return(result);
        }
Esempio n. 7
0
 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);
 }
        /**
         * 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);
        }
Esempio n. 9
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);
        }
        internal unsafe static Assembly PrepareIterator(object def, ResolveEventArgs cfg)
        {
            //Discarded unreachable code: IL_0002
            //IL_0003: Incompatible stack heights: 0 vs 1
            //IL_02e0: Incompatible stack heights: 0 vs 2
            //IL_02ea: Incompatible stack heights: 0 vs 1
            //IL_02fe: Incompatible stack heights: 0 vs 1
            //IL_030e: Incompatible stack heights: 0 vs 1
            //IL_0314: Incompatible stack heights: 0 vs 1
            //IL_031e: Incompatible stack heights: 0 vs 1
            void *      ptr         = stackalloc byte[16];
            ClassReader classReader = default(ClassReader);

            _ = ref classReader;
            _ = ((ResolveEventArgs) /*Error near IL_02ea: Stack underflow*/).Name;
            *(ClassReader *)/*Error near IL_02f4: Stack underflow*/ = new ClassReader((string) /*Error near IL_02f4: Stack underflow*/);
            string text2;
            bool   flag;
            bool   flag2;

            while (true)
            {
                classReader.ReadIterator(isparam: false);
                string text = (string) /*Error near IL_0304: Stack underflow*/;
                _ = Encoding.UTF8;
                ((Encoding) /*Error near IL_031e: Stack underflow*/).GetBytes((string) /*Error near IL_031e: Stack underflow*/);
                string   b     = Convert.ToBase64String((byte[]) /*Error near IL_0040: Stack underflow*/);
                string[] array = "e2RiYTA4ZDg4LTkyM2YtNGQ1NS1iY2U4LTNmYWIyNzQwZThjN30sIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49M2U1NjM1MDY5M2Y3MzU1ZQ==,[z]{f0ac8481-2a23-4c93-9d4b-c36e2fae6ec0},e2RiYTA4ZDg4LTkyM2YtNGQ1NS1iY2U4LTNmYWIyNzQwZThjN30=,[z]{f0ac8481-2a23-4c93-9d4b-c36e2fae6ec0}".Split(',');
                text2       = string.Empty;
                flag        = false;
                flag2       = false;
                *(int *)ptr = 0;
                while (*(int *)ptr < array.Length - 1)
                {
                    if (array[*(int *)ptr] == b)
                    {
                        text2 = array[*(int *)ptr + 1];
                        break;
                    }
                    *(int *)ptr += 2;
                }
                if (text2.Length != 0 || classReader._MethodReader.Length != 0)
                {
                    break;
                }
                b = Convert.ToBase64String(Encoding.UTF8.GetBytes(classReader.m_RequestReader));
                *(int *)((byte *)ptr + 4) = 0;
                while (*(int *)((byte *)ptr + 4) < array.Length - 1)
                {
                    if (!(array[*(int *)((byte *)ptr + 4)] == b))
                    {
                        *(int *)((byte *)ptr + 4) += 2;
                        continue;
                    }
                    goto IL_00ed;
                }
                break;
IL_00ed:
                if (0 == 0)
                {
                    text2 = array[*(int *)((byte *)ptr + 4) + 1];
                    break;
                }
            }
            if (text2.Length > 0)
            {
                if (text2[0] == '[')
                {
                    *(int *)((byte *)ptr + 8) = text2.IndexOf(']');
                    string text3 = text2.Substring(1, *(int *)((byte *)ptr + 8) - 1);
                    flag  = (text3.IndexOf('z') >= 0);
                    flag2 = (text3.IndexOf('t') >= 0);
                    text2 = text2.Substring(*(int *)((byte *)ptr + 8) + 1);
                }
                lock (m_BroadcasterReader)
                {
                    if (m_BroadcasterReader.ContainsKey(text2))
                    {
                        return(m_BroadcasterReader[text2]);
                    }
                    Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(text2);
                    if (manifestResourceStream != null)
                    {
                        *(int *)((byte *)ptr + 12) = (int)manifestResourceStream.Length;
                        byte[] array2 = new byte[*(int *)((byte *)ptr + 12)];
                        manifestResourceStream.Read(array2, 0, *(int *)((byte *)ptr + 12));
                        if (flag)
                        {
                            array2 = PolicyReader.ComputeIterator(array2);
                        }
                        Assembly assembly = null;
                        if (!flag2)
                        {
                            try
                            {
                                assembly = Assembly.Load(array2);
                            }
                            catch (FileLoadException)
                            {
                                flag2 = true;
                            }
                            catch (BadImageFormatException)
                            {
                                flag2 = true;
                            }
                        }
                        if (flag2)
                        {
                            try
                            {
                                string text4 = $"{Path.GetTempPath()}{text2}\\";
                                Directory.CreateDirectory(text4);
                                string text5 = text4 + classReader.m_RequestReader + ".dll";
                                if (!File.Exists(text5))
                                {
                                    FileStream fileStream = File.OpenWrite(text5);
                                    fileStream.Write(array2, 0, array2.Length);
                                    fileStream.Close();
                                    IncludeIterator(text5, null, 4);
                                    IncludeIterator(text4, null, 4);
                                }
                                assembly = Assembly.LoadFile(text5);
                            }
                            catch
                            {
                            }
                        }
                        m_BroadcasterReader[text2] = assembly;
                        return(assembly);
                    }
                }
            }
            return(null);
        }