-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathmain.go
233 lines (196 loc) · 5.95 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
package main
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"syscall"
"github.com/nirhaas/gopacker/lib"
"github.com/pkg/errors"
)
const (
usageString = "USAGE: gopacker <executable_path>"
packedExt = ".packed"
footerMagicString = "LALALALA"
)
var (
// Compression method.
compression = lib.ZSTDCompression{}
// Placeholders.
footerMagic = []byte(footerMagicString)
selfPath string
inputPath string
packedPath string
unpackedPath string
)
// Writer that counts how many bytes were written. User here to get compressed
// size when streaming with io.Copy.
type counterWriter struct {
io.Writer
n int
}
func (w *counterWriter) Write(buf []byte) (n int, err error) {
n, err = w.Writer.Write(buf)
w.n += n
return n, err
}
func appendToFile(dst string, in io.Reader, compress bool) (n int64, err error) {
// Check that destination file exists.
_, err = os.Stat(dst)
if err != nil {
return 0, errors.Wrap(err, "destination file does not exist")
}
// Open file on APPEND mode.
destination, err := os.OpenFile(dst, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return 0, errors.Wrap(err, "failed opening destination file")
}
defer func() {
if err == nil {
err = destination.Close()
}
}()
// Compress and stream.
if compress {
cw := &counterWriter{Writer: destination}
_, err := lib.CompressStream(compression, cw, in)
return int64(cw.n), errors.Wrap(err, "failed appending compressed to destination")
}
// Just stream.
return io.Copy(destination, in)
}
func copyFile(src, dst string) (err error) {
// Verify that source file exists.
sourceFileStat, err := os.Stat(src)
if err != nil {
return errors.Wrap(err, "src file does not exist")
}
if !sourceFileStat.Mode().IsRegular() {
return fmt.Errorf("%s is not a regular file", src)
}
// Open source file.
source, err := os.Open(src)
if err != nil {
return errors.Wrap(err, "failed opening source file")
}
defer func() { _ = source.Close() }() // Best effort.
// Open dest file.
destination, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0755)
if err != nil {
return errors.Wrap(err, "failed opening destination file")
}
defer func() {
if err == nil {
err = destination.Close()
}
}()
// Copy.
_, err = io.Copy(destination, source)
return err
}
// CLI tool.
func mainCLI() {
// Parse arg.
if len(os.Args) == 1 {
fmt.Println(usageString)
return
}
inputPath = os.Args[1]
packedPath = os.Args[1] + packedExt
// See that the file exists.
if _, err := os.Stat(os.Args[1]); err != nil {
log.Fatal(errors.Wrap(err, "target exec does not exist"))
}
// Copy self (stub) to final path.
if err := copyFile(selfPath, packedPath); err != nil {
log.Fatal(errors.Wrap(err, "failed copying stub"))
}
// Open packed.
packedPathHandle, err := os.Open(os.Args[1])
if err != nil {
log.Fatal(errors.Wrap(err, "failed opening packed path"))
}
// Compress and append to final path.
bytesWritten, err := appendToFile(packedPath, packedPathHandle, true)
if err != nil {
log.Fatal(errors.Wrap(err, "failed appending stub"))
}
// Append footer.
bs := make([]byte, 8)
binary.LittleEndian.PutUint64(bs, uint64(bytesWritten))
if _, err := appendToFile(packedPath, bytes.NewReader(bs), false); err != nil {
log.Fatal(errors.Wrap(err, "failed appending len"))
}
if _, err := appendToFile(packedPath, bytes.NewReader(footerMagic), false); err != nil {
log.Fatal(errors.Wrap(err, "failed appending magic"))
}
}
// This is a stub. Unpack and run.
func mainStub(selfFileHandle *os.File, fileSize int64) {
unpackedPath = selfPath
// Read DWORD before the magic, which is the data length to extract.
dstLen := make([]byte, 8)
if _, err := selfFileHandle.Seek(fileSize-int64(len(footerMagic))-int64(len(dstLen)), 0); err != nil {
log.Fatal(errors.Wrap(err, "failed seeking length"))
}
if _, err := selfFileHandle.Read(dstLen); err != nil {
log.Fatal(errors.Wrap(err, "failed reading length"))
}
targetLen := int64(binary.LittleEndian.Uint64(dstLen))
// Decompress all to memory. We don't stream here so we can overwrite the current
// executable. Streaming where src and dst are equal just breaks everything.
var buf bytes.Buffer
compressedOff := fileSize - int64(len(footerMagic)) - int64(len(dstLen)) - targetLen
compressedReader := io.NewSectionReader(selfFileHandle, compressedOff, targetLen)
if _, err := lib.DecompressStream(compression, &buf, compressedReader); err != nil {
log.Fatal(errors.Wrap(err, "failed writing unpacked file"))
}
// Write to file (overwrite).
if err := ioutil.WriteFile(unpackedPath, buf.Bytes(), 0755); err != nil {
log.Fatal(errors.Wrap(err, "failed writing unpacked file"))
}
// Exec.
if err := syscall.Exec(unpackedPath, []string{unpackedPath}, os.Environ()); err != nil {
log.Fatal(errors.Wrap(err, "failed exec-ing to unpacked executable"))
}
}
func main() {
// No := so selfPath won't be overridden.
var err error
selfPath, err = exec.LookPath(os.Args[0])
if err != nil {
log.Fatal(errors.Wrap(err, "failed expanding self path"))
}
// Get self (stub) executable path.
selfFileStat, err := os.Stat(selfPath)
if err != nil {
log.Fatal(errors.Wrap(err, "failed stat self file"))
}
// Open self.
selfFileHandle, err := os.Open(selfPath)
if err != nil {
log.Fatal(errors.Wrap(err, "failed opening self file"))
}
defer func() { _ = selfFileHandle.Close() }() // Best effort.
// Read the end of the file to get the magic.
dstMagic := make([]byte, len(footerMagic))
if _, err := selfFileHandle.Seek(selfFileStat.Size()-int64(len(footerMagic)), 0); err != nil {
log.Fatal(errors.Wrap(err, "failed seeking magic"))
}
if _, err := selfFileHandle.Read(dstMagic); err != nil {
log.Fatal(errors.Wrap(err, "failed reading magic"))
}
// Compare found magic with expected magic.
if !bytes.Equal(footerMagic, dstMagic) {
// Magic not found - CLI tool.
mainCLI()
return
}
// Magic found - this is a stub.
mainStub(selfFileHandle, selfFileStat.Size())
return
}