-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathWindowsCertificateManager.cs
168 lines (142 loc) · 6.11 KB
/
WindowsCertificateManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Versioning;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
namespace Microsoft.AspNetCore.Certificates.Generation;
[SupportedOSPlatform("windows")]
internal sealed class WindowsCertificateManager : CertificateManager
{
private const int UserCancelledErrorCode = 1223;
public WindowsCertificateManager()
{
}
// For testing purposes only
internal WindowsCertificateManager(string subject, int version)
: base(subject, version)
{
}
internal override bool IsExportable(X509Certificate2 c)
{
#if XPLAT
// For the first run experience we don't need to know if the certificate can be exported.
return true;
#else
using var key = c.GetRSAPrivateKey();
return (key is RSACryptoServiceProvider rsaPrivateKey &&
rsaPrivateKey.CspKeyContainerInfo.Exportable) ||
(key is RSACng cngPrivateKey &&
cngPrivateKey.Key.ExportPolicy == CngExportPolicies.AllowExport);
#endif
}
internal override CheckCertificateStateResult CheckCertificateState(X509Certificate2 candidate)
{
return new CheckCertificateStateResult(true, null);
}
internal override void CorrectCertificateState(X509Certificate2 candidate)
{
// Do nothing since we don't have anything to check here.
}
protected override X509Certificate2 SaveCertificateCore(X509Certificate2 certificate, StoreName storeName, StoreLocation storeLocation)
{
// On non OSX systems we need to export the certificate and import it so that the transient
// key that we generated gets persisted.
var export = certificate.Export(X509ContentType.Pkcs12, "");
certificate.Dispose();
certificate = new X509Certificate2(export, "", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
Array.Clear(export, 0, export.Length);
certificate.FriendlyName = AspNetHttpsOidFriendlyName;
using (var store = new X509Store(storeName, storeLocation))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certificate);
store.Close();
};
return certificate;
}
protected override TrustLevel TrustCertificateCore(X509Certificate2 certificate)
{
using var store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
if (TryFindCertificateInStore(store, certificate, out _))
{
Log.WindowsCertificateAlreadyTrusted();
return TrustLevel.Full;
}
try
{
Log.WindowsAddCertificateToRootStore();
using var publicCertificate = X509CertificateLoader.LoadCertificate(certificate.Export(X509ContentType.Cert));
publicCertificate.FriendlyName = certificate.FriendlyName;
store.Add(publicCertificate);
return TrustLevel.Full;
}
catch (CryptographicException exception) when (exception.HResult == UserCancelledErrorCode)
{
Log.WindowsCertificateTrustCanceled();
throw new UserCancelledTrustException();
}
}
protected override void RemoveCertificateFromTrustedRoots(X509Certificate2 certificate)
{
Log.WindowsRemoveCertificateFromRootStoreStart();
using var store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
if (TryFindCertificateInStore(store, certificate, out var matching))
{
store.Remove(matching);
}
else
{
Log.WindowsRemoveCertificateFromRootStoreNotFound();
}
Log.WindowsRemoveCertificateFromRootStoreEnd();
}
public override TrustLevel GetTrustLevel(X509Certificate2 certificate)
{
var isTrusted = ListCertificates(StoreName.Root, StoreLocation.CurrentUser, isValid: true, requireExportable: false)
.Any(c => AreCertificatesEqual(c, certificate));
return isTrusted ? TrustLevel.Full : TrustLevel.None;
}
protected override IList<X509Certificate2> GetCertificatesToRemove(StoreName storeName, StoreLocation storeLocation)
{
return ListCertificates(storeName, storeLocation, isValid: false);
}
protected override void CreateDirectoryWithPermissions(string directoryPath)
{
var dirInfo = new DirectoryInfo(directoryPath);
if (!dirInfo.Exists)
{
// We trust the default permissions on Windows enough not to apply custom ACLs.
// We'll warn below if things seem really off.
dirInfo.Create();
}
var currentUser = WindowsIdentity.GetCurrent();
var currentUserSid = currentUser.User;
var systemSid = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, domainSid: null);
var adminGroupSid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, domainSid: null);
var dirSecurity = dirInfo.GetAccessControl();
var accessRules = dirSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier));
foreach (FileSystemAccessRule rule in accessRules)
{
var idRef = rule.IdentityReference;
if (rule.AccessControlType == AccessControlType.Allow &&
!idRef.Equals(currentUserSid) &&
!idRef.Equals(systemSid) &&
!idRef.Equals(adminGroupSid))
{
// This is just a heuristic - determining whether the cumulative effect of the rules
// is to allow access to anyone other than the current user, system, or administrators
// is very complicated. We're not going to do anything but log, so an approximation
// is fine.
Log.DirectoryPermissionsNotSecure(dirInfo.FullName);
break;
}
}
}
}