File: elf.go

package info (click to toggle)
adequate 0.17.6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 488 kB
  • sloc: python: 254; makefile: 111; sh: 75; ansic: 29
file content (467 lines) | stat: -rw-r--r-- 11,950 bytes parent folder | download | duplicates (2)
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// This file is part of the adequate Debian-native package, and is available
// under the Expat license. For the full terms please see debian/copyright.

package main

import (
	"fmt"
	"log"
	"os"
	osUser "os/user"
	"path"
	"path/filepath"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"syscall"
)

const (
	BIN_OR_SBIN_BINARY_REQUIRES_USR_LIB_LIBRARY_TAG = "bin-or-sbin-binary-requires-usr-lib-library" // obsolete given usrmerge
	UNDEFINED_SYMBOL_TAG                            = "undefined-symbol"
	SYMBOL_SIZE_MISMATCH_TAG                        = "symbol-size-mismatch"
	MISSING_SYMBOL_VERSION_INFORMATION_TAG          = "missing-symbol-version-information"
	LIBRARY_NOT_FOUND_TAG                           = "library-not-found"
	INCOMPATIBLE_LICENSES_TAG                       = "incompatible-licenses" // obsolete
	LDD_FAILURE_TAG                                 = "ldd-failure"
)

var elfTags = []string{
	BIN_OR_SBIN_BINARY_REQUIRES_USR_LIB_LIBRARY_TAG,
	UNDEFINED_SYMBOL_TAG,
	SYMBOL_SIZE_MISMATCH_TAG,
	MISSING_SYMBOL_VERSION_INFORMATION_TAG,
	LIBRARY_NOT_FOUND_TAG,
	INCOMPATIBLE_LICENSES_TAG,
	LDD_FAILURE_TAG,
}

type elfErr struct {
	tag    string
	pkg    string
	path   string
	symbol string
	lib    string
	err    error
}

func (c elfErr) Error() string {
	switch c.tag {
	case LDD_FAILURE_TAG:
		return fmt.Sprintf("%s: %s => %s (%s)", c.pkg, c.tag, c.symbol, c.err)
	case UNDEFINED_SYMBOL_TAG:
		// libparted-fs-resize0:amd64: undefined-symbol /lib/x86_64-linux-gnu/libparted-fs-resize.so.0.0.4 => ptt_geom_clear_sectors
		var optionalLib string
		if c.lib != "" {
			optionalLib = " (" + c.lib + ")"
		}
		return fmt.Sprintf("%s: %s %s => %s%s", c.pkg, c.tag, c.path, c.symbol, optionalLib)
	case SYMBOL_SIZE_MISMATCH_TAG:
		return fmt.Sprintf("%s: %s %s => %s", c.pkg, c.tag, c.path, c.symbol)
	case MISSING_SYMBOL_VERSION_INFORMATION_TAG:
		return fmt.Sprintf("%s: %s %s => %s", c.pkg, c.tag, c.path, c.lib)
	case LIBRARY_NOT_FOUND_TAG:
		return fmt.Sprintf("%s: %s %s => %s", c.pkg, c.tag, c.path, c.lib)
	default:
		log.Fatal("Invalid elf error tag: ", c.tag)
		return "" // will never get here
	}
}

type elfChecker struct {
	tagsToEmit      map[string]bool
	doNotEmitAnyTag bool
	ids             lddIDs
}

func newElfChecker(tags tagFilter, ids lddIDs) elfChecker {
	emit := make(map[string]bool)
	var emitAny bool
	for _, t := range elfTags {
		emit[t] = tags.shouldEmit(t)
		if tags.shouldEmit(t) {
			emitAny = true
		}
	}
	return elfChecker{
		tagsToEmit:      emit,
		doNotEmitAnyTag: !emitAny,
		ids:             ids,
	}
}

