ssh.go 24 KB

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