ssh.go 23 KB

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