dnscmd.go 9.8 KB

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