public ECDHEKeyExchange( IServiceProvider serviceProvider, IRandom random, MasterSecretCalculator masterSecretCalculator, CipherSuitesRegistry cipherSuitesRegistry, NamedCurvesRegistry namedCurvesRegistry, ECDHExchangeConfig ecdhExchangeConfig, SupportedGroupsConfig supportedGroupsConfig, CertificateConfig certificateConfig) : base( masterSecretCalculator, cipherSuitesRegistry, ecdhExchangeConfig, certificateConfig) { _serviceProvider = serviceProvider; _random = random; _namedCurvesRegistry = namedCurvesRegistry; _supportedGroupsConfig = supportedGroupsConfig; }
public RSACipherParameterFactory( CertificateManager certificateManager, CertificateConfig certificateConfig) { _certificateManager = certificateManager; _certificateConfig = certificateConfig; }
private X509Certificate2 LoadPEMCertificate(CertificateConfig certificateConfig, string certificatePath) { var certificateKeyPath = Path.Combine(_hostEnvironment.ContentRootPath, certificateConfig.KeyPath); var certificate = GetCertificate(certificatePath); if (certificate != null) { certificate = LoadCertificateKey(certificate, certificateKeyPath, certificateConfig.Password); } else { throw GetFailedToLoadCertificateKeyException(certificateKeyPath); } if (certificate != null) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return(PersistKey(certificate)); } return(certificate); } throw GetFailedToLoadCertificateKeyException(certificateKeyPath); }
public X509Certificate2 LoadCertificate(CertificateConfig certificateConfig) { if (certificateConfig is null) { return(null); } if (certificateConfig.IsFileCert && certificateConfig.IsStoreCert) { throw new InvalidOperationException($"Multiple certificate sources are defined in the cluster configuration."); } else if (certificateConfig.IsFileCert) { var certificatePath = Path.Combine(_hostEnvironment.ContentRootPath, certificateConfig.Path); if (string.IsNullOrWhiteSpace(certificateConfig.KeyPath)) { return(new X509Certificate2(Path.Combine(_hostEnvironment.ContentRootPath, certificateConfig.Path), certificateConfig.Password)); } else { #if NET5_0 return(LoadPEMCertificate(certificateConfig, certificatePath)); #elif NETCOREAPP3_1 throw new NotSupportedException("PEM certificate format is only supported on .NET 5 or higher."); #else #error A target framework was added to the project and needs to be added to this condition. #endif } } else if (certificateConfig.IsStoreCert) { return(LoadFromCertStore(certificateConfig)); } throw new ArgumentException($"Passed {nameof(CertificateConfig)} doesn't define a certificate in any known format."); }
public DHServerKeyExchange( CertificateManager certificateManager, MasterSecretCalculator masterSecretCalculator, CertificateConfig certificateConfig) { _certificateManager = certificateManager; _masterSecretCalculator = masterSecretCalculator; _certificateConfig = certificateConfig; }
public X509Certificate2 LoadCertificate(CertificateConfig certInfo, string endpointName) { if (certInfo is null) { return(null); } if (certInfo.IsFileCert && certInfo.IsStoreCert) { throw new InvalidOperationException(CoreStrings.FormatMultipleCertificateSources(endpointName)); } else if (certInfo.IsFileCert) { var certificatePath = Path.Combine(HostEnvironment.ContentRootPath, certInfo.Path); if (certInfo.KeyPath != null) { var certificateKeyPath = Path.Combine(HostEnvironment.ContentRootPath, certInfo.KeyPath); var certificate = GetCertificate(certificatePath); if (certificate != null) { certificate = LoadCertificateKey(certificate, certificateKeyPath, certInfo.Password); } else { Logger.FailedToLoadCertificate(certificateKeyPath); } if (certificate != null) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return(PersistKey(certificate)); } return(certificate); } else { Logger.FailedToLoadCertificateKey(certificateKeyPath); } throw new InvalidOperationException(CoreStrings.InvalidPemKey); } return(new X509Certificate2(Path.Combine(HostEnvironment.ContentRootPath, certInfo.Path), certInfo.Password)); } else if (certInfo.IsStoreCert) { return(LoadFromStoreCert(certInfo)); } return(null); }
public X509Certificate2 LoadCertificate(CertificateConfig certInfo, string endpointName) { if (certInfo is null) { return(null); } var cert = TestResources.GetTestCertificate(); CertToPathDictionary.Add(cert, certInfo.Path); return(cert); }
private X509Certificate2 LoadCertificate(CertificateConfig certInfo, string endpointName) { var logger = Options.ApplicationServices.GetRequiredService <ILogger <KestrelConfigurationLoader> >(); if (certInfo.IsFileCert && certInfo.IsStoreCert) { throw new InvalidOperationException(CoreStrings.FormatMultipleCertificateSources(endpointName)); } else if (certInfo.IsFileCert) { var environment = Options.ApplicationServices.GetRequiredService <IHostEnvironment>(); var certificatePath = Path.Combine(environment.ContentRootPath, certInfo.Path); if (certInfo.KeyPath != null) { var certificateKeyPath = Path.Combine(environment.ContentRootPath, certInfo.KeyPath); var certificate = GetCertificate(certificatePath); if (certificate != null) { certificate = LoadCertificateKey(certificate, certificateKeyPath, certInfo.Password); } else { logger.FailedToLoadCertificate(certificateKeyPath); } if (certificate != null) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return(PersistKey(certificate)); } return(certificate); } else { logger.FailedToLoadCertificateKey(certificateKeyPath); } throw new InvalidOperationException(CoreStrings.InvalidPemKey); } return(new X509Certificate2(Path.Combine(environment.ContentRootPath, certInfo.Path), certInfo.Password)); } else if (certInfo.IsStoreCert) { return(LoadFromStoreCert(certInfo)); } return(null);
protected ECDHKeyExchangeBase( MasterSecretCalculator masterSecretCalculator, CipherSuitesRegistry cipherSuitesRegistry, ECDHExchangeConfig ecdhExchangeConfig, CertificateConfig certificateConfig) { MasterSecretCalculator = masterSecretCalculator; CipherSuitesRegistry = cipherSuitesRegistry; ECDHExchangeConfig = ecdhExchangeConfig; CertificateConfig = certificateConfig; }
public RSAKeyExchange( IRandom random, CertificateManager certificateManager, MasterSecretCalculator masterSecretCalculator, VersionConfig versionConfig, CertificateConfig certificateConfig) { _random = random; _certificateManager = certificateManager; _masterSecretCalculator = masterSecretCalculator; _versionConfig = versionConfig; _certificateConfig = certificateConfig; }
private static X509Certificate2 LoadFromStoreCert(CertificateConfig certInfo) { var subject = certInfo.Subject !; var storeName = string.IsNullOrEmpty(certInfo.Store) ? StoreName.My.ToString() : certInfo.Store; var location = certInfo.Location; var storeLocation = StoreLocation.CurrentUser; if (!string.IsNullOrEmpty(location)) { storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), location, ignoreCase: true); } var allowInvalid = certInfo.AllowInvalid ?? false; return(CertificateLoader.LoadFromStoreCert(subject, storeName, storeLocation, allowInvalid)); }
private HandleCertificateState( IServiceProvider serviceProvider, EndConfig endConfig, CertificateConfig certificateConfig, CertificateMessage handshake) { _serviceProvider = serviceProvider; _endConfig = endConfig; _certificateConfig = certificateConfig; _handshake = handshake; }
public void Setup() { //SecureTestServer.config ICertificateConfig certificate = new CertificateConfig() { FilePath = @"c:\Projects\EYDAP\Code\SuperSocket-1.6\supersocket.pfx", Password = "******", ClientCertificateRequired = false, }; m_Config = new ServerConfig { Port = 555, Ip = "Any", MaxConnectionNumber = 10000, Mode = SocketMode.Tcp, Name = "NLogDevices", MaxRequestLength = 50000, //Certificate=certificate, //Security="tls" }; m_ConfigNLogClient = new ServerConfig { Port = 8200, Ip = "Any", MaxConnectionNumber = 10, Mode = SocketMode.Tcp, Name = "NLogClient", MaxRequestLength = 50000 //Certificate=certificate, //Security="tls" }; NLogDevicesServer = new MyNLogDevicesAppServer(NLogClientServer); NLogDevicesServer.Setup(new RootConfig(), m_Config, logFactory: new ConsoleLogFactory()); NLogClientServer = new myNLogClientAppServer(NLogDevicesServer); NLogClientServer.Setup(new RootConfig(), m_ConfigNLogClient, logFactory: new ConsoleLogFactory()); NLogDevicesServer.ClientAppServer = NLogClientServer; Global.serversDic.TryAdd(NLogDevicesServer.Name, NLogDevicesServer); Global.serversDic.TryAdd(NLogClientServer.Name, NLogDevicesServer); }
private X509Certificate2 LoadCertificate(CertificateConfig certInfo, string endpointName) { if (certInfo.IsFileCert && certInfo.IsStoreCert) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "The endpoint {0} specified multiple certificate sources.", endpointName)); } else if (certInfo.IsFileCert) { var env = Options.ApplicationServices.GetRequiredService <IHostingEnvironment>(); return(new X509Certificate2(Path.Combine(env.ContentRootPath, certInfo.Path), certInfo.Password)); } else if (certInfo.IsStoreCert) { return(LoadFromStoreCert(certInfo)); } return(null); }
public (X509Certificate2, X509Certificate2Collection) LoadCertificate(CertificateConfig certInfo, string endpointName) { if (certInfo is null) { return(null, null); } var cert = TestResources.GetTestCertificate(); CertToPathDictionary.Add(cert, certInfo.Path); var fullChain = TestResources.GetTestChain(); CertToFullChain[cert] = fullChain; return(cert, fullChain); }
private X509Certificate2 LoadCertificate(CertificateConfig certInfo, string endpointName) { if (certInfo.IsFileCert && certInfo.IsStoreCert) { throw new InvalidOperationException(CoreStrings.FormatMultipleCertificateSources(endpointName)); } else if (certInfo.IsFileCert) { var env = Options.ApplicationServices.GetRequiredService <IHostEnvironment>(); return(new X509Certificate2(Path.Combine(env.ContentRootPath, certInfo.Path), certInfo.Password)); } else if (certInfo.IsStoreCert) { return(LoadFromStoreCert(certInfo)); } return(null); }
static async Task Main(string[] args) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false) .Build(); HttpClientConfig clientConfig = new HttpClientConfig(); config.GetSection("HttpClientConfig").Bind(clientConfig); CertificateConfig certificateConfig = new CertificateConfig(); config.GetSection("CertificateConfig").Bind(certificateConfig); MaskinportenConfig maskinportenConfig = new MaskinportenConfig(); config.GetSection("MaskinportenConfig").Bind(maskinportenConfig); var host = new HostBuilder() .ConfigureServices((hostContext, services) => { services.Configure <RequestConfig>(config.GetSection("RequestConfig")); services.Configure <AccreditationConfig>(config.GetSection("Accreditation")); services.Configure <MaskinportenConfig>(config.GetSection("MaskinportenConfig")); services.Configure <CertificateConfig>(config.GetSection("CertificateConfig")); services.AddTransient <RequestService>(); services.AddTransient <AccreditationService>(); services.AddTransient <MaskinportenService>(); services.AddHttpClient("", c => { c.BaseAddress = new Uri(clientConfig.BaseAddress); c.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", clientConfig.SubscriptionKey); }); }).Build(); RequestService requestHandler = host.Services.GetRequiredService <RequestService>(); Console.WriteLine(await requestHandler.Demo()); await host.RunAsync(); }
public static void CreateCertificateAuthority(CertificateConfig config) { Cryptography.Init(); /* Create the CA KeyStore DB*/ var caKeyStore = Cryptography.KeysetOpen(Cryptography.UNUSED, Cryptography.KEYSET_ODBC_STORE, config.CaCertificateStore, Cryptography.KEYOPT_CREATE); /* Create the Root CA Private Key */ var caRootCertContext = Cryptography.CreateContext(Cryptography.UNUSED, Cryptography.ALGO_RSA); Cryptography.SetAttributeString(caRootCertContext, Cryptography.CTXINFO_LABEL, "CaPrivateKey"); Cryptography.GenerateKey(caRootCertContext); /* Create the CA certificate and add the public key */ var caCert = Cryptography.CreateCert(Cryptography.UNUSED, Cryptography.CERTTYPE_CERTIFICATE); Cryptography.SetAttribute(caCert, Cryptography.CERTINFO_SUBJECTPUBLICKEYINFO, caRootCertContext); Cryptography.SetAttributeString(caCert, Cryptography.CERTINFO_COUNTRYNAME, config.Country); Cryptography.SetAttributeString(caCert, Cryptography.CERTINFO_ORGANIZATIONNAME, config.Organization); Cryptography.SetAttributeString(caCert, Cryptography.CERTINFO_ORGANIZATIONALUNITNAME, config.OrganizationalUnit); Cryptography.SetAttributeString(caCert, Cryptography.CERTINFO_COMMONNAME, config.CommonName); /* Self Sign the Cert */ Cryptography.SetAttribute(caCert, Cryptography.CERTINFO_SELFSIGNED, 1); Cryptography.SetAttribute(caCert, Cryptography.CERTINFO_CA, 1); //Cryptography.SetAttribute(caCert, Cryptography.CERTINFO_AUTHORITYINFO_CERTSTORE, Cryptography.UNUSED); //Cryptography.SetAttributeString(caCert, Cryptography.CERTINFO_UNIFORMRESOURCEIDENTIFIER, "http://localhost/ca/certstore"); //Cryptography.SetAttribute(caCert, Cryptography.CERTINFO_AUTHORITYINFO_RTCS, Cryptography.UNUSED); //Cryptography.SetAttributeString(caCert, Cryptography.CERTINFO_UNIFORMRESOURCEIDENTIFIER, "http://localhost/ca/rtcs"); Cryptography.SignCert(caCert, caRootCertContext); var cryptKeyset = Cryptography.KeysetOpen(Cryptography.UNUSED, Cryptography.KEYSET_FILE, config.CaKeyStoreName, Cryptography.KEYOPT_CREATE); Cryptography.AddPrivateKey(cryptKeyset, caRootCertContext, config.CaPrivateKeyPassword.ToString()); Cryptography.AddPublicKey(cryptKeyset, caCert); Cryptography.KeysetClose(cryptKeyset); Cryptography.KeysetClose(caKeyStore); Cryptography.DestroyContext(caRootCertContext); Cryptography.DestroyCert(caCert); Cryptography.End(); }
public DHEServerKeyExchange( IServiceProvider serviceProvider, IRandom random, MasterSecretCalculator masterSecretCalculator, DHParameterConfig dhParameterConfig, DHExchangeConfig dhExchangeConfig, CertificateConfig certificateConfig) { _serviceProvider = serviceProvider; _random = random; _masterSecretCalculator = masterSecretCalculator; _dhParameterConfig = dhParameterConfig; _dhExchangeConfig = dhExchangeConfig; _certificateConfig = certificateConfig; }
public Server(Configuration configuration) { Configuration = configuration; bool useEncryption = configuration.Certificate != null; SocketServer.NewSessionConnected += new SessionHandler <WebSocketSession>(OnConnect); SocketServer.SessionClosed += new SessionHandler <WebSocketSession, CloseReason>(OnDisconnect); SocketServer.NewMessageReceived += new SessionHandler <WebSocketSession, string>(OnMessage); ServerConfig serverConfiguration = new ServerConfig(); serverConfiguration.Ip = configuration.Host; serverConfiguration.Port = configuration.Port; serverConfiguration.Mode = SocketMode.Tcp; if (configuration.Certificate != null) { CertificateConfig certificateConfiguration = new CertificateConfig(); certificateConfiguration.FilePath = configuration.Certificate; serverConfiguration.Certificate = certificateConfiguration; } SocketServer.Setup(serverConfiguration); }
public ECDHKeyExchange( MasterSecretCalculator masterSecretCalculator, CertificateManager certificateManager, CipherSuitesRegistry cipherSuitesRegistry, NamedCurvesRegistry namedCurvesRegistry, ECDHExchangeConfig ecdhExchangeConfig, SupportedGroupsConfig supportedGroupsConfig, CertificateConfig certificateConfig) : base( masterSecretCalculator, cipherSuitesRegistry, ecdhExchangeConfig, certificateConfig) { _certificateManager = certificateManager; _namedCurvesRegistry = namedCurvesRegistry; _supportedGroupsConfig = supportedGroupsConfig; }
public MaskinportenService(IOptions <MaskinportenConfig> maskinportenConfig, IOptions <CertificateConfig> certificateConfig) { _maskinportenConfig = maskinportenConfig.Value; _certificateConfig = certificateConfig.Value; switch (_maskinportenConfig.Environment.ToLower()) { case "ver2": _tokenEndpoint = "https://ver2.maskinporten.no/token"; _audience = "https://ver2.maskinporten.no/"; break; case "prod": _tokenEndpoint = "https://maskinporten.no/token"; _audience = "https://maskinporten.no/"; break; default: throw new ArgumentException("Invalid Maskinporten environment specified, must be either 'ver2' or 'prod'"); } _scopes = maskinportenConfig.Value.Scopes; _issuer = maskinportenConfig.Value.ClientId; // Thumbprint takes precendence if supplied if (!string.IsNullOrEmpty(_certificateConfig.Thumbprint)) { _signingCertificate = GetCertificateFromKeyStore(); } else { if (!File.Exists(_certificateConfig.Pkcs12FilePath)) { throw new ArgumentException("Unable to find PKCS#12 certificate at " + _certificateConfig.Pkcs12FilePath); } _signingCertificate = new X509Certificate2(); _signingCertificate.Import(File.ReadAllBytes(_certificateConfig.Pkcs12FilePath), _certificateConfig.Pkcs12FileSecret, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); } }
private void LoadDefaultCert() { if (ConfigurationReader.Certificates.TryGetValue("Default", out var defaultCertConfig)) { var defaultCert = CertificateConfigLoader.LoadCertificate(defaultCertConfig, "Default"); if (defaultCert != null) { DefaultCertificateConfig = defaultCertConfig; Options.DefaultCertificate = defaultCert; } } else { var(certificate, certificateConfig) = FindDeveloperCertificateFile(); if (certificate != null) { Logger.LocatedDevelopmentCertificate(certificate); DefaultCertificateConfig = certificateConfig; Options.DefaultCertificate = certificate; } } }
private void LoadDefaultCert(ConfigurationReader configReader) { if (configReader.Certificates.TryGetValue("Default", out var defaultCertConfig)) { var defaultCert = LoadCertificate(defaultCertConfig, "Default"); if (defaultCert != null) { DefaultCertificateConfig = defaultCertConfig; Options.DefaultCertificate = defaultCert; } } else { var logger = Options.ApplicationServices.GetRequiredService <ILogger <KestrelServer> >(); var(certificate, certificateConfig) = FindDeveloperCertificateFile(configReader, logger); if (certificate != null) { logger.LocatedDevelopmentCertificate(certificate); DefaultCertificateConfig = certificateConfig; Options.DefaultCertificate = certificate; } } }
public HandleClientHelloState( IServiceProvider serviceProvider, INegotiatior negotiatior, IRandom random, VersionConfig versionConfig, CipherSuiteConfig cipherSuiteConfig, CertificateConfig certificateConfig, RandomConfig randomConfig, SessionConfig sessionConfig, ClientHelloMessage handshake) { _serviceProvider = serviceProvider; _negotiatior = negotiatior; _random = random; _versionConfig = versionConfig; _cipherSuiteConfig = cipherSuiteConfig; _certificateConfig = certificateConfig; _randomConfig = randomConfig; _sessionConfig = sessionConfig; _handshake = handshake; }
// Adds endpoints from config to KestrelServerOptions.ConfigurationBackedListenOptions and configures some other options. // Any endpoints that were removed from the last time endpoints were loaded are returned. internal (List <ListenOptions>, List <ListenOptions>) Reload() { var endpointsToStop = Options.ConfigurationBackedListenOptions.ToList(); var endpointsToStart = new List <ListenOptions>(); Options.ConfigurationBackedListenOptions.Clear(); DefaultCertificateConfig = null; ConfigurationReader = new ConfigurationReader(Configuration); Options.Latin1RequestHeaders = ConfigurationReader.Latin1RequestHeaders; LoadDefaultCert(ConfigurationReader); foreach (var endpoint in ConfigurationReader.Endpoints) { var listenOptions = AddressBinder.ParseAddress(endpoint.Url, out var https); Options.ApplyEndpointDefaults(listenOptions); if (endpoint.Protocols.HasValue) { listenOptions.Protocols = endpoint.Protocols.Value; } else { // Ensure endpoint is reloaded if it used the default protocol and the protocol changed. // listenOptions.Protocols should already be set to this by ApplyEndpointDefaults. endpoint.Protocols = ConfigurationReader.EndpointDefaults.Protocols; } // Compare to UseHttps(httpsOptions => { }) var httpsOptions = new HttpsConnectionAdapterOptions(); if (https) { // Defaults Options.ApplyHttpsDefaults(httpsOptions); // Specified httpsOptions.ServerCertificate = LoadCertificate(endpoint.Certificate, endpoint.Name) ?? httpsOptions.ServerCertificate; if (httpsOptions.ServerCertificate == null && httpsOptions.ServerCertificateSelector == null) { // Fallback Options.ApplyDefaultCert(httpsOptions); // Ensure endpoint is reloaded if it used the default certificate and the certificate changed. endpoint.Certificate = DefaultCertificateConfig; } } // Now that defaults have been loaded, we can compare to the currently bound endpoints to see if the config changed. // There's no reason to rerun an EndpointConfigurations callback if nothing changed. var matchingBoundEndpoints = endpointsToStop.Where(o => o.EndpointConfig == endpoint).ToList(); if (matchingBoundEndpoints.Count > 0) { endpointsToStop.RemoveAll(o => o.EndpointConfig == endpoint); Options.ConfigurationBackedListenOptions.AddRange(matchingBoundEndpoints); continue; } if (EndpointConfigurations.TryGetValue(endpoint.Name, out var configureEndpoint)) { var endpointConfig = new EndpointConfiguration(https, listenOptions, httpsOptions, endpoint.ConfigSection); configureEndpoint(endpointConfig); } // EndpointDefaults or configureEndpoint may have added an https adapter. if (https && !listenOptions.IsTls) { if (httpsOptions.ServerCertificate == null && httpsOptions.ServerCertificateSelector == null) { throw new InvalidOperationException(CoreStrings.NoCertSpecifiedNoDevelopmentCertificateFound); } listenOptions.UseHttps(httpsOptions); } listenOptions.EndpointConfig = endpoint; endpointsToStart.Add(listenOptions); Options.ConfigurationBackedListenOptions.Add(listenOptions); } return(endpointsToStop, endpointsToStart); }