Example #1
2
	static void Main(string[] args) {
		if (args.Length != 4) {
			Console.WriteLine("Usage: cra.exe cert-file cert-password input-path output-path");
			return;
		}

		String certFile = args[0];
		String password = args[1];
		String input    = args[2];
		String output   = args[3];

		X509Certificate2 cert = new X509Certificate2(certFile, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

		XmlDocument xmlDoc = new XmlDocument();
		xmlDoc.Load(input);

		var XmlToSign = new XmlDocument();
  	XmlToSign.LoadXml(xmlDoc.DocumentElement["Body"].OuterXml);

		SignedXml signedXml = new SignedXml(XmlToSign);
		signedXml.SigningKey = cert.PrivateKey;

		Reference reference = new Reference();
		reference.Uri = "";

    XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
    reference.AddTransform(env);

		signedXml.AddReference(reference);
		signedXml.ComputeSignature();
		XmlElement xmlDigitalSignature = signedXml.GetXml();
		xmlDoc.DocumentElement["Body"].AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
		xmlDoc.Save(output);
	}
Example #2
0
 private static PublicKey GetTestDsaKey()
 {
     using (var cert = new X509Certificate2(TestData.DssCer))
     {
         return cert.PublicKey;
     }
 }
Example #3
0
        public static void X509Cert2Test()
        {
            string certName = TestData.NormalizeX500String(
                @"[email protected], CN=ABA.ECOM Root CA, O=""ABA.ECOM, INC."", L=Washington, S=DC, C=US");

            DateTime notBefore = new DateTime(1999, 7, 12, 17, 33, 53, DateTimeKind.Utc).ToLocalTime();
            DateTime notAfter = new DateTime(2009, 7, 9, 17, 33, 53, DateTimeKind.Utc).ToLocalTime();

            using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "test.cer")))
            {
                Assert.Equal(certName, cert2.IssuerName.Name);
                Assert.Equal(certName, cert2.SubjectName.Name);

                Assert.Equal("ABA.ECOM Root CA", cert2.GetNameInfo(X509NameType.DnsName, true));

                PublicKey pubKey = cert2.PublicKey;
                Assert.Equal("RSA", pubKey.Oid.FriendlyName);

                Assert.Equal(notAfter, cert2.NotAfter);
                Assert.Equal(notBefore, cert2.NotBefore);

                Assert.Equal("00D01E4090000046520000000100000004", cert2.SerialNumber);
                Assert.Equal("1.2.840.113549.1.1.5", cert2.SignatureAlgorithm.Value);
                Assert.Equal("7A74410FB0CD5C972A364B71BF031D88A6510E9E", cert2.Thumbprint);
                Assert.Equal(3, cert2.Version);
            }
        }
Example #4
0
public static bool TestCert(CertificateInfo ci)
{
	bool bRes = true;

	try {
		X509Certificate2 cert;
		if (ci.Password != null)
			cert = new X509Certificate2(ci.FileName, ci.Password);
		else
			cert = new X509Certificate2(ci.FileName);
	
		if (!ci.Matches(cert)) bRes = false;

//		Console.WriteLine("ToString: " + cert.ToString());
//		Console.WriteLine("ToString(true): " + cert.ToString(true));

		X509Certificate2 certImp = new X509Certificate2();
		if (ci.Password != null)
			certImp.Import(ci.FileName, ci.Password, X509KeyStorageFlags.DefaultKeySet);
		else
			certImp.Import(ci.FileName);
		
		if (!ci.Matches(certImp)) bRes = false;
		
		
	}
	catch(Exception e)
	{
		bRes = false;
		Console.WriteLine("Exception is caught:" + Environment.NewLine + e.ToString());
	}

	return bRes;
}
Example #5
0
        public static void TestRawData()
        {
            byte[] expectedRawData = (
                "308201e530820152a0030201020210d5b5bc1c458a558845" +
                "bff51cb4dff31c300906052b0e03021d05003011310f300d" +
                "060355040313064d794e616d65301e170d31303034303130" +
                "38303030305a170d3131303430313038303030305a301131" +
                "0f300d060355040313064d794e616d6530819f300d06092a" +
                "864886f70d010101050003818d0030818902818100b11e30" +
                "ea87424a371e30227e933ce6be0e65ff1c189d0d888ec8ff" +
                "13aa7b42b68056128322b21f2b6976609b62b6bc4cf2e55f" +
                "f5ae64e9b68c78a3c2dacc916a1bc7322dd353b32898675c" +
                "fb5b298b176d978b1f12313e3d865bc53465a11cca106870" +
                "a4b5d50a2c410938240e92b64902baea23eb093d9599e9e3" +
                "72e48336730203010001a346304430420603551d01043b30" +
                "39801024859ebf125e76af3f0d7979b4ac7a96a113301131" +
                "0f300d060355040313064d794e616d658210d5b5bc1c458a" +
                "558845bff51cb4dff31c300906052b0e03021d0500038181" +
                "009bf6e2cf830ed485b86d6b9e8dffdcd65efc7ec145cb93" +
                "48923710666791fcfa3ab59d689ffd7234b7872611c5c23e" +
                "5e0714531abadb5de492d2c736e1c929e648a65cc9eb63cd" +
                "84e57b5909dd5ddf5dbbba4a6498b9ca225b6e368b94913b" +
                "fc24de6b2bd9a26b192b957304b89531e902ffc91b54b237" +
                "bb228be8afcda26476").HexToByteArray();

            using (var c = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
            {
                byte[] rawData = c.RawData;
                Assert.Equal(expectedRawData, rawData);
            }
        }
Example #6
0
    public static void Main(String[] args)
    {
        var exe = Assembly.GetExecutingAssembly().Location;
        var folder = Path.GetDirectoryName(exe);
        var pfx = Path.Combine(folder, "ClientPrivate.pfx");
        var c = new X509Certificate2(File.ReadAllBytes(pfx), "wse2qs");

        if (args[0] == "verify")
        {
            Console.WriteLine("verifying signature...");
            var file = Path.Combine(folder, "SignedExample.xml");
            bool b = VerifyXmlFile(file, (RSA)c.PublicKey.Key);
            Console.WriteLine("signature is " + (b ? "valid" : "not valid!"));
            if (!b) Environment.Exit(-1);
        }
        else if (args[0] == "sign")
        {
            Console.WriteLine("generating signature...");
            var xmlFile = Path.Combine(folder, "Example.xml");
            var sigFile = Path.Combine(folder, "signedExample.xml");
            CreateSomeXml(xmlFile);
            SignXmlFile(xmlFile, sigFile, (RSA)c.PrivateKey);
            Console.WriteLine("done");
        }
    }
Example #7
0
        public static void TestHandle()
        {
            //
            // Ensure that the Handle property returns a valid CER_CONTEXT pointer.
            //
            using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate))
            {
                IntPtr h = c.Handle;
                unsafe
                {
                    CERT_CONTEXT* pCertContext = (CERT_CONTEXT*)h;

                    // Does the blob data match?
                    int cbCertEncoded = pCertContext->cbCertEncoded;
                    Assert.Equal(TestData.MsCertificate.Length, cbCertEncoded);

                    byte[] pCertEncoded = new byte[cbCertEncoded];
                    Marshal.Copy((IntPtr)(pCertContext->pbCertEncoded), pCertEncoded, 0, cbCertEncoded);
                    Assert.Equal(TestData.MsCertificate, pCertEncoded);

                    // Does the serial number match?
                    CERT_INFO* pCertInfo = pCertContext->pCertInfo;
                    byte[] serialNumber = pCertInfo->SerialNumber.ToByteArray();
                    byte[] expectedSerial = "b00000000100dd9f3bd08b0aaf11b000000033".HexToByteArray();
                    Assert.Equal(expectedSerial, serialNumber);
                }
            }
        }
Example #8
0
        public static void TestByteArrayConstructor()
        {
            byte[] expectedThumbPrint = new byte[]
            {
                0x10, 0x8e, 0x2b, 0xa2, 0x36, 0x32, 0x62, 0x0c,
                0x42, 0x7c, 0x57, 0x0b, 0x6d, 0x9d, 0xb5, 0x1a,
                0xc3, 0x13, 0x87, 0xfe,
            };

            using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate))
            {
                IntPtr h = c.Handle;
                object ignored;
                Assert.NotEqual(IntPtr.Zero, h);
                byte[] actualThumbprint = c.GetCertHash();
                Assert.Equal(expectedThumbPrint, actualThumbprint);

                c.Dispose();

                // For compat reasons, Dispose() acts like the now-defunct Reset() method rather than causing ObjectDisposedExceptions.
                h = c.Handle;
                Assert.Equal(IntPtr.Zero, h);
                Assert.Throws<CryptographicException>(() => c.GetCertHash());
                Assert.Throws<CryptographicException>(() => c.GetKeyAlgorithm());
                Assert.Throws<CryptographicException>(() => c.GetKeyAlgorithmParameters());
                Assert.Throws<CryptographicException>(() => c.GetKeyAlgorithmParametersString());
                Assert.Throws<CryptographicException>(() => c.GetPublicKey());
                Assert.Throws<CryptographicException>(() => c.GetSerialNumber());
                Assert.Throws<CryptographicException>(() => ignored = c.Issuer);
                Assert.Throws<CryptographicException>(() => ignored = c.Subject);
            }
        }
Example #9
0
 public static void TestDefaultConstructor()
 {
     using (X509Certificate2 c = new X509Certificate2())
     {
         IntPtr h = c.Handle;
         object ignored;
         Assert.Equal(IntPtr.Zero, h);
         Assert.Throws<CryptographicException>(() => c.GetCertHash());
         Assert.Throws<CryptographicException>(() => c.GetKeyAlgorithm());
         Assert.Throws<CryptographicException>(() => c.GetKeyAlgorithmParameters());
         Assert.Throws<CryptographicException>(() => c.GetKeyAlgorithmParametersString());
         Assert.Throws<CryptographicException>(() => c.GetPublicKey());
         Assert.Throws<CryptographicException>(() => c.GetSerialNumber());
         Assert.Throws<CryptographicException>(() => ignored = c.Issuer);
         Assert.Throws<CryptographicException>(() => ignored = c.Subject);
         Assert.Throws<CryptographicException>(() => ignored = c.RawData);
         Assert.Throws<CryptographicException>(() => ignored = c.Thumbprint);
         Assert.Throws<CryptographicException>(() => ignored = c.SignatureAlgorithm);
         Assert.Throws<CryptographicException>(() => ignored = c.HasPrivateKey);
         Assert.Throws<CryptographicException>(() => ignored = c.Version);
         Assert.Throws<CryptographicException>(() => ignored = c.Archived);
         Assert.Throws<CryptographicException>(() => c.Archived = false);
         Assert.Throws<CryptographicException>(() => c.FriendlyName = "Hi");
         Assert.Throws<CryptographicException>(() => ignored = c.SubjectName);
         Assert.Throws<CryptographicException>(() => ignored = c.IssuerName);
         Assert.Throws<CryptographicException>(() => ignored = c.PrivateKey);
     }
 }
