dnscmd.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. return dnsdisc.NewClient(cfg)
  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. // writeTreeMetadata writes a DNS node tree metadata file to the given directory.
  296. func writeTreeMetadata(directory string, def *dnsDefinition) {
  297. metaJSON, err := json.MarshalIndent(&def.Meta, "", jsonIndent)
  298. if err != nil {
  299. exit(err)
  300. }
  301. if err := os.Mkdir(directory, 0744); err != nil && !os.IsExist(err) {
  302. exit(err)
  303. }
  304. metaFile, _ := treeDefinitionFiles(directory)
  305. if err := ioutil.WriteFile(metaFile, metaJSON, 0644); err != nil {
  306. exit(err)
  307. }
  308. }
  309. func writeTreeNodes(directory string, def *dnsDefinition) {
  310. ns := make(nodeSet, len(def.Nodes))
  311. ns.add(def.Nodes...)
  312. _, nodesFile := treeDefinitionFiles(directory)
  313. writeNodesJSON(nodesFile, ns)
  314. }
  315. func treeDefinitionFiles(directory string) (string, string) {
  316. meta := filepath.Join(directory, "enrtree-info.json")
  317. nodes := filepath.Join(directory, "nodes.json")
  318. return meta, nodes
  319. }
  320. // writeTXTJSON writes TXT records in JSON format.
  321. func writeTXTJSON(file string, txt map[string]string) {
  322. txtJSON, err := json.MarshalIndent(txt, "", jsonIndent)
  323. if err != nil {
  324. exit(err)
  325. }
  326. if file == "-" {
  327. os.Stdout.Write(txtJSON)
  328. fmt.Println()
  329. return
  330. }
  331. if err := ioutil.WriteFile(file, txtJSON, 0644); err != nil {
  332. exit(err)
  333. }
  334. }