1 /* ldid - (Mach-O) Link-Loader Identity Editor
2 * Copyright (C) 2007-2015 Jay Freeman (saurik)
5 /* GNU Affero General Public License, Version 3 {{{ */
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
43 #include <sys/types.h>
46 #include <openssl/err.h>
47 #include <openssl/pem.h>
48 #include <openssl/pkcs7.h>
49 #include <openssl/pkcs12.h>
53 #include <CommonCrypto/CommonDigest.h>
55 #define LDID_SHA1_DIGEST_LENGTH CC_SHA1_DIGEST_LENGTH
56 #define LDID_SHA1 CC_SHA1
57 #define LDID_SHA1_CTX CC_SHA1_CTX
58 #define LDID_SHA1_Init CC_SHA1_Init
59 #define LDID_SHA1_Update CC_SHA1_Update
60 #define LDID_SHA1_Final CC_SHA1_Final
62 #define LDID_SHA256_DIGEST_LENGTH CC_SHA256_DIGEST_LENGTH
63 #define LDID_SHA256 CC_SHA256
64 #define LDID_SHA256_CTX CC_SHA256_CTX
65 #define LDID_SHA256_Init CC_SHA256_Init
66 #define LDID_SHA256_Update CC_SHA256_Update
67 #define LDID_SHA256_Final CC_SHA256_Final
69 #include <openssl/sha.h>
71 #define LDID_SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH
72 #define LDID_SHA1 SHA1
73 #define LDID_SHA1_CTX SHA_CTX
74 #define LDID_SHA1_Init SHA1_Init
75 #define LDID_SHA1_Update SHA1_Update
76 #define LDID_SHA1_Final SHA1_Final
78 #define LDID_SHA256_DIGEST_LENGTH SHA256_DIGEST_LENGTH
79 #define LDID_SHA256 SHA256
80 #define LDID_SHA256_CTX SHA256_CTX
81 #define LDID_SHA256_Init SHA256_Init
82 #define LDID_SHA256_Update SHA256_Update
83 #define LDID_SHA256_Final SHA256_Final
87 #include <plist/plist.h>
92 #define _assert___(line) \
94 #define _assert__(line) \
98 #define $(value) value
102 #define _assert_(expr, format, ...) \
104 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
105 throw $(__FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"); \
108 // XXX: this is not acceptable
109 #define _assert_(expr, format, ...) \
111 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
116 #define _assert(expr) \
117 _assert_(expr, "%s", $(#expr))
119 #define _syscall(expr, ...) [&] { for (;;) { \
121 if ((long) _value != -1) \
124 if (error == EINTR) \
126 /* XXX: EINTR is included in this list to fix g++ */ \
127 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
128 if (error == success) \
129 return (decltype(expr)) -success; \
130 _assert_(false, "errno=%u", error); \
134 fprintf(stderr, $("_trace(%s:%u): %s\n"), __FILE__, __LINE__, $(__FUNCTION__))
140 __attribute__((packed))
142 template <typename Type_
>
144 typedef typename
Type_::const_iterator Result
;
147 #define _foreach(item, list) \
148 for (bool _stop(true); _stop; ) \
149 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
150 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
151 for (bool _suck(true); _suck; _suck = false) \
152 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
157 template <typename Function_
>
165 Scope(const Function_
&function
) :
175 template <typename Function_
>
176 Scope
<Function_
> _scope(const Function_
&function
) {
177 return Scope
<Function_
>(function
);
180 #define _scope__(counter, function) \
181 __attribute__((__unused__)) \
182 const _Scope &_scope ## counter(_scope([&]function))
183 #define _scope_(counter, function) \
184 _scope__(counter, function)
185 #define _scope(function) \
186 _scope_(__COUNTER__, function)
188 #define CPU_ARCH_MASK uint32_t(0xff000000)
189 #define CPU_ARCH_ABI64 uint32_t(0x01000000)
191 #define CPU_TYPE_ANY uint32_t(-1)
192 #define CPU_TYPE_VAX uint32_t( 1)
193 #define CPU_TYPE_MC680x0 uint32_t( 6)
194 #define CPU_TYPE_X86 uint32_t( 7)
195 #define CPU_TYPE_MC98000 uint32_t(10)
196 #define CPU_TYPE_HPPA uint32_t(11)
197 #define CPU_TYPE_ARM uint32_t(12)
198 #define CPU_TYPE_MC88000 uint32_t(13)
199 #define CPU_TYPE_SPARC uint32_t(14)
200 #define CPU_TYPE_I860 uint32_t(15)
201 #define CPU_TYPE_POWERPC uint32_t(18)
203 #define CPU_TYPE_I386 CPU_TYPE_X86
205 #define CPU_TYPE_ARM64 (CPU_ARCH_ABI64 | CPU_TYPE_ARM)
206 #define CPU_TYPE_POWERPC64 (CPU_ARCH_ABI64 | CPU_TYPE_POWERPC)
207 #define CPU_TYPE_X86_64 (CPU_ARCH_ABI64 | CPU_TYPE_X86)
214 #define FAT_MAGIC 0xcafebabe
215 #define FAT_CIGAM 0xbebafeca
235 #define MH_MAGIC 0xfeedface
236 #define MH_CIGAM 0xcefaedfe
238 #define MH_MAGIC_64 0xfeedfacf
239 #define MH_CIGAM_64 0xcffaedfe
241 #define MH_DYLDLINK 0x4
243 #define MH_OBJECT 0x1
244 #define MH_EXECUTE 0x2
246 #define MH_BUNDLE 0x8
247 #define MH_DYLIB_STUB 0x9
249 struct load_command
{
254 #define LC_REQ_DYLD uint32_t(0x80000000)
256 #define LC_SEGMENT uint32_t(0x01)
257 #define LC_SYMTAB uint32_t(0x02)
258 #define LC_DYSYMTAB uint32_t(0x0b)
259 #define LC_LOAD_DYLIB uint32_t(0x0c)
260 #define LC_ID_DYLIB uint32_t(0x0d)
261 #define LC_SEGMENT_64 uint32_t(0x19)
262 #define LC_UUID uint32_t(0x1b)
263 #define LC_CODE_SIGNATURE uint32_t(0x1d)
264 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
265 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
266 #define LC_ENCRYPTION_INFO uint32_t(0x21)
267 #define LC_DYLD_INFO uint32_t(0x22)
268 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
269 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
284 uint32_t current_version
;
285 uint32_t compatibility_version
;
288 struct dylib_command
{
294 struct uuid_command
{
300 struct symtab_command
{
309 struct dyld_info_command
{
313 uint32_t rebase_size
;
316 uint32_t weak_bind_off
;
317 uint32_t weak_bind_size
;
318 uint32_t lazy_bind_off
;
319 uint32_t lazy_bind_size
;
321 uint32_t export_size
;
324 struct dysymtab_command
{
337 uint32_t extrefsymoff
;
338 uint32_t nextrefsyms
;
339 uint32_t indirectsymoff
;
340 uint32_t nindirectsyms
;
347 struct dylib_table_of_contents
{
348 uint32_t symbol_index
;
349 uint32_t module_index
;
352 struct dylib_module
{
353 uint32_t module_name
;
362 uint32_t iinit_iterm
;
363 uint32_t ninit_nterm
;
364 uint32_t objc_module_info_addr
;
365 uint32_t objc_module_info_size
;
368 struct dylib_reference
{
373 struct relocation_info
{
375 uint32_t r_symbolnum
:24;
394 struct segment_command
{
408 struct segment_command_64
{
451 struct linkedit_data_command
{
458 struct encryption_info_command
{
466 #define BIND_OPCODE_MASK 0xf0
467 #define BIND_IMMEDIATE_MASK 0x0f
468 #define BIND_OPCODE_DONE 0x00
469 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
470 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
471 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
472 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
473 #define BIND_OPCODE_SET_TYPE_IMM 0x50
474 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
475 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
476 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
477 #define BIND_OPCODE_DO_BIND 0x90
478 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
479 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
480 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
482 static auto dummy([](double) {});
484 static std::streamsize
read(std::streambuf
&stream
, void *data
, size_t size
) {
485 auto writ(stream
.sgetn(static_cast<char *>(data
), size
));
490 static inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
491 _assert(read(stream
, data
, size
) == size
);
494 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
495 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
498 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
, const ldid::Functor
<void (double)> &percent
) {
500 for (size_t total(0); total
!= size
;) {
501 auto writ(std::min(size
- total
, size_t(4096 * 4)));
502 _assert(stream
.sputn(static_cast<const char *>(data
) + total
, writ
) == writ
);
504 percent(double(total
) / size
);
508 static size_t most(std::streambuf
&stream
, void *data
, size_t size
) {
511 if (auto writ
= read(stream
, data
, size
))
517 static inline void pad(std::streambuf
&stream
, size_t size
) {
519 memset(padding
, 0, size
);
520 put(stream
, padding
, size
);
523 template <typename Type_
>
524 Type_
Align(Type_ value
, size_t align
) {
531 static const uint8_t PageShift_(0x0c);
532 static const uint32_t PageSize_(1 << PageShift_
);
534 static inline uint16_t Swap_(uint16_t value
) {
536 ((value
>> 8) & 0x00ff) |
537 ((value
<< 8) & 0xff00);
540 static inline uint32_t Swap_(uint32_t value
) {
541 value
= ((value
>> 8) & 0x00ff00ff) |
542 ((value
<< 8) & 0xff00ff00);
543 value
= ((value
>> 16) & 0x0000ffff) |
544 ((value
<< 16) & 0xffff0000);
548 static inline uint64_t Swap_(uint64_t value
) {
549 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
550 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
551 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
555 static inline int16_t Swap_(int16_t value
) {
556 return Swap_(static_cast<uint16_t>(value
));
559 static inline int32_t Swap_(int32_t value
) {
560 return Swap_(static_cast<uint32_t>(value
));
563 static inline int64_t Swap_(int64_t value
) {
564 return Swap_(static_cast<uint64_t>(value
));
567 static bool little_(true);
569 static inline uint16_t Swap(uint16_t value
) {
570 return little_
? Swap_(value
) : value
;
573 static inline uint32_t Swap(uint32_t value
) {
574 return little_
? Swap_(value
) : value
;
577 static inline uint64_t Swap(uint64_t value
) {
578 return little_
? Swap_(value
) : value
;
581 static inline int16_t Swap(int16_t value
) {
582 return Swap(static_cast<uint16_t>(value
));
585 static inline int32_t Swap(int32_t value
) {
586 return Swap(static_cast<uint32_t>(value
));
589 static inline int64_t Swap(int64_t value
) {
590 return Swap(static_cast<uint64_t>(value
));
603 Swapped(bool swapped
) :
608 template <typename Type_
>
609 Type_
Swap(Type_ value
) const {
610 return swapped_
? Swap_(value
) : value
;
622 Data(void *base
, size_t size
) :
628 void *GetBase() const {
632 size_t GetSize() const {
643 struct mach_header
*mach_header_
;
644 struct load_command
*load_command_
;
647 MachHeader(void *base
, size_t size
) :
650 mach_header_
= (mach_header
*) base
;
652 switch (Swap(mach_header_
->magic
)) {
654 swapped_
= !swapped_
;
660 swapped_
= !swapped_
;
669 void *post
= mach_header_
+ 1;
671 post
= (uint32_t *) post
+ 1;
672 load_command_
= (struct load_command
*) post
;
675 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
676 Swap(mach_header_
->filetype
) == MH_DYLIB
||
677 Swap(mach_header_
->filetype
) == MH_BUNDLE
681 bool Bits64() const {
685 struct mach_header
*operator ->() const {
689 operator struct mach_header
*() const {
693 uint32_t GetCPUType() const {
694 return Swap(mach_header_
->cputype
);
697 uint32_t GetCPUSubtype() const {
698 return Swap(mach_header_
->cpusubtype
) & 0xff;
701 struct load_command
*GetLoadCommand() const {
702 return load_command_
;
705 std::vector
<struct load_command
*> GetLoadCommands() const {
706 std::vector
<struct load_command
*> load_commands
;
708 struct load_command
*load_command
= load_command_
;
709 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
710 load_commands
.push_back(load_command
);
711 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
714 return load_commands
;
717 void ForSection(const ldid::Functor
<void (const char *, const char *, void *, size_t)> &code
) const {
718 _foreach (load_command
, GetLoadCommands())
719 switch (Swap(load_command
->cmd
)) {
721 auto segment(reinterpret_cast<struct segment_command
*>(load_command
));
722 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
723 auto section(reinterpret_cast<struct section
*>(segment
+ 1));
724 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
725 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
728 case LC_SEGMENT_64
: {
729 auto segment(reinterpret_cast<struct segment_command_64
*>(load_command
));
730 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
731 auto section(reinterpret_cast<struct section_64
*>(segment
+ 1));
732 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
733 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
738 template <typename Target_
>
739 Target_
*GetOffset(uint32_t offset
) const {
740 return reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
);
744 class FatMachHeader
:
751 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
752 MachHeader(base
, size
),
757 fat_arch
*GetFatArch() const {
766 fat_header
*fat_header_
;
767 std::vector
<FatMachHeader
> mach_headers_
;
770 FatHeader(void *base
, size_t size
) :
773 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
775 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
776 swapped_
= !swapped_
;
778 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
780 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
782 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
783 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
785 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
786 uint32_t arch_offset
= Swap(fat_arch
->offset
);
787 uint32_t arch_size
= Swap(fat_arch
->size
);
788 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
794 std::vector
<FatMachHeader
> &GetMachHeaders() {
795 return mach_headers_
;
799 return fat_header_
!= NULL
;
802 struct fat_header
*operator ->() const {
806 operator struct fat_header
*() const {
811 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
812 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
813 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
814 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
815 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
816 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
817 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
818 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
820 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
821 #define CSSLOT_INFOSLOT uint32_t(0x00001)
822 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
823 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
824 #define CSSLOT_APPLICATION uint32_t(0x00004)
825 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
826 #define CSSLOT_ALTERNATE uint32_t(0x01000)
828 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
830 #define CS_HASHTYPE_SHA160_160 1
831 #define CS_HASHTYPE_SHA256_256 2
832 #define CS_HASHTYPE_SHA256_160 3
833 #define CS_HASHTYPE_SHA386_386 4
848 struct BlobIndex index
[];
851 struct CodeDirectory
{
855 uint32_t identOffset
;
856 uint32_t nSpecialSlots
;
864 uint32_t scatterOffset
;
865 uint32_t teamIDOffset
;
867 //uint64_t codeLimit64;
870 enum Kind
: uint32_t {
871 exprForm
= 1, // prefix expr form
874 enum ExprOp
: uint32_t {
875 opFalse
, // unconditionally false
876 opTrue
, // unconditionally true
877 opIdent
, // match canonical code [string]
878 opAppleAnchor
, // signed by Apple as Apple's product
879 opAnchorHash
, // match anchor [cert hash]
880 opInfoKeyValue
, // *legacy* - use opInfoKeyField [key; value]
881 opAnd
, // binary prefix expr AND expr [expr; expr]
882 opOr
, // binary prefix expr OR expr [expr; expr]
883 opCDHash
, // match hash of CodeDirectory directly [cd hash]
884 opNot
, // logical inverse [expr]
885 opInfoKeyField
, // Info.plist key field [string; match suffix]
886 opCertField
, // Certificate field [cert index; field name; match suffix]
887 opTrustedCert
, // require trust settings to approve one particular cert [cert index]
888 opTrustedCerts
, // require trust settings to approve the cert chain
889 opCertGeneric
, // Certificate component by OID [cert index; oid; match suffix]
890 opAppleGenericAnchor
, // signed by Apple in any capacity
891 opEntitlementField
, // entitlement dictionary field [string; match suffix]
892 opCertPolicy
, // Certificate policy by OID [cert index; oid; match suffix]
893 opNamedAnchor
, // named anchor type
894 opNamedCode
, // named subroutine
895 opPlatform
, // platform constraint [integer]
896 exprOpCount
// (total opcode count in use)
899 enum MatchOperation
{
900 matchExists
, // anything but explicit "false" - no value stored
901 matchEqual
, // equal (CFEqual)
902 matchContains
, // partial match (substring)
903 matchBeginsWith
, // partial match (initial substring)
904 matchEndsWith
, // partial match (terminal substring)
905 matchLessThan
, // less than (string with numeric comparison)
906 matchGreaterThan
, // greater than (string with numeric comparison)
907 matchLessEqual
, // less or equal (string with numeric comparison)
908 matchGreaterEqual
, // greater or equal (string with numeric comparison)
911 #define OID_ISO_MEMBER 42
912 #define OID_US OID_ISO_MEMBER, 134, 72
913 #define APPLE_OID OID_US, 0x86, 0xf7, 0x63
914 #define APPLE_ADS_OID APPLE_OID, 0x64
915 #define APPLE_EXTENSION_OID APPLE_ADS_OID, 6
918 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
925 Algorithm(size_t size
, uint8_t type
) :
931 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const = 0;
933 virtual void operator ()(uint8_t *hash
, const void *data
, size_t size
) const = 0;
934 virtual void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const = 0;
935 virtual void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const = 0;
938 struct AlgorithmSHA1
:
942 Algorithm(LDID_SHA1_DIGEST_LENGTH
, CS_HASHTYPE_SHA160_160
)
946 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
950 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
951 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
954 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
955 return operator()(hash
.sha1_
, data
, size
);
958 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
959 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
960 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
964 struct AlgorithmSHA256
:
968 Algorithm(LDID_SHA256_DIGEST_LENGTH
, CS_HASHTYPE_SHA256_256
)
972 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
976 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
977 LDID_SHA256(static_cast<const uint8_t *>(data
), size
, hash
);
980 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
981 return operator()(hash
.sha256_
, data
, size
);
984 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
985 hash
.resize(LDID_SHA256_DIGEST_LENGTH
);
986 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
990 static const std::vector
<Algorithm
*> &GetAlgorithms() {
991 static AlgorithmSHA1 sha1
;
992 static AlgorithmSHA256 sha256
;
994 static Algorithm
*array
[] = {
999 static std::vector
<Algorithm
*> algorithms(array
, array
+ sizeof(array
) / sizeof(array
[0]));
1003 struct CodesignAllocation
{
1004 FatMachHeader mach_header_
;
1011 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
) :
1012 mach_header_(mach_header
),
1022 #ifndef LDID_NOTOOLS
1035 _syscall(close(file_
));
1038 void open(const char *path
, int flags
) {
1039 _assert(file_
== -1);
1040 file_
= _syscall(::open(path
, flags
));
1057 _syscall(munmap(data_
, size_
));
1069 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
1072 open(path
, oflag
, pflag
, mflag
);
1075 Map(const std::string
&path
, bool edit
) :
1085 bool empty() const {
1086 return data_
== NULL
;
1089 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
1092 file_
.open(path
.c_str(), oflag
);
1093 int file(file_
.file());
1096 _syscall(fstat(file
, &stat
));
1097 size_
= stat
.st_size
;
1099 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
1102 void open(const std::string
&path
, bool edit
) {
1104 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
1106 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1109 void *data() const {
1113 size_t size() const {
1117 operator std::string() const {
1118 return std::string(static_cast<char *>(data_
), size_
);
1125 std::string
Analyze(const void *data
, size_t size
) {
1126 std::string entitlements
;
1128 FatHeader
fat_header(const_cast<void *>(data
), size
);
1129 _foreach (mach_header
, fat_header
.GetMachHeaders())
1130 _foreach (load_command
, mach_header
.GetLoadCommands())
1131 if (mach_header
.Swap(load_command
->cmd
) == LC_CODE_SIGNATURE
) {
1132 auto signature(reinterpret_cast<struct linkedit_data_command
*>(load_command
));
1133 auto offset(mach_header
.Swap(signature
->dataoff
));
1134 auto pointer(reinterpret_cast<uint8_t *>(mach_header
.GetBase()) + offset
);
1135 auto super(reinterpret_cast<struct SuperBlob
*>(pointer
));
1137 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1138 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1139 auto begin(Swap(super
->index
[index
].offset
));
1140 auto blob(reinterpret_cast<struct Blob
*>(pointer
+ begin
));
1141 auto writ(Swap(blob
->length
) - sizeof(*blob
));
1143 if (entitlements
.empty())
1144 entitlements
.assign(reinterpret_cast<char *>(blob
+ 1), writ
);
1146 _assert(entitlements
.compare(0, entitlements
.size(), reinterpret_cast<char *>(blob
+ 1), writ
) == 0);
1150 return entitlements
;
1153 static void Allocate(const void *idata
, size_t isize
, std::streambuf
&output
, const Functor
<size_t (const MachHeader
&, size_t)> &allocate
, const Functor
<size_t (const MachHeader
&, std::streambuf
&output
, size_t, const std::string
&, const char *, const Functor
<void (double)> &)> &save
, const Functor
<void (double)> &percent
) {
1154 FatHeader
source(const_cast<void *>(idata
), isize
);
1158 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
1160 std::vector
<CodesignAllocation
> allocations
;
1161 _foreach (mach_header
, source
.GetMachHeaders()) {
1162 struct linkedit_data_command
*signature(NULL
);
1163 struct symtab_command
*symtab(NULL
);
1165 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1166 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1168 else if (cmd
== LC_CODE_SIGNATURE
)
1169 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1170 else if (cmd
== LC_SYMTAB
)
1171 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
1175 if (signature
== NULL
)
1176 size
= mach_header
.GetSize();
1178 size
= mach_header
.Swap(signature
->dataoff
);
1179 _assert(size
<= mach_header
.GetSize());
1182 if (symtab
!= NULL
) {
1183 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
1184 _assert(end
<= size
);
1185 _assert(end
>= size
- 0x10);
1189 size_t alloc(allocate(mach_header
, size
));
1191 auto *fat_arch(mach_header
.GetFatArch());
1194 if (fat_arch
!= NULL
)
1195 align
= source
.Swap(fat_arch
->align
);
1196 else switch (mach_header
.GetCPUType()) {
1197 case CPU_TYPE_POWERPC
:
1198 case CPU_TYPE_POWERPC64
:
1200 case CPU_TYPE_X86_64
:
1204 case CPU_TYPE_ARM64
:
1212 offset
= Align(offset
, 1 << align
);
1214 uint32_t limit(size
);
1216 limit
= Align(limit
, 0x10);
1218 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
));
1219 offset
+= size
+ alloc
;
1220 offset
= Align(offset
, 0x10);
1225 if (source
.IsFat()) {
1226 fat_header fat_header
;
1227 fat_header
.magic
= Swap(FAT_MAGIC
);
1228 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1229 put(output
, &fat_header
, sizeof(fat_header
));
1230 position
+= sizeof(fat_header
);
1232 _foreach (allocation
, allocations
) {
1233 auto &mach_header(allocation
.mach_header_
);
1236 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1237 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1238 fat_arch
.offset
= Swap(allocation
.offset_
);
1239 fat_arch
.size
= Swap(allocation
.limit_
+ allocation
.alloc_
);
1240 fat_arch
.align
= Swap(allocation
.align_
);
1241 put(output
, &fat_arch
, sizeof(fat_arch
));
1242 position
+= sizeof(fat_arch
);
1246 _foreach (allocation
, allocations
) {
1247 auto &mach_header(allocation
.mach_header_
);
1249 pad(output
, allocation
.offset_
- position
);
1250 position
= allocation
.offset_
;
1252 std::vector
<std::string
> commands
;
1254 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1255 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1257 switch (mach_header
.Swap(load_command
->cmd
)) {
1258 case LC_CODE_SIGNATURE
:
1263 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1264 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1266 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1267 segment_command
->filesize
= size
;
1268 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1271 case LC_SEGMENT_64
: {
1272 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1273 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1275 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1276 segment_command
->filesize
= size
;
1277 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1281 commands
.push_back(copy
);
1284 if (allocation
.alloc_
!= 0) {
1285 linkedit_data_command signature
;
1286 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1287 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1288 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1289 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1290 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1293 size_t begin(position
);
1296 _foreach(command
, commands
)
1297 after
+= command
.size();
1299 std::stringbuf altern
;
1301 struct mach_header
header(*mach_header
);
1302 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1303 header
.sizeofcmds
= mach_header
.Swap(after
);
1304 put(output
, &header
, sizeof(header
));
1305 put(altern
, &header
, sizeof(header
));
1306 position
+= sizeof(header
);
1308 if (mach_header
.Bits64()) {
1309 auto pad(mach_header
.Swap(uint32_t(0)));
1310 put(output
, &pad
, sizeof(pad
));
1311 put(altern
, &pad
, sizeof(pad
));
1312 position
+= sizeof(pad
);
1315 _foreach(command
, commands
) {
1316 put(output
, command
.data(), command
.size());
1317 put(altern
, command
.data(), command
.size());
1318 position
+= command
.size();
1321 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1322 if (before
> after
) {
1323 pad(output
, before
- after
);
1324 pad(altern
, before
- after
);
1325 position
+= before
- after
;
1328 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1330 std::string
overlap(altern
.str());
1331 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1333 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
), percent
);
1334 position
= begin
+ allocation
.size_
;
1336 pad(output
, allocation
.limit_
- allocation
.size_
);
1337 position
+= allocation
.limit_
- allocation
.size_
;
1339 size_t saved(save(mach_header
, output
, allocation
.limit_
, overlap
, top
, percent
));
1340 if (allocation
.alloc_
> saved
)
1341 pad(output
, allocation
.alloc_
- saved
);
1343 _assert(allocation
.alloc_
== saved
);
1344 position
+= allocation
.alloc_
;
1350 typedef std::map
<uint32_t, std::string
> Blobs
;
1352 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1353 auto value(buffer
.str());
1354 std::swap(blobs
[slot
], value
);
1357 static const std::string
&insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1358 auto value(buffer
.str());
1360 blob
.magic
= Swap(magic
);
1361 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1362 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1363 auto &save(blobs
[slot
]);
1364 std::swap(save
, value
);
1368 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1370 _foreach (blob
, blobs
)
1371 total
+= blob
.second
.size();
1373 struct SuperBlob super
;
1374 super
.blob
.magic
= Swap(magic
);
1375 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1376 super
.count
= Swap(uint32_t(blobs
.size()));
1377 put(output
, &super
, sizeof(super
));
1379 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1381 _foreach (blob
, blobs
) {
1383 index
.type
= Swap(blob
.first
);
1384 index
.offset
= Swap(uint32_t(offset
));
1385 put(output
, &index
, sizeof(index
));
1386 offset
+= blob
.second
.size();
1389 _foreach (blob
, blobs
)
1390 put(output
, blob
.second
.data(), blob
.second
.size());
1395 #ifndef LDID_NOSMIME
1404 _assert(bio_
!= NULL
);
1408 bio_(BIO_new(BIO_s_mem()))
1412 Buffer(const char *data
, size_t size
) :
1413 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1417 Buffer(const std::string
&data
) :
1418 Buffer(data
.data(), data
.size())
1422 Buffer(PKCS7
*pkcs
) :
1425 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1432 operator BIO
*() const {
1436 explicit operator std::string() const {
1438 auto size(BIO_get_mem_data(bio_
, &data
));
1439 return std::string(data
, size
);
1448 STACK_OF(X509
) *ca_
;
1452 value_(d2i_PKCS12_bio(bio
, NULL
)),
1455 _assert(value_
!= NULL
);
1456 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1458 _assert(key_
!= NULL
);
1459 _assert(cert_
!= NULL
);
1462 ca_
= sk_X509_new_null();
1463 _assert(ca_
!= NULL
);
1466 Stuff(const std::string
&data
) :
1472 sk_X509_pop_free(ca_
, X509_free
);
1474 EVP_PKEY_free(key_
);
1475 PKCS12_free(value_
);
1478 operator PKCS12
*() const {
1482 operator EVP_PKEY
*() const {
1486 operator X509
*() const {
1490 operator STACK_OF(X509
) *() const {
1500 Signature(const Stuff
&stuff
, const Buffer
&data
, const std::string
&xml
) {
1501 value_
= PKCS7_new();
1502 _assert(value_
!= NULL
);
1504 _assert(PKCS7_set_type(value_
, NID_pkcs7_signed
));
1505 _assert(PKCS7_content_new(value_
, NID_pkcs7_data
));
1507 STACK_OF(X509
) *certs(stuff
);
1508 for (unsigned i(0), e(sk_X509_num(certs
)); i
!= e
; i
++)
1509 _assert(PKCS7_add_certificate(value_
, sk_X509_value(certs
, e
- i
- 1)));
1511 auto info(PKCS7_sign_add_signer(value_
, stuff
, stuff
, NULL
, PKCS7_NOSMIMECAP
));
1512 _assert(info
!= NULL
);
1514 PKCS7_set_detached(value_
, 1);
1516 ASN1_OCTET_STRING
*string(ASN1_OCTET_STRING_new());
1517 _assert(string
!= NULL
);
1519 _assert(ASN1_STRING_set(string
, xml
.data(), xml
.size()));
1521 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "", ""));
1522 _assert(PKCS7_add_signed_attribute(info
, nid
, V_ASN1_OCTET_STRING
, string
));
1524 ASN1_OCTET_STRING_free(string
);
1528 _assert(PKCS7_final(value_
, data
, PKCS7_BINARY
));
1535 operator PKCS7
*() const {
1542 public std::streambuf
1545 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1549 virtual int_type
overflow(int_type next
) {
1556 uint8_t sha1_
[LDID_SHA1_DIGEST_LENGTH
];
1560 public std::streambuf
1565 LDID_SHA1_CTX sha1_
;
1566 LDID_SHA256_CTX sha256_
;
1569 HashBuffer(ldid::Hash
&hash
) :
1572 LDID_SHA1_Init(&sha1_
);
1573 LDID_SHA256_Init(&sha256_
);
1577 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.sha1_
), &sha1_
);
1578 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_
.sha256_
), &sha256_
);
1581 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1582 LDID_SHA1_Update(&sha1_
, data
, size
);
1583 LDID_SHA256_Update(&sha256_
, data
, size
);
1587 virtual int_type
overflow(int_type next
) {
1588 if (next
== traits_type::eof())
1600 std::streambuf
&buffer_
;
1603 HashProxy(ldid::Hash
&hash
, std::streambuf
&buffer
) :
1609 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1610 _assert(HashBuffer::xsputn(data
, size
) == size
);
1611 return buffer_
.sputn(data
, size
);
1615 #ifndef LDID_NOTOOLS
1616 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1617 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1625 Split(const std::string
&path
) {
1626 size_t slash(path
.rfind('/'));
1627 if (slash
== std::string::npos
)
1630 dir
= path
.substr(0, slash
+ 1);
1631 base
= path
.substr(slash
+ 1);
1636 static void mkdir_p(const std::string
&path
) {
1640 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
1643 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
1646 auto slash(path
.rfind('/', path
.size() - 1));
1647 if (slash
== std::string::npos
)
1649 mkdir_p(path
.substr(0, slash
));
1652 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
1653 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
1655 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
1659 static void Commit(const std::string
&path
, const std::string
&temp
) {
1661 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
1663 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1665 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1668 _syscall(rename(temp
.c_str(), path
.c_str()));
1674 static void get(std::string
&value
, X509_NAME
*name
, int nid
) {
1675 auto index(X509_NAME_get_index_by_NID(name
, nid
, -1));
1676 _assert(index
>= 0);
1677 auto next(X509_NAME_get_index_by_NID(name
, nid
, index
));
1678 _assert(next
== -1);
1679 auto entry(X509_NAME_get_entry(name
, index
));
1680 _assert(entry
!= NULL
);
1681 auto asn(X509_NAME_ENTRY_get_data(entry
));
1682 _assert(asn
!= NULL
);
1683 value
.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn
)), ASN1_STRING_length(asn
));
1686 static void req(std::streambuf
&buffer
, uint32_t value
) {
1687 value
= Swap(value
);
1688 put(buffer
, &value
, sizeof(value
));
1691 static void req(std::streambuf
&buffer
, const std::string
&value
) {
1692 req(buffer
, value
.size());
1693 put(buffer
, value
.data(), value
.size());
1694 static uint8_t zeros
[] = {0,0,0,0};
1695 put(buffer
, zeros
, 3 - (value
.size() + 3) % 4);
1698 template <size_t Size_
>
1699 static void req(std::streambuf
&buffer
, uint8_t (&&data
)[Size_
]) {
1701 put(buffer
, data
, Size_
);
1702 static uint8_t zeros
[] = {0,0,0,0};
1703 put(buffer
, zeros
, 3 - (Size_
+ 3) % 4);
1706 Hash
Sign(const void *idata
, size_t isize
, std::streambuf
&output
, const std::string
&identifier
, const std::string
&entitlements
, const std::string
&requirements
, const std::string
&key
, const Slots
&slots
, const Functor
<void (double)> &percent
) {
1713 #ifndef LDID_NOSMIME
1716 auto name(X509_get_subject_name(stuff
));
1717 _assert(name
!= NULL
);
1718 get(team
, name
, NID_organizationalUnitName
);
1719 get(common
, name
, NID_commonName
);
1724 std::stringbuf backing
;
1726 if (!requirements
.empty()) {
1727 put(backing
, requirements
.data(), requirements
.size());
1731 std::stringbuf requirement
;
1732 req(requirement
, exprForm
);
1733 req(requirement
, opAnd
);
1734 req(requirement
, opIdent
);
1735 req(requirement
, identifier
);
1736 req(requirement
, opAnd
);
1737 req(requirement
, opAppleGenericAnchor
);
1738 req(requirement
, opAnd
);
1739 req(requirement
, opCertField
);
1740 req(requirement
, 0);
1741 req(requirement
, "subject.CN");
1742 req(requirement
, matchEqual
);
1743 req(requirement
, common
);
1744 req(requirement
, opCertGeneric
);
1745 req(requirement
, 1);
1746 req(requirement
, (uint8_t []) {APPLE_EXTENSION_OID
, 2, 1});
1747 req(requirement
, matchExists
);
1748 insert(blobs
, 3, CSMAGIC_REQUIREMENT
, requirement
);
1750 put(backing
, CSMAGIC_REQUIREMENTS
, blobs
);
1754 // XXX: this is just a "sufficiently large number"
1755 size_t certificate(0x3000);
1757 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, size_t size
) -> size_t {
1758 size_t alloc(sizeof(struct SuperBlob
));
1760 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1762 uint32_t special(0);
1764 _foreach (slot
, slots
)
1765 special
= std::max(special
, slot
.first
);
1767 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1768 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
1769 special
= std::max(special
, CSSLOT_INFOSLOT
);
1772 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1773 alloc
+= sizeof(struct BlobIndex
);
1774 alloc
+= backing
.str().size();
1776 if (!entitlements
.empty()) {
1777 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
1778 alloc
+= sizeof(struct BlobIndex
);
1779 alloc
+= sizeof(struct Blob
);
1780 alloc
+= entitlements
.size();
1783 size_t directory(0);
1785 directory
+= sizeof(struct BlobIndex
);
1786 directory
+= sizeof(struct Blob
);
1787 directory
+= sizeof(struct CodeDirectory
);
1788 directory
+= identifier
.size() + 1;
1791 directory
+= team
.size() + 1;
1793 for (Algorithm
*algorithm
: GetAlgorithms())
1794 alloc
= Align(alloc
+ directory
+ (special
+ normal
) * algorithm
->size_
, 16);
1796 #ifndef LDID_NOSMIME
1798 alloc
+= sizeof(struct BlobIndex
);
1799 alloc
+= sizeof(struct Blob
);
1800 alloc
+= certificate
;
1805 }), fun([&](const MachHeader
&mach_header
, std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
, const Functor
<void (double)> &percent
) -> size_t {
1809 insert(blobs
, CSSLOT_REQUIREMENTS
, backing
);
1812 if (!entitlements
.empty()) {
1813 std::stringbuf data
;
1814 put(data
, entitlements
.data(), entitlements
.size());
1815 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
1820 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1821 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0) {
1822 auto &slot(posts
[CSSLOT_INFOSLOT
]);
1823 for (Algorithm
*algorithm
: GetAlgorithms())
1824 (*algorithm
)(slot
, data
, size
);
1829 for (Algorithm
*pointer
: GetAlgorithms()) {
1830 Algorithm
&algorithm(*pointer
);
1832 std::stringbuf data
;
1834 uint32_t special(0);
1835 _foreach (blob
, blobs
)
1836 special
= std::max(special
, blob
.first
);
1837 _foreach (slot
, posts
)
1838 special
= std::max(special
, slot
.first
);
1839 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
1841 CodeDirectory directory
;
1842 directory
.version
= Swap(uint32_t(0x00020200));
1843 directory
.flags
= Swap(uint32_t(0));
1844 directory
.nSpecialSlots
= Swap(special
);
1845 directory
.codeLimit
= Swap(uint32_t(limit
));
1846 directory
.nCodeSlots
= Swap(normal
);
1847 directory
.hashSize
= algorithm
.size_
;
1848 directory
.hashType
= algorithm
.type_
;
1849 directory
.spare1
= 0x00;
1850 directory
.pageSize
= PageShift_
;
1851 directory
.spare2
= Swap(uint32_t(0));
1852 directory
.scatterOffset
= Swap(uint32_t(0));
1853 //directory.spare3 = Swap(uint32_t(0));
1854 //directory.codeLimit64 = Swap(uint64_t(0));
1856 uint32_t offset(sizeof(Blob
) + sizeof(CodeDirectory
));
1858 directory
.identOffset
= Swap(uint32_t(offset
));
1859 offset
+= identifier
.size() + 1;
1862 directory
.teamIDOffset
= Swap(uint32_t(0));
1864 directory
.teamIDOffset
= Swap(uint32_t(offset
));
1865 offset
+= team
.size() + 1;
1868 offset
+= special
* algorithm
.size_
;
1869 directory
.hashOffset
= Swap(uint32_t(offset
));
1870 offset
+= normal
* algorithm
.size_
;
1872 put(data
, &directory
, sizeof(directory
));
1874 put(data
, identifier
.c_str(), identifier
.size() + 1);
1876 put(data
, team
.c_str(), team
.size() + 1);
1878 std::vector
<uint8_t> storage((special
+ normal
) * algorithm
.size_
);
1879 auto *hashes(&storage
[special
* algorithm
.size_
]);
1881 memset(storage
.data(), 0, special
* algorithm
.size_
);
1883 _foreach (blob
, blobs
) {
1884 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
1885 algorithm(hashes
- blob
.first
* algorithm
.size_
, local
, Swap(local
->length
));
1888 _foreach (slot
, posts
)
1889 memcpy(hashes
- slot
.first
* algorithm
.size_
, algorithm
[slot
.second
], algorithm
.size_
);
1893 for (size_t i
= 0; i
!= normal
- 1; ++i
) {
1894 algorithm(hashes
+ i
* algorithm
.size_
, (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
1895 percent(double(i
) / normal
);
1898 algorithm(hashes
+ (normal
- 1) * algorithm
.size_
, top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
1901 put(data
, storage
.data(), storage
.size());
1903 const auto &save(insert(blobs
, total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1, CSMAGIC_CODEDIRECTORY
, data
));
1904 algorithm(hash
, save
.data(), save
.size());
1909 #ifndef LDID_NOSMIME
1911 auto plist(plist_new_dict());
1912 _scope({ plist_free(plist
); });
1914 auto cdhashes(plist_new_array());
1915 plist_dict_set_item(plist
, "cdhashes", cdhashes
);
1918 for (Algorithm
*pointer
: GetAlgorithms()) {
1919 Algorithm
&algorithm(*pointer
);
1922 const auto &blob(blobs
[total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1]);
1925 std::vector
<char> hash
;
1926 algorithm(hash
, blob
.data(), blob
.size());
1929 plist_array_append_item(cdhashes
, plist_new_data(hash
.data(), hash
.size()));
1934 plist_to_xml(plist
, &xml
, &size
);
1935 _scope({ free(xml
); });
1937 std::stringbuf data
;
1938 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
1943 Signature
signature(stuff
, sign
, std::string(xml
, size
));
1944 Buffer
result(signature
);
1945 std::string
value(result
);
1946 put(data
, value
.data(), value
.size());
1948 const auto &save(insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
));
1949 _assert(save
.size() <= certificate
);
1953 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
1959 #ifndef LDID_NOTOOLS
1960 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
, const Functor
<void (double)> &percent
) {
1961 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, size_t size
) -> size_t {
1963 }), fun([](const MachHeader
&mach_header
, std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
, const Functor
<void (double)> &percent
) -> size_t {
1968 std::string
DiskFolder::Path(const std::string
&path
) const {
1969 return path_
+ "/" + path
;
1972 DiskFolder::DiskFolder(const std::string
&path
) :
1977 DiskFolder::~DiskFolder() {
1978 if (!std::uncaught_exception())
1979 for (const auto &commit
: commit_
)
1980 Commit(commit
.first
, commit
.second
);
1984 std::string
readlink(const std::string
&path
) {
1985 for (size_t size(1024); ; size
*= 2) {
1989 int writ(_syscall(::readlink(path
.c_str(), &data
[0], data
.size())));
1990 if (size_t(writ
) >= size
)
1999 void DiskFolder::Find(const std::string
&root
, const std::string
&base
, const Functor
<void (const std::string
&)> &code
, const Functor
<void (const std::string
&, const Functor
<std::string ()> &)> &link
) const {
2000 std::string
path(Path(root
) + base
);
2002 DIR *dir(opendir(path
.c_str()));
2003 _assert(dir
!= NULL
);
2004 _scope({ _syscall(closedir(dir
)); });
2006 while (auto child
= readdir(dir
)) {
2007 std::string
name(child
->d_name
);
2008 if (name
== "." || name
== "..")
2010 if (Starts(name
, ".ldid."))
2017 _syscall(stat((path
+ name
).c_str(), &info
));
2019 else if (S_ISDIR(info
.st_mode
))
2021 else if (S_ISREG(info
.st_mode
))
2024 _assert_(false, "st_mode=%x", info
.st_mode
);
2026 switch (child
->d_type
) {
2034 link(base
+ name
, fun([&]() { return readlink(path
+ name
); }));
2037 _assert_(false, "d_type=%u", child
->d_type
);
2042 Find(root
, base
+ name
+ "/", code
, link
);
2048 void DiskFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2051 std::stringbuf save
;
2055 auto from(Path(path
));
2056 commit_
[from
] = Temporary(save
, from
);
2061 bool DiskFolder::Look(const std::string
&path
) const {
2062 return _syscall(access(Path(path
).c_str(), R_OK
), ENOENT
) == 0;
2065 void DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2067 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
2068 _assert_(result
== &data
, "DiskFolder::Open(%s)", path
.c_str());
2070 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2071 data
.pubseekpos(0, std::ios::in
);
2072 code(data
, length
, NULL
);
2075 void DiskFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&)> &code
, const Functor
<void (const std::string
&, const Functor
<std::string ()> &)> &link
) const {
2076 Find(path
, "", code
, link
);
2080 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
2086 void SubFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2087 return parent_
.Save(path_
+ path
, edit
, flag
, code
);
2090 bool SubFolder::Look(const std::string
&path
) const {
2091 return parent_
.Look(path_
+ path
);
2094 void SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2095 return parent_
.Open(path_
+ path
, code
);
2098 void SubFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&)> &code
, const Functor
<void (const std::string
&, const Functor
<std::string ()> &)> &link
) const {
2099 return parent_
.Find(path_
+ path
, code
, link
);
2102 std::string
UnionFolder::Map(const std::string
&path
) const {
2103 auto remap(remaps_
.find(path
));
2104 if (remap
== remaps_
.end())
2106 return remap
->second
;
2109 void UnionFolder::Map(const std::string
&path
, const Functor
<void (const std::string
&)> &code
, const std::string
&file
, const Functor
<void (const Functor
<void (std::streambuf
&, size_t, const void *)> &)> &save
) const {
2110 if (file
.size() >= path
.size() && file
.substr(0, path
.size()) == path
)
2111 code(file
.substr(path
.size()));
2114 UnionFolder::UnionFolder(Folder
&parent
) :
2119 void UnionFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2120 return parent_
.Save(Map(path
), edit
, flag
, code
);
2123 bool UnionFolder::Look(const std::string
&path
) const {
2124 auto file(resets_
.find(path
));
2125 if (file
!= resets_
.end())
2127 return parent_
.Look(Map(path
));
2130 void UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2131 auto file(resets_
.find(path
));
2132 if (file
== resets_
.end())
2133 return parent_
.Open(Map(path
), code
);
2134 auto &entry(file
->second
);
2136 auto &data(*entry
.data_
);
2137 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2138 data
.pubseekpos(0, std::ios::in
);
2139 code(data
, length
, entry
.flag_
);
2142 void UnionFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&)> &code
, const Functor
<void (const std::string
&, const Functor
<std::string ()> &)> &link
) const {
2143 for (auto &reset
: resets_
)
2144 Map(path
, code
, reset
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2145 auto &entry(reset
.second
);
2146 auto &data(*entry
.data_
);
2147 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2148 data
.pubseekpos(0, std::ios::in
);
2149 code(data
, length
, entry
.flag_
);
2152 for (auto &remap
: remaps_
)
2153 Map(path
, code
, remap
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2154 parent_
.Open(remap
.second
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2155 code(data
, length
, flag
);
2159 parent_
.Find(path
, fun([&](const std::string
&name
) {
2160 if (deletes_
.find(path
+ name
) == deletes_
.end())
2162 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2163 if (deletes_
.find(path
+ name
) == deletes_
.end())
2168 #ifndef LDID_NOTOOLS
2169 static void copy(std::streambuf
&source
, std::streambuf
&target
, size_t length
, const ldid::Functor
<void (double)> &percent
) {
2173 char data
[4096 * 4];
2174 size_t writ(source
.sgetn(data
, sizeof(data
)));
2177 _assert(target
.sputn(data
, writ
) == writ
);
2179 percent(double(total
) / length
);
2183 #ifndef LDID_NOPLIST
2184 static plist_t
plist(const std::string
&data
) {
2185 plist_t
plist(NULL
);
2186 if (Starts(data
, "bplist00"))
2187 plist_from_bin(data
.data(), data
.size(), &plist
);
2189 plist_from_xml(data
.data(), data
.size(), &plist
);
2190 _assert(plist
!= NULL
);
2194 static void plist_d(std::streambuf
&buffer
, size_t length
, const Functor
<void (plist_t
)> &code
) {
2195 std::stringbuf data
;
2196 copy(buffer
, data
, length
, ldid::fun(dummy
));
2197 auto node(plist(data
.str()));
2198 _scope({ plist_free(node
); });
2199 _assert(plist_get_node_type(node
) == PLIST_DICT
);
2203 static std::string
plist_s(plist_t node
) {
2204 _assert(node
!= NULL
);
2205 _assert(plist_get_node_type(node
) == PLIST_STRING
);
2207 plist_get_string_val(node
, &data
);
2208 _scope({ free(data
); });
2224 std::vector
<std::string
> matches_
;
2227 Expression(const std::string
&code
) {
2228 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
) == 0, "regcomp()");
2229 matches_
.resize(regex_
.re_nsub
+ 1);
2236 bool operator ()(const std::string
&data
) {
2237 regmatch_t matches
[matches_
.size()];
2238 auto value(regexec(®ex_
, data
.c_str(), matches_
.size(), matches
, 0));
2239 if (value
== REG_NOMATCH
)
2241 _assert_(value
== 0, "regexec()");
2242 for (size_t i(0); i
!= matches_
.size(); ++i
)
2243 matches_
[i
].assign(data
.data() + matches
[i
].rm_so
, matches
[i
].rm_eo
- matches
[i
].rm_so
);
2247 const std::string
&operator [](size_t index
) const {
2248 return matches_
[index
];
2257 mutable std::auto_ptr
<Expression
> regex_
;
2259 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
2266 Rule(const Rule
&rhs
) :
2267 weight_(rhs
.weight_
),
2273 void Compile() const {
2274 regex_
.reset(new Expression(code_
));
2277 bool operator ()(const std::string
&data
) const {
2278 _assert(regex_
.get() != NULL
);
2279 return (*regex_
)(data
);
2282 bool operator <(const Rule
&rhs
) const {
2283 if (weight_
> rhs
.weight_
)
2285 if (weight_
< rhs
.weight_
)
2287 return mode_
> rhs
.mode_
;
2292 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
2293 return lhs
->code_
< rhs
->code_
;
2297 #ifndef LDID_NOPLIST
2298 static Hash
Sign(const uint8_t *prefix
, size_t size
, std::streambuf
&buffer
, Hash
&hash
, std::streambuf
&save
, const std::string
&identifier
, const std::string
&entitlements
, const std::string
&requirements
, const std::string
&key
, const Slots
&slots
, size_t length
, const Functor
<void (double)> &percent
) {
2299 // XXX: this is a miserable fail
2300 std::stringbuf temp
;
2301 put(temp
, prefix
, size
);
2302 copy(buffer
, temp
, length
- size
, percent
);
2303 // XXX: this is a stupid hack
2304 pad(temp
, 0x10 - (length
& 0xf));
2305 auto data(temp
.str());
2307 HashProxy
proxy(hash
, save
);
2308 return Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, requirements
, key
, slots
, percent
);
2311 Bundle
Sign(const std::string
&root
, Folder
&folder
, const std::string
&key
, std::map
<std::string
, Hash
> &remote
, const std::string
&requirements
, const Functor
<std::string (const std::string
&, const std::string
&)> &alter
, const Functor
<void (const std::string
&)> &progress
, const Functor
<void (double)> &percent
) {
2312 std::string executable
;
2313 std::string identifier
;
2317 std::string
info("Info.plist");
2318 if (!folder
.Look(info
) && folder
.Look("Resources/" + info
)) {
2320 info
= "Resources/" + info
;
2323 folder
.Open(info
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2324 plist_d(buffer
, length
, fun([&](plist_t node
) {
2325 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
2326 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
2330 if (!mac
&& folder
.Look("MacOS/" + executable
)) {
2331 executable
= "MacOS/" + executable
;
2335 std::string entitlements
;
2336 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2337 // XXX: this is a miserable fail
2338 std::stringbuf temp
;
2339 copy(buffer
, temp
, length
, percent
);
2340 // XXX: this is a stupid hack
2341 pad(temp
, 0x10 - (length
& 0xf));
2342 auto data(temp
.str());
2343 entitlements
= alter(root
, Analyze(data
.data(), data
.size()));
2346 static const std::string
directory("_CodeSignature/");
2347 static const std::string
signature(directory
+ "CodeResources");
2349 std::map
<std::string
, std::multiset
<Rule
>> versions
;
2351 auto &rules1(versions
[""]);
2352 auto &rules2(versions
["2"]);
2354 const std::string
resources(mac
? "Resources/" : "");
2357 rules1
.insert(Rule
{1, NoMode
, "^" + resources
});
2358 rules1
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2359 rules1
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2360 rules1
.insert(Rule
{1010, NoMode
, "^Base\\.lproj/"});
2361 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
2365 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
2366 rules2
.insert(Rule
{20, NoMode
, "^" + resources
});
2367 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
2368 rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2369 rules2
.insert(Rule
{1, NoMode
, "^.*"});
2370 rules2
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2371 rules2
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2372 rules2
.insert(Rule
{1010, NoMode
, "^Base\\.lproj/"});
2373 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
2374 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
2375 rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
2376 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
2377 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
2380 std::map
<std::string
, Hash
> local
;
2382 std::string
failure(mac
? "Contents/|Versions/[^/]*/Resources/" : "");
2383 Expression
nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure
+ ")Info\\.plist$");
2384 std::map
<std::string
, Bundle
> bundles
;
2386 folder
.Find("", fun([&](const std::string
&name
) {
2389 auto bundle(root
+ Split(name
).dir
);
2390 bundle
.resize(bundle
.size() - resources
.size());
2391 SubFolder
subfolder(folder
, bundle
);
2393 bundles
[nested
[1]] = Sign(bundle
, subfolder
, key
, local
, "", Starts(name
, "PlugIns/") ? alter
:
2394 static_cast<const Functor
<std::string (const std::string
&, const std::string
&)> &>(fun([&](const std::string
&, const std::string
&entitlements
) -> std::string
{ return entitlements
; }))
2395 , progress
, percent
);
2396 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2399 std::set
<std::string
> excludes
;
2401 auto exclude([&](const std::string
&name
) {
2402 // BundleDiskRep::adjustResources -> builder.addExclusion
2403 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
2406 for (const auto &bundle
: bundles
)
2407 if (Starts(name
, bundle
.first
+ "/")) {
2408 excludes
.insert(name
);
2415 std::map
<std::string
, std::string
> links
;
2417 folder
.Find("", fun([&](const std::string
&name
) {
2421 if (local
.find(name
) != local
.end())
2423 auto &hash(local
[name
]);
2425 folder
.Open(name
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2426 progress(root
+ name
);
2437 auto size(most(data
, &header
.bytes
, sizeof(header
.bytes
)));
2439 if (name
!= "_WatchKitStub/WK" && size
== sizeof(header
.bytes
))
2440 switch (Swap(header
.magic
)) {
2442 // Java class file format
2443 if (Swap(header
.count
) >= 40)
2446 case MH_MAGIC
: case MH_MAGIC_64
:
2447 case MH_CIGAM
: case MH_CIGAM_64
:
2448 folder
.Save(name
, true, flag
, fun([&](std::streambuf
&save
) {
2450 Sign(header
.bytes
, size
, data
, hash
, save
, identifier
, "", "", key
, slots
, length
, percent
);
2455 folder
.Save(name
, false, flag
, fun([&](std::streambuf
&save
) {
2456 HashProxy
proxy(hash
, save
);
2457 put(proxy
, header
.bytes
, size
);
2458 copy(data
, proxy
, length
- size
, percent
);
2461 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2465 links
[name
] = read();
2468 auto plist(plist_new_dict());
2469 _scope({ plist_free(plist
); });
2471 for (const auto &version
: versions
) {
2472 auto files(plist_new_dict());
2473 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
2475 for (const auto &rule
: version
.second
)
2478 bool old(&version
.second
== &rules1
);
2480 for (const auto &hash
: local
)
2481 for (const auto &rule
: version
.second
)
2482 if (rule(hash
.first
)) {
2483 if (!old
&& mac
&& excludes
.find(hash
.first
) != excludes
.end());
2484 else if (old
&& rule
.mode_
== NoMode
)
2485 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2486 else if (rule
.mode_
!= OmitMode
) {
2487 auto entry(plist_new_dict());
2488 plist_dict_set_item(entry
, "hash", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2490 plist_dict_set_item(entry
, "hash2", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha256_
), sizeof(hash
.second
.sha256_
)));
2491 if (rule
.mode_
== OptionalMode
)
2492 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2493 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
2499 for (const auto &link
: links
)
2500 for (const auto &rule
: version
.second
)
2501 if (rule(link
.first
)) {
2502 if (rule
.mode_
!= OmitMode
) {
2503 auto entry(plist_new_dict());
2504 plist_dict_set_item(entry
, "symlink", plist_new_string(link
.second
.c_str()));
2505 if (rule
.mode_
== OptionalMode
)
2506 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2507 plist_dict_set_item(files
, link
.first
.c_str(), entry
);
2514 for (const auto &bundle
: bundles
) {
2515 auto entry(plist_new_dict());
2516 plist_dict_set_item(entry
, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle
.second
.hash
.sha256_
), sizeof(bundle
.second
.hash
.sha256_
)));
2517 plist_dict_set_item(entry
, "requirement", plist_new_string("anchor apple generic"));
2518 plist_dict_set_item(files
, bundle
.first
.c_str(), entry
);
2522 for (const auto &version
: versions
) {
2523 auto rules(plist_new_dict());
2524 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
2526 std::multiset
<const Rule
*, RuleCode
> ordered
;
2527 for (const auto &rule
: version
.second
)
2528 ordered
.insert(&rule
);
2530 for (const auto &rule
: ordered
)
2531 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
2532 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
2534 auto entry(plist_new_dict());
2535 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
2537 switch (rule
->mode_
) {
2541 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
2544 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2547 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
2550 plist_dict_set_item(entry
, "top", plist_new_bool(true));
2554 if (rule
->weight_
>= 10000)
2555 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
2556 else if (rule
->weight_
!= 1)
2557 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
2561 folder
.Save(signature
, true, NULL
, fun([&](std::streambuf
&save
) {
2562 HashProxy
proxy(local
[signature
], save
);
2565 plist_to_xml(plist
, &xml
, &size
);
2566 _scope({ free(xml
); });
2567 put(proxy
, xml
, size
);
2571 bundle
.path
= executable
;
2573 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2574 progress(root
+ executable
);
2575 folder
.Save(executable
, true, flag
, fun([&](std::streambuf
&save
) {
2577 slots
[1] = local
.at(info
);
2578 slots
[3] = local
.at(signature
);
2579 bundle
.hash
= Sign(NULL
, 0, buffer
, local
[executable
], save
, identifier
, entitlements
, requirements
, key
, slots
, length
, percent
);
2583 for (const auto &entry
: local
)
2584 remote
[root
+ entry
.first
] = entry
.second
;
2589 Bundle
Sign(const std::string
&root
, Folder
&folder
, const std::string
&key
, const std::string
&requirements
, const Functor
<std::string (const std::string
&, const std::string
&)> &alter
, const Functor
<void (const std::string
&)> &progress
, const Functor
<void (double)> &percent
) {
2590 std::map
<std::string
, Hash
> local
;
2591 return Sign(root
, folder
, key
, local
, requirements
, alter
, progress
, percent
);
2598 #ifndef LDID_NOTOOLS
2599 int main(int argc
, char *argv
[]) {
2600 #ifndef LDID_NOSMIME
2601 OpenSSL_add_all_algorithms();
2609 little_
= endian
.byte
[0];
2615 #ifndef LDID_NOFLAGT
2629 uint32_t flag_CPUType(_not(uint32_t));
2630 uint32_t flag_CPUSubtype(_not(uint32_t));
2632 const char *flag_I(NULL
);
2634 #ifndef LDID_NOFLAGT
2644 std::vector
<std::string
> files
;
2647 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv
[0]);
2648 fprintf(stderr
, " %s -e MobileSafari\n", argv
[0]);
2649 fprintf(stderr
, " %s -S cat\n", argv
[0]);
2650 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv
[0]);
2654 for (int argi(1); argi
!= argc
; ++argi
)
2655 if (argv
[argi
][0] != '-')
2656 files
.push_back(argv
[argi
]);
2657 else switch (argv
[argi
][1]) {
2664 case 'e': flag_e
= true; break;
2667 const char *string
= argv
[argi
] + 2;
2668 const char *colon
= strchr(string
, ':');
2669 _assert(colon
!= NULL
);
2670 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2672 unsigned number(strtoul(string
, &arge
, 0));
2673 _assert(arge
== colon
);
2674 auto &slot(slots
[number
]);
2675 for (Algorithm
*algorithm
: GetAlgorithms())
2676 (*algorithm
)(slot
, file
.data(), file
.size());
2679 case 'q': flag_q
= true; break;
2682 const char *xml
= argv
[argi
] + 2;
2683 requirements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2686 case 'D': flag_D
= true; break;
2688 case 'a': flag_a
= true; break;
2693 if (argv
[argi
][2] != '\0') {
2694 const char *cpu
= argv
[argi
] + 2;
2695 const char *colon
= strchr(cpu
, ':');
2696 _assert(colon
!= NULL
);
2698 flag_CPUType
= strtoul(cpu
, &arge
, 0);
2699 _assert(arge
== colon
);
2700 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
2701 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2715 if (argv
[argi
][2] != '\0') {
2716 const char *xml
= argv
[argi
] + 2;
2717 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2722 if (argv
[argi
][2] != '\0')
2723 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2726 #ifndef LDID_NOFLAGT
2729 if (argv
[argi
][2] == '-')
2733 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
2734 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2744 flag_I
= argv
[argi
] + 2;
2752 _assert(flag_S
|| key
.empty());
2753 _assert(flag_S
|| flag_I
== NULL
);
2755 if (files
.empty()) usage
: {
2759 size_t filei(0), filee(0);
2760 _foreach (file
, files
) try {
2761 std::string
path(file
);
2764 _syscall(stat(path
.c_str(), &info
));
2766 if (S_ISDIR(info
.st_mode
)) {
2767 #ifndef LDID_NOPLIST
2769 ldid::DiskFolder
folder(path
);
2770 path
+= "/" + Sign("", folder
, key
, requirements
, ldid::fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; })
2771 , ldid::fun([&](const std::string
&) {}), ldid::fun(dummy
)
2776 } else if (flag_S
|| flag_r
) {
2777 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2779 std::filebuf output
;
2781 auto temp(Temporary(output
, split
));
2784 ldid::Unsign(input
.data(), input
.size(), output
, ldid::fun(dummy
));
2786 std::string
identifier(flag_I
?: split
.base
.c_str());
2787 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, requirements
, key
, slots
, ldid::fun(dummy
));
2794 #ifndef LDID_NOFLAGT
2801 Map
mapping(path
, modify
);
2802 FatHeader
fat_header(mapping
.data(), mapping
.size());
2804 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
2805 struct linkedit_data_command
*signature(NULL
);
2806 struct encryption_info_command
*encryption(NULL
);
2809 if (mach_header
.GetCPUType() != flag_CPUType
)
2811 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
2816 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
2818 _foreach (load_command
, mach_header
.GetLoadCommands()) {
2819 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
2822 else if (cmd
== LC_CODE_SIGNATURE
)
2823 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
2824 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
2825 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
2826 else if (cmd
== LC_LOAD_DYLIB
) {
2827 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2828 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
2830 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
2833 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
2834 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
2838 #ifndef LDID_NOFLAGT
2839 else if (cmd
== LC_ID_DYLIB
) {
2840 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2848 dylib_command
->dylib
.timestamp
= 0;
2849 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
2852 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
2859 _assert(encryption
!= NULL
);
2860 encryption
->cryptid
= mach_header
.Swap(0);
2864 _assert(signature
!= NULL
);
2866 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2868 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2869 uint8_t *blob
= top
+ data
;
2870 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2872 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2873 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
2874 uint32_t begin
= Swap(super
->index
[index
].offset
);
2875 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
2876 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
2881 _assert(signature
!= NULL
);
2883 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2885 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2886 uint8_t *blob
= top
+ data
;
2887 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2889 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2890 if (Swap(super
->index
[index
].type
) == CSSLOT_REQUIREMENTS
) {
2891 uint32_t begin
= Swap(super
->index
[index
].offset
);
2892 struct Blob
*requirement
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
2893 fwrite(requirement
, 1, Swap(requirement
->length
), stdout
);
2898 _assert(signature
!= NULL
);
2900 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2902 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2903 uint8_t *blob
= top
+ data
;
2904 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2906 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2907 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
2908 uint32_t begin
= Swap(super
->index
[index
].offset
);
2909 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
2911 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
2912 uint32_t pages
= Swap(directory
->nCodeSlots
);
2915 for (size_t i
= 0; i
!= pages
- 1; ++i
)
2916 LDID_SHA1(top
+ PageSize_
* i
, PageSize_
, hashes
[i
]);
2918 LDID_SHA1(top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1, hashes
[pages
- 1]);
2924 } catch (const char *) {