-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminredir.go
321 lines (270 loc) · 6.97 KB
/
minredir.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
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
package minredir
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"net"
"net/http"
"strings"
"text/template"
"time"
)
type result struct {
Color string
Icon string
Message string
}
type config struct {
pattern string
extract func(r *http.Request, resultChan chan string) bool
pageTempl string
title string
success, failure result
}
func defaultConfig() config {
return config{
pattern: "/",
extract: ExtractOAuth2Code,
pageTempl: `<html>
<head><title>{{.Result.Icon}} {{.Title}}</title></head>
<style>
.icon { animation: anim .3s linear }
@keyframes anim { 0% { background-color:green } }
</style>
<body onload="open(location, '_self').close(); window.stop()"> <!-- close or stop connecting to a server -->
<div>
<span style="font-size:xx-large; color:{{.Result.Color}}; border:solid thin {{.Result.Color}};" class="icon">{{.Result.Icon}}</span>
{{.Result.Message}}
</div>
<hr />
<p>This is a temporary page.<br />Please close it.</p>
</body>
</html>
`,
title: "Auth",
success: result{Color: "green", Icon: "✓", Message: "Successfully authenticated!!"},
failure: result{Color: "red", Icon: "✘", Message: "FAILED!"},
}
}
type option func(*config)
func Pattern(pattern string) option {
return func(c *config) {
c.pattern = pattern
}
}
func Extract(extract func(r *http.Request, resultChan chan string) bool) option {
return func(c *config) {
c.extract = extract
}
}
func PageTempl(pageTempl string) option {
return func(c *config) {
c.pageTempl = pageTempl
}
}
func Title(title string) option {
return func(c *config) {
c.title = title
}
}
func Success(color, icon, message string) option {
return func(c *config) {
c.success = result{
Color: color,
Icon: icon,
Message: message,
}
}
}
func Failure(color, icon, message string) option {
return func(c *config) {
c.failure = result{
Color: color,
Icon: icon,
Message: message,
}
}
}
// ExtractOAuth2Code exitracts `code` from OAuth2 HTTP response.
func ExtractOAuth2Code(r *http.Request, resultChan chan string) bool {
code := r.FormValue("code")
resultChan <- code
return (code != "")
}
// Serve launches temporal HTTP server.
func Serve(ctx context.Context, addr string, resultChan chan string, opts ...option) (prepErr error, serveErr chan error) {
config := defaultConfig()
for _, o := range opts {
o(&config)
}
templ, err := template.New("").Parse(config.pageTempl)
if err != nil {
return err, nil
}
serveMux := http.ServeMux{}
server := &http.Server{
Addr: addr,
Handler: &serveMux,
ReadHeaderTimeout: 60 * time.Second,
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err, nil
}
errChan := make(chan error, 2)
serveMux.HandleFunc(config.pattern, func(w http.ResponseWriter, r *http.Request) {
ok := config.extract(r, resultChan)
data := struct {
Title string
Result result
}{
Title: config.title,
}
if ok {
data.Result = config.success
} else {
data.Result = config.failure
}
err := templ.Execute(w, data)
if err != nil {
errChan <- err
}
_ = server.Shutdown(ctx)
})
go func() {
err := server.Serve(ln)
errChan <- err
}()
return nil, errChan
}
func ServeTLS(ctx context.Context, addr string, resultChan chan string, opts ...option) (prepErr error, serveErr chan error) {
config := defaultConfig()
for _, o := range opts {
o(&config)
}
templ, err := template.New("").Parse(config.pageTempl)
if err != nil {
return err, nil
}
serveMux := http.ServeMux{}
server := &http.Server{
Addr: addr,
Handler: &serveMux,
ReadHeaderTimeout: 60 * time.Second,
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err, nil
}
errChan := make(chan error, 2)
serveMux.HandleFunc(config.pattern, func(w http.ResponseWriter, r *http.Request) {
ok := config.extract(r, resultChan)
data := struct {
Title string
Result result
}{
Title: config.title,
}
if ok {
data.Result = config.success
} else {
data.Result = config.failure
}
err := templ.Execute(w, data)
if err != nil {
errChan <- err
}
_ = server.Shutdown(ctx)
})
tlsconfig := tls.Config{MinVersion: tls.VersionTLS12}
tlsconfig.NextProtos = []string{"http/1.1"}
tlsconfig.Certificates = make([]tls.Certificate, 1)
tlsconfig.Certificates[0], err = generateCert("localhost")
if err != nil {
return err, nil
}
tlsListener := tls.NewListener(ln, &tlsconfig)
go func() {
err := server.Serve(tlsListener)
errChan <- err
}()
return nil, errChan
}
func publicKey(priv any) any {
switch k := priv.(type) {
case *rsa.PrivateKey:
return &k.PublicKey
case *ecdsa.PrivateKey:
return &k.PublicKey
case ed25519.PrivateKey:
return k.Public().(ed25519.PublicKey)
default:
return nil
}
}
// go/src/crypto/tls/generate_cert.go
func generateCert(host string) (tls.Certificate, error) {
var priv any
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return tls.Certificate{}, fmt.Errorf("Failed to generate private key: %w", err)
}
keyUsage := x509.KeyUsageDigitalSignature
if _, isRSA := priv.(*rsa.PrivateKey); isRSA {
keyUsage |= x509.KeyUsageKeyEncipherment
}
notBefore := time.Now()
notAfter := notBefore.Add(24 * time.Hour)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return tls.Certificate{}, fmt.Errorf("Failed to generate serial number: %w", err)
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Acme Co"},
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: keyUsage,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
hosts := strings.Split(host, ",")
for _, h := range hosts {
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, h)
}
}
template.IsCA = true
template.KeyUsage |= x509.KeyUsageCertSign
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
if err != nil {
return tls.Certificate{}, fmt.Errorf("Failed to create certificate: %w", err)
}
cert := &bytes.Buffer{}
key := &bytes.Buffer{}
if err := pem.Encode(cert, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
return tls.Certificate{}, fmt.Errorf("Failed to write data: %w", err)
}
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
return tls.Certificate{}, fmt.Errorf("Unable to marshal private key: %w", err)
}
if err := pem.Encode(key, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil {
return tls.Certificate{}, fmt.Errorf("Failed to write data: %w", err)
}
return tls.X509KeyPair(cert.Bytes(), key.Bytes())
}