ssh.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  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.AddVpnIp(vpnIp)
  530. if addr != nil {
  531. hostInfo.SetRemote(addr)
  532. }
  533. ifce.getOrHandshake(vpnIp)
  534. return w.WriteLine("Created")
  535. }
  536. func sshChangeRemote(ifce *Interface, fs interface{}, a []string, w sshd.StringWriter) error {
  537. flags, ok := fs.(*sshChangeRemoteFlags)
  538. if !ok {
  539. //TODO: error
  540. return nil
  541. }
  542. if len(a) == 0 {
  543. return w.WriteLine("No vpn ip was provided")
  544. }
  545. if flags.Address == "" {
  546. return w.WriteLine("No address was provided")
  547. }
  548. addr := udp.NewAddrFromString(flags.Address)
  549. if addr == nil {
  550. return w.WriteLine("Address could not be parsed")
  551. }
  552. parsedIp := net.ParseIP(a[0])
  553. if parsedIp == nil {
  554. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  555. }
  556. vpnIp := iputil.Ip2VpnIp(parsedIp)
  557. if vpnIp == 0 {
  558. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  559. }
  560. hostInfo := ifce.hostMap.QueryVpnIp(vpnIp)
  561. if hostInfo == nil {
  562. return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn ip: %v", a[0]))
  563. }
  564. hostInfo.SetRemote(addr)
  565. return w.WriteLine("Changed")
  566. }
  567. func sshGetHeapProfile(fs interface{}, a []string, w sshd.StringWriter) error {
  568. if len(a) == 0 {
  569. return w.WriteLine("No path to write profile provided")
  570. }
  571. file, err := os.Create(a[0])
  572. if err != nil {
  573. err = w.WriteLine(fmt.Sprintf("Unable to create profile file: %s", err))
  574. return err
  575. }
  576. err = pprof.WriteHeapProfile(file)
  577. if err != nil {
  578. err = w.WriteLine(fmt.Sprintf("Unable to write profile: %s", err))
  579. return err
  580. }
  581. err = w.WriteLine(fmt.Sprintf("Mem profile created at %s", a))
  582. return err
  583. }
  584. func sshMutexProfileFraction(fs interface{}, a []string, w sshd.StringWriter) error {
  585. if len(a) == 0 {
  586. rate := runtime.SetMutexProfileFraction(-1)
  587. return w.WriteLine(fmt.Sprintf("Current value: %d", rate))
  588. }
  589. newRate, err := strconv.Atoi(a[0])
  590. if err != nil {
  591. return w.WriteLine(fmt.Sprintf("Invalid argument: %s", a[0]))
  592. }
  593. oldRate := runtime.SetMutexProfileFraction(newRate)
  594. return w.WriteLine(fmt.Sprintf("New value: %d. Old value: %d", newRate, oldRate))
  595. }
  596. func sshGetMutexProfile(fs interface{}, a []string, w sshd.StringWriter) error {
  597. if len(a) == 0 {
  598. return w.WriteLine("No path to write profile provided")
  599. }
  600. file, err := os.Create(a[0])
  601. if err != nil {
  602. return w.WriteLine(fmt.Sprintf("Unable to create profile file: %s", err))
  603. }
  604. defer file.Close()
  605. mutexProfile := pprof.Lookup("mutex")
  606. if mutexProfile == nil {
  607. return w.WriteLine("Unable to get pprof.Lookup(\"mutex\")")
  608. }
  609. err = mutexProfile.WriteTo(file, 0)
  610. if err != nil {
  611. return w.WriteLine(fmt.Sprintf("Unable to write profile: %s", err))
  612. }
  613. return w.WriteLine(fmt.Sprintf("Mutex profile created at %s", a))
  614. }
  615. func sshLogLevel(l *logrus.Logger, fs interface{}, a []string, w sshd.StringWriter) error {
  616. if len(a) == 0 {
  617. return w.WriteLine(fmt.Sprintf("Log level is: %s", l.Level))
  618. }
  619. level, err := logrus.ParseLevel(a[0])
  620. if err != nil {
  621. return w.WriteLine(fmt.Sprintf("Unknown log level %s. Possible log levels: %s", a, logrus.AllLevels))
  622. }
  623. l.SetLevel(level)
  624. return w.WriteLine(fmt.Sprintf("Log level is: %s", l.Level))
  625. }
  626. func sshLogFormat(l *logrus.Logger, fs interface{}, a []string, w sshd.StringWriter) error {
  627. if len(a) == 0 {
  628. return w.WriteLine(fmt.Sprintf("Log format is: %s", reflect.TypeOf(l.Formatter)))
  629. }
  630. logFormat := strings.ToLower(a[0])
  631. switch logFormat {
  632. case "text":
  633. l.Formatter = &logrus.TextFormatter{}
  634. case "json":
  635. l.Formatter = &logrus.JSONFormatter{}
  636. default:
  637. return fmt.Errorf("unknown log format `%s`. possible formats: %s", logFormat, []string{"text", "json"})
  638. }
  639. return w.WriteLine(fmt.Sprintf("Log format is: %s", reflect.TypeOf(l.Formatter)))
  640. }
  641. func sshPrintCert(ifce *Interface, fs interface{}, a []string, w sshd.StringWriter) error {
  642. args, ok := fs.(*sshPrintCertFlags)
  643. if !ok {
  644. //TODO: error
  645. return nil
  646. }
  647. cert := ifce.pki.GetCertState().Certificate
  648. if len(a) > 0 {
  649. parsedIp := net.ParseIP(a[0])
  650. if parsedIp == nil {
  651. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  652. }
  653. vpnIp := iputil.Ip2VpnIp(parsedIp)
  654. if vpnIp == 0 {
  655. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  656. }
  657. hostInfo := ifce.hostMap.QueryVpnIp(vpnIp)
  658. if hostInfo == nil {
  659. return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn ip: %v", a[0]))
  660. }
  661. cert = hostInfo.GetCert()
  662. }
  663. if args.Json || args.Pretty {
  664. b, err := cert.MarshalJSON()
  665. if err != nil {
  666. //TODO: handle it
  667. return nil
  668. }
  669. if args.Pretty {
  670. buf := new(bytes.Buffer)
  671. err := json.Indent(buf, b, "", " ")
  672. b = buf.Bytes()
  673. if err != nil {
  674. //TODO: handle it
  675. return nil
  676. }
  677. }
  678. return w.WriteBytes(b)
  679. }
  680. if args.Raw {
  681. b, err := cert.MarshalToPEM()
  682. if err != nil {
  683. //TODO: handle it
  684. return nil
  685. }
  686. return w.WriteBytes(b)
  687. }
  688. return w.WriteLine(cert.String())
  689. }
  690. func sshPrintRelays(ifce *Interface, fs interface{}, a []string, w sshd.StringWriter) error {
  691. args, ok := fs.(*sshPrintTunnelFlags)
  692. if !ok {
  693. //TODO: error
  694. w.WriteLine(fmt.Sprintf("sshPrintRelays failed to convert args type"))
  695. return nil
  696. }
  697. relays := map[uint32]*HostInfo{}
  698. ifce.hostMap.Lock()
  699. for k, v := range ifce.hostMap.Relays {
  700. relays[k] = v
  701. }
  702. ifce.hostMap.Unlock()
  703. type RelayFor struct {
  704. Error error
  705. Type string
  706. State string
  707. PeerIp iputil.VpnIp
  708. LocalIndex uint32
  709. RemoteIndex uint32
  710. RelayedThrough []iputil.VpnIp
  711. }
  712. type RelayOutput struct {
  713. NebulaIp iputil.VpnIp
  714. RelayForIps []RelayFor
  715. }
  716. type CmdOutput struct {
  717. Relays []*RelayOutput
  718. }
  719. co := CmdOutput{}
  720. enc := json.NewEncoder(w.GetWriter())
  721. if args.Pretty {
  722. enc.SetIndent("", " ")
  723. }
  724. for k, v := range relays {
  725. ro := RelayOutput{NebulaIp: v.vpnIp}
  726. co.Relays = append(co.Relays, &ro)
  727. relayHI := ifce.hostMap.QueryVpnIp(v.vpnIp)
  728. if relayHI == nil {
  729. ro.RelayForIps = append(ro.RelayForIps, RelayFor{Error: errors.New("could not find hostinfo")})
  730. continue
  731. }
  732. for _, vpnIp := range relayHI.relayState.CopyRelayForIps() {
  733. rf := RelayFor{Error: nil}
  734. r, ok := relayHI.relayState.GetRelayForByIp(vpnIp)
  735. if ok {
  736. t := ""
  737. switch r.Type {
  738. case ForwardingType:
  739. t = "forwarding"
  740. case TerminalType:
  741. t = "terminal"
  742. default:
  743. t = "unknown"
  744. }
  745. s := ""
  746. switch r.State {
  747. case Requested:
  748. s = "requested"
  749. case Established:
  750. s = "established"
  751. default:
  752. s = "unknown"
  753. }
  754. rf.LocalIndex = r.LocalIndex
  755. rf.RemoteIndex = r.RemoteIndex
  756. rf.PeerIp = r.PeerIp
  757. rf.Type = t
  758. rf.State = s
  759. if rf.LocalIndex != k {
  760. rf.Error = fmt.Errorf("hostmap LocalIndex '%v' does not match RelayState LocalIndex", k)
  761. }
  762. }
  763. relayedHI := ifce.hostMap.QueryVpnIp(vpnIp)
  764. if relayedHI != nil {
  765. rf.RelayedThrough = append(rf.RelayedThrough, relayedHI.relayState.CopyRelayIps()...)
  766. }
  767. ro.RelayForIps = append(ro.RelayForIps, rf)
  768. }
  769. }
  770. err := enc.Encode(co)
  771. if err != nil {
  772. return err
  773. }
  774. return nil
  775. }
  776. func sshPrintTunnel(ifce *Interface, fs interface{}, a []string, w sshd.StringWriter) error {
  777. args, ok := fs.(*sshPrintTunnelFlags)
  778. if !ok {
  779. //TODO: error
  780. return nil
  781. }
  782. if len(a) == 0 {
  783. return w.WriteLine("No vpn ip was provided")
  784. }
  785. parsedIp := net.ParseIP(a[0])
  786. if parsedIp == nil {
  787. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  788. }
  789. vpnIp := iputil.Ip2VpnIp(parsedIp)
  790. if vpnIp == 0 {
  791. return w.WriteLine(fmt.Sprintf("The provided vpn ip could not be parsed: %s", a[0]))
  792. }
  793. hostInfo := ifce.hostMap.QueryVpnIp(vpnIp)
  794. if hostInfo == nil {
  795. return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn ip: %v", a[0]))
  796. }
  797. enc := json.NewEncoder(w.GetWriter())
  798. if args.Pretty {
  799. enc.SetIndent("", " ")
  800. }
  801. return enc.Encode(copyHostInfo(hostInfo, ifce.hostMap.preferredRanges))
  802. }
  803. func sshReload(c *config.C, w sshd.StringWriter) error {
  804. err := w.WriteLine("Reloading config")
  805. c.ReloadConfig()
  806. return err
  807. }