~sotirisp/kindleto

ref: faaff15151ac14fbdf0cb20b3b6a145bf127af3a kindleto/certificates.go -rw-r--r-- 11.6 KiB
faaff151Sotiris Papatheodorou Reduce the TOFU cache save interval 2 months ago
                                                                                
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// SPDX-FileCopyrightText: 2020 Paul Gorman
// SPDX-FileCopyrightText: 2021 Sotiris Papatheodorou
// SPDX-License-Identifier: GPL-3.0-or-later

package main

import (
	"bufio"
	"crypto/ed25519"
	"crypto/rand"
	"crypto/rsa"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"log"
	"math/big"
	mathrand "math/rand"
	"net"
	"net/url"
	"os"
	"path"
	"strings"
	"time"
)

type clientCertificate struct {
	Cert     tls.Certificate
	CertName string
	Expires  string
	Host     string
	Path     []string
	URL      string
	Leaf     *x509.Certificate
}

type persistentCert struct {
	URL     string `json:"url"`
	CertPEM string `json:"certPEM"`
	KeyPEM  string `json:"keyPEM"`
}

type serverCertificate struct {
	host    string
	expires time.Time
	cert    string
}

// checkServerCert checks the Gemini server cert against known certs (TOFU).
func checkServerCert(u *url.URL, conn *tls.Conn) string {
	var warning string

	pc := serverCertificate{
		host:    u.Host,
		expires: conn.ConnectionState().PeerCertificates[0].NotAfter,
		cert:    base64.StdEncoding.EncodeToString(conn.ConnectionState().PeerCertificates[0].Raw),
	}

	muServerCerts.Lock()
	for i, c := range serverCerts {
		if c.host == pc.host {
			if c.cert == pc.cert {
				break
			} else {
				warning = fmt.Sprintf("The TLS certificate %s sent does not match the certificate it sent last time, which was set to expire on %v. However, we will proceed with the request, and trust the new certificate in the future.", c.host, c.expires)
				serverCerts[i].cert = pc.cert
				serverCerts[i].expires = pc.expires
				serverCertsChanged = true
			}
		} else {
			if i == len(serverCerts)-1 {
				serverCerts = append(serverCerts, pc)
				serverCertsChanged = true
			}
		}
	}
	if len(serverCerts) == 0 {
		serverCerts = append(serverCerts, pc)
		serverCertsChanged = true
	}
	muServerCerts.Unlock()

	return warning
}

// deleteClientCert removes the TLS client certificate from clientCerts that
// best matches URL u. Returns a non-nil error if no client cert matches the URL.
func deleteClientCert(u *url.URL) error {
	var err error
	var bestMatchIndex int
	var bestMatchScore int

	splitPath := strings.Split(u.Path, "/")

	muClientCerts.Lock()

	for i, c := range clientCerts {
		if u.Host != c.Host {
			continue
		}
		score := 1
		for i, p := range splitPath {
			if p == c.Path[i] {
				score++
			}
		}
		if score > bestMatchScore {
			bestMatchScore = score
			bestMatchIndex = i
		}
		if score > len(splitPath) {
			break
		}
	}

	if bestMatchScore > 0 {
		newCerts := make([]clientCertificate, 0, len(clientCerts))
		for i, c := range clientCerts {
			if i == bestMatchIndex {
				continue
			}
			newCerts = append(newCerts, c)
		}
		clientCerts = newCerts
		if optLogLevel > 1 {
			log.Printf("deleteClientCert: deleted client certificate for %s", u.String())
		}
	} else {
		err = fmt.Errorf("deleteClientCert: no certificate found matching URL '%s'", u.String())
	}
	muClientCerts.Unlock()

	return err
}

