ssh.go 25 KB

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