Example #10
0
        public static void TestNullConstructorArguments()
        {
            Assert.Throws<ArgumentException>(() => new X509Certificate2((byte[])null, (String)null));
            Assert.Throws<ArgumentException>(() => new X509Certificate2(new byte[0], (String)null));
            Assert.Throws<ArgumentException>(() => new X509Certificate2((byte[])null, (String)null, X509KeyStorageFlags.DefaultKeySet));
            Assert.Throws<ArgumentException>(() => new X509Certificate2(new byte[0], (String)null, X509KeyStorageFlags.DefaultKeySet));

            // For compat reasons, the (byte[]) constructor (and only that constructor) treats a null or 0-length array as the same
            // as calling the default constructor.
            {
                using (X509Certificate2 c = new X509Certificate2((byte[])null))
                {
                    IntPtr h = c.Handle;
                    Assert.Equal(IntPtr.Zero, h);
                    Assert.Throws<CryptographicException>(() => c.GetCertHash());
                }
            }

            {
                using (X509Certificate2 c = new X509Certificate2(new byte[0]))
                {
                    IntPtr h = c.Handle;
                    Assert.Equal(IntPtr.Zero, h);
                    Assert.Throws<CryptographicException>(() => c.GetCertHash());
                }
            }
        }
Example #11
0
        public static void TestECDsa224PublicKey()
        {
            using (var cert = new X509Certificate2(TestData.ECDsa224Certificate))
            {
                // It is an Elliptic Curve Cryptography public key.
                Assert.Equal("1.2.840.10045.2.1", cert.PublicKey.Oid.Value);

                ECDsa ecdsa;

                try
                {
                    ecdsa = cert.GetECDsaPublicKey();
                }
                catch (CryptographicException)
                {
                    // Windows 7, Windows 8, CentOS.
                    return;
                }

                // Other Unix
                using (ecdsa)
                {
                    byte[] data = ByteUtils.AsciiBytes("Hello");

                    byte[] signature = (
                        // r
                        "8ede5053d546d35c1aba829bca3ecf493eb7a73f751548bd4cf2ad10" +
                        // s
                        "5e3da9d359001a6be18e2b4e49205e5219f30a9daeb026159f41b9de").HexToByteArray();

                    Assert.True(ecdsa.VerifyData(data, signature, HashAlgorithmName.SHA1));
                }
            }
        }
Example #12
0
        public static void TestConstructor_DER()
        {
            byte[] expectedThumbPrint = new byte[]
            {
                0x10, 0x8e, 0x2b, 0xa2, 0x36, 0x32, 0x62, 0x0c,
                0x42, 0x7c, 0x57, 0x0b, 0x6d, 0x9d, 0xb5, 0x1a,
                0xc3, 0x13, 0x87, 0xfe,
            };

            Action<X509Certificate2> assert = (c) =>
            {
                IntPtr h = c.Handle;
                Assert.NotEqual(IntPtr.Zero, h);
                byte[] actualThumbprint = c.GetCertHash();
                Assert.Equal(expectedThumbPrint, actualThumbprint);
            };

            using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate))
            {
                assert(c);
#if netstandard17
                using (X509Certificate2 c2 = new X509Certificate2(c))
                {
                    assert(c2);
                }
#endif
            }
        }
Example #13
0
 public static void TestDefaultConstructor()
 {
     using (X509Certificate2 c = new X509Certificate2())
     {
         VerifyDefaultConstructor(c);
     }
 }
Example #14
0
 public static void TestSerialString(string fileName, string expectedSerial)
 {
     using (var c = new X509Certificate2(Path.Combine("TestData", fileName)))
     {
         Assert.Equal(expectedSerial, c.SerialNumber);
     }
 }
Example #15
0
		// constructors

		// only accessible from X509Chain.ChainElements
		internal X509ChainElement (X509Certificate2 certificate)
		{
			this.certificate = certificate;
			// so far String.Empty is the only thing I've seen. 
			// The interesting stuff is inside X509ChainStatus.Information
			info = String.Empty;
		}
Example #16
0
        public static void X509Certificate2CollectionConstructors()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            using (X509Certificate2 c2 = new X509Certificate2())
            using (X509Certificate2 c3 = new X509Certificate2())
            {
                X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 });
                Assert.Equal(3, cc.Count);
                Assert.Same(c1, cc[0]);
                Assert.Same(c2, cc[1]);
                Assert.Same(c3, cc[2]);

                X509Certificate2Collection cc2 = new X509Certificate2Collection(cc);
                Assert.Equal(3, cc2.Count);
                Assert.Same(c1, cc2[0]);
                Assert.Same(c2, cc2[1]);
                Assert.Same(c3, cc2[2]);

                Assert.Throws<ArgumentNullException>(() => new X509Certificate2Collection(new X509Certificate2[] { c1, c2, null, c3 }));

                using (X509Certificate c4 = new X509Certificate())
                {
                    X509Certificate2Collection collection = new X509Certificate2Collection { c1, c2, c3 };
                    ((IList)collection).Add(c4); // Add non-X509Certificate2 object

                    Assert.Throws<InvalidCastException>(() => new X509Certificate2Collection(collection));
                }
            }
        }
Example #17
0
 public static void ExportAsSerializedCert_Unix()
 {
     using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate))
     {
         Assert.Throws<PlatformNotSupportedException>(() => c1.Export(X509ContentType.SerializedCert));
     }
 }
Example #18
0
        public static void X509CertificateCollectionEnumerator()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            using (X509Certificate2 c2 = new X509Certificate2())
            using (X509Certificate2 c3 = new X509Certificate2())
            {
                X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 });
                X509CertificateCollection.X509CertificateEnumerator e = cc.GetEnumerator();
                object ignored;

                // Not started
                Assert.Throws<InvalidOperationException>(() => ignored = e.Current);

                Assert.True(e.MoveNext());
                Assert.Same(c1, e.Current);

                Assert.True(e.MoveNext());
                Assert.Same(c2, e.Current);

                Assert.True(e.MoveNext());
                Assert.Same(c3, e.Current);

                Assert.False(e.MoveNext());
                Assert.False(e.MoveNext());
                Assert.False(e.MoveNext());
                Assert.False(e.MoveNext());
                Assert.False(e.MoveNext());

                // ended.
                Assert.Throws<InvalidOperationException>(() => ignored = e.Current);
            }
        }
Example #19
0
        public static void BuildChain()
        {
            using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
            using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
            using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
            using (var unrelated = new X509Certificate2(TestData.DssCer))
            {
                X509Chain chain = new X509Chain();

                chain.ChainPolicy.ExtraStore.Add(unrelated);
                chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
                chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;

                // Halfway between microsoftDotCom's NotBefore and NotAfter
                // This isn't a boundary condition test.
                chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

                bool valid = chain.Build(microsoftDotCom);
                Assert.True(valid, "Chain built validly");

                // The chain should have 3 members
                Assert.Equal(3, chain.ChainElements.Count);

                // These are the three specific members.
                Assert.Equal(microsoftDotCom, chain.ChainElements[0].Certificate);
                Assert.Equal(microsoftDotComIssuer, chain.ChainElements[1].Certificate);
                Assert.Equal(microsoftDotComRoot, chain.ChainElements[2].Certificate);
            }
        }
Example #20
0
 public static void TestImportNotSupported_X509Certificate2()
 {
     using (var c = new X509Certificate2())
     {
         VerifyImportNotSupported(c);
     }
 }
        internal static HashAlgorithm GetHashForChannelBinding(X509Certificate2 cert)
        {
            Oid signatureAlgorithm = cert.SignatureAlgorithm;
            switch (signatureAlgorithm.Value)
            {
                // RFC 5929 4.1 says that MD5 and SHA1 both upgrade to EvpSha256 for cbt calculation
                case "1.2.840.113549.2.5": // MD5
                case "1.2.840.113549.1.1.4": // MD5RSA
                case "1.3.14.3.2.26": // SHA1
                case "1.2.840.10040.4.3": // SHA1DSA
                case "1.2.840.10045.4.1": // SHA1ECDSA
                case "1.2.840.113549.1.1.5": // SHA1RSA
                case "2.16.840.1.101.3.4.2.1": // SHA256
                case "1.2.840.10045.4.3.2": // SHA256ECDSA
                case "1.2.840.113549.1.1.11": // SHA256RSA
                    return SHA256.Create();

                case "2.16.840.1.101.3.4.2.2": // SHA384
                case "1.2.840.10045.4.3.3": // SHA384ECDSA
                case "1.2.840.113549.1.1.12": // SHA384RSA
                    return SHA384.Create();

                case "2.16.840.1.101.3.4.2.3": // SHA512
                case "1.2.840.10045.4.3.4": // SHA512ECDSA
                case "1.2.840.113549.1.1.13": // SHA512RSA
                    return SHA512.Create();

                default:
                    throw new ArgumentException(signatureAlgorithm.Value);
            }
        }
Example #22
0
 public ImportedCollection(X509Certificate2Collection collection)
 {
     // Make an independent copy of the certs to dispose (in case the test mutates the collection after we return.)
     _certs = new X509Certificate2[collection.Count];
     collection.CopyTo(_certs, 0);
     Collection = collection;
 }
Example #23
0
	void CreateInstances()
		{
		bool res = false ; 
		string cd = Environment.CurrentDirectory + "\\" ; 
		X509Certificate2 real = null , fuzzed = null ; 
		string test = String.Empty ; 
		Result r = (Result) 0;
		string[] realFiles = GetFiles( cd , allCerts ) ;
		for( int i = 0 ; i < realFiles.Length ; i++ )
			{			
			string fileName = realFiles[i].ToUpper().Replace( cd.ToUpper() , String.Empty ) ; 
			string[] fuzzFiles = GetFiles( dir , fileName.Substring( 0 , fileName.IndexOf(".") ) + "-*.c*r*" ) ;
			try
				{
				real = new X509Certificate2( realFiles[i] ) ;
				}
			catch(Exception)
				{
				Console.WriteLine( realFiles[i] ) ; 
				break ; 
				}
			Console.WriteLine( "Going to test {0}" , realFiles[i] ) ; 
			for( int j = 0 ; j < fuzzFiles.Length ; j++ )
				{
				res= false ; 
				if( fuzzFiles[j].ToLower().IndexOf(".tmp" ) > 0 )
					{
					j++ ; 
					if( j == fuzzFiles.Length )
						break ; 
					}
				Console.WriteLine( "     with {0}" , fuzzFiles[j] ) ; 
				try
					{
					fuzzed = new X509Certificate2( fuzzFiles[j] ) ;
					fuzzed.Verify() ; 
					
					res = fuzzed.ToString(true).Equals(real.ToString(true)) ;
					r = res ? Result.Equals : Result.NotEquals ;
					test = fuzzFiles[i] + "    \n" ; 
					test += String.Format( "{0}\n\n!=\n\n{1}" , fuzzed.ToString(true),real.ToString(true) ) ;
					}
				catch(CryptographicException)
					{
					res = true ; 
					r = Result.CryptographicException ;
					}
				catch(Exception e)
					{
					Console.WriteLine(e) ; 
					r = Result.Exception ;
					}
				finally
					{
					Console.WriteLine( r ) ; 
					Eval( r!=Result.Exception , test ) ; 
					}
				}
			}
		}
