-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_init.go
320 lines (272 loc) · 8.32 KB
/
server_init.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
package server
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"math/big"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gofiber/fiber/v3"
regex "github.com/tkdeng/goregex"
"github.com/tkdeng/goutil"
"github.com/tkdeng/simplewebserver/cron"
)
var hasFailedSSL bool
// VerifyOrigin can be added to `app.Use` to enforce that all connections
// are coming through a specified domain and proxy ip
//
// @origin: list of valid domains
//
// @proxy: list of valid ip proxies
//
// @handleErr: optional, allows you to define a function for handling invalid origins, instead of returning the default http error
func VerifyOrigin(origin []string, proxy []string, handleErr ...func(c fiber.Ctx, err error) error) func(c fiber.Ctx) error {
return func(c fiber.Ctx) error {
hostname := goutil.Clean(c.Hostname())
ip := goutil.Clean(c.IP())
validOrigin := false
if origin == nil || len(origin) == 0 {
validOrigin = true
} else {
for _, origin := range origin {
if origin == hostname {
validOrigin = true
break
}
}
}
if !validOrigin {
if len(handleErr) != 0 {
return handleErr[0](c, errors.New("Origin Not Allowed: "+hostname))
}
c.SendStatus(403)
return c.SendString("Origin Not Allowed: " + hostname)
}
validProxy := false
if proxy == nil || len(proxy) == 0 {
validProxy = true
} else {
for _, proxy := range proxy {
if proxy == ip {
validProxy = true
break
}
}
}
if !validProxy || !c.IsProxyTrusted() {
if len(handleErr) != 0 {
return handleErr[0](c, errors.New("IP Proxy Not Allowed: "+ip))
}
c.SendStatus(403)
return c.SendString("IP Proxy Not Allowed: " + ip)
}
return c.Next()
}
}
// RedirectSSL can be added to `app.Use` to auto redirect http to https
//
// @httpPort: 80, @sslPort: 443
func RedirectSSL(httpPort, sslPort uint16) func(c fiber.Ctx) error {
return func(c fiber.Ctx) error {
if c.Secure() || hasFailedSSL {
return c.Next()
}
var hostPort uint16
if port, err := strconv.Atoi(string(regex.Comp(`^.*:([0-9]+)$`).RepStr([]byte(goutil.Clean(c.Host())), []byte("$1")))); err == nil {
hostPort = uint16(port)
}
if hostPort != sslPort && hostPort != 443 && c.Port() != strconv.Itoa(int(sslPort)) && c.Port() != "443" {
hostname := goutil.Clean(c.Hostname())
if hostPort == httpPort || c.Port() == strconv.Itoa(int(httpPort)) {
return c.Redirect().Status(301).To("https://" + hostname + ":" + strconv.Itoa(int(sslPort)) + goutil.Clean(c.OriginalURL()))
}
return c.Redirect().Status(301).To("https://" + hostname + goutil.Clean(c.OriginalURL()))
}
return c.Next()
}
}
// ListenAutoTLS will automatically generate a self signed tls certificate
// if needed and listen to both http and https ports
//
// @httpPort: 80, @sslPort: 443
//
// @certPath: file path to store ssl certificates to (this will generate a my/path.crt and my/path.key file)
//
// @proxy: optional, if only one proxy is specified, the app will only listen to that ip address
func ListenAutoTLS(app *fiber.App, httpPort, sslPort uint16, certPath string, proxy ...[]string) error {
certPath = string(regex.Comp(`\.(crt|key)$`).RepStrLit([]byte(certPath), []byte{}))
if sslPort != 0 && certPath != "" {
port := ":" + strconv.Itoa(int(sslPort))
if len(proxy) == 1 && len(proxy[0]) == 1 {
port = proxy[0][0] + port
}
// generate ssl cert if needed
os.MkdirAll(filepath.Dir(certPath), 0755)
err := GenRsaKeyIfNeeded(certPath+".crt", certPath+".key")
if err != nil {
return err
}
// auto renew ssl cert if expired
cron.New(24*time.Hour, func() bool {
err := GenRsaKeyIfNeeded(certPath+".crt", certPath+".key")
if err != nil {
fmt.Println(err)
return false
}
return true
})
go func() {
// err := app.ListenTLS(port, certPath+".crt", certPath+".key")
err := app.Listen(port, fiber.ListenConfig{
CertFile: certPath + ".crt",
CertKeyFile: certPath + ".key",
})
if err != nil {
hasFailedSSL = true
}
}()
}
port := ":" + strconv.Itoa(int(httpPort))
if len(proxy) == 1 && len(proxy[0]) == 1 {
port = proxy[0][0] + port
}
return app.Listen(port)
}
// GenRsaKeyIfNeeded auto detects if the certificates generated by
// the GenRsaKey method are either
// - not synchronized by date modified
// - are possibly expired (assuming a 1 year renewal)
//
// If it detects this is true, it will automatically regenerate a new certificate
func GenRsaKeyIfNeeded(crtPath string, keyPath string) error {
crtStat, crtErr := os.Stat(crtPath)
keyStat, keyErr := os.Stat(keyPath)
if crtErr != nil || keyErr != nil {
err := GenRsaKey(crtPath, keyPath)
if err != nil {
return err
}
return nil
}
crtTime := crtStat.ModTime()
keyTime := keyStat.ModTime()
// regenerate if cert and key not synced || its been 1 year
if crtTime.UnixMilli()/60000 != keyTime.UnixMilli()/60000 || time.Now().Year() > crtTime.Year() {
_, err := goutil.CopyFile(crtPath, crtPath+".old")
if err != nil {
os.Remove(crtPath + ".old")
return err
}
_, err = goutil.CopyFile(keyPath, keyPath+".old")
if err != nil {
os.Remove(crtPath + ".old")
os.Remove(keyPath + ".old")
return err
}
err = GenRsaKey(crtPath, keyPath)
if err != nil {
if _, e := goutil.CopyFile(crtPath+".old", crtPath); e == nil {
os.Remove(crtPath + ".old")
}
if _, e := goutil.CopyFile(keyPath+".old", keyPath); e == nil {
os.Remove(keyPath + ".old")
}
return err
}
}
return nil
}
// GenRsaKey generates a new ssl certificate and key pair
// - expires: 3 years
// - rsa: 4096
// - x509
// - sha256
// - recommended renewal: once a year
func GenRsaKey(crtPath string, keyPath string) error {
//// 10 years: openssl req -newkey rsa:4096 -x509 -sha256 -days 3650 -nodes -out example.crt -keyout example.key
// 3 years: openssl req -newkey rsa:4096 -x509 -sha256 -days 1095 -nodes -out example.crt -keyout example.key
PrintMsg(`warn`, "Generating New SSL Certificate...", 50, false)
// Generate RSA key
key, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
PrintMsg(`error`, "Error: Failed To Generate SSL Certificate!", 50, true)
return err
}
keyBytes := x509.MarshalPKCS1PrivateKey(key)
// PEM encoding of private key
keyPEM := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: keyBytes,
},
)
notBefore := time.Now()
notAfter := notBefore.Add(365 * 24 * 3 * time.Hour)
// Create certificate template
template := x509.Certificate{
SerialNumber: big.NewInt(0),
Subject: pkix.Name{CommonName: "localhost"},
SignatureAlgorithm: x509.SHA256WithRSA,
NotBefore: notBefore,
NotAfter: notAfter,
BasicConstraintsValid: true,
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyAgreement | x509.KeyUsageKeyEncipherment | x509.KeyUsageDataEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
}
// Create certificate using template
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
if err != nil {
PrintMsg(`error`, "Error: Failed To Generate SSL Certificate!", 50, true)
return err
}
// pem encoding of certificate
certPem := pem.EncodeToMemory(
&pem.Block{
Type: "CERTIFICATE",
Bytes: derBytes,
},
)
// Write key to file
if err := os.WriteFile(crtPath, certPem, 0600); err != nil {
PrintMsg(`error`, "Error: Failed To Generate SSL Certificate!", 50, true)
return err
}
// Write cert to file
if err := os.WriteFile(keyPath, keyPEM, 0600); err != nil {
PrintMsg(`error`, "Error: Failed To Generate SSL Certificate!", 50, true)
return err
}
PrintMsg(`warn`, "New SSL Certificate Generated!", 50, true)
return nil
}
// PrintMsg prints to console and auto inserts spaces
func PrintMsg(color string, msg string, size int, end bool) {
if size > len(msg) {
msg += strings.Repeat(" ", size-len(msg))
}
if color == "none" {
color = "0"
} else if color == "error" {
color = "1;31"
} else if color == "confirm" {
color = "1;32"
} else if color == "warn" {
color = "1;33"
} else if color == "info" {
color = "1;34"
} else if color == "value" {
color = "1;35"
}
if end {
fmt.Println("\r\x1b[" + color + "m" + msg + "\x1b[0m")
} else {
fmt.Print("\r\x1b[" + color + "m" + msg + "\x1b[0m")
}
}