func()

in cmd/core_plugin/agentcrypto/mtls_mds_windows.go [65:124]


func (j *CredsJob) writeRootCACert(ctx 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 {
		galog.Debugf("No previous MDS root certificate was found, will skip cleanup: %v", err)
	}

	if err := file.SaferWriteFile(ctx, cacert, outputFile, file.Options{Perm: 0644}); err != nil {
		return err
	}

	if !cfg.Retrieve().MDS.UpdateCACertificatesEnabled {
		galog.Debug("Skipping system store update as it is disabled in the configuration")
		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: %w", 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 cert context 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 {
		galog.Warnf("Failed to find previous MDS root certificate with error: %v", err)
		return nil
	}

	if err := deleteCert(oldCtx, root); err != nil {
		galog.Warnf("Failed to delete previous MDS root certificate(%s) with error: %v", num, err)
		return nil
	}

	return nil
}