Debian Codegraph @

session/session.go

raw symbols SCIP
1 package session
2
3 import (
4 "errors"
5 "fmt"
6 "net"
7 "os"
8 "regexp"
9 "runtime"
10 "runtime/pprof"
11 "sort"
12 "strings"
13 "time"
14
15 "github.com/bettercap/readline"
16
17 "github.com/bettercap/bettercap/caplets"
18 "github.com/bettercap/bettercap/core"
19 "github.com/bettercap/bettercap/firewall"
20 "github.com/bettercap/bettercap/network"
21 "github.com/bettercap/bettercap/packets"
22
23 "github.com/evilsocket/islazy/data"
24 "github.com/evilsocket/islazy/fs"
25 "github.com/evilsocket/islazy/log"
26 "github.com/evilsocket/islazy/ops"
27 "github.com/evilsocket/islazy/plugin"
28 "github.com/evilsocket/islazy/str"
29 "github.com/evilsocket/islazy/tui"
30 )
31
32 const (
33 HistoryFile = "~/bettercap.history"
34 )
35
36 var (
37 I = (*Session)(nil)
38
39 ErrNotSupported = errors.New("this component is not supported on this OS")
40
41 reCmdSpaceCleaner = regexp.MustCompile(`^([^\s]+)\s+(.+)$`)
42 reEnvVarCapture = regexp.MustCompile(`{env\.([^}]+)}`)
43 )
44
45 func ErrAlreadyStarted(name string) error {
46 return fmt.Errorf("module %s is already running", name)
47 }
48
49 func ErrAlreadyStopped(name string) error {
50 return fmt.Errorf("module %s is not running", name)
51 }
52
53 type UnknownCommandCallback func(cmd string) bool
54
55 type GPS struct {
56 Updated time.Time
57 Latitude float64 // Latitude.
58 Longitude float64 // Longitude.
59 FixQuality string // Quality of fix.
60 NumSatellites int64 // Number of satellites in use.
61 HDOP float64 // Horizontal dilution of precision.
62 Altitude float64 // Altitude.
63 Separation float64 // Geoidal separation
64 }
65
66 const AliasesFile = "~/bettercap.aliases"
67
68 var aliasesFileName, _ = fs.Expand(AliasesFile)
69
70 type Session struct {
71 Options core.Options
72 Interface *network.Endpoint
73 Gateway *network.Endpoint
74 Env *Environment
75 Lan *network.LAN
76 WiFi *network.WiFi
77 BLE *network.BLE
78 HID *network.HID
79 Queue *packets.Queue
80 StartedAt time.Time
81 Active bool
82 GPS GPS
83 Modules ModuleList
84 Aliases *data.UnsortedKV
85
86 Input *readline.Instance
87 Prompt Prompt
88 CoreHandlers []CommandHandler
89 Events *EventPool
90 EventsIgnoreList *EventsIgnoreList
91 UnkCmdCallback UnknownCommandCallback
92 Firewall firewall.FirewallManager
93
94 script *Script
95 }
96
97 func New() (*Session, error) {
98 opts, err := core.ParseOptions()
99 if err != nil {
100 return nil, err
101 }
102
103 if *opts.NoColors || !tui.Effects() {
104 tui.Disable()
105 log.NoEffects = true
106 }
107
108 s := &Session{
109 Prompt: NewPrompt(),
110 Options: opts,
111 Env: nil,
112 Active: false,
113 Queue: nil,
114
115 CoreHandlers: make([]CommandHandler, 0),
116 Modules: make([]Module, 0),
117 Events: nil,
118 EventsIgnoreList: NewEventsIgnoreList(),
119 UnkCmdCallback: nil,
120 }
121
122 if *s.Options.CpuProfile != "" {
123 f, err := os.Create(*s.Options.CpuProfile)
124 if err != nil {
125 return nil, err
126 }
127 defer f.Close()
128 if err := pprof.StartCPUProfile(f); err != nil {
129 return nil, err
130 }
131 }
132
133 if bufSize := *s.Options.PcapBufSize; bufSize != -1 {
134 network.CAPTURE_DEFAULTS.Bufsize = bufSize
135 }
136
137 if s.Env, err = NewEnvironment(*s.Options.EnvFile); err != nil {
138 return nil, err
139 }
140
141 if s.Aliases, err = data.NewUnsortedKV(aliasesFileName, data.FlushOnEdit); err != nil {
142 return nil, err
143 }
144
145 s.Events = NewEventPool(*s.Options.Debug, *s.Options.Silent)
146
147 s.registerCoreHandlers()
148
149 if I == nil {
150 I = s
151 }
152
153 return s, nil
154 }
155
156 func (s *Session) Lock() {
157 s.Env.Lock()
158 s.Lan.Lock()
159 s.WiFi.Lock()
160 }
161
162 func (s *Session) Unlock() {
163 s.Env.Unlock()
164 s.Lan.Unlock()
165 s.WiFi.Unlock()
166 }
167
168 func (s *Session) Module(name string) (err error, mod Module) {
169 for _, m := range s.Modules {
170 if m.Name() == name {
171 return nil, m
172 }
173 }
174 return fmt.Errorf("module %s not found", name), mod
175 }
176
177 func (s *Session) Close() {
178 if *s.Options.PrintVersion {
179 return
180 }
181
182 if *s.Options.Debug {
183 fmt.Printf("\nStopping modules and cleaning session state ...\n")
184 s.Events.Add("session.closing", nil)
185 }
186
187 for _, m := range s.Modules {
188 if m.Running() {
189 m.Stop()
190 }
191 }
192
193 s.Firewall.Restore()
194
195 if *s.Options.EnvFile != "" {
196 envFile, _ := fs.Expand(*s.Options.EnvFile)
197 if err := s.Env.Save(envFile); err != nil {
198 fmt.Printf("error while storing the environment to %s: %s", envFile, err)
199 }
200 }
201
202 if *s.Options.CpuProfile != "" {
203 pprof.StopCPUProfile()
204 }
205
206 if *s.Options.MemProfile != "" {
207 f, err := os.Create(*s.Options.MemProfile)
208 if err != nil {
209 fmt.Printf("could not create memory profile: %s\n", err)
210 return
211 }
212 defer f.Close()
213 runtime.GC() // get up-to-date statistics
214 if err := pprof.WriteHeapProfile(f); err != nil {
215 fmt.Printf("could not write memory profile: %s\n", err)
216 }
217 }
218 }
219
220 func (s *Session) Register(mod Module) error {
221 s.Modules = append(s.Modules, mod)
222 return nil
223 }
224
225 func (s *Session) Start() error {
226 var err error
227
228 network.Debug = func(format string, args ...interface{}) {
229 s.Events.Log(log.DEBUG, format, args...)
230 }
231
232 // make sure modules are always sorted by name
233 sort.Slice(s.Modules, func(i, j int) bool {
234 return s.Modules[i].Name() < s.Modules[j].Name()
235 })
236
237 if *s.Options.CapletsPath != "" {
238 if err = caplets.Setup(*s.Options.CapletsPath); err != nil {
239 return err
240 }
241 }
242
243 if s.Interface, err = network.FindInterface(*s.Options.InterfaceName); err != nil {
244 return err
245 }
246
247 if s.Queue, err = packets.NewQueue(s.Interface); err != nil {
248 return err
249 }
250
251 if *s.Options.Gateway != "" {
252 if s.Gateway, err = network.GatewayProvidedByUser(s.Interface, *s.Options.Gateway); err != nil {
253 s.Events.Log(log.WARNING, "%s", err.Error())
254 s.Gateway, err = network.FindGateway(s.Interface)
255 }
256 } else {
257 s.Gateway, err = network.FindGateway(s.Interface)
258 }
259
260 if err != nil {
261 level := ops.Ternary(s.Interface.IsMonitor(), log.DEBUG, log.WARNING).(log.Verbosity)
262 s.Events.Log(level, "%s", err.Error())
263 }
264
265 // we are the gateway
266 if s.Gateway == nil || s.Gateway.IpAddress == s.Interface.IpAddress {
267 s.Gateway = s.Interface
268 } else {
269 // start monitoring for gateway changes
270 go s.routeMon()
271 }
272
273 s.Firewall = firewall.Make(s.Interface)
274
275 s.HID = network.NewHID(s.Aliases, func(dev *network.HIDDevice) {
276 s.Events.Add("hid.device.new", dev)
277 }, func(dev *network.HIDDevice) {
278 s.Events.Add("hid.device.lost", dev)
279 })
280
281 s.BLE = network.NewBLE(s.Aliases, func(dev *network.BLEDevice) {
282 s.Events.Add("ble.device.new", dev)
283 }, func(dev *network.BLEDevice) {
284 s.Events.Add("ble.device.lost", dev)
285 })
286
287 s.WiFi = network.NewWiFi(s.Interface, s.Aliases, func(ap *network.AccessPoint) {
288 s.Events.Add("wifi.ap.new", ap)
289 }, func(ap *network.AccessPoint) {
290 s.Events.Add("wifi.ap.lost", ap)
291 })
292
293 s.Lan = network.NewLAN(s.Interface, s.Gateway, s.Aliases, func(e *network.Endpoint) {
294 s.Events.Add("endpoint.new", e)
295 }, func(e *network.Endpoint) {
296 s.Events.Add("endpoint.lost", e)
297 })
298
299 s.setupEnv()
300
301 if err := s.setupReadline(); err != nil {
302 return err
303 }
304
305 s.setupSignals()
306
307 s.StartedAt = time.Now()
308 s.Active = true
309
310 s.startNetMon()
311
312 s.Events.Add("session.started", nil)
313
314 // register js functions here to avoid cyclic dependency between
315 // js and session
316 plugin.Defines["env"] = jsEnvFunc
317 plugin.Defines["run"] = jsRunFunc
318 plugin.Defines["fileExists"] = jsFileExistsFunc
319 plugin.Defines["loadJSON"] = jsLoadJSONFunc
320 plugin.Defines["saveJSON"] = jsSaveJSONFunc
321 plugin.Defines["onEvent"] = jsOnEventFunc
322 plugin.Defines["session"] = s
323
324 // load the script here so the session and its internal objects are ready
325 if *s.Options.Script != "" {
326 if s.script, err = LoadScript(*s.Options.Script); err != nil {
327 return fmt.Errorf("error loading %s: %v", *s.Options.Script, err)
328 }
329 log.Debug("session script %s loaded", *s.Options.Script)
330 }
331
332 return nil
333 }
334
335 func (s *Session) Skip(ip net.IP) bool {
336 if ip.IsLoopback() {
337 return true
338 } else if ip.Equal(s.Interface.IP) || ip.Equal(s.Interface.IPv6) {
339 return true
340 } else if ip.Equal(s.Gateway.IP) {
341 return true
342 }
343 return false
344 }
345
346 func (s *Session) FindMAC(ip net.IP, probe bool) (net.HardwareAddr, error) {
347 var mac string
348 var hw net.HardwareAddr
349 var err error
350
351 // do we have this ip mac address?
352 mac, err = network.ArpLookup(s.Interface.Name(), ip.String(), false)
353 if err != nil && probe {
354 from := s.Interface.IP
355 from_hw := s.Interface.HW
356
357 if ip.To4() == nil {
358 from = s.Interface.IPv6
359 }
360
361 if err, probe := packets.NewUDPProbe(from, from_hw, ip, 139); err != nil {
362 log.Error("Error while creating UDP probe packet for %s: %s", ip.String(), err)
363 } else {
364 s.Queue.Send(probe)
365 }
366
367 time.Sleep(500 * time.Millisecond)
368 mac, _ = network.ArpLookup(s.Interface.Name(), ip.String(), false)
369 }
370
371 if mac == "" {
372 return nil, fmt.Errorf("Could not find hardware address for %s.", ip.String())
373 }
374
375 mac = network.NormalizeMac(mac)
376 hw, err = net.ParseMAC(mac)
377 if err != nil {
378 return nil, fmt.Errorf("Error while parsing hardware address '%s' for %s: %s", mac, ip.String(), err)
379 }
380 return hw, nil
381 }
382
383 func (s *Session) IsOn(moduleName string) bool {
384 for _, m := range s.Modules {
385 if m.Name() == moduleName {
386 return m.Running()
387 }
388 }
389 return false
390 }
391
392 func (s *Session) Refresh() {
393 p, _ := s.parseEnvTokens(s.Prompt.Render(s))
394 s.Input.SetPrompt(p)
395 s.Input.Refresh()
396 }
397
398 func (s *Session) ReadLine() (string, error) {
399 s.Refresh()
400 return s.Input.Readline()
401 }
402
403 func (s *Session) RunCaplet(filename string) error {
404 caplet, err := caplets.Load(filename)
405 if err != nil {
406 return err
407 }
408
409 return caplet.Eval(nil, func(line string) error {
410 return s.Run(line + "\n")
411 })
412 }
413
414 func parseCapletCommand(line string) (is bool, caplet *caplets.Caplet, argv []string) {
415 file := str.Trim(line)
416 parts := strings.Split(file, " ")
417 argc := len(parts)
418 argv = make([]string, 0)
419 // check for any arguments
420 if argc > 1 {
421 file = str.Trim(parts[0])
422 argv = parts[1:]
423 }
424
425 if cap, err := caplets.Load(file); err == nil {
426 return true, cap, argv
427 }
428
429 return false, nil, nil
430 }
431
432 func (s *Session) Run(line string) error {
433 line = str.TrimRight(line)
434 // remove extra spaces after the first command
435 // so that 'arp.spoof on' is normalized
436 // to 'arp.spoof on' (fixes #178)
437 line = reCmdSpaceCleaner.ReplaceAllString(line, "$1 $2")
438
439 // replace all {env.something} with their values
440 line, err := s.parseEnvTokens(line)
441 if err != nil {
442 return err
443 }
444
445 // is it a core command?
446 for _, h := range s.CoreHandlers {
447 if parsed, args := h.Parse(line); parsed {
448 return h.Exec(args, s)
449 }
450 }
451
452 // is it a module command?
453 for _, m := range s.Modules {
454 for _, h := range m.Handlers() {
455 if parsed, args := h.Parse(line); parsed {
456 return h.Exec(args)
457 }
458 }
459 }
460
461 // is it a caplet command?
462 if parsed, caplet, argv := parseCapletCommand(line); parsed {
463 return caplet.Eval(argv, func(line string) error {
464 return s.Run(line + "\n")
465 })
466 }
467
468 // is it a proxy module custom command?
469 if s.UnkCmdCallback != nil && s.UnkCmdCallback(line) {
470 return nil
471 }
472
473 return fmt.Errorf("unknown or invalid syntax \"%s%s%s\", type %shelp%s for the help menu.", tui.BOLD, line, tui.RESET, tui.BOLD, tui.RESET)
474 }