-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathusbgen.go
98 lines (82 loc) · 2.29 KB
/
usbgen.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Copyright 2019 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package main
import (
"encoding/hex"
"flag"
"fmt"
"os"
"regexp"
"sort"
"github.com/google/syzkaller/pkg/osutil"
"github.com/google/syzkaller/pkg/tool"
)
func main() {
flag.Parse()
args := flag.Args()
if len(args) != 2 {
usage()
}
syslog, err := os.ReadFile(args[0])
if err != nil {
tool.Failf("failed to read file %v: %v", args[0], err)
}
usbIds := extractIds(syslog, "USBID", 34)
hidIds := extractIds(syslog, "HIDID", 24)
output := []byte(`// Code generated by tools/syz-usbgen. DO NOT EDIT.
// See docs/linux/external_fuzzing_usb.md
package linux
`)
output = append(output, generateIdsVar(usbIds, "usbIds")...)
output = append(output, []byte("\n")...)
output = append(output, generateIdsVar(hidIds, "hidIds")...)
if err := osutil.WriteFile(args[1], output); err != nil {
tool.Failf("failed to output file %v: %v", args[1], err)
}
}
func extractIds(syslog []byte, prefix string, size int) []string {
re := fmt.Sprintf("%s: [0-9a-f]{%d}", prefix, size)
r := regexp.MustCompile(re)
matches := r.FindAll(syslog, -1)
uniqueMatches := make(map[string]bool)
for _, match := range matches {
uniqueMatches[string(match)] = true
}
sortedMatches := make([]string, 0)
for match := range uniqueMatches {
match = match[len(prefix+": "):]
match = match[:size]
sortedMatches = append(sortedMatches, match)
}
sort.Strings(sortedMatches)
return sortedMatches
}
func generateIdsVar(ids []string, name string) []byte {
output := []byte(fmt.Sprintf("var %s = ", name))
for i, id := range ids {
decodedID, err := hex.DecodeString(id)
if err != nil {
tool.Failf("failed to decode hex string %v: %v", id, err)
}
prefix := "\t"
suffix := " +"
if i == 0 {
prefix = ""
}
if i == len(ids)-1 {
suffix = ""
}
outputID := fmt.Sprintf("%v%#v%v\n", prefix, string(decodedID), suffix)
output = append(output, []byte(outputID)...)
}
if len(ids) == 0 {
output = append(output, []byte("\"\"")...)
}
fmt.Printf("%v %s ids written\n", len(ids), name)
return output
}
func usage() {
fmt.Fprintf(os.Stderr, "usage:\n")
fmt.Fprintf(os.Stderr, " syz-usbgen syslog.txt sys/linux/init_vusb_ids.go\n")
os.Exit(1)
}