in google_guest_agent/agentcrypto/mtls_mds_windows.go [61:118]
func (j *CredsJob) writeRootCACert(_ context.Context, cacert []byte, outputFile string) error {
// Try to fetch previous certificate's serial number before it gets overwritten.
num, err := serialNumber(outputFile)
if err != nil {
logger.Debugf("No previous MDS root certificate was found, will skip cleanup: %v", err)
}
if err := utils.SaferWriteFile(cacert, outputFile, 0644); err != nil {
return err
}
if !j.useNativeStore.Load() {
logger.Debugf("SkipNativeStore is enabled, will not write root cert to certstore")
return nil
}
x509Cert, err := parseCertificate(cacert)
if err != nil {
return fmt.Errorf("failed to parse root CA cert: %w", err)
}
// https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certcreatecertificatecontext
certContext, err := windows.CertCreateCertificateContext(
windows.X509_ASN_ENCODING|windows.PKCS_7_ASN_ENCODING,
&x509Cert.Raw[0],
uint32(len(x509Cert.Raw)))
if err != nil {
return fmt.Errorf("CertCreateCertificateContext returned: %v", err)
}
// https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certfreecertificatecontext
defer windows.CertFreeCertificateContext(certContext)
// Adds certificate to Root Trusted certificates.
if err := addCtxToLocalSystemStore(root, certContext, uint32(windows.CERT_STORE_ADD_REPLACE_EXISTING)); err != nil {
return fmt.Errorf("failed to store root cert ctx in store: %w", err)
}
// MDS root cert was not refreshed or there's no previous cert, nothing to do, return.
if num == "" || fmt.Sprintf("%x", x509Cert.SerialNumber) == num {
return nil
}
// Certificate is refreshed. Best effort to find the certcontext and delete it.
// Don't throw error here, it would skip client credential generation which
// may be about to expire.
oldCtx, err := findCert(root, certificateIssuer, num)
if err != nil {
logger.Warningf("Failed to find previous MDS root certificate with error: %v", err)
return nil
}
if err := deleteCert(oldCtx, root); err != nil {
logger.Warningf("Failed to delete previous MDS root certificate(%s) with error: %v", num, err)
return nil
}
return nil
}