aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/version/wintrust/certificate_windows.go
blob: 8c933f11af53acd1bca1f66878bbffbaa70ed241 (plain) (blame)
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
/* SPDX-License-Identifier: MIT
 *
 * Copyright (C) 2019 WireGuard LLC. All Rights Reserved.
 */

package wintrust

import (
	"syscall"
	"unsafe"

	"golang.org/x/sys/windows"
)

const (
	_CERT_QUERY_OBJECT_FILE                     = 1
	_CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED = 1024
	_CERT_QUERY_FORMAT_FLAG_ALL                 = 14
	_CERT_NAME_SIMPLE_DISPLAY_TYPE              = 4
)

//sys	cryptQueryObject(objectType uint32, object uintptr, expectedContentTypeFlags uint32, expectedFormatTypeFlags uint32, flags uint32, msgAndCertEncodingType *uint32, contentType *uint32, formatType *uint32, certStore *windows.Handle, msg *windows.Handle, context *uintptr) (err error) = crypt32.CryptQueryObject
//sys	certGetNameString(certContext *windows.CertContext, nameType uint32, flags uint32, typePara uintptr, name *uint16, size uint32) (chars uint32) = crypt32.CertGetNameStringW

func ExtractCertificateNames(path string) ([]string, error) {
	path16, err := windows.UTF16PtrFromString(path)
	if err != nil {
		return nil, err
	}
	var certStore windows.Handle
	err = cryptQueryObject(_CERT_QUERY_OBJECT_FILE, uintptr(unsafe.Pointer(path16)), _CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED, _CERT_QUERY_FORMAT_FLAG_ALL, 0, nil, nil, nil, &certStore, nil, nil)
	if err != nil {
		return nil, err
	}
	defer windows.CertCloseStore(certStore, 0)
	var cert *windows.CertContext
	var names []string
	for {
		cert, err = windows.CertEnumCertificatesInStore(certStore, cert)
		if err != nil {
			if errno, ok := err.(syscall.Errno); ok {
				if errno == syscall.Errno(windows.CRYPT_E_NOT_FOUND) {
					break
				}
			}
			return nil, err
		}
		if cert == nil {
			break
		}
		nameLen := certGetNameString(cert, _CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, 0, nil, 0)
		if nameLen == 0 {
			continue
		}
		name16 := make([]uint16, nameLen)
		if certGetNameString(cert, _CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, 0, &name16[0], nameLen) != nameLen {
			continue
		}
		if name16[0] == 0 {
			continue
		}
		names = append(names, windows.UTF16ToString(name16))
	}
	if names == nil {
		return nil, syscall.Errno(windows.CRYPT_E_NOT_FOUND)
	}
	return names, nil
}