main.go 34 KB

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