main.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  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. "bufio"
  19. "context"
  20. "crypto/rand"
  21. "crypto/sha256"
  22. "encoding/hex"
  23. "encoding/json"
  24. "fmt"
  25. "io"
  26. "io/ioutil"
  27. "math/big"
  28. "os"
  29. "os/signal"
  30. "os/user"
  31. "path/filepath"
  32. "runtime"
  33. "strings"
  34. "time"
  35. "github.com/ethereum/go-ethereum/accounts"
  36. "github.com/ethereum/go-ethereum/accounts/keystore"
  37. "github.com/ethereum/go-ethereum/cmd/utils"
  38. "github.com/ethereum/go-ethereum/common"
  39. "github.com/ethereum/go-ethereum/common/hexutil"
  40. "github.com/ethereum/go-ethereum/console"
  41. "github.com/ethereum/go-ethereum/core/types"
  42. "github.com/ethereum/go-ethereum/crypto"
  43. "github.com/ethereum/go-ethereum/internal/ethapi"
  44. "github.com/ethereum/go-ethereum/log"
  45. "github.com/ethereum/go-ethereum/node"
  46. "github.com/ethereum/go-ethereum/params"
  47. "github.com/ethereum/go-ethereum/rlp"
  48. "github.com/ethereum/go-ethereum/rpc"
  49. "github.com/ethereum/go-ethereum/signer/core"
  50. "github.com/ethereum/go-ethereum/signer/fourbyte"
  51. "github.com/ethereum/go-ethereum/signer/rules"
  52. "github.com/ethereum/go-ethereum/signer/storage"
  53. "gopkg.in/urfave/cli.v1"
  54. )
  55. const legalWarning = `
  56. WARNING!
  57. Clef is an account management tool. It may, like any software, contain bugs.
  58. Please take care to
  59. - backup your keystore files,
  60. - verify that the keystore(s) can be opened with your password.
  61. Clef is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
  62. without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  63. PURPOSE. See the GNU General Public License for more details.
  64. `
  65. var (
  66. logLevelFlag = cli.IntFlag{
  67. Name: "loglevel",
  68. Value: 4,
  69. Usage: "log level to emit to the screen",
  70. }
  71. advancedMode = cli.BoolFlag{
  72. Name: "advanced",
  73. Usage: "If enabled, issues warnings instead of rejections for suspicious requests. Default off",
  74. }
  75. keystoreFlag = cli.StringFlag{
  76. Name: "keystore",
  77. Value: filepath.Join(node.DefaultDataDir(), "keystore"),
  78. Usage: "Directory for the keystore",
  79. }
  80. configdirFlag = cli.StringFlag{
  81. Name: "configdir",
  82. Value: DefaultConfigDir(),
  83. Usage: "Directory for Clef configuration",
  84. }
  85. chainIdFlag = cli.Int64Flag{
  86. Name: "chainid",
  87. Value: params.MainnetChainConfig.ChainID.Int64(),
  88. Usage: "Chain id to use for signing (1=mainnet, 3=Ropsten, 4=Rinkeby, 5=Goerli)",
  89. }
  90. rpcPortFlag = cli.IntFlag{
  91. Name: "rpcport",
  92. Usage: "HTTP-RPC server listening port",
  93. Value: node.DefaultHTTPPort + 5,
  94. }
  95. signerSecretFlag = cli.StringFlag{
  96. Name: "signersecret",
  97. Usage: "A file containing the (encrypted) master seed to encrypt Clef data, e.g. keystore credentials and ruleset hash",
  98. }
  99. customDBFlag = cli.StringFlag{
  100. Name: "4bytedb-custom",
  101. Usage: "File used for writing new 4byte-identifiers submitted via API",
  102. Value: "./4byte-custom.json",
  103. }
  104. auditLogFlag = cli.StringFlag{
  105. Name: "auditlog",
  106. Usage: "File used to emit audit logs. Set to \"\" to disable",
  107. Value: "audit.log",
  108. }
  109. ruleFlag = cli.StringFlag{
  110. Name: "rules",
  111. Usage: "Path to the rule file to auto-authorize requests with",
  112. }
  113. stdiouiFlag = cli.BoolFlag{
  114. Name: "stdio-ui",
  115. Usage: "Use STDIN/STDOUT as a channel for an external UI. " +
  116. "This means that an STDIN/STDOUT is used for RPC-communication with a e.g. a graphical user " +
  117. "interface, and can be used when Clef is started by an external process.",
  118. }
  119. testFlag = cli.BoolFlag{
  120. Name: "stdio-ui-test",
  121. Usage: "Mechanism to test interface between Clef and UI. Requires 'stdio-ui'.",
  122. }
  123. app = cli.NewApp()
  124. initCommand = cli.Command{
  125. Action: utils.MigrateFlags(initializeSecrets),
  126. Name: "init",
  127. Usage: "Initialize the signer, generate secret storage",
  128. ArgsUsage: "",
  129. Flags: []cli.Flag{
  130. logLevelFlag,
  131. configdirFlag,
  132. },
  133. Description: `
  134. The init command generates a master seed which Clef can use to store credentials and data needed for
  135. the rule-engine to work.`,
  136. }
  137. attestCommand = cli.Command{
  138. Action: utils.MigrateFlags(attestFile),
  139. Name: "attest",
  140. Usage: "Attest that a js-file is to be used",
  141. ArgsUsage: "<sha256sum>",
  142. Flags: []cli.Flag{
  143. logLevelFlag,
  144. configdirFlag,
  145. signerSecretFlag,
  146. },
  147. Description: `
  148. The attest command stores the sha256 of the rule.js-file that you want to use for automatic processing of
  149. incoming requests.
  150. Whenever you make an edit to the rule file, you need to use attestation to tell
  151. Clef that the file is 'safe' to execute.`,
  152. }
  153. setCredentialCommand = cli.Command{
  154. Action: utils.MigrateFlags(setCredential),
  155. Name: "setpw",
  156. Usage: "Store a credential for a keystore file",
  157. ArgsUsage: "<address>",
  158. Flags: []cli.Flag{
  159. logLevelFlag,
  160. configdirFlag,
  161. signerSecretFlag,
  162. },
  163. Description: `
  164. The setpw command stores a password for a given address (keyfile).
  165. `}
  166. delCredentialCommand = cli.Command{
  167. Action: utils.MigrateFlags(removeCredential),
  168. Name: "delpw",
  169. Usage: "Remove a credential for a keystore file",
  170. ArgsUsage: "<address>",
  171. Flags: []cli.Flag{
  172. logLevelFlag,
  173. configdirFlag,
  174. signerSecretFlag,
  175. },
  176. Description: `
  177. The delpw command removes a password for a given address (keyfile).
  178. `}
  179. gendocCommand = cli.Command{
  180. Action: GenDoc,
  181. Name: "gendoc",
  182. Usage: "Generate documentation about json-rpc format",
  183. Description: `
  184. The gendoc generates example structures of the json-rpc communication types.
  185. `}
  186. )
  187. func init() {
  188. app.Name = "Clef"
  189. app.Usage = "Manage Ethereum account operations"
  190. app.Flags = []cli.Flag{
  191. logLevelFlag,
  192. keystoreFlag,
  193. configdirFlag,
  194. chainIdFlag,
  195. utils.LightKDFFlag,
  196. utils.NoUSBFlag,
  197. utils.SmartCardDaemonPathFlag,
  198. utils.RPCListenAddrFlag,
  199. utils.RPCVirtualHostsFlag,
  200. utils.IPCDisabledFlag,
  201. utils.IPCPathFlag,
  202. utils.RPCEnabledFlag,
  203. rpcPortFlag,
  204. signerSecretFlag,
  205. customDBFlag,
  206. auditLogFlag,
  207. ruleFlag,
  208. stdiouiFlag,
  209. testFlag,
  210. advancedMode,
  211. }
  212. app.Action = signer
  213. app.Commands = []cli.Command{initCommand, attestCommand, setCredentialCommand, delCredentialCommand, gendocCommand}
  214. }
  215. func main() {
  216. if err := app.Run(os.Args); err != nil {
  217. fmt.Fprintln(os.Stderr, err)
  218. os.Exit(1)
  219. }
  220. }
  221. func initializeSecrets(c *cli.Context) error {
  222. // Get past the legal message
  223. if err := initialize(c); err != nil {
  224. return err
  225. }
  226. // Ensure the master key does not yet exist, we're not willing to overwrite
  227. configDir := c.GlobalString(configdirFlag.Name)
  228. if err := os.Mkdir(configDir, 0700); err != nil && !os.IsExist(err) {
  229. return err
  230. }
  231. location := filepath.Join(configDir, "masterseed.json")
  232. if _, err := os.Stat(location); err == nil {
  233. return fmt.Errorf("master key %v already exists, will not overwrite", location)
  234. }
  235. // Key file does not exist yet, generate a new one and encrypt it
  236. masterSeed := make([]byte, 256)
  237. num, err := io.ReadFull(rand.Reader, masterSeed)
  238. if err != nil {
  239. return err
  240. }
  241. if num != len(masterSeed) {
  242. return fmt.Errorf("failed to read enough random")
  243. }
  244. n, p := keystore.StandardScryptN, keystore.StandardScryptP
  245. if c.GlobalBool(utils.LightKDFFlag.Name) {
  246. n, p = keystore.LightScryptN, keystore.LightScryptP
  247. }
  248. text := "The master seed of clef will be locked with a password.\nPlease specify a password. Do not forget this password!"
  249. var password string
  250. for {
  251. password = getPassPhrase(text, true)
  252. if err := core.ValidatePasswordFormat(password); err != nil {
  253. fmt.Printf("invalid password: %v\n", err)
  254. } else {
  255. fmt.Println()
  256. break
  257. }
  258. }
  259. cipherSeed, err := encryptSeed(masterSeed, []byte(password), n, p)
  260. if err != nil {
  261. return fmt.Errorf("failed to encrypt master seed: %v", err)
  262. }
  263. // Double check the master key path to ensure nothing wrote there in between
  264. if err = os.Mkdir(configDir, 0700); err != nil && !os.IsExist(err) {
  265. return err
  266. }
  267. if _, err := os.Stat(location); err == nil {
  268. return fmt.Errorf("master key %v already exists, will not overwrite", location)
  269. }
  270. // Write the file and print the usual warning message
  271. if err = ioutil.WriteFile(location, cipherSeed, 0400); err != nil {
  272. return err
  273. }
  274. fmt.Printf("A master seed has been generated into %s\n", location)
  275. fmt.Printf(`
  276. This is required to be able to store credentials, such as:
  277. * Passwords for keystores (used by rule engine)
  278. * Storage for JavaScript auto-signing rules
  279. * Hash of JavaScript rule-file
  280. You should treat 'masterseed.json' with utmost secrecy and make a backup of it!
  281. * The password is necessary but not enough, you need to back up the master seed too!
  282. * The master seed does not contain your accounts, those need to be backed up separately!
  283. `)
  284. return nil
  285. }
  286. func attestFile(ctx *cli.Context) error {
  287. if len(ctx.Args()) < 1 {
  288. utils.Fatalf("This command requires an argument.")
  289. }
  290. if err := initialize(ctx); err != nil {
  291. return err
  292. }
  293. stretchedKey, err := readMasterKey(ctx, nil)
  294. if err != nil {
  295. utils.Fatalf(err.Error())
  296. }
  297. configDir := ctx.GlobalString(configdirFlag.Name)
  298. vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), stretchedKey)[:10]))
  299. confKey := crypto.Keccak256([]byte("config"), stretchedKey)
  300. // Initialize the encrypted storages
  301. configStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "config.json"), confKey)
  302. val := ctx.Args().First()
  303. configStorage.Put("ruleset_sha256", val)
  304. log.Info("Ruleset attestation updated", "sha256", val)
  305. return nil
  306. }
  307. func setCredential(ctx *cli.Context) error {
  308. if len(ctx.Args()) < 1 {
  309. utils.Fatalf("This command requires an address to be passed as an argument")
  310. }
  311. if err := initialize(ctx); err != nil {
  312. return err
  313. }
  314. addr := ctx.Args().First()
  315. if !common.IsHexAddress(addr) {
  316. utils.Fatalf("Invalid address specified: %s", addr)
  317. }
  318. address := common.HexToAddress(addr)
  319. password := getPassPhrase("Please enter a passphrase to store for this address:", true)
  320. fmt.Println()
  321. stretchedKey, err := readMasterKey(ctx, nil)
  322. if err != nil {
  323. utils.Fatalf(err.Error())
  324. }
  325. configDir := ctx.GlobalString(configdirFlag.Name)
  326. vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), stretchedKey)[:10]))
  327. pwkey := crypto.Keccak256([]byte("credentials"), stretchedKey)
  328. pwStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "credentials.json"), pwkey)
  329. pwStorage.Put(address.Hex(), password)
  330. log.Info("Credential store updated", "set", address)
  331. return nil
  332. }
  333. func removeCredential(ctx *cli.Context) error {
  334. if len(ctx.Args()) < 1 {
  335. utils.Fatalf("This command requires an address to be passed as an argument")
  336. }
  337. if err := initialize(ctx); err != nil {
  338. return err
  339. }
  340. addr := ctx.Args().First()
  341. if !common.IsHexAddress(addr) {
  342. utils.Fatalf("Invalid address specified: %s", addr)
  343. }
  344. address := common.HexToAddress(addr)
  345. stretchedKey, err := readMasterKey(ctx, nil)
  346. if err != nil {
  347. utils.Fatalf(err.Error())
  348. }
  349. configDir := ctx.GlobalString(configdirFlag.Name)
  350. vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), stretchedKey)[:10]))
  351. pwkey := crypto.Keccak256([]byte("credentials"), stretchedKey)
  352. pwStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "credentials.json"), pwkey)
  353. pwStorage.Del(address.Hex())
  354. log.Info("Credential store updated", "unset", address)
  355. return nil
  356. }
  357. func initialize(c *cli.Context) error {
  358. // Set up the logger to print everything
  359. logOutput := os.Stdout
  360. if c.GlobalBool(stdiouiFlag.Name) {
  361. logOutput = os.Stderr
  362. // If using the stdioui, we can't do the 'confirm'-flow
  363. fmt.Fprintf(logOutput, legalWarning)
  364. } else {
  365. if !confirm(legalWarning) {
  366. return fmt.Errorf("aborted by user")
  367. }
  368. fmt.Println()
  369. }
  370. log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(c.Int(logLevelFlag.Name)), log.StreamHandler(logOutput, log.TerminalFormat(true))))
  371. return nil
  372. }
  373. func signer(c *cli.Context) error {
  374. // If we have some unrecognized command, bail out
  375. if args := c.Args(); len(args) > 0 {
  376. return fmt.Errorf("invalid command: %q", args[0])
  377. }
  378. if err := initialize(c); err != nil {
  379. return err
  380. }
  381. var (
  382. ui core.UIClientAPI
  383. )
  384. if c.GlobalBool(stdiouiFlag.Name) {
  385. log.Info("Using stdin/stdout as UI-channel")
  386. ui = core.NewStdIOUI()
  387. } else {
  388. log.Info("Using CLI as UI-channel")
  389. ui = core.NewCommandlineUI()
  390. }
  391. // 4bytedb data
  392. fourByteLocal := c.GlobalString(customDBFlag.Name)
  393. db, err := fourbyte.NewWithFile(fourByteLocal)
  394. if err != nil {
  395. utils.Fatalf(err.Error())
  396. }
  397. embeds, locals := db.Size()
  398. log.Info("Loaded 4byte database", "embeds", embeds, "locals", locals, "local", fourByteLocal)
  399. var (
  400. api core.ExternalAPI
  401. pwStorage storage.Storage = &storage.NoStorage{}
  402. )
  403. configDir := c.GlobalString(configdirFlag.Name)
  404. if stretchedKey, err := readMasterKey(c, ui); err != nil {
  405. log.Warn("Failed to open master, rules disabled", "err", err)
  406. } else {
  407. vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), stretchedKey)[:10]))
  408. // Generate domain specific keys
  409. pwkey := crypto.Keccak256([]byte("credentials"), stretchedKey)
  410. jskey := crypto.Keccak256([]byte("jsstorage"), stretchedKey)
  411. confkey := crypto.Keccak256([]byte("config"), stretchedKey)
  412. // Initialize the encrypted storages
  413. pwStorage = storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "credentials.json"), pwkey)
  414. jsStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "jsstorage.json"), jskey)
  415. configStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "config.json"), confkey)
  416. // Do we have a rule-file?
  417. if ruleFile := c.GlobalString(ruleFlag.Name); ruleFile != "" {
  418. ruleJS, err := ioutil.ReadFile(ruleFile)
  419. if err != nil {
  420. log.Warn("Could not load rules, disabling", "file", ruleFile, "err", err)
  421. } else {
  422. shasum := sha256.Sum256(ruleJS)
  423. foundShaSum := hex.EncodeToString(shasum[:])
  424. storedShasum, _ := configStorage.Get("ruleset_sha256")
  425. if storedShasum != foundShaSum {
  426. log.Warn("Rule hash not attested, disabling", "hash", foundShaSum, "attested", storedShasum)
  427. } else {
  428. // Initialize rules
  429. ruleEngine, err := rules.NewRuleEvaluator(ui, jsStorage)
  430. if err != nil {
  431. utils.Fatalf(err.Error())
  432. }
  433. ruleEngine.Init(string(ruleJS))
  434. ui = ruleEngine
  435. log.Info("Rule engine configured", "file", c.String(ruleFlag.Name))
  436. }
  437. }
  438. }
  439. }
  440. var (
  441. chainId = c.GlobalInt64(chainIdFlag.Name)
  442. ksLoc = c.GlobalString(keystoreFlag.Name)
  443. lightKdf = c.GlobalBool(utils.LightKDFFlag.Name)
  444. advanced = c.GlobalBool(advancedMode.Name)
  445. nousb = c.GlobalBool(utils.NoUSBFlag.Name)
  446. scpath = c.GlobalString(utils.SmartCardDaemonPathFlag.Name)
  447. )
  448. log.Info("Starting signer", "chainid", chainId, "keystore", ksLoc,
  449. "light-kdf", lightKdf, "advanced", advanced)
  450. am := core.StartClefAccountManager(ksLoc, nousb, lightKdf, scpath)
  451. apiImpl := core.NewSignerAPI(am, chainId, nousb, ui, db, advanced, pwStorage)
  452. // Establish the bidirectional communication, by creating a new UI backend and registering
  453. // it with the UI.
  454. ui.RegisterUIServer(core.NewUIServerAPI(apiImpl))
  455. api = apiImpl
  456. // Audit logging
  457. if logfile := c.GlobalString(auditLogFlag.Name); logfile != "" {
  458. api, err = core.NewAuditLogger(logfile, api)
  459. if err != nil {
  460. utils.Fatalf(err.Error())
  461. }
  462. log.Info("Audit logs configured", "file", logfile)
  463. }
  464. // register signer API with server
  465. var (
  466. extapiURL = "n/a"
  467. ipcapiURL = "n/a"
  468. )
  469. rpcAPI := []rpc.API{
  470. {
  471. Namespace: "account",
  472. Public: true,
  473. Service: api,
  474. Version: "1.0"},
  475. }
  476. if c.GlobalBool(utils.RPCEnabledFlag.Name) {
  477. vhosts := splitAndTrim(c.GlobalString(utils.RPCVirtualHostsFlag.Name))
  478. cors := splitAndTrim(c.GlobalString(utils.RPCCORSDomainFlag.Name))
  479. // start http server
  480. httpEndpoint := fmt.Sprintf("%s:%d", c.GlobalString(utils.RPCListenAddrFlag.Name), c.Int(rpcPortFlag.Name))
  481. listener, _, err := rpc.StartHTTPEndpoint(httpEndpoint, rpcAPI, []string{"account"}, cors, vhosts, rpc.DefaultHTTPTimeouts)
  482. if err != nil {
  483. utils.Fatalf("Could not start RPC api: %v", err)
  484. }
  485. extapiURL = fmt.Sprintf("http://%s", httpEndpoint)
  486. log.Info("HTTP endpoint opened", "url", extapiURL)
  487. defer func() {
  488. listener.Close()
  489. log.Info("HTTP endpoint closed", "url", httpEndpoint)
  490. }()
  491. }
  492. if !c.GlobalBool(utils.IPCDisabledFlag.Name) {
  493. if c.IsSet(utils.IPCPathFlag.Name) {
  494. ipcapiURL = c.GlobalString(utils.IPCPathFlag.Name)
  495. } else {
  496. ipcapiURL = filepath.Join(configDir, "clef.ipc")
  497. }
  498. listener, _, err := rpc.StartIPCEndpoint(ipcapiURL, rpcAPI)
  499. if err != nil {
  500. utils.Fatalf("Could not start IPC api: %v", err)
  501. }
  502. log.Info("IPC endpoint opened", "url", ipcapiURL)
  503. defer func() {
  504. listener.Close()
  505. log.Info("IPC endpoint closed", "url", ipcapiURL)
  506. }()
  507. }
  508. if c.GlobalBool(testFlag.Name) {
  509. log.Info("Performing UI test")
  510. go testExternalUI(apiImpl)
  511. }
  512. ui.OnSignerStartup(core.StartupInfo{
  513. Info: map[string]interface{}{
  514. "intapi_version": core.InternalAPIVersion,
  515. "extapi_version": core.ExternalAPIVersion,
  516. "extapi_http": extapiURL,
  517. "extapi_ipc": ipcapiURL,
  518. },
  519. })
  520. abortChan := make(chan os.Signal)
  521. signal.Notify(abortChan, os.Interrupt)
  522. sig := <-abortChan
  523. log.Info("Exiting...", "signal", sig)
  524. return nil
  525. }
  526. // splitAndTrim splits input separated by a comma
  527. // and trims excessive white space from the substrings.
  528. func splitAndTrim(input string) []string {
  529. result := strings.Split(input, ",")
  530. for i, r := range result {
  531. result[i] = strings.TrimSpace(r)
  532. }
  533. return result
  534. }
  535. // DefaultConfigDir is the default config directory to use for the vaults and other
  536. // persistence requirements.
  537. func DefaultConfigDir() string {
  538. // Try to place the data folder in the user's home dir
  539. home := homeDir()
  540. if home != "" {
  541. if runtime.GOOS == "darwin" {
  542. return filepath.Join(home, "Library", "Signer")
  543. } else if runtime.GOOS == "windows" {
  544. appdata := os.Getenv("APPDATA")
  545. if appdata != "" {
  546. return filepath.Join(appdata, "Signer")
  547. } else {
  548. return filepath.Join(home, "AppData", "Roaming", "Signer")
  549. }
  550. } else {
  551. return filepath.Join(home, ".clef")
  552. }
  553. }
  554. // As we cannot guess a stable location, return empty and handle later
  555. return ""
  556. }
  557. func homeDir() string {
  558. if home := os.Getenv("HOME"); home != "" {
  559. return home
  560. }
  561. if usr, err := user.Current(); err == nil {
  562. return usr.HomeDir
  563. }
  564. return ""
  565. }
  566. func readMasterKey(ctx *cli.Context, ui core.UIClientAPI) ([]byte, error) {
  567. var (
  568. file string
  569. configDir = ctx.GlobalString(configdirFlag.Name)
  570. )
  571. if ctx.GlobalIsSet(signerSecretFlag.Name) {
  572. file = ctx.GlobalString(signerSecretFlag.Name)
  573. } else {
  574. file = filepath.Join(configDir, "masterseed.json")
  575. }
  576. if err := checkFile(file); err != nil {
  577. return nil, err
  578. }
  579. cipherKey, err := ioutil.ReadFile(file)
  580. if err != nil {
  581. return nil, err
  582. }
  583. var password string
  584. // If ui is not nil, get the password from ui.
  585. if ui != nil {
  586. resp, err := ui.OnInputRequired(core.UserInputRequest{
  587. Title: "Master Password",
  588. Prompt: "Please enter the password to decrypt the master seed",
  589. IsPassword: true})
  590. if err != nil {
  591. return nil, err
  592. }
  593. password = resp.Text
  594. } else {
  595. password = getPassPhrase("Decrypt master seed of clef", false)
  596. }
  597. masterSeed, err := decryptSeed(cipherKey, password)
  598. if err != nil {
  599. return nil, fmt.Errorf("failed to decrypt the master seed of clef")
  600. }
  601. if len(masterSeed) < 256 {
  602. return nil, fmt.Errorf("master seed of insufficient length, expected >255 bytes, got %d", len(masterSeed))
  603. }
  604. // Create vault location
  605. vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), masterSeed)[:10]))
  606. err = os.Mkdir(vaultLocation, 0700)
  607. if err != nil && !os.IsExist(err) {
  608. return nil, err
  609. }
  610. return masterSeed, nil
  611. }
  612. // checkFile is a convenience function to check if a file
  613. // * exists
  614. // * is mode 0400
  615. func checkFile(filename string) error {
  616. info, err := os.Stat(filename)
  617. if err != nil {
  618. return fmt.Errorf("failed stat on %s: %v", filename, err)
  619. }
  620. // Check the unix permission bits
  621. if info.Mode().Perm()&0377 != 0 {
  622. return fmt.Errorf("file (%v) has insecure file permissions (%v)", filename, info.Mode().String())
  623. }
  624. return nil
  625. }
  626. // confirm displays a text and asks for user confirmation
  627. func confirm(text string) bool {
  628. fmt.Printf(text)
  629. fmt.Printf("\nEnter 'ok' to proceed:\n> ")
  630. text, err := bufio.NewReader(os.Stdin).ReadString('\n')
  631. if err != nil {
  632. log.Crit("Failed to read user input", "err", err)
  633. }
  634. if text := strings.TrimSpace(text); text == "ok" {
  635. return true
  636. }
  637. return false
  638. }
  639. func testExternalUI(api *core.SignerAPI) {
  640. ctx := context.WithValue(context.Background(), "remote", "clef binary")
  641. ctx = context.WithValue(ctx, "scheme", "in-proc")
  642. ctx = context.WithValue(ctx, "local", "main")
  643. errs := make([]string, 0)
  644. a := common.HexToAddress("0xdeadbeef000000000000000000000000deadbeef")
  645. addErr := func(errStr string) {
  646. log.Info("Test error", "err", errStr)
  647. errs = append(errs, errStr)
  648. }
  649. queryUser := func(q string) string {
  650. resp, err := api.UI.OnInputRequired(core.UserInputRequest{
  651. Title: "Testing",
  652. Prompt: q,
  653. })
  654. if err != nil {
  655. addErr(err.Error())
  656. }
  657. return resp.Text
  658. }
  659. expectResponse := func(testcase, question, expect string) {
  660. if got := queryUser(question); got != expect {
  661. addErr(fmt.Sprintf("%s: got %v, expected %v", testcase, got, expect))
  662. }
  663. }
  664. expectApprove := func(testcase string, err error) {
  665. if err == nil || err == accounts.ErrUnknownAccount {
  666. return
  667. }
  668. addErr(fmt.Sprintf("%v: expected no error, got %v", testcase, err.Error()))
  669. }
  670. expectDeny := func(testcase string, err error) {
  671. if err == nil || err != core.ErrRequestDenied {
  672. addErr(fmt.Sprintf("%v: expected ErrRequestDenied, got %v", testcase, err))
  673. }
  674. }
  675. var delay = 1 * time.Second
  676. // Test display of info and error
  677. {
  678. api.UI.ShowInfo("If you see this message, enter 'yes' to next question")
  679. time.Sleep(delay)
  680. expectResponse("showinfo", "Did you see the message? [yes/no]", "yes")
  681. api.UI.ShowError("If you see this message, enter 'yes' to the next question")
  682. time.Sleep(delay)
  683. expectResponse("showerror", "Did you see the message? [yes/no]", "yes")
  684. }
  685. { // Sign data test - clique header
  686. api.UI.ShowInfo("Please approve the next request for signing a clique header")
  687. time.Sleep(delay)
  688. cliqueHeader := types.Header{
  689. common.HexToHash("0000H45H"),
  690. common.HexToHash("0000H45H"),
  691. common.HexToAddress("0000H45H"),
  692. common.HexToHash("0000H00H"),
  693. common.HexToHash("0000H45H"),
  694. common.HexToHash("0000H45H"),
  695. types.Bloom{},
  696. big.NewInt(1337),
  697. big.NewInt(1337),
  698. 1338,
  699. 1338,
  700. 1338,
  701. []byte("Extra data Extra data Extra data Extra data Extra data Extra data Extra data Extra data"),
  702. common.HexToHash("0x0000H45H"),
  703. types.BlockNonce{},
  704. }
  705. cliqueRlp, err := rlp.EncodeToBytes(cliqueHeader)
  706. if err != nil {
  707. utils.Fatalf("Should not error: %v", err)
  708. }
  709. addr, _ := common.NewMixedcaseAddressFromString("0x0011223344556677889900112233445566778899")
  710. _, err = api.SignData(ctx, accounts.MimetypeClique, *addr, hexutil.Encode(cliqueRlp))
  711. expectApprove("signdata - clique header", err)
  712. }
  713. { // Sign data test - typed data
  714. api.UI.ShowInfo("Please approve the next request for signing EIP-712 typed data")
  715. time.Sleep(delay)
  716. addr, _ := common.NewMixedcaseAddressFromString("0x0011223344556677889900112233445566778899")
  717. data := `{"types":{"EIP712Domain":[{"name":"name","type":"string"},{"name":"version","type":"string"},{"name":"chainId","type":"uint256"},{"name":"verifyingContract","type":"address"}],"Person":[{"name":"name","type":"string"},{"name":"test","type":"uint8"},{"name":"wallet","type":"address"}],"Mail":[{"name":"from","type":"Person"},{"name":"to","type":"Person"},{"name":"contents","type":"string"}]},"primaryType":"Mail","domain":{"name":"Ether Mail","version":"1","chainId":"1","verifyingContract":"0xCCCcccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC"},"message":{"from":{"name":"Cow","test":"3","wallet":"0xcD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"},"to":{"name":"Bob","wallet":"0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB","test":"2"},"contents":"Hello, Bob!"}}`
  718. //_, err := api.SignData(ctx, accounts.MimetypeTypedData, *addr, hexutil.Encode([]byte(data)))
  719. var typedData core.TypedData
  720. json.Unmarshal([]byte(data), &typedData)
  721. _, err := api.SignTypedData(ctx, *addr, typedData)
  722. expectApprove("sign 712 typed data", err)
  723. }
  724. { // Sign data test - plain text
  725. api.UI.ShowInfo("Please approve the next request for signing text")
  726. time.Sleep(delay)
  727. addr, _ := common.NewMixedcaseAddressFromString("0x0011223344556677889900112233445566778899")
  728. _, err := api.SignData(ctx, accounts.MimetypeTextPlain, *addr, hexutil.Encode([]byte("hello world")))
  729. expectApprove("signdata - text", err)
  730. }
  731. { // Sign data test - plain text reject
  732. api.UI.ShowInfo("Please deny the next request for signing text")
  733. time.Sleep(delay)
  734. addr, _ := common.NewMixedcaseAddressFromString("0x0011223344556677889900112233445566778899")
  735. _, err := api.SignData(ctx, accounts.MimetypeTextPlain, *addr, hexutil.Encode([]byte("hello world")))
  736. expectDeny("signdata - text", err)
  737. }
  738. { // Sign transaction
  739. api.UI.ShowInfo("Please reject next transaction")
  740. time.Sleep(delay)
  741. data := hexutil.Bytes([]byte{})
  742. to := common.NewMixedcaseAddress(a)
  743. tx := core.SendTxArgs{
  744. Data: &data,
  745. Nonce: 0x1,
  746. Value: hexutil.Big(*big.NewInt(6)),
  747. From: common.NewMixedcaseAddress(a),
  748. To: &to,
  749. GasPrice: hexutil.Big(*big.NewInt(5)),
  750. Gas: 1000,
  751. Input: nil,
  752. }
  753. _, err := api.SignTransaction(ctx, tx, nil)
  754. expectDeny("signtransaction [1]", err)
  755. expectResponse("signtransaction [2]", "Did you see any warnings for the last transaction? (yes/no)", "no")
  756. }
  757. { // Listing
  758. api.UI.ShowInfo("Please reject listing-request")
  759. time.Sleep(delay)
  760. _, err := api.List(ctx)
  761. expectDeny("list", err)
  762. }
  763. { // Import
  764. api.UI.ShowInfo("Please reject new account-request")
  765. time.Sleep(delay)
  766. _, err := api.New(ctx)
  767. expectDeny("newaccount", err)
  768. }
  769. { // Metadata
  770. api.UI.ShowInfo("Please check if you see the Origin in next listing (approve or deny)")
  771. time.Sleep(delay)
  772. api.List(context.WithValue(ctx, "Origin", "origin.com"))
  773. expectResponse("metadata - origin", "Did you see origin (origin.com)? [yes/no] ", "yes")
  774. }
  775. for _, e := range errs {
  776. log.Error(e)
  777. }
  778. result := fmt.Sprintf("Tests completed. %d errors:\n%s\n", len(errs), strings.Join(errs, "\n"))
  779. api.UI.ShowInfo(result)
  780. }
  781. // getPassPhrase retrieves the password associated with clef, either fetched
  782. // from a list of preloaded passphrases, or requested interactively from the user.
  783. // TODO: there are many `getPassPhrase` functions, it will be better to abstract them into one.
  784. func getPassPhrase(prompt string, confirmation bool) string {
  785. fmt.Println(prompt)
  786. password, err := console.Stdin.PromptPassword("Passphrase: ")
  787. if err != nil {
  788. utils.Fatalf("Failed to read passphrase: %v", err)
  789. }
  790. if confirmation {
  791. confirm, err := console.Stdin.PromptPassword("Repeat passphrase: ")
  792. if err != nil {
  793. utils.Fatalf("Failed to read passphrase confirmation: %v", err)
  794. }
  795. if password != confirm {
  796. utils.Fatalf("Passphrases do not match")
  797. }
  798. }
  799. return password
  800. }
  801. type encryptedSeedStorage struct {
  802. Description string `json:"description"`
  803. Version int `json:"version"`
  804. Params keystore.CryptoJSON `json:"params"`
  805. }
  806. // encryptSeed uses a similar scheme as the keystore uses, but with a different wrapping,
  807. // to encrypt the master seed
  808. func encryptSeed(seed []byte, auth []byte, scryptN, scryptP int) ([]byte, error) {
  809. cryptoStruct, err := keystore.EncryptDataV3(seed, auth, scryptN, scryptP)
  810. if err != nil {
  811. return nil, err
  812. }
  813. return json.Marshal(&encryptedSeedStorage{"Clef seed", 1, cryptoStruct})
  814. }
  815. // decryptSeed decrypts the master seed
  816. func decryptSeed(keyjson []byte, auth string) ([]byte, error) {
  817. var encSeed encryptedSeedStorage
  818. if err := json.Unmarshal(keyjson, &encSeed); err != nil {
  819. return nil, err
  820. }
  821. if encSeed.Version != 1 {
  822. log.Warn(fmt.Sprintf("unsupported encryption format of seed: %d, operation will likely fail", encSeed.Version))
  823. }
  824. seed, err := keystore.DecryptDataV3(encSeed.Params, auth)
  825. if err != nil {
  826. return nil, err
  827. }
  828. return seed, err
  829. }
  830. // GenDoc outputs examples of all structures used in json-rpc communication
  831. func GenDoc(ctx *cli.Context) {
  832. var (
  833. a = common.HexToAddress("0xdeadbeef000000000000000000000000deadbeef")
  834. b = common.HexToAddress("0x1111111122222222222233333333334444444444")
  835. meta = core.Metadata{
  836. Scheme: "http",
  837. Local: "localhost:8545",
  838. Origin: "www.malicious.ru",
  839. Remote: "localhost:9999",
  840. UserAgent: "Firefox 3.2",
  841. }
  842. output []string
  843. add = func(name, desc string, v interface{}) {
  844. if data, err := json.MarshalIndent(v, "", " "); err == nil {
  845. output = append(output, fmt.Sprintf("### %s\n\n%s\n\nExample:\n```json\n%s\n```", name, desc, data))
  846. } else {
  847. log.Error("Error generating output", err)
  848. }
  849. }
  850. )
  851. { // Sign plain text request
  852. desc := "SignDataRequest contains information about a pending request to sign some data. " +
  853. "The data to be signed can be of various types, defined by content-type. Clef has done most " +
  854. "of the work in canonicalizing and making sense of the data, and it's up to the UI to present" +
  855. "the user with the contents of the `message`"
  856. sighash, msg := accounts.TextAndHash([]byte("hello world"))
  857. messages := []*core.NameValueType{{"message", msg, accounts.MimetypeTextPlain}}
  858. add("SignDataRequest", desc, &core.SignDataRequest{
  859. Address: common.NewMixedcaseAddress(a),
  860. Meta: meta,
  861. ContentType: accounts.MimetypeTextPlain,
  862. Rawdata: []byte(msg),
  863. Messages: messages,
  864. Hash: sighash})
  865. }
  866. { // Sign plain text response
  867. add("SignDataResponse - approve", "Response to SignDataRequest",
  868. &core.SignDataResponse{Approved: true})
  869. add("SignDataResponse - deny", "Response to SignDataRequest",
  870. &core.SignDataResponse{})
  871. }
  872. { // Sign transaction request
  873. desc := "SignTxRequest contains information about a pending request to sign a transaction. " +
  874. "Aside from the transaction itself, there is also a `call_info`-struct. That struct contains " +
  875. "messages of various types, that the user should be informed of." +
  876. "\n\n" +
  877. "As in any request, it's important to consider that the `meta` info also contains untrusted data." +
  878. "\n\n" +
  879. "The `transaction` (on input into clef) can have either `data` or `input` -- if both are set, " +
  880. "they must be identical, otherwise an error is generated. " +
  881. "However, Clef will always use `data` when passing this struct on (if Clef does otherwise, please file a ticket)"
  882. data := hexutil.Bytes([]byte{0x01, 0x02, 0x03, 0x04})
  883. add("SignTxRequest", desc, &core.SignTxRequest{
  884. Meta: meta,
  885. Callinfo: []core.ValidationInfo{
  886. {"Warning", "Something looks odd, show this message as a warning"},
  887. {"Info", "User should see this aswell"},
  888. },
  889. Transaction: core.SendTxArgs{
  890. Data: &data,
  891. Nonce: 0x1,
  892. Value: hexutil.Big(*big.NewInt(6)),
  893. From: common.NewMixedcaseAddress(a),
  894. To: nil,
  895. GasPrice: hexutil.Big(*big.NewInt(5)),
  896. Gas: 1000,
  897. Input: nil,
  898. }})
  899. }
  900. { // Sign tx response
  901. data := hexutil.Bytes([]byte{0x04, 0x03, 0x02, 0x01})
  902. add("SignTxResponse - approve", "Response to request to sign a transaction. This response needs to contain the `transaction`"+
  903. ", because the UI is free to make modifications to the transaction.",
  904. &core.SignTxResponse{Approved: true,
  905. Transaction: core.SendTxArgs{
  906. Data: &data,
  907. Nonce: 0x4,
  908. Value: hexutil.Big(*big.NewInt(6)),
  909. From: common.NewMixedcaseAddress(a),
  910. To: nil,
  911. GasPrice: hexutil.Big(*big.NewInt(5)),
  912. Gas: 1000,
  913. Input: nil,
  914. }})
  915. add("SignTxResponse - deny", "Response to SignTxRequest. When denying a request, there's no need to "+
  916. "provide the transaction in return",
  917. &core.SignTxResponse{})
  918. }
  919. { // WHen a signed tx is ready to go out
  920. desc := "SignTransactionResult is used in the call `clef` -> `OnApprovedTx(result)`" +
  921. "\n\n" +
  922. "This occurs _after_ successful completion of the entire signing procedure, but right before the signed " +
  923. "transaction is passed to the external caller. This method (and data) can be used by the UI to signal " +
  924. "to the user that the transaction was signed, but it is primarily useful for ruleset implementations." +
  925. "\n\n" +
  926. "A ruleset that implements a rate limitation needs to know what transactions are sent out to the external " +
  927. "interface. By hooking into this methods, the ruleset can maintain track of that count." +
  928. "\n\n" +
  929. "**OBS:** Note that if an attacker can restore your `clef` data to a previous point in time" +
  930. " (e.g through a backup), the attacker can reset such windows, even if he/she is unable to decrypt the content. " +
  931. "\n\n" +
  932. "The `OnApproved` method cannot be responded to, it's purely informative"
  933. rlpdata := common.FromHex("0xf85d640101948a8eafb1cf62bfbeb1741769dae1a9dd47996192018026a0716bd90515acb1e68e5ac5867aa11a1e65399c3349d479f5fb698554ebc6f293a04e8a4ebfff434e971e0ef12c5bf3a881b06fd04fc3f8b8a7291fb67a26a1d4ed")
  934. var tx types.Transaction
  935. rlp.DecodeBytes(rlpdata, &tx)
  936. add("OnApproved - SignTransactionResult", desc, &ethapi.SignTransactionResult{Raw: rlpdata, Tx: &tx})
  937. }
  938. { // User input
  939. add("UserInputRequest", "Sent when clef needs the user to provide data. If 'password' is true, the input field should be treated accordingly (echo-free)",
  940. &core.UserInputRequest{IsPassword: true, Title: "The title here", Prompt: "The question to ask the user"})
  941. add("UserInputResponse", "Response to UserInputRequest",
  942. &core.UserInputResponse{Text: "The textual response from user"})
  943. }
  944. { // List request
  945. add("ListRequest", "Sent when a request has been made to list addresses. The UI is provided with the "+
  946. "full `account`s, including local directory names. Note: this information is not passed back to the external caller, "+
  947. "who only sees the `address`es. ",
  948. &core.ListRequest{
  949. Meta: meta,
  950. Accounts: []accounts.Account{
  951. {a, accounts.URL{Scheme: "keystore", Path: "/path/to/keyfile/a"}},
  952. {b, accounts.URL{Scheme: "keystore", Path: "/path/to/keyfile/b"}}},
  953. })
  954. add("ListResponse", "Response to list request. The response contains a list of all addresses to show to the caller. "+
  955. "Note: the UI is free to respond with any address the caller, regardless of whether it exists or not",
  956. &core.ListResponse{
  957. Accounts: []accounts.Account{
  958. {common.HexToAddress("0xcowbeef000000cowbeef00000000000000000c0w"), accounts.URL{Path: ".. ignored .."}},
  959. {common.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff"), accounts.URL{}},
  960. }})
  961. }
  962. fmt.Println(`## UI Client interface
  963. These data types are defined in the channel between clef and the UI`)
  964. for _, elem := range output {
  965. fmt.Println(elem)
  966. }
  967. }