-
Notifications
You must be signed in to change notification settings - Fork 13
/
main.go
239 lines (215 loc) · 5.99 KB
/
main.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"runtime/debug"
"strings"
"time"
"github.com/CrowdStrike/csproto"
)
func main() {
var (
inputFile string
expandPaths tagPaths
stringPaths tagPaths
showVersionInfo bool
showUsage bool
)
fset := flag.NewFlagSet("protodump", flag.ExitOnError)
fset.Usage = printUsage(fset)
fset.StringVar(&inputFile, "file", "", "The path to the Protobuf data to be decoded. (optional, reads from stdin if not specified)")
fset.Var(&expandPaths, "expand", "One or more 'paths' to length-delimited fields in the message that should be expanded (optional)")
fset.Var(&stringPaths, "strings", "One or more 'paths' to length-delimited fields in the message that contain string data (optional)")
fset.BoolVar(&showVersionInfo, "version", false, "Shows version information")
fset.BoolVar(&showUsage, "help", false, "Shows usage information")
err := fset.Parse(os.Args[1:])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if showUsage {
fset.Usage()
return
}
if showVersionInfo {
echoVersion()
return
}
var (
f *os.File
)
if inputFile != "" {
f, err = os.Open(filepath.Clean(inputFile))
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to open input file %q: %v\n", inputFile, err)
os.Exit(1)
}
defer f.Close()
} else {
var fi os.FileInfo
f = os.Stdin
fi, err = f.Stat()
if err != nil {
fmt.Fprintf(os.Stderr, "Unexpected error: %v\n", err)
os.Exit(1)
}
if fi.Size() == 0 {
fmt.Fprintln(os.Stderr, "No data provided on stdin. Use '-file' or pass data on stdin.")
os.Exit(1)
}
}
err = dumpProtoFile(f, &expandPaths, &stringPaths)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
const usageMsg = `protodump - A simple Protobuf binary message decoder
Outputs tag/wire type information, along with values where possible, for binary Protobuf messages.
The message data can be passed in via stdin or using the '-file' command-line flag.
Two additional options are supported for length-delimited fields. For nested message fields, the
'-expand' flag can be used to "recurse" into those messages. The '-strings' flag can be used to output
field values as strings instead of raw bytes. Both parameters accept one or more "tag path" values,
which are dot-separated lists of integer field tags that indicate the nesting structure of the message
data.
Examples:
cat message.bin | protodump
protodump -file message.bin
protodump -file message.bin -expand "3" -expand "4.4" -strings "1,2,3.1,3.2`
func printUsage(fset *flag.FlagSet) func() {
return func() {
fmt.Fprintln(os.Stderr, usageMsg)
fmt.Fprintln(os.Stderr, "\n\nFlags:")
fset.PrintDefaults()
}
}
var (
version = ""
commit = "unknown"
date = "unknown"
builtBy = "unknown"
)
func echoVersion() {
if version == "" {
info, ok := debug.ReadBuildInfo()
if ok {
fmt.Printf("%v\n", info)
version = info.Main.Version
for _, s := range info.Settings {
switch s.Key {
case "vcs.revision":
commit = s.Value
case "vcs.time":
date = s.Value
}
}
if version == "(devel)" && commit != "unknown" && date != "unknown" {
ts, err := time.Parse(time.RFC3339, date)
if err != nil {
ts = time.Now().UTC()
}
shortHash := commit
if len(shortHash) > 12 {
shortHash = shortHash[:12]
}
version = fmt.Sprintf("v0.0.0-devel-%s-%s", ts.Format("20060102130607"), shortHash)
}
}
}
fmt.Printf("version: %s\ncommit: %s\ndate: %s\nbuiltBy: %s\n", version, commit, date, builtBy)
}
func dumpProtoFile(input io.Reader, expand *tagPaths, stringPaths *tagPaths) error {
data, err := io.ReadAll(input)
if err != nil {
return err
}
conf := dumpConfig{
indent: 0,
expand: expand,
strings: stringPaths,
}
return dumpProto(os.Stdout, csproto.NewDecoder(data), tagPath{}, conf)
}
type tagPathMatcher interface {
Matches(tagPath) bool
}
type dumpConfig struct {
indent int
expand tagPathMatcher
strings tagPathMatcher
}
func (conf dumpConfig) isStringField(tp tagPath) bool {
return conf.strings.Matches(tp)
}
func (conf dumpConfig) shouldExpand(tp tagPath) bool {
return conf.expand.Matches(tp)
}
func dumpProto(w io.Writer, dec *csproto.Decoder, parentTagPath tagPath, conf dumpConfig) error {
prefix := strings.Repeat(" ", 2*conf.indent)
bw := bufio.NewWriter(w)
defer bw.Flush()
for dec.More() {
tag, wireType, err := dec.DecodeTag()
if err != nil {
return err
}
thisTagPath := append(parentTagPath, tag)
_, _ = bw.WriteString(fmt.Sprintf("%stag: %d, wire type: %s\n", prefix, tag, wireType))
switch wireType {
case csproto.WireTypeVarint:
vv, err := dec.DecodeInt64()
if err != nil {
return err
}
_, _ = bw.WriteString(fmt.Sprintf("%s varint: %d\n", prefix, vv))
case csproto.WireTypeFixed32:
f32, err := dec.DecodeFixed32()
if err != nil {
return err
}
_, _ = bw.WriteString(fmt.Sprintf("%s fixed32: %d\n", prefix, f32))
case csproto.WireTypeFixed64:
f64, err := dec.DecodeFixed64()
if err != nil {
return err
}
_, _ = bw.WriteString(fmt.Sprintf("%s fixed64: %d\n", prefix, f64))
case csproto.WireTypeLengthDelimited:
ldv, err := dec.DecodeBytes()
if err != nil {
return err
}
_, _ = bw.WriteString(fmt.Sprintf("%s length: %d\n", prefix, len(ldv)))
switch {
case conf.isStringField(thisTagPath):
_, _ = bw.WriteString(fmt.Sprintf("%s string: %s\n", prefix, string(ldv)))
default:
_, _ = bw.WriteString(fmt.Sprintf("%s [", prefix))
for i, b := range ldv {
if i > 0 {
_, _ = bw.WriteRune(',')
}
_, _ = bw.WriteString(fmt.Sprintf("0x%02X", b))
}
_, _ = bw.WriteString("]\n")
if conf.shouldExpand(thisTagPath) {
_ = bw.Flush()
conf.indent++
err = dumpProto(w, csproto.NewDecoder(ldv), thisTagPath, conf)
conf.indent--
if err != nil {
return err
}
}
}
default:
_, _ = dec.Skip(tag, wireType)
return fmt.Errorf("unrecognized proto wire type (%d)", int(wireType))
}
}
return nil
}