-
Notifications
You must be signed in to change notification settings - Fork 9
/
util.go
259 lines (232 loc) · 6.76 KB
/
util.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/hex"
"encoding/pem"
"errors"
"fmt"
"io"
"math/big"
"net"
"net/http"
"net/url"
"strings"
"time"
)
const (
// The endpoint of AWS's Instance Metadata Service, which allows an enclave
// to learn its internal hostname:
// https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html
metadataSvcToken = "http://169.254.169.254/latest/api/token"
metadataSvcInfo = "http://169.254.169.254/latest/meta-data/local-hostname"
)
var (
errBadSliceLen = errors.New("slice is not of same length as nonce")
newUnauthenticatedHTTPClient = func() *http.Client {
return _newUnauthenticatedHTTPClient()
}
getSyncURL = func(host string, port uint16) *url.URL {
return _getSyncURL(host, port)
}
)
// _getSyncURL turns the given host and port into a URL that a leader enclave
// can sync with.
var _getSyncURL = func(host string, port uint16) *url.URL {
return &url.URL{
Scheme: "https",
Host: fmt.Sprintf("%s:%d", host, port),
Path: pathSync,
}
}
// _newUnauthenticatedHTTPClient returns an HTTP client that skips HTTPS
// certificate validation. In the context of nitriding, this is fine because
// all we need is a *confidential* channel; not an authenticated channel.
// Authentication is handled on the next layer, using attestation documents.
func _newUnauthenticatedHTTPClient() *http.Client {
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
return &http.Client{
Transport: transport,
Timeout: 3 * time.Second,
}
}
// createCertificate creates a self-signed certificate and returns the
// PEM-encoded certificate and key. Some of the code below was taken from:
// https://eli.thegreenplace.net/2021/go-https-servers-with-tls/
func createCertificate(fqdn string) (cert []byte, key []byte, err error) {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, err
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, nil, err
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{certificateOrg},
},
DNSNames: []string{fqdn},
NotBefore: time.Now(),
NotAfter: time.Now().Add(certificateValidity),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
derBytes, err := x509.CreateCertificate(
rand.Reader,
&template,
&template,
&privateKey.PublicKey,
privateKey,
)
if err != nil {
return nil, nil, err
}
pemCert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
if pemCert == nil {
return nil, nil, errors.New("error encoding cert as PEM")
}
privBytes, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
return nil, nil, err
}
pemKey := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
if pemKey == nil {
return nil, nil, errors.New("error encoding key as PEM")
}
return pemCert, pemKey, nil
}
// sliceToNonce copies the given slice into a nonce and returns the nonce.
func sliceToNonce(s []byte) (nonce, error) {
var n nonce
if len(s) != nonceLen {
return nonce{}, errBadSliceLen
}
copy(n[:], s[:nonceLen])
return n, nil
}
// getHostnameOrDie returns the "enclave"'s hostname (or IP address) or dies
// trying. If inside an enclave, we query AWS's Instance Metadata Service. If
// outside an enclave, we pick whatever IP address the operating system would
// choose when talking to a public IP address.
func getHostnameOrDie() (hostname string) {
defer func() {
elog.Printf("Determined our hostname: %s", hostname)
}()
var err error
if !inEnclave {
hostname = getLocalAddr()
return
}
// We cannot easily tell when all components are in place to receive
// incoming connections. We therefore make five attempts to get our
// hostname from IMDS while waiting for one second in between attempts.
const retries = 5
for i := 0; i < retries; i++ {
hostname, err = getLocalEC2Hostname()
if err == nil {
return
}
time.Sleep(time.Second)
}
if err != nil {
elog.Fatalf("Error obtaining hostname from IMDSv2: %v", err)
}
return
}
func getLocalAddr() string {
const target = "1.1.1.1:53"
conn, err := net.Dial("udp", target)
if err != nil {
elog.Fatalf("Error dialing %s: %v", target, err)
}
defer conn.Close()
host, _, err := net.SplitHostPort(conn.LocalAddr().String())
if err != nil {
elog.Fatalf("Error extracing host: %v", err)
}
return host
}
func getLocalEC2Hostname() (string, error) {
const (
maxTokenLen = 100
maxHostnameLen = 255
)
// IMDSv2, which we are using, is session-oriented (God knows why), so we
// first obtain a session token from the service.
req, err := http.NewRequest(http.MethodPut, metadataSvcToken, nil)
if err != nil {
return "", err
}
req.Header.Set("X-aws-ec2-metadata-token-ttl-seconds", "10")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
body, err := io.ReadAll(newLimitReader(resp.Body, maxTokenLen))
if err != nil {
return "", err
}
token := string(body)
// Having obtained the session token, we can now make the actual metadata
// request.
req, err = http.NewRequest(http.MethodGet, metadataSvcInfo, nil)
if err != nil {
return "", err
}
req.Header.Set("X-aws-ec2-metadata-token", token)
resp, err = http.DefaultClient.Do(req)
if err != nil {
return "", err
}
body, err = io.ReadAll(newLimitReader(resp.Body, maxHostnameLen))
if err != nil {
return "", err
}
return string(body), nil
}
func getNonceFromReq(r *http.Request) (nonce, error) {
if err := r.ParseForm(); err != nil {
return nonce{}, errBadForm
}
strNonce := r.URL.Query().Get("nonce")
if strNonce == "" {
return nonce{}, errNoNonce
}
strNonce = strings.ToLower(strNonce)
// Decode hex-encoded nonce.
rawNonce, err := hex.DecodeString(strNonce)
if err != nil {
return nonce{}, errBadNonceFormat
}
n, err := sliceToNonce(rawNonce)
if err != nil {
return nonce{}, err
}
return n, nil
}
func makeLeaderRequest(leader *url.URL, ourNonce nonce, areWeLeader chan bool, errChan chan error) {
elog.Println("Attempting to talk to leader designation endpoint.")
reqURL := *leader
reqURL.RawQuery = fmt.Sprintf("nonce=%x", ourNonce[:])
resp, err := newUnauthenticatedHTTPClient().Get(reqURL.String())
if err != nil {
errChan <- err
return
}
if resp.StatusCode == http.StatusGone {
// The leader already knows that it's the leader, and it's not us.
areWeLeader <- false
return
}
errChan <- fmt.Errorf("leader designation endpoint returned %d", resp.StatusCode)
}