// makeCert returns a self-signed TLS certificate.
// If rsaBits is less than 2048 (e.g., 0), makeCert returns an ed25519 certificate.
func makeCert(starts time.Time, expires time.Time, name string, rsaBits int) (tls.Certificate, error) {
	var err error
	var priv interface{}
	selfCA := true

	if starts.IsZero() {
		starts = time.Now()
	}

	if rsaBits >= 2048 {
		priv, err = rsa.GenerateKey(rand.Reader, 2048)
	} else {
		_, priv, err = ed25519.GenerateKey(rand.Reader)
	}
	if err != nil {
		log.Println("makeCert: failed to generate private key:", err)
	}

	keyUsage := x509.KeyUsageDigitalSignature
	if _, isRSA := priv.(*rsa.PrivateKey); isRSA {
		keyUsage |= x509.KeyUsageKeyEncipherment
	}

	serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
	if err != nil {
		log.Println("makeCert: failed to generate serial number:", err)
	}

	if name == "" {
		ri, err := rand.Int(rand.Reader, big.NewInt(100000000))
		if err != nil {
			log.Println("makeCert: failed to generate big int for cert info:", err)
		}
		name = ri.String()
	}

	certInfo := x509.Certificate{
		BasicConstraintsValid: true,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		KeyUsage:              keyUsage,
		NotAfter:              expires,
		NotBefore:             starts,
		SerialNumber:          serialNumber,
		Subject: pkix.Name{
			Organization: []string{name},
			CommonName:   name,
		},
	}

	certInfo.DNSNames = append(certInfo.DNSNames, "localhost")
	if addr != "" {
		if ip := net.ParseIP(addr); ip != nil {
			certInfo.IPAddresses = append(certInfo.IPAddresses, ip)
		} else {
			certInfo.DNSNames = append(certInfo.DNSNames, addr)
		}
	} else {
		certInfo.IPAddresses = append(certInfo.IPAddresses, net.ParseIP("127.0.0.1"))
	}
	hn, err := os.Hostname()
	if err == nil {
		certInfo.DNSNames = append(certInfo.DNSNames, hn)
	}

	if selfCA {
		certInfo.IsCA = true
		certInfo.KeyUsage = certInfo.KeyUsage | x509.KeyUsageCertSign
	}

	x509Cert, err := x509.CreateCertificate(rand.Reader, &certInfo, &certInfo, publicKey(priv), priv)
	if err != nil {
		log.Fatalf("failed to create certificate: %v", err)
	}

	// Note: We've generate an x509 cert but need to return a TLS cert.
	// These are two different object types.
	//
	// https://stackoverflow.com/questions/34192230/how-to-turn-an-x509-certificate-into-a-tls-certificate-in-go
	// > But if you have an x509.Certificate, you already have a tls.Certificate;
	// > just put the x509.Certificate's Raw bytes into a tls.Certificate's Certificate slice.
	// > TLS servers will need the PrivateKey field set to successfully complete the handshake.
	// > I think the rest is optional.

	tlsCert := tls.Certificate{
		Certificate: [][]byte{x509Cert},
		PrivateKey:  priv,
	}

	return tlsCert, err
}

// matchClientCert returns the TLS client certificate from clientCerts that
// best matches URL u, or nil if none of the certificates match.
func matchClientCert(u *url.URL) tls.Certificate {
	var matchingCert tls.Certificate
	var bestMatchIndex int
	var bestMatchScore int

	splitPath := strings.Split(u.Path, "/")
	splitPathLen := len(splitPath)

	muClientCerts.RLock()
	for i, c := range clientCerts {
		if u.Host != c.Host {
			continue
		}
		certPathLen := len(c.Path)
		var l int
		if splitPathLen < certPathLen {
			l = splitPathLen
		} else {
			l = certPathLen
		}
		score := 1
		for i := 0; i < l; i++ {
			if splitPath[i] == c.Path[i] {
				score++
			}
		}
		if score > bestMatchScore {
			bestMatchScore = score
			bestMatchIndex = i
		}
		if score > len(splitPath) {
			break
		}
	}

	if bestMatchScore > 0 {
		matchingCert = clientCerts[bestMatchIndex].Cert
		if optLogLevel > 1 {
			log.Printf("matchCert: URL %s matched client certificate: %s%s",
				u.String(), clientCerts[bestMatchIndex].Host,
				strings.Join(clientCerts[bestMatchIndex].Path, "/"))
		}
	}
	muClientCerts.RUnlock()

	return matchingCert
}

func publicKey(priv interface{}) interface{} {
	switch k := priv.(type) {
	case *rsa.PrivateKey:
		return &k.PublicKey
	case ed25519.PrivateKey:
		return k.Public().(ed25519.PublicKey)
	default:
		return nil
	}
}

// purgeOldClientCertificates removes expired certificates from clientCerts.
func purgeOldClientCertificates() {
	for {
		now := time.Now()
		expired := 0

		muClientCerts.Lock()
		freshCerts := make([]clientCertificate, 0, len(clientCerts))
		for _, c := range clientCerts {
			if optClientCertsFile != "" && c.Cert.Leaf == nil {
				freshCerts = append(freshCerts, c)
				continue
			}
			if now.Before(c.Cert.Leaf.NotAfter) {
				freshCerts = append(freshCerts, c)
			} else {
				expired++
			}
		}
		clientCerts = freshCerts
		muClientCerts.Unlock()

		if optLogLevel > 1 {
			log.Printf("purgeOldClientCertificates: purged %d expired certificates, kept %d certificates", expired, len(clientCerts))
		}

		time.Sleep(time.Hour)
	}
}

