1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
15 func loadSystemRoots() (*CertPool, error) {
16 return &CertPool{systemPool: true}, nil
19 // Creates a new *syscall.CertContext representing the leaf certificate in an in-memory
20 // certificate store containing itself and all of the intermediate certificates specified
21 // in the opts.Intermediates CertPool.
23 // A pointer to the in-memory store is available in the returned CertContext's Store field.
24 // The store is automatically freed when the CertContext is freed using
25 // syscall.CertFreeCertificateContext.
26 func createStoreContext(leaf *Certificate, opts *VerifyOptions) (*syscall.CertContext, error) {
27 var storeCtx *syscall.CertContext
29 leafCtx, err := syscall.CertCreateCertificateContext(syscall.X509_ASN_ENCODING|syscall.PKCS_7_ASN_ENCODING, &leaf.Raw[0], uint32(len(leaf.Raw)))
33 defer syscall.CertFreeCertificateContext(leafCtx)
35 handle, err := syscall.CertOpenStore(syscall.CERT_STORE_PROV_MEMORY, 0, 0, syscall.CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, 0)
39 defer syscall.CertCloseStore(handle, 0)
41 err = syscall.CertAddCertificateContextToStore(handle, leafCtx, syscall.CERT_STORE_ADD_ALWAYS, &storeCtx)
46 if opts.Intermediates != nil {
47 for i := 0; i < opts.Intermediates.len(); i++ {
48 intermediate, _, err := opts.Intermediates.cert(i)
52 ctx, err := syscall.CertCreateCertificateContext(syscall.X509_ASN_ENCODING|syscall.PKCS_7_ASN_ENCODING, &intermediate.Raw[0], uint32(len(intermediate.Raw)))
57 err = syscall.CertAddCertificateContextToStore(handle, ctx, syscall.CERT_STORE_ADD_ALWAYS, nil)
58 syscall.CertFreeCertificateContext(ctx)
68 // extractSimpleChain extracts the final certificate chain from a CertSimpleChain.
69 func extractSimpleChain(simpleChain **syscall.CertSimpleChain, count int) (chain []*Certificate, err error) {
70 if simpleChain == nil || count == 0 {
71 return nil, errors.New("x509: invalid simple chain")
74 simpleChains := unsafe.Slice(simpleChain, count)
75 lastChain := simpleChains[count-1]
76 elements := unsafe.Slice(lastChain.Elements, lastChain.NumElements)
77 for i := 0; i < int(lastChain.NumElements); i++ {
78 // Copy the buf, since ParseCertificate does not create its own copy.
79 cert := elements[i].CertContext
80 encodedCert := unsafe.Slice(cert.EncodedCert, cert.Length)
81 buf := bytes.Clone(encodedCert)
82 parsedCert, err := ParseCertificate(buf)
86 chain = append(chain, parsedCert)
92 // checkChainTrustStatus checks the trust status of the certificate chain, translating
93 // any errors it finds into Go errors in the process.
94 func checkChainTrustStatus(c *Certificate, chainCtx *syscall.CertChainContext) error {
95 if chainCtx.TrustStatus.ErrorStatus != syscall.CERT_TRUST_NO_ERROR {
96 status := chainCtx.TrustStatus.ErrorStatus
98 case syscall.CERT_TRUST_IS_NOT_TIME_VALID:
99 return CertificateInvalidError{c, Expired, ""}
100 case syscall.CERT_TRUST_IS_NOT_VALID_FOR_USAGE:
101 return CertificateInvalidError{c, IncompatibleUsage, ""}
102 // TODO(filippo): surface more error statuses.
104 return UnknownAuthorityError{c, nil, nil}
110 // checkChainSSLServerPolicy checks that the certificate chain in chainCtx is valid for
111 // use as a certificate chain for a SSL/TLS server.
112 func checkChainSSLServerPolicy(c *Certificate, chainCtx *syscall.CertChainContext, opts *VerifyOptions) error {
113 servernamep, err := syscall.UTF16PtrFromString(strings.TrimSuffix(opts.DNSName, "."))
117 sslPara := &syscall.SSLExtraCertChainPolicyPara{
118 AuthType: syscall.AUTHTYPE_SERVER,
119 ServerName: servernamep,
121 sslPara.Size = uint32(unsafe.Sizeof(*sslPara))
123 para := &syscall.CertChainPolicyPara{
124 ExtraPolicyPara: (syscall.Pointer)(unsafe.Pointer(sslPara)),
126 para.Size = uint32(unsafe.Sizeof(*para))
128 status := syscall.CertChainPolicyStatus{}
129 err = syscall.CertVerifyCertificateChainPolicy(syscall.CERT_CHAIN_POLICY_SSL, chainCtx, para, &status)
134 // TODO(mkrautz): use the lChainIndex and lElementIndex fields
135 // of the CertChainPolicyStatus to provide proper context, instead
137 if status.Error != 0 {
138 switch status.Error {
139 case syscall.CERT_E_EXPIRED:
140 return CertificateInvalidError{c, Expired, ""}
141 case syscall.CERT_E_CN_NO_MATCH:
142 return HostnameError{c, opts.DNSName}
143 case syscall.CERT_E_UNTRUSTEDROOT:
144 return UnknownAuthorityError{c, nil, nil}
146 return UnknownAuthorityError{c, nil, nil}
153 // windowsExtKeyUsageOIDs are the C NUL-terminated string representations of the
154 // OIDs for use with the Windows API.
155 var windowsExtKeyUsageOIDs = make(map[ExtKeyUsage][]byte, len(extKeyUsageOIDs))
158 for _, eku := range extKeyUsageOIDs {
159 windowsExtKeyUsageOIDs[eku.extKeyUsage] = []byte(eku.oid.String() + "\x00")
163 func verifyChain(c *Certificate, chainCtx *syscall.CertChainContext, opts *VerifyOptions) (chain []*Certificate, err error) {
164 err = checkChainTrustStatus(c, chainCtx)
169 if opts != nil && len(opts.DNSName) > 0 {
170 err = checkChainSSLServerPolicy(c, chainCtx, opts)
176 chain, err = extractSimpleChain(chainCtx.Chains, int(chainCtx.ChainCount))
181 return nil, errors.New("x509: internal error: system verifier returned an empty chain")
184 // Mitigate CVE-2020-0601, where the Windows system verifier might be
185 // tricked into using custom curve parameters for a trusted root, by
186 // double-checking all ECDSA signatures. If the system was tricked into
187 // using spoofed parameters, the signature will be invalid for the correct
188 // ones we parsed. (We don't support custom curves ourselves.)
189 for i, parent := range chain[1:] {
190 if parent.PublicKeyAlgorithm != ECDSA {
193 if err := parent.CheckSignature(chain[i].SignatureAlgorithm,
194 chain[i].RawTBSCertificate, chain[i].Signature); err != nil {
201 // systemVerify is like Verify, except that it uses CryptoAPI calls
202 // to build certificate chains and verify them.
203 func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) {
204 storeCtx, err := createStoreContext(c, opts)
208 defer syscall.CertFreeCertificateContext(storeCtx)
210 para := new(syscall.CertChainPara)
211 para.Size = uint32(unsafe.Sizeof(*para))
213 keyUsages := opts.KeyUsages
214 if len(keyUsages) == 0 {
215 keyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth}
217 oids := make([]*byte, 0, len(keyUsages))
218 for _, eku := range keyUsages {
219 if eku == ExtKeyUsageAny {
223 if oid, ok := windowsExtKeyUsageOIDs[eku]; ok {
224 oids = append(oids, &oid[0])
228 para.RequestedUsage.Type = syscall.USAGE_MATCH_TYPE_OR
229 para.RequestedUsage.Usage.Length = uint32(len(oids))
230 para.RequestedUsage.Usage.UsageIdentifiers = &oids[0]
232 para.RequestedUsage.Type = syscall.USAGE_MATCH_TYPE_AND
233 para.RequestedUsage.Usage.Length = 0
234 para.RequestedUsage.Usage.UsageIdentifiers = nil
237 var verifyTime *syscall.Filetime
238 if opts != nil && !opts.CurrentTime.IsZero() {
239 ft := syscall.NsecToFiletime(opts.CurrentTime.UnixNano())
243 // The default is to return only the highest quality chain,
244 // setting this flag will add additional lower quality contexts.
245 // These are returned in the LowerQualityChains field.
246 const CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS = 0x00000080
248 // CertGetCertificateChain will traverse Windows's root stores in an attempt to build a verified certificate chain
249 var topCtx *syscall.CertChainContext
250 err = syscall.CertGetCertificateChain(syscall.Handle(0), storeCtx, verifyTime, storeCtx.Store, para, CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS, 0, &topCtx)
254 defer syscall.CertFreeCertificateChain(topCtx)
256 chain, topErr := verifyChain(c, topCtx, opts)
258 chains = append(chains, chain)
261 if lqCtxCount := topCtx.LowerQualityChainCount; lqCtxCount > 0 {
262 lqCtxs := unsafe.Slice(topCtx.LowerQualityChains, lqCtxCount)
263 for _, ctx := range lqCtxs {
264 chain, err := verifyChain(c, ctx, opts)
266 chains = append(chains, chain)
271 if len(chains) == 0 {
272 // Return the error from the highest quality context.