ssh.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  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: "change-remote",
  262. ShortDescription: "Changes the remote address used in the tunnel for the provided vpn ip",
  263. Flags: func() (*flag.FlagSet, interface{}) {
  264. fl := flag.NewFlagSet("", flag.ContinueOnError)
  265. s := sshChangeRemoteFlags{}
  266. fl.StringVar(&s.Address, "address", "", "The new remote address, ip:port")
  267. return fl, &s
  268. },
  269. Callback: func(fs interface{}, a []string, w sshd.StringWriter) error {
  270. return sshChangeRemote(ifce, fs, a, w)
  271. },
  272. })
  273. ssh.RegisterCommand(&sshd.Command{
  274. Name: "close-tunnel",
  275. ShortDescription: "Closes a tunnel for the provided vpn ip",
  276. Flags: func() (*flag.FlagSet, interface{}) {
  277. fl := flag.NewFlagSet("", flag.ContinueOnError)
  278. s := sshCloseTunnelFlags{}
  279. fl.BoolVar(&s.LocalOnly, "local-only", false, "Disables notifying the remote that the tunnel is shutting down")
  280. return fl, &s
  281. },
  282. Callback: func(fs interface{}, a []string, w sshd.StringWriter) error {
  283. return sshCloseTunnel(ifce, fs, a, w)
  284. },
  285. })
  286. ssh.RegisterCommand(&sshd.Command{
  287. Name: "create-tunnel",
  288. ShortDescription: "Creates a tunnel for the provided vpn ip and address",
  289. Help: "The lighthouses will be queried for real addresses but you can provide one as well.",
  290. Flags: func() (*flag.FlagSet, interface{}) {
  291. fl := flag.NewFlagSet("", flag.ContinueOnError)
  292. s := sshCreateTunnelFlags{}
  293. fl.StringVar(&s.Address, "address", "", "Optionally provide a real remote address, ip:port ")
  294. return fl, &s
  295. },
  296. Callback: func(fs interface{}, a []string, w sshd.StringWriter) error {
  297. return sshCreateTunnel(ifce, fs, a, w)
  298. },
  299. })
  300. ssh.RegisterCommand(&sshd.Command{
  301. Name: "query-lighthouse",
  302. ShortDescription: "Query the lighthouses for the provided vpn ip",
  303. Help: "This command is asynchronous. Only currently known udp ips will be printed.",
  304. Callback: func(fs interface{}, a []string, w sshd.StringWriter) error {
  305. return sshQueryLighthouse(ifce, fs, a, w)
  306. },
  307. })
  308. }
  309. func sshListHostMap(hostMap *HostMap, a interface{}, w sshd.StringWriter) error {
  310. fs, ok := a.(*sshListHostMapFlags)
  311. if !ok {
  312. //TODO: error
  313. return nil
  314. }
  315. hm := listHostMap(hostMap)
  316. sort.Slice(hm, func(i, j int) bool {
  317. return bytes.Compare(hm[i].VpnIp, hm[j].VpnIp) < 0
  318. })
  319. if fs.Json || fs.Pretty {
  320. js := json.NewEncoder(w.GetWriter())
  321. if fs.Pretty {
  322. js.SetIndent("", " ")
  323. }
  324. err := js.Encode(hm)
  325. if err != nil {
  326. //TODO
  327. return nil
  328. }
  329. } else {
  330. for _, v := range hm {
  331. err := w.WriteLine(fmt.Sprintf("%s: %s", v.VpnIp, v.RemoteAddrs))
  332. if err != nil {
  333. return err
  334. }
  335. }
  336. }
  337. return nil
  338. }
  339. func sshListLighthouseMap(lightHouse *LightHouse, a interface{}, w sshd.StringWriter) error {
  340. fs, ok := a.(*sshListHostMapFlags)
  341. if !ok {
  342. //TODO: error
  343. return nil
  344. }
  345. type lighthouseInfo struct {
  346. VpnIp string `json:"vpnIp"`
  347. Addrs *CacheMap `json:"addrs"`
  348. }
  349. lightHouse.RLock()
  350. addrMap := make([]lighthouseInfo, len(lightHouse.addrMap))
  351. x := 0
  352. for k, v := range lightHouse.addrMap {
  353. addrMap[x] = lighthouseInfo{
  354. VpnIp: k.String(),
  355. Addrs: v.CopyCache(),
  356. }
  357. x++
  358. }
  359. lightHouse.RUnlock()
  360. sort.Slice(addrMap, func(i, j int) bool {
  361. return strings.Compare(addrMap[i].VpnIp, addrMap[j].VpnIp) < 0
  362. })
  363. if fs.Json || fs.Pretty {
  364. js := json.NewEncoder(w.GetWriter())
  365. if fs.Pretty {
  366. js.SetIndent("", " ")
  367. }
  368. err := js.Encode(addrMap)
  369. if err != nil {
  370. //TODO
  371. return nil
  372. }
  373. } else {
  374. for _, v := range addrMap {
  375. b, err := json.Marshal(v.Addrs)
  376. if err != nil {
  377. return err
  378. }
  379. err = w.WriteLine(fmt.Sprintf("%s: %s", v.VpnIp, string(b)))
  380. if err != nil {
  381. return err
  382. }
  383. }
  384. }
  385. return nil
  386. }
  387. func sshStartCpuProfile(fs interface{}, a []string, w sshd.StringWriter) error {
  388. if len(a) == 0 {
  389. err := w.WriteLine("No path to write profile provided")
  390. return err
  391. }
  392. file, err := os.Create(a[0])
  393. if err != nil {
  394. err = w.WriteLine(fmt.Sprintf("Unable to create profile file: %s", err))
  395. return err
  396. }
  397. err = pprof.StartCPUProfile(file)
  398. if err != nil {
  399. err = w.WriteLine(fmt.Sprintf("Unable to start cpu profile: %s", err))
  400. return err
  401. }
  402. err = w.WriteLine(fmt.Sprintf("Started cpu profile, issue stop-cpu-profile to write the output to %s", a))
  403. return err
  404. }
  405. func sshVersion(ifce *Interface, fs interface{}, a []string, w sshd.StringWriter) error {
  406. return w.WriteLine(fmt.Sprintf("%s", ifce.version))
  407. }
  408. func sshQueryLighthouse(ifce *Interface, fs interface{}, a []string, w sshd.StringWriter) error {
  409. if len(a) == 0 {
  410. return w.WriteLine("No vpn ip was provided")
  411. }
  412. parsedIp := net.ParseIP(a[0])
  413. if parsedIp == nil {
  414. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  415. }
  416. vpnIp := iputil.Ip2VpnIp(parsedIp)
  417. if vpnIp == 0 {
  418. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  419. }
  420. var cm *CacheMap
  421. rl := ifce.lightHouse.Query(vpnIp, ifce)
  422. if rl != nil {
  423. cm = rl.CopyCache()
  424. }
  425. return json.NewEncoder(w.GetWriter()).Encode(cm)
  426. }
  427. func sshCloseTunnel(ifce *Interface, fs interface{}, a []string, w sshd.StringWriter) error {
  428. flags, ok := fs.(*sshCloseTunnelFlags)
  429. if !ok {
  430. //TODO: error
  431. return nil
  432. }
  433. if len(a) == 0 {
  434. return w.WriteLine("No vpn ip was provided")
  435. }
  436. parsedIp := net.ParseIP(a[0])
  437. if parsedIp == nil {
  438. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  439. }
  440. vpnIp := iputil.Ip2VpnIp(parsedIp)
  441. if vpnIp == 0 {
  442. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  443. }
  444. hostInfo, err := ifce.hostMap.QueryVpnIp(vpnIp)
  445. if err != nil {
  446. return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn ip: %v", a[0]))
  447. }
  448. if !flags.LocalOnly {
  449. ifce.send(
  450. header.CloseTunnel,
  451. 0,
  452. hostInfo.ConnectionState,
  453. hostInfo,
  454. hostInfo.remote,
  455. []byte{},
  456. make([]byte, 12, 12),
  457. make([]byte, mtu),
  458. )
  459. }
  460. ifce.closeTunnel(hostInfo, false)
  461. return w.WriteLine("Closed")
  462. }
  463. func sshCreateTunnel(ifce *Interface, fs interface{}, a []string, w sshd.StringWriter) error {
  464. flags, ok := fs.(*sshCreateTunnelFlags)
  465. if !ok {
  466. //TODO: error
  467. return nil
  468. }
  469. if len(a) == 0 {
  470. return w.WriteLine("No vpn ip was provided")
  471. }
  472. parsedIp := net.ParseIP(a[0])
  473. if parsedIp == nil {
  474. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  475. }
  476. vpnIp := iputil.Ip2VpnIp(parsedIp)
  477. if vpnIp == 0 {
  478. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  479. }
  480. hostInfo, _ := ifce.hostMap.QueryVpnIp(vpnIp)
  481. if hostInfo != nil {
  482. return w.WriteLine(fmt.Sprintf("Tunnel already exists"))
  483. }
  484. hostInfo, _ = ifce.handshakeManager.pendingHostMap.QueryVpnIp(vpnIp)
  485. if hostInfo != nil {
  486. return w.WriteLine(fmt.Sprintf("Tunnel already handshaking"))
  487. }
  488. var addr *udp.Addr
  489. if flags.Address != "" {
  490. addr = udp.NewAddrFromString(flags.Address)
  491. if addr == nil {
  492. return w.WriteLine("Address could not be parsed")
  493. }
  494. }
  495. hostInfo = ifce.handshakeManager.AddVpnIp(vpnIp)
  496. if addr != nil {
  497. hostInfo.SetRemote(addr)
  498. }
  499. ifce.getOrHandshake(vpnIp)
  500. return w.WriteLine("Created")
  501. }
  502. func sshChangeRemote(ifce *Interface, fs interface{}, a []string, w sshd.StringWriter) error {
  503. flags, ok := fs.(*sshChangeRemoteFlags)
  504. if !ok {
  505. //TODO: error
  506. return nil
  507. }
  508. if len(a) == 0 {
  509. return w.WriteLine("No vpn ip was provided")
  510. }
  511. if flags.Address == "" {
  512. return w.WriteLine("No address was provided")
  513. }
  514. addr := udp.NewAddrFromString(flags.Address)
  515. if addr == nil {
  516. return w.WriteLine("Address could not be parsed")
  517. }
  518. parsedIp := net.ParseIP(a[0])
  519. if parsedIp == nil {
  520. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  521. }
  522. vpnIp := iputil.Ip2VpnIp(parsedIp)
  523. if vpnIp == 0 {
  524. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  525. }
  526. hostInfo, err := ifce.hostMap.QueryVpnIp(vpnIp)
  527. if err != nil {
  528. return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn ip: %v", a[0]))
  529. }
  530. hostInfo.SetRemote(addr)
  531. return w.WriteLine("Changed")
  532. }
  533. func sshGetHeapProfile(fs interface{}, a []string, w sshd.StringWriter) error {
  534. if len(a) == 0 {
  535. return w.WriteLine("No path to write profile provided")
  536. }
  537. file, err := os.Create(a[0])
  538. if err != nil {
  539. err = w.WriteLine(fmt.Sprintf("Unable to create profile file: %s", err))
  540. return err
  541. }
  542. err = pprof.WriteHeapProfile(file)
  543. if err != nil {
  544. err = w.WriteLine(fmt.Sprintf("Unable to write profile: %s", err))
  545. return err
  546. }
  547. err = w.WriteLine(fmt.Sprintf("Mem profile created at %s", a))
  548. return err
  549. }
  550. func sshLogLevel(l *logrus.Logger, fs interface{}, a []string, w sshd.StringWriter) error {
  551. if len(a) == 0 {
  552. return w.WriteLine(fmt.Sprintf("Log level is: %s", l.Level))
  553. }
  554. level, err := logrus.ParseLevel(a[0])
  555. if err != nil {
  556. return w.WriteLine(fmt.Sprintf("Unknown log level %s. Possible log levels: %s", a, logrus.AllLevels))
  557. }
  558. l.SetLevel(level)
  559. return w.WriteLine(fmt.Sprintf("Log level is: %s", l.Level))
  560. }
  561. func sshLogFormat(l *logrus.Logger, fs interface{}, a []string, w sshd.StringWriter) error {
  562. if len(a) == 0 {
  563. return w.WriteLine(fmt.Sprintf("Log format is: %s", reflect.TypeOf(l.Formatter)))
  564. }
  565. logFormat := strings.ToLower(a[0])
  566. switch logFormat {
  567. case "text":
  568. l.Formatter = &logrus.TextFormatter{}
  569. case "json":
  570. l.Formatter = &logrus.JSONFormatter{}
  571. default:
  572. return fmt.Errorf("unknown log format `%s`. possible formats: %s", logFormat, []string{"text", "json"})
  573. }
  574. return w.WriteLine(fmt.Sprintf("Log format is: %s", reflect.TypeOf(l.Formatter)))
  575. }
  576. func sshPrintCert(ifce *Interface, fs interface{}, a []string, w sshd.StringWriter) error {
  577. args, ok := fs.(*sshPrintCertFlags)
  578. if !ok {
  579. //TODO: error
  580. return nil
  581. }
  582. cert := ifce.certState.certificate
  583. if len(a) > 0 {
  584. parsedIp := net.ParseIP(a[0])
  585. if parsedIp == nil {
  586. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  587. }
  588. vpnIp := iputil.Ip2VpnIp(parsedIp)
  589. if vpnIp == 0 {
  590. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  591. }
  592. hostInfo, err := ifce.hostMap.QueryVpnIp(vpnIp)
  593. if err != nil {
  594. return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn ip: %v", a[0]))
  595. }
  596. cert = hostInfo.GetCert()
  597. }
  598. if args.Json || args.Pretty {
  599. b, err := cert.MarshalJSON()
  600. if err != nil {
  601. //TODO: handle it
  602. return nil
  603. }
  604. if args.Pretty {
  605. buf := new(bytes.Buffer)
  606. err := json.Indent(buf, b, "", " ")
  607. b = buf.Bytes()
  608. if err != nil {
  609. //TODO: handle it
  610. return nil
  611. }
  612. }
  613. return w.WriteBytes(b)
  614. }
  615. if args.Raw {
  616. b, err := cert.MarshalToPEM()
  617. if err != nil {
  618. //TODO: handle it
  619. return nil
  620. }
  621. return w.WriteBytes(b)
  622. }
  623. return w.WriteLine(cert.String())
  624. }
  625. func sshPrintTunnel(ifce *Interface, fs interface{}, a []string, w sshd.StringWriter) error {
  626. args, ok := fs.(*sshPrintTunnelFlags)
  627. if !ok {
  628. //TODO: error
  629. return nil
  630. }
  631. if len(a) == 0 {
  632. return w.WriteLine("No vpn ip was provided")
  633. }
  634. parsedIp := net.ParseIP(a[0])
  635. if parsedIp == nil {
  636. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  637. }
  638. vpnIp := iputil.Ip2VpnIp(parsedIp)
  639. if vpnIp == 0 {
  640. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  641. }
  642. hostInfo, err := ifce.hostMap.QueryVpnIp(vpnIp)
  643. if err != nil {
  644. return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn ip: %v", a[0]))
  645. }
  646. enc := json.NewEncoder(w.GetWriter())
  647. if args.Pretty {
  648. enc.SetIndent("", " ")
  649. }
  650. return enc.Encode(copyHostInfo(hostInfo, ifce.hostMap.preferredRanges))
  651. }
  652. func sshReload(fs interface{}, a []string, w sshd.StringWriter) error {
  653. p, err := os.FindProcess(os.Getpid())
  654. if err != nil {
  655. return w.WriteLine(err.Error())
  656. //TODO
  657. }
  658. err = p.Signal(syscall.SIGHUP)
  659. if err != nil {
  660. return w.WriteLine(err.Error())
  661. //TODO
  662. }
  663. return w.WriteLine("HUP sent")
  664. }