-
Notifications
You must be signed in to change notification settings - Fork 210
/
id.go
105 lines (95 loc) · 2.55 KB
/
id.go
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Package nodeidentity contains types and helper functions for GKE Nodes.
package nodeidentity
import (
"crypto/x509"
"encoding/asn1"
"fmt"
"strconv"
"cloud.google.com/go/compute/metadata"
)
// CloudComputeInstanceIdentifierOIDis an x509 Extension OID for VM Identity info.
var CloudComputeInstanceIdentifierOID = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 1, 21}
// Identity uniquely identifies a GCE VM.
type Identity struct {
Zone string `json:"zone"`
ID uint64 `json:"id"`
Name string `json:"name"`
ProjectID uint64 `json:"project_id"`
ProjectName string `json:"project_name"`
}
// FromMetadata builds VM Identity from GCE Metadata using default client.
func FromMetadata() (Identity, error) {
var id Identity
var err error
projID, err := metadata.NumericProjectID()
if err != nil {
return id, err
}
id.ProjectID, err = strconv.ParseUint(projID, 10, 64)
if err != nil {
return id, err
}
id.ProjectName, err = metadata.ProjectID()
if err != nil {
return id, err
}
id.Zone, err = metadata.Zone()
if err != nil {
return id, err
}
instID, err := metadata.InstanceID()
if err != nil {
return id, err
}
id.ID, err = strconv.ParseUint(instID, 10, 64)
if err != nil {
return id, err
}
id.Name, err = metadata.InstanceName()
if err != nil {
return id, err
}
return id, nil
}
// We need this separate struct because encoding/asn1 doesn't understand
// uint64.
type asn1Identity struct {
Zone string
ID int64
Name string
ProjectID int64
ProjectName string
}
// FromAIKCert extracts VM Identity from cloudComputeInstanceIdentifier
// extension in cert.
func FromAIKCert(cert *x509.Certificate) (Identity, error) {
var id asn1Identity
for _, ext := range cert.Extensions {
if !ext.Id.Equal(CloudComputeInstanceIdentifierOID) {
continue
}
_, err := asn1.Unmarshal(ext.Value, &id)
if err != nil {
return Identity{}, err
}
return Identity{
Zone: id.Zone,
ID: uint64(id.ID),
Name: id.Name,
ProjectID: uint64(id.ProjectID),
ProjectName: id.ProjectName,
}, nil
}
return Identity{}, fmt.Errorf("certificate does not have cloudComputeInstanceIdentifier extension (OID %s)", CloudComputeInstanceIdentifierOID)
}
// ToASN1 serializes Identity to ASN1 format used in
// CloudComputeInstanceIdentifiedOID x509 extension.
func (id Identity) ToASN1() ([]byte, error) {
return asn1.Marshal(asn1Identity{
Zone: id.Zone,
ID: int64(id.ID),
Name: id.Name,
ProjectID: int64(id.ProjectID),
ProjectName: id.ProjectName,
})
}