ssh.go 25 KB

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