public void BeforeEachTest() { _authority = new CertificateAuthority("MyAuthority"); _mockPersonalStore = new Mock<ICertificateStore>(); _mockRootStore = new Mock<ICertificateStore>(); _certStore = new CertificateStore(_mockPersonalStore.Object, _mockRootStore.Object); }
/// <param name="certificateAuthority">Specifies an existing <see cref="CertificateAuthority"/> object.</param> /// <exception cref="UninitializedObjectException">An object in the <strong>certificateAuthority</strong> parameter is not initialized.</exception> public CRLFlag(CertificateAuthority certificateAuthority) { if (String.IsNullOrEmpty(certificateAuthority.Name)) { throw new UninitializedObjectException(); } m_initialize(certificateAuthority); }
/// <summary> /// Updates policy module extension lists by writing them to Certification Authority. /// </summary> /// <param name="restart"> /// Indiciates whether to restart certificate services to immediately apply changes. Updated settings has no effect /// until CA service is restarted.</param> /// <exception cref="UnauthorizedAccessException"> /// If the caller do not have sufficient permissions to make changes in the CA configuration. /// </exception> /// <exception cref="ServerUnavailableException"> /// If the target CA server could not be contacted via remote registry and RPC protocol. /// </exception> /// <returns> /// <strong>True</strong> if configuration was changed. If an object was not modified since it was instantiated, configuration is not updated /// and the method returns <strong>False</strong>. /// </returns> /// <remarks>The caller must have <strong>Administrator</strong> permissions on the target CA server.</remarks> public Boolean SetInfo(Boolean restart) { if (IsModified) { List <String> oidstrings; if (CryptoRegistry.Ping(ComputerName)) { String path = $@"{Name}\PolicyModules\{ActivePolicyModule}"; oidstrings = EnabledExtensionList.Select(oid => oid.Value).ToList(); CryptoRegistry.SetRReg(oidstrings, "EnableRequestExtensionList", path, ComputerName); oidstrings.Clear(); oidstrings.AddRange(OfflineExtensionList.Select(oid => oid.Value)); CryptoRegistry.SetRReg(oidstrings, "EnableEnrolleeRequestExtensionList", path, ComputerName); oidstrings.Clear(); oidstrings.AddRange(DisabledExtensionList.Select(oid => oid.Value)); CryptoRegistry.SetRReg(oidstrings, "DisableExtensionList", path, ComputerName); oidstrings.Clear(); if (restart) { CertificateAuthority.Restart(ComputerName); } IsModified = false; return(true); } if (CertificateAuthority.Ping(ComputerName)) { String path = $@"PolicyModules\{ActivePolicyModule}"; oidstrings = EnabledExtensionList.Select(oid => oid.Value).ToList(); CryptoRegistry.SetRegFallback(ConfigString, path, "EnableRequestExtensionList", oidstrings.ToArray()); oidstrings.Clear(); oidstrings.AddRange(OfflineExtensionList.Select(oid => oid.Value)); CryptoRegistry.SetRegFallback(ConfigString, path, "EnableEnrolleeRequestExtensionList", oidstrings.ToArray()); oidstrings.Clear(); oidstrings.AddRange(DisabledExtensionList.Select(oid => oid.Value)); CryptoRegistry.SetRegFallback(ConfigString, path, "DisableExtensionList", oidstrings.ToArray()); oidstrings.Clear(); if (restart) { CertificateAuthority.Restart(ComputerName); } IsModified = false; return(true); } ServerUnavailableException e = new ServerUnavailableException(DisplayName); e.Data.Add(nameof(e.Source), (OfflineSource)3); throw e; } return(false); }
public async Task VerifySignaturesAsync_ExpiredCertificateAndTimestampWithTooLargeRange_FailsAsync() { ISigningTestServer testServer = await _testFixture.GetSigningTestServerAsync(); CertificateAuthority ca = await _testFixture.GetDefaultTrustedCertificateAuthorityAsync(); var accuracy = new BcAccuracy(seconds: new DerInteger(30), millis: null, micros: null); var serviceOptions = new TimestampServiceOptions() { Accuracy = accuracy }; TimestampService timestampService = TimestampService.Create(ca, serviceOptions); AsymmetricCipherKeyPair keyPair = SigningTestUtility.GenerateKeyPair(publicKeyLength: 2048); DateTimeOffset now = DateTimeOffset.UtcNow; var issueOptions = new IssueCertificateOptions() { KeyPair = keyPair, NotAfter = now.AddSeconds(10), NotBefore = now.AddSeconds(-2), SubjectName = new X509Name("CN=NuGet Test Expired Certificate") }; BcX509Certificate bcCertificate = ca.IssueCertificate(issueOptions); using (testServer.RegisterResponder(timestampService)) using (TestDirectory directory = TestDirectory.Create()) using (X509Certificate2 certificate = CertificateUtilities.GetCertificateWithPrivateKey(bcCertificate, keyPair)) { var packageContext = new SimpleTestPackageContext(); string signedPackagePath = await SignedArchiveTestUtility.AuthorSignPackageAsync( certificate, packageContext, directory, timestampService.Url); await SignatureTestUtility.WaitForCertificateExpirationAsync(certificate); var verifier = new PackageSignatureVerifier(_trustProviders); using (var packageReader = new PackageArchiveReader(signedPackagePath)) { VerifySignaturesResult results = await verifier.VerifySignaturesAsync(packageReader, _verifyCommandSettings, CancellationToken.None); PackageVerificationResult result = results.Results.Single(); Assert.False(results.IsValid); Assert.Equal(SignatureVerificationStatus.Disallowed, result.Trust); Assert.Equal(1, result.Issues.Count(issue => issue.Level == LogLevel.Error)); Assert.Equal(0, result.Issues.Count(issue => issue.Level == LogLevel.Warning)); Assert.Contains(result.Issues, issue => issue.Code == NuGetLogCode.NU3037 && issue.Level == LogLevel.Error && issue.Message.Contains("validity period has expired.")); } } }
public async Task SetUpCertificatesAsync() { await Profiler.Run( () => this.SasProvisionEdgeAsync(), "Completed edge manual provisioning with SAS token"); await Profiler.Run( async() => { (string, string, string)rootCa = Context.Current.RootCaKeys.Expect(() => new InvalidOperationException("Missing root CA keys")); string caCertScriptPath = Context.Current.CaCertScriptPath.Expect(() => new InvalidOperationException("Missing CA cert script path")); using (var cts = new CancellationTokenSource(Context.Current.SetupTimeout)) { DateTime startTime = DateTime.Now; CancellationToken token = cts.Token; string deviceId = this.runtime.DeviceId; try { this.ca = await CertificateAuthority.CreateAsync( deviceId, rootCa, caCertScriptPath, token); CaCertificates caCert = await this.ca.GenerateCaCertificatesAsync(deviceId, token); this.ca.EdgeCertificates = caCert; await this.daemon.ConfigureAsync( config => { config.SetCertificates(caCert); config.Update(); return(Task.FromResult(("with edge certificates", Array.Empty <object>()))); }, token); await this.runtime.DeployConfigurationAsync(token); } // ReSharper disable once RedundantCatchClause catch { throw; } finally { await NUnitLogs.CollectAsync(startTime, token); } } }, "Completed custom certificate setup"); }
public X509Certificate2 CreateSigningCertificate(CertificateAuthority ca) { void CustomizeAsSigningCertificate(X509V3CertificateGenerator generator) { generator.AddSigningEku(); generator.AddAuthorityInfoAccess(ca, addOcsp: true, addCAIssuers: true); } return(IssueCertificate(ca, "Signing", CustomizeAsSigningCertificate).certificate); }
public async Task <ActionResult> UpdateCertificateAuthority(CertificateAuthority ca) { var result = await CertifyClient.UpdateCertificateAuthority(ca); if (result.IsSuccess) { await this.RefreshCertificateAuthorityList(); } return(result); }
public async Task AcceptsTrustedSigningCertificateWithUnavailableRevocation() { // Arrange var testServer = await _fixture.GetTestServerAsync(); var rootCa = CertificateAuthority.Create(testServer.Url); var intermediateCa = rootCa.CreateIntermediateCertificateAuthority(); var rootCertificate = new X509Certificate2(rootCa.Certificate.GetEncoded()); var signingCertificate = _fixture.CreateSigningCertificate(intermediateCa); using (var trust = new TrustedTestCert <X509Certificate2>( rootCertificate, x => x, StoreName.Root, StoreLocation.LocalMachine)) { byte[] packageBytes; using (testServer.RegisterResponders(intermediateCa)) { packageBytes = await _fixture.GenerateSignedPackageBytesAsync( TestResources.SignedPackageLeaf1, signingCertificate, await _fixture.GetTimestampServiceUrlAsync(), _output); } // Wait one second for the OCSP response cached by the operating system during signing to get stale. // This can be mitigated by leaving the OCSP unavailable during signing once this work item is done: // https://github.com/NuGet/Home/issues/6508 await Task.Delay(TimeSpan.FromSeconds(1)); TestUtility.RequireSignedPackage(_corePackageService, TestResources.SignedPackageLeafId, signingCertificate.ComputeSHA256Thumbprint()); _packageStream = new MemoryStream(packageBytes); SignatureValidatorResult result; using (testServer.RegisterResponders(intermediateCa, addOcsp: false)) { // Act result = await _target.ValidateAsync( _packageKey, _packageStream, _message, _token); } // Assert VerifyPackageSigningStatus(result, ValidationStatus.Succeeded, PackageSigningStatus.Valid); Assert.Empty(result.Issues); var allMessages = string.Join(Environment.NewLine, _logger.Messages); Assert.Contains("NU3018: The revocation function was unable to check revocation because the revocation server was offline.", allMessages); Assert.Contains("NU3018: The revocation function was unable to check revocation for the certificate.", allMessages); } }
public async Task DpsX509() { (string, string, string)rootCa = Context.Current.RootCaKeys.Expect(() => new InvalidOperationException("Missing root CA keys")); string caCertScriptPath = Context.Current.CaCertScriptPath.Expect(() => new InvalidOperationException("Missing CA cert script path")); string idScope = Context.Current.DpsIdScope.Expect(() => new InvalidOperationException("Missing DPS ID scope")); string registrationId = DeviceId.Current.Generate(); CancellationToken token = this.TestToken; CertificateAuthority ca = await CertificateAuthority.CreateAsync( registrationId, rootCa, caCertScriptPath, token); IdCertificates idCert = await ca.GenerateIdentityCertificatesAsync(registrationId, token); // The trust bundle for this test isn't used. It can be any arbitrary existing certificate. string trustBundle = Path.Combine( caCertScriptPath, "certs", "azure-iot-test-only.intermediate-full-chain.cert.pem"); await this.daemon.ConfigureAsync( config => { config.SetDpsX509(idScope, registrationId, idCert, trustBundle); config.Update(); return(Task.FromResult(( "with DPS X509 attestation for '{Identity}'", new object[] { registrationId }))); }, token); await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token); var agent = new EdgeAgent(registrationId, this.iotHub); await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token); await agent.PingAsync(token); Option <EdgeDevice> device = await EdgeDevice.GetIdentityAsync( registrationId, Context.Current.ParentDeviceId, this.iotHub, token, takeOwnership : true); Context.Current.DeleteList.TryAdd( registrationId, device.Expect(() => new InvalidOperationException( $"Device '{registrationId}' should have been created by DPS, but was not found in '{this.iotHub.Hostname}'"))); }
public async Task RejectsUntrustedTimestampingCertificate() { // Arrange var testServer = await _fixture.GetTestServerAsync(); var untrustedRootCa = CertificateAuthority.Create(testServer.Url); var untrustedRootCertficate = new X509Certificate2(untrustedRootCa.Certificate.GetEncoded()); var timestampService = TimestampService.Create(untrustedRootCa); using (testServer.RegisterDefaultResponders(timestampService)) { byte[] packageBytes; using (var temporaryTrust = new TrustedTestCert <X509Certificate2>( untrustedRootCertficate, x => x, StoreName.Root, StoreLocation.LocalMachine)) { packageBytes = await _fixture.GenerateSignedPackageBytesAsync( TestResources.SignedPackageLeaf1, await _fixture.GetSigningCertificateAsync(), timestampService.Url, _output); } TestUtility.RequireSignedPackage(_corePackageService, TestResources.SignedPackageLeafId, await _fixture.GetSigningCertificateThumbprintAsync()); _packageStream = new MemoryStream(packageBytes); _message = new SignatureValidationMessage( TestResources.SignedPackageLeafId, TestResources.SignedPackageLeaf1Version, new Uri($"https://unit.test/validation/{TestResources.SignedPackageLeaf1.ToLowerInvariant()}"), Guid.NewGuid()); // Act var result = await _target.ValidateAsync( _packageKey, _packageStream, _message, _token); // Assert VerifyPackageSigningStatus(result, ValidationStatus.Failed, PackageSigningStatus.Invalid); var issue = Assert.Single(result.Issues); var clientIssue = Assert.IsType <ClientSigningVerificationFailure>(issue); Assert.Equal("NU3028", clientIssue.ClientCode); Assert.Equal( "A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.", clientIssue.ClientMessage); } }
/// <param name="certificateAuthority">Specifies an existing <see cref="CertificateAuthority"/> object.</param> /// <exception cref="UninitializedObjectException">An object in the <strong>certificateAuthority</strong> parameter is not initialized.</exception> public EditFlag(CertificateAuthority certificateAuthority) { if (!String.IsNullOrEmpty(certificateAuthority.Name)) { m_initialize(certificateAuthority); } else { throw new UninitializedObjectException(); } }
public async Task GetTimestampCertificateChain_WithMismatchedEssCertIdCertificateHash_ReturnsChain( SigningCertificateUsage signingCertificateUsage) { ISigningTestServer testServer = await _fixture.GetSigningTestServerAsync(); CertificateAuthority rootCa = await _fixture.GetDefaultTrustedCertificateAuthorityAsync(); var options = new TimestampServiceOptions() { SigningCertificateUsage = signingCertificateUsage, SigningCertificateV1Hash = new byte[SHA1HashLength] }; TimestampService timestampService = TimestampService.Create(rootCa, options); using (testServer.RegisterResponder(timestampService)) { var nupkg = new SimpleTestPackageContext(); using (var certificate = new X509Certificate2(_fixture.TrustedTestCertificate.Source.Cert)) using (var directory = TestDirectory.Create()) { var signedPackagePath = await SignedArchiveTestUtility.AuthorSignPackageAsync( certificate, nupkg, directory, timestampService.Url); using (FileStream stream = File.OpenRead(signedPackagePath)) using (var reader = new PackageArchiveReader(stream)) { PrimarySignature signature = await reader.GetPrimarySignatureAsync(CancellationToken.None); using (IX509CertificateChain actualChain = SignatureUtility.GetTimestampCertificateChain(signature)) { Assert.NotEmpty(actualChain); IReadOnlyList <Org.BouncyCastle.X509.X509Certificate> expectedChain = GetExpectedCertificateChain(timestampService); Assert.Equal(expectedChain.Count, actualChain.Count); for (var i = 0; i < expectedChain.Count; ++i) { Org.BouncyCastle.X509.X509Certificate expectedCertificate = expectedChain[i]; X509Certificate2 actualCertificate = actualChain[i]; Assert.True( expectedCertificate.GetEncoded().SequenceEqual(actualCertificate.RawData), $"The certificate at index {i} in the chain is unexpected."); } } } } } }
void m_initialize(CertificateAuthority certificateAuthority) { List <Oid> Oids = new List <Oid>(); Name = certificateAuthority.Name; DisplayName = certificateAuthority.DisplayName; ComputerName = certificateAuthority.ComputerName; ConfigString = certificateAuthority.ConfigString; if (CryptoRegistry.Ping(ComputerName)) { ActivePolicyModule = (String)CryptoRegistry.GetRReg("Active", $@"{Name}\PolicyModules", ComputerName); String[] oidstrings = (String[])CryptoRegistry.GetRReg("EnableRequestExtensionList", $@"{Name}\PolicyModules\{ActivePolicyModule}", ComputerName); Oids.AddRange(oidstrings.Select(item => new Oid(item))); EnabledExtensionList = Oids.ToArray(); Oids.Clear(); oidstrings = (String[])CryptoRegistry.GetRReg("EnableEnrolleeRequestExtensionList", $@"{Name}\PolicyModules\{ActivePolicyModule}", ComputerName); Oids.AddRange(oidstrings.Select(item => new Oid(item))); OfflineExtensionList = Oids.ToArray(); Oids.Clear(); oidstrings = (String[])CryptoRegistry.GetRReg("DisableExtensionList", $@"{Name}\PolicyModules\{ActivePolicyModule}", ComputerName); Oids.AddRange(oidstrings.Select(item => new Oid(item))); DisabledExtensionList = Oids.ToArray(); Oids.Clear(); } else { if (CertificateAuthority.Ping(ComputerName)) { ActivePolicyModule = (String)CryptoRegistry.GetRReg("Active", $@"{Name}\PolicyModules", ComputerName); String[] oidstrings = (String[])CryptoRegistry.GetRegFallback(ConfigString, $@"PolicyModules\{ActivePolicyModule}", "EnableRequestExtensionList"); Oids.AddRange(oidstrings.Select(item => new Oid(item))); EnabledExtensionList = Oids.ToArray(); Oids.Clear(); oidstrings = (String[])CryptoRegistry.GetRegFallback(ConfigString, $@"PolicyModules\{ActivePolicyModule}", "EnableEnrolleeRequestExtensionList"); Oids.AddRange(oidstrings.Select(item => new Oid(item))); OfflineExtensionList = Oids.ToArray(); Oids.Clear(); oidstrings = (String[])CryptoRegistry.GetRegFallback(ConfigString, $@"PolicyModules\{ActivePolicyModule}", "DisableExtensionList"); Oids.AddRange(oidstrings.Select(item => new Oid(item))); DisabledExtensionList = Oids.ToArray(); } else { ServerUnavailableException e = new ServerUnavailableException(DisplayName); e.Data.Add(nameof(e.Source), (OfflineSource)3); throw e; } } }
public EditCertificateAuthority() { InitializeComponent(); Item = new CertificateAuthority(); DataContext = this; this.Width *= MainViewModel.UIScaleFactor; this.Height *= MainViewModel.UIScaleFactor; }
/// <summary> /// Generates the CA and saves it into options /// </summary> public static void GenerateBlackopsCA() { string key, base64Cer; CertificateAuthority.GenerateCACert(out key, out base64Cer); string encKey = Encryptor.EncryptToString(key); TrafficViewerOptions.Instance.CACertPrivKey = encKey; TrafficViewerOptions.Instance.CACertCer = base64Cer; TrafficViewerOptions.Instance.Save(); }
public X509Certificate2 CreateTimestampingCertificate(CertificateAuthority ca) { void CustomizeAsTimestampingCertificate(X509V3CertificateGenerator generator) { generator.AddTimestampingEku(); generator.AddAuthorityInfoAccess(ca, addOcsp: true, addCAIssuers: true); } var(publicCertificate, certificate) = IssueCertificate(ca, "Timestamping", CustomizeAsTimestampingCertificate); return(certificate); }
public void TestCA() { var ca = new CertificateAuthority("CN=something"); var pbuf = ca.PublicKey.Export(X509ContentType.Pfx); var tfil = Path.GetTempFileName(); File.WriteAllBytes(tfil, pbuf); var readit = new X509Certificate2(tfil); Assert.AreEqual("CN=something", readit.SubjectName.Name); }
public async Task <UntrustedTimestampService> CreateUntrustedTimestampServiceAsync() { var testServer = await _testServer.Value; var untrustedRootCa = CertificateAuthority.Create(testServer.Url); var untrustedRootCertificate = untrustedRootCa.Certificate.ToX509Certificate2(); var timestampService = TimestampService.Create(untrustedRootCa); var responders = testServer.RegisterDefaultResponders(timestampService); return(new UntrustedTimestampService( untrustedRootCertificate, timestampService.Url, responders)); }
public async Task BeforeAllAsync() { await Profiler.Run( async() => { (string, string, string)rootCa = Context.Current.RootCaKeys.Expect(() => new ArgumentException()); Option <Uri> proxy = Context.Current.Proxy; string deviceId = Context.Current.DeviceId; using (var cts = new CancellationTokenSource(Context.Current.SetupTimeout)) { CancellationToken token = cts.Token; this.iotHub = new IotHub( Context.Current.ConnectionString, Context.Current.EventHubEndpoint, proxy); this.ca = await CertificateAuthority.CreateAsync( deviceId, rootCa, Context.Current.CaCertScriptPath, token); this.daemon = OsPlatform.Current.CreateEdgeDaemon(Context.Current.InstallerPath); await this.daemon.ConfigureAsync( config => { config.SetCertificates(this.ca.Certificates); config.Update(); return(Task.FromResult(("with edge certificates", Array.Empty <object>()))); }, token); var runtime = new EdgeRuntime( deviceId, Context.Current.EdgeAgentImage, Context.Current.EdgeHubImage, proxy, Context.Current.Registries, Context.Current.OptimizeForPerformance, this.iotHub); await runtime.DeployConfigurationAsync(token); } }, "Completed custom certificate setup"); }
private async Task <CertificateAuthority> CreateDefaultTrustedRootCertificateAuthorityAsync() { var testServer = await GetTestServerAsync(); var rootCa = CertificateAuthority.Create(testServer.Url); var rootCertificate = new X509Certificate2(rootCa.Certificate.GetEncoded()); _trustedRoot = new TrustedTestCert <X509Certificate2>( rootCertificate, certificate => certificate, StoreName.Root, StoreLocation.LocalMachine); return(rootCa); }
public async Task <UntrustedSigningCertificate> CreateUntrustedSigningCertificateAsync() { var testServer = await _testServer.Value; var untrustedRootCa = CertificateAuthority.Create(testServer.Url); var untrustedRootCertificate = untrustedRootCa.Certificate.ToX509Certificate2(); var responders = testServer.RegisterRespondersForEntireChain(untrustedRootCa); var certificate = CreateSigningCertificate(untrustedRootCa); var disposable = new DisposableList <IDisposable> { untrustedRootCertificate, responders, certificate }; return(new UntrustedSigningCertificate(untrustedRootCertificate, certificate, disposable)); }
private void GenerateClick(object sender, EventArgs e) { if (_saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { var cert = CertificateAuthority.GetBlackOpsCertWithCustomSubject(_textSubject.Text); File.WriteAllBytes(_saveFileDialog.FileName, cert.RawData); } catch (Exception ex) { ErrorBox.ShowDialog(ex.Message); } } }
static async Task <LeafDevice> CreateWithCaCertAsync( string leafDeviceId, string parentId, CertificateAuthority ca, IotHub iotHub, ITransportSettings transport, string edgeHostname, CancellationToken token, ClientOptions options) { Device edge = await GetEdgeDeviceIdentityAsync(parentId, iotHub, token); Device leaf = new Device(leafDeviceId) { Authentication = new AuthenticationMechanism { Type = AuthenticationType.CertificateAuthority }, Scope = edge.Scope }; leaf = await iotHub.CreateDeviceIdentityAsync(leaf, token); return(await DeleteIdentityIfFailedAsync( leaf, iotHub, token, async() => { IdCertificates certFiles = await ca.GenerateIdentityCertificatesAsync(leafDeviceId, token); (X509Certificate2 leafCert, IEnumerable <X509Certificate2> trustedCerts) = CertificateHelper.GetServerCertificateAndChainFromFile(certFiles.CertificatePath, certFiles.KeyPath); // .NET runtime requires that we install the chain of CA certs, otherwise it can't // provide them to a server during authentication. OsPlatform.Current.InstallTrustedCertificates(trustedCerts); return await CreateLeafDeviceAsync( leaf, () => DeviceClient.Create( iotHub.Hostname, edgeHostname, new DeviceAuthenticationWithX509Certificate(leaf.Id, leafCert), new[] { transport }, options), iotHub, token); }));
public CertificateAuthority create(CertificateAuthority authority) { if (authority.CreatedOn == null) { authority.CreatedOn = DateTime.Now; } if (authority.ModifiedOn == null) { authority.ModifiedOn = DateTime.Now; } _context.CertificateAuthority.Add(authority); _context.SaveChanges(); return(authority); }
private static IReadOnlyList <Org.BouncyCastle.X509.X509Certificate> GetExpectedCertificateChain(TimestampService timestampService) { var expectedChain = new List <Org.BouncyCastle.X509.X509Certificate>(); expectedChain.Add(timestampService.Certificate); CertificateAuthority ca = timestampService.CertificateAuthority; while (ca != null) { expectedChain.Add(ca.Certificate); ca = ca.Parent; } return(expectedChain); }
public static (X509Certificate2 certificate, X509Certificate2Collection) GenerateCertificates(string targetName, [CallerMemberName] string?testName = null, bool longChain = false, bool serverCertificate = true) { const int keySize = 2048; if (PlatformDetection.IsWindows && testName != null) { CleanupCertificates(testName); } X509Certificate2Collection chain = new X509Certificate2Collection(); X509ExtensionCollection extensions = BuildTlsCertExtensions(targetName, serverCertificate); CertificateAuthority.BuildPrivatePki( PkiOptions.IssuerRevocationViaCrl, out RevocationResponder responder, out CertificateAuthority root, out CertificateAuthority[] intermediates,
private async Task <CertificateAuthority> CreateDefaultTrustedRootCertificateAuthorityAsync() { var testServer = await GetTestServerAsync(); var rootCa = CertificateAuthority.Create(testServer.Url); var rootCertificate = rootCa.Certificate.ToX509Certificate2(); _trustedRoot = new TrustedTestCert <X509Certificate2>( rootCertificate, certificate => certificate, StoreName.Root, StoreLocation.LocalMachine); _responders.AddRange(testServer.RegisterResponders(rootCa)); return(rootCa); }
public static DisposableList <IDisposable> RegisterRespondersForEntireChain( this ISigningTestServer testServer, CertificateAuthority ca, bool addCa = true, bool addOcsp = true) { var responders = new DisposableList <IDisposable>(); var currentCa = ca; while (currentCa != null) { responders.AddRange(testServer.RegisterResponders(currentCa, addCa, addOcsp)); currentCa = currentCa.Parent; } return(responders); }
public async Task <ActionResult> UpdateCertificateAuthority(CertificateAuthority certificateAuthority) { try { if (_certificateAuthorities.Any(c => c.Key == certificateAuthority.Id && c.Value.IsCustom == false)) { // can't modify built in CAs return(new ActionResult("Default Certificate Authorities cannot be modified.", false)); } var customCAs = SettingsManager.GetCustomCertificateAuthorities(); var customCa = customCAs.FirstOrDefault(c => c.Id == certificateAuthority.Id); if (customCa != null) { // replace customCAs.Remove(customCa); customCAs.Add(certificateAuthority); _certificateAuthorities.TryUpdate(certificateAuthority.Id, certificateAuthority, customCa); } else { // add customCAs.Add(certificateAuthority); _certificateAuthorities.TryAdd(certificateAuthority.Id, certificateAuthority); } //store updated CAs if (SettingsManager.SaveCustomCertificateAuthorities(customCAs)) { return(new ActionResult("OK", true)); } } catch (Exception exp) { // failed to load custom CAs _serviceLog.Error(exp.Message); } return(await Task.FromResult(new ActionResult("An error occurred saving the updated Certificate Authorities list.", false))); }
public async Task VerifySignaturesAsync_ExpiredCertificateAndTimestamp_SuccessAsync() { CertificateAuthority ca = await _testFixture.GetDefaultTrustedCertificateAuthorityAsync(); TimestampService timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync(); AsymmetricCipherKeyPair keyPair = SigningTestUtility.GenerateKeyPair(publicKeyLength: 2048); DateTimeOffset now = DateTimeOffset.UtcNow; var issueOptions = new IssueCertificateOptions() { KeyPair = keyPair, NotAfter = now.AddSeconds(10), NotBefore = now.AddSeconds(-2), SubjectName = new X509Name("CN=NuGet Test Expired Certificate") }; BcX509Certificate bcCertificate = ca.IssueCertificate(issueOptions); using (TestDirectory directory = TestDirectory.Create()) using (X509Certificate2 certificate = CertificateUtilities.GetCertificateWithPrivateKey(bcCertificate, keyPair)) { var packageContext = new SimpleTestPackageContext(); string signedPackagePath = await SignedArchiveTestUtility.AuthorSignPackageAsync( certificate, packageContext, directory, timestampService.Url); await SignatureTestUtility.WaitForCertificateExpirationAsync(certificate); var verifier = new PackageSignatureVerifier(_trustProviders); using (var packageReader = new PackageArchiveReader(signedPackagePath)) { VerifySignaturesResult result = await verifier.VerifySignaturesAsync(packageReader, _verifyCommandSettings, CancellationToken.None); PackageVerificationResult trustProvider = result.Results.Single(); Assert.True(result.IsValid); Assert.Equal(SignatureVerificationStatus.Valid, trustProvider.Trust); Assert.Equal(0, trustProvider.Issues.Count(issue => issue.Level == LogLevel.Error)); Assert.Equal(0, trustProvider.Issues.Count(issue => issue.Level == LogLevel.Warning)); } } }
public async Task DotnetSign_SignPackageWithUnsuportedTimestampHashAlgorithm_FailsAsync() { // Arrange using (SimpleTestPathContext pathContext = _msbuildFixture.CreateSimpleTestPathContext()) { await SimpleTestPackageUtility.CreatePackagesAsync( pathContext.PackageSource, new SimpleTestPackageContext("PackageA", "1.0.0")); string packageFilePath = Path.Combine(pathContext.PackageSource, "PackageA.1.0.0.nupkg"); byte[] originalFile = File.ReadAllBytes(packageFilePath); ISigningTestServer testServer = await _signFixture.GetSigningTestServerAsync(); CertificateAuthority certificateAuthority = await _signFixture.GetDefaultTrustedCertificateAuthorityAsync(); var options = new TimestampServiceOptions() { SignatureHashAlgorithm = new Oid(Oids.Sha1) }; TimestampService timestampService = TimestampService.Create(certificateAuthority, options); IX509StoreCertificate storeCertificate = _signFixture.UntrustedSelfIssuedCertificateInCertificateStore; using (testServer.RegisterResponder(timestampService)) { // Act CommandRunnerResult result = _msbuildFixture.RunDotnet( pathContext.PackageSource, $"nuget sign {packageFilePath} " + $"--certificate-fingerprint {storeCertificate.Certificate.Thumbprint} " + $"--timestamper {timestampService.Url}", ignoreExitCode: true); // Assert result.Success.Should().BeFalse(because: result.AllOutput); result.AllOutput.Should().Contain(_timestampUnsupportedDigestAlgorithmCode); Assert.Contains("The timestamp signature has an unsupported digest algorithm (SHA1). The following algorithms are supported: SHA256, SHA384, SHA512.", result.AllOutput); byte[] resultingFile = File.ReadAllBytes(packageFilePath); Assert.Equal(resultingFile, originalFile); } } }
public void ShouldCreateAnX509Certificate() { var auth = new CertificateAuthority("MyAuthority"); var cert = auth.ToX509Certificate(); Assert.That(cert != null); }