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/opensslv.h>
47 # if OPENSSL_VERSION_MAJOR >= 3
48 # include <openssl/provider.h>
50 #include <openssl/err.h>
51 #include <openssl/pem.h>
52 #include <openssl/pkcs7.h>
53 #include <openssl/pkcs12.h>
54 #include <openssl/ui.h>
58 #include <CommonCrypto/CommonDigest.h>
60 #define LDID_SHA1_DIGEST_LENGTH CC_SHA1_DIGEST_LENGTH
61 #define LDID_SHA1 CC_SHA1
62 #define LDID_SHA1_CTX CC_SHA1_CTX
63 #define LDID_SHA1_Init CC_SHA1_Init
64 #define LDID_SHA1_Update CC_SHA1_Update
65 #define LDID_SHA1_Final CC_SHA1_Final
67 #define LDID_SHA256_DIGEST_LENGTH CC_SHA256_DIGEST_LENGTH
68 #define LDID_SHA256 CC_SHA256
69 #define LDID_SHA256_CTX CC_SHA256_CTX
70 #define LDID_SHA256_Init CC_SHA256_Init
71 #define LDID_SHA256_Update CC_SHA256_Update
72 #define LDID_SHA256_Final CC_SHA256_Final
74 #include <openssl/sha.h>
76 #define LDID_SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH
77 #define LDID_SHA1 SHA1
78 #define LDID_SHA1_CTX SHA_CTX
79 #define LDID_SHA1_Init SHA1_Init
80 #define LDID_SHA1_Update SHA1_Update
81 #define LDID_SHA1_Final SHA1_Final
83 #define LDID_SHA256_DIGEST_LENGTH SHA256_DIGEST_LENGTH
84 #define LDID_SHA256 SHA256
85 #define LDID_SHA256_CTX SHA256_CTX
86 #define LDID_SHA256_Init SHA256_Init
87 #define LDID_SHA256_Update SHA256_Update
88 #define LDID_SHA256_Final SHA256_Final
92 #include <plist/plist.h>
94 #include <CoreFoundation/CoreFoundation.h>
99 #define _assert___(line) \
101 #define _assert__(line) \
105 #define $(value) value
109 #define _assert_(expr, format, ...) \
111 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
112 throw $(__FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"); \
115 // XXX: this is not acceptable
116 #define _assert_(expr, format, ...) \
118 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
123 #define _assert(expr) \
124 _assert_(expr, "%s", $(#expr))
126 #define _syscall(expr, ...) [&] { for (;;) { \
128 if ((long) _value != -1) \
131 if (error == EINTR) \
133 /* XXX: EINTR is included in this list to fix g++ */ \
134 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
135 if (error == success) \
136 return (decltype(expr)) -success; \
137 _assert_(false, "errno=%u", error); \
141 fprintf(stderr, $("_trace(%s:%u): %s\n"), __FILE__, __LINE__, $(__FUNCTION__))
147 __attribute__((packed))
150 std::string password
;
153 template <typename Type_
>
155 typedef typename
Type_::const_iterator Result
;
158 #define _foreach(item, list) \
159 for (bool _stop(true); _stop; ) \
160 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
161 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
162 for (bool _suck(true); _suck; _suck = false) \
163 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
168 template <typename Function_
>
176 Scope(const Function_
&function
) :
186 template <typename Function_
>
187 Scope
<Function_
> _scope(const Function_
&function
) {
188 return Scope
<Function_
>(function
);
191 #define _scope__(counter, function) \
192 __attribute__((__unused__)) \
193 const _Scope &_scope ## counter(_scope([&]function))
194 #define _scope_(counter, function) \
195 _scope__(counter, function)
196 #define _scope(function) \
197 _scope_(__COUNTER__, function)
199 #define CPU_ARCH_MASK uint32_t(0xff000000)
200 #define CPU_ARCH_ABI64 uint32_t(0x01000000)
201 #define CPU_ARCH_ABI64_32 uint32_t(0x02000000)
203 #define CPU_TYPE_ANY uint32_t(-1)
204 #define CPU_TYPE_VAX uint32_t( 1)
205 #define CPU_TYPE_MC680x0 uint32_t( 6)
206 #define CPU_TYPE_X86 uint32_t( 7)
207 #define CPU_TYPE_MC98000 uint32_t(10)
208 #define CPU_TYPE_HPPA uint32_t(11)
209 #define CPU_TYPE_ARM uint32_t(12)
210 #define CPU_TYPE_MC88000 uint32_t(13)
211 #define CPU_TYPE_SPARC uint32_t(14)
212 #define CPU_TYPE_I860 uint32_t(15)
213 #define CPU_TYPE_POWERPC uint32_t(18)
215 #define CPU_TYPE_I386 CPU_TYPE_X86
217 #define CPU_TYPE_ARM64 (CPU_ARCH_ABI64 | CPU_TYPE_ARM)
218 #define CPU_TYPE_POWERPC64 (CPU_ARCH_ABI64 | CPU_TYPE_POWERPC)
219 #define CPU_TYPE_X86_64 (CPU_ARCH_ABI64 | CPU_TYPE_X86)
220 #define CPU_TYPE_ARM64_32 (CPU_TYPE_ARM | CPU_ARCH_ABI64_32)
227 #define FAT_MAGIC 0xcafebabe
228 #define FAT_CIGAM 0xbebafeca
248 #define MH_MAGIC 0xfeedface
249 #define MH_CIGAM 0xcefaedfe
251 #define MH_MAGIC_64 0xfeedfacf
252 #define MH_CIGAM_64 0xcffaedfe
254 #define MH_DYLDLINK 0x4
256 #define MH_OBJECT 0x1
257 #define MH_EXECUTE 0x2
259 #define MH_DYLINKER 0x7
260 #define MH_BUNDLE 0x8
261 #define MH_DYLIB_STUB 0x9
263 struct load_command
{
268 #define LC_REQ_DYLD uint32_t(0x80000000)
270 #define LC_SEGMENT uint32_t(0x01)
271 #define LC_SYMTAB uint32_t(0x02)
272 #define LC_DYSYMTAB uint32_t(0x0b)
273 #define LC_LOAD_DYLIB uint32_t(0x0c)
274 #define LC_ID_DYLIB uint32_t(0x0d)
275 #define LC_SEGMENT_64 uint32_t(0x19)
276 #define LC_UUID uint32_t(0x1b)
277 #define LC_CODE_SIGNATURE uint32_t(0x1d)
278 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
279 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
280 #define LC_ENCRYPTION_INFO uint32_t(0x21)
281 #define LC_DYLD_INFO uint32_t(0x22)
282 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
283 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
298 uint32_t current_version
;
299 uint32_t compatibility_version
;
302 struct dylib_command
{
308 struct uuid_command
{
314 struct symtab_command
{
323 struct dyld_info_command
{
327 uint32_t rebase_size
;
330 uint32_t weak_bind_off
;
331 uint32_t weak_bind_size
;
332 uint32_t lazy_bind_off
;
333 uint32_t lazy_bind_size
;
335 uint32_t export_size
;
338 struct dysymtab_command
{
351 uint32_t extrefsymoff
;
352 uint32_t nextrefsyms
;
353 uint32_t indirectsymoff
;
354 uint32_t nindirectsyms
;
361 struct dylib_table_of_contents
{
362 uint32_t symbol_index
;
363 uint32_t module_index
;
366 struct dylib_module
{
367 uint32_t module_name
;
376 uint32_t iinit_iterm
;
377 uint32_t ninit_nterm
;
378 uint32_t objc_module_info_addr
;
379 uint32_t objc_module_info_size
;
382 struct dylib_reference
{
387 struct relocation_info
{
389 uint32_t r_symbolnum
:24;
408 struct segment_command
{
422 struct segment_command_64
{
465 struct linkedit_data_command
{
472 struct encryption_info_command
{
480 #define BIND_OPCODE_MASK 0xf0
481 #define BIND_IMMEDIATE_MASK 0x0f
482 #define BIND_OPCODE_DONE 0x00
483 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
484 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
485 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
486 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
487 #define BIND_OPCODE_SET_TYPE_IMM 0x50
488 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
489 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
490 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
491 #define BIND_OPCODE_DO_BIND 0x90
492 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
493 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
494 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
496 struct : ldid::Progress
{
497 virtual void operator()(const std::string
&value
) const {
500 virtual void operator()(double value
) const {
504 struct Progression
: ldid::Progress
{
505 const ldid::Progress
&progress_
;
508 Progression(const ldid::Progress
&progress
, const std::string
&name
) :
514 virtual void operator()(const std::string
&value
) const {
515 return progress_(name_
+ " (" + value
+ ")");
518 virtual void operator()(double value
) const {
519 return progress_(value
);
523 static std::streamsize
read(std::streambuf
&stream
, void *data
, size_t size
) {
524 auto writ(stream
.sgetn(static_cast<char *>(data
), size
));
529 static inline void put(std::streambuf
&stream
, uint8_t value
) {
530 _assert(stream
.sputc(value
) != EOF
);
533 static inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
534 _assert(read(stream
, data
, size
) == size
);
537 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
538 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
541 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
, const ldid::Progress
&progress
) {
543 for (size_t total(0); total
!= size
;) {
544 auto writ(std::min(size
- total
, size_t(4096 * 4)));
545 _assert(stream
.sputn(static_cast<const char *>(data
) + total
, writ
) == writ
);
547 progress(double(total
) / size
);
551 static inline void put(std::streambuf
&stream
, const std::string
&data
) {
552 return put(stream
, data
.data(), data
.size());
555 static size_t most(std::streambuf
&stream
, void *data
, size_t size
) {
558 if (auto writ
= read(stream
, data
, size
))
564 static inline void pad(std::streambuf
&stream
, size_t size
) {
566 memset(padding
, 0, size
);
567 put(stream
, padding
, size
);
570 template <typename Type_
>
571 Type_
Align(Type_ value
, size_t align
) {
578 static const uint8_t PageShift_(0x0c);
579 static const uint32_t PageSize_(1 << PageShift_
);
581 static inline unsigned bytes(uint64_t value
) {
582 return (64 - __builtin_clzll(value
) + 7) / 8;
585 static void put(std::streambuf
&stream
, uint64_t value
, size_t length
) {
587 do put(stream
, uint8_t(value
>> (length
-= 8)));
591 static void der(std::streambuf
&stream
, uint64_t value
) {
595 unsigned length(bytes(value
));
596 put(stream
, 0x80 | length
);
597 put(stream
, value
, length
);
601 static std::string
der(uint8_t tag
, const char *value
, size_t length
) {
605 put(data
, value
, length
);
609 static std::string
der(uint8_t tag
, const char *value
) {
610 return der(tag
, value
, strlen(value
)); }
611 static std::string
der(uint8_t tag
, const std::string
&value
) {
612 return der(tag
, value
.data(), value
.size()); }
614 template <typename Type_
>
615 static void der_(std::stringbuf
&data
, const Type_
&values
) {
617 for (const auto &value
: values
)
618 size
+= value
.size();
620 for (const auto &value
: values
)
624 static std::string
der(const std::vector
<std::string
> &values
) {
631 static std::string
der(const std::multiset
<std::string
> &values
) {
638 static std::string
der(const std::pair
<std::string
, std::string
> &value
) {
639 const auto key(der(0x0c, value
.first
));
642 der(data
, key
.size() + value
.second
.size());
644 put(data
, value
.second
);
649 static std::string
der(plist_t data
) {
650 switch (const auto type
= plist_get_node_type(data
)) {
651 case PLIST_BOOLEAN
: {
653 plist_get_bool_val(data
, &value
);
658 put(data
, value
!= 0 ? 1 : 0);
664 plist_get_uint_val(data
, &value
);
665 const auto length(bytes(value
));
670 put(data
, value
, length
);
685 plist_get_data_val(data
, &value
, &length
);
686 _scope({ free(value
); });
687 return der(0x04, value
, length
);
692 plist_get_string_val(data
, &value
);
693 _scope({ free(value
); });
694 return der(0x0c, value
);
698 std::vector
<std::string
> values
;
699 for (auto e(plist_array_get_size(data
)), i(decltype(e
)(0)); i
!= e
; ++i
)
700 values
.push_back(der(plist_array_get_item(data
, i
)));
705 std::multiset
<std::string
> values
;
707 plist_dict_iter
iterator(NULL
);
708 plist_dict_new_iter(data
, &iterator
);
709 _scope({ free(iterator
); });
714 plist_dict_next_item(data
, iterator
, &key
, &value
);
717 _scope({ free(key
); });
718 values
.insert(der(std::make_pair(key
, der(value
))));
725 _assert_(false, "unsupported plist type %d", type
);
731 static inline uint16_t Swap_(uint16_t value
) {
733 ((value
>> 8) & 0x00ff) |
734 ((value
<< 8) & 0xff00);
737 static inline uint32_t Swap_(uint32_t value
) {
738 value
= ((value
>> 8) & 0x00ff00ff) |
739 ((value
<< 8) & 0xff00ff00);
740 value
= ((value
>> 16) & 0x0000ffff) |
741 ((value
<< 16) & 0xffff0000);
745 static inline uint64_t Swap_(uint64_t value
) {
746 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
747 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
748 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
752 static inline int16_t Swap_(int16_t value
) {
753 return Swap_(static_cast<uint16_t>(value
));
756 static inline int32_t Swap_(int32_t value
) {
757 return Swap_(static_cast<uint32_t>(value
));
760 static inline int64_t Swap_(int64_t value
) {
761 return Swap_(static_cast<uint64_t>(value
));
764 static bool little_(true);
766 static inline uint16_t Swap(uint16_t value
) {
767 return little_
? Swap_(value
) : value
;
770 static inline uint32_t Swap(uint32_t value
) {
771 return little_
? Swap_(value
) : value
;
774 static inline uint64_t Swap(uint64_t value
) {
775 return little_
? Swap_(value
) : value
;
778 static inline int16_t Swap(int16_t value
) {
779 return Swap(static_cast<uint16_t>(value
));
782 static inline int32_t Swap(int32_t value
) {
783 return Swap(static_cast<uint32_t>(value
));
786 static inline int64_t Swap(int64_t value
) {
787 return Swap(static_cast<uint64_t>(value
));
800 Swapped(bool swapped
) :
805 template <typename Type_
>
806 Type_
Swap(Type_ value
) const {
807 return swapped_
? Swap_(value
) : value
;
819 Data(void *base
, size_t size
) :
825 void *GetBase() const {
829 size_t GetSize() const {
840 struct mach_header
*mach_header_
;
841 struct load_command
*load_command_
;
844 MachHeader(void *base
, size_t size
) :
847 mach_header_
= (mach_header
*) base
;
849 switch (Swap(mach_header_
->magic
)) {
851 swapped_
= !swapped_
;
857 swapped_
= !swapped_
;
866 void *post
= mach_header_
+ 1;
868 post
= (uint32_t *) post
+ 1;
869 load_command_
= (struct load_command
*) post
;
872 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
873 Swap(mach_header_
->filetype
) == MH_DYLIB
||
874 Swap(mach_header_
->filetype
) == MH_DYLINKER
||
875 Swap(mach_header_
->filetype
) == MH_BUNDLE
879 bool Bits64() const {
883 struct mach_header
*operator ->() const {
887 operator struct mach_header
*() const {
891 uint32_t GetCPUType() const {
892 return Swap(mach_header_
->cputype
);
895 uint32_t GetCPUSubtype() const {
896 return Swap(mach_header_
->cpusubtype
) & 0xff;
899 struct load_command
*GetLoadCommand() const {
900 return load_command_
;
903 std::vector
<struct load_command
*> GetLoadCommands() const {
904 std::vector
<struct load_command
*> load_commands
;
906 struct load_command
*load_command
= load_command_
;
907 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
908 load_commands
.push_back(load_command
);
909 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
912 return load_commands
;
915 void ForSection(const ldid::Functor
<void (const char *, const char *, void *, size_t)> &code
) const {
916 _foreach (load_command
, GetLoadCommands())
917 switch (Swap(load_command
->cmd
)) {
919 auto segment(reinterpret_cast<struct segment_command
*>(load_command
));
920 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
921 auto section(reinterpret_cast<struct section
*>(segment
+ 1));
922 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
923 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
926 case LC_SEGMENT_64
: {
927 auto segment(reinterpret_cast<struct segment_command_64
*>(load_command
));
928 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
929 auto section(reinterpret_cast<struct section_64
*>(segment
+ 1));
930 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
931 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
936 template <typename Target_
>
937 Target_
*GetOffset(uint32_t offset
) const {
938 return reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
);
942 class FatMachHeader
:
949 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
950 MachHeader(base
, size
),
955 fat_arch
*GetFatArch() const {
964 fat_header
*fat_header_
;
965 std::vector
<FatMachHeader
> mach_headers_
;
968 FatHeader(void *base
, size_t size
) :
971 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
973 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
974 swapped_
= !swapped_
;
976 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
978 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
980 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
981 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
983 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
984 uint32_t arch_offset
= Swap(fat_arch
->offset
);
985 uint32_t arch_size
= Swap(fat_arch
->size
);
986 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
992 std::vector
<FatMachHeader
> &GetMachHeaders() {
993 return mach_headers_
;
997 return fat_header_
!= NULL
;
1000 struct fat_header
*operator ->() const {
1004 operator struct fat_header
*() const {
1009 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
1010 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
1011 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
1012 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
1013 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
1014 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
1015 #define CSMAGIC_EMBEDDED_DERFORMAT uint32_t(0xfade7172) // name?
1016 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
1017 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
1019 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
1020 #define CSSLOT_INFOSLOT uint32_t(0x00001)
1021 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
1022 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
1023 #define CSSLOT_APPLICATION uint32_t(0x00004)
1024 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
1025 #define CSSLOT_REPSPECIFIC uint32_t(0x00006) // name?
1026 #define CSSLOT_DERFORMAT uint32_t(0x00007) // name?
1027 #define CSSLOT_ALTERNATE uint32_t(0x01000)
1029 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
1031 #define CS_HASHTYPE_SHA160_160 1
1032 #define CS_HASHTYPE_SHA256_256 2
1033 #define CS_HASHTYPE_SHA256_160 3
1034 #define CS_HASHTYPE_SHA386_386 4
1037 #define CS_EXECSEG_MAIN_BINARY 0x001 /* executable segment denotes main binary */
1038 #define CS_EXECSEG_ALLOW_UNSIGNED 0x010 /* allow unsigned pages (for debugging) */
1039 #define CS_EXECSEG_DEBUGGER 0x020 /* main binary is debugger */
1040 #define CS_EXECSEG_JIT 0x040 /* JIT enabled */
1041 #define CS_EXECSEG_SKIP_LV 0x080 /* skip library validation */
1042 #define CS_EXECSEG_CAN_LOAD_CDHASH 0x100 /* can bless cdhash for execution */
1043 #define CS_EXECSEG_CAN_EXEC_CDHASH 0x200 /* can execute blessed cdhash */
1045 enum SecCodeExecSegFlags
{
1046 kSecCodeExecSegMainBinary
= 0x001,
1047 kSecCodeExecSegAllowUnsigned
= 0x010,
1048 kSecCodeExecSegDebugger
= 0x020,
1049 kSecCodeExecSegJit
= 0x040,
1050 kSecCodeExecSegSkipLibraryVal
= 0x080,
1051 kSecCodeExecSegCanLoadCdHash
= 0x100,
1052 kSecCodeExecSegCanExecCdHash
= 0x100,
1069 struct BlobIndex index
[];
1072 struct CodeDirectory
{
1075 uint32_t hashOffset
;
1076 uint32_t identOffset
;
1077 uint32_t nSpecialSlots
;
1078 uint32_t nCodeSlots
;
1085 uint32_t scatterOffset
;
1086 uint32_t teamIDOffset
;
1088 uint64_t codeLimit64
;
1089 uint64_t execSegBase
;
1090 uint64_t execSegLimit
;
1091 uint64_t execSegFlags
;
1092 #if 0 // version = 0x20500
1094 uint32_t preEncryptOffset
;
1096 #if 0 // version = 0x20600
1097 uint8_t linkageHashType
;
1098 uint8_t linkageTruncated
;
1100 uint32_t linkageOffset
;
1101 uint32_t linkageSize
;
1105 enum CodeSignatureFlags
{
1106 kSecCodeSignatureHost
= 0x0001,
1107 kSecCodeSignatureAdhoc
= 0x0002,
1108 kSecCodeSignatureForceHard
= 0x0100,
1109 kSecCodeSignatureForceKill
= 0x0200,
1110 kSecCodeSignatureForceExpiration
= 0x0400,
1111 kSecCodeSignatureRestrict
= 0x0800,
1112 kSecCodeSignatureEnforcement
= 0x1000,
1113 kSecCodeSignatureLibraryValidation
= 0x2000,
1114 kSecCodeSignatureRuntime
= 0x10000,
1117 enum Kind
: uint32_t {
1118 exprForm
= 1, // prefix expr form
1121 enum ExprOp
: uint32_t {
1122 opFalse
, // unconditionally false
1123 opTrue
, // unconditionally true
1124 opIdent
, // match canonical code [string]
1125 opAppleAnchor
, // signed by Apple as Apple's product
1126 opAnchorHash
, // match anchor [cert hash]
1127 opInfoKeyValue
, // *legacy* - use opInfoKeyField [key; value]
1128 opAnd
, // binary prefix expr AND expr [expr; expr]
1129 opOr
, // binary prefix expr OR expr [expr; expr]
1130 opCDHash
, // match hash of CodeDirectory directly [cd hash]
1131 opNot
, // logical inverse [expr]
1132 opInfoKeyField
, // Info.plist key field [string; match suffix]
1133 opCertField
, // Certificate field [cert index; field name; match suffix]
1134 opTrustedCert
, // require trust settings to approve one particular cert [cert index]
1135 opTrustedCerts
, // require trust settings to approve the cert chain
1136 opCertGeneric
, // Certificate component by OID [cert index; oid; match suffix]
1137 opAppleGenericAnchor
, // signed by Apple in any capacity
1138 opEntitlementField
, // entitlement dictionary field [string; match suffix]
1139 opCertPolicy
, // Certificate policy by OID [cert index; oid; match suffix]
1140 opNamedAnchor
, // named anchor type
1141 opNamedCode
, // named subroutine
1142 opPlatform
, // platform constraint [integer]
1143 exprOpCount
// (total opcode count in use)
1146 enum MatchOperation
{
1147 matchExists
, // anything but explicit "false" - no value stored
1148 matchEqual
, // equal (CFEqual)
1149 matchContains
, // partial match (substring)
1150 matchBeginsWith
, // partial match (initial substring)
1151 matchEndsWith
, // partial match (terminal substring)
1152 matchLessThan
, // less than (string with numeric comparison)
1153 matchGreaterThan
, // greater than (string with numeric comparison)
1154 matchLessEqual
, // less or equal (string with numeric comparison)
1155 matchGreaterEqual
, // greater or equal (string with numeric comparison)
1158 #define OID_ISO_MEMBER 42
1159 #define OID_US OID_ISO_MEMBER, 134, 72
1160 #define APPLE_OID OID_US, 0x86, 0xf7, 0x63
1161 #define APPLE_ADS_OID APPLE_OID, 0x64
1162 #define APPLE_EXTENSION_OID APPLE_ADS_OID, 6
1164 #ifndef LDID_NOFLAGT
1165 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
1172 Algorithm(size_t size
, uint8_t type
) :
1178 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const = 0;
1180 virtual void operator ()(uint8_t *hash
, const void *data
, size_t size
) const = 0;
1181 virtual void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const = 0;
1182 virtual void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const = 0;
1184 virtual const char *name() = 0;
1187 struct AlgorithmSHA1
:
1191 Algorithm(LDID_SHA1_DIGEST_LENGTH
, CS_HASHTYPE_SHA160_160
)
1195 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1199 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1200 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
1203 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1204 return operator()(hash
.sha1_
, data
, size
);
1207 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1208 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
1209 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1212 virtual const char *name() {
1217 struct AlgorithmSHA256
:
1221 Algorithm(LDID_SHA256_DIGEST_LENGTH
, CS_HASHTYPE_SHA256_256
)
1225 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1226 return hash
.sha256_
;
1229 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1230 LDID_SHA256(static_cast<const uint8_t *>(data
), size
, hash
);
1233 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1234 return operator()(hash
.sha256_
, data
, size
);
1237 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1238 hash
.resize(LDID_SHA256_DIGEST_LENGTH
);
1239 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1242 virtual const char *name() {
1247 static bool do_sha1(true);
1248 static bool do_sha256(true);
1250 static const std::vector
<Algorithm
*> &GetAlgorithms() {
1251 static AlgorithmSHA1 sha1
;
1252 static AlgorithmSHA256 sha256
;
1254 static std::vector
<Algorithm
*> algorithms
;
1255 if (algorithms
.empty()) {
1257 algorithms
.push_back(&sha1
);
1259 algorithms
.push_back(&sha256
);
1266 std::string entitlements_
;
1267 std::string derformat_
;
1270 struct CodesignAllocation
{
1271 FatMachHeader mach_header_
;
1280 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
, const char *arch
, const Baton
&baton
) :
1281 mach_header_(mach_header
),
1293 #ifndef LDID_NOTOOLS
1306 _syscall(close(file_
));
1309 void open(const char *path
, int flags
) {
1310 _assert(file_
== -1);
1311 file_
= _syscall(::open(path
, flags
));
1328 _syscall(munmap(data_
, size_
));
1340 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
1343 open(path
, oflag
, pflag
, mflag
);
1346 Map(const std::string
&path
, bool edit
) :
1356 bool empty() const {
1357 return data_
== NULL
;
1360 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
1363 file_
.open(path
.c_str(), oflag
);
1364 int file(file_
.file());
1367 _syscall(fstat(file
, &stat
));
1368 size_
= stat
.st_size
;
1370 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
1373 void open(const std::string
&path
, bool edit
) {
1375 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
1377 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1380 void *data() const {
1384 size_t size() const {
1388 operator std::string() const {
1389 return std::string(static_cast<char *>(data_
), size_
);
1396 #ifndef LDID_NOPLIST
1397 static plist_t
plist(const std::string
&data
);
1400 void Analyze(const MachHeader
&mach_header
, const Functor
<void (const char *data
, size_t size
)> &entitle
) {
1401 _foreach (load_command
, mach_header
.GetLoadCommands())
1402 if (mach_header
.Swap(load_command
->cmd
) == LC_CODE_SIGNATURE
) {
1403 auto signature(reinterpret_cast<struct linkedit_data_command
*>(load_command
));
1404 auto offset(mach_header
.Swap(signature
->dataoff
));
1405 auto pointer(reinterpret_cast<uint8_t *>(mach_header
.GetBase()) + offset
);
1406 auto super(reinterpret_cast<struct SuperBlob
*>(pointer
));
1408 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1409 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1410 auto begin(Swap(super
->index
[index
].offset
));
1411 auto blob(reinterpret_cast<struct Blob
*>(pointer
+ begin
));
1412 auto writ(Swap(blob
->length
) - sizeof(*blob
));
1413 entitle(reinterpret_cast<char *>(blob
+ 1), writ
);
1418 std::string
Analyze(const void *data
, size_t size
) {
1419 std::string entitlements
;
1421 FatHeader
fat_header(const_cast<void *>(data
), size
);
1422 _foreach (mach_header
, fat_header
.GetMachHeaders())
1423 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
1424 if (entitlements
.empty())
1425 entitlements
.assign(data
, size
);
1427 _assert(entitlements
.compare(0, entitlements
.size(), data
, size
) == 0);
1430 return entitlements
;
1433 static void Allocate(const void *idata
, size_t isize
, std::streambuf
&output
, const Functor
<size_t (const MachHeader
&, Baton
&, size_t)> &allocate
, const Functor
<size_t (const MachHeader
&, const Baton
&, std::streambuf
&output
, size_t, size_t, size_t, const std::string
&, const char *, const Progress
&)> &save
, const Progress
&progress
) {
1434 FatHeader
source(const_cast<void *>(idata
), isize
);
1438 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
1440 std::vector
<CodesignAllocation
> allocations
;
1441 _foreach (mach_header
, source
.GetMachHeaders()) {
1442 struct linkedit_data_command
*signature(NULL
);
1443 struct symtab_command
*symtab(NULL
);
1445 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1446 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1448 else if (cmd
== LC_CODE_SIGNATURE
)
1449 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1450 else if (cmd
== LC_SYMTAB
)
1451 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
1455 if (signature
== NULL
)
1456 size
= mach_header
.GetSize();
1458 size
= mach_header
.Swap(signature
->dataoff
);
1459 _assert(size
<= mach_header
.GetSize());
1462 if (symtab
!= NULL
) {
1463 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
1464 if (symtab
->stroff
!= 0 || symtab
->strsize
!= 0) {
1465 _assert(end
<= size
);
1466 _assert(end
>= size
- 0x10);
1472 size_t alloc(allocate(mach_header
, baton
, size
));
1474 auto *fat_arch(mach_header
.GetFatArch());
1477 if (fat_arch
!= NULL
)
1478 align
= source
.Swap(fat_arch
->align
);
1479 else switch (mach_header
.GetCPUType()) {
1480 case CPU_TYPE_POWERPC
:
1481 case CPU_TYPE_POWERPC64
:
1483 case CPU_TYPE_X86_64
:
1487 case CPU_TYPE_ARM64
:
1488 case CPU_TYPE_ARM64_32
:
1496 const char *arch(NULL
);
1497 switch (mach_header
.GetCPUType()) {
1498 case CPU_TYPE_POWERPC
:
1501 case CPU_TYPE_POWERPC64
:
1507 case CPU_TYPE_X86_64
:
1513 case CPU_TYPE_ARM64
:
1516 case CPU_TYPE_ARM64_32
:
1521 offset
= Align(offset
, 1 << align
);
1523 uint32_t limit(size
);
1525 limit
= Align(limit
, 0x10);
1527 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
, arch
, baton
));
1528 offset
+= size
+ alloc
;
1529 offset
= Align(offset
, 0x10);
1534 if (source
.IsFat()) {
1535 fat_header fat_header
;
1536 fat_header
.magic
= Swap(FAT_MAGIC
);
1537 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1538 put(output
, &fat_header
, sizeof(fat_header
));
1539 position
+= sizeof(fat_header
);
1541 // XXX: support fat_arch_64 (not in my toolchain)
1542 // probably use C++14 generic lambda (not in my toolchain)
1545 _foreach (allocation
, allocations
) {
1546 const auto offset(allocation
.offset_
);
1547 const auto size(allocation
.limit_
+ allocation
.alloc_
);
1548 if (uint32_t(offset
) != offset
|| uint32_t(size
) != size
)
1552 }(), "FAT slice >=4GiB not currently supported");
1554 _foreach (allocation
, allocations
) {
1555 auto &mach_header(allocation
.mach_header_
);
1558 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1559 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1560 fat_arch
.offset
= Swap(uint32_t(allocation
.offset_
));
1561 fat_arch
.size
= Swap(uint32_t(allocation
.limit_
+ allocation
.alloc_
));
1562 fat_arch
.align
= Swap(allocation
.align_
);
1563 put(output
, &fat_arch
, sizeof(fat_arch
));
1564 position
+= sizeof(fat_arch
);
1568 _foreach (allocation
, allocations
) {
1569 progress(allocation
.arch_
);
1570 auto &mach_header(allocation
.mach_header_
);
1572 pad(output
, allocation
.offset_
- position
);
1573 position
= allocation
.offset_
;
1578 std::vector
<std::string
> commands
;
1580 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1581 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1583 switch (mach_header
.Swap(load_command
->cmd
)) {
1584 case LC_CODE_SIGNATURE
:
1588 // XXX: this is getting ridiculous: provide a better abstraction
1591 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1593 if ((segment_command
->initprot
& 04) != 0) {
1594 auto begin(mach_header
.Swap(segment_command
->fileoff
));
1595 auto end(begin
+ mach_header
.Swap(segment_command
->filesize
));
1602 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) == 0) {
1603 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1604 segment_command
->filesize
= size
;
1605 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1609 case LC_SEGMENT_64
: {
1610 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1612 if ((segment_command
->initprot
& 04) != 0) {
1613 auto begin(mach_header
.Swap(segment_command
->fileoff
));
1614 auto end(begin
+ mach_header
.Swap(segment_command
->filesize
));
1621 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) == 0) {
1622 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1623 segment_command
->filesize
= size
;
1624 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1629 commands
.push_back(copy
);
1632 if (allocation
.alloc_
!= 0) {
1633 linkedit_data_command signature
;
1634 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1635 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1636 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1637 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1638 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1641 size_t begin(position
);
1644 _foreach(command
, commands
)
1645 after
+= command
.size();
1647 std::stringbuf altern
;
1649 struct mach_header
header(*mach_header
);
1650 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1651 header
.sizeofcmds
= mach_header
.Swap(after
);
1652 put(output
, &header
, sizeof(header
));
1653 put(altern
, &header
, sizeof(header
));
1654 position
+= sizeof(header
);
1656 if (mach_header
.Bits64()) {
1657 auto pad(mach_header
.Swap(uint32_t(0)));
1658 put(output
, &pad
, sizeof(pad
));
1659 put(altern
, &pad
, sizeof(pad
));
1660 position
+= sizeof(pad
);
1663 _foreach(command
, commands
) {
1664 put(output
, command
.data(), command
.size());
1665 put(altern
, command
.data(), command
.size());
1666 position
+= command
.size();
1669 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1670 if (before
> after
) {
1671 pad(output
, before
- after
);
1672 pad(altern
, before
- after
);
1673 position
+= before
- after
;
1676 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1678 std::string
overlap(altern
.str());
1679 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1681 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
), progress
);
1682 position
= begin
+ allocation
.size_
;
1684 pad(output
, allocation
.limit_
- allocation
.size_
);
1685 position
+= allocation
.limit_
- allocation
.size_
;
1687 size_t saved(save(mach_header
, allocation
.baton_
, output
, allocation
.limit_
, left
, right
, overlap
, top
, progress
));
1688 if (allocation
.alloc_
> saved
)
1689 pad(output
, allocation
.alloc_
- saved
);
1691 _assert(allocation
.alloc_
== saved
);
1692 position
+= allocation
.alloc_
;
1698 typedef std::map
<uint32_t, std::string
> Blobs
;
1700 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1701 auto value(buffer
.str());
1702 std::swap(blobs
[slot
], value
);
1705 static const std::string
&insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1706 auto value(buffer
.str());
1708 blob
.magic
= Swap(magic
);
1709 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1710 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1711 auto &save(blobs
[slot
]);
1712 std::swap(save
, value
);
1716 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1718 _foreach (blob
, blobs
)
1719 total
+= blob
.second
.size();
1721 struct SuperBlob super
;
1722 super
.blob
.magic
= Swap(magic
);
1723 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1724 super
.count
= Swap(uint32_t(blobs
.size()));
1725 put(output
, &super
, sizeof(super
));
1727 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1729 _foreach (blob
, blobs
) {
1731 index
.type
= Swap(blob
.first
);
1732 index
.offset
= Swap(uint32_t(offset
));
1733 put(output
, &index
, sizeof(index
));
1734 offset
+= blob
.second
.size();
1737 _foreach (blob
, blobs
)
1738 put(output
, blob
.second
.data(), blob
.second
.size());
1743 #ifndef LDID_NOSMIME
1752 _assert(bio_
!= NULL
);
1756 bio_(BIO_new(BIO_s_mem()))
1760 Buffer(const char *data
, size_t size
) :
1761 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1765 Buffer(const std::string
&data
) :
1766 Buffer(data
.data(), data
.size())
1770 Buffer(PKCS7
*pkcs
) :
1773 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1780 operator BIO
*() const {
1784 explicit operator std::string() const {
1786 auto size(BIO_get_mem_data(bio_
, &data
));
1787 return std::string(data
, size
);
1796 STACK_OF(X509
) *ca_
;
1800 value_(d2i_PKCS12_bio(bio
, NULL
)),
1803 _assert(value_
!= NULL
);
1805 if (!PKCS12_verify_mac(value_
, "", 0) && password
.empty()) {
1807 UI_UTIL_read_pw_string(passbuf
, 2048, "Enter password: ", 0);
1811 _assert(PKCS12_parse(value_
, password
.c_str(), &key_
, &cert_
, &ca_
) != 0);
1812 _assert(key_
!= NULL
);
1813 _assert(cert_
!= NULL
);
1816 ca_
= sk_X509_new_null();
1817 _assert(ca_
!= NULL
);
1820 Stuff(const std::string
&data
) :
1826 sk_X509_pop_free(ca_
, X509_free
);
1828 EVP_PKEY_free(key_
);
1829 PKCS12_free(value_
);
1832 operator PKCS12
*() const {
1836 operator EVP_PKEY
*() const {
1840 operator X509
*() const {
1844 operator STACK_OF(X509
) *() const {
1854 Signature(const Stuff
&stuff
, const Buffer
&data
, const std::string
&xml
) {
1855 value_
= PKCS7_new();
1856 _assert(value_
!= NULL
);
1858 _assert(PKCS7_set_type(value_
, NID_pkcs7_signed
));
1859 _assert(PKCS7_content_new(value_
, NID_pkcs7_data
));
1861 STACK_OF(X509
) *certs(stuff
);
1862 for (unsigned i(0), e(sk_X509_num(certs
)); i
!= e
; i
++)
1863 _assert(PKCS7_add_certificate(value_
, sk_X509_value(certs
, e
- i
- 1)));
1865 auto info(PKCS7_sign_add_signer(value_
, stuff
, stuff
, NULL
, PKCS7_NOSMIMECAP
));
1866 _assert(info
!= NULL
);
1868 PKCS7_set_detached(value_
, 1);
1870 ASN1_OCTET_STRING
*string(ASN1_OCTET_STRING_new());
1871 _assert(string
!= NULL
);
1873 _assert(ASN1_STRING_set(string
, xml
.data(), xml
.size()));
1875 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "", ""));
1876 _assert(PKCS7_add_signed_attribute(info
, nid
, V_ASN1_OCTET_STRING
, string
));
1878 ASN1_OCTET_STRING_free(string
);
1882 _assert(PKCS7_final(value_
, data
, PKCS7_BINARY
));
1889 operator PKCS7
*() const {
1896 public std::streambuf
1899 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1903 virtual int_type
overflow(int_type next
) {
1909 public std::streambuf
1914 LDID_SHA1_CTX sha1_
;
1915 LDID_SHA256_CTX sha256_
;
1918 HashBuffer(ldid::Hash
&hash
) :
1921 LDID_SHA1_Init(&sha1_
);
1922 LDID_SHA256_Init(&sha256_
);
1926 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.sha1_
), &sha1_
);
1927 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_
.sha256_
), &sha256_
);
1930 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1931 LDID_SHA1_Update(&sha1_
, data
, size
);
1932 LDID_SHA256_Update(&sha256_
, data
, size
);
1936 virtual int_type
overflow(int_type next
) {
1937 if (next
== traits_type::eof())
1949 std::streambuf
&buffer_
;
1952 HashProxy(ldid::Hash
&hash
, std::streambuf
&buffer
) :
1958 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1959 _assert(HashBuffer::xsputn(data
, size
) == size
);
1960 return buffer_
.sputn(data
, size
);
1964 #ifndef LDID_NOTOOLS
1965 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1966 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1974 Split(const std::string
&path
) {
1975 size_t slash(path
.rfind('/'));
1976 if (slash
== std::string::npos
)
1979 dir
= path
.substr(0, slash
+ 1);
1980 base
= path
.substr(slash
+ 1);
1985 static void mkdir_p(const std::string
&path
) {
1989 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
1992 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
1995 auto slash(path
.rfind('/', path
.size() - 1));
1996 if (slash
== std::string::npos
)
1998 mkdir_p(path
.substr(0, slash
));
2001 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
2002 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
2004 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
2008 static void Commit(const std::string
&path
, const std::string
&temp
) {
2010 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
2012 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
2014 _syscall(chmod(temp
.c_str(), info
.st_mode
));
2017 _syscall(rename(temp
.c_str(), path
.c_str()));
2023 #ifndef LDID_NOSMIME
2024 static void get(std::string
&value
, X509_NAME
*name
, int nid
) {
2025 auto index(X509_NAME_get_index_by_NID(name
, nid
, -1));
2026 _assert(index
>= 0);
2027 auto next(X509_NAME_get_index_by_NID(name
, nid
, index
));
2028 _assert(next
== -1);
2029 auto entry(X509_NAME_get_entry(name
, index
));
2030 _assert(entry
!= NULL
);
2031 auto asn(X509_NAME_ENTRY_get_data(entry
));
2032 _assert(asn
!= NULL
);
2033 value
.assign(reinterpret_cast<const char *>(ASN1_STRING_get0_data(asn
)), ASN1_STRING_length(asn
));
2037 static void req(std::streambuf
&buffer
, uint32_t value
) {
2038 value
= Swap(value
);
2039 put(buffer
, &value
, sizeof(value
));
2042 static void req(std::streambuf
&buffer
, const std::string
&value
) {
2043 req(buffer
, value
.size());
2044 put(buffer
, value
.data(), value
.size());
2045 static uint8_t zeros
[] = {0,0,0,0};
2046 put(buffer
, zeros
, 3 - (value
.size() + 3) % 4);
2049 template <size_t Size_
>
2050 static void req(std::streambuf
&buffer
, uint8_t (&&data
)[Size_
]) {
2052 put(buffer
, data
, Size_
);
2053 static uint8_t zeros
[] = {0,0,0,0};
2054 put(buffer
, zeros
, 3 - (Size_
+ 3) % 4);
2057 Hash
Sign(const void *idata
, size_t isize
, std::streambuf
&output
, const std::string
&identifier
, const std::string
&entitlements
, bool merge
, const std::string
&requirements
, const std::string
&key
, const Slots
&slots
, uint32_t flags
, bool platform
, const Progress
&progress
) {
2064 #ifndef LDID_NOSMIME
2067 auto name(X509_get_subject_name(stuff
));
2068 _assert(name
!= NULL
);
2069 get(team
, name
, NID_organizationalUnitName
);
2070 get(common
, name
, NID_commonName
);
2075 std::stringbuf backing
;
2077 if (!requirements
.empty()) {
2078 put(backing
, requirements
.data(), requirements
.size());
2082 std::stringbuf requirement
;
2083 req(requirement
, exprForm
);
2084 req(requirement
, opAnd
);
2085 req(requirement
, opIdent
);
2086 req(requirement
, identifier
);
2087 req(requirement
, opAnd
);
2088 req(requirement
, opAppleGenericAnchor
);
2089 req(requirement
, opAnd
);
2090 req(requirement
, opCertField
);
2091 req(requirement
, 0);
2092 req(requirement
, "subject.CN");
2093 req(requirement
, matchEqual
);
2094 req(requirement
, common
);
2095 req(requirement
, opCertGeneric
);
2096 req(requirement
, 1);
2097 req(requirement
, (uint8_t []) {APPLE_EXTENSION_OID
, 2, 1});
2098 req(requirement
, matchExists
);
2099 insert(blobs
, 3, CSMAGIC_REQUIREMENT
, requirement
);
2101 put(backing
, CSMAGIC_REQUIREMENTS
, blobs
);
2105 // XXX: this is just a "sufficiently large number"
2106 size_t certificate(0x3000);
2108 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2109 size_t alloc(sizeof(struct SuperBlob
));
2111 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
2113 uint32_t special(0);
2115 _foreach (slot
, slots
)
2116 special
= std::max(special
, slot
.first
);
2118 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2119 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
2120 special
= std::max(special
, CSSLOT_INFOSLOT
);
2123 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
2124 alloc
+= sizeof(struct BlobIndex
);
2125 alloc
+= backing
.str().size();
2128 baton
.entitlements_
= entitlements
;
2131 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
2132 baton
.entitlements_
.assign(data
, size
);
2135 if (!baton
.entitlements_
.empty() || !entitlements
.empty()) {
2136 auto combined(plist(baton
.entitlements_
));
2137 _scope({ plist_free(combined
); });
2138 _assert(plist_get_node_type(combined
) == PLIST_DICT
);
2140 auto merging(plist(entitlements
));
2141 _scope({ plist_free(merging
); });
2142 _assert(plist_get_node_type(merging
) == PLIST_DICT
);
2144 plist_dict_iter
iterator(NULL
);
2145 plist_dict_new_iter(merging
, &iterator
);
2146 _scope({ free(iterator
); });
2150 plist_t
value(NULL
);
2151 plist_dict_next_item(merging
, iterator
, &key
, &value
);
2154 _scope({ free(key
); });
2155 plist_dict_set_item(combined
, key
, plist_copy(value
));
2158 baton
.derformat_
= der(combined
);
2162 plist_to_xml(combined
, &xml
, &size
);
2163 _scope({ free(xml
); });
2165 baton
.entitlements_
.assign(xml
, size
);
2169 if (!baton
.entitlements_
.empty()) {
2170 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
2171 alloc
+= sizeof(struct BlobIndex
);
2172 alloc
+= sizeof(struct Blob
);
2173 alloc
+= baton
.entitlements_
.size();
2176 if (!baton
.derformat_
.empty()) {
2177 special
= std::max(special
, CSSLOT_DERFORMAT
);
2178 alloc
+= sizeof(struct BlobIndex
);
2179 alloc
+= sizeof(struct Blob
);
2180 alloc
+= baton
.derformat_
.size();
2183 size_t directory(0);
2185 directory
+= sizeof(struct BlobIndex
);
2186 directory
+= sizeof(struct Blob
);
2187 directory
+= sizeof(struct CodeDirectory
);
2188 directory
+= identifier
.size() + 1;
2191 directory
+= team
.size() + 1;
2193 for (Algorithm
*algorithm
: GetAlgorithms())
2194 alloc
= Align(alloc
+ directory
+ (special
+ normal
) * algorithm
->size_
, 16);
2196 #ifndef LDID_NOSMIME
2198 alloc
+= sizeof(struct BlobIndex
);
2199 alloc
+= sizeof(struct Blob
);
2200 alloc
+= certificate
;
2205 }), fun([&](const MachHeader
&mach_header
, const Baton
&baton
, std::streambuf
&output
, size_t limit
, size_t left
, size_t right
, const std::string
&overlap
, const char *top
, const Progress
&progress
) -> size_t {
2209 insert(blobs
, CSSLOT_REQUIREMENTS
, backing
);
2213 if (mach_header
.Swap(mach_header
->filetype
) == MH_EXECUTE
)
2214 execs
|= kSecCodeExecSegMainBinary
;
2216 if (!baton
.entitlements_
.empty()) {
2217 std::stringbuf data
;
2218 put(data
, baton
.entitlements_
.data(), baton
.entitlements_
.size());
2219 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
2221 #ifndef LDID_NOPLIST
2222 auto entitlements(plist(baton
.entitlements_
));
2223 _scope({ plist_free(entitlements
); });
2224 _assert(plist_get_node_type(entitlements
) == PLIST_DICT
);
2226 const auto entitled([&](const char *key
) {
2227 auto item(plist_dict_get_item(entitlements
, key
));
2228 if (plist_get_node_type(item
) != PLIST_BOOLEAN
)
2231 plist_get_bool_val(item
, &value
);
2235 if (entitled("get-task-allow"))
2236 execs
|= kSecCodeExecSegAllowUnsigned
;
2237 if (entitled("run-unsigned-code"))
2238 execs
|= kSecCodeExecSegAllowUnsigned
;
2239 if (entitled("com.apple.private.cs.debugger"))
2240 execs
|= kSecCodeExecSegDebugger
;
2241 if (entitled("dynamic-codesigning"))
2242 execs
|= kSecCodeExecSegJit
;
2243 if (entitled("com.apple.private.skip-library-validation"))
2244 execs
|= kSecCodeExecSegSkipLibraryVal
;
2245 if (entitled("com.apple.private.amfi.can-load-cdhash"))
2246 execs
|= kSecCodeExecSegCanLoadCdHash
;
2247 if (entitled("com.apple.private.amfi.can-execute-cdhash"))
2248 execs
|= kSecCodeExecSegCanExecCdHash
;
2252 if (!baton
.derformat_
.empty()) {
2253 std::stringbuf data
;
2254 put(data
, baton
.derformat_
.data(), baton
.derformat_
.size());
2255 insert(blobs
, CSSLOT_DERFORMAT
, CSMAGIC_EMBEDDED_DERFORMAT
, data
);
2260 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2261 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0) {
2262 auto &slot(posts
[CSSLOT_INFOSLOT
]);
2263 for (Algorithm
*algorithm
: GetAlgorithms())
2264 (*algorithm
)(slot
, data
, size
);
2269 for (Algorithm
*pointer
: GetAlgorithms()) {
2270 Algorithm
&algorithm(*pointer
);
2272 std::stringbuf data
;
2274 uint32_t special(0);
2275 _foreach (blob
, blobs
)
2276 special
= std::max(special
, blob
.first
);
2277 _foreach (slot
, posts
)
2278 special
= std::max(special
, slot
.first
);
2279 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
2281 CodeDirectory directory
;
2282 directory
.version
= Swap(uint32_t(0x00020400));
2283 directory
.flags
= Swap(uint32_t(flags
));
2284 directory
.nSpecialSlots
= Swap(special
);
2285 directory
.codeLimit
= Swap(uint32_t(limit
> UINT32_MAX
? UINT32_MAX
: limit
));
2286 directory
.nCodeSlots
= Swap(normal
);
2287 directory
.hashSize
= algorithm
.size_
;
2288 directory
.hashType
= algorithm
.type_
;
2289 directory
.platform
= platform
? 0x01 : 0x00;
2290 directory
.pageSize
= PageShift_
;
2291 directory
.spare2
= Swap(uint32_t(0));
2292 directory
.scatterOffset
= Swap(uint32_t(0));
2293 directory
.spare3
= Swap(uint32_t(0));
2294 directory
.codeLimit64
= Swap(uint64_t(limit
> UINT32_MAX
? limit
: 0));
2295 directory
.execSegBase
= Swap(uint64_t(left
));
2296 directory
.execSegLimit
= Swap(uint64_t(right
- left
));
2297 directory
.execSegFlags
= Swap(execs
);
2299 uint32_t offset(sizeof(Blob
) + sizeof(CodeDirectory
));
2301 directory
.identOffset
= Swap(uint32_t(offset
));
2302 offset
+= identifier
.size() + 1;
2305 directory
.teamIDOffset
= Swap(uint32_t(0));
2307 directory
.teamIDOffset
= Swap(uint32_t(offset
));
2308 offset
+= team
.size() + 1;
2311 offset
+= special
* algorithm
.size_
;
2312 directory
.hashOffset
= Swap(uint32_t(offset
));
2313 offset
+= normal
* algorithm
.size_
;
2315 put(data
, &directory
, sizeof(directory
));
2317 put(data
, identifier
.c_str(), identifier
.size() + 1);
2319 put(data
, team
.c_str(), team
.size() + 1);
2321 std::vector
<uint8_t> storage((special
+ normal
) * algorithm
.size_
);
2322 auto *hashes(&storage
[special
* algorithm
.size_
]);
2324 memset(storage
.data(), 0, special
* algorithm
.size_
);
2326 _foreach (blob
, blobs
) {
2327 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
2328 algorithm(hashes
- blob
.first
* algorithm
.size_
, local
, Swap(local
->length
));
2331 _foreach (slot
, posts
)
2332 memcpy(hashes
- slot
.first
* algorithm
.size_
, algorithm
[slot
.second
], algorithm
.size_
);
2336 for (size_t i
= 0; i
!= normal
- 1; ++i
) {
2337 algorithm(hashes
+ i
* algorithm
.size_
, (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
2338 progress(double(i
) / normal
);
2341 algorithm(hashes
+ (normal
- 1) * algorithm
.size_
, top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
2344 put(data
, storage
.data(), storage
.size());
2346 const auto &save(insert(blobs
, total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1, CSMAGIC_CODEDIRECTORY
, data
));
2347 algorithm(hash
, save
.data(), save
.size());
2352 #ifndef LDID_NOSMIME
2355 auto plist(CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
));
2356 _scope({ CFRelease(plist
); });
2358 auto cdhashes(CFArrayCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeArrayCallBacks
));
2359 _scope({ CFRelease(cdhashes
); });
2361 CFDictionarySetValue(plist
, CFSTR("cdhashes"), cdhashes
);
2363 auto plist(plist_new_dict());
2364 _scope({ plist_free(plist
); });
2366 auto cdhashes(plist_new_array());
2367 plist_dict_set_item(plist
, "cdhashes", cdhashes
);
2371 for (Algorithm
*pointer
: GetAlgorithms()) {
2372 Algorithm
&algorithm(*pointer
);
2375 const auto &blob(blobs
[total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1]);
2378 std::vector
<char> hash
;
2379 algorithm(hash
, blob
.data(), blob
.size());
2383 auto value(CFDataCreate(kCFAllocatorDefault
, reinterpret_cast<const UInt8
*>(hash
.data()), hash
.size()));
2384 _scope({ CFRelease(value
); });
2385 CFArrayAppendValue(cdhashes
, value
);
2387 plist_array_append_item(cdhashes
, plist_new_data(hash
.data(), hash
.size()));
2392 auto created(CFPropertyListCreateXMLData(kCFAllocatorDefault
, plist
));
2393 _scope({ CFRelease(created
); });
2394 auto xml(reinterpret_cast<const char *>(CFDataGetBytePtr(created
)));
2395 auto size(CFDataGetLength(created
));
2399 plist_to_xml(plist
, &xml
, &size
);
2400 _scope({ free(xml
); });
2403 std::stringbuf data
;
2404 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
2409 Signature
signature(stuff
, sign
, std::string(xml
, size
));
2410 Buffer
result(signature
);
2411 std::string
value(result
);
2412 put(data
, value
.data(), value
.size());
2414 const auto &save(insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
));
2415 _assert(save
.size() <= certificate
);
2419 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
2425 #ifndef LDID_NOTOOLS
2426 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
, const Progress
&progress
) {
2427 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2429 }), fun([](const MachHeader
&mach_header
, const Baton
&baton
, std::streambuf
&output
, size_t limit
, size_t left
, size_t right
, const std::string
&overlap
, const char *top
, const Progress
&progress
) -> size_t {
2434 std::string
DiskFolder::Path(const std::string
&path
) const {
2435 return path_
+ path
;
2438 DiskFolder::DiskFolder(const std::string
&path
) :
2441 _assert_(path_
.size() != 0 && path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2444 DiskFolder::~DiskFolder() {
2445 if (!std::uncaught_exception())
2446 for (const auto &commit
: commit_
)
2447 Commit(commit
.first
, commit
.second
);
2451 std::string
readlink(const std::string
&path
) {
2452 for (size_t size(1024); ; size
*= 2) {
2456 int writ(_syscall(::readlink(path
.c_str(), &data
[0], data
.size())));
2457 if (size_t(writ
) >= size
)
2466 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 {
2467 std::string
path(Path(root
) + base
);
2469 DIR *dir(opendir(path
.c_str()));
2470 _assert(dir
!= NULL
);
2471 _scope({ _syscall(closedir(dir
)); });
2473 while (auto child
= readdir(dir
)) {
2474 std::string
name(child
->d_name
);
2475 if (name
== "." || name
== "..")
2477 if (Starts(name
, ".ldid."))
2484 _syscall(stat((path
+ name
).c_str(), &info
));
2486 else if (S_ISDIR(info
.st_mode
))
2488 else if (S_ISREG(info
.st_mode
))
2491 _assert_(false, "st_mode=%x", info
.st_mode
);
2493 switch (child
->d_type
) {
2501 link(base
+ name
, fun([&]() { return readlink(path
+ name
); }));
2504 _assert_(false, "d_type=%u", child
->d_type
);
2509 Find(root
, base
+ name
+ "/", code
, link
);
2515 void DiskFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2521 auto from(Path(path
));
2522 commit_
[from
] = Temporary(save
, from
);
2527 bool DiskFolder::Look(const std::string
&path
) const {
2528 return _syscall(access(Path(path
).c_str(), R_OK
), ENOENT
) == 0;
2531 void DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2533 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
2534 _assert_(result
== &data
, "DiskFolder::Open(%s)", Path(path
).c_str());
2536 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2537 data
.pubseekpos(0, std::ios::in
);
2538 code(data
, length
, NULL
);
2541 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 {
2542 Find(path
, "", code
, link
);
2546 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
2550 _assert_(path_
.size() == 0 || path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2553 std::string
SubFolder::Path(const std::string
&path
) const {
2554 return path_
+ path
;
2557 void SubFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2558 return parent_
.Save(Path(path
), edit
, flag
, code
);
2561 bool SubFolder::Look(const std::string
&path
) const {
2562 return parent_
.Look(Path(path
));
2565 void SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2566 return parent_
.Open(Path(path
), code
);
2569 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 {
2570 return parent_
.Find(Path(path
), code
, link
);
2573 std::string
UnionFolder::Map(const std::string
&path
) const {
2574 auto remap(remaps_
.find(path
));
2575 if (remap
== remaps_
.end())
2577 return remap
->second
;
2580 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 {
2581 if (file
.size() >= path
.size() && file
.substr(0, path
.size()) == path
)
2582 code(file
.substr(path
.size()));
2585 UnionFolder::UnionFolder(Folder
&parent
) :
2590 void UnionFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2591 return parent_
.Save(Map(path
), edit
, flag
, code
);
2594 bool UnionFolder::Look(const std::string
&path
) const {
2595 auto file(resets_
.find(path
));
2596 if (file
!= resets_
.end())
2598 return parent_
.Look(Map(path
));
2601 void UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2602 auto file(resets_
.find(path
));
2603 if (file
== resets_
.end())
2604 return parent_
.Open(Map(path
), code
);
2605 auto &entry(file
->second
);
2607 auto &data(*entry
.data_
);
2608 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2609 data
.pubseekpos(0, std::ios::in
);
2610 code(data
, length
, entry
.flag_
);
2613 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 {
2614 for (auto &reset
: resets_
)
2615 Map(path
, code
, reset
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2616 auto &entry(reset
.second
);
2617 auto &data(*entry
.data_
);
2618 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2619 data
.pubseekpos(0, std::ios::in
);
2620 code(data
, length
, entry
.flag_
);
2623 for (auto &remap
: remaps_
)
2624 Map(path
, code
, remap
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2625 parent_
.Open(remap
.second
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2626 code(data
, length
, flag
);
2630 parent_
.Find(path
, fun([&](const std::string
&name
) {
2631 if (deletes_
.find(path
+ name
) == deletes_
.end())
2633 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2634 if (deletes_
.find(path
+ name
) == deletes_
.end())
2639 #ifndef LDID_NOTOOLS
2640 static void copy(std::streambuf
&source
, std::streambuf
&target
, size_t length
, const Progress
&progress
) {
2644 char data
[4096 * 4];
2645 size_t writ(source
.sgetn(data
, sizeof(data
)));
2648 _assert(target
.sputn(data
, writ
) == writ
);
2650 progress(double(total
) / length
);
2654 #ifndef LDID_NOPLIST
2655 static plist_t
plist(const std::string
&data
) {
2657 return plist_new_dict();
2658 plist_t
plist(NULL
);
2659 if (Starts(data
, "bplist00"))
2660 plist_from_bin(data
.data(), data
.size(), &plist
);
2662 plist_from_xml(data
.data(), data
.size(), &plist
);
2663 _assert(plist
!= NULL
);
2667 static void plist_d(std::streambuf
&buffer
, size_t length
, const Functor
<void (plist_t
)> &code
) {
2668 std::stringbuf data
;
2669 copy(buffer
, data
, length
, dummy_
);
2670 auto node(plist(data
.str()));
2671 _scope({ plist_free(node
); });
2672 _assert(plist_get_node_type(node
) == PLIST_DICT
);
2676 static std::string
plist_s(plist_t node
) {
2677 _assert(node
!= NULL
);
2678 _assert(plist_get_node_type(node
) == PLIST_STRING
);
2680 plist_get_string_val(node
, &data
);
2681 _scope({ free(data
); });
2697 std::vector
<std::string
> matches_
;
2700 Expression(const std::string
&code
) {
2701 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
) == 0, "regcomp()");
2702 matches_
.resize(regex_
.re_nsub
+ 1);
2709 bool operator ()(const std::string
&data
) {
2710 regmatch_t matches
[matches_
.size()];
2711 auto value(regexec(®ex_
, data
.c_str(), matches_
.size(), matches
, 0));
2712 if (value
== REG_NOMATCH
)
2714 _assert_(value
== 0, "regexec()");
2715 for (size_t i(0); i
!= matches_
.size(); ++i
)
2716 matches_
[i
].assign(data
.data() + matches
[i
].rm_so
, matches
[i
].rm_eo
- matches
[i
].rm_so
);
2720 const std::string
&operator [](size_t index
) const {
2721 return matches_
[index
];
2730 mutable std::unique_ptr
<Expression
> regex_
;
2732 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
2739 Rule(const Rule
&rhs
) :
2740 weight_(rhs
.weight_
),
2746 void Compile() const {
2747 regex_
.reset(new Expression(code_
));
2750 bool operator ()(const std::string
&data
) const {
2751 _assert(regex_
.get() != NULL
);
2752 return (*regex_
)(data
);
2755 bool operator <(const Rule
&rhs
) const {
2756 if (weight_
> rhs
.weight_
)
2758 if (weight_
< rhs
.weight_
)
2760 return mode_
> rhs
.mode_
;
2765 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
2766 return lhs
->code_
< rhs
->code_
;
2770 #ifndef LDID_NOPLIST
2771 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
, bool merge
, const std::string
&requirements
, const std::string
&key
, const Slots
&slots
, size_t length
, uint32_t flags
, bool platform
, const Progress
&progress
) {
2772 // XXX: this is a miserable fail
2773 std::stringbuf temp
;
2774 put(temp
, prefix
, size
);
2775 copy(buffer
, temp
, length
- size
, progress
);
2776 // XXX: this is a stupid hack
2777 pad(temp
, 0x10 - (length
& 0xf));
2778 auto data(temp
.str());
2780 HashProxy
proxy(hash
, save
);
2781 return Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, merge
, requirements
, key
, slots
, flags
, platform
, progress
);
2785 std::map
<std::string
, Hash
> files
;
2786 std::map
<std::string
, std::string
> links
;
2788 void Merge(const std::string
&root
, const State
&state
) {
2789 for (const auto &entry
: state
.files
)
2790 files
[root
+ entry
.first
] = entry
.second
;
2791 for (const auto &entry
: state
.links
)
2792 links
[root
+ entry
.first
] = entry
.second
;
2796 Bundle
Sign(const std::string
&root
, Folder
&parent
, const std::string
&key
, State
&local
, const std::string
&requirements
, const Functor
<std::string (const std::string
&, const std::string
&)> &alter
, const Progress
&progress
) {
2797 std::string executable
;
2798 std::string identifier
;
2802 std::string
info("Info.plist");
2804 SubFolder
folder(parent
, [&]() {
2805 if (parent
.Look(info
))
2809 else if (parent
.Look("Contents/" + info
))
2811 else if (parent
.Look("Resources/" + info
)) {
2812 info
= "Resources/" + info
;
2814 } else _assert_(false, "cannot find Info.plist");
2817 folder
.Open(info
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2818 plist_d(buffer
, length
, fun([&](plist_t node
) {
2819 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
2820 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
2824 if (mac
&& info
== "Info.plist")
2825 executable
= "MacOS/" + executable
;
2827 progress(root
+ "*");
2829 std::string entitlements
;
2830 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2831 // XXX: this is a miserable fail
2832 std::stringbuf temp
;
2833 copy(buffer
, temp
, length
, progress
);
2834 // XXX: this is a stupid hack
2835 pad(temp
, 0x10 - (length
& 0xf));
2836 auto data(temp
.str());
2837 entitlements
= alter(root
, Analyze(data
.data(), data
.size()));
2840 static const std::string
directory("_CodeSignature/");
2841 static const std::string
signature(directory
+ "CodeResources");
2843 std::map
<std::string
, std::multiset
<Rule
>> versions
;
2845 auto &rules1(versions
[""]);
2846 auto &rules2(versions
["2"]);
2848 const std::string
resources(mac
? "Resources/" : "");
2851 rules1
.insert(Rule
{1, NoMode
, "^" + (resources
== "" ? ".*" : resources
)});
2852 rules1
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2853 rules1
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2854 rules1
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2855 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
2859 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
2860 if (mac
) rules2
.insert(Rule
{20, NoMode
, "^" + resources
});
2861 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
2862 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2863 rules2
.insert(Rule
{1, NoMode
, "^.*"});
2864 rules2
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2865 rules2
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2866 if (!mac
) rules2
.insert(Rule
{1010, NoMode
, "^Base\\.lproj/"});
2867 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
2868 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
2869 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
2870 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
2871 if (mac
) rules2
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2872 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
2875 std::string
failure(mac
? "Contents/|Versions/[^/]*/Resources/" : "");
2876 Expression
nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure
+ ")Info\\.plist$");
2877 std::map
<std::string
, Bundle
> bundles
;
2879 folder
.Find("", fun([&](const std::string
&name
) {
2882 auto bundle(Split(name
).dir
);
2884 _assert(!bundle
.empty());
2885 bundle
= Split(bundle
.substr(0, bundle
.size() - 1)).dir
;
2887 SubFolder
subfolder(folder
, bundle
);
2890 bundles
[nested
[1]] = Sign(root
+ bundle
, subfolder
, key
, remote
, "", Starts(name
, "PlugIns/") ? alter
:
2891 static_cast<const Functor
<std::string (const std::string
&, const std::string
&)> &>(fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }))
2893 local
.Merge(bundle
, remote
);
2894 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2897 std::set
<std::string
> excludes
;
2899 auto exclude([&](const std::string
&name
) {
2900 // BundleDiskRep::adjustResources -> builder.addExclusion
2901 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
2904 for (const auto &bundle
: bundles
)
2905 if (Starts(name
, bundle
.first
+ "/")) {
2906 excludes
.insert(name
);
2913 folder
.Find("", fun([&](const std::string
&name
) {
2917 if (local
.files
.find(name
) != local
.files
.end())
2919 auto &hash(local
.files
[name
]);
2921 folder
.Open(name
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2922 progress(root
+ name
);
2933 auto size(most(data
, &header
.bytes
, sizeof(header
.bytes
)));
2935 if (name
!= "_WatchKitStub/WK" && size
== sizeof(header
.bytes
))
2936 switch (Swap(header
.magic
)) {
2938 // Java class file format
2939 if (Swap(header
.count
) >= 40)
2942 case MH_MAGIC
: case MH_MAGIC_64
:
2943 case MH_CIGAM
: case MH_CIGAM_64
:
2944 folder
.Save(name
, true, flag
, fun([&](std::streambuf
&save
) {
2946 Sign(header
.bytes
, size
, data
, hash
, save
, identifier
, "", false, "", key
, slots
, length
, 0, false, Progression(progress
, root
+ name
));
2951 folder
.Save(name
, false, flag
, fun([&](std::streambuf
&save
) {
2952 HashProxy
proxy(hash
, save
);
2953 put(proxy
, header
.bytes
, size
);
2954 copy(data
, proxy
, length
- size
, progress
);
2957 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2961 local
.links
[name
] = read();
2964 auto plist(plist_new_dict());
2965 _scope({ plist_free(plist
); });
2967 for (const auto &version
: versions
) {
2968 auto files(plist_new_dict());
2969 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
2971 for (const auto &rule
: version
.second
)
2974 bool old(&version
.second
== &rules1
);
2976 for (const auto &hash
: local
.files
)
2977 for (const auto &rule
: version
.second
)
2978 if (rule(hash
.first
)) {
2979 if (!old
&& mac
&& excludes
.find(hash
.first
) != excludes
.end());
2980 else if (old
&& rule
.mode_
== NoMode
)
2981 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2982 else if (rule
.mode_
!= OmitMode
) {
2983 auto entry(plist_new_dict());
2984 plist_dict_set_item(entry
, "hash", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2986 plist_dict_set_item(entry
, "hash2", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha256_
), sizeof(hash
.second
.sha256_
)));
2987 if (rule
.mode_
== OptionalMode
)
2988 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2989 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
2996 for (const auto &link
: local
.links
)
2997 for (const auto &rule
: version
.second
)
2998 if (rule(link
.first
)) {
2999 if (rule
.mode_
!= OmitMode
) {
3000 auto entry(plist_new_dict());
3001 plist_dict_set_item(entry
, "symlink", plist_new_string(link
.second
.c_str()));
3002 if (rule
.mode_
== OptionalMode
)
3003 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3004 plist_dict_set_item(files
, link
.first
.c_str(), entry
);
3011 for (const auto &bundle
: bundles
) {
3012 auto entry(plist_new_dict());
3013 plist_dict_set_item(entry
, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle
.second
.hash
.sha256_
), sizeof(bundle
.second
.hash
.sha256_
)));
3014 plist_dict_set_item(entry
, "requirement", plist_new_string("anchor apple generic"));
3015 plist_dict_set_item(files
, bundle
.first
.c_str(), entry
);
3019 for (const auto &version
: versions
) {
3020 auto rules(plist_new_dict());
3021 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
3023 std::multiset
<const Rule
*, RuleCode
> ordered
;
3024 for (const auto &rule
: version
.second
)
3025 ordered
.insert(&rule
);
3027 for (const auto &rule
: ordered
)
3028 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
3029 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
3031 auto entry(plist_new_dict());
3032 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
3034 switch (rule
->mode_
) {
3038 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
3041 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3044 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
3047 plist_dict_set_item(entry
, "top", plist_new_bool(true));
3051 if (rule
->weight_
>= 10000)
3052 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
3053 else if (rule
->weight_
!= 1)
3054 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
3058 folder
.Save(signature
, true, NULL
, fun([&](std::streambuf
&save
) {
3059 HashProxy
proxy(local
.files
[signature
], save
);
3062 plist_to_xml(plist
, &xml
, &size
);
3063 _scope({ free(xml
); });
3064 put(proxy
, xml
, size
);
3068 bundle
.path
= folder
.Path(executable
);
3070 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
3071 progress(root
+ executable
);
3072 folder
.Save(executable
, true, flag
, fun([&](std::streambuf
&save
) {
3074 slots
[1] = local
.files
.at(info
);
3075 slots
[3] = local
.files
.at(signature
);
3076 bundle
.hash
= Sign(NULL
, 0, buffer
, local
.files
[executable
], save
, identifier
, entitlements
, false, requirements
, key
, slots
, length
, 0, false, Progression(progress
, root
+ executable
));
3083 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 Progress
&progress
) {
3085 return Sign(root
, folder
, key
, local
, requirements
, alter
, progress
);
3092 std::string
Hex(const uint8_t *data
, size_t size
) {
3094 hex
.reserve(size
* 2);
3095 for (size_t i(0); i
!= size
; ++i
) {
3096 hex
+= "0123456789abcdef"[data
[i
] >> 4];
3097 hex
+= "0123456789abcdef"[data
[i
] & 0xf];
3102 static void usage(const char *argv0
) {
3103 fprintf(stderr
, "Link Identity Editor %s\n\n", LDID_VERSION
);
3104 fprintf(stderr
, "usage: %s [-Acputype:subtype] [-a] [-C[adhoc | enforcement | expires | hard |\n", argv0
);
3105 fprintf(stderr
, " host | kill | library-validation | restrict | runtime]] [-D] [-d]\n");
3106 fprintf(stderr
, " [-Enum:file] [-e] [-h] [-Kkey.p12 [-Upassword]] [-M] [-P] [-q]\n");
3107 fprintf(stderr
, " [-r | -Sfile | -s] [-Ttimestamp] [-u] file ...\n\n");
3108 fprintf(stderr
, "Options:\n");
3109 fprintf(stderr
, " -S[file.xml] Pseudo-sign using the entitlements in file.xml\n");
3110 fprintf(stderr
, " -Kkey.p12 Sign using private key in key.p12\n");
3111 fprintf(stderr
, " -Upassword Use password to unlock key.p12\n");
3112 fprintf(stderr
, " -M Merge entitlements with any existing\n");
3113 fprintf(stderr
, " -h Print CDHash of file\n\n");
3114 fprintf(stderr
, "More information: 'man ldid'\n");
3117 #ifndef LDID_NOTOOLS
3118 int main(int argc
, char *argv
[]) {
3119 #ifndef LDID_NOSMIME
3120 OpenSSL_add_all_algorithms();
3121 # if OPENSSL_VERSION_MAJOR >= 3
3122 OSSL_PROVIDER
*legacy
= OSSL_PROVIDER_load(NULL
, "legacy");
3123 OSSL_PROVIDER
*deflt
= OSSL_PROVIDER_load(NULL
, "default");
3132 little_
= endian
.byte
[0];
3141 #ifndef LDID_NOFLAGT
3159 bool platform(false);
3161 uint32_t flag_CPUType(_not(uint32_t));
3162 uint32_t flag_CPUSubtype(_not(uint32_t));
3164 const char *flag_I(NULL
);
3166 #ifndef LDID_NOFLAGT
3176 std::vector
<std::string
> files
;
3183 for (int argi(1); argi
!= argc
; ++argi
)
3184 if (argv
[argi
][0] != '-')
3185 files
.push_back(argv
[argi
]);
3186 else switch (argv
[argi
][1]) {
3193 case 'e': flag_e
= true; break;
3196 const char *string
= argv
[argi
] + 2;
3197 const char *colon
= strchr(string
, ':');
3198 _assert(colon
!= NULL
);
3199 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3201 unsigned number(strtoul(string
, &arge
, 0));
3202 _assert(arge
== colon
);
3203 auto &slot(slots
[number
]);
3204 for (Algorithm
*algorithm
: GetAlgorithms())
3205 (*algorithm
)(slot
, file
.data(), file
.size());
3208 case 'q': flag_q
= true; break;
3211 const char *hash
= argv
[argi
] + 2;
3221 else if (strcmp(hash
, "sha1") == 0)
3223 else if (strcmp(hash
, "sha256") == 0)
3225 else _assert(false);
3228 case 'h': flag_h
= true; break;
3231 const char *xml
= argv
[argi
] + 2;
3232 requirements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3235 case 'D': flag_D
= true; break;
3236 case 'd': flag_d
= true; break;
3238 case 'a': flag_a
= true; break;
3243 if (argv
[argi
][2] != '\0') {
3244 const char *cpu
= argv
[argi
] + 2;
3245 const char *colon
= strchr(cpu
, ':');
3246 _assert(colon
!= NULL
);
3248 flag_CPUType
= strtoul(cpu
, &arge
, 0);
3249 _assert(arge
== colon
);
3250 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
3251 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
3256 const char *name
= argv
[argi
] + 2;
3258 else if (strcmp(name
, "host") == 0)
3259 flags
|= kSecCodeSignatureHost
;
3260 else if (strcmp(name
, "adhoc") == 0)
3261 flags
|= kSecCodeSignatureAdhoc
;
3262 else if (strcmp(name
, "hard") == 0)
3263 flags
|= kSecCodeSignatureForceHard
;
3264 else if (strcmp(name
, "kill") == 0)
3265 flags
|= kSecCodeSignatureForceKill
;
3266 else if (strcmp(name
, "expires") == 0)
3267 flags
|= kSecCodeSignatureForceExpiration
;
3268 else if (strcmp(name
, "restrict") == 0)
3269 flags
|= kSecCodeSignatureRestrict
;
3270 else if (strcmp(name
, "enforcement") == 0)
3271 flags
|= kSecCodeSignatureEnforcement
;
3272 else if (strcmp(name
, "library-validation") == 0)
3273 flags
|= kSecCodeSignatureLibraryValidation
;
3274 else if (strcmp(name
, "runtime") == 0)
3275 flags
|= kSecCodeSignatureRuntime
;
3276 else _assert(false);
3293 if (argv
[argi
][2] != '\0') {
3294 const char *xml
= argv
[argi
] + 2;
3295 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3304 password
= argv
[argi
] + 2;
3308 if (argv
[argi
][2] != '\0')
3309 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3312 #ifndef LDID_NOFLAGT
3315 if (argv
[argi
][2] == '-')
3319 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
3320 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
3330 flag_I
= argv
[argi
] + 2;
3339 _assert(flag_S
|| key
.empty());
3340 _assert(flag_S
|| flag_I
== NULL
);
3342 if (flag_d
&& !flag_h
) {
3344 fprintf(stderr
, "WARNING: -d also (temporarily) does the behavior of -h for compatibility with a fork of ldid\n");
3350 size_t filei(0), filee(0);
3351 _foreach (file
, files
) try {
3352 std::string
path(file
);
3355 _syscall(stat(path
.c_str(), &info
));
3357 if (S_ISDIR(info
.st_mode
)) {
3359 #ifndef LDID_NOPLIST
3360 ldid::DiskFolder
folder(path
+ "/");
3361 path
+= "/" + Sign("", folder
, key
, requirements
, ldid::fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }), dummy_
).path
;
3365 } else if (flag_S
|| flag_r
) {
3366 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3368 std::filebuf output
;
3370 auto temp(Temporary(output
, split
));
3373 ldid::Unsign(input
.data(), input
.size(), output
, dummy_
);
3375 std::string
identifier(flag_I
?: split
.base
.c_str());
3376 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, flag_M
, requirements
, key
, slots
, flags
, platform
, dummy_
);
3383 #ifndef LDID_NOFLAGT
3390 Map
mapping(path
, modify
);
3391 FatHeader
fat_header(mapping
.data(), mapping
.size());
3393 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
3394 struct linkedit_data_command
*signature(NULL
);
3395 struct encryption_info_command
*encryption(NULL
);
3398 if (mach_header
.GetCPUType() != flag_CPUType
)
3400 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
3405 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
3407 _foreach (load_command
, mach_header
.GetLoadCommands()) {
3408 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
3411 else if (cmd
== LC_CODE_SIGNATURE
)
3412 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
3413 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
3414 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
3415 else if (cmd
== LC_LOAD_DYLIB
) {
3416 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3417 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
3419 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
3422 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
3423 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
3427 #ifndef LDID_NOFLAGT
3428 else if (cmd
== LC_ID_DYLIB
) {
3429 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3437 dylib_command
->dylib
.timestamp
= 0;
3438 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
3441 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
3447 if (flag_d
&& encryption
!= NULL
) {
3448 printf("cryptid=%d\n", mach_header
.Swap(encryption
->cryptid
));
3452 _assert(encryption
!= NULL
);
3453 encryption
->cryptid
= mach_header
.Swap(0);
3457 _assert(signature
!= NULL
);
3459 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3461 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3462 uint8_t *blob
= top
+ data
;
3463 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3465 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3466 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
3467 uint32_t begin
= Swap(super
->index
[index
].offset
);
3468 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3469 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
3474 _assert(signature
!= NULL
);
3476 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3478 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3479 uint8_t *blob
= top
+ data
;
3480 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3482 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3483 if (Swap(super
->index
[index
].type
) == CSSLOT_REQUIREMENTS
) {
3484 uint32_t begin
= Swap(super
->index
[index
].offset
);
3485 struct Blob
*requirement
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3486 fwrite(requirement
, 1, Swap(requirement
->length
), stdout
);
3491 _assert(signature
!= NULL
);
3493 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3495 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3496 uint8_t *blob
= top
+ data
;
3497 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3499 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3500 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
3501 uint32_t begin
= Swap(super
->index
[index
].offset
);
3502 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3504 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
3505 uint32_t pages
= Swap(directory
->nCodeSlots
);
3508 for (size_t i
= 0; i
!= pages
- 1; ++i
)
3509 LDID_SHA1(top
+ PageSize_
* i
, PageSize_
, hashes
[i
]);
3511 LDID_SHA1(top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1, hashes
[pages
- 1]);
3516 _assert(signature
!= NULL
);
3518 auto algorithms(GetAlgorithms());
3520 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3522 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3523 uint8_t *blob
= top
+ data
;
3524 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3527 CodeDirectory
*directory_
;
3529 Algorithm
&algorithm_
;
3533 std::map
<uint8_t, Candidate
> candidates
;
3535 for (size_t index(0); index
!= Swap(super
->count
); ++index
) {
3536 auto type(Swap(super
->index
[index
].type
));
3537 if ((type
== CSSLOT_CODEDIRECTORY
|| type
>= CSSLOT_ALTERNATE
) && type
!= CSSLOT_SIGNATURESLOT
) {
3538 uint32_t begin
= Swap(super
->index
[index
].offset
);
3539 uint32_t end
= index
+ 1 == Swap(super
->count
) ? Swap(super
->blob
.length
) : Swap(super
->index
[index
+ 1].offset
);
3540 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3541 auto type(directory
->hashType
);
3542 _assert(type
> 0 && type
<= algorithms
.size());
3543 auto &algorithm(*algorithms
[type
- 1]);
3544 uint8_t hash
[algorithm
.size_
];
3545 algorithm(hash
, blob
+ begin
, end
- begin
);
3546 candidates
.insert({type
, {directory
, end
- begin
, algorithm
, Hex(hash
, 20)}});
3550 _assert(!candidates
.empty());
3551 auto best(candidates
.end());
3554 const auto directory(best
->second
.directory_
);
3555 const auto flags(Swap(directory
->flags
));
3558 if (flags
& kSecCodeSignatureHost
)
3560 if (flags
& kSecCodeSignatureAdhoc
)
3562 if (flags
& kSecCodeSignatureForceHard
)
3564 if (flags
& kSecCodeSignatureForceKill
)
3566 if (flags
& kSecCodeSignatureForceExpiration
)
3567 names
+= ",expires";
3568 if (flags
& kSecCodeSignatureRestrict
)
3569 names
+= ",restrict";
3570 if (flags
& kSecCodeSignatureEnforcement
)
3571 names
+= ",enforcement";
3572 if (flags
& kSecCodeSignatureLibraryValidation
)
3573 names
+= ",library-validation";
3574 if (flags
& kSecCodeSignatureRuntime
)
3575 names
+= ",runtime";
3577 printf("CodeDirectory v=%x size=%zd flags=0x%x(%s) hashes=%d+%d location=embedded\n",
3578 Swap(directory
->version
), best
->second
.size_
, flags
, names
.empty() ? "none" : names
.c_str() + 1, Swap(directory
->nCodeSlots
), Swap(directory
->nSpecialSlots
));
3579 printf("Hash type=%s size=%d\n", best
->second
.algorithm_
.name(), directory
->hashSize
);
3581 std::string choices
;
3582 for (const auto &candidate
: candidates
) {
3583 auto choice(candidate
.second
.algorithm_
.name());
3586 printf("CandidateCDHash %s=%s\n", choice
, candidate
.second
.hash_
.c_str());
3588 printf("Hash choices=%s\n", choices
.c_str() + 1);
3590 printf("CDHash=%s\n", best
->second
.hash_
.c_str());
3595 } catch (const char *) {
3600 #ifndef LDID_NOSMIME
3601 # if OPENSSL_VERSION_MAJOR >= 3
3602 OSSL_PROVIDER_unload(legacy
);
3603 OSSL_PROVIDER_unload(deflt
);