-
-
Notifications
You must be signed in to change notification settings - Fork 134
/
grpc.go
104 lines (89 loc) · 2.27 KB
/
grpc.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
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"os"
"github.com/tg123/sshpiper/cmd/sshpiperd/internal/plugin"
"github.com/urfave/cli/v2"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
)
func createNetGrpcPlugin(args []string) (grpcPlugin *plugin.GrpcPlugin, err error) {
app := &cli.App{
Name: "grpc",
Usage: "sshpiperd grpc plugin",
HideHelpCommand: true,
HideHelp: true,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "endpoint",
Usage: "grpc endpoint address",
EnvVars: []string{"SSHPIPERD_GRPC_ENDPOINT"},
Required: true,
},
&cli.BoolFlag{
Name: "insecure",
Usage: "disable tls",
EnvVars: []string{"SSHPIPERD_GRPC_INSECURE"},
},
&cli.StringFlag{
Name: "key",
Usage: "grpc client key path",
EnvVars: []string{"SSHPIPERD_GRPC_KEY"},
},
&cli.StringFlag{
Name: "cert",
Usage: "grpc client cert path",
EnvVars: []string{"SSHPIPERD_GRPC_CERT"},
},
&cli.StringFlag{
Name: "cacert",
Usage: "grpc ca cert path",
EnvVars: []string{"SSHPIPERD_GRPC_CACERT"},
},
},
Action: func(c *cli.Context) error {
var secopt grpc.DialOption
if c.Bool("insecure") {
secopt = grpc.WithTransportCredentials(insecure.NewCredentials())
} else {
clientCert, err := tls.LoadX509KeyPair(c.String("cert"), c.String("key"))
if err != nil {
return err
}
config := &tls.Config{
Certificates: []tls.Certificate{clientCert},
}
cacert := c.String("cacert")
if cacert != "" {
ca, err := os.ReadFile(cacert)
if err != nil {
return err
}
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(ca) {
return fmt.Errorf("failed to append ca")
}
config.RootCAs = certPool
}
secopt = grpc.WithTransportCredentials(credentials.NewTLS(config))
}
conn, err := grpc.NewClient(c.String("endpoint"), secopt)
if err != nil {
return err
}
grpcPlugin, err = plugin.DialGrpc(conn)
if err != nil {
return err
}
grpcPlugin.Name = fmt.Sprintf("grpc://%s", c.String("endpoint"))
return nil
},
}
if err := app.Run(args); err != nil {
return nil, err
}
return grpcPlugin, nil
}