Example #24
0
    private static void ValidateCertificate(X509Certificate2 certificate, StoreName storeName, StoreLocation storeLocation)
    {
        Assert.True(certificate != null, "Certificate is null");

        DateTime now = DateTime.Now;
        Assert.True(now > certificate.NotBefore,
                   String.Format("The current date {{0}} is earlier than NotBefore ({1})",
                                 now,
                                 certificate.NotBefore));

        Assert.True(now < certificate.NotAfter,
           String.Format("The current date {{0}} is later than NotAfter ({1})",
                         now,
                         certificate.NotAfter));

        using (X509Store store = new X509Store(storeName, storeLocation))
        {
            store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindByThumbprint, certificate.Thumbprint, validOnly: true);
            Assert.True(certificates.Count == 1,
                        String.Format("Did not find valid certificate with thumbprint {0} in StoreName '{1}', StoreLocation '{2}'",
                                      certificate.Thumbprint,
                                      storeName,
                                      storeLocation));
        }

        using (X509Store store = new X509Store(StoreName.Disallowed, storeLocation))
        {
            store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindByThumbprint, certificate.Thumbprint, validOnly: false);
            Assert.True(certificates.Count == 0, "Certificate was found in Disallowed store.");
        }
    }
            public static string Sign(string xml, X509Certificate2 certificate)
            {
                if (xml == null) throw new ArgumentNullException("xml");
                if (certificate == null) throw new ArgumentNullException("certificate");
                if (!certificate.HasPrivateKey) throw new ArgumentException("certificate", "Certificate should have a private key");

                XmlDocument doc = new XmlDocument();

                doc.PreserveWhitespace = true;
                doc.LoadXml(xml);

                SignedXml signedXml = new SignedXml(doc);
                signedXml.SigningKey = certificate.PrivateKey;

                // Attach certificate KeyInfo
                KeyInfoX509Data keyInfoData = new KeyInfoX509Data(certificate);
                KeyInfo keyInfo = new KeyInfo();
                keyInfo.AddClause(keyInfoData);
                signedXml.KeyInfo = keyInfo;

                // Attach transforms
                var reference = new Reference("");
                reference.AddTransform(new XmlDsigEnvelopedSignatureTransform(includeComments: false));
                reference.AddTransform(new XmlDsigExcC14NTransform(includeComments: false));
                signedXml.AddReference(reference);

                // Compute signature
                signedXml.ComputeSignature();
                var signatureElement = signedXml.GetXml();

                // Add signature to bundle
                doc.DocumentElement.AppendChild(doc.ImportNode(signatureElement, true));

                return doc.OuterXml;
            }
Example #26
0
 public static void TestGetFormat()
 {
     using (var c = new X509Certificate2(TestData.MsCertificate))
     {
         string format = c.GetFormat();
         Assert.Equal("X509", format);  // Only one format is supported so this is very predicatable api...
     }
 }
Example #27
0
 public static void TestGetKeyAlgorithm()
 {
     using (var c = new X509Certificate2(TestData.MsCertificate))
     {
         string keyAlgorithm = c.GetKeyAlgorithm();
         Assert.Equal("1.2.840.113549.1.1.1", keyAlgorithm);
     }
 }
Example #28
0
 public static void AddClosedThrows()
 {
     using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
     using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate))
     {
         Assert.ThrowsAny<CryptographicException>(() => store.Add(cert));
     }
 }
        public static void VerifyCrlCache()
        {
            string crlDirectory = PersistedFiles.GetUserFeatureDirectory("cryptography", "crls");
            string crlFile = Path.Combine(crlDirectory,MicrosoftDotComRootCrlFilename);

            Directory.CreateDirectory(crlDirectory);
            File.Delete(crlFile);

            using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
            using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
            using (var unrelated = new X509Certificate2(TestData.DssCer))
            {
                X509Chain chain = new X509Chain();

                chain.ChainPolicy.ExtraStore.Add(unrelated);
                chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
                
                // The very start of the CRL period.
                chain.ChainPolicy.VerificationTime = new DateTime(2015, 6, 17, 0, 0, 0, DateTimeKind.Utc);
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EndCertificateOnly;
                chain.ChainPolicy.VerificationFlags |= X509VerificationFlags.AllowUnknownCertificateAuthority;

                bool valid = chain.Build(microsoftDotComIssuer);
                Assert.True(valid, "Precondition: Chain builds with no revocation checks");

                int initialErrorCount = chain.ChainStatus.Length;
                Assert.InRange(initialErrorCount, 0, 1);

                if (initialErrorCount > 0)
                {
                    Assert.Equal(X509ChainStatusFlags.UntrustedRoot, chain.ChainStatus[0].Status);
                }

                chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;

                valid = chain.Build(microsoftDotComIssuer);
                Assert.False(valid, "Chain should not build validly");

                Assert.Equal(initialErrorCount + 1, chain.ChainStatus.Length);
                Assert.Equal(X509ChainStatusFlags.RevocationStatusUnknown, chain.ChainStatus[0].Status);

                File.WriteAllText(crlFile, MicrosoftDotComRootCrlPem, Encoding.ASCII);

                valid = chain.Build(microsoftDotComIssuer);
                Assert.True(valid, "Chain should build validly now");
                Assert.Equal(initialErrorCount, chain.ChainStatus.Length);

                // Rewind one second, the CRL is not "not yet valid"
                chain.ChainPolicy.VerificationTime = chain.ChainPolicy.VerificationTime.Subtract(TimeSpan.FromSeconds(1));

                valid = chain.Build(microsoftDotComIssuer);
                Assert.False(valid, "Chain should not build validly, CRL is not yet valid");

                Assert.Equal(initialErrorCount + 1, chain.ChainStatus.Length);
                Assert.Equal(X509ChainStatusFlags.RevocationStatusUnknown, chain.ChainStatus[0].Status);
            }
        }
Example #30
0
 public static void ExportAsCert()
 {
     using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate))
     {
         byte[] rawData = c1.Export(X509ContentType.Cert);
         Assert.Equal(X509ContentType.Cert, X509Certificate2.GetCertContentType(rawData));
         Assert.Equal(TestData.MsCertificate, rawData);
     }
 }
Example #31
0
 /// <summary>
 /// Instantiates a <see cref="SecurityKey"/> using a <see cref="X509Certificate2"/>
 /// </summary>
 /// <param name="certificate">The cert to use.</param>
 public X509SecurityKey(X509Certificate2 certificate)
 {
     _certificate = certificate ?? throw LogHelper.LogExceptionMessage(new ArgumentNullException(nameof(certificate)));
     KeyId        = Base64UrlEncoder.Encode(certificate.GetCertHash());
     X5t          = Base64UrlEncoder.Encode(certificate.GetCertHash());
 }
Example #32
0
 public void Use(string hostName, X509Certificate2 certificate)
 {
     _certs.AddOrUpdate(hostName, certificate, (_, __) => certificate);
 }
Example #33
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // CORS
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll",
                                  builder =>
                {
                    builder
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowAnyOrigin();
                }
                                  );
                var clientUrisRaw = Configuration.GetValue <string>("ClientUris");
                var clientUris    = clientUrisRaw.Split(",", StringSplitOptions.RemoveEmptyEntries);
                options.AddPolicy("Production",
                                  builder =>
                {
                    builder.WithOrigins(clientUris);
                }
                                  );
            });

            services.AddDbContext <WingedKeysContext>(options =>
                                                      options.UseSqlServer(WingedKeysConnectionString)
                                                      );

            // MVC
            services.AddMvc(option => option.EnableEndpointRouting = false);

            services.AddIdentity <ApplicationUser, IdentityRole>(config =>
            {
                config.SignIn.RequireConfirmedEmail = true;
                config.User.RequireUniqueEmail      = true;
                // Password requirements
                config.Password.RequireDigit           = false;
                config.Password.RequiredLength         = 6;
                config.Password.RequiredUniqueChars    = 1;
                config.Password.RequireLowercase       = false;
                config.Password.RequireNonAlphanumeric = false;
                config.Password.RequireUppercase       = false;
            })
            .AddEntityFrameworkStores <WingedKeysContext>()
            .AddDefaultTokenProviders();

            // Identity Server
            var identityServerServices = services
                                         .AddIdentityServer(options =>
            {
                var baseUri   = Configuration.GetValue <string>("BaseUri");
                var issuerUri = Configuration.GetValue <string>("IssuerUri");
                if (issuerUri != "")
                {
                    options.IssuerUri = issuerUri;
                }
                else
                {
                    options.PublicOrigin = baseUri;
                }

                if (Environment.IsDevelopment())
                {
                    IdentityModelEventSource.ShowPII = true;
                }
            })
                                         .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = b =>
                                             b.UseSqlServer(
                    WingedKeysConnectionString,
                    sql => sql.MigrationsAssembly(MigrationsAssembly)
                    );
            })
                                         // this adds the operational data from DB (codes, tokens, consents)
                                         .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = b =>
                                             b.UseSqlServer(
                    WingedKeysConnectionString,
                    sql => sql.MigrationsAssembly(MigrationsAssembly)
                    );

                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup = true;
            })
                                         .AddAspNetIdentity <ApplicationUser>();

            if (Environment.IsDevelopment())
            {
                identityServerServices.AddDeveloperSigningCredential();
            }
            else
            {
                var currentDirectory = Path.GetDirectoryName(
                    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
                    ).Replace("file:\\\\", "");
                var certificateFileName = Configuration.GetValue <string>("CertificateFileName");
                var certificatePath     = Path.Join(currentDirectory, certificateFileName);
                var certificatePassword = Configuration.GetValue <string>("CertificatePassword");
                var certificate         = new X509Certificate2(certificateFileName, certificatePassword, X509KeyStorageFlags.MachineKeySet);
                identityServerServices.AddSigningCredential(certificate);
            }

            services.AddAuthentication();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("AdminOnly", policy =>
                                  policy.RequireClaim("role", "admin"));
            });
        }
Example #34
0
        /// <summary>
        /// Ensures that the application configuration is valid.
        /// </summary>
        /// <param name="applicationType">Type of the application.</param>
        public virtual void Validate(ApplicationType applicationType)
        {
            if (String.IsNullOrEmpty(ApplicationName))
            {
                throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ApplicationName must be specified.");
            }

#if !SILVERLIGHT
            if (SecurityConfiguration == null)
            {
                throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "SecurityConfiguration must be specified.");
            }

            SecurityConfiguration.Validate();

            // ensure application uri matches the certificate.
            X509Certificate2 certificate = SecurityConfiguration.ApplicationCertificate.LoadPrivateKey(null);

            if (certificate != null)
            {
                ApplicationUri = Utils.GetApplicationUriFromCertficate(certificate);
            }
#endif

            //  generate a default uri.
            if (String.IsNullOrEmpty(ApplicationUri))
            {
                StringBuilder buffer = new StringBuilder();

                buffer.Append("urn:");
                buffer.Append(System.Net.Dns.GetHostName());
                buffer.Append(":");
                buffer.Append(ApplicationName);

                m_applicationUri = buffer.ToString();
            }

            if (applicationType == ApplicationType.Client || applicationType == ApplicationType.ClientAndServer)
            {
                if (ClientConfiguration == null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ClientConfiguration must be specified.");
                }

                ClientConfiguration.Validate();
            }

            if (applicationType == ApplicationType.Server || applicationType == ApplicationType.ClientAndServer)
            {
                if (ServerConfiguration == null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ServerConfiguration must be specified.");
                }

                ServerConfiguration.Validate();
            }

            if (applicationType == ApplicationType.DiscoveryServer)
            {
                if (DiscoveryServerConfiguration == null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "DiscoveryServerConfiguration must be specified.");
                }

                DiscoveryServerConfiguration.Validate();
            }

            // toggle the state of the hi-res clock.
            HiResClock.Disabled = m_disableHiResClock;

            if (m_disableHiResClock)
            {
                if (m_serverConfiguration != null)
                {
                    if (m_serverConfiguration.PublishingResolution < 50)
                    {
                        m_serverConfiguration.PublishingResolution = 50;
                    }
                }
            }

            #if !SILVERLIGHT
            // create the certificate validator.
            m_certificateValidator = new CertificateValidator();
            m_certificateValidator.Update(this.SecurityConfiguration);
            #endif
        }
