dnscmd.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "crypto/ecdsa"
  19. "encoding/json"
  20. "fmt"
  21. "io/ioutil"
  22. "os"
  23. "path/filepath"
  24. "time"
  25. "github.com/ethereum/go-ethereum/accounts/keystore"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/console/prompt"
  28. "github.com/ethereum/go-ethereum/p2p/dnsdisc"
  29. "github.com/ethereum/go-ethereum/p2p/enode"
  30. "gopkg.in/urfave/cli.v1"
  31. )
  32. var (
  33. dnsCommand = cli.Command{
  34. Name: "dns",
  35. Usage: "DNS Discovery Commands",
  36. Subcommands: []cli.Command{
  37. dnsSyncCommand,
  38. dnsSignCommand,
  39. dnsTXTCommand,
  40. dnsCloudflareCommand,
  41. dnsRoute53Command,
  42. dnsRoute53NukeCommand,
  43. },
  44. }
  45. dnsSyncCommand = cli.Command{
  46. Name: "sync",
  47. Usage: "Download a DNS discovery tree",
  48. ArgsUsage: "<url> [ <directory> ]",
  49. Action: dnsSync,
  50. Flags: []cli.Flag{dnsTimeoutFlag},
  51. }
  52. dnsSignCommand = cli.Command{
  53. Name: "sign",
  54. Usage: "Sign a DNS discovery tree",
  55. ArgsUsage: "<tree-directory> <key-file>",
  56. Action: dnsSign,
  57. Flags: []cli.Flag{dnsDomainFlag, dnsSeqFlag},
  58. }
  59. dnsTXTCommand = cli.Command{
  60. Name: "to-txt",
  61. Usage: "Create a DNS TXT records for a discovery tree",
  62. ArgsUsage: "<tree-directory> <output-file>",
  63. Action: dnsToTXT,
  64. }
  65. dnsCloudflareCommand = cli.Command{
  66. Name: "to-cloudflare",
  67. Usage: "Deploy DNS TXT records to CloudFlare",
  68. ArgsUsage: "<tree-directory>",
  69. Action: dnsToCloudflare,
  70. Flags: []cli.Flag{cloudflareTokenFlag, cloudflareZoneIDFlag},
  71. }
  72. dnsRoute53Command = cli.Command{
  73. Name: "to-route53",
  74. Usage: "Deploy DNS TXT records to Amazon Route53",
  75. ArgsUsage: "<tree-directory>",
  76. Action: dnsToRoute53,
  77. Flags: []cli.Flag{
  78. route53AccessKeyFlag,
  79. route53AccessSecretFlag,
  80. route53ZoneIDFlag,
  81. route53RegionFlag,
  82. },
  83. }
  84. dnsRoute53NukeCommand = cli.Command{
  85. Name: "nuke-route53",
  86. Usage: "Deletes DNS TXT records of a subdomain on Amazon Route53",
  87. ArgsUsage: "<domain>",
  88. Action: dnsNukeRoute53,
  89. Flags: []cli.Flag{
  90. route53AccessKeyFlag,
  91. route53AccessSecretFlag,
  92. route53ZoneIDFlag,
  93. route53RegionFlag,
  94. },
  95. }
  96. )
  97. var (
  98. dnsTimeoutFlag = cli.DurationFlag{
  99. Name: "timeout",
  100. Usage: "Timeout for DNS lookups",
  101. }
  102. dnsDomainFlag = cli.StringFlag{
  103. Name: "domain",
  104. Usage: "Domain name of the tree",
  105. }
  106. dnsSeqFlag = cli.UintFlag{
  107. Name: "seq",
  108. Usage: "New sequence number of the tree",
  109. }
  110. )
  111. const (
  112. rootTTL = 30 * 60 // 30 min
  113. treeNodeTTL = 4 * 7 * 24 * 60 * 60 // 4 weeks
  114. )
  115. // dnsSync performs dnsSyncCommand.
  116. func dnsSync(ctx *cli.Context) error {
  117. var (
  118. c = dnsClient(ctx)
  119. url = ctx.Args().Get(0)
  120. outdir = ctx.Args().Get(1)
  121. )
  122. domain, _, err := dnsdisc.ParseURL(url)
  123. if err != nil {
  124. return err
  125. }
  126. if outdir == "" {
  127. outdir = domain
  128. }
  129. t, err := c.SyncTree(url)
  130. if err != nil {
  131. return err
  132. }
  133. def := treeToDefinition(url, t)
  134. def.Meta.LastModified = time.Now()
  135. writeTreeMetadata(outdir, def)
  136. writeTreeNodes(outdir, def)
  137. return nil
  138. }
  139. func dnsSign(ctx *cli.Context) error {
  140. if ctx.NArg() < 2 {
  141. return fmt.Errorf("need tree definition directory and key file as arguments")
  142. }
  143. var (
  144. defdir = ctx.Args().Get(0)
  145. keyfile = ctx.Args().Get(1)
  146. def = loadTreeDefinition(defdir)
  147. domain = directoryName(defdir)
  148. )
  149. if def.Meta.URL != "" {
  150. d, _, err := dnsdisc.ParseURL(def.Meta.URL)
  151. if err != nil {
  152. return fmt.Errorf("invalid 'url' field: %v", err)
  153. }
  154. domain = d
  155. }
  156. if ctx.IsSet(dnsDomainFlag.Name) {
  157. domain = ctx.String(dnsDomainFlag.Name)
  158. }
  159. if ctx.IsSet(dnsSeqFlag.Name) {
  160. def.Meta.Seq = ctx.Uint(dnsSeqFlag.Name)
  161. } else {
  162. def.Meta.Seq++ // Auto-bump sequence number if not supplied via flag.
  163. }
  164. t, err := dnsdisc.MakeTree(def.Meta.Seq, def.Nodes, def.Meta.Links)
  165. if err != nil {
  166. return err
  167. }
  168. key := loadSigningKey(keyfile)
  169. url, err := t.Sign(key, domain)
  170. if err != nil {
  171. return fmt.Errorf("can't sign: %v", err)
  172. }
  173. def = treeToDefinition(url, t)
  174. def.Meta.LastModified = time.Now()
  175. writeTreeMetadata(defdir, def)
  176. return nil
  177. }
  178. // directoryName returns the directory name of the given path.
  179. // For example, when dir is "foo/bar", it returns "bar".
  180. // When dir is ".", and the working directory is "example/foo", it returns "foo".
  181. func directoryName(dir string) string {
  182. abs, err := filepath.Abs(dir)
  183. if err != nil {
  184. exit(err)
  185. }
  186. return filepath.Base(abs)
  187. }
  188. // dnsToTXT performs dnsTXTCommand.
  189. func dnsToTXT(ctx *cli.Context) error {
  190. if ctx.NArg() < 1 {
  191. return fmt.Errorf("need tree definition directory as argument")
  192. }
  193. output := ctx.Args().Get(1)
  194. if output == "" {
  195. output = "-" // default to stdout
  196. }
  197. domain, t, err := loadTreeDefinitionForExport(ctx.Args().Get(0))
  198. if err != nil {
  199. return err
  200. }
  201. writeTXTJSON(output, t.ToTXT(domain))
  202. return nil
  203. }
  204. // dnsToCloudflare performs dnsCloudflareCommand.
  205. func dnsToCloudflare(ctx *cli.Context) error {
  206. if ctx.NArg() != 1 {
  207. return fmt.Errorf("need tree definition directory as argument")
  208. }
  209. domain, t, err := loadTreeDefinitionForExport(ctx.Args().Get(0))
  210. if err != nil {
  211. return err
  212. }
  213. client := newCloudflareClient(ctx)
  214. return client.deploy(domain, t)
  215. }
  216. // dnsToRoute53 performs dnsRoute53Command.
  217. func dnsToRoute53(ctx *cli.Context) error {
  218. if ctx.NArg() != 1 {
  219. return fmt.Errorf("need tree definition directory as argument")
  220. }
  221. domain, t, err := loadTreeDefinitionForExport(ctx.Args().Get(0))
  222. if err != nil {
  223. return err
  224. }
  225. client := newRoute53Client(ctx)
  226. return client.deploy(domain, t)
  227. }
  228. // dnsNukeRoute53 performs dnsRoute53NukeCommand.
  229. func dnsNukeRoute53(ctx *cli.Context) error {
  230. if ctx.NArg() != 1 {
  231. return fmt.Errorf("need domain name as argument")
  232. }
  233. client := newRoute53Client(ctx)
  234. return client.deleteDomain(ctx.Args().First())
  235. }
  236. // loadSigningKey loads a private key in Ethereum keystore format.
  237. func loadSigningKey(keyfile string) *ecdsa.PrivateKey {
  238. keyjson, err := ioutil.ReadFile(keyfile)
  239. if err != nil {
  240. exit(fmt.Errorf("failed to read the keyfile at '%s': %v", keyfile, err))
  241. }
  242. password, _ := prompt.Stdin.PromptPassword("Please enter the password for '" + keyfile + "': ")
  243. key, err := keystore.DecryptKey(keyjson, password)
  244. if err != nil {
  245. exit(fmt.Errorf("error decrypting key: %v", err))
  246. }
  247. return key.PrivateKey
  248. }
  249. // dnsClient configures the DNS discovery client from command line flags.
  250. func dnsClient(ctx *cli.Context) *dnsdisc.Client {
  251. var cfg dnsdisc.Config
  252. if commandHasFlag(ctx, dnsTimeoutFlag) {
  253. cfg.Timeout = ctx.Duration(dnsTimeoutFlag.Name)
  254. }
  255. return dnsdisc.NewClient(cfg)
  256. }
  257. // There are two file formats for DNS node trees on disk:
  258. //
  259. // The 'TXT' format is a single JSON file containing DNS TXT records
  260. // as a JSON object where the keys are names and the values are objects
  261. // containing the value of the record.
  262. //
  263. // The 'definition' format is a directory containing two files:
  264. //
  265. // enrtree-info.json -- contains sequence number & links to other trees
  266. // nodes.json -- contains the nodes as a JSON array.
  267. //
  268. // This format exists because it's convenient to edit. nodes.json can be generated
  269. // in multiple ways: it may be written by a DHT crawler or compiled by a human.
  270. type dnsDefinition struct {
  271. Meta dnsMetaJSON
  272. Nodes []*enode.Node
  273. }
  274. type dnsMetaJSON struct {
  275. URL string `json:"url,omitempty"`
  276. Seq uint `json:"seq"`
  277. Sig string `json:"signature,omitempty"`
  278. Links []string `json:"links"`
  279. LastModified time.Time `json:"lastModified"`
  280. }
  281. func treeToDefinition(url string, t *dnsdisc.Tree) *dnsDefinition {
  282. meta := dnsMetaJSON{
  283. URL: url,
  284. Seq: t.Seq(),
  285. Sig: t.Signature(),
  286. Links: t.Links(),
  287. }
  288. if meta.Links == nil {
  289. meta.Links = []string{}
  290. }
  291. return &dnsDefinition{Meta: meta, Nodes: t.Nodes()}
  292. }
  293. // loadTreeDefinition loads a directory in 'definition' format.
  294. func loadTreeDefinition(directory string) *dnsDefinition {
  295. metaFile, nodesFile := treeDefinitionFiles(directory)
  296. var def dnsDefinition
  297. err := common.LoadJSON(metaFile, &def.Meta)
  298. if err != nil && !os.IsNotExist(err) {
  299. exit(err)
  300. }
  301. if def.Meta.Links == nil {
  302. def.Meta.Links = []string{}
  303. }
  304. // Check link syntax.
  305. for _, link := range def.Meta.Links {
  306. if _, _, err := dnsdisc.ParseURL(link); err != nil {
  307. exit(fmt.Errorf("invalid link %q: %v", link, err))
  308. }
  309. }
  310. // Check/convert nodes.
  311. nodes := loadNodesJSON(nodesFile)
  312. if err := nodes.verify(); err != nil {
  313. exit(err)
  314. }
  315. def.Nodes = nodes.nodes()
  316. return &def
  317. }
  318. // loadTreeDefinitionForExport loads a DNS tree and ensures it is signed.
  319. func loadTreeDefinitionForExport(dir string) (domain string, t *dnsdisc.Tree, err error) {
  320. metaFile, _ := treeDefinitionFiles(dir)
  321. def := loadTreeDefinition(dir)
  322. if def.Meta.URL == "" {
  323. return "", nil, fmt.Errorf("missing 'url' field in %v", metaFile)
  324. }
  325. domain, pubkey, err := dnsdisc.ParseURL(def.Meta.URL)
  326. if err != nil {
  327. return "", nil, fmt.Errorf("invalid 'url' field in %v: %v", metaFile, err)
  328. }
  329. if t, err = dnsdisc.MakeTree(def.Meta.Seq, def.Nodes, def.Meta.Links); err != nil {
  330. return "", nil, err
  331. }
  332. if err := ensureValidTreeSignature(t, pubkey, def.Meta.Sig); err != nil {
  333. return "", nil, err
  334. }
  335. return domain, t, nil
  336. }
  337. // ensureValidTreeSignature checks that sig is valid for tree and assigns it as the
  338. // tree's signature if valid.
  339. func ensureValidTreeSignature(t *dnsdisc.Tree, pubkey *ecdsa.PublicKey, sig string) error {
  340. if sig == "" {
  341. return fmt.Errorf("missing signature, run 'devp2p dns sign' first")
  342. }
  343. if err := t.SetSignature(pubkey, sig); err != nil {
  344. return fmt.Errorf("invalid signature on tree, run 'devp2p dns sign' to update it")
  345. }
  346. return nil
  347. }
  348. // writeTreeMetadata writes a DNS node tree metadata file to the given directory.
  349. func writeTreeMetadata(directory string, def *dnsDefinition) {
  350. metaJSON, err := json.MarshalIndent(&def.Meta, "", jsonIndent)
  351. if err != nil {
  352. exit(err)
  353. }
  354. if err := os.Mkdir(directory, 0744); err != nil && !os.IsExist(err) {
  355. exit(err)
  356. }
  357. metaFile, _ := treeDefinitionFiles(directory)
  358. if err := ioutil.WriteFile(metaFile, metaJSON, 0644); err != nil {
  359. exit(err)
  360. }
  361. }
  362. func writeTreeNodes(directory string, def *dnsDefinition) {
  363. ns := make(nodeSet, len(def.Nodes))
  364. ns.add(def.Nodes...)
  365. _, nodesFile := treeDefinitionFiles(directory)
  366. writeNodesJSON(nodesFile, ns)
  367. }
  368. func treeDefinitionFiles(directory string) (string, string) {
  369. meta := filepath.Join(directory, "enrtree-info.json")
  370. nodes := filepath.Join(directory, "nodes.json")
  371. return meta, nodes
  372. }
  373. // writeTXTJSON writes TXT records in JSON format.
  374. func writeTXTJSON(file string, txt map[string]string) {
  375. txtJSON, err := json.MarshalIndent(txt, "", jsonIndent)
  376. if err != nil {
  377. exit(err)
  378. }
  379. if file == "-" {
  380. os.Stdout.Write(txtJSON)
  381. fmt.Println()
  382. return
  383. }
  384. if err := ioutil.WriteFile(file, txtJSON, 0644); err != nil {
  385. exit(err)
  386. }
  387. }