Skip to content

Commit 7f95a85

Browse files
authored
signer, log: properly escape character sequences (#20987)
* signer: properly handle terminal escape characters * log: use strconv conversion instead of custom escape function * log: remove relection tests for nil
1 parent 0708b57 commit 7f95a85

5 files changed

Lines changed: 35 additions & 57 deletions

File tree

‎log/format.go‎

Lines changed: 9 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -358,49 +358,19 @@ func formatLogfmtValue(value interface{}, term bool) string {
358358
}
359359
}
360360

361-
var stringBufPool = sync.Pool{
362-
New: func() interface{} { return new(bytes.Buffer) },
363-
}
364-
361+
// escapeString checks if the provided string needs escaping/quoting, and
362+
// calls strconv.Quote if needed
365363
func escapeString(s string) string {
366-
needsQuotes := false
367-
needsEscape := false
364+
needsQuoting := false
368365
for _, r := range s {
369-
if r <= ' ' || r == '=' || r == '"' {
370-
needsQuotes = true
371-
}
372-
if r == '\\' || r == '"' || r == '\n' || r == '\r' || r == '\t' {
373-
needsEscape = true
366+
// We quote everything below " (0x34) and above~ (0x7E), plus equal-sign
367+
if r <= '"' || r > '~' || r == '=' {
368+
needsQuoting = true
369+
break
374370
}
375371
}
376-
if !needsEscape && !needsQuotes {
372+
if !needsQuoting {
377373
return s
378374
}
379-
e := stringBufPool.Get().(*bytes.Buffer)
380-
e.WriteByte('"')
381-
for _, r := range s {
382-
switch r {
383-
case '\\', '"':
384-
e.WriteByte('\\')
385-
e.WriteByte(byte(r))
386-
case '\n':
387-
e.WriteString("\\n")
388-
case '\r':
389-
e.WriteString("\\r")
390-
case '\t':
391-
e.WriteString("\\t")
392-
default:
393-
e.WriteRune(r)
394-
}
395-
}
396-
e.WriteByte('"')
397-
var ret string
398-
if needsQuotes {
399-
ret = e.String()
400-
} else {
401-
ret = string(e.Bytes()[1 : e.Len()-1])
402-
}
403-
e.Reset()
404-
stringBufPool.Put(e)
405-
return ret
375+
return strconv.Quote(s)
406376
}

‎signer/core/cliui.go‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,10 +85,19 @@ func (ui *CommandlineUI) confirm() bool {
8585
return false
8686
}
8787

88+
// sanitize quotes and truncates 'txt' if longer than 'limit'. If truncated,
89+
// and ellipsis is added after the quoted string
90+
func sanitize(txt string, limit int) string {
91+
if len(txt) > limit {
92+
return fmt.Sprintf("%q...", txt[:limit])
93+
}
94+
return fmt.Sprintf("%q", txt)
95+
}
96+
8897
func showMetadata(metadata Metadata) {
8998
fmt.Printf("Request context:\n\t%v -> %v -> %v\n", metadata.Remote, metadata.Scheme, metadata.Local)
9099
fmt.Printf("\nAdditional HTTP header data, provided by the external caller:\n")
91-
fmt.Printf("\tUser-Agent: %v\n\tOrigin: %v\n", metadata.UserAgent, metadata.Origin)
100+
fmt.Printf("\tUser-Agent: %v\n\tOrigin: %v\n", sanitize(metadata.UserAgent, 200), sanitize(metadata.Origin, 100))
92101
}
93102

94103
// ApproveTx prompt the user for confirmation to request to sign Transaction
@@ -113,7 +122,6 @@ func (ui *CommandlineUI) ApproveTx(request *SignTxRequest) (SignTxResponse, erro
113122
if request.Transaction.Data != nil {
114123
d := *request.Transaction.Data
115124
if len(d) > 0 {
116-
117125
fmt.Printf("data: %v\n", hexutil.Encode(d))
118126
}
119127
}
@@ -145,7 +153,7 @@ func (ui *CommandlineUI) ApproveSignData(request *SignDataRequest) (SignDataResp
145153
for _, nvt := range request.Messages {
146154
fmt.Printf("\u00a0\u00a0%v\n", strings.TrimSpace(nvt.Pprint(1)))
147155
}
148-
fmt.Printf("raw data: \n%q\n", request.Rawdata)
156+
fmt.Printf("raw data: \n\t%q\n", request.Rawdata)
149157
fmt.Printf("data hash: %v\n", request.Hash)
150158
fmt.Printf("-------------------------------------------\n")
151159
showMetadata(request.Meta)

‎signer/core/signed_data.go‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -827,23 +827,23 @@ func (t Types) validate() error {
827827
}
828828
for i, typeObj := range typeArr {
829829
if len(typeObj.Type) == 0 {
830-
return fmt.Errorf("type %v:%d: empty Type", typeKey, i)
830+
return fmt.Errorf("type %q:%d: empty Type", typeKey, i)
831831
}
832832
if len(typeObj.Name) == 0 {
833-
return fmt.Errorf("type %v:%d: empty Name", typeKey, i)
833+
return fmt.Errorf("type %q:%d: empty Name", typeKey, i)
834834
}
835835
if typeKey == typeObj.Type {
836-
return fmt.Errorf("type '%s' cannot reference itself", typeObj.Type)
836+
return fmt.Errorf("type %q cannot reference itself", typeObj.Type)
837837
}
838838
if typeObj.isReferenceType() {
839839
if _, exist := t[typeObj.typeName()]; !exist {
840-
return fmt.Errorf("reference type '%s' is undefined", typeObj.Type)
840+
return fmt.Errorf("reference type %q is undefined", typeObj.Type)
841841
}
842842
if !typedDataReferenceTypeRegexp.MatchString(typeObj.Type) {
843-
return fmt.Errorf("unknown reference type '%s", typeObj.Type)
843+
return fmt.Errorf("unknown reference type %q", typeObj.Type)
844844
}
845845
} else if !isPrimitiveTypeValid(typeObj.Type) {
846-
return fmt.Errorf("unknown type '%s'", typeObj.Type)
846+
return fmt.Errorf("unknown type %q", typeObj.Type)
847847
}
848848
}
849849
}

‎signer/fourbyte/abi.go‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ var selectorRegexp = regexp.MustCompile(`^([^\)]+)\(([A-Za-z0-9,\[\]]*)\)`)
8585

8686
// parseSelector converts a method selector into an ABI JSON spec. The returned
8787
// data is a valid JSON string which can be consumed by the standard abi package.
88-
func parseSelector(selector string) ([]byte, error) {
88+
func parseSelector(unescapedSelector string) ([]byte, error) {
8989
// Define a tiny fake ABI struct for JSON marshalling
9090
type fakeArg struct {
9191
Type string `json:"type"`
@@ -95,10 +95,10 @@ func parseSelector(selector string) ([]byte, error) {
9595
Type string `json:"type"`
9696
Inputs []fakeArg `json:"inputs"`
9797
}
98-
// Validate the selector and extract it's components
99-
groups := selectorRegexp.FindStringSubmatch(selector)
98+
// Validate the unescapedSelector and extract it's components
99+
groups := selectorRegexp.FindStringSubmatch(unescapedSelector)
100100
if len(groups) != 3 {
101-
return nil, fmt.Errorf("invalid selector %s (%v matches)", selector, len(groups))
101+
return nil, fmt.Errorf("invalid selector %q (%v matches)", unescapedSelector, len(groups))
102102
}
103103
name := groups[1]
104104
args := groups[2]
@@ -115,7 +115,7 @@ func parseSelector(selector string) ([]byte, error) {
115115

116116
// parseCallData matches the provided call data against the ABI definition and
117117
// returns a struct containing the actual go-typed values.
118-
func parseCallData(calldata []byte, abidata string) (*decodedCallData, error) {
118+
func parseCallData(calldata []byte, unescapedAbidata string) (*decodedCallData, error) {
119119
// Validate the call data that it has the 4byte prefix and the rest divisible by 32 bytes
120120
if len(calldata) < 4 {
121121
return nil, fmt.Errorf("invalid call data, incomplete method signature (%d bytes < 4)", len(calldata))
@@ -127,9 +127,9 @@ func parseCallData(calldata []byte, abidata string) (*decodedCallData, error) {
127127
return nil, fmt.Errorf("invalid call data; length should be a multiple of 32 bytes (was %d)", len(argdata))
128128
}
129129
// Validate the called method and upack the call data accordingly
130-
abispec, err := abi.JSON(strings.NewReader(abidata))
130+
abispec, err := abi.JSON(strings.NewReader(unescapedAbidata))
131131
if err != nil {
132-
return nil, fmt.Errorf("invalid method signature (%s): %v", abidata, err)
132+
return nil, fmt.Errorf("invalid method signature (%q): %v", unescapedAbidata, err)
133133
}
134134
method, err := abispec.MethodById(sigdata)
135135
if err != nil {

‎signer/fourbyte/validation.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ func (db *Database) ValidateCallData(selector *string, data []byte, messages *co
9898
if info, err := verifySelector(*selector, data); err != nil {
9999
messages.Warn(fmt.Sprintf("Transaction contains data, but provided ABI signature could not be matched: %v", err))
100100
} else {
101-
messages.Info(info.String())
101+
messages.Info(fmt.Sprintf("Transaction invokes the following method: %q", info.String()))
102102
db.AddSelector(*selector, data[:4])
103103
}
104104
return
@@ -112,6 +112,6 @@ func (db *Database) ValidateCallData(selector *string, data []byte, messages *co
112112
if info, err := verifySelector(embedded, data); err != nil {
113113
messages.Warn(fmt.Sprintf("Transaction contains data, but provided ABI signature could not be verified: %v", err))
114114
} else {
115-
messages.Info(info.String())
115+
messages.Info(fmt.Sprintf("Transaction invokes the following method: %q", info.String()))
116116
}
117117
}

0 commit comments

Comments
 (0)