Example #35
0
        internal static Signature SignFile(SigningOption option,
                                           string fileName,
                                           X509Certificate2 certificate,
                                           string timeStampServerUrl,
                                           string hashAlgorithm)
        {
            bool      result    = false;
            Signature signature = null;
            IntPtr    pSignInfo = IntPtr.Zero;
            DWORD     error     = 0;
            string    hashOid   = null;

            Utils.CheckArgForNullOrEmpty(fileName, "fileName");
            Utils.CheckArgForNull(certificate, "certificate");

            // If given, TimeStamp server URLs must begin with http://
            if (!String.IsNullOrEmpty(timeStampServerUrl))
            {
                if ((timeStampServerUrl.Length <= 7) ||
                    (timeStampServerUrl.IndexOf("http://", StringComparison.OrdinalIgnoreCase) != 0))
                {
                    throw PSTraceSource.NewArgumentException(
                              "certificate",
                              Authenticode.TimeStampUrlRequired);
                }
            }

            // Validate that the hash algorithm is valid
            if (!String.IsNullOrEmpty(hashAlgorithm))
            {
                IntPtr intptrAlgorithm = Marshal.StringToHGlobalUni(hashAlgorithm);

                IntPtr oidPtr = NativeMethods.CryptFindOIDInfo(NativeConstants.CRYPT_OID_INFO_NAME_KEY,
                                                               intptrAlgorithm,
                                                               0);


                // If we couldn't find an OID for the hash
                // algorithm, it was invalid.
                if (oidPtr == IntPtr.Zero)
                {
                    throw PSTraceSource.NewArgumentException(
                              "certificate",
                              Authenticode.InvalidHashAlgorithm);
                }
                else
                {
                    NativeMethods.CRYPT_OID_INFO oidInfo =
                        Marshal.PtrToStructure <NativeMethods.CRYPT_OID_INFO>(oidPtr);

                    hashOid = oidInfo.pszOID;
                }
            }

            if (!SecuritySupport.CertIsGoodForSigning(certificate))
            {
                throw PSTraceSource.NewArgumentException(
                          "certificate",
                          Authenticode.CertNotGoodForSigning);
            }

            SecuritySupport.CheckIfFileExists(fileName);
            //SecurityUtils.CheckIfFileSmallerThan4Bytes(fileName);

            try
            {
                // CryptUI is not documented either way, but does not
                // support empty strings for the timestamp server URL.
                // It expects null, only.  Instead, it randomly AVs if you
                // try.
                string timeStampServerUrlForCryptUI = null;
                if (!String.IsNullOrEmpty(timeStampServerUrl))
                {
                    timeStampServerUrlForCryptUI = timeStampServerUrl;
                }

                //
                // first initialize the struct to pass to
                // CryptUIWizDigitalSign() function
                //
                NativeMethods.CRYPTUI_WIZ_DIGITAL_SIGN_INFO si = NativeMethods.InitSignInfoStruct(fileName,
                                                                                                  certificate,
                                                                                                  timeStampServerUrlForCryptUI,
                                                                                                  hashOid,
                                                                                                  option);

                pSignInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(si));
                Marshal.StructureToPtr(si, pSignInfo, false);

                //
                // sign the file
                //
                // The GetLastWin32Error of this is checked, but PreSharp doesn't seem to be
                // able to see that.
#pragma warning disable 56523
                result = NativeMethods.CryptUIWizDigitalSign(
                    (DWORD)NativeMethods.CryptUIFlags.CRYPTUI_WIZ_NO_UI,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    pSignInfo,
                    IntPtr.Zero);
#pragma warning enable 56523

                if (si.pSignExtInfo != null)
                {
                    Marshal.DestroyStructure <NativeMethods.CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO>(si.pSignExtInfo);
                    Marshal.FreeCoTaskMem(si.pSignExtInfo);
                }

                if (!result)
                {
                    error = GetLastWin32Error();

                    //
                    // ISSUE-2004/05/08-kumarp : there seems to be a bug
                    // in CryptUIWizDigitalSign().
                    // It returns 80004005 or 80070001
                    // but it signs the file correctly. Mask this error
                    // till we figure out this odd behavior.
                    //
                    if ((error == 0x80004005) ||
                        (error == 0x80070001) ||

                        // CryptUIWizDigitalSign introduced a breaking change in Win8 to return this
                        // error code (ERROR_INTERNET_NAME_NOT_RESOLVED) when you provide an invalid
                        // timestamp server. It used to be 0x80070001.
                        // Also masking this out so that we don't introduce a breaking change ourselves.
                        (error == 0x80072EE7)
                        )
                    {
                        result = true;
                    }
                    else
                    {
                        if (error == Win32Errors.NTE_BAD_ALGID)
                        {
                            throw PSTraceSource.NewArgumentException(
                                      "certificate",
                                      Authenticode.InvalidHashAlgorithm);
                        }

                        s_tracer.TraceError("CryptUIWizDigitalSign: failed: {0:x}",
                                            error);
                    }
                }

                if (result)
                {
                    signature = GetSignature(fileName, null);
                }
                else
                {
                    signature = new Signature(fileName, (DWORD)error);
                }
            }
            finally
            {
                Marshal.DestroyStructure <NativeMethods.CRYPTUI_WIZ_DIGITAL_SIGN_INFO>(pSignInfo);
                Marshal.FreeCoTaskMem(pSignInfo);
            }

            return(signature);
        }
Example #36
0
        /// <summary>
        /// Accepts SAML Response, serializes it to XML and signs using the supplied certificate
        /// </summary>
        /// <param name="Response">SAML 2.0 Response</param>
        /// <param name="SigningCert">X509 certificate</param>
        /// <returns>XML Document with computed signature</returns>
        private static XmlDocument SerializeAndSignSAMLResponse(ResponseType Response, X509Certificate2 SigningCert)
        {
            // Set serializer and writers for action
            XmlSerializer responseSerializer = new XmlSerializer(Response.GetType());
            StringWriter  stringWriter       = new StringWriter();
            XmlWriter     responseWriter     = XmlTextWriter.Create(stringWriter, new XmlWriterSettings()
            {
                OmitXmlDeclaration = true, Indent = true, Encoding = Encoding.UTF8
            });

            responseSerializer.Serialize(responseWriter, Response);
            responseWriter.Close();
            XmlDocument xmlResponse = new XmlDocument();

            xmlResponse.LoadXml(stringWriter.ToString());

            // Set the namespace for prettire and more consistent XML
            XmlNamespaceManager ns = new XmlNamespaceManager(xmlResponse.NameTable);

            ns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");

            CertificateUtility.AppendSignatureToXMLDocument(ref xmlResponse, ((AssertionType)Response.Items[0]).ID, SigningCert);

            return(xmlResponse);
        }
        public async Task ValidateMergeCertificate()
        {
            string serverCertificateName = Recording.GenerateId();

            // Generate the request.
            CertificatePolicy policy = new CertificatePolicy(WellKnownIssuerNames.Unknown, "CN=Azure SDK")
            {
                CertificateTransparency = false,
                ContentType             = CertificateContentType.Pkcs12,
            };

            CertificateOperation operation = await Client.StartCreateCertificateAsync(serverCertificateName, policy);

            RegisterForCleanup(serverCertificateName);
            await using IAsyncDisposable disposableOperation = EnsureDeleted(operation);

            // Read the CA.
            byte[]           caCertificateBytes = Convert.FromBase64String(CaPublicKeyBase64);
            X509Certificate2 caCertificate      = new X509Certificate2(caCertificateBytes);

            // Read CA private key since getting it from caCertificate above throws.
            AsymmetricCipherKeyPair caPrivateKey;

            using (StringReader caPrivateKeyReader = new StringReader(CaPrivateKeyPem))
            {
                Org.BouncyCastle.OpenSsl.PemReader reader = new Org.BouncyCastle.OpenSsl.PemReader(caPrivateKeyReader);
                caPrivateKey = (AsymmetricCipherKeyPair)reader.ReadObject();
            }

            // Read the CSR.
            Pkcs10CertificationRequest csr     = new Pkcs10CertificationRequest(operation.Properties.Csr);
            CertificationRequestInfo   csrInfo = csr.GetCertificationRequestInfo();

            // Parse the issuer subject name.
            Hashtable oidLookup = new Hashtable(X509Name.DefaultLookup)
            {
                { "s", new DerObjectIdentifier("2.5.4.8") },
            };

            X509Name issuerName = new X509Name(true, oidLookup, caCertificate.Subject);

            // Sign the request.
            X509V3CertificateGenerator generator = new X509V3CertificateGenerator();

            generator.SetIssuerDN(issuerName);
            generator.SetSerialNumber(BigInteger.One);
            generator.SetNotBefore(DateTime.Now);
            generator.SetNotAfter(DateTime.Now.AddDays(1));
            generator.SetSubjectDN(csrInfo.Subject);
            generator.SetPublicKey(csr.GetPublicKey());

            Asn1SignatureFactory signatureFactory      = new Asn1SignatureFactory("SHA256WITHRSA", caPrivateKey.Private);
            X509Certificate      serverSignedPublicKey = generator.Generate(signatureFactory);

            // Merge the certificate chain.
            MergeCertificateOptions       options = new MergeCertificateOptions(serverCertificateName, new[] { serverSignedPublicKey.GetEncoded(), caCertificateBytes });
            KeyVaultCertificateWithPolicy mergedServerCertificate = await Client.MergeCertificateAsync(options);

            X509Certificate2 serverCertificate = new X509Certificate2(mergedServerCertificate.Cer);

            Assert.AreEqual(csrInfo.Subject.ToString(), serverCertificate.Subject);
            Assert.AreEqual(serverCertificateName, mergedServerCertificate.Name);

            KeyVaultCertificateWithPolicy completedServerCertificate = await WaitForCompletion(operation);

            Assert.AreEqual(mergedServerCertificate.Name, completedServerCertificate.Name);
            CollectionAssert.AreEqual(mergedServerCertificate.Cer, completedServerCertificate.Cer);
        }
