dnscmd.go 10 KB

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