This repository has been archived by the owner on Jun 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 122
/
jar.go
365 lines (334 loc) · 9.71 KB
/
jar.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package jar implements JAR scanning capabilities for log4j.
package jar
import (
"archive/zip"
"bufio"
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path"
"strings"
zipfork "github.com/google/log4jscanner/third_party/zip"
)
const (
maxZipDepth = 16
maxZipSize = 4 << 30 // 4GiB
)
var exts = map[string]bool{
".jar": true,
".war": true,
".ear": true,
".zip": true,
".jmod": true,
}
// Report contains information about a scanned JAR.
type Report struct {
// Vulnerable reports if a vulnerable version of the log4j is included in the
// JAR and has been initialized.
//
// Note that this package considers the 2.15.0 versions vulnerable.
Vulnerable bool
// MainClass and Version are information taken from the MANIFEST.MF file.
// Version indicates the version of JAR, NOT the log4j package.
MainClass string
Version string
}
// Parse traverses a JAR file, attempting to detect any usages of vulnerable
// log4j versions.
func Parse(r *zip.Reader) (*Report, error) {
var c checker
if err := c.checkJAR(r, 0, 0); err != nil {
return nil, fmt.Errorf("failed to check JAR: %v", err)
}
return &Report{
Vulnerable: c.bad(),
MainClass: c.mainClass,
Version: c.version,
}, nil
}
// ReadCloser mirrors zip.ReadCloser.
type ReadCloser struct {
zip.Reader
f *os.File
}
// Close closes the underlying file.
func (r *ReadCloser) Close() error {
return r.f.Close()
}
// OpenReader mirrors zip.OpenReader, loading a JAR from a file, but supports
// self-executable JARs. See NewReader() for details.
func OpenReader(path string) (r *ReadCloser, offset int64, err error) {
f, err := os.Open(path)
if err != nil {
return
}
info, err := f.Stat()
if err != nil {
f.Close()
return
}
zr, offset, err := NewReader(f, info.Size())
if err != nil {
f.Close()
return
}
return &ReadCloser{*zr, f}, offset, nil
}
// offsetReader is a io.ReaderAt that starts at some offset from the start of
// the file.
type offsetReader struct {
ra io.ReaderAt
offset int64
}
func (o offsetReader) ReadAt(p []byte, off int64) (n int, err error) {
return o.ra.ReadAt(p, off+o.offset)
}
// NewReader is a wrapper around zip.NewReader that supports self-executable
// JARs. JAR files with prefixed data, such as a bash script to allow them to
// run directly.
//
// If the ZIP contains a prefix, the returned offset indicates the size of the
// prefix.
//
// See:
// - https://kevinboone.me/execjava.html
// - https://github.com/golang/go/issues/10464
func NewReader(ra io.ReaderAt, size int64) (zr *zip.Reader, offset int64, err error) {
zr, err = zip.NewReader(ra, size)
if err == nil || !errors.Is(err, zip.ErrFormat) {
return zr, 0, err
}
offset, err = zipfork.ReadZIPOffset(ra, size)
if err != nil {
return nil, 0, err
}
zr, err = zip.NewReader(offsetReader{ra, offset}, size-offset)
return zr, offset, err
}
type checker struct {
// Does the JAR contain the JNDI lookup class?
hasLookupClass bool
// Does the JAR contain JndiManager with the old constructor, a
// version that hasn't been fixed.
hasOldJndiManagerConstructor bool
// Does the jar contain a string that was added in 2.16 and whether we've checked for it yet
seenJndiManagerClass bool
isAtLeastTwoDotSixteen bool
mainClass string
version string
}
func (c *checker) done() bool {
return c.bad() && c.mainClass != ""
}
func (c *checker) bad() bool {
return (c.hasLookupClass && c.hasOldJndiManagerConstructor) || (c.hasLookupClass && c.seenJndiManagerClass && !c.isAtLeastTwoDotSixteen)
}
func walkZIP(r *zip.Reader, fn func(f *zip.File) error) error {
for _, f := range r.File {
if err := fn(f); err != nil {
if errors.Is(err, fs.SkipDir) {
return nil
}
return err
}
}
return nil
}
func (c *checker) checkJAR(r *zip.Reader, depth int, size int64) error {
if depth > maxZipDepth {
return fmt.Errorf("reached max zip depth of %d", maxZipDepth)
}
err := walkZIP(r, func(zf *zip.File) error {
d := fs.FileInfoToDirEntry(zf.FileInfo())
p := zf.Name
if c.done() {
if d.IsDir() {
return fs.SkipDir
}
return nil
}
if !d.Type().IsRegular() {
return nil
}
if strings.HasSuffix(p, ".class") {
// Same logic as http://google3/security/tools/seam/cli/log4j_check.py
if c.bad() {
// Already determined that the content is bad, no
// need to check more.
return nil
}
f, err := zf.Open()
if err != nil {
return fmt.Errorf("opening file %s: %v", p, err)
}
defer f.Close()
info := zf.FileInfo()
var r io.Reader = f
if fsize := info.Size(); fsize > 0 {
if fsize+size > maxZipSize {
return fmt.Errorf("reading %s would exceed memory limit: %v", p, err)
}
r = io.LimitReader(f, fsize)
}
content, err := io.ReadAll(r)
if err != nil {
return fmt.Errorf("reading file %s: %v", p, err)
}
if !c.hasLookupClass {
if strings.Contains(p, "JndiLookup.class") {
c.hasLookupClass = true
}
}
if !c.hasOldJndiManagerConstructor {
c.hasOldJndiManagerConstructor = strings.Contains(p, "JndiManager") && matchesLog4JYARARule(content)
}
if strings.Contains(p, "JndiManager.class") {
c.seenJndiManagerClass = true
c.isAtLeastTwoDotSixteen = matchesTwoSixteen(content)
}
return nil
}
if p == "META-INF/MANIFEST.MF" {
mf, err := zf.Open()
if err != nil {
return fmt.Errorf("opening manifest file %s: %v", p, err)
}
defer mf.Close()
s := bufio.NewScanner(mf)
for s.Scan() {
// Use s.Bytes instead of s.Text to avoid a string allocation.
b := s.Bytes()
// Use IndexByte directly instead of strings.Split to avoid allocating a return slice.
i := bytes.IndexByte(b, ':')
if i < 0 {
continue
}
k, v := b[:i], b[i+1:]
if bytes.IndexByte(v, ':') >= 0 {
continue
}
if string(k) == "Main-Class" {
c.mainClass = strings.TrimSpace(string(v))
} else if string(k) == "Implementation-Version" {
c.version = strings.TrimSpace(string(v))
}
}
if err := s.Err(); err != nil {
return fmt.Errorf("scanning manifest file %s: %v", p, err)
}
return nil
}
// Scan for jars within jars.
if !exts[path.Ext(p)] {
return nil
}
// We've found a jar in a jar. Open it!
fi, err := d.Info()
if err != nil {
return fmt.Errorf("failed to get archive inside of archive %s: %v", p, err)
}
// If we're about to read more than the max size we've configure ahead of time then stop.
// Note that this only applies to embedded ZIPs/JARs. The outer ZIP/JAR can still be larger than the limit.
if size+fi.Size() > maxZipSize {
return fmt.Errorf("archive inside archive at %q is greater than 4GB, skipping", p)
}
f, err := zf.Open()
if err != nil {
return fmt.Errorf("open file %s: %v", p, err)
}
defer f.Close()
data, err := io.ReadAll(f)
if err != nil {
return fmt.Errorf("read file %s: %v", p, err)
}
br := bytes.NewReader(data)
r2, err := zip.NewReader(br, br.Size())
if err != nil {
if err == zip.ErrFormat {
// Not a zip file.
return nil
}
return fmt.Errorf("parsing file %s: %v", p, err)
}
if err := c.checkJAR(r2, depth+1, size+fi.Size()); err != nil {
return fmt.Errorf("checking sub jar %s: %v", p, err)
}
return nil
})
return err
}
var (
// Replicate YARA rule:
//
// strings:
// $JndiManagerConstructor = {
// 3c 69 6e 69 74 3e ?? ?? ?? 28 4c 6a 61 76 61 2f 6c 61 6e 67 2f 53 74 72 69
// 6e 67 3b 4c 6a 61 76 61 78 2f 6e 61 6d 69 6e 67 2f 43 6f 6e 74 65 78 74 3b
// 29 56
// }
//
// https://github.com/darkarnium/Log4j-CVE-Detect/blob/main/rules/vulnerability/log4j/CVE-2021-44228.yar
log4JYARAPrefix = []byte{0x3c, 0x69, 0x6e, 0x69, 0x74, 0x3e}
log4JYARASuffix = []byte{
0x28, 0x4c, 0x6a, 0x61, 0x76, 0x61, 0x2f, 0x6c,
0x61, 0x6e, 0x67, 0x2f, 0x53, 0x74, 0x72, 0x69,
0x6e, 0x67, 0x3b, 0x4c, 0x6a, 0x61, 0x76, 0x61,
0x78, 0x2f, 0x6e, 0x61, 0x6d, 0x69, 0x6e, 0x67,
0x2f, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74,
0x3b, 0x29, 0x56,
}
// Relevant commit: https://github.com/apache/logging-log4j2/commit/44569090f1cf1e92c711fb96dfd18cd7dccc72ea
// In 2.16 the JndiManager class added the method `isJndiEnabled`. This was
// done so the Interpolator could check if JNDI was enabled. We expect the
// existence of this method should be relatively stable over time.
//
// This is definitely a bit brittle and may mean we fail to detect future versions
// correctly (e.g. if there is a 2.17 that changes the name of the method).
// What we really would like is something that was removed (a method, a
// constructor, a string, anything...) in 2.16. But there isn't anything
// so we have to rely on this brittle solution.
//
// Since this is so brittle, we're keeping the above rule that can reliably and
// non-brittle-ey detect <2.15 as a back up.
log4j216Detector = []byte("isJndiEnabled")
)
func matchesLog4JYARARule(b []byte) bool {
start := 0
for {
i := bytes.Index(b[start:], log4JYARAPrefix)
if i < 0 {
return false
}
n := i + len(log4JYARAPrefix)
if len(b) <= n {
return false
}
j := bytes.Index(b[n:], log4JYARASuffix)
if j < 0 {
return false
}
if (j - i) <= 3 {
return true
}
start = i + len(log4JYARAPrefix)
}
}
func matchesTwoSixteen(b []byte) bool {
return bytes.Contains(b, log4j216Detector)
}