Example #38
0
        /// <summary>
        /// Displays the dialog.
        /// </summary>
        public bool ShowDialog(CertificateIdentifier certificate)
        {
            m_certificate = certificate;

            CertificateStoreCTRL.StoreType = null;
            CertificateStoreCTRL.StorePath = null;
            CertificateStoreCTRL.ReadOnly  = true;
            ApplicationNameTB.Text         = null;
            ApplicationUriTB.Text          = null;
            OrganizationTB.Text            = null;
            DomainsTB.Text     = System.Net.Dns.GetHostName();
            SubjectNameTB.Text = null;
            IssuerNameTB.Text  = null;
            ValidFromTB.Text   = null;
            ValidToTB.Text     = null;
            ThumbprintTB.Text  = null;

            if (certificate != null)
            {
                CertificateStoreCTRL.StoreType = certificate.StoreType;
                CertificateStoreCTRL.StorePath = certificate.StorePath;
                SubjectNameTB.Text             = certificate.SubjectName;
                ThumbprintTB.Text = certificate.Thumbprint;

                X509Certificate2 data = certificate.Find();

                if (data != null)
                {
                    // fill in subject name.
                    StringBuilder buffer = new StringBuilder();

                    foreach (string element in Utils.ParseDistinguishedName(data.Subject))
                    {
                        if (element.StartsWith("CN="))
                        {
                            ApplicationNameTB.Text = element.Substring(3);
                        }

                        if (element.StartsWith("O="))
                        {
                            OrganizationTB.Text = element.Substring(2);
                        }

                        if (buffer.Length > 0)
                        {
                            buffer.Append('/');
                        }

                        buffer.Append(element);
                    }

                    if (buffer.Length > 0)
                    {
                        SubjectNameTB.Text = buffer.ToString();
                    }

                    // fill in issuer name.
                    buffer = new StringBuilder();

                    foreach (string element in Utils.ParseDistinguishedName(data.Issuer))
                    {
                        if (buffer.Length > 0)
                        {
                            buffer.Append('/');
                        }

                        buffer.Append(element);
                    }

                    if (buffer.Length > 0)
                    {
                        IssuerNameTB.Text = buffer.ToString();
                    }

                    // fill in application uri.
                    string applicationUri = Utils.GetApplicationUriFromCertficate(data);

                    if (!String.IsNullOrEmpty(applicationUri))
                    {
                        ApplicationUriTB.Text = applicationUri;
                    }

                    // fill in domains.
                    buffer = new StringBuilder();

                    foreach (string domain in Utils.GetDomainsFromCertficate(data))
                    {
                        if (buffer.Length > 0)
                        {
                            buffer.Append(", ");
                        }

                        buffer.Append(domain);
                    }

                    if (buffer.Length > 0)
                    {
                        DomainsTB.Text = buffer.ToString();
                    }

                    ValidFromTB.Text  = data.NotBefore.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss");
                    ValidToTB.Text    = data.NotAfter.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss");
                    ThumbprintTB.Text = data.Thumbprint;
                }
            }

            if (ShowDialog() != DialogResult.OK)
            {
                return(false);
            }

            return(true);
        }
Example #39
0
        private void ExportBTN_Click(object sender, EventArgs e)
        {
            try
            {
                const string caption = "Export Certificate";

                if (m_currentDirectory == null)
                {
                    m_currentDirectory = Utils.GetAbsoluteDirectoryPath("%LocalApplicationData%", false, false, false);
                }

                if (m_currentDirectory == null)
                {
                    m_currentDirectory = Environment.CurrentDirectory;
                }

                X509Certificate2 certificate = m_certificate.Find();

                if (certificate == null)
                {
                    MessageBox.Show("Cannot export an invalid certificate.", caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                string displayName = null;

                foreach (string element in Utils.ParseDistinguishedName(certificate.Subject))
                {
                    if (element.StartsWith("CN="))
                    {
                        displayName = element.Substring(3);
                        break;
                    }
                }

                StringBuilder filePath = new StringBuilder();

                if (!String.IsNullOrEmpty(displayName))
                {
                    filePath.Append(displayName);
                    filePath.Append(" ");
                }

                filePath.Append("[");
                filePath.Append(certificate.Thumbprint);
                filePath.Append("].der");

                SaveFileDialog dialog = new SaveFileDialog();

                dialog.CheckFileExists  = false;
                dialog.CheckPathExists  = true;
                dialog.DefaultExt       = ".der";
                dialog.Filter           = "Certificate Files (*.der)|*.der|All Files (*.*)|*.*";
                dialog.ValidateNames    = true;
                dialog.Title            = "Save Certificate File";
                dialog.FileName         = filePath.ToString();
                dialog.InitialDirectory = m_currentDirectory;

                if (dialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                FileInfo fileInfo = new FileInfo(dialog.FileName);
                m_currentDirectory = fileInfo.DirectoryName;

                // save the file.
                using (Stream ostrm = fileInfo.Open(FileMode.Create, FileAccess.ReadWrite, FileShare.None))
                {
                    byte[] data = certificate.RawData;
                    ostrm.Write(data, 0, data.Length);
                }
            }
            catch (Exception exception)
            {
                GuiUtils.HandleException(this.Text, System.Reflection.MethodBase.GetCurrentMethod(), exception);
            }
        }
Example #40
0
        // Receive the authentication request from the service provider.
        private void ReceiveAuthnRequest(out AuthnRequest authnRequest, out string relayState)
        {
            // Determine the service provider to identity provider binding type.
            // We use a query string parameter rather than having separate endpoints per binding.
            string bindingType = Request.QueryString[bindingQueryParameter];

            Trace.Write("IdP", "Receiving authentication request over binding " + bindingType);

            // Receive the authentication request.
            XmlElement authnRequestXml = null;

            switch (bindingType)
            {
            case SAMLIdentifiers.BindingURIs.HTTPRedirect:
                bool             signed          = false;
                X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPX509Certificate];

                IdentityProvider.ReceiveAuthnRequestByHTTPRedirect(Request, out authnRequestXml, out relayState, out signed, x509Certificate.PublicKey.Key);
                break;

            case SAMLIdentifiers.BindingURIs.HTTPPost:
                IdentityProvider.ReceiveAuthnRequestByHTTPPost(Request, out authnRequestXml, out relayState);
                break;

            case SAMLIdentifiers.BindingURIs.HTTPArtifact:
                // Receive the artifact.
                HTTPArtifact httpArtifact = null;

                IdentityProvider.ReceiveArtifactByHTTPArtifact(Request, false, out httpArtifact, out relayState);

                // Create an artifact resolve request.
                ArtifactResolve artifactResolve = new ArtifactResolve();
                artifactResolve.Issuer   = new Issuer(CreateAbsoluteURL("~/"));
                artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                XmlElement artifactResolveXml = artifactResolve.ToXml();

                // Send the artifact resolve request and receive the artifact response.
                string spArtifactResponderURL = WebConfigurationManager.AppSettings["spArtifactResponderURL"];

                XmlElement artifactResponseXml = ArtifactResolver.SendRequestReceiveResponse(spArtifactResponderURL, artifactResolveXml);

                ArtifactResponse artifactResponse = new ArtifactResponse(artifactResponseXml);

                // Extract the authentication request from the artifact response.
                authnRequestXml = artifactResponse.SAMLMessage;
                break;

            default:
                throw new ArgumentException("Invalid service provider to identity provider binding");
            }

            // If using HTTP redirect the message isn't signed as the generated query string is too long for most browsers.
            if (bindingType != SAMLIdentifiers.BindingURIs.HTTPRedirect)
            {
                if (SAMLMessageSignature.IsSigned(authnRequestXml))
                {
                    // Verify the request's signature.
                    X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPX509Certificate];

                    if (!SAMLMessageSignature.Verify(authnRequestXml, x509Certificate))
                    {
                        throw new ArgumentException("The authentication request signature failed to verify.");
                    }
                }
            }

            // Deserialize the XML.
            authnRequest = new AuthnRequest(authnRequestXml);

            Trace.Write("IdP", "Received authentication request");
        }
Example #41
0
 public static IServiceCollection AddConsulServices(this IServiceCollection self, string encryptedAclTokenKey, X509Certificate2 encryptionCertifcate, RSAEncryptionPadding padding)
 {
     self.AddSingleton <IConsulAclProvider>(new EncryptedConsulKeyAclProvider(encryptedAclTokenKey, encryptionCertifcate, padding));
     return(self.AddConsulServices());
 }
Example #42
0
 public SignDSL Using(X509Certificate2 certificate)
 {
     _parameters.SignatureCertificate = certificate;
     return(this);
 }
Example #43
0
 public void GetReady()
 {
     m_serverCert = new X509Certificate2(m_serverCertRaw, "server");
     m_clientCert = new X509Certificate2(m_clientCertRaw, "client");
 }
 public SslSettings()
 {
     Certificate = null;
     SuppressValidation = false;
 }
Example #45
0
        private void SetupIdentity(IServiceCollection services)
        {
            var isDemo = bool.Parse(Configuration["DemoSiteMode"]);

            // Identity options.
            services.Configure <IdentityOptions>(options =>
            {
                // Password settings.
                if (isDemo)
                {
                    options.Password.RequireDigit           = false;
                    options.Password.RequireNonAlphanumeric = false;
                    options.Password.RequireUppercase       = false;
                    options.Password.RequireLowercase       = false;
                }
                else
                {
                    options.Password.RequireDigit           = true;
                    options.Password.RequireNonAlphanumeric = true;
                    options.Password.RequireUppercase       = true;
                    options.Password.RequireLowercase       = true;
                }

                options.Password.RequiredLength = 8;
                options.User.RequireUniqueEmail = true;
            });

            var accessTokenLifetime  = int.Parse(Configuration["AccessTokenLifetime"]);
            var refreshTokenLifetime = int.Parse(Configuration["RefreshTokenLifetime"]);

            if (isDemo)
            {
                services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryClients(Config.GetClients(accessTokenLifetime, refreshTokenLifetime))
                .AddAspNetIdentity <ApplicationUser>()
                .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>()
                .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
            }
            else
            {
                var cert = new X509Certificate2("coraltime.pfx", "", X509KeyStorageFlags.MachineKeySet);

                services.AddIdentityServer()
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryClients(Config.GetClients(accessTokenLifetime, refreshTokenLifetime))
                .AddAspNetIdentity <ApplicationUser>()
                .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>()
                .AddSigningCredential(cert).AddAppAuthRedirectUriValidator()
                .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
            }

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = "Bearer";
                options.DefaultChallengeScheme    = "Bearer";
                options.DefaultForbidScheme       = "Identity.Application";
            }).AddJwtBearer(options =>
            {
                // name of the API resource
                options.Audience             = "WebAPI";
                options.Authority            = Configuration["Authority"];
                options.RequireHttpsMetadata = false;
            });

            services.AddAuthorization(options =>
            {
                Config.CreateAuthorizatoinOptions(options);
            });
        }