func (cc elfChecker) check(pkg2files map[string][]string) []error {
	if cc.doNotEmitAnyTag {
		return nil
	}

	clearLDDenvOrDie()
	applyIDsOrDie(cc.ids)

	dirsToCheck := map[string]bool{
		"/bin":       true,
		"/sbin":      true,
		"/usr/bin":   true,
		"/usr/games": true,
		"/usr/sbin":  true,
	}
	out, err := runCommand([]string{"/sbin/ldconfig", "-p"})
	if err != nil {
		log.Fatal("ldconfig: ", err)
	}

	// sample input:
	// 	libxml2.so.2 (libc6,x86-64) => /lib/x86_64-linux-gnu/libxml2.so.2
	// sample output:
	//	/lib/x86_64-linux-gnu
	ldcRE := regexp.MustCompile(spaceToken + "[(]libc[^)]+[)]" + spaceToken + "=>" + spaceToken + "(" + nonSpaceToken + ")[/][^/]+$")
	for _, line := range out {
		if m := ldcRE.FindStringSubmatch(line); len(m) == 2 {
			dirsToCheck[m[1]] = true
		}
	}

	// sample input:
	//	/lib64/ld-linux-x86-64.so.2
	dynLinkerRE := regexp.MustCompile("/lib[0-9]*/.*ld(?:-.*)[.]so(?:$|[.])")
	path2pkg := make(map[string]string)
	for pkg, files := range pkg2files {
		for _, path := range files {
			dir := filepath.Dir(path)

			if !dirsToCheck[dir] ||
				dynLinkerRE.MatchString(path) {
				continue
			}

			// Skip unless path is a readable file.
			fi, err := os.OpenFile(path, os.O_RDONLY, 0)
			if err != nil {
				continue
			}
			fi.Close()

			// If it's a symlink, does it point to an interesting directory?
			if isPathSymlink(path) {
				destPath, err := os.Readlink(path)
				if err != nil {
					continue
				}
				if !dirsToCheck[filepath.Dir(destPath)] {
					continue
				}

			}
			path2pkg[path] = pkg
		}
	}

	var tags []error
	undefSymRE := regexp.MustCompile("^undefined symbol:" + spaceToken +
		"(" + nonSpaceToken + ")(?:," + spaceToken + "version" + spaceToken +
		"(" + nonSpaceToken + "))?" + spaceToken + "[(](" + nonSpaceToken + ")[)]$")

	linkTimeRefRE := regexp.MustCompile("^symbol (" + nonSpaceToken + "), version (" +
		nonSpaceToken + ") not defined in file (" + nonSpaceToken +
		") with link time reference" + spaceToken + "[(](" + nonSpaceToken + ")[)]")

	symSizeMismatchRE := regexp.MustCompile("^(" + nonSpaceToken + "): Symbol `(" + nonSpaceToken +
		")' has different size in shared object, consider re-linking$")

	// sample input:
	//	/usr/bin/adequate-test-msvi: /lib/libadequate-test-versionless.so.0: no version information available (required by /usr/bin/adequate-test-msvi)
	missingSymbolVerRE := regexp.MustCompile("^(" + nonSpaceToken + "): (" + nonSpaceToken +
		"): no version information available [(]required by (" + nonSpaceToken + ")[)]$")
	missingLibRE := regexp.MustCompile("^[\t ]*(" + nonSpaceToken + ") => not found$")
	libthreadRE := regexp.MustCompile(`libthread_db\.so(\.[0-9.]+)?$`)

	for path, pkg := range path2pkg {
		if is, err := isDir(path); err == nil && is {
			continue
		} else if err != nil {
			log.Printf("W: failed to stat %q: %s", path, err)
			continue
		}
		output, err := runCommand([]string{"/usr/bin/ldd", "-r", path})
		if e := strings.TrimSpace(strings.Join(output, " ")); e == "statically linked" || e == "not a dynamic executable" {
			continue
		}

		if err != nil {
			if !cc.tagsToEmit[LDD_FAILURE_TAG] {
				continue
			}

			tags = append(tags, elfErr{
				tag:  LDD_FAILURE_TAG,
				pkg:  pkg,
				path: path,
				err:  err,
			})
			continue
		}

		for _, line := range output {
			line = strings.TrimSpace(line)
			if m := undefSymRE.FindStringSubmatch(line); len(m) == 4 {
				if !cc.tagsToEmit[UNDEFINED_SYMBOL_TAG] {
					continue
				}
				symbol := m[1]
				if m[2] != "" {
					symbol = m[1] + "@" + m[2]
				}
				triggeringPath := m[3]
				switch {
				case (strings.Contains(path, "python3") || strings.Contains(path, "py3")) &&
					(strings.HasPrefix(symbol, "_Py") || strings.HasPrefix(symbol, "Py")):
					continue
				case strings.Contains(path, "perl") &&
					strings.HasPrefix(symbol, "Perl_") || strings.HasPrefix(symbol, "PL_"):
					continue
				case strings.Contains(path, "liblua") &&
					(strings.HasPrefix(symbol, "luaL_") || strings.HasPrefix(symbol, "lua_")):
					continue
				case libthreadRE.MatchString(path) && strings.HasPrefix(symbol, "ps_"):
					continue
				}

				augmentedPath := augmentPath(path, triggeringPath, dirsToCheck)
				if augmentedPath == "" {
					continue
				}

				tags = append(tags, elfErr{
					tag:    UNDEFINED_SYMBOL_TAG,
					pkg:    pkg,
					path:   augmentedPath,
					symbol: symbol,
				})
				continue
			}
			if m := linkTimeRefRE.FindStringSubmatch(line); len(m) == 4 {
				if !cc.tagsToEmit[UNDEFINED_SYMBOL_TAG] {
					continue
				}
				symbol := m[1] + "@" + m[2]
				lib := m[3]
				triggeringPath := m[4]
				augmentedPath := augmentPath(path, triggeringPath, dirsToCheck)
				if augmentedPath == "" {
					continue
				}

				tags = append(tags, elfErr{
					tag:    UNDEFINED_SYMBOL_TAG,
					pkg:    pkg,
					path:   augmentedPath,
					symbol: symbol,
					lib:    lib,
				})
				continue
			}
			if m := symSizeMismatchRE.FindStringSubmatch(line); len(m) == 3 {
				if !cc.tagsToEmit[SYMBOL_SIZE_MISMATCH_TAG] {
					continue
				}
				if m[1] != path {
					continue
				}
				symbol := m[2]
				tags = append(tags, elfErr{
					tag:    SYMBOL_SIZE_MISMATCH_TAG,
					pkg:    pkg,
					path:   path,
					symbol: symbol,
				})
				continue
			}
			if m := missingSymbolVerRE.FindStringSubmatch(line); len(m) == 4 {
				if !cc.tagsToEmit[MISSING_SYMBOL_VERSION_INFORMATION_TAG] {
					continue
				}
				path = m[1]
				lib := m[2]
				triggeringPath := m[3]
				augmentedPath := augmentPath(path, triggeringPath, dirsToCheck)
				if augmentedPath == "" {
					continue
				}

				tags = append(tags, elfErr{
					tag:  MISSING_SYMBOL_VERSION_INFORMATION_TAG,
					pkg:  pkg,
					path: augmentedPath,
					lib:  lib,
				})
				continue
			}
			if m := missingLibRE.FindStringSubmatch(line); len(m) == 2 {
				if !cc.tagsToEmit[LIBRARY_NOT_FOUND_TAG] {
					continue
				}
				lib := m[1]
				tags = append(tags, elfErr{
					tag:  LIBRARY_NOT_FOUND_TAG,
					pkg:  pkg,
					path: path,
					lib:  lib,
				})
				continue
			}
		}
	}

	return tags
}

