forked from pkujhd/goloader
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmacho_darwin.go
197 lines (180 loc) · 4.98 KB
/
macho_darwin.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
//go:build darwin && !no_darwin_patch
// +build darwin,!no_darwin_patch
package goloader
import (
"bytes"
"debug/macho"
"encoding/binary"
"fmt"
"io"
"log"
"math/rand"
"os"
"os/exec"
"runtime"
"syscall"
"unsafe"
)
func init() {
path, err := os.Executable()
if err != nil {
panic(fmt.Errorf("could not find executable path: %w", err))
}
// This is somewhat insane, but hey ¯\_(ツ)_/¯
havePatched, err := PatchMachoSelfMakeWriteable(path)
if err != nil {
panic(err)
}
if havePatched {
// Replace ourselves with the newly patched binary
// Since this is inside the init function, there shouldn't be too much program state built up...
log.Printf("patched Mach-O __TEXT segment to make writeable, restarting\n")
if runtime.GOARCH == "arm64" {
// Kernel caches code signing info for an inode so you have to replace it entirely
f, err := os.OpenFile(fmt.Sprintf("jit_bin_%x", rand.Uint64()), os.O_CREATE|os.O_WRONLY, 0755)
if err != nil {
panic(err)
}
orig, err := os.OpenFile(path, os.O_RDONLY, 0755)
if err != nil {
panic(err)
}
_, err = io.Copy(f, orig)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
// What is the point of code signing if you can just do this?
err = exec.Command("codesign", "-s", "-", f.Name()).Run()
if err != nil {
panic(err)
}
err = os.Rename(f.Name(), path)
if err != nil {
panic(err)
}
}
err = syscall.Exec(os.Args[0], os.Args, os.Environ())
if err != nil {
panic(err)
}
}
}
const Write = 2
const (
fileHeaderSize32 = 7 * 4
fileHeaderSize64 = 8 * 4
)
func PatchMachoSelfMakeWriteable(path string) (bool, error) {
r, err := os.OpenFile(path, os.O_RDWR, 0755)
if err != nil {
return false, fmt.Errorf("could not open file %s: %w", path, err)
}
sr := io.NewSectionReader(r, 0, 1<<63-1)
var ident [4]byte
if _, err := r.ReadAt(ident[0:], 0); err != nil {
return false, fmt.Errorf("could not read first 4 bytes of file %s: %w", path, err)
}
be := binary.BigEndian.Uint32(ident[0:])
le := binary.LittleEndian.Uint32(ident[0:])
var magic uint32
var bo binary.ByteOrder
switch macho.Magic32 &^ 1 {
case be &^ 1:
bo = binary.BigEndian
magic = be
case le &^ 1:
bo = binary.LittleEndian
magic = le
default:
return false, fmt.Errorf("invalid magic number 0x%x", magic)
}
header := macho.FileHeader{}
if err := binary.Read(sr, bo, &header); err != nil {
return false, fmt.Errorf("could not read macho file header of file %s: %w", path, err)
}
offset := int64(fileHeaderSize32)
if magic == macho.Magic64 {
offset = fileHeaderSize64
}
dat := make([]byte, header.Cmdsz)
if _, err := r.ReadAt(dat, offset); err != nil {
return false, fmt.Errorf("failed to read macho command data: %w", err)
}
var havePatched = false
for i := 0; i < int(header.Ncmd); i++ {
if len(dat) < 8 {
return false, fmt.Errorf("command block too small")
}
cmd, siz := macho.LoadCmd(bo.Uint32(dat[0:4])), bo.Uint32(dat[4:8])
if siz < 8 || siz > uint32(len(dat)) {
return false, fmt.Errorf("invalid command block size")
}
var cmddat []byte
cmddat, dat = dat[0:siz], dat[siz:]
switch cmd {
case macho.LoadCmdSegment:
var seg32 macho.Segment32
b := bytes.NewReader(cmddat)
if err := binary.Read(b, bo, &seg32); err != nil {
return false, fmt.Errorf("failed to read LoadCmdSegment: %w", err)
}
if cstring(seg32.Name[0:]) == "__TEXT" {
if seg32.Maxprot&Write == 0 {
buf := make([]byte, 4)
_, err := r.ReadAt(buf, offset+int64(unsafe.Offsetof(seg32.Maxprot)))
if err != nil {
return false, fmt.Errorf("failed to read MaxProt uint32: %w", err)
}
newPerms := bo.Uint32(buf) | Write
bo.PutUint32(buf, newPerms)
_, err = r.WriteAt(buf, offset+int64(unsafe.Offsetof(seg32.Maxprot)))
if err != nil {
return false, fmt.Errorf("failed to write MaxProt uint32: %w", err)
}
if seg32.Maxprot != newPerms {
havePatched = true
}
}
textIsWriteable = true
}
case macho.LoadCmdSegment64:
var seg64 macho.Segment64
b := bytes.NewReader(cmddat)
if err := binary.Read(b, bo, &seg64); err != nil {
return false, fmt.Errorf("failed to read LoadCmdSegment64: %w", err)
}
if cstring(seg64.Name[0:]) == "__TEXT" {
if seg64.Maxprot&Write == 0 {
buf := make([]byte, 4)
_, err := r.ReadAt(buf, offset+int64(unsafe.Offsetof(seg64.Maxprot)))
if err != nil {
return false, fmt.Errorf("failed to read MaxProt uint32: %w", err)
}
newPerms := bo.Uint32(buf) | Write
bo.PutUint32(buf, newPerms)
_, err = r.WriteAt(buf, offset+int64(unsafe.Offsetof(seg64.Maxprot)))
if err != nil {
return false, fmt.Errorf("failed to write MaxProt uint32: %w", err)
}
if seg64.Maxprot != newPerms {
havePatched = true
}
}
textIsWriteable = true
}
}
offset += int64(siz)
}
return havePatched, nil
}
func cstring(b []byte) string {
i := bytes.IndexByte(b, 0)
if i == -1 {
i = len(b)
}
return string(b[0:i])
}