forked from nicocha30/ligolo-ng
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
459 lines (399 loc) · 12.6 KB
/
app.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
package app
import (
"errors"
"fmt"
"github.com/AlecAivazis/survey/v2"
"github.com/desertbit/grumble"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/sirupsen/logrus"
"io"
"github.com/audibleblink/ligolo-ng/pkg/protocol"
"github.com/audibleblink/ligolo-ng/pkg/proxy"
"github.com/audibleblink/ligolo-ng/pkg/proxy/netstack"
"github.com/audibleblink/ligolo-ng/pkg/relay"
"net"
"strconv"
"strings"
"sync"
)
var AgentList map[int]proxy.LigoloAgent
var AgentListMutex sync.Mutex
var ListenerList map[int]proxy.Listener
var ListenerListMutex sync.Mutex
var (
ErrInvalidAgent = errors.New("please, select an agent using the session command")
ErrAlreadyRunning = errors.New("already running")
ErrNotRunning = errors.New("no tunnel started")
)
const (
MaxConnectionHandler = 1024
)
func RegisterAgent(agent proxy.LigoloAgent) error {
AgentListMutex.Lock()
AgentList[agent.Id] = agent
AgentListMutex.Unlock()
return nil
}
func Run(tuniface string) {
// CurrentAgent points to the selected agent in the UI (when running session)
var CurrentAgent proxy.LigoloAgent
// ListeningAgent points to the currently running agent (forwarding packets)
var ListeningAgent proxy.LigoloAgent
// AgentList contains all the connected agents
AgentList = make(map[int]proxy.LigoloAgent)
// ListenerList contains all listener relays
ListenerList = make(map[int]proxy.Listener)
// Create a new stack, but without connPool.
// The connPool will be created when using the *start* command
nstack := netstack.NewStack(tuniface, nil)
App.AddCommand(&grumble.Command{
Name: "session",
Help: "Change the current relay agent",
Usage: "session",
Run: func(c *grumble.Context) error {
AgentListMutex.Lock()
if len(AgentList) == 0 {
AgentListMutex.Unlock()
return errors.New("no sessions available")
}
AgentListMutex.Unlock()
var session string
sessionSelector := &survey.Select{
Message: "Specify a session :",
Options: func() (out []string) {
AgentListMutex.Lock()
for id, agent := range AgentList {
out = append(out, fmt.Sprintf("%d - %s", id, agent.String()))
}
AgentListMutex.Unlock()
return
}(),
}
err := survey.AskOne(sessionSelector, &session)
if err != nil {
return err
}
s := strings.Split(session, " ")
sessionID, err := strconv.Atoi(s[0])
if err != nil {
return err
}
CurrentAgent = AgentList[sessionID]
c.App.SetPrompt(fmt.Sprintf("[Agent : %s] » ", CurrentAgent.Name))
return nil
},
})
App.AddCommand(&grumble.Command{
Name: "start",
Help: "Start relaying connection to the current agent",
Usage: "start",
HelpGroup: "Tunneling",
Run: func(c *grumble.Context) error {
if CurrentAgent.Session == nil {
return ErrInvalidAgent
}
if ListeningAgent.Session != nil {
if ListeningAgent.Id == CurrentAgent.Id {
return ErrAlreadyRunning
}
if !ListeningAgent.Session.IsClosed() {
var switchConfirm bool
askSwitch := survey.Confirm{
Message: fmt.Sprintf("Tunnel already running, switch from %s to %s?", ListeningAgent.Name, CurrentAgent.Name),
}
if err := survey.AskOne(&askSwitch, &switchConfirm); err != nil {
return err
}
if !switchConfirm {
return nil
}
// Close agent
ListeningAgent.CloseChan <- true
}
}
ListeningAgent = CurrentAgent
go func() {
logrus.Infof("Starting tunnel to %s", ListeningAgent.Name)
// Create a new, empty, connpool to store connections/packets
connPool := netstack.NewConnPool(MaxConnectionHandler)
nstack.SetConnPool(&connPool)
// Cleanup pool if channel is closed
defer connPool.Close()
for {
select {
case <-ListeningAgent.CloseChan: // User stopped
logrus.Infof("Closing tunnel to %s...", ListeningAgent.Name)
return
case <-ListeningAgent.Session.CloseChan(): // Agent closed
logrus.Warnf("Lost connection with agent %s!", ListeningAgent.Name)
// Connection lost, we need to delete the Agent from the list
AgentListMutex.Lock()
delete(AgentList, ListeningAgent.Id)
AgentListMutex.Unlock()
if CurrentAgent.Id == ListeningAgent.Id {
App.SetDefaultPrompt()
CurrentAgent.Session = nil
}
return
case <-connPool.CloseChan: // pool closed, we can't process packets!
logrus.Infof("Connection pool closed")
return
case tunnelPacket := <-connPool.Pool: // Process connections/packets
go netstack.HandlePacket(nstack.GetStack(), tunnelPacket, ListeningAgent.Session)
}
}
}()
return nil
},
})
App.AddCommand(&grumble.Command{Name: "stop",
Help: "Stop the tunnel",
Usage: "stop",
HelpGroup: "Tunneling",
Run: func(c *grumble.Context) error {
if ListeningAgent.Session == nil {
return ErrNotRunning
}
ListeningAgent.CloseChan <- true
ListeningAgent.Session = nil
return nil
},
})
App.AddCommand(&grumble.Command{
Name: "ifconfig",
Help: "Show agent interfaces",
Usage: "ifconfig",
Run: func(c *grumble.Context) error {
// Note: Network information is not refreshed when calling this command
if CurrentAgent.Session == nil {
return ErrInvalidAgent
}
for n, ifaceInfo := range CurrentAgent.Network {
t := table.NewWriter()
t.SetStyle(table.StyleLight)
t.SetTitle(fmt.Sprintf("Interface %d", n))
t.AppendRow(table.Row{"Name", ifaceInfo.Name})
t.AppendRow(table.Row{"Hardware MAC", ifaceInfo.HardwareAddr})
t.AppendRow(table.Row{"MTU", ifaceInfo.MTU})
t.AppendRow(table.Row{"Flags", ifaceInfo.Flags})
for _, address := range ifaceInfo.Addresses {
if address != "" {
ip, _, err := net.ParseCIDR(address)
if err != nil {
continue
}
if ip.To4() != nil {
t.AppendRow(table.Row{"IPv4 Address", address})
} else {
t.AppendRow(table.Row{"IPv6 Address", address})
}
}
}
App.Println(t.Render())
}
return nil
},
})
App.AddCommand(&grumble.Command{
Name: "listener_list",
Help: "List currently running listeners",
Usage: "listener_list",
HelpGroup: "Listeners",
Run: func(c *grumble.Context) error {
t := table.NewWriter()
t.SetStyle(table.StyleLight)
t.SetTitle("Active listeners")
t.AppendHeader(table.Row{"#", "Agent", "Agent listener address", "Proxy redirect address"})
ListenerListMutex.Lock()
for id, listener := range ListenerList {
t.AppendRow(table.Row{id, listener.Agent.Name, listener.ListenerAddr, listener.RedirectAddr})
}
ListenerListMutex.Unlock()
c.App.Println(t.Render())
return nil
},
})
App.AddCommand(&grumble.Command{
Name: "listener_stop",
Help: "Stop a listener",
Usage: "listener_stop [id]",
HelpGroup: "Listeners",
Args: func(a *grumble.Args) {
a.Int("id", "listener id")
},
Run: func(c *grumble.Context) error {
ListenerListMutex.Lock()
if _, ok := ListenerList[c.Args.Int("id")]; !ok {
ListenerListMutex.Unlock()
return errors.New("invalid listener id")
}
listener := ListenerList[c.Args.Int("id")]
ListenerListMutex.Unlock()
listener.Session.Close()
yamuxConnectionSession, err := CurrentAgent.Session.Open()
if err != nil {
return err
}
protocolEncoder := protocol.NewEncoder(yamuxConnectionSession)
protocolDecoder := protocol.NewDecoder(yamuxConnectionSession)
// Send close request
closeRequest := protocol.ListenerCloseRequestPacket{ListenerID: listener.ListenerID}
if err := protocolEncoder.Encode(protocol.Envelope{
Type: protocol.MessageListenerCloseRequest,
Payload: closeRequest,
}); err != nil {
return err
}
// Process close response
if err := protocolDecoder.Decode(); err != nil {
return err
}
response := protocolDecoder.Envelope.Payload
if err := response.(protocol.ListenerCloseResponsePacket).Err; err != false {
return errors.New(response.(protocol.ListenerCloseResponsePacket).ErrString)
}
logrus.Info("Listener closed.")
// Delete from the Listener List
ListenerListMutex.Lock()
delete(ListenerList, c.Args.Int("id"))
ListenerListMutex.Unlock()
return nil
},
})
App.AddCommand(&grumble.Command{
Name: "listener_add",
Help: "Listen on the agent and redirect connections to the desired address",
Usage: "listener_add --addr [agent_listening_address:port] --to [local_listening_address:port] --tcp/--udp",
HelpGroup: "Listeners",
Flags: func(f *grumble.Flags) {
f.BoolL("tcp", false, "Use TCP listener")
f.BoolL("udp", false, "Use UDP listener")
f.StringL("addr", "", "The agent listening address:port")
f.StringL("to", "", "Where to redirect connections")
},
Run: func(c *grumble.Context) error {
if CurrentAgent.Session == nil {
return errors.New("please, select an agent using the session command")
}
var netProto string
if c.Flags.Bool("tcp") && c.Flags.Bool("udp") {
return errors.New("choose TCP or UDP, not both")
}
if c.Flags.Bool("tcp") {
netProto = "tcp"
}
if c.Flags.Bool("udp") {
netProto = "udp"
}
if netProto == "" {
netProto = "tcp" // Use TCP by default.
}
if c.Flags.String("to") == "" {
return errors.New("please, specify a valid redirect (to) IP address - expected format : ip:port")
}
// Check if specified IP is valid.
if _, _, err := net.SplitHostPort(c.Flags.String("to")); err != nil {
return err
}
if _, _, err := net.SplitHostPort(c.Flags.String("addr")); err != nil {
return err
}
// Open a new Yamux Session
yamuxConnectionSession, err := CurrentAgent.Session.Open()
if err != nil {
return err
}
protocolEncoder := protocol.NewEncoder(yamuxConnectionSession)
protocolDecoder := protocol.NewDecoder(yamuxConnectionSession)
// Request to open a new port on the agent
listenerPacket := protocol.ListenerRequestPacket{Address: c.Flags.String("addr"), Network: netProto}
if err := protocolEncoder.Encode(protocol.Envelope{
Type: protocol.MessageListenerRequest,
Payload: listenerPacket,
}); err != nil {
return err
}
// Get response from agent
if err := protocolDecoder.Decode(); err != nil {
return err
}
response := protocolDecoder.Envelope.Payload.(protocol.ListenerResponsePacket)
if err := response.Err; err != false {
return errors.New(response.ErrString)
}
logrus.Info("Listener created on remote agent!")
// Register the listener in the UI
listener := proxy.Listener{
Agent: CurrentAgent,
Network: netProto,
ListenerAddr: c.Flags.String("addr"),
RedirectAddr: c.Flags.String("to"),
Session: yamuxConnectionSession,
ListenerID: response.ListenerID,
}
ListenerListMutex.Lock()
ListenerList[proxy.ListenerCounter] = listener
ListenerListMutex.Unlock()
proxy.ListenerCounter++
go func() {
for {
// Wait for BindResponses
if err := protocolDecoder.Decode(); err != nil {
if err == io.EOF {
// Listener closed.
return
}
logrus.Error(err)
return
}
// We received a new BindResponse!
response := protocolDecoder.Envelope.Payload.(protocol.ListenerBindReponse)
if err := response.Err; err != false {
logrus.Error(response.ErrString)
return
}
logrus.Debugf("New socket opened : %d", response.SockID)
// relay connection
go func(sockID int32) {
forwarderSession, err := CurrentAgent.Session.Open()
if err != nil {
logrus.Error(err)
return
}
protocolEncoder := protocol.NewEncoder(forwarderSession)
protocolDecoder := protocol.NewDecoder(forwarderSession)
// Request socket access
socketRequestPacket := protocol.ListenerSockRequestPacket{SockID: sockID}
if err := protocolEncoder.Encode(protocol.Envelope{
Type: protocol.MessageListenerSockRequest,
Payload: socketRequestPacket,
}); err != nil {
logrus.Error(err)
return
}
if err := protocolDecoder.Decode(); err != nil {
logrus.Error(err)
return
}
response := protocolDecoder.Envelope.Payload
if err := response.(protocol.ListenerSockResponsePacket).Err; err != false {
logrus.Error(response.(protocol.ListenerSockResponsePacket).ErrString)
return
}
// Got socket access!
logrus.Debug("Listener relay established!")
// Dial the "to" target
lconn, err := net.Dial(netProto, c.Flags.String("to"))
if err != nil {
logrus.Error(err)
return
}
// relay connections
relay.StartRelay(lconn, forwarderSession)
}(response.SockID)
}
}()
return nil
},
})
}