type lddIDs struct {
	uid int
	gid int
}

type idSpecErr struct {
	user  string
	group string
}

func (u idSpecErr) Error() string {
	if u.user != "" {
		return fmt.Sprintf("%q: no such user", u.user)
	}
	if u.group != "" {
		return fmt.Sprintf("%q: no such group", u.group)
	}
	return "invalid user/group specification"
}

func newLDDids(spec string) (lddIDs, error) {
	var ids lddIDs
	if spec == "" {
		return ids, nil
	}

	var user, group string
	tokens := strings.Split(spec, ":")
	switch n := len(tokens); {
	case n == 1:
		user = tokens[0]
	case n == 2 && spec != ":":
		user = tokens[0]
		group = tokens[1]
	default:
		return ids, idSpecErr{}
	}

	if user != "" {
		u, err := osUser.Lookup(user)
		if err != nil {
			return ids, idSpecErr{user: user}
		}
		n, err := strconv.Atoi(u.Uid)
		if err != nil {
			return lddIDs{}, fmt.Errorf("failed to parse uid %q: %w", u, err)
		}
		ids.uid = n
	}
	if group != "" {
		g, err := osUser.LookupGroup(group)
		if err != nil {
			return ids, idSpecErr{group: group}
		}
		n, err := strconv.Atoi(g.Gid)
		if err != nil {
			return lddIDs{}, fmt.Errorf("failed to parse gid %q: %w", g, err)
		}
		ids.gid = n
	}

	return ids, nil
}

