ssh.go 19 KB

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