/
grpc.go
347 lines (300 loc) · 9.03 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
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// Package remote provides a gRPC backed signer (both client and server).
package remote
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"strings"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/oasisprotocol/oasis-core/go/common/crypto/signature"
cmnGrpc "github.com/oasisprotocol/oasis-core/go/common/grpc"
)
// SignerName is the name used to identify the remote signer.
const SignerName = "remote"
var (
serviceName = cmnGrpc.NewServiceName("RemoteSigner")
methodPublicKeys = serviceName.NewMethod("PublicKeys", nil)
methodSign = serviceName.NewMethod("Sign", SignRequest{})
methodProve = serviceName.NewMethod("Prove", ProveRequest{})
serviceDesc = grpc.ServiceDesc{
ServiceName: string(serviceName),
HandlerType: (*Backend)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: methodPublicKeys.ShortName(),
Handler: handlerPublicKeys,
},
{
MethodName: methodSign.ShortName(),
Handler: handlerSign,
},
{
MethodName: methodProve.ShortName(),
Handler: handlerProve,
},
},
}
)
// PublicKey is a public key supported by the remote signer.
type PublicKey struct {
Role signature.SignerRole `json:"role"`
PublicKey signature.PublicKey `json:"public_key"`
}
// SignRequest is a signature request.
type SignRequest struct {
Role signature.SignerRole `json:"role"`
Context string `json:"context"`
Message []byte `json:"message"`
}
// ProveRequest is a VRF proof request.
type ProveRequest struct {
Role signature.SignerRole `json:"role"`
Alpha []byte `json:"alpha"`
}
// Backend is the remote signer backend interface.
type Backend interface {
PublicKeys(context.Context) ([]PublicKey, error)
Sign(context.Context, *SignRequest) ([]byte, error)
Prove(context.Context, *ProveRequest) ([]byte, error)
}
type wrapper struct {
signers map[signature.SignerRole]signature.Signer
}
func (w *wrapper) PublicKeys(ctx context.Context) ([]PublicKey, error) {
var resp []PublicKey
for _, v := range signature.SignerRoles { // Return in consistent order.
if signer := w.signers[v]; signer != nil {
resp = append(resp, PublicKey{
Role: v,
PublicKey: signer.Public(),
})
}
}
return resp, nil
}
func (w *wrapper) Sign(ctx context.Context, req *SignRequest) ([]byte, error) {
signer, ok := w.signers[req.Role]
if !ok {
return nil, signature.ErrNotExist
}
return signer.ContextSign(signature.Context(req.Context), req.Message)
}
func (w *wrapper) Prove(ctx context.Context, req *ProveRequest) ([]byte, error) {
signer, ok := w.signers[req.Role]
if !ok {
return nil, signature.ErrNotExist
}
vrfSigner, ok := signer.(signature.VRFSigner)
if !ok {
return nil, fmt.Errorf("signature/signer/remote: signer does not support VRF prove")
}
if req.Role != signature.SignerVRF {
return nil, signature.ErrInvalidRole
}
return vrfSigner.Prove(req.Alpha)
}
func handlerPublicKeys(
srv interface{},
ctx context.Context,
dec func(interface{}) error,
interceptor grpc.UnaryServerInterceptor,
) (interface{}, error) {
if interceptor == nil {
return srv.(Backend).PublicKeys(ctx)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: methodPublicKeys.FullName(),
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(Backend).PublicKeys(ctx)
}
return interceptor(ctx, nil, info, handler)
}
func handlerSign(
srv interface{},
ctx context.Context,
dec func(interface{}) error,
interceptor grpc.UnaryServerInterceptor,
) (interface{}, error) {
var req SignRequest
if err := dec(&req); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(Backend).Sign(ctx, &req)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: methodSign.FullName(),
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(Backend).Sign(ctx, req.(*SignRequest))
}
return interceptor(ctx, &req, info, handler)
}
func handlerProve(
srv interface{},
ctx context.Context,
dec func(interface{}) error,
interceptor grpc.UnaryServerInterceptor,
) (interface{}, error) {
var req ProveRequest
if err := dec(&req); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(Backend).Prove(ctx, &req)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: methodProve.FullName(),
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(Backend).Prove(ctx, req.(*ProveRequest))
}
return interceptor(ctx, &req, info, handler)
}
// RegisterService registers a new remote signer backend service with the given
// gRPC server.
func RegisterService(server *grpc.Server, signerFactory signature.SignerFactory) {
if !signature.IsUnsafeUnregisteredContextsAllowed() {
panic("signature/signer/remote: context registration bypass is required")
}
// Load all signers, ignoring errors.
w := &wrapper{
signers: make(map[signature.SignerRole]signature.Signer),
}
for _, v := range signature.SignerRoles {
signer, err := signerFactory.Load(v)
if err == nil {
w.signers[v] = signer
}
}
server.RegisterService(&serviceDesc, w)
}
type remoteFactory struct {
conn *grpc.ClientConn
reqCtx context.Context
signers map[signature.SignerRole]*remoteSigner
}
func (rf *remoteFactory) EnsureRole(role signature.SignerRole) error {
if rf.signers[role] == nil {
return signature.ErrNotExist
}
return nil
}
func (rf *remoteFactory) Generate(role signature.SignerRole, rng io.Reader) (signature.Signer, error) {
return nil, fmt.Errorf("signature/signer/remote: key re-generation prohibited")
}
func (rf *remoteFactory) Load(role signature.SignerRole) (signature.Signer, error) {
signer := rf.signers[role]
if signer == nil {
return nil, signature.ErrNotExist
}
return signer, nil
}
type remoteSigner struct {
factory *remoteFactory
publicKey signature.PublicKey
role signature.SignerRole
}
func (rs *remoteSigner) Public() signature.PublicKey {
return rs.publicKey
}
func (rs *remoteSigner) ContextSign(context signature.Context, message []byte) ([]byte, error) {
// Prepare the context (chain separation is done client side).
rawCtx, err := signature.PrepareSignerContext(context)
if err != nil {
return nil, err
}
req := &SignRequest{
Role: rs.role,
Context: string(rawCtx),
Message: message,
}
var rsp []byte
if err := rs.factory.conn.Invoke(rs.factory.reqCtx, methodSign.FullName(), req, &rsp); err != nil {
return nil, err
}
return rsp, nil
}
func (rs *remoteSigner) String() string {
return "[redacted remote private key]"
}
func (rs *remoteSigner) Reset() {
// Nothing to do.
}
// FactoryConfig is the remote factory configuration.
type FactoryConfig struct {
// Address is the remote factory gRPC address.
Address string
// ServerCertificate is the server certificate.
ServerCertificate *tls.Certificate
// ClientCertificate is the client certificate.
ClientCertificate *tls.Certificate
}
// IsLocal returns true iff the configured endpoint is over AF_LOCAL.
func (fc *FactoryConfig) IsLocal() bool {
return strings.HasPrefix(strings.ToLower(fc.Address), "unix:")
}
// NewFactory creates a new factory with the specified roles.
func NewFactory(config interface{}, roles ...signature.SignerRole) (signature.SignerFactory, error) {
cfg, ok := config.(*FactoryConfig)
if !ok {
return nil, fmt.Errorf("signature/signer/remote: invalid remote signer configuration provided")
}
var cOpts []grpc.DialOption
if !cfg.IsLocal() {
if cfg.ServerCertificate == nil {
return nil, fmt.Errorf("signature/signer/remote: server certificate is required")
}
serverCert, err := x509.ParseCertificate(cfg.ServerCertificate.Certificate[0])
if err != nil {
return nil, fmt.Errorf("signature/signer/remote: failed to parse server certificate: %w", err)
}
creds, err := cmnGrpc.NewClientCreds(&cmnGrpc.ClientOptions{
Certificates: []tls.Certificate{
*cfg.ClientCertificate,
},
GetServerPubKeys: cmnGrpc.ServerPubKeysGetterFromCertificate(serverCert),
CommonName: "remote-signer-server",
})
if err != nil {
return nil, err
}
cOpts = append(cOpts, grpc.WithTransportCredentials(creds))
} else {
cOpts = append(cOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))
}
conn, err := cmnGrpc.Dial(cfg.Address, cOpts...)
if err != nil {
return nil, fmt.Errorf("signature/signer/remote: failed to dial server: %w", err)
}
return NewRemoteFactory(context.Background(), conn)
}
// NewRemoteFactory creates a new gRPC remote signer client service given an
// existing grpc connection.
func NewRemoteFactory(ctx context.Context, conn *grpc.ClientConn) (signature.SignerFactory, error) {
// Enumerate the keys available, and cache them.
var rsp []PublicKey
if err := conn.Invoke(ctx, methodPublicKeys.FullName(), nil, &rsp); err != nil {
return nil, err
}
rf := &remoteFactory{
conn: conn,
reqCtx: ctx,
signers: make(map[signature.SignerRole]*remoteSigner),
}
for _, v := range rsp {
rf.signers[v.Role] = &remoteSigner{
factory: rf,
publicKey: v.PublicKey,
role: v.Role,
}
}
return rf, nil
}