-
-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathlua.go
More file actions
876 lines (733 loc) · 22.2 KB
/
lua.go
File metadata and controls
876 lines (733 loc) · 22.2 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
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
//go:build full || e2e
package main
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
log "github.com/sirupsen/logrus"
"github.com/tg123/sshpiper/libplugin"
lua "github.com/yuin/gopher-lua"
)
const (
luaModulePattern = "?.lua"
luaModuleInitPattern = "?/init.lua"
)
type luaPlugin struct {
ScriptPath string
SearchPath string
statePool *sync.Pool
sharedState *lua.LState
stateMu sync.Mutex
mu sync.RWMutex // protects script reloading
reloadMu sync.Mutex // prevents concurrent reloads
cancelFunc context.CancelFunc // for cleanup
}
func newLuaPlugin() *luaPlugin {
return &luaPlugin{}
}
// CreateConfig creates the SSH Piper plugin configuration
func (p *luaPlugin) CreateConfig() (*libplugin.SshPiperPluginConfig, error) {
// Validate the script exists
if _, err := os.Stat(p.ScriptPath); err != nil {
return nil, fmt.Errorf("lua script not found: %w", err)
}
// Prime a lua state so we can detect which callbacks exist before
// wiring them. This lets callbacks be truly optional.
prime, err := p.newStateWithScriptPath(p.ScriptPath)
if err != nil {
return nil, fmt.Errorf("failed to load lua script: %w", err)
}
// Discover which callback functions are present in the script.
checkFn := func(name string) bool {
if fn, ok := prime.GetGlobal(name).(*lua.LFunction); ok && fn != nil {
return true
}
return false
}
config := &libplugin.SshPiperPluginConfig{}
callbacks := []struct {
name string
assign func()
}{
{"sshpiper_on_noauth", func() { config.NoClientAuthCallback = p.handleNoAuth }},
{"sshpiper_on_password", func() { config.PasswordCallback = p.handlePassword }},
{"sshpiper_on_publickey", func() { config.PublicKeyCallback = p.handlePublicKey }},
{"sshpiper_on_keyboard_interactive", func() { config.KeyboardInteractiveCallback = p.handleKeyboardInteractive }},
{"sshpiper_on_new_connection", func() { config.NewConnectionCallback = p.handleNewConnection }},
{"sshpiper_on_next_auth_methods", func() { config.NextAuthMethodsCallback = p.handleNextAuthMethods }},
{"sshpiper_on_upstream_auth_failure", func() { config.UpstreamAuthFailureCallback = p.handleUpstreamAuthFailure }},
{"sshpiper_on_banner", func() { config.BannerCallback = p.handleBanner }},
{"sshpiper_on_verify_hostkey", func() { config.VerifyHostKeyCallback = p.handleVerifyHostKey }},
{"sshpiper_on_pipe_create_error", func() { config.PipeCreateErrorCallback = p.handlePipeCreateError }},
{"sshpiper_on_pipe_start", func() { config.PipeStartCallback = p.handlePipeStart }},
{"sshpiper_on_pipe_error", func() { config.PipeErrorCallback = p.handlePipeError }},
}
hasAnyCallback := false
names := make([]string, 0, len(callbacks))
for _, cb := range callbacks {
names = append(names, cb.name)
if checkFn(cb.name) {
hasAnyCallback = true
cb.assign()
}
}
// Ensure at least one callback is defined
if !hasAnyCallback {
prime.Close()
return nil, fmt.Errorf("no callbacks defined in Lua script (must define at least one of: %s)", strings.Join(names, ", "))
}
// Reuse the primed state so globals (counters, etc.) stay consistent
// across callbacks.
// Initialize state pool for reload paths and legacy callers.
p.initPool()
// Reuse the primed state so globals (counters, etc.) stay consistent
// across callbacks.
p.sharedState = prime
return config, nil
}
// getLuaState gets a Lua state from the pool
func (p *luaPlugin) getLuaState() (*lua.LState, error) {
p.stateMu.Lock()
if p.sharedState != nil {
return p.sharedState, nil
}
p.stateMu.Unlock()
v := p.statePool.Get()
if v == nil {
return nil, fmt.Errorf("failed to get Lua state from pool")
}
L, ok := v.(*lua.LState)
if !ok || L == nil {
return nil, fmt.Errorf("invalid Lua state in pool")
}
return L, nil
}
// putLuaState returns a Lua state to the pool
func (p *luaPlugin) putLuaState(L *lua.LState) {
if p.sharedState != nil {
p.stateMu.Unlock()
return
}
p.statePool.Put(L)
}
// redirectPrint redirects Lua print() to Go log.Info
func (p *luaPlugin) redirectPrint(L *lua.LState) {
L.SetGlobal("print", L.NewFunction(func(L *lua.LState) int {
top := L.GetTop()
str := ""
for i := 1; i <= top; i++ {
if i > 1 {
str += "\t"
}
str += L.CheckAny(i).String()
}
log.Info(str)
return 0
}))
}
// initPool initializes the Lua state pool with the New function
func (p *luaPlugin) initPool() {
p.statePool = &sync.Pool{
New: func() interface{} {
// Get current script path for state creation
p.mu.RLock()
scriptPath := p.ScriptPath
p.mu.RUnlock()
L, err := p.newStateWithScriptPath(scriptPath)
if err != nil {
log.Errorf("Failed to load lua script in pool: %v", err)
return nil
}
return L
},
}
}
// reloadScript reloads the Lua script by draining and repopulating the pool
func (p *luaPlugin) reloadScript() error {
p.reloadMu.Lock()
defer p.reloadMu.Unlock()
p.mu.Lock()
defer p.mu.Unlock()
// Validate the script still exists
if _, err := os.Stat(p.ScriptPath); err != nil {
return fmt.Errorf("lua script not found: %w", err)
}
// Test load the script to ensure it's valid before draining the pool
testState, err := p.newStateWithScriptPath(p.ScriptPath)
if err != nil {
return fmt.Errorf("failed to reload lua script: %w", err)
}
defer testState.Close()
// Drain the old pool by creating a new one
oldPool := p.statePool
p.initPool()
// Close all states in the old pool synchronously before returning
// This ensures old states aren't returned after reload
for {
v := oldPool.Get()
if v == nil {
break
}
if L, ok := v.(*lua.LState); ok && L != nil {
L.Close()
}
}
log.Info("Lua script reloaded successfully")
return nil
}
// injectLogFunction injects a logging function into the Lua environment
func (p *luaPlugin) injectLogFunction(L *lua.LState) {
logFn := L.NewFunction(func(L *lua.LState) int {
level := L.CheckString(1)
message := L.CheckString(2)
switch level {
case "debug":
log.Debug(message)
case "info":
log.Info(message)
case "warn":
log.Warn(message)
case "error":
log.Error(message)
default:
log.Info(message)
}
return 0
})
L.SetGlobal("sshpiper_log", logFn)
}
func (p *luaPlugin) setLuaSearchPath(L *lua.LState, scriptPath string) {
pkg, ok := L.GetGlobal("package").(*lua.LTable)
if !ok {
return
}
currentPath := ""
if cur, ok := pkg.RawGetString("path").(lua.LString); ok {
currentPath = string(cur)
}
var scriptPaths []string
var customPaths []string
if p.SearchPath != "" {
for _, entry := range strings.Split(p.SearchPath, ";") {
entry = strings.TrimSpace(entry)
if entry != "" {
entry = filepath.ToSlash(entry)
customPaths = append(customPaths, entry)
}
}
}
if scriptPath != "" {
dir := filepath.ToSlash(filepath.Dir(scriptPath))
scriptPaths = append(scriptPaths,
fmt.Sprintf("%s/%s", dir, luaModulePattern),
fmt.Sprintf("%s/%s", dir, luaModuleInitPattern),
)
}
if len(scriptPaths) == 0 && len(customPaths) == 0 {
return
}
allPaths := make([]string, 0, len(scriptPaths)+len(customPaths)+1)
// Prefer modules colocated with the script, then user-specified paths, then defaults.
allPaths = append(allPaths, scriptPaths...)
allPaths = append(allPaths, customPaths...)
if currentPath != "" {
allPaths = append(allPaths, currentPath)
}
pkg.RawSetString("path", lua.LString(strings.Join(allPaths, ";")))
}
// newStateWithScriptPath creates a fresh Lua state, applies search paths, wires logging, and loads the provided script.
func (p *luaPlugin) newStateWithScriptPath(scriptPath string) (*lua.LState, error) {
L := lua.NewState()
p.redirectPrint(L)
p.injectLogFunction(L)
p.setLuaSearchPath(L, scriptPath)
if err := L.DoFile(scriptPath); err != nil {
L.Close()
return nil, err
}
return L, nil
}
// createConnTable creates a Lua table with connection metadata
func (p *luaPlugin) createConnTable(L *lua.LState, conn libplugin.ConnMetadata) *lua.LTable {
connTable := L.NewTable()
L.SetField(connTable, "sshpiper_user", lua.LString(conn.User()))
L.SetField(connTable, "sshpiper_remote_addr", lua.LString(conn.RemoteAddr()))
L.SetField(connTable, "sshpiper_unique_id", lua.LString(conn.UniqueID()))
return connTable
}
func (p *luaPlugin) handleNewConnection(conn libplugin.ConnMetadata) error {
L, err := p.getLuaState()
if err != nil {
return err
}
defer p.putLuaState(L)
connTable := p.createConnTable(L, conn)
fn := L.GetGlobal("sshpiper_on_new_connection")
if fn == lua.LNil {
return fmt.Errorf("sshpiper_on_new_connection function not defined in Lua script")
}
if err := L.CallByParam(lua.P{
Fn: fn,
NRet: 1,
Protect: true,
}, connTable); err != nil {
return fmt.Errorf("lua error in sshpiper_on_new_connection: %w", err)
}
ret := L.Get(-1)
L.Pop(1)
if ret == lua.LNil {
return nil
}
switch v := ret.(type) {
case lua.LBool:
if bool(v) {
return nil
}
return fmt.Errorf("connection rejected")
case lua.LString:
msg := string(v)
if msg == "" {
msg = "connection rejected"
}
return errors.New(msg)
}
return fmt.Errorf("unexpected return type from sshpiper_on_new_connection: %s", ret.Type())
}
func (p *luaPlugin) handleNextAuthMethods(conn libplugin.ConnMetadata) ([]string, error) {
L, err := p.getLuaState()
if err != nil {
return nil, err
}
defer p.putLuaState(L)
connTable := p.createConnTable(L, conn)
fn := L.GetGlobal("sshpiper_on_next_auth_methods")
if fn == lua.LNil {
return nil, fmt.Errorf("sshpiper_on_next_auth_methods function not defined in Lua script")
}
if err := L.CallByParam(lua.P{
Fn: fn,
NRet: 1,
Protect: true,
}, connTable); err != nil {
return nil, fmt.Errorf("lua error in sshpiper_on_next_auth_methods: %w", err)
}
ret := L.Get(-1)
L.Pop(1)
tbl, ok := ret.(*lua.LTable)
if !ok {
return nil, fmt.Errorf("expected table return value, got %s", ret.Type())
}
var methods []string
for i := 1; ; i++ {
value := tbl.RawGetInt(i)
if value == lua.LNil {
break
}
v, ok := value.(lua.LString)
if !ok {
return nil, fmt.Errorf("expected auth method name as string, got %s", value.Type())
}
methods = append(methods, string(v))
}
return methods, nil
}
// handlePassword is called when a user tries to authenticate with a password
func (p *luaPlugin) handlePassword(conn libplugin.ConnMetadata, password []byte) (*libplugin.Upstream, error) {
L, err := p.getLuaState()
if err != nil {
return nil, err
}
defer p.putLuaState(L)
// Create a table with connection metadata
connTable := p.createConnTable(L, conn)
// Check if the function exists
fn := L.GetGlobal("sshpiper_on_password")
if fn == lua.LNil {
return nil, fmt.Errorf("sshpiper_on_password function not defined in Lua script")
}
// Call the sshpiper_on_password function
if err := L.CallByParam(lua.P{
Fn: fn,
NRet: 1,
Protect: true,
}, connTable, lua.LString(password)); err != nil {
return nil, fmt.Errorf("lua error in sshpiper_on_password: %w", err)
}
// Get the return value
ret := L.Get(-1)
L.Pop(1)
if ret == lua.LNil {
return nil, fmt.Errorf("authentication failed: no upstream returned")
}
upstream, err := p.parseUpstreamTable(L, ret, conn, password)
if err != nil {
return nil, err
}
log.Infof("routing user %s to %s", conn.User(), upstream.Uri)
return upstream, nil
}
// handlePublicKey is called when a user tries to authenticate with a public key
func (p *luaPlugin) handlePublicKey(conn libplugin.ConnMetadata, key []byte) (*libplugin.Upstream, error) {
L, err := p.getLuaState()
if err != nil {
return nil, err
}
defer p.putLuaState(L)
// Create a table with connection metadata
connTable := p.createConnTable(L, conn)
// Check if the function exists
fn := L.GetGlobal("sshpiper_on_publickey")
if fn == lua.LNil {
return nil, fmt.Errorf("sshpiper_on_publickey function not defined in Lua script")
}
// Call the sshpiper_on_publickey function
if err := L.CallByParam(lua.P{
Fn: fn,
NRet: 1,
Protect: true,
}, connTable, lua.LString(key)); err != nil {
return nil, fmt.Errorf("lua error in sshpiper_on_publickey: %w", err)
}
// Get the return value
ret := L.Get(-1)
L.Pop(1)
if ret == lua.LNil {
return nil, fmt.Errorf("authentication failed: no upstream returned")
}
upstream, err := p.parseUpstreamTable(L, ret, conn, nil)
if err != nil {
return nil, err
}
log.Infof("routing user %s to %s", conn.User(), upstream.Uri)
return upstream, nil
}
// parseUpstreamTable parses a Lua table into an Upstream struct
func (p *luaPlugin) parseUpstreamTable(L *lua.LState, value lua.LValue, conn libplugin.ConnMetadata, password []byte) (*libplugin.Upstream, error) {
table, ok := value.(*lua.LTable)
if !ok {
return nil, fmt.Errorf("expected table return value, got %s", value.Type())
}
// Extract host (required)
hostVal := L.GetField(table, "host")
if hostVal == lua.LNil {
return nil, fmt.Errorf("host field is required in upstream table")
}
hostStr, ok := hostVal.(lua.LString)
if !ok {
return nil, fmt.Errorf("host must be a string")
}
// Parse host:port and create URI
host, port, err := libplugin.SplitHostPortForSSH(string(hostStr))
if err != nil {
return nil, fmt.Errorf("invalid host:port format: %w", err)
}
// grpc plugin expects a URI with a transport scheme; default to tcp.
upstream := &libplugin.Upstream{
Uri: fmt.Sprintf("tcp://%s:%d", host, port),
IgnoreHostKey: false, // default to false for security
}
// Extract username (optional, defaults to connecting user)
usernameVal := L.GetField(table, "username")
if usernameVal != lua.LNil {
if username, ok := usernameVal.(lua.LString); ok {
upstream.UserName = string(username)
}
} else {
// Use the connecting user's username as default
upstream.UserName = conn.User()
}
// Extract ignore_hostkey (optional, defaults to false for security)
upstream.IgnoreHostKey = false // default - secure
ignoreHostKeyVal := L.GetField(table, "ignore_hostkey")
if ignoreHostKeyVal != lua.LNil {
if ignoreHostKey, ok := ignoreHostKeyVal.(lua.LBool); ok {
upstream.IgnoreHostKey = bool(ignoreHostKey)
}
}
// Handle authentication
privateKeyDataVal := L.GetField(table, "private_key_data")
if privateKeyDataVal != lua.LNil {
// Use private key authentication
if pkData, ok := privateKeyDataVal.(lua.LString); ok {
privateKeyData := []byte(pkData)
if len(privateKeyData) == 0 {
return nil, fmt.Errorf("private key data is empty")
}
upstream.Auth = libplugin.CreatePrivateKeyAuth(privateKeyData, nil)
} else {
return nil, fmt.Errorf("private_key_data must be a string")
}
} else {
// Use password authentication
passwordVal := L.GetField(table, "password")
if passwordVal != lua.LNil {
if pwd, ok := passwordVal.(lua.LString); ok {
upstream.Auth = libplugin.CreatePasswordAuth([]byte(pwd))
}
} else if password != nil {
// Use the original password
upstream.Auth = libplugin.CreatePasswordAuth(password)
} else {
return nil, fmt.Errorf("no authentication method specified")
}
}
return upstream, nil
}
// handleNoAuth is called when a user tries no authentication
func (p *luaPlugin) handleNoAuth(conn libplugin.ConnMetadata) (*libplugin.Upstream, error) {
L, err := p.getLuaState()
if err != nil {
return nil, err
}
if L != nil {
defer p.putLuaState(L)
}
// Create a table with connection metadata
connTable := p.createConnTable(L, conn)
// Check if the function exists
fn := L.GetGlobal("sshpiper_on_noauth")
if fn == lua.LNil {
return nil, fmt.Errorf("sshpiper_on_noauth function not defined in Lua script")
}
// Call the sshpiper_on_noauth function
if err := L.CallByParam(lua.P{
Fn: fn,
NRet: 1,
Protect: true,
}, connTable); err != nil {
return nil, fmt.Errorf("lua error in sshpiper_on_noauth: %w", err)
}
// Get the return value
ret := L.Get(-1)
L.Pop(1)
if ret == lua.LNil {
return nil, fmt.Errorf("authentication failed: no upstream returned")
}
upstream, err := p.parseUpstreamTable(L, ret, conn, nil)
if err != nil {
return nil, err
}
log.Infof("routing user %s to %s (noauth)", conn.User(), upstream.Uri)
return upstream, nil
}
// handleKeyboardInteractive is called when a user tries keyboard-interactive authentication
func (p *luaPlugin) handleKeyboardInteractive(conn libplugin.ConnMetadata, client libplugin.KeyboardInteractiveChallenge) (*libplugin.Upstream, error) {
L, err := p.getLuaState()
if err != nil {
return nil, err
}
defer p.putLuaState(L)
// Create a table with connection metadata
connTable := p.createConnTable(L, conn)
// Create a challenge function that can be called from Lua
challengeFn := L.NewFunction(func(L *lua.LState) int {
user := L.CheckString(1)
instruction := L.CheckString(2)
question := L.CheckString(3)
echo := L.CheckBool(4)
answer, err := client(user, instruction, question, echo)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
L.Push(lua.LString(answer))
L.Push(lua.LNil)
return 2
})
// Check if the function exists
fn := L.GetGlobal("sshpiper_on_keyboard_interactive")
if fn == lua.LNil {
return nil, fmt.Errorf("sshpiper_on_keyboard_interactive function not defined in Lua script")
}
// Call the sshpiper_on_keyboard_interactive function
if err := L.CallByParam(lua.P{
Fn: fn,
NRet: 1,
Protect: true,
}, connTable, challengeFn); err != nil {
return nil, fmt.Errorf("lua error in sshpiper_on_keyboard_interactive: %w", err)
}
// Get the return value
ret := L.Get(-1)
L.Pop(1)
if ret == lua.LNil {
return nil, fmt.Errorf("authentication failed: no upstream returned")
}
upstream, err := p.parseUpstreamTable(L, ret, conn, nil)
if err != nil {
return nil, err
}
log.Infof("routing user %s to %s (keyboard-interactive)", conn.User(), upstream.Uri)
return upstream, nil
}
func (p *luaPlugin) handleUpstreamAuthFailure(conn libplugin.ConnMetadata, method string, callbackErr error, allowmethods []string) {
L, err := p.getLuaState()
if err != nil {
log.Errorf("failed to get lua state: %v", err)
return
}
defer p.putLuaState(L)
connTable := p.createConnTable(L, conn)
allowedTable := L.NewTable()
for _, m := range allowmethods {
allowedTable.Append(lua.LString(m))
}
fn := L.GetGlobal("sshpiper_on_upstream_auth_failure")
if fn == lua.LNil {
log.Error("sshpiper_on_upstream_auth_failure function not defined in Lua script")
return
}
errMsg := ""
if callbackErr != nil {
errMsg = callbackErr.Error()
}
if err := L.CallByParam(lua.P{
Fn: fn,
NRet: 0,
Protect: true,
}, connTable, lua.LString(method), lua.LString(errMsg), allowedTable); err != nil {
log.Errorf("lua error in sshpiper_on_upstream_auth_failure: %v", err)
}
}
func (p *luaPlugin) handleBanner(conn libplugin.ConnMetadata) string {
L, err := p.getLuaState()
if err != nil {
log.Errorf("failed to get lua state: %v", err)
return ""
}
defer p.putLuaState(L)
connTable := p.createConnTable(L, conn)
fn := L.GetGlobal("sshpiper_on_banner")
if fn == lua.LNil {
log.Error("sshpiper_on_banner function not defined in Lua script")
return ""
}
if err := L.CallByParam(lua.P{
Fn: fn,
NRet: 1,
Protect: true,
}, connTable); err != nil {
log.Errorf("lua error in sshpiper_on_banner: %v", err)
return ""
}
ret := L.Get(-1)
L.Pop(1)
if ret == lua.LNil {
return ""
}
if v, ok := ret.(lua.LString); ok {
return string(v)
}
log.Errorf("unexpected return type from sshpiper_on_banner: %s", ret.Type())
return ""
}
func (p *luaPlugin) handleVerifyHostKey(conn libplugin.ConnMetadata, hostname, netaddr string, key []byte) error {
L, err := p.getLuaState()
if err != nil {
return err
}
defer p.putLuaState(L)
connTable := p.createConnTable(L, conn)
fn := L.GetGlobal("sshpiper_on_verify_hostkey")
if fn == lua.LNil {
return fmt.Errorf("sshpiper_on_verify_hostkey function not defined in Lua script")
}
if err := L.CallByParam(lua.P{
Fn: fn,
NRet: 2,
Protect: true,
}, connTable, lua.LString(hostname), lua.LString(netaddr), lua.LString(string(key))); err != nil {
return fmt.Errorf("lua error in sshpiper_on_verify_hostkey: %w", err)
}
result := L.Get(-2)
luaErr := L.Get(-1)
L.Pop(2)
if luaErr != lua.LNil {
if msg, ok := luaErr.(lua.LString); ok {
if msg == "" {
return fmt.Errorf("host key verification failed")
}
return errors.New(string(msg))
}
return fmt.Errorf("host key verification failed")
}
if v, ok := result.(lua.LBool); ok && bool(v) {
return nil
}
return fmt.Errorf("host key verification failed")
}
func (p *luaPlugin) handlePipeCreateError(remoteAddr string, callbackErr error) {
L, err := p.getLuaState()
if err != nil {
log.Errorf("failed to get lua state: %v", err)
return
}
defer p.putLuaState(L)
fn := L.GetGlobal("sshpiper_on_pipe_create_error")
if fn == lua.LNil {
log.Error("sshpiper_on_pipe_create_error function not defined in Lua script")
return
}
errMsg := ""
if callbackErr != nil {
errMsg = callbackErr.Error()
}
if err := L.CallByParam(lua.P{
Fn: fn,
NRet: 0,
Protect: true,
}, lua.LString(remoteAddr), lua.LString(errMsg)); err != nil {
log.Errorf("lua error in sshpiper_on_pipe_create_error: %v", err)
}
}
func (p *luaPlugin) handlePipeStart(conn libplugin.ConnMetadata) {
L, err := p.getLuaState()
if err != nil {
log.Errorf("failed to get lua state: %v", err)
return
}
defer p.putLuaState(L)
connTable := p.createConnTable(L, conn)
fn := L.GetGlobal("sshpiper_on_pipe_start")
if fn == lua.LNil {
log.Error("sshpiper_on_pipe_start function not defined in Lua script")
return
}
if err := L.CallByParam(lua.P{
Fn: fn,
NRet: 0,
Protect: true,
}, connTable); err != nil {
log.Errorf("lua error in sshpiper_on_pipe_start: %v", err)
}
}
func (p *luaPlugin) handlePipeError(conn libplugin.ConnMetadata, callbackErr error) {
L, err := p.getLuaState()
if err != nil {
log.Errorf("failed to get lua state: %v", err)
return
}
defer p.putLuaState(L)
connTable := p.createConnTable(L, conn)
fn := L.GetGlobal("sshpiper_on_pipe_error")
if fn == lua.LNil {
log.Error("sshpiper_on_pipe_error function not defined in Lua script")
return
}
errMsg := ""
if callbackErr != nil {
errMsg = callbackErr.Error()
}
if err := L.CallByParam(lua.P{
Fn: fn,
NRet: 0,
Protect: true,
}, connTable, lua.LString(errMsg)); err != nil {
log.Errorf("lua error in sshpiper_on_pipe_error: %v", err)
}
}