forked from indigo-web/indigo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport.go
213 lines (179 loc) · 5.26 KB
/
transport.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
package indigo
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"github.com/indigo-web/indigo/config"
"github.com/indigo-web/indigo/http/crypt"
"github.com/indigo-web/indigo/http/serve"
"github.com/indigo-web/indigo/router"
"github.com/indigo-web/indigo/transport"
"golang.org/x/crypto/acme/autocert"
"math/big"
"net"
"os"
"path/filepath"
"time"
)
type Transport struct {
addr string // must be left intact. Used by App entity only
inner transport.Transport
spawnCallback func(cfg *config.Config, r router.Router) func(net.Conn)
}
func TCP() Transport {
return Transport{
inner: transport.NewTCP(),
spawnCallback: func(cfg *config.Config, r router.Router) func(net.Conn) {
return func(conn net.Conn) {
serve.HTTP1(cfg, conn, crypt.Plain, r)
}
},
}
}
func TLS(certs ...tls.Certificate) Transport {
if len(certs) == 0 {
panic("need at least one certificate")
}
return newTLSTransport(&tls.Config{Certificates: certs})
}
// Autocert tries to automatically issue a certificate for the given domains.
// If operation succeeds, those will be (hopefully) saved into the default cache
// directory, which depends on the OS. If you want to specify the cache directory,
// use AutocertWithCache instead.
func Autocert(domains ...string) Transport {
return AutocertWithCache(tlsCacheDir(), domains...)
}
// AutocertWithCache tries to automatically issue a certificate for the given domains.
// If the operation succeeds, those will be (hopefully) saved into the provided cache
// directory. It's recommended to use Autocert if there are no explicit needs to set
// custom cache directory.
func AutocertWithCache(cache string, domains ...string) Transport {
m := &autocert.Manager{
Prompt: autocert.AcceptTOS,
Cache: autocert.DirCache(cache),
}
if len(domains) > 0 {
m.HostPolicy = autocert.HostWhitelist(domains...)
}
return newTLSTransport(&tls.Config{GetCertificate: m.GetCertificate})
}
// LocalCert issues a self-signed certificate for local TLS-secured connections.
// Please note, that self-signed certificates are failing security checks, so
// browsers and tools like curl will complain.
func LocalCert(cache ...string) tls.Certificate {
dir := tlsCacheDir()
if len(cache) > 0 {
dir = cache[0]
}
cert, key, err := generateSelfSignedCert(dir)
if err != nil {
panic(fmt.Errorf("cannot issue a local certificate: %s", err))
}
return Cert(cert, key)
}
// Cert loads the TLS certificate. Panics if an error happened.
func Cert(cert, key string) tls.Certificate {
c, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
panic(fmt.Errorf("could not load TLS certificate: %s", err))
}
return c
}
func newTLSTransport(cfg *tls.Config) Transport {
return Transport{
inner: transport.NewTLS(cfg),
spawnCallback: func(cfg *config.Config, r router.Router) func(net.Conn) {
return func(conn net.Conn) {
ver := conn.(*tls.Conn).ConnectionState().Version
serve.HTTP1(cfg, conn, mapTLS(ver), r)
}
},
}
}
func mapTLS(ver uint16) crypt.Encryption {
switch ver {
case tls.VersionTLS10:
return crypt.TLSv10
case tls.VersionTLS11:
return crypt.TLSv11
case tls.VersionTLS12:
return crypt.TLSv12
case tls.VersionTLS13:
return crypt.TLSv13
case tls.VersionSSL30:
return crypt.SSL
default:
return crypt.Unknown
}
}
func generateSelfSignedCert(cache string) (cert, key string, err error) {
var (
certfile = filepath.Join(cache, "localhost.crt")
keyfile = filepath.Join(cache, "localhost.key")
)
if certExists(certfile, keyfile) {
return certfile, keyfile, nil
}
if err := mkdirIfNotExists(cache); err != nil {
return "", "", err
}
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return "", "", err
}
notBefore := time.Now()
notAfter := notBefore.Add(10 * 365 * 24 * time.Hour) // 10 years validity
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{Organization: []string{"Localhost"}},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return "", "", err
}
certFile, err := os.Create(certfile)
if err != nil {
return "", "", err
}
defer certFile.Close()
err = pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: certDER})
if err != nil {
return "", "", err
}
keyFile, err := os.Create(keyfile)
if err != nil {
return "", "", err
}
defer keyFile.Close()
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
return "", "", err
}
err = pem.Encode(keyFile, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
if err != nil {
return "", "", err
}
return certfile, keyfile, nil
}
func mkdirIfNotExists(dir string) error {
if stat, err := os.Stat(dir); err == nil && stat.IsDir() {
return nil
}
return os.MkdirAll(dir, 0700)
}
func certExists(cert, key string) bool {
return fileExists(cert) && fileExists(key)
}
func fileExists(filename string) bool {
stat, err := os.Stat(filename)
return err == nil && !stat.IsDir()
}