ssh.go 20 KB

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