Debian Codegraph @

ssh.go

raw
1 package nebula
2
3 import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "flag"
8 "fmt"
9 "log/slog"
10 "maps"
11 "net"
12 "net/netip"
13 "os"
14 "path/filepath"
15 "runtime"
16 "runtime/pprof"
17 "sort"
18 "strconv"
19 "strings"
20
21 "github.com/slackhq/nebula/config"
22 "github.com/slackhq/nebula/header"
23 "github.com/slackhq/nebula/logging"
24 "github.com/slackhq/nebula/sshd"
25 )
26
27 type sshListHostMapFlags struct {
28 Json bool
29 Pretty bool
30 ByIndex bool
31 }
32
33 type sshPrintCertFlags struct {
34 Json bool
35 Pretty bool
36 Raw bool
37 }
38
39 type sshPrintTunnelFlags struct {
40 Pretty bool
41 }
42
43 type sshChangeRemoteFlags struct {
44 Address string
45 }
46
47 type sshCloseTunnelFlags struct {
48 LocalOnly bool
49 }
50
51 type sshCreateTunnelFlags struct {
52 Address string
53 }
54
55 type sshDeviceInfoFlags struct {
56 Json bool
57 Pretty bool
58 }
59
60 func wireSSHReload(l *slog.Logger, ssh *sshd.SSHServer, c *config.C) {
61 c.RegisterReloadCallback(func(c *config.C) {
62 if c.GetBool("sshd.enabled", false) {
63 sshRun, err := configSSH(l, ssh, c)
64 if err != nil {
65 l.Error("Failed to reconfigure the sshd", "error", err)
66 ssh.Stop()
67 }
68 if sshRun != nil {
69 go sshRun()
70 }
71 } else {
72 ssh.Stop()
73 }
74 })
75 }
76
77 // configSSH reads the ssh info out of the passed-in Config and
78 // updates the passed-in SSHServer. On success, it returns a function
79 // that callers may invoke to run the configured ssh server. On
80 // failure, it returns nil, error.
81 func configSSH(l *slog.Logger, ssh *sshd.SSHServer, c *config.C) (func(), error) {
82 listen := c.GetString("sshd.listen", "")
83 if listen == "" {
84 return nil, fmt.Errorf("sshd.listen must be provided")
85 }
86
87 _, port, err := net.SplitHostPort(listen)
88 if err != nil {
89 return nil, fmt.Errorf("invalid sshd.listen address: %s", err)
90 }
91 if port == "22" {
92 return nil, fmt.Errorf("sshd.listen can not use port 22")
93 }
94
95 hostKeyPathOrKey := c.GetString("sshd.host_key", "")
96 if hostKeyPathOrKey == "" {
97 return nil, fmt.Errorf("sshd.host_key must be provided")
98 }
99
100 var hostKeyBytes []byte
101 if strings.Contains(hostKeyPathOrKey, "-----BEGIN") {
102 hostKeyBytes = []byte(hostKeyPathOrKey)
103 } else {
104 hostKeyBytes, err = os.ReadFile(hostKeyPathOrKey)
105 if err != nil {
106 return nil, fmt.Errorf("error while loading sshd.host_key file: %s", err)
107 }
108 }
109
110 err = ssh.SetHostKey(hostKeyBytes)
111 if err != nil {
112 return nil, fmt.Errorf("error while adding sshd.host_key: %s", err)
113 }
114
115 // Clear existing trusted CAs and authorized keys
116 ssh.ClearTrustedCAs()
117 ssh.ClearAuthorizedKeys()
118
119 rawCAs := c.GetStringSlice("sshd.trusted_cas", []string{})
120 for _, caAuthorizedKey := range rawCAs {
121 err := ssh.AddTrustedCA(caAuthorizedKey)
122 if err != nil {
123 l.Warn("SSH CA had an error, ignoring", "error", err, "sshCA", caAuthorizedKey)
124 continue
125 }
126 }
127
128 rawKeys := c.Get("sshd.authorized_users")
129 keys, ok := rawKeys.([]any)
130 if ok {
131 for _, rk := range keys {
132 kDef, ok := rk.(map[string]any)
133 if !ok {
134 l.Warn("Authorized user had an error, ignoring", "sshKeyConfig", rk)
135 continue
136 }
137
138 user, ok := kDef["user"].(string)
139 if !ok {
140 l.Warn("Authorized user is missing the user field", "sshKeyConfig", rk)
141 continue
142 }
143
144 k := kDef["keys"]
145 switch v := k.(type) {
146 case string:
147 err := ssh.AddAuthorizedKey(user, v)
148 if err != nil {
149 l.Warn("Failed to authorize key",
150 "error", err,
151 "sshKeyConfig", rk,
152 "sshKey", v,
153 )
154 continue
155 }
156
157 case []any:
158 for _, subK := range v {
159 sk, ok := subK.(string)
160 if !ok {
161 l.Warn("Did not understand ssh key",
162 "sshKeyConfig", rk,
163 "sshKey", subK,
164 )
165 continue
166 }
167
168 err := ssh.AddAuthorizedKey(user, sk)
169 if err != nil {
170 l.Warn("Failed to authorize key",
171 "error", err,
172 "sshKeyConfig", sk,
173 )
174 continue
175 }
176 }
177
178 default:
179 l.Warn("Authorized user is missing the keys field or was not understood", "sshKeyConfig", rk)
180 }
181 }
182 } else {
183 l.Info("no ssh users to authorize")
184 }
185
186 var runner func()
187 if c.GetBool("sshd.enabled", false) {
188 ssh.Stop()
189 runner = func() {
190 if err := ssh.Run(listen); err != nil {
191 l.Warn("Failed to run the SSH server", "error", err)
192 }
193 }
194 } else {
195 ssh.Stop()
196 }
197
198 return runner, nil
199 }
200
201 func attachCommands(l *slog.Logger, c *config.C, ssh *sshd.SSHServer, f *Interface) {
202 // sandboxDir defaults to a dir in temp. The intention is that end user will
203 // create this dir as needed. Overriding this config value to "" allows
204 // writing to anywhere in the system.
205 defaultDir := filepath.Join(os.TempDir(), "nebula-debug")
206 sandboxDir := c.GetString("sshd.sandbox_dir", defaultDir)
207
208 ssh.RegisterCommand(&sshd.Command{
209 Name: "list-hostmap",
210 ShortDescription: "List all known previously connected hosts",
211 Flags: func() (*flag.FlagSet, any) {
212 fl := flag.NewFlagSet("", flag.ContinueOnError)
213 s := sshListHostMapFlags{}
214 fl.BoolVar(&s.Json, "json", false, "outputs as json with more information")
215 fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
216 fl.BoolVar(&s.ByIndex, "by-index", false, "gets all hosts in the hostmap from the index table")
217 return fl, &s
218 },
219 Callback: func(fs any, a []string, w sshd.StringWriter) error {
220 return sshListHostMap(f.hostMap, fs, w)
221 },
222 })
223
224 ssh.RegisterCommand(&sshd.Command{
225 Name: "list-pending-hostmap",
226 ShortDescription: "List all handshaking hosts",
227 Flags: func() (*flag.FlagSet, any) {
228 fl := flag.NewFlagSet("", flag.ContinueOnError)
229 s := sshListHostMapFlags{}
230 fl.BoolVar(&s.Json, "json", false, "outputs as json with more information")
231 fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
232 fl.BoolVar(&s.ByIndex, "by-index", false, "gets all hosts in the hostmap from the index table")
233 return fl, &s
234 },
235 Callback: func(fs any, a []string, w sshd.StringWriter) error {
236 return sshListHostMap(f.handshakeManager, fs, w)
237 },
238 })
239
240 ssh.RegisterCommand(&sshd.Command{
241 Name: "list-lighthouse-addrmap",
242 ShortDescription: "List all lighthouse map entries",
243 Flags: func() (*flag.FlagSet, any) {
244 fl := flag.NewFlagSet("", flag.ContinueOnError)
245 s := sshListHostMapFlags{}
246 fl.BoolVar(&s.Json, "json", false, "outputs as json with more information")
247 fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
248 return fl, &s
249 },
250 Callback: func(fs any, a []string, w sshd.StringWriter) error {
251 return sshListLighthouseMap(f.lightHouse, fs, w)
252 },
253 })
254
255 ssh.RegisterCommand(&sshd.Command{
256 Name: "reload",
257 ShortDescription: "Reloads configuration from disk, same as sending HUP to the process",
258 Callback: func(fs any, a []string, w sshd.StringWriter) error {
259 return sshReload(c, w)
260 },
261 })
262
263 ssh.RegisterCommand(&sshd.Command{
264 Name: "start-cpu-profile",
265 ShortDescription: "Starts a cpu profile and write output to the provided file, ex: `cpu-profile.pb.gz`",
266 Callback: func(fs any, a []string, w sshd.StringWriter) error {
267 return sshStartCpuProfile(sandboxDir, fs, a, w)
268 },
269 })
270
271 ssh.RegisterCommand(&sshd.Command{
272 Name: "stop-cpu-profile",
273 ShortDescription: "Stops a cpu profile and writes output to the previously provided file",
274 Callback: func(fs any, a []string, w sshd.StringWriter) error {
275 pprof.StopCPUProfile()
276 return w.WriteLine("If a CPU profile was running it is now stopped")
277 },
278 })
279
280 ssh.RegisterCommand(&sshd.Command{
281 Name: "save-heap-profile",
282 ShortDescription: "Saves a heap profile to the provided path, ex: `heap-profile.pb.gz`",
283 Callback: func(fs any, a []string, w sshd.StringWriter) error {
284 return sshGetHeapProfile(sandboxDir, fs, a, w)
285 },
286 })
287
288 ssh.RegisterCommand(&sshd.Command{
289 Name: "mutex-profile-fraction",
290 ShortDescription: "Gets or sets runtime.SetMutexProfileFraction",
291 Callback: sshMutexProfileFraction,
292 })
293
294 ssh.RegisterCommand(&sshd.Command{
295 Name: "save-mutex-profile",
296 ShortDescription: "Saves a mutex profile to the provided path, ex: `mutex-profile.pb.gz`",
297 Callback: func(fs any, a []string, w sshd.StringWriter) error {
298 return sshGetMutexProfile(sandboxDir, fs, a, w)
299 },
300 })
301
302 ssh.RegisterCommand(&sshd.Command{
303 Name: "log-level",
304 ShortDescription: "Gets or sets the current log level",
305 Callback: func(fs any, a []string, w sshd.StringWriter) error {
306 return sshLogLevel(l, fs, a, w)
307 },
308 })
309
310 ssh.RegisterCommand(&sshd.Command{
311 Name: "log-format",
312 ShortDescription: "Gets or sets the current log format",
313 Callback: func(fs any, a []string, w sshd.StringWriter) error {
314 return sshLogFormat(l, fs, a, w)
315 },
316 })
317
318 ssh.RegisterCommand(&sshd.Command{
319 Name: "version",
320 ShortDescription: "Prints the currently running version of nebula",
321 Callback: func(fs any, a []string, w sshd.StringWriter) error {
322 return sshVersion(f, fs, a, w)
323 },
324 })
325
326 ssh.RegisterCommand(&sshd.Command{
327 Name: "device-info",
328 ShortDescription: "Prints information about the network device.",
329 Flags: func() (*flag.FlagSet, any) {
330 fl := flag.NewFlagSet("", flag.ContinueOnError)
331 s := sshDeviceInfoFlags{}
332 fl.BoolVar(&s.Json, "json", false, "outputs as json with more information")
333 fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
334 return fl, &s
335 },
336 Callback: func(fs any, a []string, w sshd.StringWriter) error {
337 return sshDeviceInfo(f, fs, w)
338 },
339 })
340
341 ssh.RegisterCommand(&sshd.Command{
342 Name: "print-cert",
343 ShortDescription: "Prints the current certificate being used or the certificate for the provided vpn addr",
344 Flags: func() (*flag.FlagSet, any) {
345 fl := flag.NewFlagSet("", flag.ContinueOnError)
346 s := sshPrintCertFlags{}
347 fl.BoolVar(&s.Json, "json", false, "outputs as json")
348 fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
349 fl.BoolVar(&s.Raw, "raw", false, "raw prints the PEM encoded certificate, not compatible with -json or -pretty")
350 return fl, &s
351 },
352 Callback: func(fs any, a []string, w sshd.StringWriter) error {
353 return sshPrintCert(f, fs, a, w)
354 },
355 })
356
357 ssh.RegisterCommand(&sshd.Command{
358 Name: "print-tunnel",
359 ShortDescription: "Prints json details about a tunnel for the provided vpn addr",
360 Flags: func() (*flag.FlagSet, any) {
361 fl := flag.NewFlagSet("", flag.ContinueOnError)
362 s := sshPrintTunnelFlags{}
363 fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json")
364 return fl, &s
365 },
366 Callback: func(fs any, a []string, w sshd.StringWriter) error {
367 return sshPrintTunnel(f, fs, a, w)
368 },
369 })
370
371 ssh.RegisterCommand(&sshd.Command{
372 Name: "print-relays",
373 ShortDescription: "Prints json details about all relay info",
374 Flags: func() (*flag.FlagSet, any) {
375 fl := flag.NewFlagSet("", flag.ContinueOnError)
376 s := sshPrintTunnelFlags{}
377 fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json")
378 return fl, &s
379 },
380 Callback: func(fs any, a []string, w sshd.StringWriter) error {
381 return sshPrintRelays(f, fs, a, w)
382 },
383 })
384
385 ssh.RegisterCommand(&sshd.Command{
386 Name: "change-remote",
387 ShortDescription: "Changes the remote address used in the tunnel for the provided vpn addr",
388 Flags: func() (*flag.FlagSet, any) {
389 fl := flag.NewFlagSet("", flag.ContinueOnError)
390 s := sshChangeRemoteFlags{}
391 fl.StringVar(&s.Address, "address", "", "The new remote address, ip:port")
392 return fl, &s
393 },
394 Callback: func(fs any, a []string, w sshd.StringWriter) error {
395 return sshChangeRemote(f, fs, a, w)
396 },
397 })
398
399 ssh.RegisterCommand(&sshd.Command{
400 Name: "close-tunnel",
401 ShortDescription: "Closes a tunnel for the provided vpn addr",
402 Flags: func() (*flag.FlagSet, any) {
403 fl := flag.NewFlagSet("", flag.ContinueOnError)
404 s := sshCloseTunnelFlags{}
405 fl.BoolVar(&s.LocalOnly, "local-only", false, "Disables notifying the remote that the tunnel is shutting down")
406 return fl, &s
407 },
408 Callback: func(fs any, a []string, w sshd.StringWriter) error {
409 return sshCloseTunnel(f, fs, a, w)
410 },
411 })
412
413 ssh.RegisterCommand(&sshd.Command{
414 Name: "create-tunnel",
415 ShortDescription: "Creates a tunnel for the provided vpn address",
416 Help: "The lighthouses will be queried for real addresses but you can provide one as well.",
417 Flags: func() (*flag.FlagSet, any) {
418 fl := flag.NewFlagSet("", flag.ContinueOnError)
419 s := sshCreateTunnelFlags{}
420 fl.StringVar(&s.Address, "address", "", "Optionally provide a real remote address, ip:port ")
421 return fl, &s
422 },
423 Callback: func(fs any, a []string, w sshd.StringWriter) error {
424 return sshCreateTunnel(f, fs, a, w)
425 },
426 })
427
428 ssh.RegisterCommand(&sshd.Command{
429 Name: "query-lighthouse",
430 ShortDescription: "Query the lighthouses for the provided vpn address",
431 Help: "This command is asynchronous. Only currently known udp addresses will be printed.",
432 Callback: func(fs any, a []string, w sshd.StringWriter) error {
433 return sshQueryLighthouse(f, fs, a, w)
434 },
435 })
436 }
437
438 func sshListHostMap(hl controlHostLister, a any, w sshd.StringWriter) error {
439 fs, ok := a.(*sshListHostMapFlags)
440 if !ok {
441 return nil
442 }
443
444 var hm []ControlHostInfo
445 if fs.ByIndex {
446 hm = listHostMapIndexes(hl)
447 } else {
448 hm = listHostMapHosts(hl)
449 }
450
451 sort.Slice(hm, func(i, j int) bool {
452 return hm[i].VpnAddrs[0].Compare(hm[j].VpnAddrs[0]) < 0
453 })
454
455 if fs.Json || fs.Pretty {
456 js := json.NewEncoder(w.GetWriter())
457 if fs.Pretty {
458 js.SetIndent("", " ")
459 }
460
461 err := js.Encode(hm)
462 if err != nil {
463 return nil
464 }
465
466 } else {
467 for _, v := range hm {
468 err := w.WriteLine(fmt.Sprintf("%s: %s", v.VpnAddrs, v.RemoteAddrs))
469 if err != nil {
470 return err
471 }
472 }
473 }
474
475 return nil
476 }
477
478 func sshListLighthouseMap(lightHouse *LightHouse, a any, w sshd.StringWriter) error {
479 fs, ok := a.(*sshListHostMapFlags)
480 if !ok {
481 return nil
482 }
483
484 type lighthouseInfo struct {
485 VpnAddr string `json:"vpnAddr"`
486 Addrs *CacheMap `json:"addrs"`
487 }
488
489 lightHouse.RLock()
490 addrMap := make([]lighthouseInfo, len(lightHouse.addrMap))
491 x := 0
492 for k, v := range lightHouse.addrMap {
493 addrMap[x] = lighthouseInfo{
494 VpnAddr: k.String(),
495 Addrs: v.CopyCache(),
496 }
497 x++
498 }
499 lightHouse.RUnlock()
500
501 sort.Slice(addrMap, func(i, j int) bool {
502 return strings.Compare(addrMap[i].VpnAddr, addrMap[j].VpnAddr) < 0
503 })
504
505 if fs.Json || fs.Pretty {
506 js := json.NewEncoder(w.GetWriter())
507 if fs.Pretty {
508 js.SetIndent("", " ")
509 }
510
511 err := js.Encode(addrMap)
512 if err != nil {
513 return nil
514 }
515
516 } else {
517 for _, v := range addrMap {
518 b, err := json.Marshal(v.Addrs)
519 if err != nil {
520 return err
521 }
522 err = w.WriteLine(fmt.Sprintf("%s: %s", v.VpnAddr, string(b)))
523 if err != nil {
524 return err
525 }
526 }
527 }
528
529 return nil
530 }
531
532 // sshSanitizeFilePath validates that the given file path is within the sandbox directory.
533 // If sandboxDir is empty, the path is returned as-is for backwards compatibility.
534 func sshSanitizeFilePath(sandboxDir, filePath string) (string, error) {
535 if sandboxDir == "" {
536 return filePath, nil
537 }
538
539 // Clean and resolve the path relative to the sandbox directory
540 if !filepath.IsAbs(filePath) {
541 filePath = filepath.Join(sandboxDir, filePath)
542 }
543 cleaned := filepath.Clean(filePath)
544
545 // Ensure the resolved path is within the sandbox directory
546 cleanedSandbox := filepath.Clean(sandboxDir)
547 if cleaned == cleanedSandbox {
548 return "", fmt.Errorf("path %q resolves to the sandbox directory itself %q", filePath, sandboxDir)
549 }
550 if !strings.HasPrefix(cleaned, cleanedSandbox+string(filepath.Separator)) {
551 return "", fmt.Errorf("path %q is outside the sandbox directory %q", filePath, sandboxDir)
552 }
553
554 return cleaned, nil
555 }
556
557 func sshStartCpuProfile(sandboxDir string, fs any, a []string, w sshd.StringWriter) error {
558 if len(a) == 0 {
559 err := w.WriteLine("No path to write profile provided")
560 return err
561 }
562
563 filePath, err := sshSanitizeFilePath(sandboxDir, a[0])
564 if err != nil {
565 return w.WriteLine(err.Error())
566 }
567
568 file, err := os.Create(filePath)
569 if err != nil {
570 err = w.WriteLine(fmt.Sprintf("Unable to create profile file: %s", err))
571 return err
572 }
573
574 err = pprof.StartCPUProfile(file)
575 if err != nil {
576 err = w.WriteLine(fmt.Sprintf("Unable to start cpu profile: %s", err))
577 return err
578 }
579
580 err = w.WriteLine(fmt.Sprintf("Started cpu profile, issue stop-cpu-profile to write the output to %s", a))
581 return err
582 }
583
584 func sshVersion(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
585 return w.WriteLine(fmt.Sprintf("%s", ifce.version))
586 }
587
588 func sshQueryLighthouse(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
589 if len(a) == 0 {
590 return w.WriteLine("No vpn address was provided")
591 }
592
593 vpnAddr, err := netip.ParseAddr(a[0])
594 if err != nil {
595 return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
596 }
597
598 if !vpnAddr.IsValid() {
599 return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
600 }
601
602 var cm *CacheMap
603 rl := ifce.lightHouse.Query(vpnAddr)
604 if rl != nil {
605 cm = rl.CopyCache()
606 }
607 return json.NewEncoder(w.GetWriter()).Encode(cm)
608 }
609
610 func sshCloseTunnel(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
611 flags, ok := fs.(*sshCloseTunnelFlags)
612 if !ok {
613 return nil
614 }
615
616 if len(a) == 0 {
617 return w.WriteLine("No vpn address was provided")
618 }
619
620 vpnAddr, err := netip.ParseAddr(a[0])
621 if err != nil {
622 return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
623 }
624
625 if !vpnAddr.IsValid() {
626 return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
627 }
628
629 hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
630 if hostInfo == nil {
631 return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn address: %v", a[0]))
632 }
633
634 if !flags.LocalOnly {
635 ifce.send(
636 header.CloseTunnel,
637 0,
638 hostInfo.ConnectionState,
639 hostInfo,
640 []byte{},
641 make([]byte, 12, 12),
642 make([]byte, mtu),
643 )
644 }
645
646 ifce.closeTunnel(hostInfo)
647 return w.WriteLine("Closed")
648 }
649
650 func sshCreateTunnel(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
651 flags, ok := fs.(*sshCreateTunnelFlags)
652 if !ok {
653 return nil
654 }
655
656 if len(a) == 0 {
657 return w.WriteLine("No vpn address was provided")
658 }
659
660 vpnAddr, err := netip.ParseAddr(a[0])
661 if err != nil {
662 return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
663 }
664
665 if !vpnAddr.IsValid() {
666 return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
667 }
668
669 hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
670 if hostInfo != nil {
671 return w.WriteLine(fmt.Sprintf("Tunnel already exists"))
672 }
673
674 hostInfo = ifce.handshakeManager.QueryVpnAddr(vpnAddr)
675 if hostInfo != nil {
676 return w.WriteLine(fmt.Sprintf("Tunnel already handshaking"))
677 }
678
679 var addr netip.AddrPort
680 if flags.Address != "" {
681 addr, err = netip.ParseAddrPort(flags.Address)
682 if err != nil {
683 return w.WriteLine("Address could not be parsed")
684 }
685 }
686
687 hostInfo = ifce.handshakeManager.StartHandshake(vpnAddr, nil)
688 if addr.IsValid() {
689 hostInfo.SetRemote(addr)
690 }
691
692 return w.WriteLine("Created")
693 }
694
695 func sshChangeRemote(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
696 flags, ok := fs.(*sshChangeRemoteFlags)
697 if !ok {
698 return nil
699 }
700
701 if len(a) == 0 {
702 return w.WriteLine("No vpn address was provided")
703 }
704
705 if flags.Address == "" {
706 return w.WriteLine("No address was provided")
707 }
708
709 addr, err := netip.ParseAddrPort(flags.Address)
710 if err != nil {
711 return w.WriteLine("Address could not be parsed")
712 }
713
714 vpnAddr, err := netip.ParseAddr(a[0])
715 if err != nil {
716 return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
717 }
718
719 if !vpnAddr.IsValid() {
720 return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
721 }
722
723 hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
724 if hostInfo == nil {
725 return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn address: %v", a[0]))
726 }
727
728 hostInfo.SetRemote(addr)
729 return w.WriteLine("Changed")
730 }
731
732 func sshGetHeapProfile(sandboxDir string, fs any, a []string, w sshd.StringWriter) error {
733 if len(a) == 0 {
734 return w.WriteLine("No path to write profile provided")
735 }
736
737 filePath, err := sshSanitizeFilePath(sandboxDir, a[0])
738 if err != nil {
739 return w.WriteLine(err.Error())
740 }
741
742 file, err := os.Create(filePath)
743 if err != nil {
744 err = w.WriteLine(fmt.Sprintf("Unable to create profile file: %s", err))
745 return err
746 }
747
748 err = pprof.WriteHeapProfile(file)
749 if err != nil {
750 err = w.WriteLine(fmt.Sprintf("Unable to write profile: %s", err))
751 return err
752 }
753
754 err = w.WriteLine(fmt.Sprintf("Mem profile created at %s", a))
755 return err
756 }
757
758 func sshMutexProfileFraction(fs any, a []string, w sshd.StringWriter) error {
759 if len(a) == 0 {
760 rate := runtime.SetMutexProfileFraction(-1)
761 return w.WriteLine(fmt.Sprintf("Current value: %d", rate))
762 }
763
764 newRate, err := strconv.Atoi(a[0])
765 if err != nil {
766 return w.WriteLine(fmt.Sprintf("Invalid argument: %s", a[0]))
767 }
768
769 oldRate := runtime.SetMutexProfileFraction(newRate)
770 return w.WriteLine(fmt.Sprintf("New value: %d. Old value: %d", newRate, oldRate))
771 }
772
773 func sshGetMutexProfile(sandboxDir string, fs any, a []string, w sshd.StringWriter) error {
774 if len(a) == 0 {
775 return w.WriteLine("No path to write profile provided")
776 }
777
778 filePath, err := sshSanitizeFilePath(sandboxDir, a[0])
779 if err != nil {
780 return w.WriteLine(err.Error())
781 }
782
783 file, err := os.Create(filePath)
784 if err != nil {
785 return w.WriteLine(fmt.Sprintf("Unable to create profile file: %s", err))
786 }
787 defer file.Close()
788
789 mutexProfile := pprof.Lookup("mutex")
790 if mutexProfile == nil {
791 return w.WriteLine("Unable to get pprof.Lookup(\"mutex\")")
792 }
793
794 err = mutexProfile.WriteTo(file, 0)
795 if err != nil {
796 return w.WriteLine(fmt.Sprintf("Unable to write profile: %s", err))
797 }
798
799 return w.WriteLine(fmt.Sprintf("Mutex profile created at %s", a))
800 }
801
802 func sshLogLevel(l *slog.Logger, fs any, a []string, w sshd.StringWriter) error {
803 ctrl, ok := l.Handler().(interface {
804 GetLevel() slog.Level
805 SetLevel(slog.Level)
806 })
807 if !ok {
808 return w.WriteLine("Log level is not reconfigurable on this logger")
809 }
810
811 if len(a) == 0 {
812 return w.WriteLine(fmt.Sprintf("Log level is: %s", logging.LevelName(ctrl.GetLevel())))
813 }
814
815 level, err := logging.ParseLevel(strings.ToLower(a[0]))
816 if err != nil {
817 return w.WriteLine(fmt.Sprintf("Unknown log level %s. Possible log levels: trace, debug, info, warn, error", a))
818 }
819
820 ctrl.SetLevel(level)
821 return w.WriteLine(fmt.Sprintf("Log level is: %s", logging.LevelName(ctrl.GetLevel())))
822 }
823
824 func sshLogFormat(l *slog.Logger, fs any, a []string, w sshd.StringWriter) error {
825 ctrl, ok := l.Handler().(interface {
826 GetFormat() string
827 SetFormat(string) error
828 })
829 if !ok {
830 return w.WriteLine("Log format is not reconfigurable on this logger")
831 }
832
833 if len(a) == 0 {
834 return w.WriteLine(fmt.Sprintf("Log format is: %s", ctrl.GetFormat()))
835 }
836
837 if err := ctrl.SetFormat(strings.ToLower(a[0])); err != nil {
838 return err
839 }
840 return w.WriteLine(fmt.Sprintf("Log format is: %s", ctrl.GetFormat()))
841 }
842
843 func sshPrintCert(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
844 args, ok := fs.(*sshPrintCertFlags)
845 if !ok {
846 return nil
847 }
848
849 cert := ifce.pki.getCertState().GetDefaultCertificate()
850 if len(a) > 0 {
851 vpnAddr, err := netip.ParseAddr(a[0])
852 if err != nil {
853 return w.WriteLine(fmt.Sprintf("The provided vpn addr could not be parsed: %s", a[0]))
854 }
855
856 if !vpnAddr.IsValid() {
857 return w.WriteLine(fmt.Sprintf("The provided vpn addr could not be parsed: %s", a[0]))
858 }
859
860 hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
861 if hostInfo == nil {
862 return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn addr: %v", a[0]))
863 }
864
865 cert = hostInfo.GetCert().Certificate
866 }
867
868 if args.Json || args.Pretty {
869 b, err := cert.MarshalJSON()
870 if err != nil {
871 return nil
872 }
873
874 if args.Pretty {
875 buf := new(bytes.Buffer)
876 err := json.Indent(buf, b, "", " ")
877 b = buf.Bytes()
878 if err != nil {
879 return nil
880 }
881 }
882
883 return w.WriteBytes(b)
884 }
885
886 if args.Raw {
887 b, err := cert.MarshalPEM()
888 if err != nil {
889 return nil
890 }
891
892 return w.WriteBytes(b)
893 }
894
895 return w.WriteLine(cert.String())
896 }
897
898 func sshPrintRelays(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
899 args, ok := fs.(*sshPrintTunnelFlags)
900 if !ok {
901 w.WriteLine(fmt.Sprintf("sshPrintRelays failed to convert args type"))
902 return nil
903 }
904
905 relays := map[uint32]*HostInfo{}
906 ifce.hostMap.Lock()
907 maps.Copy(relays, ifce.hostMap.Relays)
908 ifce.hostMap.Unlock()
909
910 type RelayFor struct {
911 Error error
912 Type string
913 State string
914 PeerAddr netip.Addr
915 LocalIndex uint32
916 RemoteIndex uint32
917 RelayedThrough []netip.Addr
918 }
919
920 type RelayOutput struct {
921 NebulaAddr netip.Addr
922 RelayForAddrs []RelayFor
923 }
924
925 type CmdOutput struct {
926 Relays []*RelayOutput
927 }
928
929 co := CmdOutput{}
930
931 enc := json.NewEncoder(w.GetWriter())
932
933 if args.Pretty {
934 enc.SetIndent("", " ")
935 }
936
937 for k, v := range relays {
938 ro := RelayOutput{NebulaAddr: v.vpnAddrs[0]}
939 co.Relays = append(co.Relays, &ro)
940 relayHI := ifce.hostMap.QueryVpnAddr(v.vpnAddrs[0])
941 if relayHI == nil {
942 ro.RelayForAddrs = append(ro.RelayForAddrs, RelayFor{Error: errors.New("could not find hostinfo")})
943 continue
944 }
945 for _, vpnAddr := range relayHI.relayState.CopyRelayForIps() {
946 rf := RelayFor{Error: nil}
947 r, ok := relayHI.relayState.GetRelayForByAddr(vpnAddr)
948 if ok {
949 t := ""
950 switch r.Type {
951 case ForwardingType:
952 t = "forwarding"
953 case TerminalType:
954 t = "terminal"
955 default:
956 t = "unknown"
957 }
958
959 s := ""
960 switch r.State {
961 case Requested:
962 s = "requested"
963 case Established:
964 s = "established"
965 default:
966 s = "unknown"
967 }
968
969 rf.LocalIndex = r.LocalIndex
970 rf.RemoteIndex = r.RemoteIndex
971 rf.PeerAddr = r.PeerAddr
972 rf.Type = t
973 rf.State = s
974 if rf.LocalIndex != k {
975 rf.Error = fmt.Errorf("hostmap LocalIndex '%v' does not match RelayState LocalIndex", k)
976 }
977 }
978 relayedHI := ifce.hostMap.QueryVpnAddr(vpnAddr)
979 if relayedHI != nil {
980 rf.RelayedThrough = append(rf.RelayedThrough, relayedHI.relayState.CopyRelayIps()...)
981 }
982
983 ro.RelayForAddrs = append(ro.RelayForAddrs, rf)
984 }
985 }
986 err := enc.Encode(co)
987 if err != nil {
988 return err
989 }
990 return nil
991 }
992
993 func sshPrintTunnel(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
994 args, ok := fs.(*sshPrintTunnelFlags)
995 if !ok {
996 return nil
997 }
998
999 if len(a) == 0 {
1000 return w.WriteLine("No vpn address was provided")
1001 }
1002
1003 vpnAddr, err := netip.ParseAddr(a[0])
1004 if err != nil {
1005 return w.WriteLine(fmt.Sprintf("The provided vpn addr could not be parsed: %s", a[0]))
1006 }
1007
1008 if !vpnAddr.IsValid() {
1009 return w.WriteLine(fmt.Sprintf("The provided vpn addr could not be parsed: %s", a[0]))
1010 }
1011
1012 hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
1013 if hostInfo == nil {
1014 return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn addr: %v", a[0]))
1015 }
1016
1017 enc := json.NewEncoder(w.GetWriter())
1018 if args.Pretty {
1019 enc.SetIndent("", " ")
1020 }
1021
1022 return enc.Encode(copyHostInfo(hostInfo, ifce.hostMap.GetPreferredRanges()))
1023 }
1024
1025 func sshDeviceInfo(ifce *Interface, fs any, w sshd.StringWriter) error {
1026
1027 data := struct {
1028 Name string `json:"name"`
1029 Cidr []netip.Prefix `json:"cidr"`
1030 }{
1031 Name: ifce.inside.Name(),
1032 Cidr: make([]netip.Prefix, len(ifce.inside.Networks())),
1033 }
1034
1035 copy(data.Cidr, ifce.inside.Networks())
1036
1037 flags, ok := fs.(*sshDeviceInfoFlags)
1038 if !ok {
1039 return fmt.Errorf("internal error: expected flags to be sshDeviceInfoFlags but was %+v", fs)
1040 }
1041
1042 if flags.Json || flags.Pretty {
1043 js := json.NewEncoder(w.GetWriter())
1044 if flags.Pretty {
1045 js.SetIndent("", " ")
1046 }
1047
1048 return js.Encode(data)
1049 } else {
1050 return w.WriteLine(fmt.Sprintf("name=%v cidr=%v", data.Name, data.Cidr))
1051 }
1052 }
1053
1054 func sshReload(c *config.C, w sshd.StringWriter) error {
1055 err := w.WriteLine("Reloading config")
1056 c.ReloadConfig()
1057 return err
1058 }