示例#1
0
        public void ConstructorAsnEncodedData_BadAsnLength()
        {
            AsnEncodedData aed = new AsnEncodedData("1.2.3", new byte[] { 0x30, 0x01 });
            X509Extension  ex  = new X509Extension(aed, true);

            Assert.AreEqual("30 01", ex.Format(true), "Format(true)");
            Assert.AreEqual("30 01", ex.Format(false), "Format(false)");
            // no exception for an bad (invalid length) extension
        }
示例#2
0
        public void ConstructorAsnEncodedData_BadAsn()
        {
            AsnEncodedData aed = new AsnEncodedData("1.2.3", new byte[0]);
            X509Extension  ex  = new X509Extension(aed, true);

            Assert.AreEqual(String.Empty, ex.Format(true), "Format(true)");
            Assert.AreEqual(String.Empty, ex.Format(false), "Format(false)");
            // no exception for an "empty" extension
        }
示例#3
0
        public void ConstructorAsnEncodedData_BadAsnTag()
        {
            AsnEncodedData aed = new AsnEncodedData("1.2.3", new byte[] { 0x05, 0x00 });
            X509Extension  ex  = new X509Extension(aed, true);

            Assert.AreEqual("05 00", ex.Format(true), "Format(true)");
            Assert.AreEqual("05 00", ex.Format(false), "Format(false)");
            // no exception for an "unknown" (ASN.1 NULL) extension
        }
示例#4
0
        void processCert()
        {
            X509Extension san = srv.Certificate.Extensions["2.5.29.17"];

            if (san != null)
            {
                srv.Log.Add($"Found Subject Alternative Names extension in the certificate.{_nl}");
                srv.Log.Add($"Fetching SAN values:{_nl}");
                srv.Log.Add(san.Format(true) + _nl);
                foreach (String name in san.Format(false).Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries))
                {
                    srv.SAN.Add(name);
                }
            }
        }
示例#5
0
        void readAltNames()
        {
            X509Extension san = NativeEntry.Certificate.Extensions[EXT_SAN];

            if (san != null)
            {
                NativeEntry.Log.AppendLine("Found Subject Alternative Names extension in the certificate.");
                NativeEntry.Log.AppendLine("Fetching SAN values:");
                NativeEntry.Log.AppendLine(san.Format(true));
                foreach (String name in san.Format(false)
                         .Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries))
                {
                    NativeEntry.SAN.Add(name);
                }
            }
        }
示例#6
0
        public void DecodeExtensions(
            CertificateAsset certAsset
            )
        {
            var x509Cert = new X509Certificate2(certAsset.Cert);

            Assert.NotNull(x509Cert);
            TestContext.Out.WriteLine($"CertificateAsset:");
            TestContext.Out.WriteLine(x509Cert);
            var altName = X509Extensions.FindExtension <X509SubjectAltNameExtension>(x509Cert);

            if (altName != null)
            {
                TestContext.Out.WriteLine($"X509SubjectAltNameExtension:");
                TestContext.Out.WriteLine(altName?.Format(true));
                var ext = new X509Extension(altName.Oid, altName.RawData, altName.Critical);
                TestContext.Out.WriteLine(ext.Format(true));
            }
            var authority = X509Extensions.FindExtension <X509AuthorityKeyIdentifierExtension>(x509Cert);

            if (authority != null)
            {
                TestContext.Out.WriteLine($"X509AuthorityKeyIdentifierExtension:");
                TestContext.Out.WriteLine(authority?.Format(true));
                var ext = new X509Extension(authority.Oid, authority.RawData, authority.Critical);
                TestContext.Out.WriteLine(ext.Format(true));
            }
            TestContext.Out.WriteLine($"All extensions:");
            foreach (var extension in x509Cert.Extensions)
            {
                TestContext.Out.WriteLine(extension.Format(true));
            }
        }
