main.go 33 KB

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