ssh.go 19 KB

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