private string GetIssuerCertificate(CertificateRequest certificate, CertificateProvider cp) { Log("\t\t\t\tGetIssuerCertificate started"); var linksEnum = certificate.Links; if (linksEnum == null) { Log("\t\t\t\t\tGetIssuerCertificate error linksEnum == null"); Log("\t\t\t\tGetIssuerCertificate ended"); return(null); } var links = new LinkCollection(linksEnum); var upLink = links.GetFirstOrDefault("up"); if (upLink == null) { Log("\t\t\t\t\tGetIssuerCertificate error upLink == null"); Log("\t\t\t\tGetIssuerCertificate ended"); return(null); } var temporaryFileName = Path.GetTempFileName(); try { using (var web = new WebClient()) { var uri = new Uri(this.BaseUri, upLink.Uri); web.DownloadFile(uri, temporaryFileName); } var cacert = new X509Certificate2(temporaryFileName); var sernum = cacert.GetSerialNumberString(); var cacertDerFile = string.Format("ca-{0}-crt.der", sernum); var cacertPemFile = string.Format("ca-{0}-crt.pem", sernum); if (!File.Exists(cacertDerFile)) { File.Copy(temporaryFileName, cacertDerFile, true); } if (!File.Exists(cacertPemFile)) { using (FileStream source = new FileStream(cacertDerFile, FileMode.Open), target = new FileStream(cacertPemFile, FileMode.Create)) { var caCrt = cp.ImportCertificate(EncodingFormat.DER, source); cp.ExportCertificate(caCrt, EncodingFormat.PEM, target); } } Log("\t\t\t\tGetIssuerCertificate ended"); return(cacertPemFile); } catch (Exception ex) { Log("\t\t\t\t\tGetIssuerCertificate error {0}", ex.Message); } finally { if (File.Exists(temporaryFileName)) { File.Delete(temporaryFileName); } } Log("\t\t\t\tGetIssuerCertificate ended"); return(null); }
public virtual TlsCredentials?GetClientCredentials(CertificateRequest certificateRequest) { return(null); }
public TlsCredentials GetClientCredentials(TlsContext context, CertificateRequest certificateRequest) { return(GetClientCredentials(certificateRequest)); }
private static X509Certificate2 GenerateCertificate( string subjectName, Action <TestCertificateGenerator> modifyGenerator, RSA rsa, NuGet.Common.HashAlgorithmName hashAlgorithm, RSASignaturePaddingMode paddingMode, ChainCertificateRequest chainCertificateRequest) { if (string.IsNullOrEmpty(subjectName)) { subjectName = "NuGetTest"; } // Create cert var subjectDN = $"CN={subjectName}"; var certGen = new TestCertificateGenerator(); var isSelfSigned = true; X509Certificate2 issuer = null; DateTimeOffset? notAfter = null; var keyUsage = X509KeyUsageFlags.DigitalSignature; if (chainCertificateRequest != null) { if (chainCertificateRequest.Issuer != null) { isSelfSigned = false; // for a certificate with an issuer assign Authority Key Identifier issuer = chainCertificateRequest?.Issuer; notAfter = issuer.NotAfter.Subtract(TimeSpan.FromMinutes(5)); var publicKey = DotNetUtilities.GetRsaPublicKey(issuer.GetRSAPublicKey()); certGen.Extensions.Add( new X509Extension( Oids.AuthorityKeyIdentifier, new AuthorityKeyIdentifierStructure(publicKey).GetEncoded(), critical: false)); } if (chainCertificateRequest.ConfigureCrl) { // for a certificate in a chain create CRL distribution point extension var issuerDN = chainCertificateRequest?.Issuer?.Subject ?? subjectDN; var crlServerUri = $"{chainCertificateRequest.CrlServerBaseUri}{issuerDN}.crl"; var generalName = new Org.BouncyCastle.Asn1.X509.GeneralName(Org.BouncyCastle.Asn1.X509.GeneralName.UniformResourceIdentifier, new DerIA5String(crlServerUri)); var distPointName = new DistributionPointName(new GeneralNames(generalName)); var distPoint = new DistributionPoint(distPointName, null, null); certGen.Extensions.Add( new X509Extension( TestOids.CrlDistributionPoints, new DerSequence(distPoint).GetDerEncoded(), critical: false)); } if (chainCertificateRequest.IsCA) { // update key usage with CA cert sign and crl sign attributes keyUsage |= X509KeyUsageFlags.CrlSign | X509KeyUsageFlags.KeyCertSign; } } var padding = paddingMode.ToPadding(); var request = new CertificateRequest(subjectDN, rsa, hashAlgorithm.ConvertToSystemSecurityHashAlgorithmName(), padding); certGen.NotAfter = notAfter ?? DateTime.UtcNow.Add(TimeSpan.FromMinutes(30)); certGen.NotBefore = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(30)); var random = new Random(); var serial = random.Next(); var serialNumber = BitConverter.GetBytes(serial); Array.Reverse(serialNumber); certGen.SetSerialNumber(serialNumber); certGen.Extensions.Add( new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false)); certGen.Extensions.Add( new X509KeyUsageExtension(keyUsage, critical: false)); certGen.Extensions.Add( new X509BasicConstraintsExtension(certificateAuthority: chainCertificateRequest?.IsCA ?? false, hasPathLengthConstraint: false, pathLengthConstraint: 0, critical: true)); // Allow changes modifyGenerator?.Invoke(certGen); foreach (var extension in certGen.Extensions) { request.CertificateExtensions.Add(extension); } X509Certificate2 certResult; if (isSelfSigned) { certResult = request.CreateSelfSigned(certGen.NotBefore, certGen.NotAfter); } else { using (var temp = request.Create(issuer, certGen.NotBefore, certGen.NotAfter, certGen.SerialNumber)) { certResult = temp.CopyWithPrivateKey(rsa); } } return(new X509Certificate2(certResult.Export(X509ContentType.Pkcs12), password: (string)null, keyStorageFlags: X509KeyStorageFlags.Exportable)); }
public async Task <ImmutableArray <SecurityKey> > GetSigningKeysAsync() { var settings = await GetSettingsAsync(); // If a certificate was explicitly provided, return it immediately // instead of using the fallback managed certificates logic. if (settings.CertificateStoreLocation != null && settings.CertificateStoreName != null && !string.IsNullOrEmpty(settings.CertificateThumbprint)) { var certificate = GetCertificate( settings.CertificateStoreLocation.Value, settings.CertificateStoreName.Value, settings.CertificateThumbprint); if (certificate != null) { return(ImmutableArray.Create <SecurityKey>(new X509SecurityKey(certificate))); } _logger.LogWarning("The signing certificate '{Thumbprint}' could not be found in the " + "{StoreLocation}/{StoreName} store.", settings.CertificateThumbprint, settings.CertificateStoreLocation.Value.ToString(), settings.CertificateStoreName.Value.ToString()); } try { var certificates = (await GetManagedSigningCertificatesAsync()).Select(tuple => tuple.certificate).ToList(); if (certificates.Any(certificate => certificate.NotAfter.AddDays(-7) > DateTime.Now)) { return(ImmutableArray.CreateRange <SecurityKey>( from certificate in certificates select new X509SecurityKey(certificate))); } try { // If the certificates list is empty or only contains certificates about to expire, // generate a new certificate and add it on top of the list to ensure it's preferred // by OpenIddict to the other certificates when issuing JWT access or identity tokens. certificates.Insert(0, await GenerateSigningCertificateAsync()); return(ImmutableArray.CreateRange <SecurityKey>( from certificate in certificates select new X509SecurityKey(certificate))); } catch (Exception exception) { _logger.LogError(exception, "An error occurred while trying to generate a X.509 signing certificate."); } } catch (Exception exception) { _logger.LogWarning(exception, "An error occurred while trying to retrieve the X.509 signing certificates."); } // If none of the previous attempts succeeded, try to generate an ephemeral RSA key // and add it in the tenant memory cache so that future calls to this method return it. return(ImmutableArray.Create <SecurityKey>(_memoryCache.GetOrCreate(nameof(RsaSecurityKey), entry => { entry.SetPriority(CacheItemPriority.NeverRemove); return new RsaSecurityKey(GenerateRsaSigningKey(2048)); }))); RSA GenerateRsaSigningKey(int size) { RSA algorithm; // By default, the default RSA implementation used by .NET Core relies on the newest Windows CNG APIs. // Unfortunately, when a new key is generated using the default RSA.Create() method, it is not bound // to the machine account, which may cause security exceptions when running Orchard on IIS using a // virtual application pool identity or without the profile loading feature enabled (off by default). // To ensure a RSA key can be generated flawlessly, it is manually created using the managed CNG APIs. // For more information, visit https://github.com/openiddict/openiddict-core/issues/204. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Warning: ensure a null key name is specified to ensure the RSA key is not persisted by CNG. var key = CngKey.Create(CngAlgorithm.Rsa, keyName: null, new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextExport, KeyCreationOptions = CngKeyCreationOptions.MachineKey, KeyUsage = CngKeyUsages.Signing, Parameters = { new CngProperty("Length", BitConverter.GetBytes(size), CngPropertyOptions.None) } }); algorithm = new RSACng(key); } else { algorithm = RSA.Create(size); } return(algorithm); } async Task <X509Certificate2> GenerateSigningCertificateAsync() { var subject = GetSubjectName(); var algorithm = GenerateRsaSigningKey(size: 2048); // Note: ensure the digitalSignature bit is added to the certificate, so that no validation error // is returned to clients that fully validate the certificates chain and their X.509 key usages. var request = new CertificateRequest(subject, algorithm, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, critical: true)); var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddMonths(3)); // Note: setting the friendly name is not supported on Unix machines (including Linux and macOS). // To ensure an exception is not thrown by the property setter, an OS runtime check is used here. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { certificate.FriendlyName = "OrchardCore OpenID Server Signing Certificate"; } var directory = Directory.CreateDirectory(Path.Combine( _shellOptions.CurrentValue.ShellsApplicationDataPath, _shellOptions.CurrentValue.ShellsContainerName, _shellSettings.Name, "IdentityModel-Signing-Certificates")); var password = GeneratePassword(); var path = Path.Combine(directory.FullName, Guid.NewGuid().ToString()); await File.WriteAllBytesAsync(Path.ChangeExtension(path, ".pfx"), certificate.Export(X509ContentType.Pfx, password)); await File.WriteAllTextAsync(Path.ChangeExtension(path, ".pwd"), _dataProtector.Protect(password)); return(certificate); X500DistinguishedName GetSubjectName() { try { return(new X500DistinguishedName("CN=" + (_shellSettings.RequestUrlHost ?? "localhost"))); } catch { return(new X500DistinguishedName("CN=localhost")); } } string GeneratePassword() { Span <byte> data = stackalloc byte[256 / 8]; RandomNumberGenerator.Fill(data); return(Convert.ToBase64String(data, Base64FormattingOptions.None)); } } }
private string GetIssuerCertificate(CertificateRequest certificate, IPkiTool cp, string certificateFolder, TargetApplication targetApplication) { var linksEnum = certificate.Links; if (linksEnum == null) { return(null); } var links = new LinkCollection(linksEnum); var upLink = links.GetFirstOrDefault("up"); if (upLink == null) { return(null); } var temporaryFileName = Path.GetTempFileName(); try { using (var web = new WebClient()) { var acmeServerBaseUri = _configuration.GetAcmeServerBaseUri(targetApplication); var uri = new Uri(acmeServerBaseUri, upLink.Uri); web.DownloadFile(uri, temporaryFileName); } var cacert = new X509Certificate2(temporaryFileName); var sernum = cacert.GetSerialNumberString(); var cacertDerFile = Path.Combine(certificateFolder, $"ca-{sernum}-crt.der"); var cacertPemFile = Path.Combine(certificateFolder, $"ca-{sernum}-crt.pem"); if (!File.Exists(cacertDerFile)) { File.Copy(temporaryFileName, cacertDerFile, true); } _logger.Information("Saving issuer certificate to {cacertPemFile}", cacertPemFile); if (File.Exists(cacertPemFile)) { return(cacertPemFile); } using (FileStream source = new FileStream(cacertDerFile, FileMode.Open), target = new FileStream(cacertPemFile, FileMode.Create)) { var caCrt = cp.ImportCertificate(EncodingFormat.DER, source); cp.ExportCertificate(caCrt, EncodingFormat.PEM, target); } return(cacertPemFile); } finally { if (File.Exists(temporaryFileName)) { File.Delete(temporaryFileName); } } }
public StressServer(Configuration configuration) { ServerUri = configuration.ServerUri; (string scheme, string hostname, int port) = ParseServerUri(configuration.ServerUri); IWebHostBuilder host = WebHost.CreateDefaultBuilder(); if (configuration.UseHttpSys) { // Use http.sys. This requires additional manual configuration ahead of time; // see https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/httpsys?view=aspnetcore-2.2#configure-windows-server. // In particular, you need to: // 1. Create a self-signed cert and install it into your local personal store, e.g. New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My" // 2. Pre-register the URL prefix, e.g. netsh http add urlacl url=https://localhost:5001/ user=Users // 3. Register the cert, e.g. netsh http add sslcert ipport=[::1]:5001 certhash=THUMBPRINTFROMABOVE appid="{some-guid}" host = host.UseHttpSys(hso => { hso.UrlPrefixes.Add(ServerUri); hso.Authentication.Schemes = Microsoft.AspNetCore.Server.HttpSys.AuthenticationSchemes.None; hso.Authentication.AllowAnonymous = true; hso.MaxConnections = null; hso.MaxRequestBodySize = null; }); } else { // Use Kestrel, and configure it for HTTPS with a self-signed test certificate. host = host.UseKestrel(ko => { // conservative estimation based on https://github.com/aspnet/AspNetCore/blob/caa910ceeba5f2b2c02c47a23ead0ca31caea6f0/src/Servers/Kestrel/Core/src/Internal/Http2/Http2Stream.cs#L204 ko.Limits.MaxRequestLineSize = Math.Max(ko.Limits.MaxRequestLineSize, configuration.MaxRequestUriSize + 100); ko.Limits.MaxRequestHeaderCount = Math.Max(ko.Limits.MaxRequestHeaderCount, configuration.MaxRequestHeaderCount); ko.Limits.MaxRequestHeadersTotalSize = Math.Max(ko.Limits.MaxRequestHeadersTotalSize, configuration.MaxRequestHeaderTotalSize); ko.Limits.Http2.MaxStreamsPerConnection = configuration.ServerMaxConcurrentStreams ?? ko.Limits.Http2.MaxStreamsPerConnection; ko.Limits.Http2.MaxFrameSize = configuration.ServerMaxFrameSize ?? ko.Limits.Http2.MaxFrameSize; ko.Limits.Http2.InitialConnectionWindowSize = configuration.ServerInitialConnectionWindowSize ?? ko.Limits.Http2.InitialConnectionWindowSize; ko.Limits.Http2.MaxRequestHeaderFieldSize = configuration.ServerMaxRequestHeaderFieldSize ?? ko.Limits.Http2.MaxRequestHeaderFieldSize; switch (hostname) { case "+": case "*": ko.ListenAnyIP(port, ConfigureListenOptions); break; default: IPAddress iPAddress = Dns.GetHostAddresses(hostname).First(); ko.Listen(iPAddress, port, ConfigureListenOptions); break; } void ConfigureListenOptions(ListenOptions listenOptions) { if (scheme == "https") { // Create self-signed cert for server. using (RSA rsa = RSA.Create()) { var certReq = new CertificateRequest("CN=contoso.com", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); certReq.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false)); certReq.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false)); certReq.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false)); X509Certificate2 cert = certReq.CreateSelfSigned(DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow.AddMonths(1)); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { cert = new X509Certificate2(cert.Export(X509ContentType.Pfx)); } listenOptions.UseHttps(cert); } } else { listenOptions.Protocols = configuration.HttpVersion == new Version(2, 0) ? HttpProtocols.Http2 : HttpProtocols.Http1; } } }); }; // Output only warnings and errors from Kestrel host = host .ConfigureLogging(log => log.AddFilter("Microsoft.AspNetCore", level => configuration.LogAspNet ? level >= LogLevel.Warning : false)) // Set up how each request should be handled by the server. .Configure(app => { app.UseRouting(); app.UseEndpoints(MapRoutes); }); // Handle command-line arguments. _eventListener = configuration.LogPath == null ? null : new HttpEventListener(configuration.LogPath != "console" ? new StreamWriter(configuration.LogPath) { AutoFlush = true } : null); SetUpJustInTimeLogging(); _webHost = host.Build(); _webHost.Start(); }
/// <summary> /// Create the X509 extensions to build the certificate. /// </summary> /// <param name="request"></param> private void CreateX509Extensions(CertificateRequest request) { // Basic Constraints X509BasicConstraintsExtension bc = GetBasicContraints(); request.CertificateExtensions.Add(bc); // Subject Key Identifier var ski = new X509SubjectKeyIdentifierExtension( request.PublicKey, X509SubjectKeyIdentifierHashAlgorithm.Sha1, false); request.CertificateExtensions.Add(ski); // Authority Key Identifier X509Extension authorityKeyIdentifier = IssuerCAKeyCert != null ? X509Extensions.BuildAuthorityKeyIdentifier(IssuerCAKeyCert) : new X509AuthorityKeyIdentifierExtension( ski.SubjectKeyIdentifier.FromHexString(), SubjectName, m_serialNumber ); request.CertificateExtensions.Add(authorityKeyIdentifier); X509KeyUsageFlags keyUsageFlags; if (m_isCA) { keyUsageFlags = X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign; } else { // Key Usage keyUsageFlags = X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.NonRepudiation | X509KeyUsageFlags.KeyEncipherment; if (IssuerCAKeyCert == null) { // self signed case keyUsageFlags |= X509KeyUsageFlags.KeyCertSign; } } request.CertificateExtensions.Add( new X509KeyUsageExtension( keyUsageFlags, true)); if (!m_isCA) { // Enhanced key usage request.CertificateExtensions.Add( new X509EnhancedKeyUsageExtension( new OidCollection { new Oid(Oids.ServerAuthentication), new Oid(Oids.ClientAuthentication) }, true)); } foreach (var extension in m_extensions) { request.CertificateExtensions.Add(extension); } }
public static void CheckTimeNested() { HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA256; using (RSA rsa = RSA.Create(TestData.RsaBigExponentParams)) { CertificateRequest request = new CertificateRequest("CN=Issuer", rsa, hashAlgorithm, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add( new X509BasicConstraintsExtension(true, false, 0, true)); DateTimeOffset now = DateTimeOffset.UtcNow; DateTimeOffset notBefore = now.AddMinutes(-10); DateTimeOffset notAfter = now.AddMinutes(10); if (notAfter.Millisecond > 900) { // We're only going to add 1, but let's be defensive. notAfter -= TimeSpan.FromMilliseconds(200); } using (X509Certificate2 issuer = request.CreateSelfSigned(notBefore, notAfter)) { request = new CertificateRequest("CN=Leaf", rsa, hashAlgorithm, RSASignaturePadding.Pkcs1); byte[] serial = { 3, 1, 4, 1, 5, 9 }; // Boundary case, exact match: Issue+Dispose request.Create(issuer, notBefore, notAfter, serial).Dispose(); DateTimeOffset truncatedNotBefore = new DateTimeOffset( notBefore.Year, notBefore.Month, notBefore.Day, notBefore.Hour, notBefore.Minute, notBefore.Second, notBefore.Offset); // Boundary case, the notBefore rounded down: Issue+Dispose request.Create(issuer, truncatedNotBefore, notAfter, serial).Dispose(); // Boundary case, the notAfter plus a millisecond, same second rounded down. request.Create(issuer, notBefore, notAfter.AddMilliseconds(1), serial).Dispose();//); // The notBefore value a whole second earlier: AssertExtensions.Throws <ArgumentException>("notBefore", () => { request.Create(issuer, notBefore.AddSeconds(-1), notAfter, serial).Dispose(); }); // The notAfter value bumped past the second mark: DateTimeOffset tooLate = notAfter.AddMilliseconds(1000 - notAfter.Millisecond); AssertExtensions.Throws <ArgumentException>("notAfter", () => { request.Create(issuer, notBefore, tooLate, serial).Dispose(); }); // And ensure that both out of range isn't magically valid again AssertExtensions.Throws <ArgumentException>("notBefore", () => { request.Create(issuer, notBefore.AddDays(-1), notAfter.AddDays(1), serial).Dispose(); }); } } }
/// <summary> /// Method to execute the command /// </summary> private void GetBackupCredentialsWithCertificate(string certificate) { // for .netStandard var targetLocation = string.IsNullOrEmpty(Path) ? Utilities.GetDefaultPath() : Path; if (!Directory.Exists(targetLocation)) { throw new ArgumentException(Resources.VaultCredPathException); } var subscriptionId = DefaultContext.Subscription.Id; var displayName = Vault.Name; WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.ExecutingGetVaultCredCmdlet, subscriptionId, Vault.ResourceGroupName, Vault.Name, targetLocation)); VaultCertificateResponse vaultCertificateResponse; var channelIntegrityKey = string.Empty; try { // Upload cert into ID Mgmt WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.UploadingCertToIdmgmt)); X509Certificate2 x509 = new X509Certificate2(); byte[] data = Convert.FromBase64String(certificate); x509.Import(data); var bytes = x509.RawData; var certificateArgs = new CertificateRequest { Properties = new RawCertificateData { Certificate = bytes, AuthType = AuthType.AAD } }; var dateString = DateTime.Now.ToString("M-d-yyyy"); var friendlyName = string.Format("{0}{1}-{2}-vaultcredentials", Vault.Name, subscriptionId, dateString); vaultCertificateResponse = RecoveryServicesClient.GetRecoveryServicesClient.VaultCertificates.CreateWithHttpMessagesAsync( Vault.ResourceGroupName, Vault.Name, friendlyName, certificateArgs.Properties, RecoveryServicesClient.GetRequestHeaders()).Result.Body; WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.UploadedCertToIdmgmt)); } catch (Exception exception) { throw exception; } // generate vault credentials var vaultCredsFileContent = GenerateVaultCredsForBackup(certificate, subscriptionId, vaultCertificateResponse); // NOTE: One of the scenarios for this cmdlet is to generate a file which will be an input // to DPM servers. // We found a bug in the DPM UI which is looking for a particular namespace in the input file. // The below is a hack to circumvent this issue and this would be removed once the bug can be fixed. vaultCredsFileContent = vaultCredsFileContent.Replace("Microsoft.Azure.Commands.AzureBackup.Models", "Microsoft.Azure.Portal.RecoveryServices.Models.Common"); // prepare for download var fileName = string.Format("{0}_{1:ddd MMM dd yyyy}.VaultCredentials", displayName, DateTime.UtcNow); var filePath = System.IO.Path.Combine(targetLocation, fileName); WriteDebug(string.Format(Resources.SavingVaultCred, filePath)); AzureSession.Instance.DataStore.WriteFile(filePath, Encoding.UTF8.GetBytes(vaultCredsFileContent)); var output = new VaultSettingsFilePath { FilePath = filePath, }; // Output filename back to user WriteObject(output); }
private void GetSiteRecoveryCredentialsWithCertificate(string certificate) { var subscriptionId = DefaultContext.Subscription.Id; var site = new ASRSite(); if (!string.IsNullOrEmpty(SiteIdentifier) && !string.IsNullOrEmpty(SiteFriendlyName)) { site.ID = SiteIdentifier; site.Name = SiteFriendlyName; } try { var fileName = GenerateFileName(); var filePath = string.IsNullOrEmpty(Path) ? Utilities.GetDefaultPath() : Path; var fullFilePath = System.IO.Path.Combine(filePath, fileName); // Upload cert into ID Mgmt WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.UploadingCertToIdmgmt)); X509Certificate2 x509 = new X509Certificate2(); byte[] data = Convert.FromBase64String(certificate); x509.Import(data); var bytes = x509.RawData; var certificateArgs = new CertificateRequest { Properties = new RawCertificateData { Certificate = bytes, AuthType = AuthType.AAD } }; var dateString = DateTime.Now.ToString("M-d-yyyy"); var friendlyName = string.Format("{0}{1}-{2}-vaultcredentials", Vault.Name, subscriptionId, dateString); var vaultCertificateResponse = RecoveryServicesClient.GetRecoveryServicesClient.VaultCertificates.CreateWithHttpMessagesAsync( Vault.ResourceGroupName, Vault.Name, friendlyName, certificateArgs.Properties, RecoveryServicesClient.GetRequestHeaders()).Result.Body; WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.UploadedCertToIdmgmt)); var vaultCredsFileContent = GenerateVaultCredsForSiteRecovery( certificate, subscriptionId, vaultCertificateResponse, site); WriteDebug(string.Format(Resources.SavingVaultCred, fullFilePath)); AzureSession.Instance.DataStore.WriteFile(fullFilePath, Encoding.UTF8.GetBytes(vaultCredsFileContent)); var output = new VaultSettingsFilePath { FilePath = fullFilePath, }; // Output filename back to user WriteObject(output, true); } catch (Exception exception) { throw exception; } }
public async Task <CertificateRequest> RevokeCertificateRequestAsync(ClientContext context, CertificateRequest certificateRequest) { await Configure.AwaitFalse(); var uriBuilder = new AppleDeveloperRequestUriBuilder(new RestUri(this.UrlProvider.DownloadCertificateUrl, new { platform = certificateRequest.Platform })); uriBuilder.AddQueryValues(new Dictionary <string, string> { { "teamId", certificateRequest.TeamId }, { "certificateId", certificateRequest.CertificateId }, { "type", certificateRequest.CertificateTypeDisplayId.ToStringValue() } }); var request = RestRequest.Post(uriBuilder.ToUri()); var response = await this.SendAsync <Result <CertificateRequest> >(context, request); this.CheckResultForErrors(response.Content); return(response.Content.Data); }
public async Task <X509Certificate2> DownloadCertificateAsync(ClientContext context, CertificateRequest certificateRequest) { await Configure.AwaitFalse(); var bytes = await this.DownloadRawCertificateAsync(context, certificateRequest); return(bytes != null ? new X509Certificate2(bytes) : null); }
public async Task <byte[]> DownloadRawCertificateAsync(ClientContext context, CertificateRequest certificateRequest) { await Configure.AwaitFalse(); var uriBuilder = new AppleDeveloperRequestUriBuilder(new RestUri(this.UrlProvider.DownloadCertificateUrl, new { platform = certificateRequest.Platform })); uriBuilder.AddQueryValues(new Dictionary <string, string> { { "teamId", certificateRequest.TeamId }, { "certificateId", certificateRequest.CertificateId }, { "type", certificateRequest.CertificateTypeDisplayId.ToStringValue() } }); var request = RestRequest.Get(uriBuilder.ToUri()); var response = await this.SendAsync(context, request); var binaryContent = response.RawContent as RawBinaryContent; return(binaryContent?.Value); }
public TlsCredentials GetClientCredentials(CertificateRequest certificateRequest) { return(null); }
public static void ReproduceBigExponentCert() { DateTimeOffset notBefore = new DateTimeOffset(2016, 3, 2, 1, 48, 0, TimeSpan.Zero); DateTimeOffset notAfter = new DateTimeOffset(2017, 3, 2, 1, 48, 0, TimeSpan.Zero); byte[] serialNumber = "9B5DE6C15126A58B".HexToByteArray(); var subject = new X500DistinguishedName( "CN=localhost, OU=.NET Framework (CoreFX), O=Microsoft Corporation, L=Redmond, S=Washington, C=US"); X509Extension skidExtension = new X509SubjectKeyIdentifierExtension( "78A5C75D51667331D5A96924114C9B5FA00D7BCB", false); X509Extension akidExtension = new X509Extension( "2.5.29.35", "3016801478A5C75D51667331D5A96924114C9B5FA00D7BCB".HexToByteArray(), false); X509Extension basicConstraints = new X509BasicConstraintsExtension(true, false, 0, false); X509Certificate2 cert; using (RSA rsa = RSA.Create()) { rsa.ImportParameters(TestData.RsaBigExponentParams); var request = new CertificateRequest(subject, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(skidExtension); request.CertificateExtensions.Add(akidExtension); request.CertificateExtensions.Add(basicConstraints); var signatureGenerator = X509SignatureGenerator.CreateForRSA(rsa, RSASignaturePadding.Pkcs1); cert = request.Create(subject, signatureGenerator, notBefore, notAfter, serialNumber); } const string expectedHex = "308203EB308202D3A0030201020209009B5DE6C15126A58B300D06092A864886" + "F70D01010B050030818A310B3009060355040613025553311330110603550408" + "130A57617368696E67746F6E3110300E060355040713075265646D6F6E64311E" + "301C060355040A13154D6963726F736F667420436F72706F726174696F6E3120" + "301E060355040B13172E4E4554204672616D65776F726B2028436F7265465829" + "31123010060355040313096C6F63616C686F7374301E170D3136303330323031" + "343830305A170D3137303330323031343830305A30818A310B30090603550406" + "13025553311330110603550408130A57617368696E67746F6E3110300E060355" + "040713075265646D6F6E64311E301C060355040A13154D6963726F736F667420" + "436F72706F726174696F6E3120301E060355040B13172E4E4554204672616D65" + "776F726B2028436F726546582931123010060355040313096C6F63616C686F73" + "7430820124300D06092A864886F70D010101050003820111003082010C028201" + "0100AF81C1CBD8203F624A539ED6608175372393A2837D4890E48A19DED36973" + "115620968D6BE0D3DAA38AA777BE02EE0B6B93B724E8DCC12B632B4FA80BBC92" + "5BCE624F4CA7CC606306B39403E28C932D24DD546FFE4EF6A37F10770B2215EA" + "8CBB5BF427E8C4D89B79EB338375100C5F83E55DE9B4466DDFBEEE42539AEF33" + "EF187B7760C3B1A1B2103C2D8144564A0C1039A09C85CF6B5974EB516FC8D662" + "3C94AE3A5A0BB3B4C792957D432391566CF3E2A52AFB0C142B9E0681B8972671" + "AF2B82DD390A39B939CF719568687E4990A63050CA7768DCD6B378842F18FDB1" + "F6D9FF096BAF7BEB98DCF930D66FCFD503F58D41BFF46212E24E3AFC45EA42BD" + "884702050200000441A350304E301D0603551D0E0416041478A5C75D51667331" + "D5A96924114C9B5FA00D7BCB301F0603551D2304183016801478A5C75D516673" + "31D5A96924114C9B5FA00D7BCB300C0603551D13040530030101FF300D06092A" + "864886F70D01010B0500038201010077756D05FFA6ADFED5B6D4AFB540840C6D" + "01CF6B3FA6C973DFD61FCAA0A814FA1E2469019D94B1D856D07DD2B95B8550DF" + "D2085953A494B99EFCBAA7982CE771984F9D4A445FFEE062E8A049736A39FD99" + "4E1FDA0A5DC2B5B0E57A0B10C41BC7FE6A40B24F85977302593E60B98DD4811D" + "47D948EDF8D6E6B5AF80A1827496E20BFD240E467674504D4E4703331D64705C" + "36FB6E14BABFD9CBEEC44B33A8D7B36479900F3C5BBAB69C5E453D180783E250" + "8051B998C038E4622571D2AB891D898E5458828CF18679517D28DBCABF72E813" + "07BFD721B73DDB1751123F99D8FC0D533798C4DBD14719D5D8A85B00A144A367" + "677B48891A9B56F045334811BACB7A"; using (cert) { Assert.Equal(expectedHex, cert.RawData.ByteArrayToHex()); } }
public virtual TlsCredentials GetClientCredentials(CertificateRequest certificateRequest) { byte[] certificateTypes = certificateRequest.CertificateTypes; if (certificateTypes == null || !Arrays.Contains(certificateTypes, ClientCertificateType.rsa_sign)) return null; SignatureAndHashAlgorithm signatureAndHashAlgorithm = null; IList sigAlgs = certificateRequest.SupportedSignatureAlgorithms; if (sigAlgs != null) { foreach (SignatureAndHashAlgorithm sigAlg in sigAlgs) { if (sigAlg.Signature == SignatureAlgorithm.rsa) { signatureAndHashAlgorithm = sigAlg; break; } } if (signatureAndHashAlgorithm == null) { return null; } } return TlsTestUtilities.LoadSignerCredentials(mContext, new string[] { "x509-client.pem", "x509-ca.pem" }, "x509-client-key.pem", signatureAndHashAlgorithm); }
public static void FractionalSecondsNotWritten(bool selfSigned) { using (X509Certificate2 savedCert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) using (RSA rsa = savedCert.GetRSAPrivateKey()) { X500DistinguishedName subjectName = new X500DistinguishedName("CN=Test"); var request = new CertificateRequest( subjectName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); // notBefore is a date before 2050 UTC (encoded using UTC TIME), // notAfter is a date after 2050 UTC (encoded using GENERALIZED TIME). DateTimeOffset notBefore = new DateTimeOffset(2049, 3, 4, 5, 6, 7, 89, TimeSpan.Zero); DateTimeOffset notAfter = notBefore.AddYears(2); Assert.NotEqual(0, notAfter.Millisecond); DateTimeOffset normalizedBefore = notBefore.AddMilliseconds(-notBefore.Millisecond); DateTimeOffset normalizedAfter = notAfter.AddMilliseconds(-notAfter.Millisecond); byte[] manualSerialNumber = { 3, 2, 1 }; X509Certificate2 cert; if (selfSigned) { cert = request.CreateSelfSigned(notBefore, notAfter); } else { cert = request.Create( subjectName, X509SignatureGenerator.CreateForRSA(rsa, RSASignaturePadding.Pkcs1), notBefore, notAfter, manualSerialNumber); } using (cert) { Assert.Equal(normalizedBefore.DateTime.ToLocalTime(), cert.NotBefore); Assert.Equal(normalizedAfter.DateTime.ToLocalTime(), cert.NotAfter); if (selfSigned) { // The serial number used in CreateSelfSigned is random, so find the issuer name, // and the validity period is the next 34 bytes. Verify it was encoded as expected. // // Since the random serial number is at most 9 bytes and the subjectName encoded // value is 17 bytes, there's no chance of an early false match. byte[] encodedCert = cert.RawData; byte[] needle = subjectName.RawData; int index = encodedCert.AsSpan().IndexOf(needle); Assert.Equal( "3020170D3439303330343035303630375A180F32303531303330343035303630375A", encodedCert.AsSpan(index + needle.Length, 34).ByteArrayToHex()); } else { // The entire encoding is deterministic in this mode. Assert.Equal( "308201953081FFA0030201020203030201300D06092A864886F70D01010B0500" + "300F310D300B06035504031304546573743020170D3439303330343035303630" + "375A180F32303531303330343035303630375A300F310D300B06035504031304" + "5465737430819F300D06092A864886F70D010101050003818D00308189028181" + "00B11E30EA87424A371E30227E933CE6BE0E65FF1C189D0D888EC8FF13AA7B42" + "B68056128322B21F2B6976609B62B6BC4CF2E55FF5AE64E9B68C78A3C2DACC91" + "6A1BC7322DD353B32898675CFB5B298B176D978B1F12313E3D865BC53465A11C" + "CA106870A4B5D50A2C410938240E92B64902BAEA23EB093D9599E9E372E48336" + "730203010001300D06092A864886F70D01010B0500038181000095ABC7CC7B01" + "9C2A88A7891165B6ACCDBC5137D80C0A5151B11FD4D789CCE808412ABF05FFB1" + "D9BE097776147A6D4C3EE177E5F9C2C9E8C005D72A6473F9904185B95634BFB4" + "EA80B232B271DC1BF20A2FDC46FC93771636B618F29417C31D5F602236FDB414" + "CDC1BEDE700E31E80DC5E7BB7D3F367420B72925605C916BDA", cert.RawData.ByteArrayToHex()); } } } }
/// <summary> /// Uploads a certificate for a resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='certificateName'> /// Certificate friendly name. /// </param> /// <param name='properties'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <VaultCertificateResponse> > CreateWithHttpMessagesAsync(string resourceGroupName, string vaultName, string certificateName, RawCertificateData properties = default(RawCertificateData), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (certificateName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "certificateName"); } CertificateRequest certificateRequest = new CertificateRequest(); if (properties != null) { certificateRequest.Properties = properties; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("certificateName", certificateName); tracingParameters.Add("certificateRequest", certificateRequest); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/certificates/{certificateName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{certificateName}", System.Uri.EscapeDataString(certificateName)); List <string> _queryParameters = new List <string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (certificateRequest != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(certificateRequest, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <VaultCertificateResponse>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <VaultCertificateResponse>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public FileContentResult get_ssl_certificate(DistinguishedName dName) { var rootCA = CertUtil.getInstance().getRootCA(); var rsa = RSA.Create(); var request = new CertificateRequest(dName.getX509DistinguishedName(), rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); var subjectANB = new SubjectAlternativeNameBuilder(); subjectANB.AddDnsName(dName.DNS); subjectANB.AddEmailAddress(dName.E); request.CertificateExtensions.Add(subjectANB.Build()); request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false)); request.CertificateExtensions.Add(new X509KeyUsageExtension( X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.NonRepudiation, false) ); // set the AuthorityKeyIdentifier. There is no built-in // support, so it needs to be copied from the Subject Key // Identifier of the signing certificate and massaged slightly. // AuthorityKeyIdentifier is "KeyID=" var issuerSubjectKey = rootCA.Extensions["Subject Key Identifier"].RawData; var segment = new byte[issuerSubjectKey.Length - 2]; Buffer.BlockCopy(issuerSubjectKey, 2, segment, 0, issuerSubjectKey.Length - 2); var authorityKeyIdentifer = new byte[segment.Length + 4]; // these bytes define the "KeyID" part of the AuthorityKeyIdentifer var KeyID = new byte[] { 0x30, 0x16, 0x80, 0x14 }; KeyID.CopyTo(authorityKeyIdentifer, 0); segment.CopyTo(authorityKeyIdentifer, 4); request.CertificateExtensions.Add(new X509Extension("2.5.29.35", authorityKeyIdentifer, false)); request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension( new OidCollection { new Oid("1.3.6.1.5.5.7.3.8"), // Timestamping new Oid("1.3.6.1.5.5.7.3.2"), // TLS Client auth new Oid("1.3.6.1.5.5.7.3.1") // TLS Server auth }, false) ); request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, false)); // Add Time and Key X509Certificate2 sslCert = request.Create(rootCA, DateTimeOffset.Now, DateTimeOffset.Now.AddYears(1), BitConverter.GetBytes(DateTimeOffset.Now.Ticks)); sslCert = sslCert.CopyWithPrivateKey(rsa); // Create PFX (PKCS #12) with private key byte[] p12Cert = sslCert.Export(X509ContentType.Pkcs12, "password"); // Create Base 64 encoded CER (public key only) string cerCert = "-----BEGIN CERTIFICATE-----\r\n" + Convert.ToBase64String(sslCert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks) + "\r\n-----END CERTIFICATE-----"; byte[] pfxCert = sslCert.Export(X509ContentType.Pfx, "password"); String CertID = DateTimeOffset.Now.Ticks.ToString(); // Write to disk System.IO.File.WriteAllBytes(AppContext.BaseDirectory + "/" + CertID + ".p12", p12Cert); System.IO.File.WriteAllText(AppContext.BaseDirectory + "/" + CertID + ".cer", cerCert); System.IO.File.WriteAllBytes(AppContext.BaseDirectory + "/" + CertID + ".pfx", pfxCert); FileContentResult fcResult = File(p12Cert, "application/octet-stream", CertID + ".p12"); //FileContentResult fcResult = File(System.Text.Encoding.ASCII.GetBytes(cerCert), "application/octet-stream", "176743490865.cer"); return(fcResult); }
/// <summary> /// Creates a KeyVault signed certificate. /// </summary> /// <returns>The signed certificate</returns> public static Task <X509Certificate2> CreateSignedCertificate( string applicationUri, string applicationName, string subjectName, IList <String> domainNames, ushort keySize, DateTime notBefore, DateTime notAfter, ushort hashSizeInBits, X509Certificate2 issuerCAKeyCert, RSA publicKey, X509SignatureGenerator generator, bool caCert = false, string extensionUrl = null ) { if (publicKey == null) { throw new NotSupportedException("Need a public key and a CA certificate."); } if (publicKey.KeySize != keySize) { throw new NotSupportedException(String.Format("Public key size {0} does not match expected key size {1}", publicKey.KeySize, keySize)); } // new serial number byte[] serialNumber = new byte[SerialNumberLength]; RandomNumberGenerator.Fill(serialNumber); serialNumber[0] &= 0x7F; // set default values. X500DistinguishedName subjectDN = SetSuitableDefaults( ref applicationUri, ref applicationName, ref subjectName, ref domainNames, ref keySize); var request = new CertificateRequest(subjectDN, publicKey, GetRSAHashAlgorithmName(hashSizeInBits), RSASignaturePadding.Pkcs1); // Basic constraints request.CertificateExtensions.Add( new X509BasicConstraintsExtension(caCert, caCert, 0, true)); // Subject Key Identifier var ski = new X509SubjectKeyIdentifierExtension( request.PublicKey, X509SubjectKeyIdentifierHashAlgorithm.Sha1, false); request.CertificateExtensions.Add(ski); // Authority Key Identifier if (issuerCAKeyCert != null) { request.CertificateExtensions.Add(BuildAuthorityKeyIdentifier(issuerCAKeyCert)); } else { request.CertificateExtensions.Add(BuildAuthorityKeyIdentifier(subjectDN, serialNumber.Reverse().ToArray(), ski)); } if (caCert) { request.CertificateExtensions.Add( new X509KeyUsageExtension( X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true)); if (extensionUrl != null) { // add CRL endpoint, if available request.CertificateExtensions.Add( BuildX509CRLDistributionPoints(PatchExtensionUrl(extensionUrl, serialNumber)) ); } } else { // Key Usage X509KeyUsageFlags defaultFlags = X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.NonRepudiation | X509KeyUsageFlags.KeyEncipherment; if (issuerCAKeyCert == null) { // self signed case defaultFlags |= X509KeyUsageFlags.KeyCertSign; } request.CertificateExtensions.Add( new X509KeyUsageExtension(defaultFlags, true)); // Enhanced key usage request.CertificateExtensions.Add( new X509EnhancedKeyUsageExtension( new OidCollection { new Oid("1.3.6.1.5.5.7.3.1"), new Oid("1.3.6.1.5.5.7.3.2") }, true)); // Subject Alternative Name var subjectAltName = BuildSubjectAlternativeName(applicationUri, domainNames); request.CertificateExtensions.Add(new X509Extension(subjectAltName, false)); if (issuerCAKeyCert != null && extensionUrl != null) { // add Authority Information Access, if available request.CertificateExtensions.Add( BuildX509AuthorityInformationAccess(new string[] { PatchExtensionUrl(extensionUrl, issuerCAKeyCert.SerialNumber) }) ); } } if (issuerCAKeyCert != null) { if (notAfter > issuerCAKeyCert.NotAfter) { notAfter = issuerCAKeyCert.NotAfter; } if (notBefore < issuerCAKeyCert.NotBefore) { notBefore = issuerCAKeyCert.NotBefore; } } var issuerSubjectName = issuerCAKeyCert != null ? issuerCAKeyCert.SubjectName : subjectDN; X509Certificate2 signedCert = request.Create( issuerSubjectName, generator, notBefore, notAfter, serialNumber ); return(Task.FromResult <X509Certificate2>(signedCert)); }
public virtual TlsCredentials GetClientCredentials(CertificateRequest certificateRequest) { if (mOuter.mConfig.serverCertReq == TlsTestConfig.SERVER_CERT_REQ_NONE) throw new InvalidOperationException(); if (mOuter.mConfig.clientAuth == TlsTestConfig.CLIENT_AUTH_NONE) return null; byte[] certificateTypes = certificateRequest.CertificateTypes; if (certificateTypes == null || !Arrays.Contains(certificateTypes, ClientCertificateType.rsa_sign)) { return null; } TlsSignerCredentials signerCredentials = TlsTestUtilities.LoadSignerCredentials(mContext, certificateRequest.SupportedSignatureAlgorithms, SignatureAlgorithm.rsa, "x509-client.pem", "x509-client-key.pem"); if (mOuter.mConfig.clientAuth == TlsTestConfig.CLIENT_AUTH_VALID) { return signerCredentials; } return new MyTlsSignerCredentials(mOuter, signerCredentials); }
public async Task InvokeAsync(HttpContext context) { var credentialsProvider = context.RequestServices.GetService <DeveloperCertificateSigningCredentialsSource>(); if (credentialsProvider == null) { await _next(context); return; } if (_environment.IsDevelopment() && context.Request.Path.Equals(_options.Value.ListeningEndpoint)) { if (context.Request.Method.Equals(HttpMethods.Get)) { var credentials = await credentialsProvider.GetCredentials(); bool hasDevelopmentCertificate = await IsDevelopmentCertificateConfiguredAndValid(); var foundDeveloperCertificate = FoundDeveloperCertificate(); if (!foundDeveloperCertificate || !hasDevelopmentCertificate) { var page = new DeveloperCertificateErrorPage(); page.Model = new DeveloperCertificateViewModel() { CertificateExists = foundDeveloperCertificate, CertificateIsInvalid = !hasDevelopmentCertificate, Options = _options.Value }; await page.ExecuteAsync(context); return; } } if (context.Request.Method.Equals(HttpMethods.Post)) { CreateDevelopmentCertificate(); return; } } await _next(context); void CreateDevelopmentCertificate() { #if NETCOREAPP2_0 || NETCOREAPP2_1 using (var rsa = RSA.Create(2048)) { var signingRequest = new CertificateRequest( new X500DistinguishedName("CN=Identity.Development"), rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); var enhacedKeyUsage = new OidCollection(); enhacedKeyUsage.Add(new Oid("1.3.6.1.5.5.7.3.1", "Server Authentication")); signingRequest.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(enhacedKeyUsage, critical: true)); signingRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, critical: true)); var certificate = signingRequest.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddYears(1)); certificate.FriendlyName = "Identity Service developer certificate"; // We need to take this step so that the key gets persisted. var export = certificate.Export(X509ContentType.Pkcs12, ""); var imported = new X509Certificate2(export, "", X509KeyStorageFlags.PersistKeySet); Array.Clear(export, 0, export.Length); using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadWrite); store.Add(imported); store.Close(); context.Response.StatusCode = StatusCodes.Status204NoContent; }; } #elif NETSTANDARD2_0 #else #error The target frameworks need to be updated. #endif } bool FoundDeveloperCertificate() { using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); var developmentCertificate = store.Certificates.Find( X509FindType.FindBySubjectName, "Identity.Development", validOnly: false); store.Close(); return(developmentCertificate.OfType <X509Certificate2>().Any()); } } async Task <bool> IsDevelopmentCertificateConfiguredAndValid() { var certificates = await credentialsProvider.GetCredentials(); return(certificates.Any( c => _timeStampManager.IsValidPeriod(c.NotBefore, c.Expires) && c.Credentials.Key is X509SecurityKey key && key.Certificate.Subject.Equals("CN=Identity.Development"))); } }
public virtual byte[] Export() { using var ephemeralRsa = RSA.Create(_certificateBuilderConfiguration.KeySizeInBits); var request = new CertificateRequest( BuildX500DistinguishedName(), ephemeralRsa, _certificateBuilderConfiguration.HashAlgorithmName, _certificateBuilderConfiguration.RsaSignaturePadding); request.CertificateExtensions.Add( new X509KeyUsageExtension(_certificateBuilderConfiguration.X509KeyUsageFlags, false)); if (_certificateBuilderConfiguration.Issuer == null) { request.CertificateExtensions.Add( new X509BasicConstraintsExtension(true, false, -1, false)); } switch (_certificateBuilderConfiguration.CertificateType) { case CertificateTypes.Server: request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(Constants.ServerCertificate, false)); break; case CertificateTypes.Client: request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(Constants.ClientCertificate, false)); break; case CertificateTypes.Signing: request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(Constants.SigningCertificate, false)); break; default: throw new InvalidOperationException(); } request.CertificateExtensions.Add(BuildSubjectAlternativeName()); var notBefore = _certificateBuilderConfiguration.Issuer?.NotBefore ?? DateTime.UtcNow.AddDays(-1); var notAfter = _certificateBuilderConfiguration.Issuer?.NotAfter ?? DateTime.UtcNow.AddDays(_certificateBuilderConfiguration.ExpiresInDays); var certificate = _certificateBuilderConfiguration.Issuer == null ? request.CreateSelfSigned(notBefore, notAfter) : request.Create(_certificateBuilderConfiguration.Issuer, notBefore, notAfter, _certificateBuilderConfiguration.Issuer.GetSerialNumber()); certificate.FriendlyName = _certificateBuilderConfiguration.CertificateName; var exportedCertificate = _certificateBuilderConfiguration.Issuer == null ? certificate.Export( _certificateBuilderConfiguration.X509ContentType, _certificateBuilderConfiguration.CertificatePassword) : certificate.CopyWithPrivateKey(ephemeralRsa).Export( _certificateBuilderConfiguration.X509ContentType, _certificateBuilderConfiguration.CertificatePassword); return(exportedCertificate); }
private static void RunTest( string targetName, string subjectCN, IList <string> sanDnsNames, bool flattenCase, bool expectedResult) { using (RSA rsa = RSA.Create(TestData.RsaBigExponentParams)) { CertificateRequest request = new CertificateRequest( $"CN={FixCase(subjectCN, flattenCase)}, O=.NET Framework (CoreFX)", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add( new X509KeyUsageExtension( X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.DigitalSignature, false)); if (sanDnsNames != null) { var builder = new SubjectAlternativeNameBuilder(); foreach (string sanDnsName in sanDnsNames) { builder.AddDnsName(sanDnsName); } X509Extension extension = builder.Build(); // The SAN builder will have done DNS case normalization via IdnMapping. // We need to undo that here. if (!flattenCase) { UTF8Encoding encoding = new UTF8Encoding(); byte[] extensionBytes = extension.RawData; Span <byte> extensionSpan = extensionBytes; foreach (string sanDnsName in sanDnsNames) { // If the string is longer than 127 then the quick DER encoding check // is not correct. Assert.InRange(sanDnsName.Length, 1, 127); byte[] lowerBytes = encoding.GetBytes(sanDnsName.ToLowerInvariant()); byte[] mixedBytes = encoding.GetBytes(sanDnsName); // Only 7-bit ASCII should be here, no byte expansion. // (non-7-bit ASCII values require IdnMapping normalization) Assert.Equal(sanDnsName.Length, lowerBytes.Length); Assert.Equal(sanDnsName.Length, mixedBytes.Length); int idx = extensionSpan.IndexOf(lowerBytes); while (idx >= 0) { if (idx < 2 || extensionBytes[idx - 2] != 0x82 || extensionBytes[idx - 1] != sanDnsName.Length) { int relativeIdx = extensionSpan.Slice(idx + 1).IndexOf(lowerBytes); idx = idx + 1 + relativeIdx; continue; } mixedBytes.AsSpan().CopyTo(extensionSpan.Slice(idx)); break; } } extension.RawData = extensionBytes; } request.CertificateExtensions.Add(extension); } DateTimeOffset start = DateTimeOffset.UtcNow.AddYears(-1); DateTimeOffset end = start.AddYears(1); using (X509Certificate2 cert = request.CreateSelfSigned(start, end)) { bool isMatch = CheckHostname(cert, targetName); string lowerTarget = targetName.ToLowerInvariant(); bool isLowerMatch = CheckHostname(cert, lowerTarget); if (expectedResult) { Assert.True(isMatch, $"{targetName} matches"); Assert.True(isLowerMatch, $"{lowerTarget} (lowercase) matches"); } else { Assert.False(isMatch, $"{targetName} matches"); Assert.False(isLowerMatch, $"{lowerTarget} (lowercase) matches"); } } } }
static X509Certificate2 CreateCertificateWithECDsa( string subject, bool isCA, int pathLength, X509Certificate2 signer = null) { // Create the key for this certificate and initialize the keysiez var ecdsa = ECDsa.Create("ECDsa"); ecdsa.KeySize = 256; var hash = HashAlgorithmName.SHA256; // Create the subject name for the new certificate var subjectName = new X500DistinguishedName(subject); // Create a certificate request - // this is codified form of the ASN certificate request format. var req = new CertificateRequest( subjectName, ecdsa, hash ); // Create basic extension to represent if the certificate is a CA. req.CertificateExtensions.Add( new X509BasicConstraintsExtension(isCA, pathLength != 0, pathLength, true) ); // Create subject key identifier extension, helps speed up creating the certificate chain. var subjectKeyExtension = new X509SubjectKeyIdentifierExtension(req.PublicKey, false); req.CertificateExtensions.Add(subjectKeyExtension); // Create authority key identifier extension, helps find the signing cert when forming chain. byte[] authorityKeyData = signer != null ? signer.Extensions[CertificateExtensionOids.AuthorityKeyIdentifier].RawData : subjectKeyExtension.RawData; var skisegment = new ArraySegment <byte>(authorityKeyData, 2, authorityKeyData.Length - 2); var authorityKeyIdentifier = new byte[skisegment.Count + 4]; // These bytes define the KeyID part of the AuthorityKeyIdentifier authorityKeyIdentifier[0] = 0x30; authorityKeyIdentifier[1] = 0x16; authorityKeyIdentifier[2] = 0x80; authorityKeyIdentifier[3] = 0x14; skisegment.CopyTo(authorityKeyIdentifier, 4); req.CertificateExtensions.Add( new X509Extension(CertificateExtensionOids.AuthorityKeyIdentifier, authorityKeyIdentifier, false) ); // Create the certificate, either selfsigned or signed by the signer. X509Certificate2 cert = signer == null ? req.CreateSelfSigned( DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddYears(1)) : req.Create( signer, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddYears(1), Guid.NewGuid().ToByteArray()); // When a certificate is signed by a CA, then its private key // is not included in the new certificate by default. // Include the private key explicitly. if (signer != null) { cert = cert.CopyWithPrivateKey(ecdsa); } return(cert); }
public Apple() { validX5cStrings = new[] { "MIICRDCCAcmgAwIBAgIGAXUCfWGDMAoGCCqGSM49BAMCMEgxHDAaBgNVBAMME0FwcGxlIFdlYkF1dGhuIENBIDExEzARBgNVBAoMCkFwcGxlIEluYy4xEzARBgNVBAgMCkNhbGlmb3JuaWEwHhcNMjAxMDA3MDk0NjEyWhcNMjAxMDA4MDk1NjEyWjCBkTFJMEcGA1UEAwxANjEyNzZmYzAyZDNmZThkMTZiMzNiNTU0OWQ4MTkyMzZjODE3NDZhODNmMmU5NGE2ZTRiZWUxYzcwZjgxYjViYzEaMBgGA1UECwwRQUFBIENlcnRpZmljYXRpb24xEzARBgNVBAoMCkFwcGxlIEluYy4xEzARBgNVBAgMCkNhbGlmb3JuaWEwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAR5/lkIu1EpyAk4t1TATSs0DvpmFbmHaYv1naTlPqPm/vsD2qEnDVgE6KthwVqsokNcfb82nXHKFcUjsABKG3W3o1UwUzAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB/wQEAwIE8DAzBgkqhkiG92NkCAIEJjAkoSIEIJxgAhVAs+GYNN/jfsYkRcieGylPeSzka5QTwyMO84aBMAoGCCqGSM49BAMCA2kAMGYCMQDaHBjrI75xAF7SXzyF5zSQB/Lg9PjTdyye+w7stiqy84K6lmo8d3fIptYjLQx81bsCMQCvC8MSN+aewiaU0bMsdxRbdDerCJJj3xJb3KZwloevJ3daCmCcrZrAPYfLp2kDOsg=", "MIICNDCCAbqgAwIBAgIQViVTlcen+0Dr4ijYJghTtjAKBggqhkjOPQQDAzBLMR8wHQYDVQQDDBZBcHBsZSBXZWJBdXRobiBSb290IENBMRMwEQYDVQQKDApBcHBsZSBJbmMuMRMwEQYDVQQIDApDYWxpZm9ybmlhMB4XDTIwMDMxODE4MzgwMVoXDTMwMDMxMzAwMDAwMFowSDEcMBoGA1UEAwwTQXBwbGUgV2ViQXV0aG4gQ0EgMTETMBEGA1UECgwKQXBwbGUgSW5jLjETMBEGA1UECAwKQ2FsaWZvcm5pYTB2MBAGByqGSM49AgEGBSuBBAAiA2IABIMuhy8mFJGBAiW59fzWu2N4tfVfP8sEW8c1mTR1/VSQRN+b/hkhF2XGmh3aBQs41FCDQBpDT7JNES1Ww+HPv8uYkf7AaWCBvvlsvHfIjd2vRqWu4d1RW1r6q5O+nAsmkaNmMGQwEgYDVR0TAQH/BAgwBgEB/wIBADAfBgNVHSMEGDAWgBQm12TZxXjCWmfRp95rEtAbY/HG1zAdBgNVHQ4EFgQU666CxP+hrFtR1M8kYQUAvmO9d4gwDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2gAMGUCMQDdixo0gaX62du052V7hB4UTCe3W4dqQYbCsUdXUDNyJ+/lVEV+9kiVDGMuXEg+cMECMCyKYETcIB/P5ZvDTSkwwUh4Udlg7Wp18etKyr44zSW4l9DIBb7wx/eLB6VxxugOBw==" }; _attestationObject = new CborMap { { "fmt", "apple" } }; var(type, alg, crv) = Fido2Tests._validCOSEParameters[0]; X509Certificate2 root, attestnCert; DateTimeOffset notBefore = DateTimeOffset.UtcNow; DateTimeOffset notAfter = notBefore.AddDays(2); var attDN = new X500DistinguishedName("CN=attest.apple.com, OU=Apple Authenticator Attestation, O=FIDO2-NET-LIB, C=US"); using (var ecdsaRoot = ECDsa.Create()) { var rootRequest = new CertificateRequest(rootDN, ecdsaRoot, HashAlgorithmName.SHA256); rootRequest.CertificateExtensions.Add(caExt); ECCurve eCCurve = ECCurve.NamedCurves.nistP256; using (root = rootRequest.CreateSelfSigned( notBefore, notAfter)) using (var ecdsaAtt = ECDsa.Create(eCCurve)) { var attRequest = new CertificateRequest(attDN, ecdsaAtt, HashAlgorithmName.SHA256); byte[] serial = new byte[12]; RandomNumberGenerator.Fill(serial); using (X509Certificate2 publicOnly = attRequest.Create( root, notBefore, notAfter, serial)) { attestnCert = publicOnly.CopyWithPrivateKey(ecdsaAtt); } var ecparams = ecdsaAtt.ExportParameters(true); var cpk = new CborMap { { COSE.KeyCommonParameter.KeyType, type }, { COSE.KeyCommonParameter.Alg, alg }, { COSE.KeyTypeParameter.X, ecparams.Q.X }, { COSE.KeyTypeParameter.Y, ecparams.Q.Y }, { COSE.KeyTypeParameter.Crv, crv } }; var x = (byte[])cpk[COSE.KeyTypeParameter.X]; var y = (byte[])cpk[COSE.KeyTypeParameter.Y]; _credentialPublicKey = new CredentialPublicKey(cpk); var X5c = new CborArray { attestnCert.RawData, root.RawData }; _attestationObject.Add("attStmt", new CborMap { { "x5c", X5c } }); } } }
/// <summary> /// Upload a certificate for a resource. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='certificateName'> /// Certificate friendly name. /// </param> /// <param name='certificateRequest'> /// Input parameters for uploading the vault certificate. /// </param> public static VaultCertificateResponse Create(this IVaultCertificatesOperations operations, string resourceGroupName, string vaultName, string certificateName, CertificateRequest certificateRequest) { return(operations.CreateAsync(resourceGroupName, vaultName, certificateName, certificateRequest).GetAwaiter().GetResult()); }
public StressServer(Configuration configuration) { ServerUri = configuration.ServerUri; (string scheme, string hostname, int port) = ParseServerUri(configuration.ServerUri); IWebHostBuilder host = WebHost.CreateDefaultBuilder(); if (configuration.UseHttpSys && OperatingSystem.IsWindows()) { // Use http.sys. This requires additional manual configuration ahead of time; // see https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/httpsys?view=aspnetcore-2.2#configure-windows-server. // In particular, you need to: // 1. Create a self-signed cert and install it into your local personal store, e.g. New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My" // 2. Pre-register the URL prefix, e.g. netsh http add urlacl url=https://localhost:5001/ user=Users // 3. Register the cert, e.g. netsh http add sslcert ipport=[::1]:5001 certhash=THUMBPRINTFROMABOVE appid="{some-guid}" host = host.UseHttpSys(hso => { hso.UrlPrefixes.Add(ServerUri); hso.Authentication.Schemes = Microsoft.AspNetCore.Server.HttpSys.AuthenticationSchemes.None; hso.Authentication.AllowAnonymous = true; hso.MaxConnections = null; hso.MaxRequestBodySize = null; }); } else { // Use Kestrel, and configure it for HTTPS with a self-signed test certificate. host = host.UseKestrel(ko => { // conservative estimation based on https://github.com/dotnet/aspnetcore/blob/caa910ceeba5f2b2c02c47a23ead0ca31caea6f0/src/Servers/Kestrel/Core/src/Internal/Http2/Http2Stream.cs#L204 ko.Limits.MaxRequestLineSize = Math.Max(ko.Limits.MaxRequestLineSize, configuration.MaxRequestUriSize + 100); ko.Limits.MaxRequestHeaderCount = Math.Max(ko.Limits.MaxRequestHeaderCount, configuration.MaxRequestHeaderCount); ko.Limits.MaxRequestHeadersTotalSize = Math.Max(ko.Limits.MaxRequestHeadersTotalSize, configuration.MaxRequestHeaderTotalSize); ko.Limits.Http2.MaxStreamsPerConnection = configuration.ServerMaxConcurrentStreams ?? ko.Limits.Http2.MaxStreamsPerConnection; ko.Limits.Http2.MaxFrameSize = configuration.ServerMaxFrameSize ?? ko.Limits.Http2.MaxFrameSize; ko.Limits.Http2.InitialConnectionWindowSize = configuration.ServerInitialConnectionWindowSize ?? ko.Limits.Http2.InitialConnectionWindowSize; ko.Limits.Http2.MaxRequestHeaderFieldSize = configuration.ServerMaxRequestHeaderFieldSize ?? ko.Limits.Http2.MaxRequestHeaderFieldSize; switch (hostname) { case "+": case "*": ko.ListenAnyIP(port, ConfigureListenOptions); break; default: IPAddress iPAddress = Dns.GetHostAddresses(hostname).First(); ko.Listen(iPAddress, port, ConfigureListenOptions); break; } void ConfigureListenOptions(ListenOptions listenOptions) { if (scheme == "https") { // Create self-signed cert for server. using (RSA rsa = RSA.Create()) { var certReq = new CertificateRequest("CN=contoso.com", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); certReq.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false)); certReq.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false)); certReq.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false)); X509Certificate2 cert = certReq.CreateSelfSigned(DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow.AddMonths(1)); if (OperatingSystem.IsWindows()) { cert = new X509Certificate2(cert.Export(X509ContentType.Pfx)); } listenOptions.UseHttps(cert); } if (configuration.HttpVersion == HttpVersion.Version30) { listenOptions.Protocols = HttpProtocols.Http3; } } else { listenOptions.Protocols = configuration.HttpVersion == HttpVersion.Version20 ? HttpProtocols.Http2 : HttpProtocols.Http1; } } }); if (configuration.HttpVersion == HttpVersion.Version30) { host = host.UseQuic(options => { options.Alpn = "h3-29"; options.IdleTimeout = TimeSpan.FromMinutes(1); }); } }; LoggerConfiguration loggerConfiguration = new LoggerConfiguration(); if (configuration.Trace) { // Clear existing logs first. foreach (var filename in Directory.GetFiles(".", "server*.log")) { try { File.Delete(filename); } catch {} } loggerConfiguration = loggerConfiguration // Output diagnostics to the file .WriteTo.File("server.log", fileSizeLimitBytes: 50 << 20, rollOnFileSizeLimit: true) .MinimumLevel.Debug(); } if (configuration.LogAspNet) { loggerConfiguration = loggerConfiguration // Output only warnings and errors .WriteTo.Console(Serilog.Events.LogEventLevel.Warning); } Log.Logger = loggerConfiguration.CreateLogger(); host = host .UseSerilog() // Set up how each request should be handled by the server. .Configure(app => { app.UseRouting(); app.UseEndpoints(MapRoutes); }); _webHost = host.Build(); _webHost.Start(); }
/// <summary> /// Upload a certificate for a resource. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='certificateName'> /// Certificate friendly name. /// </param> /// <param name='certificateRequest'> /// Input parameters for uploading the vault certificate. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <VaultCertificateResponse> CreateAsync(this IVaultCertificatesOperations operations, string resourceGroupName, string vaultName, string certificateName, CertificateRequest certificateRequest, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, vaultName, certificateName, certificateRequest, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
private string GetCertificate(string host) { Log("\t\t\tGetCertificate started"); var certificateProvider = CertificateProvider.GetProvider(); var rsaPrivateKeyParams = new RsaPrivateKeyParams() { NumBits = Properties.Settings.Default.RSAKeyBits, }; var rsaPrivateKey = certificateProvider.GeneratePrivateKey(rsaPrivateKeyParams); var csrDetails = new CsrDetails { CommonName = host, }; var csrParams = new CsrParams { Details = csrDetails, }; var csr = certificateProvider.GenerateCsr(csrParams, rsaPrivateKey, Crt.MessageDigest.SHA256); byte[] derBytes; using (var ms = new MemoryStream()) { certificateProvider.ExportCsr(csr, EncodingFormat.DER, ms); derBytes = ms.ToArray(); } CertificateRequest requestCertificate = null; var derBase64UrlEncoded = JwsHelper.Base64UrlEncode(derBytes); try { requestCertificate = this.client.RequestCertificate(derBase64UrlEncoded); } catch (Exception ex) { Log("\t\t\t\tGetCertificate error {0}", ex.InnerException.Message); certificateProvider.Dispose(); return(null); } var crtPfxFile = host + "-all.pfx"; if (requestCertificate.StatusCode != System.Net.HttpStatusCode.Created) { crtPfxFile = null; Log("\t\t\t\tGetCertificate certRequ.StatusCode {0}", requestCertificate.StatusCode); } else { var keyGenFile = host + "-gen-key.json"; var keyPemFile = host + "-key.pem"; var csrGenFile = host + "-gen-csr.json"; var csrPemFile = host + "-csr.pem"; var crtDerFile = host + "-crt.der"; var crtPemFile = host + "-crt.pem"; var chainPemFile = host + "-chain.pem"; using (var fs = new FileStream(keyGenFile, FileMode.Create)) certificateProvider.SavePrivateKey(rsaPrivateKey, fs); using (var fs = new FileStream(keyPemFile, FileMode.Create)) certificateProvider.ExportPrivateKey(rsaPrivateKey, EncodingFormat.PEM, fs); using (var fs = new FileStream(csrGenFile, FileMode.Create)) certificateProvider.SaveCsr(csr, fs); using (var fs = new FileStream(csrPemFile, FileMode.Create)) certificateProvider.ExportCsr(csr, EncodingFormat.PEM, fs); using (var file = File.Create(crtDerFile)) requestCertificate.SaveCertificate(file); Crt crt; using (FileStream source = new FileStream(crtDerFile, FileMode.Open), target = new FileStream(crtPemFile, FileMode.Create)) { crt = certificateProvider.ImportCertificate(EncodingFormat.DER, source); certificateProvider.ExportCertificate(crt, EncodingFormat.PEM, target); } // To generate a PKCS#12 (.PFX) file, we need the issuer's public certificate var isuPemFile = GetIssuerCertificate(requestCertificate, certificateProvider); using (FileStream intermediate = new FileStream(isuPemFile, FileMode.Open), certificate = new FileStream(crtPemFile, FileMode.Open), chain = new FileStream(chainPemFile, FileMode.Create)) { certificate.CopyTo(chain); intermediate.CopyTo(chain); } using (FileStream source = new FileStream(isuPemFile, FileMode.Open), target = new FileStream(crtPfxFile, FileMode.Create)) { try { var isuCrt = certificateProvider.ImportCertificate(EncodingFormat.PEM, source); certificateProvider.ExportArchive(rsaPrivateKey, new[] { crt, isuCrt }, ArchiveFormat.PKCS12, target, Properties.Settings.Default.PFXPassword); } catch (Exception ex) { Log("\t\t\t\tGetCertificate error {0}", ex.Message); } } } certificateProvider.Dispose(); Log("\t\t\tGetCertificate ended"); return(crtPfxFile); }
internal static X509Certificate2 CreateSelfSignedCertificate(string commonName, string country, string state, string locality, string organization, string organizationUnit, SecureString password, string friendlyName, DateTimeOffset from, DateTimeOffset to) { SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder(); sanBuilder.AddDnsName("localhost"); sanBuilder.AddDnsName(Environment.MachineName); var x500Values = new List <string>(); if (!string.IsNullOrWhiteSpace(commonName)) { x500Values.Add($"CN={commonName}"); } if (!string.IsNullOrWhiteSpace(country)) { x500Values.Add($"C={country}"); } if (!string.IsNullOrWhiteSpace(state)) { x500Values.Add($"S={state}"); } if (!string.IsNullOrWhiteSpace(locality)) { x500Values.Add($"L={locality}"); } if (!string.IsNullOrWhiteSpace(organization)) { x500Values.Add($"O={organization}"); } if (!string.IsNullOrWhiteSpace(organizationUnit)) { x500Values.Add($"OU={organizationUnit}"); } string distinguishedNameString = string.Join("; ", x500Values); X500DistinguishedName distinguishedName = new X500DistinguishedName(distinguishedNameString); using (RSA rsa = RSA.Create(2048)) { var request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add( new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false)); request.CertificateExtensions.Add( new X509EnhancedKeyUsageExtension( new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false)); request.CertificateExtensions.Add(sanBuilder.Build()); var certificate = request.CreateSelfSigned(from, to); if (Platform.IsWindows) { certificate.FriendlyName = friendlyName; } return(new X509Certificate2(certificate.Export(X509ContentType.Pfx, password), password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet)); } }
public virtual TlsCredentials GetClientCredentials(CertificateRequest certificateRequest) { byte[] certificateTypes = certificateRequest.CertificateTypes; if (certificateTypes == null || !Arrays.Contains(certificateTypes, ClientCertificateType.rsa_sign)) return null; return TlsTestUtilities.LoadSignerCredentials(mContext, certificateRequest.SupportedSignatureAlgorithms, SignatureAlgorithm.rsa, "x509-client.pem", "x509-client-key.pem"); }
static string GetIssuerCertificate(CertificateRequest certificate) { var linksEnum = certificate.Links; if (linksEnum != null) { var links = new LinkCollection(linksEnum); var upLink = links.GetFirstOrDefault("up"); if (upLink != null) { var tmp = Path.GetTempFileName(); try { using (var web = new WebClient()) { //if (v.Proxy != null) // web.Proxy = v.Proxy.GetWebProxy(); var uri = new Uri(new Uri(BaseURI), upLink.Uri); web.DownloadFile(uri, tmp); } var cacert = new X509Certificate2(tmp); var sernum = cacert.GetSerialNumberString(); var tprint = cacert.Thumbprint; var sigalg = cacert.SignatureAlgorithm?.FriendlyName; var sigval = cacert.GetCertHashString(); var cacertDerFile = Path.Combine(configPath, $"ca-{sernum}-crt.der"); var cacertPemFile = Path.Combine(configPath, $"ca-{sernum}-crt.pem"); if (!File.Exists(cacertDerFile)) File.Copy(tmp, cacertDerFile, true); Console.WriteLine($" Saving Issuer Certificate to {cacertPemFile}"); if (!File.Exists(cacertPemFile)) CsrHelper.Crt.ConvertDerToPem(cacertDerFile, cacertPemFile); return cacertPemFile; } finally { if (File.Exists(tmp)) File.Delete(tmp); } } } return null; }