main.go 33 KB

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