dnscmd.go 9.7 KB

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