Skip to content

Commit d3441eb

Browse files
authored
cmd/clef, signer: security fixes (#17554)
* signer: remove local path disclosure from extapi * signer: show more data in cli ui * rpc: make http server forward UA and Origin via Context * signer, clef/core: ui changes + display UA and Origin * signer: cliui - indicate less trust in remote headers, see ethereum/go-ethereum#17637 * signer: prevent possibility swap KV-entries in aes_gcm storage, fixes #17635 * signer: remove ecrecover from external API * signer,clef: default reject instead of warn + valideate new passwords. fixes #17632 and #17631 * signer: check calldata length even if no ABI signature is present * signer: fix failing testcase * clef: remove account import from external api * signer: allow space in passwords, improve error messsage * signer/storage: fix typos
1 parent a95a601 commit d3441eb

12 files changed

Lines changed: 307 additions & 133 deletions

File tree

‎cmd/clef/extapi_changelog.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
### Changelog for external API
22

3+
#### 4.0.0
34

5+
* The external `account_Ecrecover`-method was removed.
6+
* The external `account_Import`-method was removed.
7+
8+
#### 3.0.0
9+
10+
* The external `account_List`-method was changed to not expose `url`, which contained info about the local filesystem. It now returns only a list of addresses.
411

512
#### 2.0.0
613

‎cmd/clef/main.go‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ import (
4848
)
4949

5050
// ExternalAPIVersion -- see extapi_changelog.md
51-
const ExternalAPIVersion = "2.0.0"
51+
const ExternalAPIVersion = "3.0.0"
5252

5353
// InternalAPIVersion -- see intapi_changelog.md
5454
const InternalAPIVersion = "2.0.0"
@@ -70,6 +70,10 @@ var (
7070
Value: 4,
7171
Usage: "log level to emit to the screen",
7272
}
73+
advancedMode = cli.BoolFlag{
74+
Name: "advanced",
75+
Usage: "If enabled, issues warnings instead of rejections for suspicious requests. Default off",
76+
}
7377
keystoreFlag = cli.StringFlag{
7478
Name: "keystore",
7579
Value: filepath.Join(node.DefaultDataDir(), "keystore"),
@@ -191,6 +195,7 @@ func init() {
191195
ruleFlag,
192196
stdiouiFlag,
193197
testFlag,
198+
advancedMode,
194199
}
195200
app.Action = signer
196201
app.Commands = []cli.Command{initCommand, attestCommand, addCredentialCommand}
@@ -384,7 +389,8 @@ func signer(c *cli.Context) error {
384389
c.String(keystoreFlag.Name),
385390
c.Bool(utils.NoUSBFlag.Name),
386391
ui, db,
387-
c.Bool(utils.LightKDFFlag.Name))
392+
c.Bool(utils.LightKDFFlag.Name),
393+
c.Bool(advancedMode.Name))
388394

389395
api = apiImpl
390396

‎rpc/http.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,12 @@ func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
238238
ctx = context.WithValue(ctx, "remote", r.RemoteAddr)
239239
ctx = context.WithValue(ctx, "scheme", r.Proto)
240240
ctx = context.WithValue(ctx, "local", r.Host)
241+
if ua := r.Header.Get("User-Agent"); ua != "" {
242+
ctx = context.WithValue(ctx, "User-Agent", ua)
243+
}
244+
if origin := r.Header.Get("Origin"); origin != "" {
245+
ctx = context.WithValue(ctx, "Origin", origin)
246+
}
241247

242248
body := io.LimitReader(r.Body, maxRequestContentLength)
243249
codec := NewJSONCodec(&httpReadWriteNopCloser{body, w})

‎signer/core/api.go‎

Lines changed: 68 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -39,19 +39,19 @@ import (
3939
// ExternalAPI defines the external API through which signing requests are made.
4040
type ExternalAPI interface {
4141
// List available accounts
42-
List(ctx context.Context) (Accounts, error)
42+
List(ctx context.Context) ([]common.Address, error)
4343
// New request to create a new account
4444
New(ctx context.Context) (accounts.Account, error)
4545
// SignTransaction request to sign the specified transaction
4646
SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error)
4747
// Sign - request to sign the given data (plus prefix)
4848
Sign(ctx context.Context, addr common.MixedcaseAddress, data hexutil.Bytes) (hexutil.Bytes, error)
49-
// EcRecover - request to perform ecrecover
50-
EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error)
5149
// Export - request to export an account
5250
Export(ctx context.Context, addr common.Address) (json.RawMessage, error)
5351
// Import - request to import an account
54-
Import(ctx context.Context, keyJSON json.RawMessage) (Account, error)
52+
// Should be moved to Internal API, in next phase when we have
53+
// bi-directional communication
54+
//Import(ctx context.Context, keyJSON json.RawMessage) (Account, error)
5555
}
5656

