-
Notifications
You must be signed in to change notification settings - Fork 51
/
rpc_handle.go
266 lines (204 loc) · 6.5 KB
/
rpc_handle.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
package rpcwrapper
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/binary"
"encoding/gob"
"fmt"
"go.uber.org/zap"
"net"
"net/http"
"os"
"strconv"
"sync"
"time"
"net/rpc"
"github.com/mitchellh/hashstructure"
"go.aporeto.io/trireme-lib/controller/pkg/secrets"
"go.aporeto.io/trireme-lib/utils/cache"
)
// RPCHdl is a per client handle
type RPCHdl struct {
Client *rpc.Client
Channel string
Secret string
}
// RPCWrapper is a struct which holds stats for all rpc sesions
type RPCWrapper struct {
rpcClientMap *cache.Cache
contextList []string
sync.Mutex
}
// NewRPCWrapper creates a new rpcwrapper
func NewRPCWrapper() *RPCWrapper {
RegisterTypes()
return &RPCWrapper{
rpcClientMap: cache.NewCache("RPCWrapper"),
contextList: []string{},
}
}
const (
maxRetries = 10000
envRetryString = "REMOTE_RPCRETRIES"
)
// NewRPCClient exported
func (r *RPCWrapper) NewRPCClient(contextID string, channel string, sharedsecret string) error {
max := maxRetries
retries := os.Getenv(envRetryString)
if len(retries) > 0 {
max, _ = strconv.Atoi(retries)
}
numRetries := 0
client, err := rpc.DialHTTP("unix", channel)
for err != nil {
numRetries++
if numRetries >= max {
return err
}
time.Sleep(5 * time.Millisecond)
client, err = rpc.DialHTTP("unix", channel)
}
r.Lock()
r.contextList = append(r.contextList, contextID)
r.Unlock()
return r.rpcClientMap.Add(contextID, &RPCHdl{Client: client, Channel: channel, Secret: sharedsecret})
}
// GetRPCClient gets a handle to the rpc client for the contextID( enforcer in the container)
func (r *RPCWrapper) GetRPCClient(contextID string) (*RPCHdl, error) {
val, err := r.rpcClientMap.Get(contextID)
if err != nil {
return nil, err
}
return val.(*RPCHdl), nil
}
// RemoteCall is a wrapper around rpc.Call and also ensure message integrity by adding a hmac
func (r *RPCWrapper) RemoteCall(contextID string, methodName string, req *Request, resp *Response) error {
rpcClient, err := r.GetRPCClient(contextID)
if err != nil {
return err
}
digest := hmac.New(sha256.New, []byte(rpcClient.Secret))
hash, err := payloadHash(req.Payload)
if err != nil {
return err
}
if _, err := digest.Write(hash); err != nil {
return err
}
req.HashAuth = digest.Sum(nil)
return rpcClient.Client.Call(methodName, req, resp)
}
// CheckValidity checks if the received message is valid
func (r *RPCWrapper) CheckValidity(req *Request, secret string) bool {
digest := hmac.New(sha256.New, []byte(secret))
hash, err := payloadHash(req.Payload)
if err != nil {
return false
}
if _, err := digest.Write(hash); err != nil {
return false
}
return hmac.Equal(req.HashAuth, digest.Sum(nil))
}
//NewRPCServer returns an interface RPCServer
func NewRPCServer() RPCServer {
return &RPCWrapper{}
}
// StartServer Starts a server and waits for new connections this function never returns
func (r *RPCWrapper) StartServer(ctx context.Context, protocol string, path string, handler interface{}) error {
if len(path) == 0 {
zap.L().Fatal("Sock param not passed in environment")
}
// Register RPC Type
RegisterTypes()
// Register handlers
if err := rpc.Register(handler); err != nil {
return err
}
rpc.HandleHTTP()
// removing old path in case it exists already - error if we can't remove it
if _, err := os.Stat(path); err == nil {
zap.L().Debug("Socket path already exists: removing", zap.String("path", path))
if rerr := os.Remove(path); rerr != nil {
return fmt.Errorf("unable to delete existing socket path %s: %s", path, rerr)
}
}
// Get listener
listen, err := net.Listen(protocol, path)
if err != nil {
return err
}
go http.Serve(listen, nil) // nolint
<-ctx.Done()
if merr := listen.Close(); merr != nil {
zap.L().Warn("Connection already closed", zap.Error(merr))
}
_, err = os.Stat(path)
if !os.IsNotExist(err) {
if err := os.Remove(path); err != nil {
zap.L().Warn("failed to remove old path", zap.Error(err))
}
}
return nil
}
// DestroyRPCClient calls close on the rpc and cleans up the connection
func (r *RPCWrapper) DestroyRPCClient(contextID string) {
rpcHdl, err := r.rpcClientMap.Get(contextID)
if err != nil {
return
}
if err = rpcHdl.(*RPCHdl).Client.Close(); err != nil {
zap.L().Warn("Failed to close channel",
zap.String("contextID", contextID),
zap.Error(err),
)
}
if err = os.Remove(rpcHdl.(*RPCHdl).Channel); err != nil {
zap.L().Debug("Failed to remove channel - already closed",
zap.String("contextID", contextID),
zap.Error(err),
)
}
if err = r.rpcClientMap.Remove(contextID); err != nil {
zap.L().Warn("Failed to remove item from cache",
zap.String("contextID", contextID),
zap.Error(err),
)
}
}
// ContextList returns the list of active context managed by the rpcwrapper
func (r *RPCWrapper) ContextList() []string {
r.Lock()
defer r.Unlock()
return r.contextList
}
// ProcessMessage checks if the given request is valid
func (r *RPCWrapper) ProcessMessage(req *Request, secret string) bool {
return r.CheckValidity(req, secret)
}
// payloadHash returns the has of the payload
func payloadHash(payload interface{}) ([]byte, error) {
hash, err := hashstructure.Hash(payload, nil)
if err != nil {
return []byte{}, err
}
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, hash)
return buf, nil
}
// RegisterTypes registers types that are exchanged between the controller and remoteenforcer
func RegisterTypes() {
gob.Register(&secrets.CompactPKIPublicSecrets{})
gob.Register(&secrets.PKIPublicSecrets{})
gob.Register(&secrets.PSKPublicSecrets{})
gob.RegisterName("go.aporeto.io/internal/enforcer/utils/rpcwrapper.Init_Request_Payload", *(&InitRequestPayload{}))
gob.RegisterName("go.aporeto.io/internal/enforcer/utils/rpcwrapper.Init_Response_Payload", *(&InitResponsePayload{}))
gob.RegisterName("go.aporeto.io/internal/enforcer/utils/rpcwrapper.Init_Supervisor_Payload", *(&InitSupervisorPayload{}))
gob.RegisterName("go.aporeto.io/internal/enforcer/utils/rpcwrapper.Enforce_Payload", *(&EnforcePayload{}))
gob.RegisterName("go.aporeto.io/internal/enforcer/utils/rpcwrapper.UnEnforce_Payload", *(&UnEnforcePayload{}))
gob.RegisterName("go.aporeto.io/enforcer/utils/rpcwrapper.Supervise_Request_Payload", *(&SuperviseRequestPayload{}))
gob.RegisterName("go.aporeto.io/enforcer/utils/rpcwrapper.UnSupervise_Payload", *(&UnSupervisePayload{}))
gob.RegisterName("go.aporeto.io/enforcer/utils/rpcwrapper.Stats_Payload", *(&StatsPayload{}))
gob.RegisterName("go.aporeto.io/enforcer/utils/rpcwrapper.UpdateSecrets_Payload", *(&UpdateSecretsPayload{}))
}