public KeyStoreViewModel(SystemX509.StoreName storeName, SystemX509.StoreLocation storeLocation) { var storeBuilder = new Pkcs12StoreBuilder(); _store = storeBuilder.Build(); Name = String.Format("System KeyStore: [{0} : {1}]", storeLocation.ToString(), storeName.ToString()); Load(storeName, storeLocation); }
internal static ITlsConfiguration CreateTlsConfiguration ( string hostname, bool serverMode, MSI.TlsProtocols protocolFlags, SSCX.X509Certificate serverCertificate, bool remoteCertRequired, MSI.MonoTlsSettings settings) { object[] args; ITlsConfiguration config; if (serverMode) { var cert = (PSSCX.X509Certificate2)serverCertificate; var monoCert = new MX.X509Certificate (cert.RawData); args = new object[] { (MSI.TlsProtocols)protocolFlags, (MSI.MonoTlsSettings)settings, monoCert, cert.PrivateKey }; } else { args = new object[] { (MSI.TlsProtocols)protocolFlags, (MSI.MonoTlsSettings)settings, hostname }; } config = (ITlsConfiguration)CreateInstance (tlsConfigTypeName, args); if (serverMode && remoteCertRequired) config.AskForClientCertificate = true; return config; }
internal override MSI.IMonoTlsContext CreateTlsContext ( string hostname, bool serverMode, MSI.TlsProtocols protocolFlags, SSCX.X509Certificate serverCertificate, PSSCX.X509CertificateCollection clientCertificates, bool remoteCertRequired, MSI.MonoEncryptionPolicy encryptionPolicy, MSI.MonoTlsSettings settings) { var config = TlsProviderFactory.CreateTlsConfiguration ( hostname, serverMode, protocolFlags, serverCertificate, remoteCertRequired, settings); return new TlsContextWrapper (config, serverMode); }
public static MonoNewTlsStream CreateClient ( Stream innerStream, bool leaveOpen, MonoTlsProvider provider, MonoTlsSettings settings, string targetHost, PSSCX.X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { var stream = new MonoNewTlsStream (innerStream, leaveOpen, provider, settings); try { stream.AuthenticateAsClient (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation); } catch (Exception ex) { var tlsEx = stream.LastError; if (tlsEx != null) throw new AggregateException (ex, tlsEx); throw; } return stream; }
public static MonoNewTlsStream CreateServer ( Stream innerStream, bool leaveOpen, ICertificateValidator certificateValidator, TlsSettings settings, SSCX.X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { var stream = new MonoNewTlsStream (innerStream, leaveOpen, certificateValidator, settings); try { stream.AuthenticateAsServer (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation); } catch (Exception ex) { var tlsEx = stream.LastError; if (tlsEx != null) throw new AggregateException (ex, tlsEx); throw; } return stream; }
public override MSI.IMonoTlsContext CreateTlsContext ( string hostname, bool serverMode, MSI.TlsProtocols protocolFlags, SSCX.X509Certificate serverCertificate, PSSCX.X509CertificateCollection clientCertificates, bool remoteCertRequired, MSI.MonoEncryptionPolicy encryptionPolicy, MSI.MonoTlsSettings settings) { TlsConfiguration config; if (serverMode) { var cert = (PSSCX.X509Certificate2)serverCertificate; var monoCert = new MX.X509Certificate (cert.RawData); config = new TlsConfiguration ((TlsProtocols)protocolFlags, (MSI.MonoTlsSettings)settings, monoCert, cert.PrivateKey); if (remoteCertRequired) config.AskForClientCertificate = true; } else { config = new TlsConfiguration ((TlsProtocols)protocolFlags, (MSI.MonoTlsSettings)settings, hostname); } return new TlsContextWrapper (config, serverMode); }
public static bool DumpCertificateInfo (object sender, SSCX.X509Certificate certificate, SSCX.X509Chain chain, SslPolicyErrors sslPolicyErrors) { Console.WriteLine ("Certificate:"); Console.WriteLine ("============"); Console.WriteLine ("Subject: " + certificate.Subject); Console.WriteLine ("Errors: {0}", sslPolicyErrors); Console.WriteLine (); foreach (SSCX.X509Certificate2 cert in chain.ChainPolicy.ExtraStore) { Console.WriteLine ("ExtraStore Certificate:"); Console.WriteLine (); Console.WriteLine ("Subject: {0}", cert.Subject); Console.WriteLine ("Issuer: {0}", cert.Issuer); Console.WriteLine ("Valid: {0}", cert.Verify ()); Console.WriteLine (); } foreach (SSCX.X509ChainElement element in chain.ChainElements) { Console.WriteLine ("ChainElement Certificate:"); Console.WriteLine (); Console.WriteLine ("Subject: {0}", element.Certificate.Subject); Console.WriteLine ("Issuer: {0}", element.Certificate.Issuer); Console.WriteLine ("Valid: {0}", element.Certificate.Verify ()); Console.WriteLine ("Extensions: {0}", element.Certificate.Extensions.Count); Console.WriteLine ("Status:"); for (int index = 0; index < element.ChainElementStatus.Length; index++) { Console.WriteLine ("\t{0}:{1}", element.ChainElementStatus [index].Status, element.ChainElementStatus [index].StatusInformation); } Console.WriteLine (); } if (sslPolicyErrors == SslPolicyErrors.None) return true; return true; }
static bool CertificateValidation (SSCX.X509Certificate certificate, int [] certificateErrors) { // the main reason to download it is that it's not trusted return true; // OTOH we ask user confirmation before adding certificates into the stores }
static bool SSLHandler(Syscert.X509Certificate certificate, int[] certificateErrors) { bool retVal = true; X509Certificate x509 = null; byte[] data = certificate.GetRawCertData(); if (data != null) x509 = new X509Certificate (data); StringBuilder msg = new StringBuilder (); msg.AppendFormat (" {0}X.509 v{1} Certificate", (x509.IsSelfSigned ? "Self-signed " : String.Empty), x509.Version); msg.AppendFormat ("\nSerial Number: {0}", CryptoConvert.ToHex (x509.SerialNumber)); msg.AppendFormat ("\nIssuer Name: {0}", x509.IssuerName); msg.AppendFormat ("\nSubject Name: {0}", x509.SubjectName); msg.AppendFormat ("\nValid From: {0}", x509.ValidFrom); msg.AppendFormat ("\nValid Until: {0}", x509.ValidUntil); msg.AppendFormat ("\nUnique Hash: {0}", CryptoConvert.ToHex (x509.Hash)); Log.Debug ("Certificate info:\n{0}", msg.ToString()); Log.Debug ("Certificate errors:\n{0}", certificateErrors.Length); return retVal; }
private MSX509.X509Certificate2 GetCertificate(X509Name name, Usage usage, int validity, MSX509.StoreName storeName, MSX509.X509Certificate2 issuer) { // Try to load the certificate from the machine store MSX509.X509Certificate2 certificate = LoadCertificate(name, storeName, MSX509.StoreLocation.LocalMachine); if(certificate != null) return certificate; // Try to load the certificate from the user store certificate = LoadCertificate(name, storeName, MSX509.StoreLocation.CurrentUser); if(certificate != null) return certificate; return InternalGenerateCertificate(name, usage, validity, storeName, issuer); }
/// <summary> /// Loads the specified system keystore and puts /// the keys store in read-only mode /// </summary> /// <param name="storeName">one of the enum values </param> /// <param name="storelocation">one of the enum values</param> public void Load(SystemX509.StoreName storeName, SystemX509.StoreLocation storelocation) { ReadOnlyKeyStore = true; _listItems.Clear(); var store = new SystemX509.X509Store(storeName, storelocation); store.Open(SystemX509.OpenFlags.ReadOnly); foreach (SystemX509.X509Certificate2 cert in store.Certificates) { AddEntry(cert.FriendlyName, DotNetUtilities.FromX509Certificate(cert), null); } }
/// <summary> /// Construct a CertificatesAuthority object /// </summary> /// <param name="name">Name of the certification authority.</param> /// <param name="store">Where to store the certificates</param> public CertificatesAuthority(string name, MSX509.StoreLocation store) { authorityName_ = name != null ? X509NameFromString(name) : null; store_ = store; }
private void StoreCertificate(X509Name name, MSX509.X509Certificate2 certificate, MSX509.StoreName storeName) { MSX509.X509Store store = new MSX509.X509Store(storeName, store_); store.Open(MSX509.OpenFlags.ReadWrite); store.Add(certificate); store.Close(); certificates_[name] = certificate; }
private MSX509.X509Certificate2 LoadCertificate(X509Name name, MSX509.StoreName storeName, MSX509.StoreLocation location) { if(certificates_.ContainsKey(name)) return certificates_[name]; string dn = name.ToString(); MSX509.X509Store store = new MSX509.X509Store(storeName, location); store.Open(MSX509.OpenFlags.ReadOnly); var certificates = store.Certificates.Find(MSX509.X509FindType.FindBySubjectDistinguishedName, dn, true); store.Close(); if(certificates.Count <= 0) return null; MSX509.X509Certificate2 certificate = certificates[0]; certificates_[name] = certificate; return certificate; }
private MSX509.X509Certificate2 InternalGenerateCertificate(X509Name name, Usage usage, int validity, MSX509.StoreName storeName, AsymmetricKeyParameter publicKey, AsymmetricKeyParameter privateKey, AsymmetricKeyParameter signator) { DateTime notBefore = DateTime.Now.AddDays(-1); // Build a X509v3 certificate X509V3CertificateGenerator builder = new X509V3CertificateGenerator(); builder.SetSerialNumber(new BigInteger(GenerateSerial())); builder.SetIssuerDN(authorityName_ ?? name); builder.SetSubjectDN(name); builder.SetPublicKey(publicKey); builder.SetNotBefore(notBefore); builder.SetNotAfter(notBefore.AddDays(validity == 0 ? defaultCertificatesValidity_ : validity)); builder.SetSignatureAlgorithm("SHA1WithRSA"); // Add the extensions AddExtensions(builder, usage); // Sign the certificate X509Certificate newCertificate = builder.Generate(signator); // Create a .NET X509Certificate2 from the BouncyCastle one and put the private key into it MSX509.X509Certificate2 certificate = CreateCertificate(name, newCertificate, privateKey); // Store the certificate StoreCertificate(name, certificate, storeName); return certificate; }
private MSX509.X509Certificate2 InternalGenerateCertificate(X509Name name, Usage usage, int validity, MSX509.StoreName storeName, MSX509.X509Certificate2 issuer) { // Create a pair of keys RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator(); keyGenerator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024)); var keys = keyGenerator.GenerateKeyPair(); // Get the signator (issuer or itself in the case of a root certificate which is self-signed) AsymmetricKeyParameter signator = issuer == null ? keys.Private : DotNetUtilities.GetKeyPair(issuer.PrivateKey).Private; return InternalGenerateCertificate(name, usage, validity, storeName, keys.Public, keys.Private, signator); }
/// <summary> /// Delegete handler to process SSL Communications over LDAP. /// This allows the user to accept or reject a certificate chain /// Thus the certificate Auth Authority does not have to pre-exist in the truststore /// </summary> /// <param name="certificate"> /// A <see cref="Syscert.X509Certificate"/> /// </param> /// <param name="certificateErrors"> /// A <see cref="System.Int32[]"/> /// </param> /// <returns> /// A <see cref="System.Boolean"/> /// </returns> private bool MySSLHandler(Syscert.X509Certificate certificate, int[] certificateErrors) { Logger.Debug("calling MySSLHandler()"); X509Store store = null; X509Stores stores = X509StoreManager.CurrentUser; String input; store = stores.TrustedRoot; //Import the details of the certificate from the server. X509Certificate x509 = null; X509CertificateCollection coll = new X509CertificateCollection (); Logger.Debug("calling GetRawCertData()"); byte[] data = certificate.GetRawCertData(); if (data != null) x509 = new X509Certificate (data); //List the details of the Server //check for ceritficate in store X509CertificateCollection check = store.Certificates; if(!check.Contains(x509)) { if(bindCount == 1) { Console.WriteLine ( " \n\nCERTIFICATE DETAILS: \n" ); Console.WriteLine ( " {0}X.509 v{1} Certificate", (x509.IsSelfSigned ? "Self-signed " : String.Empty), x509.Version); Console.WriteLine ( " Serial Number: {0}", CryptoConvert.ToHex (x509.SerialNumber)); Console.WriteLine ( " Issuer Name: {0}", x509.IssuerName); Console.WriteLine ( " Subject Name: {0}", x509.SubjectName); Console.WriteLine ( " Valid From: {0}", x509.ValidFrom); Console.WriteLine ( " Valid Until: {0}", x509.ValidUntil); Console.WriteLine ( " Unique Hash: {0}", CryptoConvert.ToHex (x509.Hash)); } //Get the response from the Client do { Console.WriteLine("\nDo you want to proceed with the connection (y/n)?"); input = Console.ReadLine(); if(input=="y" || input == "Y") bHowToProceed = true; if(input=="n" || input == "N") bHowToProceed = false; }while(input!="y" && input != "Y" && input !="n" && input != "N"); } else { if(bHowToProceed == true) { //Add the certificate to the store. if (x509 != null) coll.Add (x509); store.Import (x509); if(bindCount == 1) removeFlag = true; } } if(bHowToProceed == false) { //Remove the certificate added from the store. if(removeFlag == true && bindCount > 1) { foreach (X509Certificate xt509 in store.Certificates) { if (CryptoConvert.ToHex (xt509.Hash) == CryptoConvert.ToHex (x509.Hash)) { store.Remove (x509); } } } Console.WriteLine("SSL Bind Failed."); } return bHowToProceed; }
public MSX509.X509Certificate2 SignRequest(string csrFile, Usage usage, int validity, MSX509.StoreName storeName) { Pkcs10CertificationRequest request = ReadPkcs10(csrFile); var info = request.GetCertificationRequestInfo(); SubjectPublicKeyInfo publicKeyInfo = info.SubjectPublicKeyInfo; RsaPublicKeyStructure publicKeyStructure = RsaPublicKeyStructure.GetInstance(publicKeyInfo.GetPublicKey()); RsaKeyParameters publicKey = new RsaKeyParameters(false, publicKeyStructure.Modulus, publicKeyStructure.PublicExponent); if(!request.Verify(publicKey)) throw new ApplicationException("The CSR is not valid: verification failed"); MSX509.X509Certificate2 root = GetRootCertificate(); if(root == null) throw new ApplicationException("Root certificate not found"); return InternalGenerateCertificate(info.Subject, usage, validity, storeName, publicKey, null, DotNetUtilities.GetKeyPair(root.PrivateKey).Private); }