forked from xiaguan/cubefs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
authtool.go
523 lines (464 loc) · 11.9 KB
/
authtool.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
package main
import (
"crypto/rand"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/cubefs/cubefs/proto"
"github.com/cubefs/cubefs/util/config"
"github.com/cubefs/cubefs/util/cryptoutil"
"github.com/cubefs/cubefs/util/keystore"
)
// requst path
const (
GetTicket = "getticket"
CreateKey = "createkey"
DeleteKey = "deletekey"
GetKey = "getkey"
AddCaps = "addcaps"
DeleteCaps = "deletecaps"
AddRaftNode = "addraftnode"
RemoveRaftNode = "removeraftnode"
OSAddCaps = "osaddcaps"
OSDeleteCaps = "osdeletecaps"
OSGetCaps = "osgetcaps"
HTTP = "http://"
HTTPS = "https://"
)
const (
ID = "id"
Role = "role"
Caps = "caps"
AccessKey = "access_key"
AuthKey = "auth_key"
SessionKey = "session_key"
)
var action2PathMap = map[string]string{
GetTicket: proto.ClientGetTicket,
CreateKey: proto.AdminCreateKey,
DeleteKey: proto.AdminDeleteKey,
GetKey: proto.AdminGetKey,
AddCaps: proto.AdminAddCaps,
DeleteCaps: proto.AdminDeleteCaps,
AddRaftNode: proto.AdminAddRaftNode,
RemoveRaftNode: proto.AdminRemoveRaftNode,
OSAddCaps: proto.OSAddCaps,
OSDeleteCaps: proto.OSDeleteCaps,
OSGetCaps: proto.OSGetCaps,
}
var (
cflag string
flaginfo flagInfo
)
type ticketFlag struct {
key string
host string
output string
request string
service string
}
type apiFlag struct {
ticket string
host string
service string
request string
data string
output string
}
type flagInfo struct {
ticket ticketFlag
api apiFlag
https httpsSetting
}
type keyRing struct {
ID string `json:"id"`
Key []byte `json:"key"`
}
type ticketFile struct {
ID string `json:"id"`
Key string `json:"session_key"`
ServiceID string `json:"service_id"`
Ticket string `json:"ticket"`
}
type httpsSetting struct {
enable bool
cert []byte
}
func (m *ticketFile) dumpJSONFile(filename string) {
data, err := json.MarshalIndent(m, "", " ")
if err != nil {
panic(err)
}
file, err := os.Create(filename)
if err != nil {
panic(err)
}
defer file.Close()
_, err = io.WriteString(file, string(data))
if err != nil {
panic(err)
}
}
func sendReqX(target string, data interface{}, cert *[]byte) (res []byte, err error) {
var (
client *http.Client
)
target = HTTPS + target
client, err = cryptoutil.CreateClientX(cert)
if err != nil {
return
}
res, err = proto.SendData(client, target, data)
return
}
func sendReq(target string, data interface{}) (res []byte, err error) {
target = HTTP + target
client := &http.Client{}
res, err = proto.SendData(client, target, data)
return
}
func getTicketFromAuth(keyring *keyRing) (ticketfile ticketFile) {
var (
err error
ts int64
msgResp proto.AuthGetTicketResp
body []byte
)
// construct request body
message := proto.AuthGetTicketReq{
Type: proto.MsgAuthTicketReq,
ClientID: keyring.ID,
ServiceID: flaginfo.ticket.service,
}
if message.Verifier, ts, err = cryptoutil.GenVerifier(keyring.Key); err != nil {
panic(err)
}
url := flaginfo.ticket.host + action2PathMap[flaginfo.ticket.request]
if flaginfo.https.enable {
body, err = sendReqX(url, message, &flaginfo.https.cert)
} else {
body, err = sendReq(url, message)
}
if err != nil {
panic(err)
}
fmt.Printf("\n" + string(body) + "\n")
if msgResp, err = proto.ParseAuthGetTicketResp(body, keyring.Key); err != nil {
panic(err)
}
if err = proto.VerifyTicketRespComm(&msgResp, proto.MsgAuthTicketReq, keyring.ID, flaginfo.ticket.service, ts); err != nil {
panic(err)
}
ticketfile.Ticket = msgResp.Ticket
ticketfile.ServiceID = msgResp.ServiceID
ticketfile.Key = cryptoutil.Base64Encode(msgResp.SessionKey.Key)
ticketfile.ID = keyring.ID
return
}
func getTicket() {
cfg, err1 := config.LoadConfigFile(flaginfo.ticket.key)
if err1 != nil {
panic(err1)
}
key, err2 := cryptoutil.Base64Decode(cfg.GetString(AuthKey))
if err2 != nil {
panic(err2)
}
keyring := keyRing{
ID: cfg.GetString(ID),
Key: key,
}
ticketfile := getTicketFromAuth(&keyring)
ticketfile.dumpJSONFile(flaginfo.ticket.output)
return
}
func accessAuthServer() {
var (
msg proto.MsgType
sessionKey []byte
err error
message interface{}
ts int64
res string
body []byte
)
switch flaginfo.api.request {
case CreateKey:
msg = proto.MsgAuthCreateKeyReq
case DeleteKey:
msg = proto.MsgAuthDeleteKeyReq
case GetKey:
msg = proto.MsgAuthGetKeyReq
case AddCaps:
msg = proto.MsgAuthAddCapsReq
case DeleteCaps:
msg = proto.MsgAuthDeleteCapsReq
case AddRaftNode:
msg = proto.MsgAuthAddRaftNodeReq
case RemoveRaftNode:
msg = proto.MsgAuthRemoveRaftNodeReq
case OSAddCaps:
msg = proto.MsgAuthOSAddCapsReq
case OSDeleteCaps:
msg = proto.MsgAuthOSDeleteCapsReq
case OSGetCaps:
msg = proto.MsgAuthOSGetCapsReq
default:
panic(fmt.Errorf("wrong requst [%s]", flaginfo.api.request))
}
ticketCFG, err := config.LoadConfigFile(flaginfo.api.ticket)
if err != nil {
panic(err)
}
apiReq := &proto.APIAccessReq{
Type: msg,
ClientID: ticketCFG.GetString(ID),
ServiceID: proto.AuthServiceID,
}
if sessionKey, err = cryptoutil.Base64Decode(ticketCFG.GetString(SessionKey)); err != nil {
panic(err)
}
if apiReq.Verifier, ts, err = cryptoutil.GenVerifier(sessionKey); err != nil {
panic(err)
}
apiReq.Ticket = ticketCFG.GetString("ticket")
dataCFG, err := config.LoadConfigFile(flaginfo.api.data)
if err != nil {
panic(err)
}
switch flaginfo.api.request {
case CreateKey:
message = proto.AuthAPIAccessReq{
APIReq: *apiReq,
KeyInfo: keystore.KeyInfo{
ID: dataCFG.GetString(ID),
Role: dataCFG.GetString(Role),
Caps: []byte(dataCFG.GetString(Caps)),
},
}
case DeleteKey:
fallthrough
case GetKey:
message = proto.AuthAPIAccessReq{
APIReq: *apiReq,
KeyInfo: keystore.KeyInfo{
ID: dataCFG.GetString(ID),
},
}
case AddCaps:
fallthrough
case DeleteCaps:
message = proto.AuthAPIAccessReq{
APIReq: *apiReq,
KeyInfo: keystore.KeyInfo{
ID: dataCFG.GetString(ID),
Caps: []byte(dataCFG.GetString(Caps)),
},
}
case AddRaftNode:
fallthrough
case RemoveRaftNode:
message = proto.AuthRaftNodeReq{
APIReq: *apiReq,
RaftNodeInfo: proto.AuthRaftNodeInfo{
ID: uint64(dataCFG.GetInt64(ID)),
Addr: dataCFG.GetString("addr"),
},
}
case OSAddCaps:
fallthrough
case OSDeleteCaps:
message = proto.AuthOSAccessKeyReq{
APIReq: *apiReq,
AKCaps: keystore.AccessKeyCaps{
AccessKey: dataCFG.GetString(AccessKey),
Caps: []byte(dataCFG.GetString(Caps)),
},
}
case OSGetCaps:
message = proto.AuthOSAccessKeyReq{
APIReq: *apiReq,
AKCaps: keystore.AccessKeyCaps{
AccessKey: dataCFG.GetString(AccessKey),
},
}
default:
panic(fmt.Errorf("wrong action [%s]", flaginfo.api.request))
}
url := flaginfo.api.host + action2PathMap[flaginfo.api.request]
if flaginfo.https.enable {
body, err = sendReqX(url, message, &flaginfo.https.cert)
} else {
body, err = sendReq(url, message)
}
if err != nil {
panic(err)
}
fmt.Printf("\nbody: " + string(body) + "\n")
switch flaginfo.api.request {
case CreateKey:
fallthrough
case DeleteKey:
fallthrough
case GetKey:
fallthrough
case AddCaps:
fallthrough
case DeleteCaps:
var resp proto.AuthAPIAccessResp
if resp, err = proto.ParseAuthAPIAccessResp(body, sessionKey); err != nil {
panic(err)
}
if err = proto.VerifyAPIRespComm(&resp.APIResp, msg, ticketCFG.GetString(ID), proto.AuthServiceID, ts); err != nil {
panic(err)
}
if flaginfo.api.request == CreateKey {
if err = resp.KeyInfo.DumpJSONFile(flaginfo.api.output); err != nil {
panic(err)
}
} else {
if res, err = resp.KeyInfo.DumpJSONStr(); err != nil {
panic(err)
}
fmt.Printf(res + "\n")
}
case AddRaftNode:
fallthrough
case RemoveRaftNode:
var resp proto.AuthRaftNodeResp
if resp, err = proto.ParseAuthRaftNodeResp(body, sessionKey); err != nil {
panic(err)
}
if err = proto.VerifyAPIRespComm(&resp.APIResp, msg, ticketCFG.GetString(ID), proto.AuthServiceID, ts); err != nil {
panic(err)
}
fmt.Printf(resp.Msg + "\n")
case OSAddCaps:
fallthrough
case OSDeleteCaps:
fallthrough
case OSGetCaps:
var resp proto.AuthOSAccessKeyResp
if resp, err = proto.ParseAuthOSAKResp(body, sessionKey); err != nil {
panic(err)
}
if err = proto.VerifyAPIRespComm(&resp.APIResp, msg, ticketCFG.GetString(ID), proto.AuthServiceID, ts); err != nil {
panic(err)
}
if res, err = resp.AKCaps.DumpJSONStr(); err != nil {
panic(err)
}
fmt.Printf(res + "\n")
}
return
}
func accessAPI() {
switch flaginfo.api.service {
case proto.AuthServiceID:
accessAuthServer()
default:
panic(fmt.Errorf("server type error [%s]", flaginfo.api.service))
}
}
func loadCertfile(path string) (caCert []byte) {
var err error
caCert, err = ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
}
return
}
func generateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
// Note that err == nil only if we read len(b) bytes.
if err != nil {
return nil, err
}
return b, nil
}
func main() {
ticketCmd := flag.NewFlagSet("ticket", flag.ExitOnError)
apiCmd := flag.NewFlagSet("api", flag.ExitOnError)
authkeyCmd := flag.NewFlagSet("authkey", flag.ExitOnError)
switch os.Args[1] {
case "ticket":
key := ticketCmd.String("keyfile", "keyring.json", "path to key file")
host := ticketCmd.String("host", "localhost:8080", "api host")
file := ticketCmd.String("output", "ticket.json", "output path to ticket file")
https := ticketCmd.Bool("https", false, "enable https")
certfile := ticketCmd.String("certfile", "server.crt", "path to cert file")
ticketCmd.Parse(os.Args[2:])
flaginfo.ticket.key = *key
flaginfo.ticket.host = *host
flaginfo.ticket.output = *file
flaginfo.https.enable = *https
if flaginfo.https.enable {
flaginfo.https.cert = loadCertfile(*certfile)
}
if len(ticketCmd.Args()) >= 2 {
flaginfo.ticket.request = ticketCmd.Args()[0]
flaginfo.ticket.service = ticketCmd.Args()[1]
if _, ok := action2PathMap[flaginfo.ticket.request]; !ok {
panic(fmt.Errorf("illegal parameter %s", flaginfo.ticket.request))
}
}
getTicket()
case "api":
ticket := apiCmd.String("ticketfile", "ticket.json", "path to ticket file")
host := apiCmd.String("host", "localhost:8080", "api host")
data := apiCmd.String("data", "data.json", "request data file")
output := apiCmd.String("output", "keyring.json", "output path to keyring file")
https := apiCmd.Bool("https", false, "enable https")
certfile := apiCmd.String("certfile", "server.crt", "path to cert file")
apiCmd.Parse(os.Args[2:])
flaginfo.api.ticket = *ticket
flaginfo.api.host = *host
flaginfo.api.data = *data
flaginfo.api.output = *output
flaginfo.https.enable = *https
if flaginfo.https.enable {
flaginfo.https.cert = loadCertfile(*certfile)
}
if len(apiCmd.Args()) >= 2 {
flaginfo.api.service = apiCmd.Args()[0]
flaginfo.api.request = apiCmd.Args()[1]
if _, ok := action2PathMap[flaginfo.api.request]; !ok {
panic(fmt.Errorf("illegal parameter %s", flaginfo.api.request))
}
} else {
panic(fmt.Errorf("requst parameter needed"))
}
accessAPI()
case "authkey":
len := authkeyCmd.Int("keylen", 32, "length of authkey")
output := [2]*string{
authkeyCmd.String("rootkey", "authroot.json", "output path to keyring file of auth root"),
authkeyCmd.String("servicekey", "authservice.json", "output path to keyring file of service"),
}
authkeyCmd.Parse(os.Args[2:])
for i := range output {
random, err := generateRandomBytes(*len)
if err != nil {
panic(err)
}
keyInfo := keystore.KeyInfo{
ID: "AuthService",
AuthKey: random,
Ts: time.Now().Unix(),
Role: "AuthService",
Caps: []byte(`{"*"}`),
}
keyInfo.DumpJSONFile(*output[i])
}
default:
fmt.Println("expected 'ticket', 'api' or 'authkey'subcommands")
os.Exit(1)
}
}