/// <summary> /// Returns a selected certificate based on configuration. /// </summary> /// <param name="certificateSubject">The subject serial number of the certificate</param> /// <returns>Returns a selected certificate based on configuration.</returns> public X509Certificate2 GetCertificate(CertificateSubject certificateSubject) { CertificateLoader certificateLoader = new CertificateLoader(); switch (_config.Action) { case LdapCertificateLookupTestConfig.LookupAction.FindCertificate: // 1. Attempt to load the certificate from store: return(certificateLoader.GetCertificateFromStoreWithSSN( certificateSubject.SerialNumberValue, _config.StoreLocation, _config.StoreName )); case LdapCertificateLookupTestConfig.LookupAction.ConnectionFailed: LdapSettings settings = ConfigurationHandler.GetConfigurationSection <LdapSettings>(); throw new ConnectingToLdapServerFailedException(settings, new Exception(this.ToString())); case LdapCertificateLookupTestConfig.LookupAction.SearchFailed: throw new SearchFailedException(new Exception(this.ToString())); default: throw new NotImplementedException(); } }
public void can_load() { var loader = new CertificateLoader(); loader.Load(certificate2.Thumbprint) .SerialNumber.ShouldEqual(certificate2.SerialNumber); }
/// <summary> /// Creates a <see cref="RestClient"/> using a given <see cref="AuthenticationData"/> /// </summary> /// <param name="authenticationData">The data from which the instance will be created</param> public static RestClient CreateFrom(AuthenticationData authenticationData) { switch (authenticationData.Type) { case AuthenticationMethodProvider.AuthenticationType.SymmetricKey: { // Getting a specific module using REST with SAS token authentication string key = AuthenticationFileUtils.GetBase64EncodedSymmetricKeyFromFile(authenticationData.FilePath); string keyTarget = authenticationData.Identity == AuthenticationMethodProvider.AuthenticationIdentity.Device ? authenticationData.GatewayHostName : // Device Sas Token $"{authenticationData.IdScope}/registrations/{authenticationData.RegistrationId}"; // DPS Sas Token string sasToken = GenerateSaSToken(key, keyTarget, TimeSpan.FromMinutes(_sasTokenTtl)); var restClient = new RestClient(authenticationData.GatewayHostName, sasToken); return(restClient); } case AuthenticationMethodProvider.AuthenticationType.SelfSignedCertificate: { X509Certificate2 cert = CertificateLoader.Load(authenticationData.CertificateLocation.Value, authenticationData.FilePath); var restClient = new RestClient(authenticationData.GatewayHostName, cert); return(restClient); } default: throw new ArgumentOutOfRangeException(nameof(authenticationData.Type), authenticationData.Type, "Unsupported authentication type"); } }
public static async Task Main() { Console.Title = "Mutual TLS client"; try { CertificateLoader.ValidateTrustedRootCertificate(); var response = await RequestTokenAsync(); response.Show(); WriteYellowLine("Press any key to continue..."); ReadLine(); await CallServiceAsync(response.AccessToken); } catch (Exception exception) { WriteRedLine(exception.ToString()); } WriteYellowLine("Press any key to close..."); ReadLine(); }
public static IAppBuilder UseIdentityServer(this IAppBuilder app, string pathPrefix = "/identity") { return(app.Map(pathPrefix, subApp => { subApp.UseIdentityServer(new IdentityServerOptions { SiteName = "Waste Products Identity Server", SigningCertificate = CertificateLoader.Load(), Factory = new IdentityServerServiceFactory().Configure(), RequireSsl = true, LoggingOptions = new LoggingOptions { EnableHttpLogging = true, EnableKatanaLogging = true, EnableWebApiDiagnostics = true, WebApiDiagnosticsIsVerbose = false }, AuthenticationOptions = new AuthenticationOptions { EnablePostSignOutAutoRedirect = true } }); })); }
private void LoadRootCertificates(RootCertificateCollectionConfig rootCertificateCollectionConfig) { CertificateLoader certificateLoader = new CertificateLoader(); foreach (RootCertificateLocation rootCertificateLocation in rootCertificateCollectionConfig.RootCertificateCollection) { try { X509Certificate2 loadedRootCertificate = certificateLoader.GetCertificateFromCertificateStoreInformation(rootCertificateLocation); this.rootCertificateDirectory.Add(loadedRootCertificate.Thumbprint.ToLowerInvariant(), loadedRootCertificate); } catch (CertificateLoaderCertificateNotFoundException notFoundException) { // So, this root certificate was not found. try { this.logger.Warn(notFoundException.Message); } catch (Exception) { this.logger.Warn(string.Format("Root certificate ({0}) not found. StoreLocation: {1}. StoreName: {2}. SerialNumber: {3}.", rootCertificateLocation.Description, rootCertificateLocation.StoreLocation, rootCertificateLocation.StoreName, rootCertificateLocation.SerialNumber)); } } catch (Exception ex) { Debug.Fail(ex.Message); } } }
public async Task RunAsync() { try { await EnsureCertificateAsync(); } catch (LetsEncryptException ex) { if (ErrorHandler != null) { var errorInfo = new ErrorInfo { Continue = ContinueHandler != null, Exception = ex }; ErrorHandler(errorInfo); if (!errorInfo.Continue) { ContinueHandler = null; } } } // Retrieve the certificate from loader CertificateLoader.TryLoad(Options.Hostname, out var certificate); // This starts the actual web app await ContinueHandler ?.Invoke(certificate) ?.RunAsync(); }
private static void EnsureCertificateIsAllowedForServerAuth(X509Certificate2 certificate) { if (!CertificateLoader.IsCertificateAllowedForServerAuth(certificate)) { throw new InvalidOperationException($@"Certificate {certificate.Thumbprint} cannot be used as an SSL server certificate. It has an Extended Key Usage extension but the usages do not include Server Authentication (OID 1.3.6.1.5.5.7.3.1)."); } }
private static void SetHttpsAndUrls(KestrelServerOptions kestrelOptions, IWireMockMiddlewareOptions wireMockMiddlewareOptions, IEnumerable <HostUrlDetails> urlDetails) { foreach (var urlDetail in urlDetails) { if (urlDetail.IsHttps) { kestrelOptions.Listen(System.Net.IPAddress.Any, urlDetail.Port, listenOptions => { if (wireMockMiddlewareOptions.CustomCertificateDefined) { listenOptions.UseHttps(CertificateLoader.LoadCertificate( wireMockMiddlewareOptions.X509StoreName, wireMockMiddlewareOptions.X509StoreLocation, wireMockMiddlewareOptions.X509ThumbprintOrSubjectName, wireMockMiddlewareOptions.X509CertificateFilePath, wireMockMiddlewareOptions.X509CertificatePassword, urlDetail.Host) ); } else { listenOptions.UseHttps(); } }); } else { kestrelOptions.Listen(System.Net.IPAddress.Any, urlDetail.Port); } } }
public void Run() { try { EnsureCertificate(); } catch (LetsEncryptException ex) { Logger?.LogError(ex, ex.InnerException?.Message); if (ErrorHandler != null) { var errorInfo = new ErrorInfo { Continue = ContinueHandler != null, Exception = ex }; ErrorHandler(errorInfo); if (!errorInfo.Continue) { ContinueHandler = null; } } } // Retrieve the certificate from loader CertificateLoader.TryLoad(Options.Hostname, out var certificate); // This starts the actual web app ContinueHandler ?.Invoke(certificate) ?.Run(); }
public static void Main(string[] args) { var cert = CertificateLoader.LoadFromStoreCert("localhost", StoreName.My.ToString(), StoreLocation.CurrentUser, true); var hostBuilder = new HostBuilder() .ConfigureLogging((_, factory) => { factory.SetMinimumLevel(LogLevel.Trace); factory.AddConsole(); }) .ConfigureWebHost(webHost => { webHost.UseKestrel() // Things like APLN and cert should be able to be passed from corefx into bedrock .UseQuic(options => { options.Certificate = cert; options.RegistrationName = "Quic"; options.Alpn = "h3-24"; options.IdleTimeout = TimeSpan.FromHours(1); }) .ConfigureKestrel((context, options) => { var basePort = 5555; options.Listen(IPAddress.Any, basePort, listenOptions => { listenOptions.UseHttps(); listenOptions.Protocols = HttpProtocols.Http3; }); }) .UseStartup <Startup>(); }); hostBuilder.Build().Run(); }
public void ShouldLoadCertificateFromLocalFile() { using (X509Certificate2 certificate = CertificateLoader.Load(AuthenticationMethodProvider.CertificateLocation.LocalFile, _tempCertificatePath)) { Assert.AreEqual(_expectedCertificate.Thumbprint, certificate.Thumbprint); } }
public void IsCertificateAllowedForServerAuth_AllowWithNoExtensions(string testCertName) { var certPath = TestResources.GetCertPath(testCertName); TestOutputHelper.WriteLine("Loading " + certPath); var cert = new X509Certificate2(certPath, "testPassword"); Assert.Empty(cert.Extensions.OfType<X509EnhancedKeyUsageExtension>()); Assert.True(CertificateLoader.IsCertificateAllowedForServerAuth(cert)); }
public void ConfigureServices(IServiceCollection services) { services.AddTransient(p => new HouseholdConfiguration(p.GetService <IConfiguration>())); services.AddTransient(p => new ProductsImportHandler(p.GetService <ILogger <ProductsImportHandler> >())); services.AddDbContext <HouseholdDbContext>( o => DatabaseSystemFeatures.DefineSqlServer(o, HouseholdConfiguration)); services.AddDefaultIdentity <ApplicationUser>() .AddEntityFrameworkStores <HouseholdDbContext>(); services.Configure <IdentityOptions>(options => { options.Password.RequireDigit = false; options.Password.RequireUppercase = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; }); var key = CertificateLoader.LoadRsaSecurityKey(HouseholdConfiguration.KeyPath); services.AddIdentityServer() .AddAspNetIdentity <ApplicationUser>() .AddOperationalStore <HouseholdDbContext>() .AddIdentityResources() .AddSigningCredential(key, IdentityServerConstants.RsaSigningAlgorithm.PS512) .AddApiResources() .AddClients(); services.AddAuthentication() .AddIdentityServerJwt(); services.AddCors(); services.AddControllersWithViews(); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); services.AddRazorPages(); services.AddMvc().AddRazorPagesOptions(o => { o.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()); }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Apishka", Version = "v1" }); }); services.AddAutoMapper(typeof(Startup)); services.Configure <KestrelServerOptions>(options => { options.AllowSynchronousIO = true; }); }
public void GetCertificateByThumbprint_VeriSignCA_FindsCertificate() { const string veriSignClass3PublicPrimaryCertificationAuthorityG5Thumbprint = "4e b6 d5 78 49 9b 1c cf 5f 58 1e ad 56 be 3d 9b 67 44 a5 e5"; var cert = CertificateLoader.GetCertificateByThumbprint(StoreName.Root, StoreLocation.LocalMachine, veriSignClass3PublicPrimaryCertificationAuthorityG5Thumbprint); Assert.AreEqual(@"CN=VeriSign Class 3 Public Primary Certification Authority - G5, OU=""(c) 2006 VeriSign, Inc. - For authorized use only"", OU=VeriSign Trust Network, O=""VeriSign, Inc."", C=US", cert.Subject); }
public static HttpClient CreateHttpClient(IProxyAndRecordSettings settings) { #if NETSTANDARD || NETCOREAPP3_1 || NET5_0 var handler = new HttpClientHandler { CheckCertificateRevocationList = false, SslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls, ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; #elif NET46 var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; #else var handler = new WebRequestHandler { ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; #endif if (!string.IsNullOrEmpty(settings.ClientX509Certificate2ThumbprintOrSubjectName)) { handler.ClientCertificateOptions = ClientCertificateOption.Manual; var x509Certificate2 = CertificateLoader.LoadCertificate(settings.ClientX509Certificate2ThumbprintOrSubjectName); handler.ClientCertificates.Add(x509Certificate2); } handler.AllowAutoRedirect = settings.AllowAutoRedirect == true; // If UseCookies enabled, httpClient ignores Cookie header handler.UseCookies = false; if (settings.WebProxySettings != null) { handler.UseProxy = true; handler.Proxy = new WebProxy(settings.WebProxySettings.Address); if (settings.WebProxySettings.UserName != null && settings.WebProxySettings.Password != null) { handler.Proxy.Credentials = new NetworkCredential(settings.WebProxySettings.UserName, settings.WebProxySettings.Password); } } var client = new HttpClient(handler); #if NET452 || NET46 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; #endif return(client); }
public void EncryptDecrypt() { var loader = new CertificateLoader(); var certificate = loader.Load(new FileInfo(FileName).Adapt(), PassPhrase); var cipher = new RSACertificateCipher(new X509CertificateSimpleProvider(certificate)); var encryptedData = cipher.Encrypt(DataToEncrypt); var decryptedData = cipher.Decrypt(encryptedData); Assert.Equal(DataToEncrypt, decryptedData); }
public void ItLoadsPemAndKeyFileByDefault(string keyFormat, string thumbprint) { var path = Path.Combine(AppContext.BaseDirectory, "TestAssets", "Https", keyFormat); var options = new Mock <CommandLineOptions>(); options.SetupGet(o => o.UseTls).Returns(true); Assert.True(CertificateLoader.TryLoadCertificate(options.Object, path, out var x509, out _)); Assert.NotNull(x509); Assert.Equal(thumbprint, x509.Thumbprint); Assert.True(x509.HasPrivateKey, "Cert should have private key"); }
public void IsCertificateAllowedForServerAuth_RejectsCertificatesMissingServerEku(string testCertName) { var certPath = TestResources.GetCertPath(testCertName); TestOutputHelper.WriteLine("Loading " + certPath); var cert = new X509Certificate2(certPath, "testPassword"); Assert.NotEmpty(cert.Extensions); var eku = Assert.Single(cert.Extensions.OfType<X509EnhancedKeyUsageExtension>()); Assert.NotEmpty(eku.EnhancedKeyUsages); Assert.False(CertificateLoader.IsCertificateAllowedForServerAuth(cert)); }
public Key(string pem) { var k = new CertificateLoader().LoadFirst<AsymmetricCipherKeyPair>("key", pem); _rsaKey = k.Private as RsaPrivateCrtKeyParameters; if (_rsaKey == null) throw new SecularException("Cannot find key in PEM string."); var rsaKeyParameters = new RsaKeyParameters(false, _rsaKey.Modulus, _rsaKey.PublicExponent); PublicKey = new PublicKey(rsaKeyParameters); }
public static void When_load_certificate_thumb_empty() { const string thumbprint = ""; var norm = CertificateLoader.NormalizeThumbprint(thumbprint); Assert.Equal(string.Empty, norm); Assert.Throws <ArgumentNullException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out _)); Assert.Throws <ArgumentNullException>(() => CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false)); }
public void ItLoadsCertPfxFileByDefault() { var path = Path.Combine(AppContext.BaseDirectory, "TestAssets", "Https", "pfx"); var options = new Mock <CommandLineOptions>(); options.SetupGet(o => o.CertificatePassword).Returns("testPassword"); options.SetupGet(o => o.UseTls).Returns(true); Assert.True(CertificateLoader.TryLoadCertificate(options.Object, path, out var x509, out _)); Assert.NotNull(x509); Assert.Equal("E8481D606B15080024C806EFE89B00F0976BD906", x509.Thumbprint); Assert.True(x509.HasPrivateKey, "Cert should have private key"); }
public static void When_load_certificate_thumb_short_by_N(int n) { var thumbprint = s_existingCertificate.Thumbprint.Substring(n); // Too short var norm = CertificateLoader.NormalizeThumbprint(thumbprint); Assert.Equal(thumbprint.Length, norm.Length); Assert.NotEqual(CertificateLoader.Sha1Length, norm.Length); Assert.Throws <FormatException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out _)); Assert.Throws <FormatException>(() => CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false)); }
public static void When_load_certificate_thumb_noisy_only() { var thumbprint = new string('?', CertificateLoader.Sha1Length); // Special characters only var norm = CertificateLoader.NormalizeThumbprint(thumbprint); Assert.Equal(0, norm.Length); Assert.Throws <ArgumentNullException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, norm, false, out _)); Assert.Throws <FormatException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out _)); Assert.Throws <FormatException>(() => CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false)); }
private void ConfigureOAuth(IAppBuilder app) { app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions { //Authority = "https://localhost:44326/identity", Authority = "https://waste-api.belpyro.net/identity", RequiredScopes = new[] { IdentityConstants.WasteProducts_Api_Scope }, SigningCertificate = CertificateLoader.Load(), ValidationMode = ValidationMode.ValidationEndpoint }); app.UseIdentityServer(); }
public static void When_load_certificate_thumb_noisy_short(int n) { var thumbprint = "\n" + s_existingCertificate.Thumbprint.Substring(n) + "\t"; // Too short after removing special chars var norm = CertificateLoader.NormalizeThumbprint(thumbprint); Assert.NotEqual(thumbprint.Length, norm.Length); Assert.NotEqual(CertificateLoader.Sha1Length, norm.Length); Assert.Throws <FormatException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, norm, false, out _)); Assert.Throws <FormatException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out _)); Assert.Throws <FormatException>(() => CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false)); }
public static void When_load_certificate_thumb_noisy_short_0() { const string thumbprint = "\r\n"; // 0 chars after removing special chars var norm = CertificateLoader.NormalizeThumbprint(thumbprint); Assert.NotEqual(thumbprint.Length, norm.Length); Assert.Equal(0, norm.Length); Assert.Throws <ArgumentNullException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, norm, false, out _)); Assert.Throws <ArgumentNullException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out _)); Assert.Throws <ArgumentNullException>(() => CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false)); }
public void IsCertificateAllowedForServerAuth_ValidatesEnhancedKeyUsageOnCertificate(string testCertName) { var certPath = TestResources.GetCertPath(testCertName); _output.WriteLine("Loading " + certPath); var cert = new X509Certificate2(certPath, "testPassword"); Assert.NotEmpty(cert.Extensions); var eku = Assert.Single(cert.Extensions.OfType <X509EnhancedKeyUsageExtension>()); Assert.NotEmpty(eku.EnhancedKeyUsages); Assert.True(CertificateLoader.IsCertificateAllowedForServerAuth(cert)); }
public static void When_load_certificate_thumb_nonexistent() { var thumbprint = "00000" + s_existingCertificate.Thumbprint.Substring(10) + "00000"; // Valid format but unlikely to exist var norm = CertificateLoader.NormalizeThumbprint(thumbprint); Assert.Equal(thumbprint.Length, norm.Length); Assert.Equal(CertificateLoader.Sha1Length, norm.Length); var found = CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out _); Assert.False(found); Assert.Throws <InvalidOperationException>(() => CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false)); }
private void button3_Click(object sender, EventArgs e) { byte[] priKey = PKCS8.PrivateKeyInfo.Encode(CertificateLoader.ConvertPrivateKeyToRSA(certificate.PrivateKeyInfo.PrivateKey)); if (File.Exists(textBox2.Text)) { MessageBox.Show("파일이 이미 존재함", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } using (FileStream fs = new FileStream(textBox2.Text, FileMode.Create, FileAccess.Write)) { fs.Write(priKey, 0, priKey.Length); fs.Flush(); } MessageBox.Show("내보냈습니다.", "결과", MessageBoxButtons.OK, MessageBoxIcon.Information); }
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)); }