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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
|
// Package ipc is the protocol between mitmuxd (which owns the proxy and
// the history database) and a client such as the TUI, spoken as
// newline-agnostic JSON messages over a Unix domain socket. This keeps
// the proxy engine running independently of any UI attached to it.
package ipc
import (
"encoding/json"
"errors"
"fmt"
"net"
"sync"
"time"
"mitmux/internal/proxy"
"mitmux/internal/rules"
"mitmux/internal/scope"
"mitmux/internal/store"
)
// Request is sent by a client to the daemon.
type Request struct {
Type string `json:"type"` // "list", "get", "subscribe", "repeat", "intrude", "rules_list", "rules_save", "rules_delete", "rules_toggle", "delete_entry", or "clear_history"
Limit int `json:"limit,omitempty"`
BeforeID int64 `json:"before_id,omitempty"`
ID int64 `json:"id,omitempty"`
// For "list": a non-empty Query switches from most-recent-first to
// an FTS5 search (see store.Store.Search for syntax), ranked by
// relevance.
Query string `json:"query,omitempty"`
// For "repeat": send Raw to scheme://host exactly as given.
// For "intrude": Raw is the §marked§ template - see proxy.Intrude.
Scheme string `json:"scheme,omitempty"`
Host string `json:"host,omitempty"`
Raw []byte `json:"raw,omitempty"`
// For "intrude": the attack mode (proxy.Sniper and so on - empty
// defaults to Sniper) and its payload sets. Sniper and BatteringRam
// only ever use PayloadSets[0] (one shared set); Pitchfork and
// ClusterBomb require exactly one set per §marked§ position, in
// order - see proxy.Intrude.
Mode proxy.AttackMode `json:"mode,omitempty"`
PayloadSets [][]string `json:"payload_sets,omitempty"`
// For "intrude": optional Go regexps evaluated against each result's
// response bytes. GrepMatch flags whether it matched at all;
// GrepExtract additionally captures text (first submatch if the
// pattern has a capturing group, else the whole match) into the
// result. Either or both may be empty to skip that check. Compiled
// and validated once, server-side, before the attack starts - a bad
// pattern fails the same way a bad marker or empty payload set does.
GrepMatch string `json:"grep_match,omitempty"`
GrepExtract string `json:"grep_extract,omitempty"`
// For "rules_save": add (Rule.ID == 0) or update (Rule.ID != 0) a
// match-and-replace rule. For "rules_delete"/"rules_toggle": RuleID
// (and RuleEnabled for toggle) identify the target.
Rule *rules.Rule `json:"rule,omitempty"`
RuleID int64 `json:"rule_id,omitempty"`
RuleEnabled bool `json:"rule_enabled,omitempty"`
// For "scope_add": the new rule (always an add - scope rules are
// simple enough that edit-in-place isn't worth a separate update
// path; delete and re-add covers it). For "scope_delete"/
// "scope_toggle": ScopeRuleID (and RuleEnabled for toggle) identify
// the target.
ScopeRule *scope.Rule `json:"scope_rule,omitempty"`
ScopeRuleID int64 `json:"scope_rule_id,omitempty"`
// For "set_flagged" and "delete_entry": ID identifies the history
// entry. "clear_history" needs no fields at all.
Flagged bool `json:"flagged,omitempty"`
// For "import": entries to insert directly into history - the
// client has already parsed/converted them (e.g. from a HAR file,
// see cmd/mitmux/har.go); the daemon just stores them.
ImportEntries []ImportEntry `json:"import_entries,omitempty"`
}
// ImportEntry is one entry to insert directly into history via
// "import". RequestExact/ResponseExact are always false once stored:
// an imported entry is reconstructed from whatever structured format it
// came from (HAR, say), never the literal bytes that were on the wire
// for the original request - the same situation an HTTP/2 capture is
// already in.
type ImportEntry struct {
Method string `json:"method"`
Scheme string `json:"scheme"`
Host string `json:"host"`
Path string `json:"path"`
StatusCode int `json:"status_code"`
RequestRaw []byte `json:"request_raw"`
ResponseRaw []byte `json:"response_raw"`
StartedAt time.Time `json:"started_at"`
Duration time.Duration `json:"duration"`
}
// Response is sent by the daemon to a client.
type Response struct {
Type string `json:"type"` // "list", "get", "new", "repeat", "rules", "scope_rules", "intrude_result", "intrude_done", "import_done", "status", "flagged", "deleted", "cleared", or "error"
Entries []store.Summary `json:"entries,omitempty"` // for "list"
Detail *EntryDetail `json:"detail,omitempty"` // for "get" and "repeat"
New *store.Summary `json:"new,omitempty"` // for "new" (subscribe push)
Rules []rules.Rule `json:"rules,omitempty"` // for "rules"
ScopeRules []scope.Rule `json:"scope_rules,omitempty"` // for "scope_rules"
Status *StatusMsg `json:"status,omitempty"` // for "status"
// For "import_done": how many entries were actually inserted (a
// per-entry insert failure is skipped, not fatal to the batch).
Imported int `json:"imported,omitempty"`
// For "intrude_result": one completed attack request.
IntrudeResult *IntrudeResultMsg `json:"intrude_result,omitempty"`
Error string `json:"error,omitempty"`
}
// StatusMsg is basic daemon info for a TUI status bar.
type StatusMsg struct {
ProxyAddr string `json:"proxy_addr"`
HistoryCount int64 `json:"history_count"`
}
// IntrudeResultMsg is one completed Intruder attack request. Values holds
// what was substituted into each §marked§ position for this request, in
// position order - for Sniper, every entry but the one fuzzed position
// equals that position's base value; for the other three modes every
// entry is an actual payload.
type IntrudeResultMsg struct {
Iteration int `json:"iteration"`
Values []string `json:"values"`
EntryID int64 `json:"entry_id"`
StatusCode int `json:"status_code"`
RespSize int `json:"resp_size"`
Duration time.Duration `json:"duration"`
Error string `json:"error,omitempty"`
GrepMatch bool `json:"grep_match,omitempty"`
GrepExtract string `json:"grep_extract,omitempty"`
}
// EntryDetail is a full history entry, raw bytes included.
type EntryDetail struct {
store.Summary
RequestRaw []byte `json:"request_raw"`
ResponseRaw []byte `json:"response_raw"`
RequestExact bool `json:"request_exact"`
ResponseExact bool `json:"response_exact"`
// *Truncated is true when the matching *Exact is false specifically
// because capture hit its size cap and dropped bytes off the end -
// as opposed to false because there was never a wire-exact
// representation to begin with (HTTP/2). Only meaningful alongside
// a false *Exact.
RequestTruncated bool `json:"request_truncated,omitempty"`
ResponseTruncated bool `json:"response_truncated,omitempty"`
}
// Client talks to a mitmuxd instance for request/response queries
// (list, get). Use Subscribe separately for the live-update stream.
//
// One request/response round trip is in flight on the connection at a
// time, guarded by mu - a caller like the mitmux TUI dispatches each
// request as its own goroutine (a Bubble Tea tea.Cmd), and without this
// two overlapping calls (e.g. opening two entries in quick succession)
// would interleave their JSON on the wire or hand one call the other's
// response.
type Client struct {
mu sync.Mutex
conn net.Conn
dec *json.Decoder
enc *json.Encoder
}
// Dial connects to the daemon's control socket at path.
func Dial(path string) (*Client, error) {
conn, err := net.Dial("unix", path)
if err != nil {
return nil, fmt.Errorf("dial %s: %w", path, err)
}
return &Client{conn: conn, dec: json.NewDecoder(conn), enc: json.NewEncoder(conn)}, nil
}
// Close closes the connection to the daemon.
func (c *Client) Close() error {
return c.conn.Close()
}
// SetFlagged sets the flagged marker on a history entry - a simple
// "mark this, revisit later" bit, filterable via flagged:true/false in
// Search.
func (c *Client) SetFlagged(id int64, flagged bool) error {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.enc.Encode(Request{Type: "set_flagged", ID: id, Flagged: flagged}); err != nil {
return err
}
var resp Response
if err := c.dec.Decode(&resp); err != nil {
return err
}
if resp.Type == "error" {
return errors.New(resp.Error)
}
return nil
}
// DeleteEntry removes a single history entry.
func (c *Client) DeleteEntry(id int64) error {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.enc.Encode(Request{Type: "delete_entry", ID: id}); err != nil {
return err
}
var resp Response
if err := c.dec.Decode(&resp); err != nil {
return err
}
if resp.Type == "error" {
return errors.New(resp.Error)
}
return nil
}
// ClearHistory removes every history entry. Rules are untouched.
func (c *Client) ClearHistory() error {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.enc.Encode(Request{Type: "clear_history"}); err != nil {
return err
}
var resp Response
if err := c.dec.Decode(&resp); err != nil {
return err
}
if resp.Type == "error" {
return errors.New(resp.Error)
}
return nil
}
// Import inserts entries directly into history - used to bring in
// traffic from an external source (a HAR file, say) rather than
// something mitmux itself captured. Returns how many were actually
// inserted; a per-entry insert failure is skipped rather than aborting
// the whole batch.
func (c *Client) Import(entries []ImportEntry) (int, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.enc.Encode(Request{Type: "import", ImportEntries: entries}); err != nil {
return 0, err
}
var resp Response
if err := c.dec.Decode(&resp); err != nil {
return 0, err
}
if resp.Type == "error" {
return 0, errors.New(resp.Error)
}
return resp.Imported, nil
}
// Status returns basic daemon info for a status bar.
func (c *Client) Status() (*StatusMsg, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.enc.Encode(Request{Type: "status"}); err != nil {
return nil, err
}
var resp Response
if err := c.dec.Decode(&resp); err != nil {
return nil, err
}
if resp.Type == "error" {
return nil, errors.New(resp.Error)
}
return resp.Status, nil
}
// List returns up to limit history summaries older than beforeID (0 for
// the most recent), newest first.
func (c *Client) List(limit int, beforeID int64) ([]store.Summary, error) {
return c.list(Request{Type: "list", Limit: limit, BeforeID: beforeID})
}
// Search returns up to limit history summaries matching an FTS5 query
// (see store.Store.Search for syntax), ranked by relevance.
func (c *Client) Search(query string, limit int, beforeID int64) ([]store.Summary, error) {
return c.list(Request{Type: "list", Query: query, Limit: limit, BeforeID: beforeID})
}
func (c *Client) list(req Request) ([]store.Summary, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.enc.Encode(req); err != nil {
return nil, err
}
var resp Response
if err := c.dec.Decode(&resp); err != nil {
return nil, err
}
if resp.Type == "error" {
return nil, errors.New(resp.Error)
}
return resp.Entries, nil
}
// Get returns the full entry (raw bytes included) for id.
func (c *Client) Get(id int64) (*EntryDetail, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.enc.Encode(Request{Type: "get", ID: id}); err != nil {
return nil, err
}
var resp Response
if err := c.dec.Decode(&resp); err != nil {
return nil, err
}
if resp.Type == "error" {
return nil, errors.New(resp.Error)
}
return resp.Detail, nil
}
// Repeat sends raw to scheme://host exactly as given (no re-serialization,
// no header injection) and returns the resulting entry, including the raw
// response bytes. The exchange is also recorded to history.
func (c *Client) Repeat(scheme, host string, raw []byte) (*EntryDetail, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.enc.Encode(Request{Type: "repeat", Scheme: scheme, Host: host, Raw: raw}); err != nil {
return nil, err
}
var resp Response
if err := c.dec.Decode(&resp); err != nil {
return nil, err
}
if resp.Type == "error" {
return nil, errors.New(resp.Error)
}
return resp.Detail, nil
}
// ListRules returns every match-and-replace rule.
func (c *Client) ListRules() ([]rules.Rule, error) {
c.mu.Lock()
defer c.mu.Unlock()
return c.rulesRoundTrip(Request{Type: "rules_list"})
}
// SaveRule adds r (if r.ID == 0) or updates the existing rule with that
// ID, and returns its ID.
func (c *Client) SaveRule(r rules.Rule) (int64, error) {
c.mu.Lock()
defer c.mu.Unlock()
saved, err := c.rulesRoundTrip(Request{Type: "rules_save", Rule: &r})
if err != nil {
return 0, err
}
if len(saved) == 0 {
return 0, errors.New("rules_save: daemon returned no rule")
}
return saved[0].ID, nil
}
// DeleteRule removes a rule.
func (c *Client) DeleteRule(id int64) error {
c.mu.Lock()
defer c.mu.Unlock()
_, err := c.rulesRoundTrip(Request{Type: "rules_delete", RuleID: id})
return err
}
// SetRuleEnabled toggles a rule without touching its other fields.
func (c *Client) SetRuleEnabled(id int64, enabled bool) error {
c.mu.Lock()
defer c.mu.Unlock()
_, err := c.rulesRoundTrip(Request{Type: "rules_toggle", RuleID: id, RuleEnabled: enabled})
return err
}
func (c *Client) rulesRoundTrip(req Request) ([]rules.Rule, error) {
if err := c.enc.Encode(req); err != nil {
return nil, err
}
var resp Response
if err := c.dec.Decode(&resp); err != nil {
return nil, err
}
if resp.Type == "error" {
return nil, errors.New(resp.Error)
}
return resp.Rules, nil
}
// ListScopeRules returns every scope rule, enabled or not.
func (c *Client) ListScopeRules() ([]scope.Rule, error) {
c.mu.Lock()
defer c.mu.Unlock()
return c.scopeRoundTrip(Request{Type: "scope_list"})
}
// AddScopeRule adds r and returns its assigned ID.
func (c *Client) AddScopeRule(r scope.Rule) (int64, error) {
c.mu.Lock()
defer c.mu.Unlock()
saved, err := c.scopeRoundTrip(Request{Type: "scope_add", ScopeRule: &r})
if err != nil {
return 0, err
}
if len(saved) == 0 {
return 0, errors.New("scope_add: daemon returned no rule")
}
return saved[0].ID, nil
}
// DeleteScopeRule removes a scope rule.
func (c *Client) DeleteScopeRule(id int64) error {
c.mu.Lock()
defer c.mu.Unlock()
_, err := c.scopeRoundTrip(Request{Type: "scope_delete", ScopeRuleID: id})
return err
}
// SetScopeRuleEnabled toggles a scope rule without touching its pattern.
func (c *Client) SetScopeRuleEnabled(id int64, enabled bool) error {
c.mu.Lock()
defer c.mu.Unlock()
_, err := c.scopeRoundTrip(Request{Type: "scope_toggle", ScopeRuleID: id, RuleEnabled: enabled})
return err
}
func (c *Client) scopeRoundTrip(req Request) ([]scope.Rule, error) {
if err := c.enc.Encode(req); err != nil {
return nil, err
}
var resp Response
if err := c.dec.Decode(&resp); err != nil {
return nil, err
}
if resp.Type == "error" {
return nil, errors.New(resp.Error)
}
return resp.ScopeRules, nil
}
// Subscribe opens a dedicated connection that streams newly captured
// history entries as they happen. The returned channel is closed when
// the connection ends; call the returned close func to stop early.
func Subscribe(path string) (<-chan store.Summary, func() error, error) {
conn, err := net.Dial("unix", path)
if err != nil {
return nil, nil, fmt.Errorf("dial %s: %w", path, err)
}
if err := json.NewEncoder(conn).Encode(Request{Type: "subscribe"}); err != nil {
conn.Close()
return nil, nil, err
}
ch := make(chan store.Summary, 64)
go func() {
defer close(ch)
dec := json.NewDecoder(conn)
for {
var resp Response
if err := dec.Decode(&resp); err != nil {
return
}
if resp.Type == "new" && resp.New != nil {
select {
case ch <- *resp.New:
default:
}
}
}
}()
return ch, conn.Close, nil
}
// Intrude starts an attack (see proxy.Intrude and proxy.AttackMode):
// template must contain at least one §marked§ position. mode selects how
// payloadSets combine across positions; "" defaults to Sniper.
// grepMatch/grepExtract are optional Go regexps evaluated server-side
// against each result's response bytes (empty string disables either
// check) - see IntrudeResultMsg. Unlike Subscribe's live feed, no result
// is ever dropped for a slow consumer - each one is the attack's actual
// data, not a notification with the real thing recoverable elsewhere. A
// setup error (bad markers, empty payload set, too many requests, an
// unparseable grep regexp) is returned directly rather than through the
// channel. The returned channel closes when the attack finishes or the
// connection is closed early.
func Intrude(path, scheme, host string, template []byte, mode proxy.AttackMode, payloadSets [][]string, grepMatch, grepExtract string) (<-chan IntrudeResultMsg, func() error, error) {
conn, err := net.Dial("unix", path)
if err != nil {
return nil, nil, fmt.Errorf("dial %s: %w", path, err)
}
req := Request{Type: "intrude", Scheme: scheme, Host: host, Raw: template, Mode: mode, PayloadSets: payloadSets, GrepMatch: grepMatch, GrepExtract: grepExtract}
if err := json.NewEncoder(conn).Encode(req); err != nil {
conn.Close()
return nil, nil, err
}
dec := json.NewDecoder(conn)
var first Response
if err := dec.Decode(&first); err != nil {
conn.Close()
return nil, nil, err
}
if first.Type == "error" {
conn.Close()
return nil, nil, errors.New(first.Error)
}
ch := make(chan IntrudeResultMsg)
go func() {
defer close(ch)
deliver := func(resp Response) bool {
switch resp.Type {
case "intrude_result":
if resp.IntrudeResult != nil {
ch <- *resp.IntrudeResult
}
return true
default: // "intrude_done", or anything else - stop
return false
}
}
if !deliver(first) {
return
}
for {
var resp Response
if err := dec.Decode(&resp); err != nil {
return
}
if !deliver(resp) {
return
}
}
}()
return ch, conn.Close, nil
}
|