-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
387 lines (321 loc) · 7.72 KB
/
client.go
File metadata and controls
387 lines (321 loc) · 7.72 KB
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
package gomsf
import (
"bytes"
"context"
"errors"
"fmt"
"net/http"
"sync"
"time"
"github.com/vmihailenco/msgpack/v5"
)
type Client struct {
host string
port int
uri string
ssl bool
username string
token string
tokenMu sync.RWMutex
client *http.Client
consolePollInterval time.Duration
sessionPollInterval time.Duration
}
type ClientOption func(*Client)
const (
defaultConsolePollInterval = 500 * time.Millisecond
defaultSessionPollInterval = time.Second
)
func WithHost(host string) ClientOption {
return func(c *Client) {
c.host = host
}
}
func WithPort(port int) ClientOption {
return func(c *Client) {
c.port = port
}
}
func WithURI(uri string) ClientOption {
return func(c *Client) {
c.uri = uri
}
}
func WithSSL(ssl bool) ClientOption {
return func(c *Client) {
c.ssl = ssl
}
}
func WithUsername(username string) ClientOption {
return func(c *Client) {
c.username = username
}
}
func WithHTTPClient(client *http.Client) ClientOption {
return func(c *Client) {
c.client = client
}
}
func WithConsolePollInterval(interval time.Duration) ClientOption {
return func(c *Client) {
c.consolePollInterval = interval
}
}
func WithSessionPollInterval(interval time.Duration) ClientOption {
return func(c *Client) {
c.sessionPollInterval = interval
}
}
func NewClient(password string, opts ...ClientOption) (*Client, error) {
c := &Client{
host: "127.0.0.1",
port: 55553,
uri: "/api/",
ssl: true,
username: "msf",
consolePollInterval: defaultConsolePollInterval,
sessionPollInterval: defaultSessionPollInterval,
}
for _, opt := range opts {
opt(c)
}
if c.client == nil {
c.client = &http.Client{
Timeout: 30 * time.Second,
}
}
if err := c.login(c.username, password); err != nil {
return nil, err
}
return c, nil
}
func NewClientWithToken(token string, opts ...ClientOption) (*Client, error) {
c := &Client{
host: "127.0.0.1",
port: 55553,
uri: "/api/",
ssl: true,
username: "msf",
token: token,
consolePollInterval: defaultConsolePollInterval,
sessionPollInterval: defaultSessionPollInterval,
}
for _, opt := range opts {
opt(c)
}
if c.client == nil {
c.client = &http.Client{
Timeout: 30 * time.Second,
}
}
return c, nil
}
func (c *Client) url() string {
scheme := "http"
if c.ssl {
scheme = "https"
}
return fmt.Sprintf("%s://%s:%d%s", scheme, c.host, c.port, c.uri)
}
func (c *Client) Call(ctx context.Context, method MsfRpcMethod, args ...interface{}) (interface{}, error) {
c.tokenMu.RLock()
token := c.token
c.tokenMu.RUnlock()
if method != AuthLogin && token == "" {
return nil, ErrNotAuthenticated
}
reqArgs := make([]interface{}, 0, len(args)+2)
reqArgs = append(reqArgs, string(method))
if method != AuthLogin {
reqArgs = append(reqArgs, token)
}
reqArgs = append(reqArgs, args...)
payload, err := msgpack.Marshal(reqArgs)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "POST", c.url(), bytes.NewReader(payload))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "binary/message-pack")
resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
var result interface{}
if err := msgpack.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
result = convertBytesToString(result)
if rpcErr, ok := responseRPCError(result); ok {
return nil, rpcErr
}
return result, nil
}
func (c *Client) login(username, password string) error {
result, err := c.Call(context.Background(), AuthLogin, username, password)
if err != nil {
return err
}
m, ok := result.(map[string]interface{})
if !ok {
return fmt.Errorf("%w: expected auth result map", ErrUnexpectedResponse)
}
if res, ok := m["result"].(string); !ok || res != "success" {
return fmt.Errorf("authentication failed")
}
token, ok := m["token"].(string)
if !ok {
return fmt.Errorf("%w: missing auth token", ErrUnexpectedResponse)
}
c.tokenMu.Lock()
c.token = token
c.tokenMu.Unlock()
return nil
}
func (c *Client) Logout(ctx context.Context) error {
c.tokenMu.RLock()
token := c.token
c.tokenMu.RUnlock()
if token == "" {
return nil
}
_, err := c.Call(ctx, AuthLogout, token)
if err != nil {
return err
}
c.tokenMu.Lock()
c.token = ""
c.tokenMu.Unlock()
return nil
}
func (c *Client) Token() string {
c.tokenMu.RLock()
defer c.tokenMu.RUnlock()
return c.token
}
func (c *Client) IsAuthenticated() bool {
c.tokenMu.RLock()
defer c.tokenMu.RUnlock()
return c.token != ""
}
func convertBytesToString(v interface{}) interface{} {
switch val := v.(type) {
case []byte:
return string(val)
case map[string]interface{}:
for k, v := range val {
val[k] = convertBytesToString(v)
}
return val
case []interface{}:
for i, v := range val {
val[i] = convertBytesToString(v)
}
return val
case map[interface{}]interface{}:
m := make(map[string]interface{}, len(val))
for k, v := range val {
var key string
switch kt := k.(type) {
case []byte:
key = string(kt)
case string:
key = kt
default:
key = fmt.Sprintf("%v", kt)
}
m[key] = convertBytesToString(v)
}
return m
default:
return v
}
}
func decodeResult(data interface{}, target interface{}) error {
encoded, err := msgpack.Marshal(data)
if err != nil {
return err
}
return msgpack.Unmarshal(encoded, target)
}
func responseMap(result interface{}) (map[string]interface{}, error) {
m, ok := result.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("%w: expected map", ErrUnexpectedResponse)
}
return m, nil
}
func responseStringSlice(result interface{}, key string) ([]string, error) {
data, err := responseMap(result)
if err != nil {
return nil, err
}
raw, ok := data[key].([]interface{})
if !ok {
return nil, fmt.Errorf("%w: expected %s list", ErrUnexpectedResponse, key)
}
values := make([]string, len(raw))
for i, item := range raw {
value, ok := item.(string)
if !ok {
return nil, fmt.Errorf("%w: expected %s[%d] string", ErrUnexpectedResponse, key, i)
}
values[i] = value
}
return values, nil
}
func responseString(data map[string]interface{}, key string) (string, error) {
value, ok := data[key].(string)
if !ok {
return "", fmt.Errorf("%w: expected %s string", ErrUnexpectedResponse, key)
}
return value, nil
}
func responseRPCError(result interface{}) (*RPCError, bool) {
data, ok := result.(map[string]interface{})
if !ok {
return nil, false
}
isError, ok := data["error"].(bool)
if !ok || !isError {
return nil, false
}
message, _ := data["error_message"].(string)
class, _ := data["error_string"].(string)
return &RPCError{
Class: class,
Message: message,
}, true
}
func rpcErrorMessage(err error, message string) bool {
var rpcErr *RPCError
if !errors.As(err, &rpcErr) {
return false
}
return rpcErr.Message == message
}
func (c *Client) consolePollIntervalValue() time.Duration {
if c.consolePollInterval <= 0 {
return defaultConsolePollInterval
}
return c.consolePollInterval
}
func (c *Client) sessionPollIntervalValue() time.Duration {
if c.sessionPollInterval <= 0 {
return defaultSessionPollInterval
}
return c.sessionPollInterval
}
func waitForPoll(ctx context.Context, interval time.Duration) error {
timer := time.NewTimer(interval)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}