File: util.go

package info (click to toggle)
acmetool 0.2.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 792 kB
  • sloc: sh: 349; makefile: 105
file content (257 lines) | stat: -rw-r--r-- 5,070 bytes parent folder | download | duplicates (2)
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
package storage

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base32"
	"fmt"
	"gopkg.in/hlandau/acmeapi.v2/acmeutils"
	"io"
	"math/big"
	"net/url"
	"path/filepath"
	"regexp"
	"strings"
)

func decodeAccountURLPart(part string) (string, error) {
	scheme := "https"
	if strings.HasPrefix(part, "http:") {
		scheme = "http"
		part = part[5:]
	}

	unesc, err := url.QueryUnescape(part)
	if err != nil {
		return "", err
	}

	p := scheme + "://" + unesc
	u, err := url.Parse(p)
	if err != nil {
		return "", err
	}

	if u.Path == "" {
		u.Path = "/"
	}

	return u.String(), nil
}

func accountURLPart(directoryURL string) (string, error) {
	u, err := url.Parse(directoryURL)
	if err != nil {
		return "", err
	}

	if u.Scheme != "https" && u.Scheme != "http" {
		return "", fmt.Errorf("scheme must be HTTPS (or HTTP)")
	}

	directoryURL = u.String()
	s := directoryURL[strings.IndexByte(directoryURL, ':')+3:]
	if u.Path == "/" {
		s = s[0 : len(s)-1]
	}

	s = lowerEscapes(url.QueryEscape(s))
	if u.Scheme == "http" {
		s = "http:" + s
	}

	return s, nil
}

func lowerEscapes(s string) string {
	b := []byte(s)
	state := 0
	for i := 0; i < len(b); i++ {
		switch state {
		case 0:
			if b[i] == '%' {
				state = 1
			}
		case 1:
			if b[i] == '%' {
				state = 0
			} else {
				state = 2
			}
			b[i] = lowerChar(b[i])
		case 2:
			state = 0
			b[i] = lowerChar(b[i])
		}
	}
	return string(b)
}

func lowerChar(c byte) byte {
	if c >= 'A' && c <= 'F' {
		return c - 'A' + 'a'
	}
	return c
}

// 'root' must be an absolute path.
func pathIsWithin(subject, root string) (bool, error) {
	os := subject
	subject, err := filepath.EvalSymlinks(subject)
	if err != nil {
		log.Errore(err, "eval symlinks: ", os, " ", root)
		return false, err
	}

	subject, err = filepath.Abs(subject)
	if err != nil {
		return false, err
	}

	return strings.HasPrefix(subject, ensureSeparator(root)), nil
}

func ensureSeparator(p string) string {
	if !strings.HasSuffix(p, string(filepath.Separator)) {
		return p + string(filepath.Separator)
	}

	return p
}

func determineKeyIDFromCert(c *x509.Certificate) string {
	return determineKeyIDFromSubjectPublicKeyInfo(c.RawSubjectPublicKeyInfo)
}

func determineKeyIDFromSubjectPublicKeyInfo(b []byte) string {
	h := sha256.New()
	h.Write(b)
	return strings.ToLower(strings.TrimRight(base32.StdEncoding.EncodeToString(h.Sum(nil)), "="))
}

func getPublicKey(pk crypto.PrivateKey) crypto.PublicKey {
	switch pkv := pk.(type) {
	case *rsa.PrivateKey:
		return &pkv.PublicKey
	case *ecdsa.PrivateKey:
		return &pkv.PublicKey
	default:
		panic("unsupported key type")
	}
}

func determineKeyIDFromKey(pk crypto.PrivateKey) (string, error) {
	return determineKeyIDFromKeyIntl(getPublicKey(pk), pk)
}

func determineKeyIDFromKeyIntl(pubk crypto.PublicKey, pk crypto.PrivateKey) (string, error) {
	cc := &x509.Certificate{
		SerialNumber: big.NewInt(1),
	}
	cb, err := x509.CreateCertificate(rand.Reader, cc, cc, pubk, pk)
	if err != nil {
		return "", err
	}

	c, err := x509.ParseCertificate(cb)
	if err != nil {
		return "", err
	}

	return determineKeyIDFromCert(c), nil
}

type psuedoPrivateKey struct {
	pk crypto.PublicKey
}

func (ppk *psuedoPrivateKey) Public() crypto.PublicKey {
	return ppk.pk
}

func (ppk *psuedoPrivateKey) Sign(io.Reader, []byte, crypto.SignerOpts) ([]byte, error) {
	return []byte{0}, nil
}

// Given a public key, returns the key ID.
func DetermineKeyIDFromPublicKey(pubk crypto.PublicKey) (string, error) {
	b, err := x509.MarshalPKIXPublicKey(pubk)
	if err != nil {
		return "", err
	}

	return determineKeyIDFromSubjectPublicKeyInfo(b), nil
}

func determineAccountID(providerURL string, privateKey interface{}) (string, error) {
	u, err := accountURLPart(providerURL)
	if err != nil {
		return "", err
	}

	keyID, err := determineKeyIDFromKey(privateKey)
	if err != nil {
		return "", err
	}

	return u + "/" + keyID, nil
}

func determineCertificateID(url string) string {
	h := sha256.New()
	h.Write([]byte(url))
	b := h.Sum(nil)
	return strings.ToLower(strings.TrimRight(base32.StdEncoding.EncodeToString(b), "="))
}

var reCertID = regexp.MustCompile(`^[a-z0-9]{52}$`)

// Returns true iff the given string could (possibly) be a valid certificate
// (or key) ID.
func IsWellFormattedCertificateOrKeyID(certificateID string) bool {
	return reCertID.MatchString(certificateID)
}

func targetGt(a *Target, b *Target) bool {
	if a == nil && b == nil {
		return false // equal
	} else if b == nil {
		return true // a > nil
	} else if a == nil {
		return false // nil < a
	}

	if a.Priority > b.Priority {
		return true
	} else if a.Priority < b.Priority {
		return false
	}

	return len(a.Satisfy.Names) > len(b.Satisfy.Names)
}

func containsName(names []string, name string) bool {
	for _, n := range names {
		if n == name {
			return true
		}
	}
	return false
}

func normalizeNames(names []string) error {
	for i := range names {
		n, err := acmeutils.NormalizeHostname(names[i])
		if err != nil {
			return err
		}

		names[i] = n
	}

	return nil
}