-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
80 lines (64 loc) · 2.48 KB
/
server.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
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"log"
"os"
"github.com/primalmotion/netboard/server"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go.aporeto.io/tg/tglib"
)
var serverCmd = &cobra.Command{
Use: "server",
Short: "Run the server",
SilenceUsage: true,
SilenceErrors: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if err := viper.BindPFlags(cmd.PersistentFlags()); err != nil {
return err
}
return viper.BindPFlags(cmd.Flags())
},
RunE: func(cmd *cobra.Command, args []string) error {
listenAddr := viper.GetString("server.listen")
certPath := os.ExpandEnv(viper.GetString("server.cert"))
certKeyPath := os.ExpandEnv(viper.GetString("server.cert-key"))
certKeyPass := viper.GetString("server.cert-key-pass")
clientCAPath := os.ExpandEnv(viper.GetString("server.client-ca"))
log.Println("Server is listening on:", listenAddr)
x509Cert, x509Key, err := tglib.ReadCertificatePEM(certPath, certKeyPath, certKeyPass)
if err != nil {
return fmt.Errorf("unable to read certificate: %w", err)
}
tlsCert, err := tglib.ToTLSCertificate(x509Cert, x509Key)
if err != nil {
return fmt.Errorf("unable to convert to tls certificate: %w", err)
}
clientCAData, err := os.ReadFile(clientCAPath)
if err != nil {
return fmt.Errorf("unable to read client certificate: %w", err)
}
clientCAPool := x509.NewCertPool()
clientCAPool.AppendCertsFromPEM(clientCAData)
tlsConf := &tls.Config{
Certificates: []tls.Certificate{tlsCert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: clientCAPool,
}
return server.Serve(cmd.Context(), listenAddr, tlsConf)
},
}
func init() {
serverCmd.Flags().StringP("listen", "l", ":8989", "The listen address of the server")
_ = viper.BindPFlag("server.listen", serverCmd.Flags().Lookup("listen"))
serverCmd.Flags().StringP("cert", "c", "", "path to the server public key")
_ = viper.BindPFlag("server.cert", serverCmd.Flags().Lookup("cert"))
serverCmd.Flags().StringP("cert-key", "k", "", "path to the server private key")
_ = viper.BindPFlag("server.cert-key", serverCmd.Flags().Lookup("cert-key"))
serverCmd.Flags().StringP("cert-key-pass", "p", "", "optional server key passphrase")
_ = viper.BindPFlag("server.cert-key-pass", serverCmd.Flags().Lookup("cert-key-pass"))
serverCmd.Flags().StringP("client-ca", "C", "", "path to the client certificate CA")
_ = viper.BindPFlag("server.client-ca", serverCmd.Flags().Lookup("client-ca"))
}