dnscmd.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. cli "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. },
  43. }
  44. dnsSyncCommand = cli.Command{
  45. Name: "sync",
  46. Usage: "Download a DNS discovery tree",
  47. ArgsUsage: "<url> [ <directory> ]",
  48. Action: dnsSync,
  49. Flags: []cli.Flag{dnsTimeoutFlag},
  50. }
  51. dnsSignCommand = cli.Command{
  52. Name: "sign",
  53. Usage: "Sign a DNS discovery tree",
  54. ArgsUsage: "<tree-directory> <key-file>",
  55. Action: dnsSign,
  56. Flags: []cli.Flag{dnsDomainFlag, dnsSeqFlag},
  57. }
  58. dnsTXTCommand = cli.Command{
  59. Name: "to-txt",
  60. Usage: "Create a DNS TXT records for a discovery tree",
  61. ArgsUsage: "<tree-directory> <output-file>",
  62. Action: dnsToTXT,
  63. }
  64. dnsCloudflareCommand = cli.Command{
  65. Name: "to-cloudflare",
  66. Usage: "Deploy DNS TXT records to CloudFlare",
  67. ArgsUsage: "<tree-directory>",
  68. Action: dnsToCloudflare,
  69. Flags: []cli.Flag{cloudflareTokenFlag, cloudflareZoneIDFlag},
  70. }
  71. dnsRoute53Command = cli.Command{
  72. Name: "to-route53",
  73. Usage: "Deploy DNS TXT records to Amazon Route53",
  74. ArgsUsage: "<tree-directory>",
  75. Action: dnsToRoute53,
  76. Flags: []cli.Flag{route53AccessKeyFlag, route53AccessSecretFlag, route53ZoneIDFlag},
  77. }
  78. )
  79. var (
  80. dnsTimeoutFlag = cli.DurationFlag{
  81. Name: "timeout",
  82. Usage: "Timeout for DNS lookups",
  83. }
  84. dnsDomainFlag = cli.StringFlag{
  85. Name: "domain",
  86. Usage: "Domain name of the tree",
  87. }
  88. dnsSeqFlag = cli.UintFlag{
  89. Name: "seq",
  90. Usage: "New sequence number of the tree",
  91. }
  92. )
  93. const (
  94. rootTTL = 30 * 60 // 30 min
  95. treeNodeTTL = 4 * 7 * 24 * 60 * 60 // 4 weeks
  96. )
  97. // dnsSync performs dnsSyncCommand.
  98. func dnsSync(ctx *cli.Context) error {
  99. var (
  100. c = dnsClient(ctx)
  101. url = ctx.Args().Get(0)
  102. outdir = ctx.Args().Get(1)
  103. )
  104. domain, _, err := dnsdisc.ParseURL(url)
  105. if err != nil {
  106. return err
  107. }
  108. if outdir == "" {
  109. outdir = domain
  110. }
  111. t, err := c.SyncTree(url)
  112. if err != nil {
  113. return err
  114. }
  115. def := treeToDefinition(url, t)
  116. def.Meta.LastModified = time.Now()
  117. writeTreeMetadata(outdir, def)
  118. writeTreeNodes(outdir, def)
  119. return nil
  120. }
  121. func dnsSign(ctx *cli.Context) error {
  122. if ctx.NArg() < 2 {
  123. return fmt.Errorf("need tree definition directory and key file as arguments")
  124. }
  125. var (
  126. defdir = ctx.Args().Get(0)
  127. keyfile = ctx.Args().Get(1)
  128. def = loadTreeDefinition(defdir)
  129. domain = directoryName(defdir)
  130. )
  131. if def.Meta.URL != "" {
  132. d, _, err := dnsdisc.ParseURL(def.Meta.URL)
  133. if err != nil {
  134. return fmt.Errorf("invalid 'url' field: %v", err)
  135. }
  136. domain = d
  137. }
  138. if ctx.IsSet(dnsDomainFlag.Name) {
  139. domain = ctx.String(dnsDomainFlag.Name)
  140. }
  141. if ctx.IsSet(dnsSeqFlag.Name) {
  142. def.Meta.Seq = ctx.Uint(dnsSeqFlag.Name)
  143. } else {
  144. def.Meta.Seq++ // Auto-bump sequence number if not supplied via flag.
  145. }
  146. t, err := dnsdisc.MakeTree(def.Meta.Seq, def.Nodes, def.Meta.Links)
  147. if err != nil {
  148. return err
  149. }
  150. key := loadSigningKey(keyfile)
  151. url, err := t.Sign(key, domain)
  152. if err != nil {
  153. return fmt.Errorf("can't sign: %v", err)
  154. }
  155. def = treeToDefinition(url, t)
  156. def.Meta.LastModified = time.Now()
  157. writeTreeMetadata(defdir, def)
  158. return nil
  159. }
  160. func directoryName(dir string) string {
  161. abs, err := filepath.Abs(dir)
  162. if err != nil {
  163. exit(err)
  164. }
  165. return filepath.Base(abs)
  166. }
  167. // dnsToTXT peforms dnsTXTCommand.
  168. func dnsToTXT(ctx *cli.Context) error {
  169. if ctx.NArg() < 1 {
  170. return fmt.Errorf("need tree definition directory as argument")
  171. }
  172. output := ctx.Args().Get(1)
  173. if output == "" {
  174. output = "-" // default to stdout
  175. }
  176. domain, t, err := loadTreeDefinitionForExport(ctx.Args().Get(0))
  177. if err != nil {
  178. return err
  179. }
  180. writeTXTJSON(output, t.ToTXT(domain))
  181. return nil
  182. }
  183. // dnsToCloudflare peforms dnsCloudflareCommand.
  184. func dnsToCloudflare(ctx *cli.Context) error {
  185. if ctx.NArg() < 1 {
  186. return fmt.Errorf("need tree definition directory as argument")
  187. }
  188. domain, t, err := loadTreeDefinitionForExport(ctx.Args().Get(0))
  189. if err != nil {
  190. return err
  191. }
  192. client := newCloudflareClient(ctx)
  193. return client.deploy(domain, t)
  194. }
  195. // dnsToRoute53 peforms dnsRoute53Command.
  196. func dnsToRoute53(ctx *cli.Context) error {
  197. if ctx.NArg() < 1 {
  198. return fmt.Errorf("need tree definition directory as argument")
  199. }
  200. domain, t, err := loadTreeDefinitionForExport(ctx.Args().Get(0))
  201. if err != nil {
  202. return err
  203. }
  204. client := newRoute53Client(ctx)
  205. return client.deploy(domain, t)
  206. }
  207. // loadSigningKey loads a private key in Ethereum keystore format.
  208. func loadSigningKey(keyfile string) *ecdsa.PrivateKey {
  209. keyjson, err := ioutil.ReadFile(keyfile)
  210. if err != nil {
  211. exit(fmt.Errorf("failed to read the keyfile at '%s': %v", keyfile, err))
  212. }
  213. password, _ := prompt.Stdin.PromptPassword("Please enter the password for '" + keyfile + "': ")
  214. key, err := keystore.DecryptKey(keyjson, password)
  215. if err != nil {
  216. exit(fmt.Errorf("error decrypting key: %v", err))
  217. }
  218. return key.PrivateKey
  219. }
  220. // dnsClient configures the DNS discovery client from command line flags.
  221. func dnsClient(ctx *cli.Context) *dnsdisc.Client {
  222. var cfg dnsdisc.Config
  223. if commandHasFlag(ctx, dnsTimeoutFlag) {
  224. cfg.Timeout = ctx.Duration(dnsTimeoutFlag.Name)
  225. }
  226. return dnsdisc.NewClient(cfg)
  227. }
  228. // There are two file formats for DNS node trees on disk:
  229. //
  230. // The 'TXT' format is a single JSON file containing DNS TXT records
  231. // as a JSON object where the keys are names and the values are objects
  232. // containing the value of the record.
  233. //
  234. // The 'definition' format is a directory containing two files:
  235. //
  236. // enrtree-info.json -- contains sequence number & links to other trees
  237. // nodes.json -- contains the nodes as a JSON array.
  238. //
  239. // This format exists because it's convenient to edit. nodes.json can be generated
  240. // in multiple ways: it may be written by a DHT crawler or compiled by a human.
  241. type dnsDefinition struct {
  242. Meta dnsMetaJSON
  243. Nodes []*enode.Node
  244. }
  245. type dnsMetaJSON struct {
  246. URL string `json:"url,omitempty"`
  247. Seq uint `json:"seq"`
  248. Sig string `json:"signature,omitempty"`
  249. Links []string `json:"links"`
  250. LastModified time.Time `json:"lastModified"`
  251. }
  252. func treeToDefinition(url string, t *dnsdisc.Tree) *dnsDefinition {
  253. meta := dnsMetaJSON{
  254. URL: url,
  255. Seq: t.Seq(),
  256. Sig: t.Signature(),
  257. Links: t.Links(),
  258. }
  259. if meta.Links == nil {
  260. meta.Links = []string{}
  261. }
  262. return &dnsDefinition{Meta: meta, Nodes: t.Nodes()}
  263. }
  264. // loadTreeDefinition loads a directory in 'definition' format.
  265. func loadTreeDefinition(directory string) *dnsDefinition {
  266. metaFile, nodesFile := treeDefinitionFiles(directory)
  267. var def dnsDefinition
  268. err := common.LoadJSON(metaFile, &def.Meta)
  269. if err != nil && !os.IsNotExist(err) {
  270. exit(err)
  271. }
  272. if def.Meta.Links == nil {
  273. def.Meta.Links = []string{}
  274. }
  275. // Check link syntax.
  276. for _, link := range def.Meta.Links {
  277. if _, _, err := dnsdisc.ParseURL(link); err != nil {
  278. exit(fmt.Errorf("invalid link %q: %v", link, err))
  279. }
  280. }
  281. // Check/convert nodes.
  282. nodes := loadNodesJSON(nodesFile)
  283. if err := nodes.verify(); err != nil {
  284. exit(err)
  285. }
  286. def.Nodes = nodes.nodes()
  287. return &def
  288. }
  289. // loadTreeDefinitionForExport loads a DNS tree and ensures it is signed.
  290. func loadTreeDefinitionForExport(dir string) (domain string, t *dnsdisc.Tree, err error) {
  291. metaFile, _ := treeDefinitionFiles(dir)
  292. def := loadTreeDefinition(dir)
  293. if def.Meta.URL == "" {
  294. return "", nil, fmt.Errorf("missing 'url' field in %v", metaFile)
  295. }
  296. domain, pubkey, err := dnsdisc.ParseURL(def.Meta.URL)
  297. if err != nil {
  298. return "", nil, fmt.Errorf("invalid 'url' field in %v: %v", metaFile, err)
  299. }
  300. if t, err = dnsdisc.MakeTree(def.Meta.Seq, def.Nodes, def.Meta.Links); err != nil {
  301. return "", nil, err
  302. }
  303. if err := ensureValidTreeSignature(t, pubkey, def.Meta.Sig); err != nil {
  304. return "", nil, err
  305. }
  306. return domain, t, nil
  307. }
  308. // ensureValidTreeSignature checks that sig is valid for tree and assigns it as the
  309. // tree's signature if valid.
  310. func ensureValidTreeSignature(t *dnsdisc.Tree, pubkey *ecdsa.PublicKey, sig string) error {
  311. if sig == "" {
  312. return fmt.Errorf("missing signature, run 'devp2p dns sign' first")
  313. }
  314. if err := t.SetSignature(pubkey, sig); err != nil {
  315. return fmt.Errorf("invalid signature on tree, run 'devp2p dns sign' to update it")
  316. }
  317. return nil
  318. }
  319. // writeTreeMetadata writes a DNS node tree metadata file to the given directory.
  320. func writeTreeMetadata(directory string, def *dnsDefinition) {
  321. metaJSON, err := json.MarshalIndent(&def.Meta, "", jsonIndent)
  322. if err != nil {
  323. exit(err)
  324. }
  325. if err := os.Mkdir(directory, 0744); err != nil && !os.IsExist(err) {
  326. exit(err)
  327. }
  328. metaFile, _ := treeDefinitionFiles(directory)
  329. if err := ioutil.WriteFile(metaFile, metaJSON, 0644); err != nil {
  330. exit(err)
  331. }
  332. }
  333. func writeTreeNodes(directory string, def *dnsDefinition) {
  334. ns := make(nodeSet, len(def.Nodes))
  335. ns.add(def.Nodes...)
  336. _, nodesFile := treeDefinitionFiles(directory)
  337. writeNodesJSON(nodesFile, ns)
  338. }
  339. func treeDefinitionFiles(directory string) (string, string) {
  340. meta := filepath.Join(directory, "enrtree-info.json")
  341. nodes := filepath.Join(directory, "nodes.json")
  342. return meta, nodes
  343. }
  344. // writeTXTJSON writes TXT records in JSON format.
  345. func writeTXTJSON(file string, txt map[string]string) {
  346. txtJSON, err := json.MarshalIndent(txt, "", jsonIndent)
  347. if err != nil {
  348. exit(err)
  349. }
  350. if file == "-" {
  351. os.Stdout.Write(txtJSON)
  352. fmt.Println()
  353. return
  354. }
  355. if err := ioutil.WriteFile(file, txtJSON, 0644); err != nil {
  356. exit(err)
  357. }
  358. }