Example #46
0
        public async Task ConnectAsync(string host, int port, string scheme, X509Certificate2 clientCertificate, TimeSpan timeout)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, scheme, timeout, $"{nameof(IotHubClientWebSocket)}.{nameof(ConnectAsync)}");
            }

            this.host = host;
            bool succeeded = false;

            try
            {
                // Connect without proxy
                this.TcpClient = new TcpClient();
                await this.TcpClient.ConnectAsync(host, port).ConfigureAwait(false);

                if (string.Equals(WebSocketConstants.Scheme, scheme, StringComparison.OrdinalIgnoreCase))
                {
                    // In the real world, web-socket will happen over HTTPS
                    var sslStream = new SslStream(this.TcpClient.GetStream(), false, IotHubConnection.OnRemoteCertificateValidation);
                    var x509CertificateCollection = new X509Certificate2Collection();
                    if (clientCertificate != null)
                    {
                        x509CertificateCollection.Add(clientCertificate);
                    }

                    await sslStream.AuthenticateAsClientAsync(host, x509CertificateCollection, enabledSslProtocols : SslProtocols.Tls11 | SslProtocols.Tls12, checkCertificateRevocation : false).ConfigureAwait(false);

                    this.WebSocketStream = sslStream;
                }
                else
                {
                    this.WebSocketStream = this.TcpClient.GetStream();
                }

                var    upgradeRequest      = this.BuildUpgradeRequest();
                byte[] upgradeRequestBytes = Encoding.ASCII.GetBytes(upgradeRequest);

                this.TcpClient.Client.SendTimeout = GetSocketTimeoutInMilliSeconds(timeout);

                // Send WebSocket Upgrade request
                await this.WebSocketStream.WriteAsync(upgradeRequestBytes, 0, upgradeRequestBytes.Length).ConfigureAwait(false);

                // receive WebSocket Upgrade response
                var responseBuffer = new byte[8 * 1024];

                var upgradeResponse = new HttpResponse(this.TcpClient, this.WebSocketStream, responseBuffer);

                await upgradeResponse.ReadAsync(timeout).ConfigureAwait(false);

                if (upgradeResponse.StatusCode != HttpStatusCode.SwitchingProtocols)
                {
                    // the HTTP response code was not 101
                    if (this.TcpClient.Connected)
                    {
#if !NETSTANDARD1_3
                        this.WebSocketStream.Close();
                        this.TcpClient.Close();
#else
                        this.WebSocketStream.Dispose();
                        this.TcpClient.Dispose();
#endif
                    }

                    throw new IOException(ServerRejectedUpgradeRequest + " " + upgradeResponse);
                }

                if (!this.VerifyWebSocketUpgradeResponse(upgradeResponse.Headers))
                {
                    if (this.TcpClient.Connected)
                    {
#if !NETSTANDARD1_3
                        this.WebSocketStream.Close();
                        this.TcpClient.Close();
#else
                        this.WebSocketStream.Dispose();
                        this.TcpClient.Dispose();
#endif
                    }

                    throw new IOException(UpgradeProtocolNotSupported.FormatInvariant(WebSocketConstants.SubProtocols.Amqpwsb10));
                }

                this.State = WebSocketState.Open;
                succeeded  = true;
            }
            finally
            {
                if (!succeeded)
                {
                    this.Abort();
                }
                if (Logging.IsEnabled)
                {
                    Logging.Exit(this, scheme, timeout, $"{nameof(IotHubClientWebSocket)}.{nameof(ConnectAsync)}");
                }
            }
        }
Example #47
0
 protected virtual X509Principal CreateX509Principal(X509Certificate2 certificate)
 {
     return(new X509Principal(new X509CertificateIdentity(certificate, this.sslStream.IsRemoteCertificateValid)));
 }
Example #48
0
        private static bool TryGetProviderSigner(IntPtr wvtStateData, out IntPtr pProvSigner, out X509Certificate2 timestamperCert)
        {
            pProvSigner     = IntPtr.Zero;
            timestamperCert = null;

            // The GetLastWin32Error of this is checked, but PreSharp doesn't seem to be
            // able to see that.
#pragma warning disable 56523
            IntPtr pProvData =
                NativeMethods.WTHelperProvDataFromStateData(wvtStateData);
#pragma warning enable 56523

            if (pProvData != IntPtr.Zero)
            {
                pProvSigner =
                    NativeMethods.WTHelperGetProvSignerFromChain(pProvData, 0, 0, 0);

                if (pProvSigner != IntPtr.Zero)
                {
                    NativeMethods.CRYPT_PROVIDER_SGNR provSigner =
                        (NativeMethods.CRYPT_PROVIDER_SGNR)
                        Marshal.PtrToStructure <NativeMethods.CRYPT_PROVIDER_SGNR>(pProvSigner);
                    if (provSigner.csCounterSigners == 1)
                    {
                        //
                        // time stamper cert available
                        //
                        timestamperCert = GetCertFromChain(provSigner.pasCounterSigners);
                    }

                    return(true);
                }
            }

            return(false);
        }
Example #49
0
        static void Main(string[] args)
        {
            Console.WriteLine("SIPSorcery user agent server example.");
            Console.WriteLine("Press h to hangup a call or ctrl-c to exit.");

            Log = AddConsoleLogger();

            IPAddress listenAddress     = IPAddress.Any;
            IPAddress listenIPv6Address = IPAddress.IPv6Any;

            if (args != null && args.Length > 0)
            {
                if (!IPAddress.TryParse(args[0], out var customListenAddress))
                {
                    Log.LogWarning($"Command line argument could not be parsed as an IP address \"{args[0]}\"");
                    listenAddress = IPAddress.Any;
                }
                else
                {
                    if (customListenAddress.AddressFamily == AddressFamily.InterNetwork)
                    {
                        listenAddress = customListenAddress;
                    }
                    if (customListenAddress.AddressFamily == AddressFamily.InterNetworkV6)
                    {
                        listenIPv6Address = customListenAddress;
                    }
                }
            }

            // Set up a default SIP transport.
            var sipTransport = new SIPTransport();

            var localhostCertificate = new X509Certificate2(SIPS_CERTIFICATE_PATH);

            // IPv4 channels.
            sipTransport.AddSIPChannel(new SIPUDPChannel(new IPEndPoint(listenAddress, SIP_LISTEN_PORT)));
            sipTransport.AddSIPChannel(new SIPTCPChannel(new IPEndPoint(listenAddress, SIP_LISTEN_PORT)));
            sipTransport.AddSIPChannel(new SIPTLSChannel(localhostCertificate, new IPEndPoint(listenAddress, SIPS_LISTEN_PORT)));
            //sipTransport.AddSIPChannel(new SIPWebSocketChannel(IPAddress.Any, SIP_WEBSOCKET_LISTEN_PORT));
            //sipTransport.AddSIPChannel(new SIPWebSocketChannel(IPAddress.Any, SIP_SECURE_WEBSOCKET_LISTEN_PORT, localhostCertificate));

            // IPv6 channels.
            sipTransport.AddSIPChannel(new SIPUDPChannel(new IPEndPoint(listenIPv6Address, SIP_LISTEN_PORT)));
            sipTransport.AddSIPChannel(new SIPTCPChannel(new IPEndPoint(listenIPv6Address, SIP_LISTEN_PORT)));
            sipTransport.AddSIPChannel(new SIPTLSChannel(localhostCertificate, new IPEndPoint(listenIPv6Address, SIPS_LISTEN_PORT)));
            //sipTransport.AddSIPChannel(new SIPWebSocketChannel(IPAddress.IPv6Any, SIP_WEBSOCKET_LISTEN_PORT));
            //sipTransport.AddSIPChannel(new SIPWebSocketChannel(IPAddress.IPv6Any, SIP_SECURE_WEBSOCKET_LISTEN_PORT, localhostCertificate));

            EnableTraceLogs(sipTransport);

            string executableDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            // To keep things a bit simpler this example only supports a single call at a time and the SIP server user agent
            // acts as a singleton
            SIPServerUserAgent      uas        = null;
            CancellationTokenSource rtpCts     = null; // Cancellation token to stop the RTP stream.
            VoIPMediaSession        rtpSession = null;

            // Because this is a server user agent the SIP transport must start listening for client user agents.
            sipTransport.SIPTransportRequestReceived += async(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPRequest sipRequest) =>
            {
                try
                {
                    if (sipRequest.Method == SIPMethodsEnum.INVITE)
                    {
                        Log.LogInformation($"Incoming call request: {localSIPEndPoint}<-{remoteEndPoint} {sipRequest.URI}.");

                        // Check there's a codec we support in the INVITE offer.
                        var        offerSdp       = SDP.ParseSDPDescription(sipRequest.Body);
                        IPEndPoint dstRtpEndPoint = SDP.GetSDPRTPEndPoint(sipRequest.Body);

                        if (offerSdp.Media.Any(x => x.Media == SDPMediaTypesEnum.audio && x.HasMediaFormat((int)SDPMediaFormatsEnum.PCMU)))
                        {
                            Log.LogDebug($"Client offer contained PCMU audio codec.");
                            AudioExtrasSource extrasSource = new AudioExtrasSource(new AudioEncoder(), new AudioSourceOptions {
                                AudioSource = AudioSourcesEnum.Music
                            });
                            rtpSession = new VoIPMediaSession(new MediaEndPoints {
                                AudioSource = extrasSource
                            });
                            rtpSession.AcceptRtpFromAny = true;

                            var setResult = rtpSession.SetRemoteDescription(SdpType.offer, offerSdp);

                            if (setResult != SetDescriptionResultEnum.OK)
                            {
                                // Didn't get a match on the codecs we support.
                                SIPResponse noMatchingCodecResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.NotAcceptableHere, setResult.ToString());
                                await sipTransport.SendResponseAsync(noMatchingCodecResponse);
                            }
                            else
                            {
                                // If there's already a call in progress hang it up. Of course this is not ideal for a real softphone or server but it
                                // means this example can be kept simpler.
                                if (uas?.IsHungup == false)
                                {
                                    uas?.Hangup(false);
                                }
                                rtpCts?.Cancel();
                                rtpCts = new CancellationTokenSource();

                                UASInviteTransaction uasTransaction = new UASInviteTransaction(sipTransport, sipRequest, null);
                                uas = new SIPServerUserAgent(sipTransport, null, null, null, SIPCallDirection.In, null, null, uasTransaction);
                                uas.CallCancelled += (uasAgent) =>
                                {
                                    rtpCts?.Cancel();
                                    rtpSession.Close(null);
                                };
                                rtpSession.OnRtpClosed += (reason) => uas?.Hangup(false);
                                uas.Progress(SIPResponseStatusCodesEnum.Trying, null, null, null, null);
                                await Task.Delay(100);

                                uas.Progress(SIPResponseStatusCodesEnum.Ringing, null, null, null, null);
                                await Task.Delay(100);

                                var answerSdp = rtpSession.CreateAnswer(null);
                                uas.Answer(SDP.SDP_MIME_CONTENTTYPE, answerSdp.ToString(), null, SIPDialogueTransferModesEnum.NotAllowed);

                                await rtpSession.Start();
                            }
                        }
                    }
                    else if (sipRequest.Method == SIPMethodsEnum.BYE)
                    {
                        Log.LogInformation("Call hungup.");
                        SIPResponse byeResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                        await sipTransport.SendResponseAsync(byeResponse);

                        uas?.Hangup(true);
                        rtpSession?.Close(null);
                        rtpCts?.Cancel();
                    }
                    else if (sipRequest.Method == SIPMethodsEnum.SUBSCRIBE)
                    {
                        SIPResponse notAllowededResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.MethodNotAllowed, null);
                        await sipTransport.SendResponseAsync(notAllowededResponse);
                    }
                    else if (sipRequest.Method == SIPMethodsEnum.OPTIONS || sipRequest.Method == SIPMethodsEnum.REGISTER)
                    {
                        SIPResponse optionsResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                        await sipTransport.SendResponseAsync(optionsResponse);
                    }
                }
                catch (Exception reqExcp)
                {
                    Log.LogWarning($"Exception handling {sipRequest.Method}. {reqExcp.Message}");
                }
            };

            ManualResetEvent exitMre = new ManualResetEvent(false);

            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                e.Cancel = true;

                Log.LogInformation("Exiting...");

                Hangup(uas).Wait();

                rtpSession?.Close(null);
                rtpCts?.Cancel();

                if (sipTransport != null)
                {
                    Log.LogInformation("Shutting down SIP transport...");
                    sipTransport.Shutdown();
                }

                exitMre.Set();
            };

            // Task to handle user key presses.
            Task.Run(() =>
            {
                try
                {
                    while (!exitMre.WaitOne(0))
                    {
                        var keyProps = Console.ReadKey();
                        if (keyProps.KeyChar == 'h' || keyProps.KeyChar == 'q')
                        {
                            Console.WriteLine();
                            Console.WriteLine("Hangup requested by user...");

                            Hangup(uas).Wait();

                            rtpSession?.Close(null);
                            rtpCts?.Cancel();
                        }

                        if (keyProps.KeyChar == 'q')
                        {
                            Log.LogInformation("Quitting...");

                            if (sipTransport != null)
                            {
                                Log.LogInformation("Shutting down SIP transport...");
                                sipTransport.Shutdown();
                            }

                            exitMre.Set();
                        }
                    }
                }
                catch (Exception excp)
                {
                    Log.LogError($"Exception Key Press listener. {excp.Message}.");
                }
            });

            exitMre.WaitOne();
        }
