3
0

ssh.go 26 KB

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