示例#7
0
        private string RecuperarCNPJ(byte[] RawData)
        {
            try
            {
                System.Security.Cryptography.X509Certificates.X509Certificate2 certificado =
                    new System.Security.Cryptography.X509Certificates.X509Certificate2(RawData);

                // OID "2.5.29.17" - OtherName
                X509Extension extension = certificado.Extensions["2.5.29.17"];
                if (extension != null)
                {
                    string otherName = extension.Format(false);
                    if (!string.IsNullOrEmpty(otherName) &&
                        (otherName.Contains("2.16.76.1.3.3")))
                    {
                        int offset = otherName.IndexOf("2.16.76.1.3.3=");
                        offset += 14;
                        int         endPos        = otherName.IndexOf(",", offset);
                        string      cnpjEncValue  = otherName.Substring(offset, endPos - offset);
                        List <byte> byteArrayCnpj = new List <byte>();
                        foreach (string token in cnpjEncValue.Split(' '))
                        {
                            byte value = byte.Parse(token, System.Globalization.NumberStyles.HexNumber);
                            // Valores em hexadecimal / decimal para os caracteres
                            // -: 2d / 45
                            // .: 2e / 46
                            // /: 2f / 47
                            // 0-9: 30-39 / 48-57
                            if ((value >= 48) &&
                                (value <= 57))
                            {
                                byteArrayCnpj.Add(value);
                            }
                        }
                        string valor = ASCIIEncoding.ASCII.GetString(byteArrayCnpj.ToArray());
                        if (byteArrayCnpj.Count == 14 && Funcoes.ValidarCNPJ(valor))
                        {
                            return(ASCIIEncoding.ASCII.GetString(byteArrayCnpj.ToArray()));
                        }
                        else
                        {
                            return("");
                        }
                    }
                    else
                    {
                        return("");
                    }
                }
                else
                {
                    return("");
                }
            }

            catch (Exception ex)
            {
                return("");
            }
        }
            // static initializer runs only when one of the properties is accessed
#pragma warning disable SA1201 // Elements should appear in the correct order
            static X509SubjectAlternativeNameConstants()
#pragma warning restore SA1201 // Elements should appear in the correct order
            {
                // Extracted a well-known X509Extension
                var x509ExtensionBytes = new byte[]
                {
                    48, 36, 130, 21, 110, 111, 116, 45, 114, 101, 97, 108, 45, 115, 117, 98, 106, 101, 99,
                    116, 45, 110, 97, 109, 101, 130, 11, 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109
                };
                const string subjectName1 = "not-real-subject-name";

                try
                {
                    var x509Extension = new X509Extension(Oid, x509ExtensionBytes, true);
                    var x509ExtensionFormattedString = x509Extension.Format(false);

                    // Each OS has a different dNSName identifier and delimiter
                    // On Windows, dNSName == "DNS Name" (localizable), on Linux, dNSName == "DNS"
                    // e.g.,
                    // Windows: x509ExtensionFormattedString is: "DNS Name=not-real-subject-name, DNS Name=example.com"
                    // Linux:   x509ExtensionFormattedString is: "DNS:not-real-subject-name, DNS:example.com"
                    // Parse: <identifier><delimter><value><separator(s)>
                    var delimiterIndex = x509ExtensionFormattedString.IndexOf(subjectName1, StringComparison.Ordinal) - 1;
                    s_delimiter = x509ExtensionFormattedString[delimiterIndex];

                    // Make an assumption that all characters from the the start of string to the delimiter
                    // are part of the identifier
                    s_identifier = x509ExtensionFormattedString.Substring(0, delimiterIndex);

                    var separatorFirstChar = delimiterIndex + subjectName1.Length + 1;
                    var separatorLength    = 1;
                    for (var i = separatorFirstChar + 1; i < x509ExtensionFormattedString.Length; i++)
                    {
                        // We advance until the first character of the identifier to determine what the
                        // separator is. This assumes that the identifier assumption above is correct
                        if (x509ExtensionFormattedString[i] == s_identifier[0])
                        {
                            break;
                        }

                        separatorLength++;
                    }

                    s_separator = x509ExtensionFormattedString.Substring(separatorFirstChar, separatorLength);

                    s_successfullyInitialized = true;
                }
                catch (Exception ex)
                {
                    s_successfullyInitialized = false;
                    s_initializationException = ex;
                }
            }