Example #50
0
        private static Signature GetSignatureFromCatalog(string filename)
        {
            if (Signature.CatalogApiAvailable.HasValue && !Signature.CatalogApiAvailable.Value)
            {
                // Signature.CatalogApiAvailable would be set to false the first time it is detected that
                // WTGetSignatureInfo API does not exist on the platform, or if the API is not functional on the target platform.
                // Just return from the function instead of revalidating.
                return(null);
            }

            Signature signature = null;

            Utils.CheckArgForNullOrEmpty(filename, "fileName");
            SecuritySupport.CheckIfFileExists(filename);

            try
            {
                using (FileStream stream = File.OpenRead(filename))
                {
                    NativeMethods.SIGNATURE_INFO sigInfo = new NativeMethods.SIGNATURE_INFO();
                    sigInfo.cbSize = (uint)Marshal.SizeOf(sigInfo);

                    IntPtr ppCertContext = IntPtr.Zero;
                    IntPtr phStateData   = IntPtr.Zero;

                    try
                    {
                        int hresult = NativeMethods.WTGetSignatureInfo(filename, stream.SafeFileHandle.DangerousGetHandle(),
                                                                       NativeMethods.SIGNATURE_INFO_FLAGS.SIF_CATALOG_SIGNED |
                                                                       NativeMethods.SIGNATURE_INFO_FLAGS.SIF_CATALOG_FIRST |
                                                                       NativeMethods.SIGNATURE_INFO_FLAGS.SIF_AUTHENTICODE_SIGNED |
                                                                       NativeMethods.SIGNATURE_INFO_FLAGS.SIF_BASE_VERIFICATION |
                                                                       NativeMethods.SIGNATURE_INFO_FLAGS.SIF_CHECK_OS_BINARY,
                                                                       ref sigInfo, ref ppCertContext, ref phStateData);

                        if (Utils.Succeeded(hresult))
                        {
                            DWORD error = GetErrorFromSignatureState(sigInfo.nSignatureState);

                            X509Certificate2 cert = null;

                            if (ppCertContext != IntPtr.Zero)
                            {
                                cert = new X509Certificate2(ppCertContext);

                                // Get the time stamper certificate if available
                                TryGetProviderSigner(phStateData, out IntPtr pProvSigner, out X509Certificate2 timestamperCert);
                                if (timestamperCert != null)
                                {
                                    signature = new Signature(filename, error, cert, timestamperCert);
                                }
                                else
                                {
                                    signature = new Signature(filename, error, cert);
                                }

                                switch (sigInfo.nSignatureType)
                                {
                                case NativeMethods.SIGNATURE_INFO_TYPE.SIT_AUTHENTICODE: signature.SignatureType = SignatureType.Authenticode; break;

                                case NativeMethods.SIGNATURE_INFO_TYPE.SIT_CATALOG: signature.SignatureType = SignatureType.Catalog; break;
                                }

                                if (sigInfo.fOSBinary == 1)
                                {
                                    signature.IsOSBinary = true;
                                }
                            }
                            else
                            {
                                signature = new Signature(filename, error);
                            }

                            if (!Signature.CatalogApiAvailable.HasValue)
                            {
                                string productFile = Path.Combine(Utils.DefaultPowerShellAppBase, "Modules\\Microsoft.PowerShell.Utility\\Microsoft.PowerShell.Utility.psm1");
                                if (signature.Status != SignatureStatus.Valid)
                                {
                                    if (string.Equals(filename, productFile, StringComparison.OrdinalIgnoreCase))
                                    {
                                        Signature.CatalogApiAvailable = false;
                                    }
                                    else
                                    {
                                        // ProductFile has to be Catalog signed. Hence validating
                                        // to see if the Catalog API is functional using the ProductFile.
                                        Signature productFileSignature = GetSignatureFromCatalog(productFile);
                                        Signature.CatalogApiAvailable = (productFileSignature != null && productFileSignature.Status == SignatureStatus.Valid);
                                    }
                                }
                            }
                        }
                        else
                        {
                            // If calling NativeMethods.WTGetSignatureInfo failed (returned a non-zero value), we still want to set Signature.CatalogApiAvailable to false.
                            Signature.CatalogApiAvailable = false;
                        }
                    }
                    finally
                    {
                        if (phStateData != IntPtr.Zero)
                        {
                            NativeMethods.FreeWVTStateData(phStateData);
                        }

                        if (ppCertContext != IntPtr.Zero)
                        {
                            NativeMethods.CertFreeCertificateContext(ppCertContext);
                        }
                    }
                }
            }
            catch (TypeLoadException)
            {
                // If we don't have WTGetSignatureInfo, don't return a Signature.
                Signature.CatalogApiAvailable = false;
                return(null);
            }

            return(signature);
        }
Example #51
0
        private static bool ServerCertificateCustomValidation(HttpRequestMessage requestMessage, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslErrors)
        {
#if DEBUG
            // It is possible inpect the certificate provided by server
            Debug.WriteLine($"Requested URI: {requestMessage.RequestUri}");
            Debug.WriteLine($"Effective date: {certificate.GetEffectiveDateString()}");
            Debug.WriteLine($"Expiration date: {certificate.GetExpirationDateString()}");
            Debug.WriteLine($"Issuer: {certificate.Issuer}");
            Debug.WriteLine($"Subject: {certificate.Subject}");
            Debug.WriteLine($"Errors: {sslErrors}");
            Debug.WriteLine($"DropZoneConfig.AllowSSL: {RestApiCalls._DropZoneConfig.IgnoreSslCertProblems}");
#endif
            var result = false;
            switch (sslErrors)
            {
            case SslPolicyErrors.None:
                result = true;
                break;

            case SslPolicyErrors.RemoteCertificateChainErrors:
            case SslPolicyErrors.RemoteCertificateNameMismatch:
            case SslPolicyErrors.RemoteCertificateNotAvailable:
                result = RestApiCalls._DropZoneConfig.IgnoreSslCertProblems;
                break;

            default:
                break;
            }
            return(result);
        }
        protected async Task <MetadataTOCPayload> DeserializeAndValidateToc(string toc)
        {
            var jwtToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(toc);

            _tocAlg = jwtToken.Header["alg"] as string;
            var keys = (jwtToken.Header["x5c"] as Newtonsoft.Json.Linq.JArray)
                       .Values <string>()
                       .Select(x => new ECDsaSecurityKey(
                                   (ECDsaCng)(new X509Certificate2(System.Convert.FromBase64String(x)).GetECDsaPublicKey())))
                       .ToArray();

            var root = new X509Certificate2(Convert.FromBase64String(ROOT_CERT));

            var chain = new X509Chain();

            chain.ChainPolicy.ExtraStore.Add(root);
            chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

            var validationParameters = new TokenValidationParameters
            {
                ValidateIssuer           = false,
                ValidateAudience         = false,
                ValidateLifetime         = false,
                ValidateIssuerSigningKey = true,
                IssuerSigningKeys        = keys,
            };
            var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            tokenHandler.ValidateToken(
                toc,
                validationParameters,
                out var validatedToken);
            var payload = ((System.IdentityModel.Tokens.Jwt.JwtSecurityToken)validatedToken).Payload.SerializeToJson();

            chain.ChainPolicy.ExtraStore.Add(new X509Certificate2(System.Convert.FromBase64String((jwtToken.Header["x5c"] as Newtonsoft.Json.Linq.JArray).Values <string>().Last())));
            var valid = chain.Build(new X509Certificate2(System.Convert.FromBase64String((jwtToken.Header["x5c"] as Newtonsoft.Json.Linq.JArray).Values <string>().First())));

            // if the root is trusted in the context we are running in, valid should be true here
            if (false == valid)
            {
                foreach (var element in chain.ChainElements)
                {
                    if (element.Certificate.Issuer != element.Certificate.Subject)
                    {
                        var cdp     = CryptoUtils.CDPFromCertificateExts(element.Certificate.Extensions);
                        var crlFile = await DownloadDataAsync(cdp);

                        if (true == CryptoUtils.IsCertInCRL(crlFile, element.Certificate))
                        {
                            throw new Fido2VerificationException(string.Format("Cert {0} found in CRL {1}", element.Certificate.Subject, cdp));
                        }
                    }
                }

                // otherwise we have to manually validate that the root in the chain we are testing is the root we downloaded
                if (root.Thumbprint == chain.ChainElements[chain.ChainElements.Count - 1].Certificate.Thumbprint &&
                    // and that the number of elements in the chain accounts for what was in x5c plus the root we added
                    chain.ChainElements.Count == ((jwtToken.Header["x5c"] as Newtonsoft.Json.Linq.JArray).Count + 1) &&
                    // and that the root cert has exactly one status listed against it
                    chain.ChainElements[chain.ChainElements.Count - 1].ChainElementStatus.Length == 1 &&
                    // and that that status is a status of exactly UntrustedRoot
                    chain.ChainElements[chain.ChainElements.Count - 1].ChainElementStatus[0].Status == X509ChainStatusFlags.UntrustedRoot)
                {
                    // if we are good so far, that is a good sign
                    valid = true;
                    for (var i = 0; i < chain.ChainElements.Count - 1; i++)
                    {
                        // check each non-root cert to verify zero status listed against it, otherwise, invalidate chain
                        if (0 != chain.ChainElements[i].ChainElementStatus.Length)
                        {
                            valid = false;
                        }
                    }
                }
            }
            if (false == valid)
            {
                throw new Fido2VerificationException("Failed to validate cert chain while parsing TOC");
            }
            return(JsonConvert.DeserializeObject <MetadataTOCPayload>(payload));
        }
