ssh.go 24 KB

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