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(&sha256
);
1259 algorithms
.push_back(&sha1
);
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 // XXX: this is the same as PKCS7_sign_add_signer(value_, stuff, stuff, NULL, PKCS7_NOSMIMECAP)
1866 _assert(X509_check_private_key(stuff
, stuff
));
1867 auto info(PKCS7_add_signature(value_
, stuff
, stuff
, EVP_sha1()));
1868 _assert(info
!= NULL
);
1869 _assert(PKCS7_add_certificate(value_
, stuff
));
1870 _assert(PKCS7_add_signed_attribute(info
, NID_pkcs9_contentType
, V_ASN1_OBJECT
, OBJ_nid2obj(NID_pkcs7_data
)));
1872 PKCS7_set_detached(value_
, 1);
1874 ASN1_OCTET_STRING
*string(ASN1_OCTET_STRING_new());
1875 _assert(string
!= NULL
);
1877 _assert(ASN1_STRING_set(string
, xml
.data(), xml
.size()));
1879 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "", ""));
1880 _assert(PKCS7_add_signed_attribute(info
, nid
, V_ASN1_OCTET_STRING
, string
));
1882 ASN1_OCTET_STRING_free(string
);
1886 // XXX: this is the same as PKCS7_final(value_, data, PKCS7_BINARY)
1887 BIO
*bio(PKCS7_dataInit(value_
, NULL
));
1888 _assert(bio
!= NULL
);
1889 _scope({ BIO_free_all(bio
); });
1890 SMIME_crlf_copy(data
, bio
, PKCS7_BINARY
);
1892 _assert(PKCS7_dataFinal(value_
, bio
));
1899 operator PKCS7
*() const {
1906 public std::streambuf
1909 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1913 virtual int_type
overflow(int_type next
) {
1919 public std::streambuf
1924 LDID_SHA1_CTX sha1_
;
1925 LDID_SHA256_CTX sha256_
;
1928 HashBuffer(ldid::Hash
&hash
) :
1931 LDID_SHA1_Init(&sha1_
);
1932 LDID_SHA256_Init(&sha256_
);
1936 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.sha1_
), &sha1_
);
1937 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_
.sha256_
), &sha256_
);
1940 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1941 LDID_SHA1_Update(&sha1_
, data
, size
);
1942 LDID_SHA256_Update(&sha256_
, data
, size
);
1946 virtual int_type
overflow(int_type next
) {
1947 if (next
== traits_type::eof())
1959 std::streambuf
&buffer_
;
1962 HashProxy(ldid::Hash
&hash
, std::streambuf
&buffer
) :
1968 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1969 _assert(HashBuffer::xsputn(data
, size
) == size
);
1970 return buffer_
.sputn(data
, size
);
1974 #ifndef LDID_NOTOOLS
1975 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1976 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1984 Split(const std::string
&path
) {
1985 size_t slash(path
.rfind('/'));
1986 if (slash
== std::string::npos
)
1989 dir
= path
.substr(0, slash
+ 1);
1990 base
= path
.substr(slash
+ 1);
1995 static void mkdir_p(const std::string
&path
) {
1999 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
2002 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
2005 auto slash(path
.rfind('/', path
.size() - 1));
2006 if (slash
== std::string::npos
)
2008 mkdir_p(path
.substr(0, slash
));
2011 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
2012 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
2014 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
2018 static void Commit(const std::string
&path
, const std::string
&temp
) {
2020 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
2022 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
2024 _syscall(chmod(temp
.c_str(), info
.st_mode
));
2027 _syscall(rename(temp
.c_str(), path
.c_str()));
2033 #ifndef LDID_NOSMIME
2034 static void get(std::string
&value
, X509_NAME
*name
, int nid
) {
2035 auto index(X509_NAME_get_index_by_NID(name
, nid
, -1));
2036 _assert(index
>= 0);
2037 auto next(X509_NAME_get_index_by_NID(name
, nid
, index
));
2038 _assert(next
== -1);
2039 auto entry(X509_NAME_get_entry(name
, index
));
2040 _assert(entry
!= NULL
);
2041 auto asn(X509_NAME_ENTRY_get_data(entry
));
2042 _assert(asn
!= NULL
);
2043 value
.assign(reinterpret_cast<const char *>(ASN1_STRING_get0_data(asn
)), ASN1_STRING_length(asn
));
2047 static void req(std::streambuf
&buffer
, uint32_t value
) {
2048 value
= Swap(value
);
2049 put(buffer
, &value
, sizeof(value
));
2052 static void req(std::streambuf
&buffer
, const std::string
&value
) {
2053 req(buffer
, value
.size());
2054 put(buffer
, value
.data(), value
.size());
2055 static uint8_t zeros
[] = {0,0,0,0};
2056 put(buffer
, zeros
, 3 - (value
.size() + 3) % 4);
2059 template <size_t Size_
>
2060 static void req(std::streambuf
&buffer
, uint8_t (&&data
)[Size_
]) {
2062 put(buffer
, data
, Size_
);
2063 static uint8_t zeros
[] = {0,0,0,0};
2064 put(buffer
, zeros
, 3 - (Size_
+ 3) % 4);
2067 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
) {
2074 #ifndef LDID_NOSMIME
2077 auto name(X509_get_subject_name(stuff
));
2078 _assert(name
!= NULL
);
2079 get(team
, name
, NID_organizationalUnitName
);
2080 get(common
, name
, NID_commonName
);
2085 std::stringbuf backing
;
2087 if (!requirements
.empty()) {
2088 put(backing
, requirements
.data(), requirements
.size());
2092 std::stringbuf requirement
;
2093 req(requirement
, exprForm
);
2094 req(requirement
, opAnd
);
2095 req(requirement
, opIdent
);
2096 req(requirement
, identifier
);
2097 req(requirement
, opAnd
);
2098 req(requirement
, opAppleGenericAnchor
);
2099 req(requirement
, opAnd
);
2100 req(requirement
, opCertField
);
2101 req(requirement
, 0);
2102 req(requirement
, "subject.CN");
2103 req(requirement
, matchEqual
);
2104 req(requirement
, common
);
2105 req(requirement
, opCertGeneric
);
2106 req(requirement
, 1);
2107 req(requirement
, (uint8_t []) {APPLE_EXTENSION_OID
, 2, 1});
2108 req(requirement
, matchExists
);
2109 insert(blobs
, 3, CSMAGIC_REQUIREMENT
, requirement
);
2111 put(backing
, CSMAGIC_REQUIREMENTS
, blobs
);
2115 // XXX: this is just a "sufficiently large number"
2116 size_t certificate(0x3000);
2118 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2119 size_t alloc(sizeof(struct SuperBlob
));
2121 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
2123 uint32_t special(0);
2125 _foreach (slot
, slots
)
2126 special
= std::max(special
, slot
.first
);
2128 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2129 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
2130 special
= std::max(special
, CSSLOT_INFOSLOT
);
2133 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
2134 alloc
+= sizeof(struct BlobIndex
);
2135 alloc
+= backing
.str().size();
2138 baton
.entitlements_
= entitlements
;
2141 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
2142 baton
.entitlements_
.assign(data
, size
);
2145 if (!baton
.entitlements_
.empty() || !entitlements
.empty()) {
2146 auto combined(plist(baton
.entitlements_
));
2147 _scope({ plist_free(combined
); });
2148 _assert(plist_get_node_type(combined
) == PLIST_DICT
);
2150 auto merging(plist(entitlements
));
2151 _scope({ plist_free(merging
); });
2152 _assert(plist_get_node_type(merging
) == PLIST_DICT
);
2154 plist_dict_iter
iterator(NULL
);
2155 plist_dict_new_iter(merging
, &iterator
);
2156 _scope({ free(iterator
); });
2160 plist_t
value(NULL
);
2161 plist_dict_next_item(merging
, iterator
, &key
, &value
);
2164 _scope({ free(key
); });
2165 plist_dict_set_item(combined
, key
, plist_copy(value
));
2168 baton
.derformat_
= der(combined
);
2172 plist_to_xml(combined
, &xml
, &size
);
2173 _scope({ free(xml
); });
2175 baton
.entitlements_
.assign(xml
, size
);
2179 if (!baton
.entitlements_
.empty()) {
2180 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
2181 alloc
+= sizeof(struct BlobIndex
);
2182 alloc
+= sizeof(struct Blob
);
2183 alloc
+= baton
.entitlements_
.size();
2186 if (!baton
.derformat_
.empty()) {
2187 special
= std::max(special
, CSSLOT_DERFORMAT
);
2188 alloc
+= sizeof(struct BlobIndex
);
2189 alloc
+= sizeof(struct Blob
);
2190 alloc
+= baton
.derformat_
.size();
2193 size_t directory(0);
2195 directory
+= sizeof(struct BlobIndex
);
2196 directory
+= sizeof(struct Blob
);
2197 directory
+= sizeof(struct CodeDirectory
);
2198 directory
+= identifier
.size() + 1;
2201 directory
+= team
.size() + 1;
2203 for (Algorithm
*algorithm
: GetAlgorithms())
2204 alloc
= Align(alloc
+ directory
+ (special
+ normal
) * algorithm
->size_
, 16);
2206 #ifndef LDID_NOSMIME
2208 alloc
+= sizeof(struct BlobIndex
);
2209 alloc
+= sizeof(struct Blob
);
2210 alloc
+= certificate
;
2215 }), 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 {
2219 insert(blobs
, CSSLOT_REQUIREMENTS
, backing
);
2223 if (mach_header
.Swap(mach_header
->filetype
) == MH_EXECUTE
)
2224 execs
|= kSecCodeExecSegMainBinary
;
2226 if (!baton
.entitlements_
.empty()) {
2227 std::stringbuf data
;
2228 put(data
, baton
.entitlements_
.data(), baton
.entitlements_
.size());
2229 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
2231 #ifndef LDID_NOPLIST
2232 auto entitlements(plist(baton
.entitlements_
));
2233 _scope({ plist_free(entitlements
); });
2234 _assert(plist_get_node_type(entitlements
) == PLIST_DICT
);
2236 const auto entitled([&](const char *key
) {
2237 auto item(plist_dict_get_item(entitlements
, key
));
2238 if (plist_get_node_type(item
) != PLIST_BOOLEAN
)
2241 plist_get_bool_val(item
, &value
);
2245 if (entitled("get-task-allow"))
2246 execs
|= kSecCodeExecSegAllowUnsigned
;
2247 if (entitled("run-unsigned-code"))
2248 execs
|= kSecCodeExecSegAllowUnsigned
;
2249 if (entitled("com.apple.private.cs.debugger"))
2250 execs
|= kSecCodeExecSegDebugger
;
2251 if (entitled("dynamic-codesigning"))
2252 execs
|= kSecCodeExecSegJit
;
2253 if (entitled("com.apple.private.skip-library-validation"))
2254 execs
|= kSecCodeExecSegSkipLibraryVal
;
2255 if (entitled("com.apple.private.amfi.can-load-cdhash"))
2256 execs
|= kSecCodeExecSegCanLoadCdHash
;
2257 if (entitled("com.apple.private.amfi.can-execute-cdhash"))
2258 execs
|= kSecCodeExecSegCanExecCdHash
;
2262 if (!baton
.derformat_
.empty()) {
2263 std::stringbuf data
;
2264 put(data
, baton
.derformat_
.data(), baton
.derformat_
.size());
2265 insert(blobs
, CSSLOT_DERFORMAT
, CSMAGIC_EMBEDDED_DERFORMAT
, data
);
2270 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2271 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0) {
2272 auto &slot(posts
[CSSLOT_INFOSLOT
]);
2273 for (Algorithm
*algorithm
: GetAlgorithms())
2274 (*algorithm
)(slot
, data
, size
);
2279 for (Algorithm
*pointer
: GetAlgorithms()) {
2280 Algorithm
&algorithm(*pointer
);
2282 std::stringbuf data
;
2284 uint32_t special(0);
2285 _foreach (blob
, blobs
)
2286 special
= std::max(special
, blob
.first
);
2287 _foreach (slot
, posts
)
2288 special
= std::max(special
, slot
.first
);
2289 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
2291 CodeDirectory directory
;
2292 directory
.version
= Swap(uint32_t(0x00020400));
2293 directory
.flags
= Swap(uint32_t(flags
));
2294 directory
.nSpecialSlots
= Swap(special
);
2295 directory
.codeLimit
= Swap(uint32_t(limit
> UINT32_MAX
? UINT32_MAX
: limit
));
2296 directory
.nCodeSlots
= Swap(normal
);
2297 directory
.hashSize
= algorithm
.size_
;
2298 directory
.hashType
= algorithm
.type_
;
2299 directory
.platform
= platform
? 0x01 : 0x00;
2300 directory
.pageSize
= PageShift_
;
2301 directory
.spare2
= Swap(uint32_t(0));
2302 directory
.scatterOffset
= Swap(uint32_t(0));
2303 directory
.spare3
= Swap(uint32_t(0));
2304 directory
.codeLimit64
= Swap(uint64_t(limit
> UINT32_MAX
? limit
: 0));
2305 directory
.execSegBase
= Swap(uint64_t(left
));
2306 directory
.execSegLimit
= Swap(uint64_t(right
- left
));
2307 directory
.execSegFlags
= Swap(execs
);
2309 uint32_t offset(sizeof(Blob
) + sizeof(CodeDirectory
));
2311 directory
.identOffset
= Swap(uint32_t(offset
));
2312 offset
+= identifier
.size() + 1;
2315 directory
.teamIDOffset
= Swap(uint32_t(0));
2317 directory
.teamIDOffset
= Swap(uint32_t(offset
));
2318 offset
+= team
.size() + 1;
2321 offset
+= special
* algorithm
.size_
;
2322 directory
.hashOffset
= Swap(uint32_t(offset
));
2323 offset
+= normal
* algorithm
.size_
;
2325 put(data
, &directory
, sizeof(directory
));
2327 put(data
, identifier
.c_str(), identifier
.size() + 1);
2329 put(data
, team
.c_str(), team
.size() + 1);
2331 std::vector
<uint8_t> storage((special
+ normal
) * algorithm
.size_
);
2332 auto *hashes(&storage
[special
* algorithm
.size_
]);
2334 memset(storage
.data(), 0, special
* algorithm
.size_
);
2336 _foreach (blob
, blobs
) {
2337 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
2338 algorithm(hashes
- blob
.first
* algorithm
.size_
, local
, Swap(local
->length
));
2341 _foreach (slot
, posts
)
2342 memcpy(hashes
- slot
.first
* algorithm
.size_
, algorithm
[slot
.second
], algorithm
.size_
);
2346 for (size_t i
= 0; i
!= normal
- 1; ++i
) {
2347 algorithm(hashes
+ i
* algorithm
.size_
, (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
2348 progress(double(i
) / normal
);
2351 algorithm(hashes
+ (normal
- 1) * algorithm
.size_
, top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
2354 put(data
, storage
.data(), storage
.size());
2356 const auto &save(insert(blobs
, total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1, CSMAGIC_CODEDIRECTORY
, data
));
2357 algorithm(hash
, save
.data(), save
.size());
2362 #ifndef LDID_NOSMIME
2365 auto plist(CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
));
2366 _scope({ CFRelease(plist
); });
2368 auto cdhashes(CFArrayCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeArrayCallBacks
));
2369 _scope({ CFRelease(cdhashes
); });
2371 CFDictionarySetValue(plist
, CFSTR("cdhashes"), cdhashes
);
2373 auto plist(plist_new_dict());
2374 _scope({ plist_free(plist
); });
2376 auto cdhashes(plist_new_array());
2377 plist_dict_set_item(plist
, "cdhashes", cdhashes
);
2381 for (Algorithm
*pointer
: GetAlgorithms()) {
2382 Algorithm
&algorithm(*pointer
);
2385 const auto &blob(blobs
[total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1]);
2388 std::vector
<char> hash
;
2389 algorithm(hash
, blob
.data(), blob
.size());
2393 auto value(CFDataCreate(kCFAllocatorDefault
, reinterpret_cast<const UInt8
*>(hash
.data()), hash
.size()));
2394 _scope({ CFRelease(value
); });
2395 CFArrayAppendValue(cdhashes
, value
);
2397 plist_array_append_item(cdhashes
, plist_new_data(hash
.data(), hash
.size()));
2402 auto created(CFPropertyListCreateXMLData(kCFAllocatorDefault
, plist
));
2403 _scope({ CFRelease(created
); });
2404 auto xml(reinterpret_cast<const char *>(CFDataGetBytePtr(created
)));
2405 auto size(CFDataGetLength(created
));
2409 plist_to_xml(plist
, &xml
, &size
);
2410 _scope({ free(xml
); });
2413 std::stringbuf data
;
2414 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
2419 Signature
signature(stuff
, sign
, std::string(xml
, size
));
2420 Buffer
result(signature
);
2421 std::string
value(result
);
2422 put(data
, value
.data(), value
.size());
2424 const auto &save(insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
));
2425 _assert(save
.size() <= certificate
);
2429 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
2435 #ifndef LDID_NOTOOLS
2436 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
, const Progress
&progress
) {
2437 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2439 }), 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 {
2444 std::string
DiskFolder::Path(const std::string
&path
) const {
2445 return path_
+ path
;
2448 DiskFolder::DiskFolder(const std::string
&path
) :
2451 _assert_(path_
.size() != 0 && path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2454 DiskFolder::~DiskFolder() {
2455 if (!std::uncaught_exception())
2456 for (const auto &commit
: commit_
)
2457 Commit(commit
.first
, commit
.second
);
2461 std::string
readlink(const std::string
&path
) {
2462 for (size_t size(1024); ; size
*= 2) {
2466 int writ(_syscall(::readlink(path
.c_str(), &data
[0], data
.size())));
2467 if (size_t(writ
) >= size
)
2476 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 {
2477 std::string
path(Path(root
) + base
);
2479 DIR *dir(opendir(path
.c_str()));
2480 _assert(dir
!= NULL
);
2481 _scope({ _syscall(closedir(dir
)); });
2483 while (auto child
= readdir(dir
)) {
2484 std::string
name(child
->d_name
);
2485 if (name
== "." || name
== "..")
2487 if (Starts(name
, ".ldid."))
2494 _syscall(stat((path
+ name
).c_str(), &info
));
2496 else if (S_ISDIR(info
.st_mode
))
2498 else if (S_ISREG(info
.st_mode
))
2501 _assert_(false, "st_mode=%x", info
.st_mode
);
2503 switch (child
->d_type
) {
2511 link(base
+ name
, fun([&]() { return readlink(path
+ name
); }));
2514 _assert_(false, "d_type=%u", child
->d_type
);
2519 Find(root
, base
+ name
+ "/", code
, link
);
2525 void DiskFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2531 auto from(Path(path
));
2532 commit_
[from
] = Temporary(save
, from
);
2537 bool DiskFolder::Look(const std::string
&path
) const {
2538 return _syscall(access(Path(path
).c_str(), R_OK
), ENOENT
) == 0;
2541 void DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2543 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
2544 _assert_(result
== &data
, "DiskFolder::Open(%s)", Path(path
).c_str());
2546 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2547 data
.pubseekpos(0, std::ios::in
);
2548 code(data
, length
, NULL
);
2551 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 {
2552 Find(path
, "", code
, link
);
2556 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
2560 _assert_(path_
.size() == 0 || path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2563 std::string
SubFolder::Path(const std::string
&path
) const {
2564 return path_
+ path
;
2567 void SubFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2568 return parent_
.Save(Path(path
), edit
, flag
, code
);
2571 bool SubFolder::Look(const std::string
&path
) const {
2572 return parent_
.Look(Path(path
));
2575 void SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2576 return parent_
.Open(Path(path
), code
);
2579 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 {
2580 return parent_
.Find(Path(path
), code
, link
);
2583 std::string
UnionFolder::Map(const std::string
&path
) const {
2584 auto remap(remaps_
.find(path
));
2585 if (remap
== remaps_
.end())
2587 return remap
->second
;
2590 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 {
2591 if (file
.size() >= path
.size() && file
.substr(0, path
.size()) == path
)
2592 code(file
.substr(path
.size()));
2595 UnionFolder::UnionFolder(Folder
&parent
) :
2600 void UnionFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2601 return parent_
.Save(Map(path
), edit
, flag
, code
);
2604 bool UnionFolder::Look(const std::string
&path
) const {
2605 auto file(resets_
.find(path
));
2606 if (file
!= resets_
.end())
2608 return parent_
.Look(Map(path
));
2611 void UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2612 auto file(resets_
.find(path
));
2613 if (file
== resets_
.end())
2614 return parent_
.Open(Map(path
), code
);
2615 auto &entry(file
->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 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 {
2624 for (auto &reset
: resets_
)
2625 Map(path
, code
, reset
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2626 auto &entry(reset
.second
);
2627 auto &data(*entry
.data_
);
2628 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2629 data
.pubseekpos(0, std::ios::in
);
2630 code(data
, length
, entry
.flag_
);
2633 for (auto &remap
: remaps_
)
2634 Map(path
, code
, remap
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2635 parent_
.Open(remap
.second
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2636 code(data
, length
, flag
);
2640 parent_
.Find(path
, fun([&](const std::string
&name
) {
2641 if (deletes_
.find(path
+ name
) == deletes_
.end())
2643 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2644 if (deletes_
.find(path
+ name
) == deletes_
.end())
2649 #ifndef LDID_NOTOOLS
2650 static void copy(std::streambuf
&source
, std::streambuf
&target
, size_t length
, const Progress
&progress
) {
2654 char data
[4096 * 4];
2655 size_t writ(source
.sgetn(data
, sizeof(data
)));
2658 _assert(target
.sputn(data
, writ
) == writ
);
2660 progress(double(total
) / length
);
2664 #ifndef LDID_NOPLIST
2665 static plist_t
plist(const std::string
&data
) {
2667 return plist_new_dict();
2668 plist_t
plist(NULL
);
2669 if (Starts(data
, "bplist00"))
2670 plist_from_bin(data
.data(), data
.size(), &plist
);
2672 plist_from_xml(data
.data(), data
.size(), &plist
);
2673 _assert(plist
!= NULL
);
2677 static void plist_d(std::streambuf
&buffer
, size_t length
, const Functor
<void (plist_t
)> &code
) {
2678 std::stringbuf data
;
2679 copy(buffer
, data
, length
, dummy_
);
2680 auto node(plist(data
.str()));
2681 _scope({ plist_free(node
); });
2682 _assert(plist_get_node_type(node
) == PLIST_DICT
);
2686 static std::string
plist_s(plist_t node
) {
2687 _assert(node
!= NULL
);
2688 _assert(plist_get_node_type(node
) == PLIST_STRING
);
2690 plist_get_string_val(node
, &data
);
2691 _scope({ free(data
); });
2707 std::vector
<std::string
> matches_
;
2710 Expression(const std::string
&code
) {
2711 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
) == 0, "regcomp()");
2712 matches_
.resize(regex_
.re_nsub
+ 1);
2719 bool operator ()(const std::string
&data
) {
2720 regmatch_t matches
[matches_
.size()];
2721 auto value(regexec(®ex_
, data
.c_str(), matches_
.size(), matches
, 0));
2722 if (value
== REG_NOMATCH
)
2724 _assert_(value
== 0, "regexec()");
2725 for (size_t i(0); i
!= matches_
.size(); ++i
)
2726 matches_
[i
].assign(data
.data() + matches
[i
].rm_so
, matches
[i
].rm_eo
- matches
[i
].rm_so
);
2730 const std::string
&operator [](size_t index
) const {
2731 return matches_
[index
];
2740 mutable std::unique_ptr
<Expression
> regex_
;
2742 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
2749 Rule(const Rule
&rhs
) :
2750 weight_(rhs
.weight_
),
2756 void Compile() const {
2757 regex_
.reset(new Expression(code_
));
2760 bool operator ()(const std::string
&data
) const {
2761 _assert(regex_
.get() != NULL
);
2762 return (*regex_
)(data
);
2765 bool operator <(const Rule
&rhs
) const {
2766 if (weight_
> rhs
.weight_
)
2768 if (weight_
< rhs
.weight_
)
2770 return mode_
> rhs
.mode_
;
2775 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
2776 return lhs
->code_
< rhs
->code_
;
2780 #ifndef LDID_NOPLIST
2781 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
) {
2782 // XXX: this is a miserable fail
2783 std::stringbuf temp
;
2784 put(temp
, prefix
, size
);
2785 copy(buffer
, temp
, length
- size
, progress
);
2786 // XXX: this is a stupid hack
2787 pad(temp
, 0x10 - (length
& 0xf));
2788 auto data(temp
.str());
2790 HashProxy
proxy(hash
, save
);
2791 return Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, merge
, requirements
, key
, slots
, flags
, platform
, progress
);
2795 std::map
<std::string
, Hash
> files
;
2796 std::map
<std::string
, std::string
> links
;
2798 void Merge(const std::string
&root
, const State
&state
) {
2799 for (const auto &entry
: state
.files
)
2800 files
[root
+ entry
.first
] = entry
.second
;
2801 for (const auto &entry
: state
.links
)
2802 links
[root
+ entry
.first
] = entry
.second
;
2806 Bundle
Sign(const std::string
&root
, Folder
&parent
, const std::string
&key
, State
&remote
, const std::string
&requirements
, const Functor
<std::string (const std::string
&, const std::string
&)> &alter
, const Progress
&progress
) {
2807 std::string executable
;
2808 std::string identifier
;
2812 std::string
info("Info.plist");
2814 SubFolder
folder(parent
, [&]() {
2815 if (parent
.Look(info
))
2819 else if (parent
.Look("Contents/" + info
))
2821 else if (parent
.Look("Resources/" + info
)) {
2822 info
= "Resources/" + info
;
2824 } else _assert_(false, "cannot find Info.plist");
2827 folder
.Open(info
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2828 plist_d(buffer
, length
, fun([&](plist_t node
) {
2829 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
2830 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
2834 if (mac
&& info
== "Info.plist")
2835 executable
= "MacOS/" + executable
;
2837 progress(root
+ "*");
2839 std::string entitlements
;
2840 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2841 // XXX: this is a miserable fail
2842 std::stringbuf temp
;
2843 copy(buffer
, temp
, length
, progress
);
2844 // XXX: this is a stupid hack
2845 pad(temp
, 0x10 - (length
& 0xf));
2846 auto data(temp
.str());
2847 entitlements
= alter(root
, Analyze(data
.data(), data
.size()));
2850 static const std::string
directory("_CodeSignature/");
2851 static const std::string
signature(directory
+ "CodeResources");
2853 std::map
<std::string
, std::multiset
<Rule
>> versions
;
2855 auto &rules1(versions
[""]);
2856 auto &rules2(versions
["2"]);
2858 const std::string
resources(mac
? "Resources/" : "");
2861 rules1
.insert(Rule
{1, NoMode
, "^" + (resources
== "" ? ".*" : resources
)});
2862 rules1
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2863 rules1
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2864 rules1
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2865 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
2869 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
2870 if (mac
) rules2
.insert(Rule
{20, NoMode
, "^" + resources
});
2871 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
2872 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2873 rules2
.insert(Rule
{1, NoMode
, "^.*"});
2874 rules2
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2875 rules2
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2876 if (!mac
) rules2
.insert(Rule
{1010, NoMode
, "^Base\\.lproj/"});
2877 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
2878 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
2879 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
2880 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
2881 if (mac
) rules2
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2882 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
2887 std::string
failure(mac
? "Contents/|Versions/[^/]*/Resources/" : "");
2888 Expression
nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure
+ ")Info\\.plist$");
2889 std::map
<std::string
, Bundle
> bundles
;
2891 folder
.Find("", fun([&](const std::string
&name
) {
2894 auto bundle(root
+ Split(name
).dir
);
2896 _assert(!bundle
.empty());
2897 bundle
= Split(bundle
.substr(0, bundle
.size() - 1)).dir
;
2899 SubFolder
subfolder(folder
, bundle
);
2901 bundles
[nested
[1]] = Sign(bundle
, subfolder
, key
, local
, "", Starts(name
, "PlugIns/") ? alter
:
2902 static_cast<const Functor
<std::string (const std::string
&, const std::string
&)> &>(fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }))
2904 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2907 std::set
<std::string
> excludes
;
2909 auto exclude([&](const std::string
&name
) {
2910 // BundleDiskRep::adjustResources -> builder.addExclusion
2911 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
2914 for (const auto &bundle
: bundles
)
2915 if (Starts(name
, bundle
.first
+ "/")) {
2916 excludes
.insert(name
);
2923 folder
.Find("", fun([&](const std::string
&name
) {
2927 if (local
.files
.find(name
) != local
.files
.end())
2929 auto &hash(local
.files
[name
]);
2931 folder
.Open(name
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2932 progress(root
+ name
);
2943 auto size(most(data
, &header
.bytes
, sizeof(header
.bytes
)));
2945 if (name
!= "_WatchKitStub/WK" && size
== sizeof(header
.bytes
))
2946 switch (Swap(header
.magic
)) {
2948 // Java class file format
2949 if (Swap(header
.count
) >= 40)
2952 case MH_MAGIC
: case MH_MAGIC_64
:
2953 case MH_CIGAM
: case MH_CIGAM_64
:
2954 folder
.Save(name
, true, flag
, fun([&](std::streambuf
&save
) {
2956 Sign(header
.bytes
, size
, data
, hash
, save
, identifier
, "", false, "", key
, slots
, length
, 0, false, Progression(progress
, root
+ name
));
2961 folder
.Save(name
, false, flag
, fun([&](std::streambuf
&save
) {
2962 HashProxy
proxy(hash
, save
);
2963 put(proxy
, header
.bytes
, size
);
2964 copy(data
, proxy
, length
- size
, progress
);
2967 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2971 local
.links
[name
] = read();
2974 auto plist(plist_new_dict());
2975 _scope({ plist_free(plist
); });
2977 for (const auto &version
: versions
) {
2978 auto files(plist_new_dict());
2979 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
2981 for (const auto &rule
: version
.second
)
2984 bool old(&version
.second
== &rules1
);
2986 for (const auto &hash
: local
.files
)
2987 for (const auto &rule
: version
.second
)
2988 if (rule(hash
.first
)) {
2989 if (!old
&& mac
&& excludes
.find(hash
.first
) != excludes
.end());
2990 else if (old
&& rule
.mode_
== NoMode
)
2991 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2992 else if (rule
.mode_
!= OmitMode
) {
2993 auto entry(plist_new_dict());
2994 plist_dict_set_item(entry
, "hash", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2996 plist_dict_set_item(entry
, "hash2", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha256_
), sizeof(hash
.second
.sha256_
)));
2997 if (rule
.mode_
== OptionalMode
)
2998 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2999 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
3006 for (const auto &link
: local
.links
)
3007 for (const auto &rule
: version
.second
)
3008 if (rule(link
.first
)) {
3009 if (rule
.mode_
!= OmitMode
) {
3010 auto entry(plist_new_dict());
3011 plist_dict_set_item(entry
, "symlink", plist_new_string(link
.second
.c_str()));
3012 if (rule
.mode_
== OptionalMode
)
3013 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3014 plist_dict_set_item(files
, link
.first
.c_str(), entry
);
3021 for (const auto &bundle
: bundles
) {
3022 auto entry(plist_new_dict());
3023 plist_dict_set_item(entry
, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle
.second
.hash
.sha256_
), sizeof(bundle
.second
.hash
.sha256_
)));
3024 plist_dict_set_item(entry
, "requirement", plist_new_string("anchor apple generic"));
3025 plist_dict_set_item(files
, bundle
.first
.c_str(), entry
);
3029 for (const auto &version
: versions
) {
3030 auto rules(plist_new_dict());
3031 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
3033 std::multiset
<const Rule
*, RuleCode
> ordered
;
3034 for (const auto &rule
: version
.second
)
3035 ordered
.insert(&rule
);
3037 for (const auto &rule
: ordered
)
3038 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
3039 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
3041 auto entry(plist_new_dict());
3042 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
3044 switch (rule
->mode_
) {
3048 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
3051 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3054 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
3057 plist_dict_set_item(entry
, "top", plist_new_bool(true));
3061 if (rule
->weight_
>= 10000)
3062 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
3063 else if (rule
->weight_
!= 1)
3064 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
3068 folder
.Save(signature
, true, NULL
, fun([&](std::streambuf
&save
) {
3069 HashProxy
proxy(local
.files
[signature
], save
);
3072 plist_to_xml(plist
, &xml
, &size
);
3073 _scope({ free(xml
); });
3074 put(proxy
, xml
, size
);
3078 bundle
.path
= folder
.Path(executable
);
3080 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
3081 progress(root
+ executable
);
3082 folder
.Save(executable
, true, flag
, fun([&](std::streambuf
&save
) {
3084 slots
[1] = local
.files
.at(info
);
3085 slots
[3] = local
.files
.at(signature
);
3086 bundle
.hash
= Sign(NULL
, 0, buffer
, local
.files
[executable
], save
, identifier
, entitlements
, false, requirements
, key
, slots
, length
, 0, false, Progression(progress
, root
+ executable
));
3090 remote
.Merge(root
, local
);
3094 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
) {
3096 return Sign(root
, folder
, key
, local
, requirements
, alter
, progress
);
3103 std::string
Hex(const uint8_t *data
, size_t size
) {
3105 hex
.reserve(size
* 2);
3106 for (size_t i(0); i
!= size
; ++i
) {
3107 hex
+= "0123456789abcdef"[data
[i
] >> 4];
3108 hex
+= "0123456789abcdef"[data
[i
] & 0xf];
3113 static void usage(const char *argv0
) {
3114 fprintf(stderr
, "Link Identity Editor %s\n\n", LDID_VERSION
);
3115 fprintf(stderr
, "usage: %s [-Acputype:subtype] [-a] [-C[adhoc | enforcement | expires | hard |\n", argv0
);
3116 fprintf(stderr
, " host | kill | library-validation | restrict | runtime]] [-D] [-d]\n");
3117 fprintf(stderr
, " [-Enum:file] [-e] [-h] [-Kkey.p12 [-Upassword]] [-M] [-P] [-q]\n");
3118 fprintf(stderr
, " [-r | -Sfile | -s] [-Ttimestamp] [-u] file ...\n\n");
3119 fprintf(stderr
, "Options:\n");
3120 fprintf(stderr
, " -S[file.xml] Pseudo-sign using the entitlements in file.xml\n");
3121 fprintf(stderr
, " -Kkey.p12 Sign using private key in key.p12\n");
3122 fprintf(stderr
, " -Upassword Use password to unlock key.p12\n");
3123 fprintf(stderr
, " -M Merge entitlements with any existing\n");
3124 fprintf(stderr
, " -h Print CDHash of file\n\n");
3125 fprintf(stderr
, "More information: 'man ldid'\n");
3128 #ifndef LDID_NOTOOLS
3129 int main(int argc
, char *argv
[]) {
3130 #ifndef LDID_NOSMIME
3131 OpenSSL_add_all_algorithms();
3132 # if OPENSSL_VERSION_MAJOR >= 3
3133 OSSL_PROVIDER
*legacy
= OSSL_PROVIDER_load(NULL
, "legacy");
3134 OSSL_PROVIDER
*deflt
= OSSL_PROVIDER_load(NULL
, "default");
3143 little_
= endian
.byte
[0];
3152 #ifndef LDID_NOFLAGT
3170 bool platform(false);
3172 uint32_t flag_CPUType(_not(uint32_t));
3173 uint32_t flag_CPUSubtype(_not(uint32_t));
3175 const char *flag_I(NULL
);
3177 #ifndef LDID_NOFLAGT
3187 std::vector
<std::string
> files
;
3194 for (int argi(1); argi
!= argc
; ++argi
)
3195 if (argv
[argi
][0] != '-')
3196 files
.push_back(argv
[argi
]);
3197 else switch (argv
[argi
][1]) {
3204 case 'e': flag_e
= true; break;
3207 const char *string
= argv
[argi
] + 2;
3208 const char *colon
= strchr(string
, ':');
3209 _assert(colon
!= NULL
);
3210 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3212 unsigned number(strtoul(string
, &arge
, 0));
3213 _assert(arge
== colon
);
3214 auto &slot(slots
[number
]);
3215 for (Algorithm
*algorithm
: GetAlgorithms())
3216 (*algorithm
)(slot
, file
.data(), file
.size());
3219 case 'q': flag_q
= true; break;
3222 const char *hash
= argv
[argi
] + 2;
3230 fprintf(stderr
, "WARNING: -H is only present for compatibility with a fork of ldid\n");
3231 fprintf(stderr
, " you should NOT be manually specifying the hash algorithm\n");
3235 else if (strcmp(hash
, "sha1") == 0)
3237 else if (strcmp(hash
, "sha256") == 0)
3239 else _assert(false);
3242 case 'h': flag_h
= true; break;
3245 const char *xml
= argv
[argi
] + 2;
3246 requirements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3249 case 'D': flag_D
= true; break;
3250 case 'd': flag_d
= true; break;
3252 case 'a': flag_a
= true; break;
3257 if (argv
[argi
][2] != '\0') {
3258 const char *cpu
= argv
[argi
] + 2;
3259 const char *colon
= strchr(cpu
, ':');
3260 _assert(colon
!= NULL
);
3262 flag_CPUType
= strtoul(cpu
, &arge
, 0);
3263 _assert(arge
== colon
);
3264 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
3265 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
3270 const char *name
= argv
[argi
] + 2;
3272 else if (strcmp(name
, "host") == 0)
3273 flags
|= kSecCodeSignatureHost
;
3274 else if (strcmp(name
, "adhoc") == 0)
3275 flags
|= kSecCodeSignatureAdhoc
;
3276 else if (strcmp(name
, "hard") == 0)
3277 flags
|= kSecCodeSignatureForceHard
;
3278 else if (strcmp(name
, "kill") == 0)
3279 flags
|= kSecCodeSignatureForceKill
;
3280 else if (strcmp(name
, "expires") == 0)
3281 flags
|= kSecCodeSignatureForceExpiration
;
3282 else if (strcmp(name
, "restrict") == 0)
3283 flags
|= kSecCodeSignatureRestrict
;
3284 else if (strcmp(name
, "enforcement") == 0)
3285 flags
|= kSecCodeSignatureEnforcement
;
3286 else if (strcmp(name
, "library-validation") == 0)
3287 flags
|= kSecCodeSignatureLibraryValidation
;
3288 else if (strcmp(name
, "runtime") == 0)
3289 flags
|= kSecCodeSignatureRuntime
;
3290 else _assert(false);
3307 if (argv
[argi
][2] != '\0') {
3308 const char *xml
= argv
[argi
] + 2;
3309 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3318 password
= argv
[argi
] + 2;
3322 if (argv
[argi
][2] != '\0')
3323 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3326 #ifndef LDID_NOFLAGT
3329 if (argv
[argi
][2] == '-')
3333 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
3334 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
3344 flag_I
= argv
[argi
] + 2;
3353 _assert(flag_S
|| key
.empty());
3354 _assert(flag_S
|| flag_I
== NULL
);
3356 if (flag_d
&& !flag_h
) {
3358 fprintf(stderr
, "WARNING: -d also (temporarily) does the behavior of -h for compatibility with a fork of ldid\n");
3364 size_t filei(0), filee(0);
3365 _foreach (file
, files
) try {
3366 std::string
path(file
);
3369 _syscall(stat(path
.c_str(), &info
));
3371 if (S_ISDIR(info
.st_mode
)) {
3373 #ifndef LDID_NOPLIST
3374 ldid::DiskFolder
folder(path
+ "/");
3375 path
+= "/" + Sign("", folder
, key
, requirements
, ldid::fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }), dummy_
).path
;
3379 } else if (flag_S
|| flag_r
) {
3380 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3382 std::filebuf output
;
3384 auto temp(Temporary(output
, split
));
3387 ldid::Unsign(input
.data(), input
.size(), output
, dummy_
);
3389 std::string
identifier(flag_I
?: split
.base
.c_str());
3390 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, flag_M
, requirements
, key
, slots
, flags
, platform
, dummy_
);
3397 #ifndef LDID_NOFLAGT
3404 Map
mapping(path
, modify
);
3405 FatHeader
fat_header(mapping
.data(), mapping
.size());
3407 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
3408 struct linkedit_data_command
*signature(NULL
);
3409 struct encryption_info_command
*encryption(NULL
);
3412 if (mach_header
.GetCPUType() != flag_CPUType
)
3414 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
3419 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
3421 _foreach (load_command
, mach_header
.GetLoadCommands()) {
3422 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
3425 else if (cmd
== LC_CODE_SIGNATURE
)
3426 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
3427 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
3428 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
3429 else if (cmd
== LC_LOAD_DYLIB
) {
3430 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3431 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
3433 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
3436 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
3437 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
3441 #ifndef LDID_NOFLAGT
3442 else if (cmd
== LC_ID_DYLIB
) {
3443 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3451 dylib_command
->dylib
.timestamp
= 0;
3452 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
3455 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
3461 if (flag_d
&& encryption
!= NULL
) {
3462 printf("cryptid=%d\n", mach_header
.Swap(encryption
->cryptid
));
3466 _assert(encryption
!= NULL
);
3467 encryption
->cryptid
= mach_header
.Swap(0);
3471 _assert(signature
!= NULL
);
3473 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3475 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3476 uint8_t *blob
= top
+ data
;
3477 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3479 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3480 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
3481 uint32_t begin
= Swap(super
->index
[index
].offset
);
3482 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3483 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
3488 _assert(signature
!= NULL
);
3490 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3492 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3493 uint8_t *blob
= top
+ data
;
3494 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3496 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3497 if (Swap(super
->index
[index
].type
) == CSSLOT_REQUIREMENTS
) {
3498 uint32_t begin
= Swap(super
->index
[index
].offset
);
3499 struct Blob
*requirement
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3500 fwrite(requirement
, 1, Swap(requirement
->length
), stdout
);
3505 _assert(signature
!= NULL
);
3507 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3509 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3510 uint8_t *blob
= top
+ data
;
3511 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3513 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3514 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
3515 uint32_t begin
= Swap(super
->index
[index
].offset
);
3516 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3518 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
3519 uint32_t pages
= Swap(directory
->nCodeSlots
);
3522 for (size_t i
= 0; i
!= pages
- 1; ++i
)
3523 LDID_SHA1(top
+ PageSize_
* i
, PageSize_
, hashes
[i
]);
3525 LDID_SHA1(top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1, hashes
[pages
- 1]);
3530 _assert(signature
!= NULL
);
3532 auto algorithms(GetAlgorithms());
3534 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3536 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3537 uint8_t *blob
= top
+ data
;
3538 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3541 CodeDirectory
*directory_
;
3543 Algorithm
&algorithm_
;
3547 std::map
<uint8_t, Candidate
> candidates
;
3549 for (size_t index(0); index
!= Swap(super
->count
); ++index
) {
3550 auto type(Swap(super
->index
[index
].type
));
3551 if ((type
== CSSLOT_CODEDIRECTORY
|| type
>= CSSLOT_ALTERNATE
) && type
!= CSSLOT_SIGNATURESLOT
) {
3552 uint32_t begin
= Swap(super
->index
[index
].offset
);
3553 uint32_t end
= index
+ 1 == Swap(super
->count
) ? Swap(super
->blob
.length
) : Swap(super
->index
[index
+ 1].offset
);
3554 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3555 auto type(directory
->hashType
);
3556 _assert(type
> 0 && type
<= algorithms
.size());
3557 auto &algorithm(*algorithms
[type
- 1]);
3558 uint8_t hash
[algorithm
.size_
];
3559 algorithm(hash
, blob
+ begin
, end
- begin
);
3560 candidates
.insert({type
, {directory
, end
- begin
, algorithm
, Hex(hash
, 20)}});
3564 _assert(!candidates
.empty());
3565 auto best(candidates
.end());
3568 const auto directory(best
->second
.directory_
);
3569 const auto flags(Swap(directory
->flags
));
3572 if (flags
& kSecCodeSignatureHost
)
3574 if (flags
& kSecCodeSignatureAdhoc
)
3576 if (flags
& kSecCodeSignatureForceHard
)
3578 if (flags
& kSecCodeSignatureForceKill
)
3580 if (flags
& kSecCodeSignatureForceExpiration
)
3581 names
+= ",expires";
3582 if (flags
& kSecCodeSignatureRestrict
)
3583 names
+= ",restrict";
3584 if (flags
& kSecCodeSignatureEnforcement
)
3585 names
+= ",enforcement";
3586 if (flags
& kSecCodeSignatureLibraryValidation
)
3587 names
+= ",library-validation";
3588 if (flags
& kSecCodeSignatureRuntime
)
3589 names
+= ",runtime";
3591 printf("CodeDirectory v=%x size=%zd flags=0x%x(%s) hashes=%d+%d location=embedded\n",
3592 Swap(directory
->version
), best
->second
.size_
, flags
, names
.empty() ? "none" : names
.c_str() + 1, Swap(directory
->nCodeSlots
), Swap(directory
->nSpecialSlots
));
3593 printf("Hash type=%s size=%d\n", best
->second
.algorithm_
.name(), directory
->hashSize
);
3595 std::string choices
;
3596 for (const auto &candidate
: candidates
) {
3597 auto choice(candidate
.second
.algorithm_
.name());
3600 printf("CandidateCDHash %s=%s\n", choice
, candidate
.second
.hash_
.c_str());
3602 printf("Hash choices=%s\n", choices
.c_str() + 1);
3604 printf("CDHash=%s\n", best
->second
.hash_
.c_str());
3609 } catch (const char *) {
3614 #ifndef LDID_NOSMINE
3615 # if OPENSSL_VERSION_MAJOR >= 3
3616 OSSL_PROVIDER_unload(legacy
);
3617 OSSL_PROVIDER_unload(deflt
);