-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcommands.cpp
358 lines (286 loc) · 11.1 KB
/
commands.cpp
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
#include <algorithm>
#include <cstring>
#include <memory>
#include <string>
#include <sstream>
#include <sys/stat.h>
#include <spawn.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "commands.h"
#include "macho.h"
#include "signature.h"
extern char **environ;
namespace SigTool {
constexpr const unsigned int pageSize = 4096;
static std::string readFile(const std::string &filename) {
std::ifstream in{filename, std::ifstream::in | std::ifstream::binary};
if (!in.is_open()) {
throw std::runtime_error{"Failed opening file for read: '"
+ filename + "' :" + strerror(errno)};
}
std::string str;
in.seekg(0, std::ifstream::end);
str.resize(in.tellg());
in.seekg(0, std::ifstream::beg);
in.read(&str[0], str.size());
return str;
}
static Hash hashBlob(const std::shared_ptr<Blob> &blob) {
std::basic_ostringstream<char> buf;
blob->emit(buf);
return Hash{buf.str()};
}
std::string cpuTypeName(uint32_t cpuType, uint32_t cpuSubType) {
switch (cpuType | cpuSubType) {
case CPUTYPE_X86_64:
return "x86_64";
case CPUTYPE_X86_64H:
return "x86_64h";
case CPUTYPE_ARM64:
return "arm64";
case CPUTYPE_ARM64E:
return "arm64e";
default:
throw std::runtime_error{std::string{"Unsupported cpu type"} + std::to_string(cpuType)};
}
}
int Commands::checkRequiresSignature(const std::string &file) {
try {
MachOList test{file};
bool anyRequires = std::any_of(test.machos.begin(), test.machos.end(), [](const std::shared_ptr<MachO> &h) {
return h->requiresSignature();
});
return anyRequires ? 0 : 1;
} catch (NotAMachOFileException &e) {
// A shell script or text file, for example, does not require a signature.
return 1;
}
}
int Commands::showArch(const std::string &file) {
MachOList test{file};
for (const auto &macho : test.machos) {
std::cout << cpuTypeName(macho->header.cpuType, macho->header.cpuSubType) << std::endl;
}
return 0;
}
static SuperBlob signMachO(
const Commands::SignOptions &options,
const std::shared_ptr<MachO> &target
) {
SuperBlob sb{};
// blob 1: code directory
auto codeDirectory = std::make_shared<CodeDirectory>();
codeDirectory->identifier = options.identifier.empty() ? options.filename : options.identifier;
codeDirectory->setPageSize(pageSize);
// TOOD: is this sane?
if (target->header.filetype == MH_EXECUTE) {
codeDirectory->data.execSegFlags |= CS_EXECSEG_MAIN_BINARY;
}
auto textSegment = target->getSegment64LoadCommand("__TEXT");
if (textSegment) {
codeDirectory->data.execSegBase = textSegment->data.fileoff;
codeDirectory->data.execSegLimit = textSegment->data.fileoff + textSegment->data.filesize;
}
size_t limit = target->size;
auto codeSignature = target->getCodeSignatureLoadCommand();
if (codeSignature) {
limit = codeSignature->data.dataOff;
codeDirectory->setCodeLimit(codeSignature->data.dataOff);
}
std::ifstream machoFileRaw;
machoFileRaw.open(options.filename, std::ifstream::in | std::ifstream::binary);
machoFileRaw.seekg(target->offset);
if (machoFileRaw.fail()) {
throw std::runtime_error(std::string{"opening macho file: "} + strerror(errno));
}
unsigned int totalPages = (limit + (pageSize - 1)) / pageSize;
for (int page = 0; page < totalPages; page++) {
char pageBytes[pageSize];
off_t thisPageStart = page * pageSize;
size_t thisPageSize = pageSize;
if (thisPageStart + thisPageSize > limit) {
thisPageSize = limit - thisPageStart;
}
machoFileRaw.read(&pageBytes[0], thisPageSize);
if (machoFileRaw.fail()) {
throw std::runtime_error(std::string{"reading page: "}
+ std::to_string(page) + " " + strerror(errno) + " expcted_bytes="
+ std::to_string(thisPageSize) + " actual_bytes" +
std::to_string(machoFileRaw.gcount()));
}
Hash pageHash{&pageBytes[0], thisPageSize};
codeDirectory->addCodeHash(pageHash);
}
machoFileRaw.close();
sb.blobs.push_back(codeDirectory);
// blob 2: requirements index with 0 entries
auto requirements = std::make_shared<Requirements>();
codeDirectory->setSpecialHash(requirements->slotType(), hashBlob(requirements));
sb.blobs.push_back(requirements);
// optional blob: entitlements
if (!options.entitlements.empty()) {
auto entitlements = std::make_shared<Entitlements>(readFile(options.entitlements));
codeDirectory->setSpecialHash(entitlements->slotType(), hashBlob(entitlements));
sb.blobs.push_back(entitlements);
}
// blob: empty signature slot
sb.blobs.emplace_back(std::make_shared<Signature>());
return sb;
}
int Commands::showSize(const SignOptions &options) {
MachOList list{options.filename};
for (const auto &macho : list.machos) {
auto sb = signMachO(options, macho);
std::cout << cpuTypeName(macho->header.cpuType, macho->header.cpuSubType) << " " << sb.length() << std::endl;
}
return 0;
}
int Commands::generate(const SignOptions &options) {
MachOList list{options.filename};
for (const auto &macho : list.machos) {
auto sb = signMachO(options, macho);
// TODO: packing them all together is not helpful, but this is still usable
// for the thin case.
sb.emit(std::cout);
}
return 0;
}
int Commands::inject(const SignOptions &options) {
MachOList list{options.filename};
for (const auto &macho : list.machos) {
auto sb = signMachO(options, macho);
auto codeSignature = macho->getCodeSignatureLoadCommand();
if (!codeSignature) {
throw std::runtime_error{"cannot inject signature without appropriate load command"};
}
if (sb.length() > codeSignature->data.dataSize) {
throw std::runtime_error{
std::string{"allocated size too small: need "}
+ std::to_string(sb.length())
+ std::string{" but have "}
+ std::to_string(codeSignature->data.dataSize)
};
}
std::ofstream machoFileWrite;
machoFileWrite.open(options.filename, std::ofstream::in | std::ofstream::out | std::ofstream::binary);
if (machoFileWrite.fail()) {
throw std::runtime_error(std::string{"opening macho file: "} + strerror(errno));
}
machoFileWrite.seekp(macho->offset + codeSignature->data.dataOff);
sb.emit(machoFileWrite);
machoFileWrite.close();
}
return 0;
}
static char **toSpawnArgs(const std::vector<std::string> &args) {
char **spawnArgs = reinterpret_cast<char **>(
calloc(args.size() + 1, sizeof(char *)));
for (int i = 0; i < args.size(); i++) {
spawnArgs[i] = strdup(args[i].c_str());
}
spawnArgs[args.size()] = nullptr;
return spawnArgs;
}
static void freeArgs(char **spawnArgs, std::vector<std::string>::size_type size) {
for (int i = 0; i < size; i++) {
free(spawnArgs[i]);
}
free(spawnArgs);
}
static std::string inferIdentifier(const std::string& filename) {
// basename / basename_r are awkward to use. We don't need the exact
// meaning of basename.
const auto slash = filename.find_last_of('/');
if (slash == std::string::npos) {
return filename;
}
std::string basename = filename.substr(slash + 1);
if (basename.empty()) {
return filename;
}
return basename;
}
int Commands::codesign(const CodesignOptions &options, const std::string &filename) {
std::string identifier = options.identifier;
if (identifier.empty()) {
identifier = inferIdentifier(filename);
}
// Parse and discovery arguments
MachOList list{filename};
std::vector<std::string> arguments;
arguments.emplace_back("codesign_allocate");
arguments.emplace_back("-i");
arguments.emplace_back(filename);
for (const auto &macho : list.machos) {
auto codeSignature = macho->getCodeSignatureLoadCommand();
if (!options.force && codeSignature) {
throw std::runtime_error{"file is already signed. pass -f to sign regardless."};
}
auto sb = signMachO(SignOptions{
.filename = filename,
.identifier = identifier,
.entitlements = options.entitlements,
}, macho);
arguments.emplace_back("-A");
arguments.emplace_back(std::to_string(macho->header.cpuType));
arguments.emplace_back(std::to_string(macho->header.cpuSubType & ~CPU_SUBTYPE_MASK));
size_t len = sb.length();
len = ((len + 0xf) & ~0xf) + 1024; // align and pad
arguments.push_back(std::to_string(len));
}
// Make temporary name
std::unique_ptr<char, decltype(&std::free)> tempfileName { strdup((filename + "XXXXXX").c_str()), std::free };
int tempfile = mkstemp(tempfileName.get());
// Preserve mode
struct stat sourceFileStat{};
if (stat(filename.c_str(), &sourceFileStat) != 0) {
throw std::runtime_error{std::string{"stat of "} + filename + " failed: " + strerror(errno)};
}
if (fchmod(tempfile, sourceFileStat.st_mode) != 0) {
throw std::runtime_error{"chmod temporary file"};
}
arguments.emplace_back("-o");
arguments.emplace_back(std::string(tempfileName.get()));
// codesign_allocate
pid_t pid;
char **spawnArgs = toSpawnArgs(arguments);
const char *codesign_allocate = getenv("CODESIGN_ALLOCATE");
if (!codesign_allocate) {
codesign_allocate = "codesign_allocate";
}
int spawn_result;
if ((spawn_result = posix_spawnp(&pid, codesign_allocate, nullptr, nullptr, spawnArgs, environ)) != 0) {
throw std::runtime_error{std::string{"Failed to spawn codesign_allocate: "} + strerror(spawn_result)};
};
int codesign_status;
pid_t waitpid_result;
do {
waitpid_result = waitpid(pid, &codesign_status, 0);
} while (waitpid_result == -1 && errno == EINTR);
if (waitpid_result == -1) {
throw std::runtime_error{
std::string{"codesign waitpid failed: "} + strerror(errno)
};
}
freeArgs(spawnArgs, arguments.size());
if (!WIFEXITED(codesign_status) || WEXITSTATUS(codesign_status) != 0) {
throw std::runtime_error{std::string{"codesign_failed: "} + std::to_string(WEXITSTATUS(codesign_status))};
}
if (close(tempfile) != 0) {
throw std::runtime_error{std::string{"close: "} + strerror(tempfile)};
}
// inject
Commands::inject(SignOptions{
.filename = std::string(tempfileName.get()),
.identifier = identifier,
.entitlements = options.entitlements,
});
// rename temp file to output
if (rename(tempfileName.get(), filename.c_str()) != 0) {
throw std::runtime_error{"rename failed"};
}
return 0;
}
};