示例#9
0
        private static void ObterExtensions(X509Certificate2 x509, TOCertificadoDigital certEntidade)
        {
            X509Extension extension = x509.Extensions["2.5.29.17"];

            if (extension != null)
            {
                string otherName = extension.Format(false);
                if (!string.IsNullOrEmpty(otherName) &&
                    (otherName.Contains("2.16.76.1.3.1") ||
                     otherName.Contains("2.16.76.1.3.4")))
                {
                    int offset;
                    if (otherName.Contains("2.16.76.1.3.1"))
                    {
                        offset = otherName.IndexOf("2.16.76.1.3.1=");
                    }
                    else
                    {
                        offset = otherName.IndexOf("2.16.76.1.3.4=");
                    }
                    offset += 14;
                    int    endPos = otherName.IndexOf(",", offset);
                    string cpfEncValue;
                    if (endPos == -1)
                    {
                        cpfEncValue = otherName.Substring(offset);
                    }
                    else
                    {
                        cpfEncValue = otherName.Substring(offset, endPos - offset);
                    }

                    List <byte> byteArrayCpf = new List <byte>();
                    string[]    tokens       = cpfEncValue.Split(' ');
                    for (int i = 10; i < 21; i++)
                    {
                        byte value = byte.Parse(tokens[i], System.Globalization.NumberStyles.HexNumber);
                        if ((value >= 48) &&
                            (value <= 57))
                        {
                            byteArrayCpf.Add(value);
                        }
                    }
                    certEntidade.CPF = ASCIIEncoding.ASCII.GetString(byteArrayCpf.ToArray()).PadLeft(14, 'X');

                    certEntidade.DataNascimento      = ExtrairDataNascimento(tokens);
                    certEntidade.IdentificacaoSocial = ExtrairIdentificacaoSocial(tokens);
                    certEntidade.RG = ExtrairRG(tokens);
                }
            }
        }
示例#10
0
 public static bool CertificateCheckSubjectAlternativeNames(X509Extension extensions, string hostName)
 {
     if (extensions != null)
     {
         string[] strArrays  = Regex.Split(extensions.Format(true), Environment.NewLine);
         string[] strArrays1 = strArrays;
         for (int i = 0; i < (int)strArrays1.Length; i++)
         {
             string str = strArrays1[i];
             if (!string.IsNullOrEmpty(str))
             {
                 string[] strArrays2 = str.Trim().Split(new char[] { '=' });
                 if (strArrays2[0].Trim().Equals("DNS Name") && LenientDnsIdentityVerifier.CheckTopLevelDomainCompatibleness(strArrays2[1].Trim(), hostName))
                 {
                     return(true);
                 }
             }
         }
     }
     return(false);
 }
示例#11
0
        private TipoCertificado RecuperarTipoCertificado(byte[] RawData)
        {
            System.Security.Cryptography.X509Certificates.X509Certificate2 certificado =
                new System.Security.Cryptography.X509Certificates.X509Certificate2(RawData);

            // OID "2.5.29.17" - OtherName
            X509Extension extension = certificado.Extensions["2.5.29.17"];

            if (extension != null)
            {
                string otherName = extension.Format(false);
                if (!string.IsNullOrEmpty(otherName) && (otherName.Contains("2.16.76.1.3.1")))
                {
                    return(TipoCertificado.eCPF);
                }
                else if (!string.IsNullOrEmpty(otherName) && (otherName.Contains("2.16.76.1.3.3")))
                {
                    return(TipoCertificado.eCNPJ);
                }
            }

            return(TipoCertificado.Null);
        }
示例#12
0
        private static int ListCertificates(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Must specify the distinguished name of the user");
                return(1);
            }

            string        userDN = args[1];
            UserPrincipal user   = UserPrincipal.FindByIdentity(ctx, IdentityType.DistinguishedName, userDN);

            if (null == user)
            {
                Console.WriteLine("No user found with DN: " + userDN);
                return(1);
            }

            if (0 == user.Certificates.Count)
            {
                Console.WriteLine("Found user in AD, but the user has no certificates");
                return(0);
            }

            foreach (X509Certificate2 cert in user.Certificates)
            {
                Console.WriteLine();
                Console.WriteLine(cert.SerialNumber);
                Console.WriteLine("  Subject: " + cert.Subject);
                X509Extension certTemplate = Program.GetCertificateTemplateExtension(cert);
                if (null != certTemplate)
                {
                    Console.WriteLine("  Template: " + certTemplate.Format(false));
                }
            }

            return(0);
        }