// saveClientCert adds a TLS client certificate to clientCerts.
func saveClientCert(u *url.URL, name string) {
	var err error
	var newCert clientCertificate

	newCert.URL = u.String()
	newCert.Host = u.Host
	newCert.Path = strings.Split(u.Path, "/")
	starts := time.Now().Add(-time.Hour * time.Duration(24*(mathrand.Intn(100)+1)))
	expires := time.Now().Add(time.Hour * time.Duration(optHours))
	newCert.Expires = expires.String()
	newCert.Cert, err = makeCert(starts, expires, name, 2048)
	if err != nil {
		log.Println("proxyGemini: transient client cert generation failed:", err)
	}
	newCert.Leaf, err = x509.ParseCertificate(newCert.Cert.Certificate[0])
	newCert.CertName = newCert.Leaf.Subject.CommonName

	muClientCerts.Lock()
	clientCerts = append(clientCerts, newCert)
	muClientCerts.Unlock()
}

// saveTOFU saves known TLS server certificates to a file.
func saveTOFU(optTofuFile string) {
	var tofuFile string
	if optTofuFile != "" {
		tofuFile = optTofuFile
	} else {
		cacheDir, err := os.UserCacheDir()
		if err != nil {
			log.Println("saveTOFU: error finding cache directory, disabling certificate validation:", err)
			return
		}
		if os.MkdirAll(cacheDir, 0777) != nil {
			log.Println("saveTOFU: error creating cache directory, disabling certificate validation:", err)
			return
		}
		tofuFile = path.Join(cacheDir, "kindleto-tofu.txt")
	}

	if _, err := os.Stat(tofuFile); os.IsNotExist(err) {
		f, err := os.Create(tofuFile);
		f.Close()
		if err != nil {
			log.Printf("saveTOFU: error creating TOFU cache file '%s', disabling certificate validation: %v\n", tofuFile, err)
			return
		}
	}

	f, err := os.Open(tofuFile)
	if err != nil {
		log.Printf("saveTOFU: error opening TOFU cache file '%s', disabling certificate validation: %v\n", tofuFile, err)
		return
	}
	scanner := bufio.NewScanner(f)
	muServerCerts.Lock()
	for scanner.Scan() {
		split := strings.Split(scanner.Text(), " ")
		exp, err := time.Parse(time.RFC3339, split[1])
		if len(split) == 3 && err == nil {
			c := serverCertificate{
				host:    split[0],
				expires: exp,
				cert:    split[2],
			}
			serverCerts = append(serverCerts, c)
		}
	}
	if err := scanner.Err(); err != nil {
		log.Printf("saveTOFU: error reading TOFU cache file '%s': %v\n", tofuFile, err)
	}
	muServerCerts.Unlock()
	f.Close()

	tofuUpdateInterval := 8 * time.Hour
	fails := 0
	for !optTrust {
		now := time.Now()
		if serverCertsChanged {
			muServerCerts.Lock()
			certs := make([]serverCertificate, 0, len(serverCerts))
			for _, c := range serverCerts {
				if now.After(c.expires) {
					continue
				}
				certs = append(certs, c)
			}
			serverCerts = certs
			muServerCerts.Unlock()

			f, err := os.Create(tofuFile)
			if err != nil {
				fails++
				log.Printf("saveTOFU: error writing TOFU cache file '%s': %v\n", tofuFile, err)
				if fails > 10 {
					log.Printf("saveTOFU: error writing TOFU cache file '%s' %d times, disabling certificate validation\n", tofuFile, fails)
					return
				}
				time.Sleep(tofuUpdateInterval)
				continue
			}
			muServerCerts.RLock()
			for _, c := range serverCerts {
				fmt.Fprintf(f, "%s %s %s\n", c.host, c.expires.Format(time.RFC3339), c.cert)
			}
			muServerCerts.RUnlock()
			f.Close()
		}

		time.Sleep(tofuUpdateInterval)
	}
}

// Return a PEM certificate by first trying to interpret the argument as the
// certificate data and if that fails as a path to a certificate.
func loadCertificate(certificate string, certfile_path string) ([]byte, error) {
	if strings.HasPrefix(certificate, "-----BEGIN ") {
		return []byte(certificate), nil
	} else {
		if strings.HasPrefix(certificate, "~") {
			h, err := os.UserHomeDir()
			if err != nil {
				return []byte{}, err
			}
			certificate = strings.Replace(certificate, "~", h, 1)
		} else if !strings.HasPrefix(certificate, "/") {
			certificate = path.Dir(certfile_path) + "/" + certificate
		}
		keyPEM, err := ioutil.ReadFile(certificate)
		if err != nil {
			return []byte{}, err
		}
		return keyPEM, nil
	}
}