5757
// SignerUI specifies what method a UI needs to implement to be able to be used as a UI for the signer
@@ -83,22 +83,25 @@ type SignerUI interface {
8383

8484
// SignerAPI defines the actual implementation of ExternalAPI
8585
type SignerAPI struct {
86-
chainID *big.Int
87-
am *accounts.Manager
88-
UI SignerUI
89-
validator *Validator
86+
chainID *big.Int
87+
am *accounts.Manager
88+
UI SignerUI
89+
validator *Validator
90+
rejectMode bool
9091
}
9192

9293
// Metadata about a request
9394
type Metadata struct {
94-
Remote string `json:"remote"`
95-
Local string `json:"local"`
96-
Scheme string `json:"scheme"`
95+
Remote string `json:"remote"`
96+
Local string `json:"local"`
97+
Scheme string `json:"scheme"`
98+
UserAgent string `json:"User-Agent"`
99+
Origin string `json:"Origin"`
97100
}
98101

99102
// MetadataFromContext extracts Metadata from a given context.Context
100103
func MetadataFromContext(ctx context.Context) Metadata {
101-
m := Metadata{"NA", "NA", "NA"} // batman
104+
m := Metadata{"NA", "NA", "NA", "", ""} // batman
102105

103106
if v := ctx.Value("remote"); v != nil {
104107
m.Remote = v.(string)
@@ -109,6 +112,12 @@ func MetadataFromContext(ctx context.Context) Metadata {
109112
if v := ctx.Value("local"); v != nil {
110113
m.Local = v.(string)
111114
}
115+
if v := ctx.Value("Origin"); v != nil {
116+
m.Origin = v.(string)
117+
}
118+
if v := ctx.Value("User-Agent"); v != nil {
119+
m.UserAgent = v.(string)
120+
}
112121
return m
113122
}
114123

@@ -194,7 +203,7 @@ var ErrRequestDenied = errors.New("Request denied")
194203
// key that is generated when a new Account is created.
195204
// noUSB disables USB support that is required to support hardware devices such as
196205
// ledger and trezor.
197-
func NewSignerAPI(chainID int64, ksLocation string, noUSB bool, ui SignerUI, abidb *AbiDb, lightKDF bool) *SignerAPI {
206+
func NewSignerAPI(chainID int64, ksLocation string, noUSB bool, ui SignerUI, abidb *AbiDb, lightKDF bool, advancedMode bool) *SignerAPI {
198207
var (
199208
backends []accounts.Backend
200209
n, p = keystore.StandardScryptN, keystore.StandardScryptP
@@ -222,12 +231,15 @@ func NewSignerAPI(chainID int64, ksLocation string, noUSB bool, ui SignerUI, abi
222231
log.Debug("Trezor support enabled")
223232
}
224233
}
225-
return &SignerAPI{big.NewInt(chainID), accounts.NewManager(backends...), ui, NewValidator(abidb)}
234+
if advancedMode {
235+
log.Info("Clef is in advanced mode: will warn instead of reject")
236+
}
237+
return &SignerAPI{big.NewInt(chainID), accounts.NewManager(backends...), ui, NewValidator(abidb), !advancedMode}
226238
}
227239

228240
// List returns the set of wallet this signer manages. Each wallet can contain
229241
// multiple accounts.
230-
func (api *SignerAPI) List(ctx context.Context) (Accounts, error) {
242+
func (api *SignerAPI) List(ctx context.Context) ([]common.Address, error) {
231243
var accs []Account
232244
for _, wallet := range api.am.Wallets() {
233245
for _, acc := range wallet.Accounts() {
@@ -243,7 +255,13 @@ func (api *SignerAPI) List(ctx context.Context) (Accounts, error) {
243255
return nil, ErrRequestDenied
244256

245257
}
246-
return result.Accounts, nil
258+
259+
addresses := make([]common.Address, 0)
260+
for _, acc := range result.Accounts {
261+
addresses = append(addresses, acc.Address)
262+
}
263+
264+
return addresses, nil
247265
}
248266

249267
// New creates a new password protected Account. The private key is protected with
@@ -254,15 +272,28 @@ func (api *SignerAPI) New(ctx context.Context) (accounts.Account, error) {
254272
if len(be) == 0 {
255273
return accounts.Account{}, errors.New("password based accounts not supported")
256274
}
257-
resp, err := api.UI.ApproveNewAccount(&NewAccountRequest{MetadataFromContext(ctx)})
258-
259-
if err != nil {
260-
return accounts.Account{}, err
261-
}
262-
if !resp.Approved {
263-
return accounts.Account{}, ErrRequestDenied
275+
var (
276+
resp NewAccountResponse
277+
err error
278+
)
279+
// Three retries to get a valid password
280+
for i := 0; i < 3; i++ {
281+
resp, err = api.UI.ApproveNewAccount(&NewAccountRequest{MetadataFromContext(ctx)})
282+
if err != nil {
283+
return accounts.Account{}, err
284+
}
285+
if !resp.Approved {
286+
return accounts.Account{}, ErrRequestDenied
287+
}
288+
if pwErr := ValidatePasswordFormat(resp.Password); pwErr != nil {
289+
api.UI.ShowError(fmt.Sprintf("Account creation attempt #%d failed due to password requirements: %v", (i + 1), pwErr))
290+
} else {
291+
// No error
292+
return be[0].(*keystore.KeyStore).NewAccount(resp.Password)
293+
}
264294
}
265-
return be[0].(*keystore.KeyStore).NewAccount(resp.Password)
295+
// Otherwise fail, with generic error message
296+
return accounts.Account{}, errors.New("account creation failed")
266297
}
267298

268299
// logDiff logs the difference between the incoming (original) transaction and the one returned from the signer.
@@ -294,10 +325,10 @@ func logDiff(original *SignTxRequest, new *SignTxResponse) bool {
294325
d0s := ""
295326
d1s := ""
296327
if d0 != nil {
297-
d0s = common.ToHex(*d0)
328+
d0s = hexutil.Encode(*d0)
298329
}
299330
if d1 != nil {
300-
d1s = common.ToHex(*d1)
331+
d1s = hexutil.Encode(*d1)
301332
}
302333
if d1s != d0s {
303334
modified = true
@@ -321,6 +352,12 @@ func (api *SignerAPI) SignTransaction(ctx context.Context, args SendTxArgs, meth
321352
if err != nil {
322353
return nil, err
323354
}
355+
// If we are in 'rejectMode', then reject rather than show the user warnings
356+
if api.rejectMode {
357+
if err := msgs.getWarnings(); err != nil {
358+
return nil, err
359+
}
360+
}
324361

325362
req := SignTxRequest{
326363
Transaction: args,
@@ -404,32 +441,6 @@ func (api *SignerAPI) Sign(ctx context.Context, addr common.MixedcaseAddress, da
404441
return signature, nil
405442
}
406443

407-
// EcRecover returns the address for the Account that was used to create the signature.
408-
// Note, this function is compatible with eth_sign and personal_sign. As such it recovers
409-
// the address of:
410-
// hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
411-
// addr = ecrecover(hash, signature)
412-
//
413-
// Note, the signature must conform to the secp256k1 curve R, S and V values, where
414-
// the V value must be 27 or 28 for legacy reasons.
415-
//
416-
// https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover
417-
func (api *SignerAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
418-
if len(sig) != 65 {
419-
return common.Address{}, fmt.Errorf("signature must be 65 bytes long")
420-
}
421-
if sig[64] != 27 && sig[64] != 28 {
422-
return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
423-
}
424-
sig[64] -= 27 // Transform yellow paper V from 27/28 to 0/1
425-
hash, _ := SignHash(data)
426-
rpk, err := crypto.SigToPub(hash, sig)
427-
if err != nil {
428-
return common.Address{}, err
429-
}
430-
return crypto.PubkeyToAddress(*rpk), nil
431-
}
432-
433444
// SignHash is a helper function that calculates a hash for the given message that can be
434445
// safely used to calculate a signature from.
435446
//
@@ -466,6 +477,11 @@ func (api *SignerAPI) Export(ctx context.Context, addr common.Address) (json.Raw
466477
// Import tries to import the given keyJSON in the local keystore. The keyJSON data is expected to be
467478
// in web3 keystore format. It will decrypt the keyJSON with the given passphrase and on successful
468479
// decryption it will encrypt the key with the given newPassphrase and store it in the keystore.
480+
// OBS! This method is removed from the public API. It should not be exposed on the external API
481+
// for a couple of reasons:
482+
// 1. Even though it is encrypted, it should still be seen as sensitive data
483+
// 2. It can be used to DoS clef, by using malicious data with e.g. extreme large
484+
// values for the kdfparams.
469485
func (api *SignerAPI) Import(ctx context.Context, keyJSON json.RawMessage) (Account, error) {
470486
be := api.am.Backends(keystore.KeyStoreType)
471487

0 commit comments

Comments
 (0)