示例#13
0
            // static initializer will run before properties are accessed
            static X509SubjectAlternativeNameConstants()
            {
                // Extracted a well-known X509Extension
                byte[] x509ExtensionBytes = new byte[] {
                    48, 36, 130, 21, 110, 111, 116, 45, 114, 101, 97, 108, 45, 115, 117, 98, 106, 101, 99,
                    116, 45, 110, 97, 109, 101, 130, 11, 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109
                };
                const string subjectName = "not-real-subject-name";
                string       x509ExtensionFormattedString = string.Empty;

                try
                {
                    X509Extension x509Extension = new X509Extension(SanOid, x509ExtensionBytes, true);
                    x509ExtensionFormattedString = x509Extension.Format(false);

                    // Each OS has a different dNSName identifier and delimiter
                    // On Windows, dNSName == "DNS Name" (localizable), on Linux, dNSName == "DNS"
                    // e.g.,
                    // Windows: x509ExtensionFormattedString is: "DNS Name=not-real-subject-name, DNS Name=example.com"
                    // Linux:   x509ExtensionFormattedString is: "DNS:not-real-subject-name, DNS:example.com"
                    // Parse: <identifier><delimiter><value><separator(s)>

                    int delimiterIndex = x509ExtensionFormattedString.IndexOf(subjectName) - 1;
                    Delimiter = x509ExtensionFormattedString[delimiterIndex];

                    // Make an assumption that all characters from the the start of string to the delimiter
                    // are part of the identifier
                    Identifier = x509ExtensionFormattedString.Substring(0, delimiterIndex);

                    int separatorFirstChar = delimiterIndex + subjectName.Length + 1;
                    int separatorLength    = 1;
                    for (int i = separatorFirstChar + 1; i < x509ExtensionFormattedString.Length; i++)
                    {
                        // We advance until the first character of the identifier to determine what the
                        // separator is. This assumes that the identifier assumption above is correct
                        if (x509ExtensionFormattedString[i] == Identifier[0])
                        {
                            break;
                        }

                        separatorLength++;
                    }

                    Separator      = x509ExtensionFormattedString.Substring(separatorFirstChar, separatorLength);
                    SeparatorArray = new string[1] {
                        Separator
                    };
                    SuccessfullyInitialized = true;
                }
                catch (Exception ex)
                {
                    SuccessfullyInitialized = false;
                    DiagnosticUtility.TraceHandledException(
                        new FormatException(string.Format(CultureInfo.InvariantCulture,
                                                          "There was an error parsing the SubjectAlternativeNames: '{0}'. See inner exception for more details.{1}Detected values were: Identifier: '{2}'; Delimiter:'{3}'; Separator:'{4}'",
                                                          x509ExtensionFormattedString,
                                                          Environment.NewLine,
                                                          Identifier,
                                                          Delimiter,
                                                          Separator),
                                            ex),
                        TraceEventType.Warning);
                }
            }
示例#14
0
 /// <summary>
 /// Creates a new instance of the RequestAuthHandler class.
 /// </summary>
 public RequestAuthHandler()
 {
     this.ClientCertificateOptions = ClientCertificateOption.Automatic;
     this.UseDefaultCredentials    = false;
     this.UseProxy = false;
     this.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
     {
         if (sslPolicyErrors == SslPolicyErrors.None)
         {
             return(true);
         }
         if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
         {
             if (sender is HttpWebRequest)
             {
                 var request2   = sender as HttpWebRequest;
                 var requestUri = request2.RequestUri;
                 if (requestUri.HostNameType == UriHostNameType.IPv4 || requestUri.HostNameType == UriHostNameType.IPv6 || requestUri.HostNameType == UriHostNameType.Dns)
                 {
                     X509Extension ext2 = (certificate as X509Certificate2).Extensions["Subject Alternative Name"];
                     if (ext2 != null)
                     {
                         string subjAltName = ext2.Format(false);
                         if (subjAltName.IndexOf(requestUri.Host, StringComparison.OrdinalIgnoreCase) == -1)
                         {
                             return(false);
                         }
                     }
                     else
                     {
                         return(false);
                     }
                 }
                 else
                 {
                     return(false);
                 }
             }
             else if (sender is SslStream)
             {
                 //nothing to do, fall through
             }
             else
             {
                 return(false);
             }
         }
         if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
         {
             if (chain != null && chain.ChainStatus != null)
             {
                 foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
                 {
                     if (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot)
                     {
                         // Self-signed certificates with an untrusted root are valid.
                         continue;
                     }
                     else
                     {
                         if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
                         {
                             // If there are any other errors in the certificate chain, the certificate is invalid,
                             // so the method returns false.
                             return(false);
                         }
                     }
                 }
                 return(true);
             }
         }
         return(false);
     };
 }