main.go 36 KB

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