ssh.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  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 hostInfo == nil {
  552. return w.WriteLine("Handshake rate limit reached")
  553. }
  554. if addr.IsValid() {
  555. hostInfo.SetRemote(addr)
  556. }
  557. return w.WriteLine("Created")
  558. }
  559. func sshChangeRemote(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
  560. flags, ok := fs.(*sshChangeRemoteFlags)
  561. if !ok {
  562. return nil
  563. }
  564. if len(a) == 0 {
  565. return w.WriteLine("No vpn address was provided")
  566. }
  567. if flags.Address == "" {
  568. return w.WriteLine("No address was provided")
  569. }
  570. addr, err := netip.ParseAddrPort(flags.Address)
  571. if err != nil {
  572. return w.WriteLine("Address could not be parsed")
  573. }
  574. vpnAddr, err := netip.ParseAddr(a[0])
  575. if err != nil {
  576. return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
  577. }
  578. if !vpnAddr.IsValid() {
  579. return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
  580. }
  581. hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
  582. if hostInfo == nil {
  583. return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn address: %v", a[0]))
  584. }
  585. hostInfo.SetRemote(addr)
  586. return w.WriteLine("Changed")
  587. }
  588. func sshGetHeapProfile(fs any, a []string, w sshd.StringWriter) error {
  589. if len(a) == 0 {
  590. return w.WriteLine("No path to write profile provided")
  591. }
  592. file, err := os.Create(a[0])
  593. if err != nil {
  594. err = w.WriteLine(fmt.Sprintf("Unable to create profile file: %s", err))
  595. return err
  596. }
  597. err = pprof.WriteHeapProfile(file)
  598. if err != nil {
  599. err = w.WriteLine(fmt.Sprintf("Unable to write profile: %s", err))
  600. return err
  601. }
  602. err = w.WriteLine(fmt.Sprintf("Mem profile created at %s", a))
  603. return err
  604. }
  605. func sshMutexProfileFraction(fs any, a []string, w sshd.StringWriter) error {
  606. if len(a) == 0 {
  607. rate := runtime.SetMutexProfileFraction(-1)
  608. return w.WriteLine(fmt.Sprintf("Current value: %d", rate))
  609. }
  610. newRate, err := strconv.Atoi(a[0])
  611. if err != nil {
  612. return w.WriteLine(fmt.Sprintf("Invalid argument: %s", a[0]))
  613. }
  614. oldRate := runtime.SetMutexProfileFraction(newRate)
  615. return w.WriteLine(fmt.Sprintf("New value: %d. Old value: %d", newRate, oldRate))
  616. }
  617. func sshGetMutexProfile(fs any, a []string, w sshd.StringWriter) error {
  618. if len(a) == 0 {
  619. return w.WriteLine("No path to write profile provided")
  620. }
  621. file, err := os.Create(a[0])
  622. if err != nil {
  623. return w.WriteLine(fmt.Sprintf("Unable to create profile file: %s", err))
  624. }
  625. defer file.Close()
  626. mutexProfile := pprof.Lookup("mutex")
  627. if mutexProfile == nil {
  628. return w.WriteLine("Unable to get pprof.Lookup(\"mutex\")")
  629. }
  630. err = mutexProfile.WriteTo(file, 0)
  631. if err != nil {
  632. return w.WriteLine(fmt.Sprintf("Unable to write profile: %s", err))
  633. }
  634. return w.WriteLine(fmt.Sprintf("Mutex profile created at %s", a))
  635. }
  636. func sshLogLevel(l *logrus.Logger, fs any, a []string, w sshd.StringWriter) error {
  637. if len(a) == 0 {
  638. return w.WriteLine(fmt.Sprintf("Log level is: %s", l.Level))
  639. }
  640. level, err := logrus.ParseLevel(a[0])
  641. if err != nil {
  642. return w.WriteLine(fmt.Sprintf("Unknown log level %s. Possible log levels: %s", a, logrus.AllLevels))
  643. }
  644. l.SetLevel(level)
  645. return w.WriteLine(fmt.Sprintf("Log level is: %s", l.Level))
  646. }
  647. func sshLogFormat(l *logrus.Logger, fs any, a []string, w sshd.StringWriter) error {
  648. if len(a) == 0 {
  649. return w.WriteLine(fmt.Sprintf("Log format is: %s", reflect.TypeOf(l.Formatter)))
  650. }
  651. logFormat := strings.ToLower(a[0])
  652. switch logFormat {
  653. case "text":
  654. l.Formatter = &logrus.TextFormatter{}
  655. case "json":
  656. l.Formatter = &logrus.JSONFormatter{}
  657. default:
  658. return fmt.Errorf("unknown log format `%s`. possible formats: %s", logFormat, []string{"text", "json"})
  659. }
  660. return w.WriteLine(fmt.Sprintf("Log format is: %s", reflect.TypeOf(l.Formatter)))
  661. }
  662. func sshPrintCert(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
  663. args, ok := fs.(*sshPrintCertFlags)
  664. if !ok {
  665. return nil
  666. }
  667. cert := ifce.pki.getCertState().GetDefaultCertificate()
  668. if len(a) > 0 {
  669. vpnAddr, err := netip.ParseAddr(a[0])
  670. if err != nil {
  671. return w.WriteLine(fmt.Sprintf("The provided vpn addr could not be parsed: %s", a[0]))
  672. }
  673. if !vpnAddr.IsValid() {
  674. return w.WriteLine(fmt.Sprintf("The provided vpn addr could not be parsed: %s", a[0]))
  675. }
  676. hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
  677. if hostInfo == nil {
  678. return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn addr: %v", a[0]))
  679. }
  680. cert = hostInfo.GetCert().Certificate
  681. }
  682. if args.Json || args.Pretty {
  683. b, err := cert.MarshalJSON()
  684. if err != nil {
  685. return nil
  686. }
  687. if args.Pretty {
  688. buf := new(bytes.Buffer)
  689. err := json.Indent(buf, b, "", " ")
  690. b = buf.Bytes()
  691. if err != nil {
  692. return nil
  693. }
  694. }
  695. return w.WriteBytes(b)
  696. }
  697. if args.Raw {
  698. b, err := cert.MarshalPEM()
  699. if err != nil {
  700. return nil
  701. }
  702. return w.WriteBytes(b)
  703. }
  704. return w.WriteLine(cert.String())
  705. }
  706. func sshPrintRelays(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
  707. args, ok := fs.(*sshPrintTunnelFlags)
  708. if !ok {
  709. w.WriteLine(fmt.Sprintf("sshPrintRelays failed to convert args type"))
  710. return nil
  711. }
  712. relays := map[uint32]*HostInfo{}
  713. ifce.hostMap.Lock()
  714. maps.Copy(relays, ifce.hostMap.Relays)
  715. ifce.hostMap.Unlock()
  716. type RelayFor struct {
  717. Error error
  718. Type string
  719. State string
  720. PeerAddr netip.Addr
  721. LocalIndex uint32
  722. RemoteIndex uint32
  723. RelayedThrough []netip.Addr
  724. }
  725. type RelayOutput struct {
  726. NebulaAddr netip.Addr
  727. RelayForAddrs []RelayFor
  728. }
  729. type CmdOutput struct {
  730. Relays []*RelayOutput
  731. }
  732. co := CmdOutput{}
  733. enc := json.NewEncoder(w.GetWriter())
  734. if args.Pretty {
  735. enc.SetIndent("", " ")
  736. }
  737. for k, v := range relays {
  738. ro := RelayOutput{NebulaAddr: v.vpnAddrs[0]}
  739. co.Relays = append(co.Relays, &ro)
  740. relayHI := ifce.hostMap.QueryVpnAddr(v.vpnAddrs[0])
  741. if relayHI == nil {
  742. ro.RelayForAddrs = append(ro.RelayForAddrs, RelayFor{Error: errors.New("could not find hostinfo")})
  743. continue
  744. }
  745. for _, vpnAddr := range relayHI.relayState.CopyRelayForIps() {
  746. rf := RelayFor{Error: nil}
  747. r, ok := relayHI.relayState.GetRelayForByAddr(vpnAddr)
  748. if ok {
  749. t := ""
  750. switch r.Type {
  751. case ForwardingType:
  752. t = "forwarding"
  753. case TerminalType:
  754. t = "terminal"
  755. default:
  756. t = "unknown"
  757. }
  758. s := ""
  759. switch r.State {
  760. case Requested:
  761. s = "requested"
  762. case Established:
  763. s = "established"
  764. default:
  765. s = "unknown"
  766. }
  767. rf.LocalIndex = r.LocalIndex
  768. rf.RemoteIndex = r.RemoteIndex
  769. rf.PeerAddr = r.PeerAddr
  770. rf.Type = t
  771. rf.State = s
  772. if rf.LocalIndex != k {
  773. rf.Error = fmt.Errorf("hostmap LocalIndex '%v' does not match RelayState LocalIndex", k)
  774. }
  775. }
  776. relayedHI := ifce.hostMap.QueryVpnAddr(vpnAddr)
  777. if relayedHI != nil {
  778. rf.RelayedThrough = append(rf.RelayedThrough, relayedHI.relayState.CopyRelayIps()...)
  779. }
  780. ro.RelayForAddrs = append(ro.RelayForAddrs, rf)
  781. }
  782. }
  783. err := enc.Encode(co)
  784. if err != nil {
  785. return err
  786. }
  787. return nil
  788. }
  789. func sshPrintTunnel(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
  790. args, ok := fs.(*sshPrintTunnelFlags)
  791. if !ok {
  792. return nil
  793. }
  794. if len(a) == 0 {
  795. return w.WriteLine("No vpn address was provided")
  796. }
  797. vpnAddr, err := netip.ParseAddr(a[0])
  798. if err != nil {
  799. return w.WriteLine(fmt.Sprintf("The provided vpn addr could not be parsed: %s", a[0]))
  800. }
  801. if !vpnAddr.IsValid() {
  802. return w.WriteLine(fmt.Sprintf("The provided vpn addr could not be parsed: %s", a[0]))
  803. }
  804. hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
  805. if hostInfo == nil {
  806. return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn addr: %v", a[0]))
  807. }
  808. enc := json.NewEncoder(w.GetWriter())
  809. if args.Pretty {
  810. enc.SetIndent("", " ")
  811. }
  812. return enc.Encode(copyHostInfo(hostInfo, ifce.hostMap.GetPreferredRanges()))
  813. }
  814. func sshDeviceInfo(ifce *Interface, fs any, w sshd.StringWriter) error {
  815. data := struct {
  816. Name string `json:"name"`
  817. Cidr []netip.Prefix `json:"cidr"`
  818. }{
  819. Name: ifce.inside.Name(),
  820. Cidr: make([]netip.Prefix, len(ifce.inside.Networks())),
  821. }
  822. copy(data.Cidr, ifce.inside.Networks())
  823. flags, ok := fs.(*sshDeviceInfoFlags)
  824. if !ok {
  825. return fmt.Errorf("internal error: expected flags to be sshDeviceInfoFlags but was %+v", fs)
  826. }
  827. if flags.Json || flags.Pretty {
  828. js := json.NewEncoder(w.GetWriter())
  829. if flags.Pretty {
  830. js.SetIndent("", " ")
  831. }
  832. return js.Encode(data)
  833. } else {
  834. return w.WriteLine(fmt.Sprintf("name=%v cidr=%v", data.Name, data.Cidr))
  835. }
  836. }
  837. func sshReload(c *config.C, w sshd.StringWriter) error {
  838. err := w.WriteLine("Reloading config")
  839. c.ReloadConfig()
  840. return err
  841. }