func clearLDDenvOrDie() {
	for _, s := range os.Environ() {
		k := strings.Split(s, "=")[0]
		if !strings.HasPrefix(k, "LD_") {
			continue
		}
		if err := os.Unsetenv(k); err != nil {
			log.Fatal("Failed to clear environment variable ", k)
		}
	}
}

// parseCopyrightFiles returns a map of pkg to license.
func parseCopyrightFiles(pkgs []string) map[string]string {
	pkg2license := make(map[string]string)

	return pkg2license
}

func augmentPath(origPath, trigPath string, dirs map[string]bool) string {
	if origPath == trigPath {
		return trigPath
	}

	// Verify that file can be stat'ed ...
	fi, err := os.Lstat(trigPath)
	if os.IsPermission(err) || err != nil {
		log.Fatal("stat: ", err)
	}
	dstAbs := trigPath
	// ... and resolve if it's a symlink.
	if isSymlink(fi) {
		dst, err := os.Readlink(trigPath)
		if os.IsPermission(err) || err != nil {
			log.Fatal("readlink: ", err)
		}

		if filepath.IsAbs(dst) {
			dstAbs = dst
		} else {
			// Symlink targets are relative to the directory containing the link.
			dstAbs = filepath.Join(path.Dir(trigPath), dst)
		}
		// If the symlink target is still in an “interesting” directory,
		// then any issue hopefully will be reported against another
		// package.
		if dirs[path.Dir(dstAbs)] {
			return ""
		}
	}
	return fmt.Sprintf("%s => %s", origPath, dstAbs)
}

func applyIDsOrDie(want lddIDs) {
	if want.uid == 0 && want.gid == 0 {
		return
	}

	if gotUid := os.Geteuid(); gotUid != want.uid {
		if err := syscall.Setuid(want.uid); err != nil {
			log.Fatal("Could not set uid to ", want.uid)
		}
		if id := os.Geteuid(); id != want.uid {
			log.Fatal("Setuid() returned no error but also had no effect!")
		}
	}

	if gotGid := os.Getegid(); gotGid != want.gid {
		if err := syscall.Setuid(want.gid); err != nil {
			log.Fatal("Could not set gid to ", want.gid)
		}
		if id := os.Getegid(); id != want.gid {
			log.Fatal("Setgid() returned no error but also had no effect!")
		}
	}
}

// TODO: Drop once maps.Keys() moves to the stdlib.
func mapStrKeys(m map[string][]string) []string {
	var keys []string
	for k := range m {
		keys = append(keys, k)
	}
	return sort.StringSlice(keys)
}