ssh.go 22 KB

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