func()

in cmd/core_plugin/agentcrypto/mtls_mds_windows.go [186:248]


func (j *CredsJob) writeClientCredentials(ctx context.Context, creds []byte, outputFile string) error {
	num, err := serialNumber(outputFile)
	if err != nil {
		galog.Warnf("Could not get previous serial number, will skip cleanup: %v", err)
	}

	if err := file.SaferWriteFile(ctx, creds, outputFile, file.Options{Perm: 0644}); err != nil {
		return fmt.Errorf("failed to write client key: %w", err)
	}

	pfx, err := generatePFX(creds)
	if err != nil {
		return fmt.Errorf("failed to generate PFX data from client credentials: %w", err)
	}

	p := filepath.Join(filepath.Dir(outputFile), pfxFile)
	if err := file.SaferWriteFile(ctx, pfx, p, file.Options{Perm: 0644}); err != nil {
		return fmt.Errorf("failed to write PFX file: %w", err)
	}

	blob := windows.CryptDataBlob{
		Size: uint32(len(pfx)),
		Data: &pfx[0],
	}

	// https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-pfximportcertstore
	handle, err := windows.PFXImportCertStore(&blob, syscall.StringToUTF16Ptr(""), windows.CRYPT_MACHINE_KEYSET)
	if err != nil {
		return fmt.Errorf("failed to import PFX in cert store: %w", err)
	}
	defer windows.CertCloseStore(handle, 0)

	var crtCtx *windows.CertContext

	// https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certenumcertificatesinstore
	crtCtx, err = windows.CertEnumCertificatesInStore(handle, crtCtx)
	if err != nil {
		return fmt.Errorf("failed to get cert context for PFX from store: %w", err)
	}
	defer windows.CertFreeCertificateContext(crtCtx)

	// Add certificate to personal store.
	if err := addCtxToLocalSystemStore(my, crtCtx, uint32(windows.CERT_STORE_ADD_NEWER)); err != nil {
		return fmt.Errorf("failed to store pfx cert context: %w", err)
	}

	// Search for previous certificate if its not already in memory.
	if prevCtx == nil && num != "" {
		prevCtx, err = findCert(my, certificateIssuer, num)
		if err != nil {
			galog.Warnf("Failed to find previous certificate with error: %v", err)
		}
	}

	// Remove previous certificate only after successful refresh.
	if err := deleteCert(prevCtx, my); err != nil {
		galog.Warnf("Failed to delete previous certificate(%s) with error: %v", num, err)
	}

	prevCtx = windows.CertDuplicateCertificateContext(crtCtx)

	return nil
}