Example #53
0
        /// <summary>
        /// Creates a cert with the connectionstring (token) and stores it in the given cert store.
        /// </summary>
        public static async Task WriteAsync(string name, string connectionString, string storeType, string storePath)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("Token not found in X509Store and no new token provided!");
            }

            SecureRandom            random = new SecureRandom();
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            AsymmetricCipherKeyPair keys = keyPairGenerator.GenerateKeyPair();

            ArrayList nameOids = new ArrayList();

            nameOids.Add(X509Name.CN);
            ArrayList nameValues = new ArrayList();

            nameValues.Add(name);
            X509Name subjectDN = new X509Name(nameOids, nameValues);
            X509Name issuerDN  = subjectDN;

            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();

            cg.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random));
            cg.SetIssuerDN(issuerDN);
            cg.SetSubjectDN(subjectDN);
            cg.SetNotBefore(DateTime.Now);
            cg.SetNotAfter(DateTime.Now.AddMonths(12));
            cg.SetPublicKey(keys.Public);
            cg.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DataEncipherment));

            // encrypt the token with the public key so only the owner of the assoc. private key can decrypt it and
            // "hide" it in the instruction code cert extension
            RSA              rsa       = RSA.Create();
            RSAParameters    rsaParams = new RSAParameters();
            RsaKeyParameters keyParams = (RsaKeyParameters)keys.Public;

            rsaParams.Modulus = new byte[keyParams.Modulus.ToByteArrayUnsigned().Length];
            keyParams.Modulus.ToByteArrayUnsigned().CopyTo(rsaParams.Modulus, 0);

            rsaParams.Exponent = new byte[keyParams.Exponent.ToByteArrayUnsigned().Length];
            keyParams.Exponent.ToByteArrayUnsigned().CopyTo(rsaParams.Exponent, 0);

            rsa.ImportParameters(rsaParams);
            if (rsa != null)
            {
                byte[] bytes = rsa.Encrypt(Encoding.ASCII.GetBytes(connectionString), RSAEncryptionPadding.OaepSHA1);
                if (bytes != null)
                {
                    cg.AddExtension(X509Extensions.InstructionCode, false, bytes);
                }
                else
                {
                    throw new CryptographicException("Can not encrypt IoTHub security token using generated public key!");
                }
            }

            // sign the cert with the private key
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keys.Private, random);

            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create a PKCS12 store for the cert and its private key
            X509Certificate2 certificate = null;

            using (MemoryStream pfxData = new MemoryStream())
            {
                Pkcs12StoreBuilder builder = new Pkcs12StoreBuilder();
                builder.SetUseDerEncoding(true);
                Pkcs12Store            pkcsStore = builder.Build();
                X509CertificateEntry[] chain     = new X509CertificateEntry[1];
                string passcode = Guid.NewGuid().ToString();
                chain[0] = new X509CertificateEntry(x509);
                pkcsStore.SetKeyEntry(name, new AsymmetricKeyEntry(keys.Private), chain);
                pkcsStore.Save(pfxData, passcode.ToCharArray(), random);

                // create X509Certificate2 object from PKCS12 file
                certificate = CertificateFactory.CreateCertificateFromPKCS12(pfxData.ToArray(), passcode);

                // handle each store type differently
                switch (storeType)
                {
                case CertificateStoreType.Directory:
                {
                    // Add to DirectoryStore
                    using (DirectoryCertificateStore store = new DirectoryCertificateStore())
                    {
                        store.Open(storePath);
                        X509CertificateCollection certificates = await store.Enumerate().ConfigureAwait(false);

                        // remove any existing cert with our name from the store
                        foreach (X509Certificate2 cert in certificates)
                        {
                            if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase))
                            {
                                await store.Delete(cert.Thumbprint).ConfigureAwait(false);
                            }
                        }

                        // add new one
                        await store.Add(certificate).ConfigureAwait(false);
                    }
                    break;
                }

                case CertificateStoreType.X509Store:
                {
                    // Add to X509Store
                    using (X509Store store = new X509Store(storePath, StoreLocation.CurrentUser))
                    {
                        store.Open(OpenFlags.ReadWrite);

                        // remove any existing cert with our name from the store
                        foreach (X509Certificate2 cert in store.Certificates)
                        {
                            if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase))
                            {
                                store.Remove(cert);
                            }
                        }

                        // add new cert to store
                        try
                        {
                            store.Add(certificate);
                        }
                        catch (Exception e)
                        {
                            throw new Exception($"Not able to add cert to the requested store type '{storeType}' (exception message: '{e.Message}'.");
                        }
                    }
                    break;
                }

                default:
                {
                    throw new Exception($"The requested store type '{storeType}' is not supported. Please change.");
                }
                }
                return;
            }
        }
Example #54
0
        private static void OnRequestSendingRequest(WinHttpRequestState state)
        {
            Debug.Assert(state != null, "OnRequestSendingRequest: state is null");
            Debug.Assert(state.RequestHandle != null, "OnRequestSendingRequest: state.RequestHandle is null");

            if (state.RequestMessage.RequestUri.Scheme != UriScheme.Https)
            {
                // Not SSL/TLS.
                return;
            }

            // Grab the channel binding token (CBT) information from the request handle and put it into
            // the TransportContext object.
            state.TransportContext.SetChannelBinding(state.RequestHandle);

            if (state.ServerCertificateValidationCallback != null)
            {
                IntPtr certHandle     = IntPtr.Zero;
                uint   certHandleSize = (uint)IntPtr.Size;

                if (!Interop.WinHttp.WinHttpQueryOption(
                        state.RequestHandle,
                        Interop.WinHttp.WINHTTP_OPTION_SERVER_CERT_CONTEXT,
                        ref certHandle,
                        ref certHandleSize))
                {
                    int lastError = Marshal.GetLastWin32Error();
                    WinHttpTraceHelper.Trace(
                        "OnRequestSendingRequest: Error getting WINHTTP_OPTION_SERVER_CERT_CONTEXT, {0}",
                        lastError);

                    if (lastError == Interop.WinHttp.ERROR_WINHTTP_INCORRECT_HANDLE_STATE)
                    {
                        // Not yet an SSL/TLS connection. This occurs while connecting thru a proxy where the
                        // CONNECT verb hasn't yet been processed due to the proxy requiring authentication.
                        // We need to ignore this notification. Another notification will be sent once the final
                        // connection thru the proxy is completed.
                        return;
                    }

                    throw WinHttpException.CreateExceptionUsingError(lastError);
                }

                // Create a managed wrapper around the certificate handle. Since this results in duplicating
                // the handle, we will close the original handle after creating the wrapper.
                var serverCertificate = new X509Certificate2(certHandle);
                Interop.Crypt32.CertFreeCertificateContext(certHandle);

                X509Chain       chain = null;
                SslPolicyErrors sslPolicyErrors;

                try
                {
                    WinHttpCertificateHelper.BuildChain(
                        serverCertificate,
                        state.RequestMessage.RequestUri.Host,
                        state.CheckCertificateRevocationList,
                        out chain,
                        out sslPolicyErrors);

                    bool result = state.ServerCertificateValidationCallback(
                        state.RequestMessage,
                        serverCertificate,
                        chain,
                        sslPolicyErrors);
                    if (!result)
                    {
                        throw WinHttpException.CreateExceptionUsingError(
                                  (int)Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE);
                    }
                }
                finally
                {
                    if (chain != null)
                    {
                        chain.Dispose();
                    }

                    serverCertificate.Dispose();
                }
            }
        }
 public TpSigningClient(string serviceUri, X509Certificate2 signingCertificate) : base(serviceUri, signingCertificate)
 {
 }
Example #56
0
 /// <summary>
 /// Decrypts the token (implemented by the subclass).
 /// </summary>
 public virtual void Decrypt(X509Certificate2 certificate, byte[] receiverNonce, string securityPolicyUri)
 {
 }
        public static void TestManagedCertificate(TestContext ctx, X509Certificate2 cert, CertificateInfo expected, bool debug = false)
        {
            var subject = cert.SubjectName;

            if (debug)
            {
                ctx.LogMessage("MANAGED SUBJECT: {0}", subject.Name);
            }
            if (ctx.Expect(subject, Is.Not.Null, "SubjectName"))
            {
                ctx.Expect(subject.Name, Is.EqualTo(expected.ManagedSubjectName), "SubjectName.Name");
            }

            var issuer = cert.IssuerName;

            if (debug)
            {
                ctx.LogMessage("MANAGED ISSUER: {0}", issuer.Name);
            }
            if (ctx.Expect(issuer, Is.Not.Null, "IssuerName"))
            {
                ctx.Expect(issuer.Name, Is.EqualTo(expected.ManagedIssuerName), "IssuerName.Name");
            }

            ctx.Expect(cert.Subject, Is.EqualTo(expected.ManagedSubjectName), "Subject");
            ctx.Expect(cert.Issuer, Is.EqualTo(expected.ManagedIssuerName), "Issue");
            ctx.Expect(cert.NotBefore.ToUniversalTime(), Is.EqualTo(expected.NotBefore), "NotBefore");
            ctx.Expect(cert.NotAfter.ToUniversalTime(), Is.EqualTo(expected.NotAfter), "NotAfter");
            ctx.Expect(cert.GetCertHash(), Is.EqualTo(expected.Hash), "GetCertHash()");

            ctx.Expect(cert.GetSerialNumber(), Is.EqualTo(expected.SerialNumberMono), "GetSerialNumber()");

            ctx.Expect(cert.Version, Is.EqualTo(expected.Version), "Version");

            ctx.Expect(cert.GetPublicKey(), Is.EqualTo(expected.PublicKeyData), "GetPublicKey()");

            var signatureAlgorithm = cert.SignatureAlgorithm;

            if (ctx.Expect(signatureAlgorithm, Is.Not.Null, "SignatureAlgorithm"))
            {
                ctx.Expect(signatureAlgorithm.Value, Is.EqualTo(expected.SignatureAlgorithmOid), "SignatureAlgorithm.Value");
            }

            var publicKey = cert.PublicKey;

            if (ctx.Expect(publicKey, Is.Not.Null, "PublicKey"))
            {
                if (ctx.Expect(publicKey.Oid, Is.Not.Null, "PublicKey.Oid"))
                {
                    ctx.Expect(publicKey.Oid.Value, Is.EqualTo(expected.PublicKeyAlgorithmOid), "PublicKey.Oid.Value");
                }

                var value = publicKey.EncodedKeyValue;
                if (ctx.Expect(value, Is.Not.Null, "PublicKey.EncodedKeyValue"))
                {
                    if (ctx.Expect(value.Oid, Is.Not.Null, "PublicKey.Oid"))
                    {
                        ctx.Expect(value.Oid.Value, Is.EqualTo(expected.PublicKeyAlgorithmOid), "PublicKey.Oid.Value");
                    }

                    ctx.Expect(value.RawData, Is.EqualTo(expected.PublicKeyData), "PublicKey.RawData");
                }

                var publicKeyParams = publicKey.EncodedParameters;
                if (ctx.Expect(publicKeyParams, Is.Not.Null, "PublicKey.EncodedParameters"))
                {
                    if (ctx.Expect(publicKeyParams.Oid, Is.Not.Null, "PublicKey.EncodedParameters.Oid"))
                    {
                        ctx.Expect(publicKeyParams.Oid.Value, Is.EqualTo(expected.PublicKeyAlgorithmOid), "PublicKey.EncodedParameters.Oid.Value");
                    }
                    ctx.Expect(publicKeyParams.RawData, Is.EqualTo(expected.PublicKeyParameters), "PublicKey.EncodedParameters.RawData");
                }
            }
        }
Example #58
0
 public static CallInvoker Client(string baseUrl, X509Certificate2 cert, GrpcClientConfig config) =>
 Client(baseUrl, cert, null, config);
        /// <summary>
        /// Sets the signing credential.
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <param name="certificate">The certificate.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="InvalidOperationException">X509 certificate does not have a private key.</exception>
        public static IIdentityServerBuilder SetSigningCredential(this IIdentityServerBuilder builder, X509Certificate2 certificate)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }

            if (!certificate.HasPrivateKey)
            {
                throw new InvalidOperationException("X509 certificate does not have a private key.");
            }

            var credential = new SigningCredentials(new X509SecurityKey(certificate), "RS256");

            return(builder.SetSigningCredential(credential));
        }
Example #60
0
 public AADAppOnlyAuthenticationProvider(string authorityUriTemplate, string tenant, string clientId, X509Certificate2 ClientCertificate, string claimsProviderName, int timeout)
 {
     this.Tenant             = tenant;
     this.ClientId           = clientId;
     this.ClientCertificate  = ClientCertificate;
     this.AuthorityUri       = String.Format(CultureInfo.InvariantCulture, authorityUriTemplate, tenant);
     this.ClaimsProviderName = claimsProviderName;
     this.Timeout            = timeout;
 }