ssh.go 24 KB

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