1 /* ldid - (Mach-O) Link-Loader Identity Editor
2 * Copyright (C) 2007-2015 Jay Freeman (saurik)
5 /* SPDX-License-Identifier: AGPL-3.0-only */
6 /* GNU Affero General Public License, Version 3 {{{ */
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Affero General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Affero General Public License for more details.
18 * You should have received a copy of the GNU Affero General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
45 #include <sys/types.h>
47 #include <openssl/opensslv.h>
48 # if OPENSSL_VERSION_MAJOR >= 3
49 # include <openssl/provider.h>
51 #include <openssl/err.h>
52 #include <openssl/pem.h>
53 #include <openssl/pkcs7.h>
54 #include <openssl/pkcs12.h>
55 #include <openssl/ui.h>
57 #include <openssl/evp.h>
59 #include <plist/plist.h>
65 #define _assert___(line) \
67 #define _assert__(line) \
71 #define $(value) value
75 #define _assert_(expr, format, ...) \
77 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
78 throw $(__FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"); \
81 // XXX: this is not acceptable
82 #define _assert_(expr, format, ...) \
84 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
89 #define _assert(expr) \
90 _assert_(expr, "%s", $(#expr))
92 #define _syscall(expr, ...) [&] { for (;;) { \
94 if ((long) _value != -1) \
99 /* XXX: EINTR is included in this list to fix g++ */ \
100 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
101 if (error == success) \
102 return (decltype(expr)) -success; \
103 fprintf(stderr, "ldid: %s: %s\n", __func__, strerror(error)); \
108 fprintf(stderr, $("_trace(%s:%u): %s\n"), __FILE__, __LINE__, $(__FUNCTION__))
114 __attribute__((packed))
116 std::string password
;
117 std::vector
<std::string
> cleanup
;
119 template <typename Type_
>
121 typedef typename
Type_::const_iterator Result
;
124 #define _foreach(item, list) \
125 for (bool _stop(true); _stop; ) \
126 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
127 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
128 for (bool _suck(true); _suck; _suck = false) \
129 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
134 template <typename Function_
>
142 Scope(const Function_
&function
) :
152 template <typename Function_
>
153 Scope
<Function_
> _scope(const Function_
&function
) {
154 return Scope
<Function_
>(function
);
157 #define _scope__(counter, function) \
158 __attribute__((__unused__)) \
159 const _Scope &_scope ## counter(_scope([&]function))
160 #define _scope_(counter, function) \
161 _scope__(counter, function)
162 #define _scope(function) \
163 _scope_(__COUNTER__, function)
170 #define FAT_MAGIC 0xcafebabe
171 #define FAT_CIGAM 0xbebafeca
191 #define MH_MAGIC 0xfeedface
192 #define MH_CIGAM 0xcefaedfe
194 #define MH_MAGIC_64 0xfeedfacf
195 #define MH_CIGAM_64 0xcffaedfe
197 #define MH_DYLDLINK 0x4
199 #define MH_OBJECT 0x1
200 #define MH_EXECUTE 0x2
202 #define MH_DYLINKER 0x7
203 #define MH_BUNDLE 0x8
204 #define MH_DYLIB_STUB 0x9
206 struct load_command
{
211 #define LC_REQ_DYLD uint32_t(0x80000000)
213 #define LC_SEGMENT uint32_t(0x01)
214 #define LC_SYMTAB uint32_t(0x02)
215 #define LC_DYSYMTAB uint32_t(0x0b)
216 #define LC_LOAD_DYLIB uint32_t(0x0c)
217 #define LC_ID_DYLIB uint32_t(0x0d)
218 #define LC_SEGMENT_64 uint32_t(0x19)
219 #define LC_UUID uint32_t(0x1b)
220 #define LC_CODE_SIGNATURE uint32_t(0x1d)
221 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
222 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
223 #define LC_ENCRYPTION_INFO uint32_t(0x21)
224 #define LC_DYLD_INFO uint32_t(0x22)
225 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
226 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
241 uint32_t current_version
;
242 uint32_t compatibility_version
;
245 struct dylib_command
{
251 struct uuid_command
{
257 struct symtab_command
{
266 struct dyld_info_command
{
270 uint32_t rebase_size
;
273 uint32_t weak_bind_off
;
274 uint32_t weak_bind_size
;
275 uint32_t lazy_bind_off
;
276 uint32_t lazy_bind_size
;
278 uint32_t export_size
;
281 struct dysymtab_command
{
294 uint32_t extrefsymoff
;
295 uint32_t nextrefsyms
;
296 uint32_t indirectsymoff
;
297 uint32_t nindirectsyms
;
304 struct dylib_table_of_contents
{
305 uint32_t symbol_index
;
306 uint32_t module_index
;
309 struct dylib_module
{
310 uint32_t module_name
;
319 uint32_t iinit_iterm
;
320 uint32_t ninit_nterm
;
321 uint32_t objc_module_info_addr
;
322 uint32_t objc_module_info_size
;
325 struct dylib_reference
{
330 struct relocation_info
{
332 uint32_t r_symbolnum
:24;
351 struct segment_command
{
365 struct segment_command_64
{
408 struct linkedit_data_command
{
415 struct encryption_info_command
{
423 #define BIND_OPCODE_MASK 0xf0
424 #define BIND_IMMEDIATE_MASK 0x0f
425 #define BIND_OPCODE_DONE 0x00
426 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
427 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
428 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
429 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
430 #define BIND_OPCODE_SET_TYPE_IMM 0x50
431 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
432 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
433 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
434 #define BIND_OPCODE_DO_BIND 0x90
435 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
436 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
437 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
439 struct : ldid::Progress
{
440 virtual void operator()(const std::string
&value
) const {
443 virtual void operator()(double value
) const {
447 struct Progression
: ldid::Progress
{
448 const ldid::Progress
&progress_
;
451 Progression(const ldid::Progress
&progress
, const std::string
&name
) :
457 virtual void operator()(const std::string
&value
) const {
458 return progress_(name_
+ " (" + value
+ ")");
461 virtual void operator()(double value
) const {
462 return progress_(value
);
466 static std::streamsize
read(std::streambuf
&stream
, void *data
, size_t size
) {
467 auto writ(stream
.sgetn(static_cast<char *>(data
), size
));
472 static inline void put(std::streambuf
&stream
, uint8_t value
) {
473 _assert(stream
.sputc(value
) != EOF
);
476 static inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
477 _assert(read(stream
, data
, size
) == size
);
480 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
481 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
484 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
, const ldid::Progress
&progress
) {
486 for (size_t total(0); total
!= size
;) {
487 auto writ(std::min(size
- total
, size_t(4096 * 4)));
488 _assert(stream
.sputn(static_cast<const char *>(data
) + total
, writ
) == writ
);
490 progress(double(total
) / size
);
494 static inline void put(std::streambuf
&stream
, const std::string
&data
) {
495 return put(stream
, data
.data(), data
.size());
498 static size_t most(std::streambuf
&stream
, void *data
, size_t size
) {
501 if (auto writ
= read(stream
, data
, size
))
507 static inline void pad(std::streambuf
&stream
, size_t size
) {
509 memset(padding
, 0, size
);
510 put(stream
, padding
, size
);
513 template <typename Type_
>
514 Type_
Align(Type_ value
, size_t align
) {
521 static const uint8_t PageShift_(0x0c);
522 static const uint32_t PageSize_(1 << PageShift_
);
524 static inline unsigned bytes(uint64_t value
) {
525 return (64 - __builtin_clzll(value
) + 7) / 8;
528 static void put(std::streambuf
&stream
, uint64_t value
, size_t length
) {
530 do put(stream
, uint8_t(value
>> (length
-= 8)));
534 static void der(std::streambuf
&stream
, uint64_t value
) {
538 unsigned length(bytes(value
));
539 put(stream
, 0x80 | length
);
540 put(stream
, value
, length
);
544 static std::string
der(uint8_t tag
, const char *value
, size_t length
) {
548 put(data
, value
, length
);
552 static std::string
der(uint8_t tag
, const char *value
) {
553 return der(tag
, value
, strlen(value
)); }
554 static std::string
der(uint8_t tag
, const std::string
&value
) {
555 return der(tag
, value
.data(), value
.size()); }
557 template <typename Type_
>
558 static void der_(std::stringbuf
&data
, const Type_
&values
) {
560 for (const auto &value
: values
)
561 size
+= value
.size();
563 for (const auto &value
: values
)
567 static std::string
der(const std::vector
<std::string
> &values
) {
574 static std::string
der(const std::multiset
<std::string
> &values
) {
581 static std::string
der(const std::pair
<std::string
, std::string
> &value
) {
582 const auto key(der(0x0c, value
.first
));
585 der(data
, key
.size() + value
.second
.size());
587 put(data
, value
.second
);
591 static std::string
der(plist_t data
) {
592 switch (const auto type
= plist_get_node_type(data
)) {
593 case PLIST_BOOLEAN
: {
595 plist_get_bool_val(data
, &value
);
600 put(data
, value
!= 0 ? 1 : 0);
606 plist_get_uint_val(data
, &value
);
607 const auto length(bytes(value
));
612 put(data
, value
, length
);
617 fprintf(stderr
, "ldid: Invalid plist entry type\n");
622 fprintf(stderr
, "ldid: Invalid plist entry type\n");
629 plist_get_data_val(data
, &value
, &length
);
630 _scope({ free(value
); });
631 return der(0x04, value
, length
);
636 plist_get_string_val(data
, &value
);
637 _scope({ free(value
); });
638 return der(0x0c, value
);
642 std::vector
<std::string
> values
;
643 for (auto e(plist_array_get_size(data
)), i(decltype(e
)(0)); i
!= e
; ++i
)
644 values
.push_back(der(plist_array_get_item(data
, i
)));
649 std::multiset
<std::string
> values
;
651 plist_dict_iter
iterator(NULL
);
652 plist_dict_new_iter(data
, &iterator
);
653 _scope({ free(iterator
); });
658 plist_dict_next_item(data
, iterator
, &key
, &value
);
661 _scope({ free(key
); });
662 values
.insert(der(std::make_pair(key
, der(value
))));
669 fprintf(stderr
, "ldid: Unsupported plist type %d", type
);
675 static inline uint16_t Swap_(uint16_t value
) {
677 ((value
>> 8) & 0x00ff) |
678 ((value
<< 8) & 0xff00);
681 static inline uint32_t Swap_(uint32_t value
) {
682 value
= ((value
>> 8) & 0x00ff00ff) |
683 ((value
<< 8) & 0xff00ff00);
684 value
= ((value
>> 16) & 0x0000ffff) |
685 ((value
<< 16) & 0xffff0000);
689 static inline uint64_t Swap_(uint64_t value
) {
690 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
691 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
692 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
696 static inline int16_t Swap_(int16_t value
) {
697 return Swap_(static_cast<uint16_t>(value
));
700 static inline int32_t Swap_(int32_t value
) {
701 return Swap_(static_cast<uint32_t>(value
));
704 static inline int64_t Swap_(int64_t value
) {
705 return Swap_(static_cast<uint64_t>(value
));
708 static bool little_(true);
710 static inline uint16_t Swap(uint16_t value
) {
711 return little_
? Swap_(value
) : value
;
714 static inline uint32_t Swap(uint32_t value
) {
715 return little_
? Swap_(value
) : value
;
718 static inline uint64_t Swap(uint64_t value
) {
719 return little_
? Swap_(value
) : value
;
722 static inline int16_t Swap(int16_t value
) {
723 return Swap(static_cast<uint16_t>(value
));
726 static inline int32_t Swap(int32_t value
) {
727 return Swap(static_cast<uint32_t>(value
));
730 static inline int64_t Swap(int64_t value
) {
731 return Swap(static_cast<uint64_t>(value
));
744 Swapped(bool swapped
) :
749 template <typename Type_
>
750 Type_
Swap(Type_ value
) const {
751 return swapped_
? Swap_(value
) : value
;
763 Data(void *base
, size_t size
) :
769 void *GetBase() const {
773 size_t GetSize() const {
784 struct mach_header
*mach_header_
;
785 struct load_command
*load_command_
;
788 MachHeader(void *base
, size_t size
) :
791 mach_header_
= (mach_header
*) base
;
793 switch (Swap(mach_header_
->magic
)) {
795 swapped_
= !swapped_
;
801 swapped_
= !swapped_
;
807 fprintf(stderr
, "ldid: Unknown header magic\nAre you sure that is a Mach-O?\n");
811 void *post
= mach_header_
+ 1;
813 post
= (uint32_t *) post
+ 1;
814 load_command_
= (struct load_command
*) post
;
816 if (Swap(mach_header_
->filetype
) != MH_EXECUTE
&&
817 Swap(mach_header_
->filetype
) != MH_DYLIB
&&
818 Swap(mach_header_
->filetype
) != MH_DYLINKER
&&
819 Swap(mach_header_
->filetype
) != MH_BUNDLE
) {
820 fprintf(stderr
, "ldid: Unsupported Mach-O type\n");
825 bool Bits64() const {
829 struct mach_header
*operator ->() const {
833 operator struct mach_header
*() const {
837 uint32_t GetCPUType() const {
838 return Swap(mach_header_
->cputype
);
841 uint32_t GetCPUSubtype() const {
842 return Swap(mach_header_
->cpusubtype
) & 0xff;
845 struct load_command
*GetLoadCommand() const {
846 return load_command_
;
849 std::vector
<struct load_command
*> GetLoadCommands() const {
850 std::vector
<struct load_command
*> load_commands
;
852 struct load_command
*load_command
= load_command_
;
853 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
854 load_commands
.push_back(load_command
);
855 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
858 return load_commands
;
861 void ForSection(const ldid::Functor
<void (const char *, const char *, void *, size_t)> &code
) const {
862 _foreach (load_command
, GetLoadCommands())
863 switch (Swap(load_command
->cmd
)) {
865 auto segment(reinterpret_cast<struct segment_command
*>(load_command
));
866 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
867 auto section(reinterpret_cast<struct section
*>(segment
+ 1));
868 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
869 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
872 case LC_SEGMENT_64
: {
873 auto segment(reinterpret_cast<struct segment_command_64
*>(load_command
));
874 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
875 auto section(reinterpret_cast<struct section_64
*>(segment
+ 1));
876 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
877 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
882 template <typename Target_
>
883 Target_
*GetOffset(uint32_t offset
) const {
884 return reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
);
888 class FatMachHeader
:
895 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
896 MachHeader(base
, size
),
901 fat_arch
*GetFatArch() const {
910 fat_header
*fat_header_
;
911 std::vector
<FatMachHeader
> mach_headers_
;
914 FatHeader(void *base
, size_t size
) :
917 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
919 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
920 swapped_
= !swapped_
;
922 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
924 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
926 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
927 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
929 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
930 uint32_t arch_offset
= Swap(fat_arch
->offset
);
931 uint32_t arch_size
= Swap(fat_arch
->size
);
932 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
938 std::vector
<FatMachHeader
> &GetMachHeaders() {
939 return mach_headers_
;
943 return fat_header_
!= NULL
;
946 struct fat_header
*operator ->() const {
950 operator struct fat_header
*() const {
955 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
956 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
957 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
958 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
959 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
960 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
961 #define CSMAGIC_EMBEDDED_DERFORMAT uint32_t(0xfade7172) // name?
962 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
963 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
965 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
966 #define CSSLOT_INFOSLOT uint32_t(0x00001)
967 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
968 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
969 #define CSSLOT_APPLICATION uint32_t(0x00004)
970 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
971 #define CSSLOT_REPSPECIFIC uint32_t(0x00006) // name?
972 #define CSSLOT_DERFORMAT uint32_t(0x00007) // name?
973 #define CSSLOT_ALTERNATE uint32_t(0x01000)
975 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
977 #define CS_HASHTYPE_SHA160_160 1
978 #define CS_HASHTYPE_SHA256_256 2
979 #define CS_HASHTYPE_SHA256_160 3
980 #define CS_HASHTYPE_SHA386_386 4
983 #define CS_EXECSEG_MAIN_BINARY 0x001 /* executable segment denotes main binary */
984 #define CS_EXECSEG_ALLOW_UNSIGNED 0x010 /* allow unsigned pages (for debugging) */
985 #define CS_EXECSEG_DEBUGGER 0x020 /* main binary is debugger */
986 #define CS_EXECSEG_JIT 0x040 /* JIT enabled */
987 #define CS_EXECSEG_SKIP_LV 0x080 /* skip library validation */
988 #define CS_EXECSEG_CAN_LOAD_CDHASH 0x100 /* can bless cdhash for execution */
989 #define CS_EXECSEG_CAN_EXEC_CDHASH 0x200 /* can execute blessed cdhash */
991 enum SecCodeExecSegFlags
{
992 kSecCodeExecSegMainBinary
= 0x001,
993 kSecCodeExecSegAllowUnsigned
= 0x010,
994 kSecCodeExecSegDebugger
= 0x020,
995 kSecCodeExecSegJit
= 0x040,
996 kSecCodeExecSegSkipLibraryVal
= 0x080,
997 kSecCodeExecSegCanLoadCdHash
= 0x100,
998 kSecCodeExecSegCanExecCdHash
= 0x100,
1015 struct BlobIndex index
[];
1018 struct CodeDirectory
{
1021 uint32_t hashOffset
;
1022 uint32_t identOffset
;
1023 uint32_t nSpecialSlots
;
1024 uint32_t nCodeSlots
;
1031 uint32_t scatterOffset
;
1032 uint32_t teamIDOffset
;
1034 uint64_t codeLimit64
;
1035 uint64_t execSegBase
;
1036 uint64_t execSegLimit
;
1037 uint64_t execSegFlags
;
1038 #if 0 // version = 0x20500
1040 uint32_t preEncryptOffset
;
1042 #if 0 // version = 0x20600
1043 uint8_t linkageHashType
;
1044 uint8_t linkageTruncated
;
1046 uint32_t linkageOffset
;
1047 uint32_t linkageSize
;
1051 enum CodeSignatureFlags
{
1052 kSecCodeSignatureHost
= 0x0001,
1053 kSecCodeSignatureAdhoc
= 0x0002,
1054 kSecCodeSignatureForceHard
= 0x0100,
1055 kSecCodeSignatureForceKill
= 0x0200,
1056 kSecCodeSignatureForceExpiration
= 0x0400,
1057 kSecCodeSignatureRestrict
= 0x0800,
1058 kSecCodeSignatureEnforcement
= 0x1000,
1059 kSecCodeSignatureLibraryValidation
= 0x2000,
1060 kSecCodeSignatureRuntime
= 0x10000,
1063 enum Kind
: uint32_t {
1064 exprForm
= 1, // prefix expr form
1067 enum ExprOp
: uint32_t {
1068 opFalse
, // unconditionally false
1069 opTrue
, // unconditionally true
1070 opIdent
, // match canonical code [string]
1071 opAppleAnchor
, // signed by Apple as Apple's product
1072 opAnchorHash
, // match anchor [cert hash]
1073 opInfoKeyValue
, // *legacy* - use opInfoKeyField [key; value]
1074 opAnd
, // binary prefix expr AND expr [expr; expr]
1075 opOr
, // binary prefix expr OR expr [expr; expr]
1076 opCDHash
, // match hash of CodeDirectory directly [cd hash]
1077 opNot
, // logical inverse [expr]
1078 opInfoKeyField
, // Info.plist key field [string; match suffix]
1079 opCertField
, // Certificate field [cert index; field name; match suffix]
1080 opTrustedCert
, // require trust settings to approve one particular cert [cert index]
1081 opTrustedCerts
, // require trust settings to approve the cert chain
1082 opCertGeneric
, // Certificate component by OID [cert index; oid; match suffix]
1083 opAppleGenericAnchor
, // signed by Apple in any capacity
1084 opEntitlementField
, // entitlement dictionary field [string; match suffix]
1085 opCertPolicy
, // Certificate policy by OID [cert index; oid; match suffix]
1086 opNamedAnchor
, // named anchor type
1087 opNamedCode
, // named subroutine
1088 opPlatform
, // platform constraint [integer]
1089 exprOpCount
// (total opcode count in use)
1092 enum MatchOperation
{
1093 matchExists
, // anything but explicit "false" - no value stored
1094 matchEqual
, // equal (CFEqual)
1095 matchContains
, // partial match (substring)
1096 matchBeginsWith
, // partial match (initial substring)
1097 matchEndsWith
, // partial match (terminal substring)
1098 matchLessThan
, // less than (string with numeric comparison)
1099 matchGreaterThan
, // greater than (string with numeric comparison)
1100 matchLessEqual
, // less or equal (string with numeric comparison)
1101 matchGreaterEqual
, // greater or equal (string with numeric comparison)
1104 #define OID_ISO_MEMBER 42
1105 #define OID_US OID_ISO_MEMBER, 134, 72
1106 #define APPLE_OID OID_US, 0x86, 0xf7, 0x63
1107 #define APPLE_ADS_OID APPLE_OID, 0x64
1108 #define APPLE_EXTENSION_OID APPLE_ADS_OID, 6
1115 Algorithm(size_t size
, uint8_t type
) :
1121 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const = 0;
1123 virtual void operator ()(uint8_t *hash
, const void *data
, size_t size
) const = 0;
1124 virtual void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const = 0;
1125 virtual void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const = 0;
1127 virtual const char *name() = 0;
1130 struct AlgorithmSHA1
:
1134 Algorithm(SHA_DIGEST_LENGTH
, CS_HASHTYPE_SHA160_160
)
1138 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1142 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1143 SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
1146 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1147 return operator()(hash
.sha1_
, data
, size
);
1150 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1151 hash
.resize(SHA_DIGEST_LENGTH
);
1152 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1155 virtual const char *name() {
1160 struct AlgorithmSHA256
:
1164 Algorithm(SHA256_DIGEST_LENGTH
, CS_HASHTYPE_SHA256_256
)
1168 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1169 return hash
.sha256_
;
1172 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1173 SHA256(static_cast<const uint8_t *>(data
), size
, hash
);
1176 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1177 return operator()(hash
.sha256_
, data
, size
);
1180 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1181 hash
.resize(SHA256_DIGEST_LENGTH
);
1182 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1185 virtual const char *name() {
1190 static bool do_sha1(true);
1191 static bool do_sha256(true);
1193 static const std::vector
<Algorithm
*> &GetAlgorithms() {
1194 static AlgorithmSHA1 sha1
;
1195 static AlgorithmSHA256 sha256
;
1197 static std::vector
<Algorithm
*> algorithms
;
1198 if (algorithms
.empty()) {
1200 algorithms
.push_back(&sha1
);
1202 algorithms
.push_back(&sha256
);
1209 std::string entitlements_
;
1210 std::string derformat_
;
1213 struct CodesignAllocation
{
1214 FatMachHeader mach_header_
;
1223 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
) :
1224 mach_header_(mach_header
),
1236 #ifndef LDID_NOTOOLS
1249 _syscall(close(file_
));
1252 void open(const char *path
, int flags
) {
1253 file_
= ::open(path
, flags
);
1255 fprintf(stderr
, "ldid: %s: %s\n", path
, strerror(errno
));
1278 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
1281 open(path
, oflag
, pflag
, mflag
);
1284 Map(const std::string
&path
, bool edit
) :
1294 bool empty() const {
1295 return data_
== NULL
;
1298 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
1301 file_
.open(path
.c_str(), oflag
);
1302 int file(file_
.file());
1305 _syscall(fstat(file
, &stat
));
1306 size_
= stat
.st_size
;
1308 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
1311 void open(const std::string
&path
, bool edit
) {
1313 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
1315 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1321 _syscall(munmap(data_
, size_
));
1326 void *data() const {
1330 size_t size() const {
1334 operator std::string() const {
1335 return std::string(static_cast<char *>(data_
), size_
);
1338 #endif // LDID_NOTOOLS
1342 static plist_t
plist(const std::string
&data
);
1344 void Analyze(const MachHeader
&mach_header
, const Functor
<void (const char *data
, size_t size
)> &entitle
) {
1345 _foreach (load_command
, mach_header
.GetLoadCommands())
1346 if (mach_header
.Swap(load_command
->cmd
) == LC_CODE_SIGNATURE
) {
1347 auto signature(reinterpret_cast<struct linkedit_data_command
*>(load_command
));
1348 auto offset(mach_header
.Swap(signature
->dataoff
));
1349 auto pointer(reinterpret_cast<uint8_t *>(mach_header
.GetBase()) + offset
);
1350 auto super(reinterpret_cast<struct SuperBlob
*>(pointer
));
1352 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1353 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1354 auto begin(Swap(super
->index
[index
].offset
));
1355 auto blob(reinterpret_cast<struct Blob
*>(pointer
+ begin
));
1356 auto writ(Swap(blob
->length
) - sizeof(*blob
));
1357 entitle(reinterpret_cast<char *>(blob
+ 1), writ
);
1362 std::string
Analyze(const void *data
, size_t size
) {
1363 std::string entitlements
;
1365 FatHeader
fat_header(const_cast<void *>(data
), size
);
1366 _foreach (mach_header
, fat_header
.GetMachHeaders())
1367 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
1368 if (entitlements
.empty())
1369 entitlements
.assign(data
, size
);
1371 if (entitlements
.compare(0, entitlements
.size(), data
, size
) != 0) {
1372 fprintf(stderr
, "ldid: Entitlements do not match\n");
1377 return entitlements
;
1380 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
) {
1381 FatHeader
source(const_cast<void *>(idata
), isize
);
1385 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
1387 std::vector
<CodesignAllocation
> allocations
;
1388 _foreach (mach_header
, source
.GetMachHeaders()) {
1389 struct linkedit_data_command
*signature(NULL
);
1390 struct symtab_command
*symtab(NULL
);
1392 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1393 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1394 if (cmd
== LC_CODE_SIGNATURE
)
1395 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1396 else if (cmd
== LC_SYMTAB
)
1397 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
1401 if (signature
== NULL
)
1402 size
= mach_header
.GetSize();
1404 size
= mach_header
.Swap(signature
->dataoff
);
1405 _assert(size
<= mach_header
.GetSize());
1408 if (symtab
!= NULL
) {
1409 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
1410 if (symtab
->stroff
!= 0 || symtab
->strsize
!= 0) {
1411 _assert(end
<= size
);
1412 _assert(end
>= size
- 0x10);
1418 size_t alloc(allocate(mach_header
, baton
, size
));
1420 auto *fat_arch(mach_header
.GetFatArch());
1423 if (fat_arch
!= NULL
)
1424 align
= source
.Swap(fat_arch
->align
);
1425 else switch (mach_header
.GetCPUType()) {
1426 case CPU_TYPE_POWERPC
:
1427 case CPU_TYPE_POWERPC64
:
1429 case CPU_TYPE_X86_64
:
1433 case CPU_TYPE_ARM64
:
1434 case CPU_TYPE_ARM64_32
:
1442 const char *arch(NULL
);
1443 switch (mach_header
.GetCPUType()) {
1444 case CPU_TYPE_POWERPC
:
1447 case CPU_TYPE_POWERPC64
:
1453 case CPU_TYPE_X86_64
:
1459 case CPU_TYPE_ARM64
:
1462 case CPU_TYPE_ARM64_32
:
1467 offset
= Align(offset
, 1 << align
);
1469 uint32_t limit(size
);
1471 limit
= Align(limit
, 0x10);
1473 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
, arch
, baton
));
1474 offset
+= size
+ alloc
;
1475 offset
= Align(offset
, 0x10);
1480 if (source
.IsFat()) {
1481 fat_header fat_header
;
1482 fat_header
.magic
= Swap(FAT_MAGIC
);
1483 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1484 put(output
, &fat_header
, sizeof(fat_header
));
1485 position
+= sizeof(fat_header
);
1487 // XXX: support fat_arch_64 (not in my toolchain)
1488 // probably use C++14 generic lambda (not in my toolchain)
1491 _foreach (allocation
, allocations
) {
1492 const auto offset(allocation
.offset_
);
1493 const auto size(allocation
.limit_
+ allocation
.alloc_
);
1494 if (uint32_t(offset
) != offset
|| uint32_t(size
) != size
)
1498 }(), "FAT slice >=4GiB not currently supported");
1500 _foreach (allocation
, allocations
) {
1501 auto &mach_header(allocation
.mach_header_
);
1504 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1505 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1506 fat_arch
.offset
= Swap(uint32_t(allocation
.offset_
));
1507 fat_arch
.size
= Swap(uint32_t(allocation
.limit_
+ allocation
.alloc_
));
1508 fat_arch
.align
= Swap(allocation
.align_
);
1509 put(output
, &fat_arch
, sizeof(fat_arch
));
1510 position
+= sizeof(fat_arch
);
1514 _foreach (allocation
, allocations
) {
1515 progress(allocation
.arch_
);
1516 auto &mach_header(allocation
.mach_header_
);
1518 pad(output
, allocation
.offset_
- position
);
1519 position
= allocation
.offset_
;
1524 std::vector
<std::string
> commands
;
1526 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1527 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1529 switch (mach_header
.Swap(load_command
->cmd
)) {
1530 case LC_CODE_SIGNATURE
:
1534 // XXX: this is getting ridiculous: provide a better abstraction
1537 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1539 if ((segment_command
->initprot
& 04) != 0) {
1540 auto begin(mach_header
.Swap(segment_command
->fileoff
));
1541 auto end(begin
+ mach_header
.Swap(segment_command
->filesize
));
1548 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) == 0) {
1549 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1550 segment_command
->filesize
= size
;
1551 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1555 case LC_SEGMENT_64
: {
1556 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1558 if ((segment_command
->initprot
& 04) != 0) {
1559 auto begin(mach_header
.Swap(segment_command
->fileoff
));
1560 auto end(begin
+ mach_header
.Swap(segment_command
->filesize
));
1567 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) == 0) {
1568 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1569 segment_command
->filesize
= size
;
1570 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1575 commands
.push_back(copy
);
1578 if (allocation
.alloc_
!= 0) {
1579 linkedit_data_command signature
;
1580 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1581 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1582 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1583 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1584 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1587 size_t begin(position
);
1590 _foreach(command
, commands
)
1591 after
+= command
.size();
1593 std::stringbuf altern
;
1595 struct mach_header
header(*mach_header
);
1596 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1597 header
.sizeofcmds
= mach_header
.Swap(after
);
1598 put(output
, &header
, sizeof(header
));
1599 put(altern
, &header
, sizeof(header
));
1600 position
+= sizeof(header
);
1602 if (mach_header
.Bits64()) {
1603 auto pad(mach_header
.Swap(uint32_t(0)));
1604 put(output
, &pad
, sizeof(pad
));
1605 put(altern
, &pad
, sizeof(pad
));
1606 position
+= sizeof(pad
);
1609 _foreach(command
, commands
) {
1610 put(output
, command
.data(), command
.size());
1611 put(altern
, command
.data(), command
.size());
1612 position
+= command
.size();
1615 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1616 if (before
> after
) {
1617 pad(output
, before
- after
);
1618 pad(altern
, before
- after
);
1619 position
+= before
- after
;
1622 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1624 std::string
overlap(altern
.str());
1625 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1627 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
), progress
);
1628 position
= begin
+ allocation
.size_
;
1630 pad(output
, allocation
.limit_
- allocation
.size_
);
1631 position
+= allocation
.limit_
- allocation
.size_
;
1633 size_t saved(save(mach_header
, allocation
.baton_
, output
, allocation
.limit_
, left
, right
, overlap
, top
, progress
));
1634 if (allocation
.alloc_
> saved
)
1635 pad(output
, allocation
.alloc_
- saved
);
1637 _assert(allocation
.alloc_
== saved
);
1638 position
+= allocation
.alloc_
;
1644 typedef std::map
<uint32_t, std::string
> Blobs
;
1646 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1647 auto value(buffer
.str());
1648 std::swap(blobs
[slot
], value
);
1651 static const std::string
&insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1652 auto value(buffer
.str());
1654 blob
.magic
= Swap(magic
);
1655 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1656 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1657 auto &save(blobs
[slot
]);
1658 std::swap(save
, value
);
1662 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1664 _foreach (blob
, blobs
)
1665 total
+= blob
.second
.size();
1667 struct SuperBlob super
;
1668 super
.blob
.magic
= Swap(magic
);
1669 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1670 super
.count
= Swap(uint32_t(blobs
.size()));
1671 put(output
, &super
, sizeof(super
));
1673 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1675 _foreach (blob
, blobs
) {
1677 index
.type
= Swap(blob
.first
);
1678 index
.offset
= Swap(uint32_t(offset
));
1679 put(output
, &index
, sizeof(index
));
1680 offset
+= blob
.second
.size();
1683 _foreach (blob
, blobs
)
1684 put(output
, blob
.second
.data(), blob
.second
.size());
1697 _assert(bio_
!= NULL
);
1701 bio_(BIO_new(BIO_s_mem()))
1705 Buffer(const char *data
, size_t size
) :
1706 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1710 Buffer(const std::string
&data
) :
1711 Buffer(data
.data(), data
.size())
1715 Buffer(PKCS7
*pkcs
) :
1718 if (i2d_PKCS7_bio(bio_
, pkcs
) == 0){
1719 fprintf(stderr
, "ldid: An error occured while getting the PKCS12 file: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1728 operator BIO
*() const {
1732 explicit operator std::string() const {
1734 auto size(BIO_get_mem_data(bio_
, &data
));
1735 return std::string(data
, size
);
1744 STACK_OF(X509
) *ca_
;
1748 value_(d2i_PKCS12_bio(bio
, NULL
)),
1751 if (value_
== NULL
){
1752 fprintf(stderr
, "ldid: An error occured while getting the PKCS12 file: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1756 if (!PKCS12_verify_mac(value_
, "", 0) && password
.empty()) {
1758 UI_UTIL_read_pw_string(passbuf
, 2048, "Enter password: ", 0);
1762 if (PKCS12_parse(value_
, password
.c_str(), &key_
, &cert_
, &ca_
) <= 0){
1763 fprintf(stderr
, "ldid: An error occured while parsing: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1766 if (key_
== NULL
|| cert_
== NULL
){
1767 fprintf(stderr
, "ldid: An error occured while parsing: %s\nYour p12 cert might not be valid\n", ERR_error_string(ERR_get_error(), NULL
));
1772 ca_
= sk_X509_new_null();
1774 fprintf(stderr
, "ldid: An error occured while parsing: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1779 Stuff(const std::string
&data
) :
1785 sk_X509_pop_free(ca_
, X509_free
);
1787 EVP_PKEY_free(key_
);
1788 PKCS12_free(value_
);
1791 operator PKCS12
*() const {
1795 operator EVP_PKEY
*() const {
1799 operator X509
*() const {
1803 operator STACK_OF(X509
) *() const {
1809 struct SEQUENCE_hash_sha1
{
1810 uint8_t SEQUENCE
[2] = {0x30, 0x1d}; // size
1811 uint8_t OBJECT_IDENTIFIER
[7] = {0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A}; // OBJECT IDENTIFIER 1.3.14.3.2.26 sha1 (OIW)
1812 uint8_t hash_size
[2] = {0x04, 0x14};
1816 struct SEQUENCE_hash_sha256
{
1817 uint8_t SEQUENCE
[2] = {0x30, 0x2d}; // size
1818 uint8_t OBJECT_IDENTIFIER
[11] = {0x06 ,0x09 ,0x60, 0x86, 0x48, 0x01 ,0x65, 0x03, 0x04, 0x02, 0x01}; // 2.16.840.1.101.3.4.2.1 sha-256 (NIST Algorithm)
1819 uint8_t hash_size
[2] = {0x04, 0x20}; // hash size
1828 Signature(const Stuff
&stuff
, const Buffer
&data
, const std::string
&xml
, const std::vector
<char>& alternateCDSHA1
, const std::vector
<char>& alternateCDSHA256
) {
1829 value_
= PKCS7_new();
1830 if (value_
== NULL
){
1831 fprintf(stderr
, "ldid: An error occured while getting creating PKCS7 file: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1835 if (PKCS7_set_type(value_
, NID_pkcs7_signed
) == 0 ||
1836 PKCS7_content_new(value_
, NID_pkcs7_data
) == 0) {
1837 fprintf(stderr
, "ldid: An error occured while getting creating PKCS7 file: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1841 STACK_OF(X509
) *certs(stuff
);
1842 for (unsigned i(0), e(sk_X509_num(certs
)); i
!= e
; i
++) {
1843 if (PKCS7_add_certificate(value_
, sk_X509_value(certs
, e
- i
- 1)) == 0) {
1844 fprintf(stderr
, "ldid: An error occured while signing: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1849 auto info(PKCS7_sign_add_signer(value_
, stuff
, stuff
, NULL
, PKCS7_NOSMIMECAP
));
1851 fprintf(stderr
, "ldid: An error occured while signing: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1855 X509_ATTRIBUTE
*attribute
= X509_ATTRIBUTE_new();
1856 ASN1_OBJECT
*obj2
= OBJ_txt2obj("1.2.840.113635.100.9.2", 1);
1857 X509_ATTRIBUTE_set1_object(attribute
, obj2
);
1859 SEQUENCE_hash_sha1 seq1
;
1860 memcpy((void *)seq1
.hash
,(void *)alternateCDSHA1
.data() ,alternateCDSHA1
.size());
1861 X509_ATTRIBUTE_set1_data(attribute
, V_ASN1_SEQUENCE
,&seq1
, sizeof(seq1
));
1863 SEQUENCE_hash_sha256 seq256
;
1864 memcpy((void *)seq256
.hash
,(void *)alternateCDSHA256
.data() ,alternateCDSHA256
.size());
1865 X509_ATTRIBUTE_set1_data(attribute
, V_ASN1_SEQUENCE
,&seq256
, sizeof(seq256
));
1867 STACK_OF(X509_ATTRIBUTE
) *sk
= PKCS7_get_signed_attributes(info
);
1868 if (!sk_X509_ATTRIBUTE_push(sk
, attribute
)) {
1869 fprintf(stderr
, "ldid: sk_X509_ATTRIBUTE_push failed: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1873 PKCS7_set_detached(value_
, 1);
1875 ASN1_OCTET_STRING
*string(ASN1_OCTET_STRING_new());
1876 if (string
== NULL
) {
1877 fprintf(stderr
, "ldid: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1882 if (ASN1_STRING_set(string
, xml
.data(), xml
.size()) == 0) {
1883 fprintf(stderr
, "ldid: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1887 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "", ""));
1888 if (PKCS7_add_signed_attribute(info
, nid
, V_ASN1_OCTET_STRING
, string
) == 0) {
1889 fprintf(stderr
, "ldid: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1893 ASN1_OCTET_STRING_free(string
);
1897 if (PKCS7_final(value_
, data
, PKCS7_BINARY
) == 0) {
1898 fprintf(stderr
, "ldid: Failed to sign: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1907 operator PKCS7
*() const {
1913 public std::streambuf
1916 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1920 virtual int_type
overflow(int_type next
) {
1926 public std::streambuf
1932 EVP_MD_CTX
*sha256_
;
1935 HashBuffer(ldid::Hash
&hash
) :
1938 sha1_
= EVP_MD_CTX_new();
1939 sha256_
= EVP_MD_CTX_new();
1941 EVP_DigestInit_ex(sha1_
, EVP_get_digestbyname("sha1"), nullptr);
1942 EVP_DigestInit_ex(sha256_
, EVP_get_digestbyname("sha256"), nullptr);
1946 EVP_DigestFinal_ex(sha1_
, reinterpret_cast<uint8_t *>(hash_
.sha1_
), nullptr);
1947 EVP_DigestFinal_ex(sha256_
, reinterpret_cast<uint8_t *>(hash_
.sha256_
), nullptr);
1949 EVP_MD_CTX_free(sha1_
);
1950 EVP_MD_CTX_free(sha256_
);
1953 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1954 EVP_DigestUpdate(sha1_
, data
, size
);
1955 EVP_DigestUpdate(sha256_
, data
, size
);
1959 virtual int_type
overflow(int_type next
) {
1960 if (next
== traits_type::eof())
1972 std::streambuf
&buffer_
;
1975 HashProxy(ldid::Hash
&hash
, std::streambuf
&buffer
) :
1981 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1982 _assert(HashBuffer::xsputn(data
, size
) == size
);
1983 return buffer_
.sputn(data
, size
);
1987 #ifndef LDID_NOTOOLS
1988 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1989 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1997 Split(const std::string
&path
) {
1998 size_t slash(path
.rfind('/'));
1999 if (slash
== std::string::npos
)
2002 dir
= path
.substr(0, slash
+ 1);
2003 base
= path
.substr(slash
+ 1);
2008 static void mkdir_p(const std::string
&path
) {
2012 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
2015 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
2018 auto slash(path
.rfind('/', path
.size() - 1));
2019 if (slash
== std::string::npos
)
2021 mkdir_p(path
.substr(0, slash
));
2024 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
2025 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
2027 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
2028 cleanup
.push_back(temp
);
2032 static void Commit(const std::string
&path
, const std::string
&temp
) {
2034 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
2036 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
2038 _syscall(chmod(temp
.c_str(), info
.st_mode
));
2041 _syscall(rename(temp
.c_str(), path
.c_str()));
2042 cleanup
.erase(std::remove(cleanup
.begin(), cleanup
.end(), temp
), cleanup
.end());
2044 #endif // LDID_NOTOOLS
2048 static void get(std::string
&value
, X509_NAME
*name
, int nid
) {
2049 auto index(X509_NAME_get_index_by_NID(name
, nid
, -1));
2051 fprintf(stderr
, "ldid: An error occursed while parsing the certificate: %s\n", ERR_error_string(ERR_get_error(), NULL
));
2054 auto next(X509_NAME_get_index_by_NID(name
, nid
, index
));
2056 fprintf(stderr
, "ldid: An error occursed while parsing the certificate: %s\n", ERR_error_string(ERR_get_error(), NULL
));
2059 auto entry(X509_NAME_get_entry(name
, index
));
2060 if (entry
== NULL
) {
2061 fprintf(stderr
, "ldid: An error occursed while parsing the certificate: %s\n", ERR_error_string(ERR_get_error(), NULL
));
2064 auto asn(X509_NAME_ENTRY_get_data(entry
));
2066 fprintf(stderr
, "ldid: An error occursed while parsing the certificate: %s\n", ERR_error_string(ERR_get_error(), NULL
));
2069 value
.assign(reinterpret_cast<const char *>(ASN1_STRING_get0_data(asn
)), ASN1_STRING_length(asn
));
2072 static void req(std::streambuf
&buffer
, uint32_t value
) {
2073 value
= Swap(value
);
2074 put(buffer
, &value
, sizeof(value
));
2077 static void req(std::streambuf
&buffer
, const std::string
&value
) {
2078 req(buffer
, value
.size());
2079 put(buffer
, value
.data(), value
.size());
2080 static uint8_t zeros
[] = {0,0,0,0};
2081 put(buffer
, zeros
, 3 - (value
.size() + 3) % 4);
2084 template <size_t Size_
>
2085 static void req(std::streambuf
&buffer
, uint8_t (&&data
)[Size_
]) {
2087 put(buffer
, data
, Size_
);
2088 static uint8_t zeros
[] = {0,0,0,0};
2089 put(buffer
, zeros
, 3 - (Size_
+ 3) % 4);
2092 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
) {
2101 auto name(X509_get_subject_name(stuff
));
2103 fprintf(stderr
, "ldid: Your certificate might not be valid: %s\n", ERR_error_string(ERR_get_error(), NULL
));
2106 get(team
, name
, NID_organizationalUnitName
);
2107 get(common
, name
, NID_commonName
);
2111 std::stringbuf backing
;
2113 if (!requirements
.empty()) {
2114 put(backing
, requirements
.data(), requirements
.size());
2118 std::stringbuf requirement
;
2119 req(requirement
, exprForm
);
2120 req(requirement
, opAnd
);
2121 req(requirement
, opIdent
);
2122 req(requirement
, identifier
);
2123 req(requirement
, opAnd
);
2124 req(requirement
, opAppleGenericAnchor
);
2125 req(requirement
, opAnd
);
2126 req(requirement
, opCertField
);
2127 req(requirement
, 0);
2128 req(requirement
, "subject.CN");
2129 req(requirement
, matchEqual
);
2130 req(requirement
, common
);
2131 req(requirement
, opCertGeneric
);
2132 req(requirement
, 1);
2133 req(requirement
, (uint8_t []) {APPLE_EXTENSION_OID
, 2, 1});
2134 req(requirement
, matchExists
);
2135 insert(blobs
, 3, CSMAGIC_REQUIREMENT
, requirement
);
2137 put(backing
, CSMAGIC_REQUIREMENTS
, blobs
);
2141 // XXX: this is just a "sufficiently large number"
2142 size_t certificate(0x3000);
2144 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2145 size_t alloc(sizeof(struct SuperBlob
));
2147 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
2149 uint32_t special(0);
2151 _foreach (slot
, slots
)
2152 special
= std::max(special
, slot
.first
);
2154 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2155 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
2156 special
= std::max(special
, CSSLOT_INFOSLOT
);
2159 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
2160 alloc
+= sizeof(struct BlobIndex
);
2161 alloc
+= backing
.str().size();
2164 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
2165 baton
.entitlements_
.assign(data
, size
);
2168 if (!baton
.entitlements_
.empty() || !entitlements
.empty()) {
2169 auto combined(plist(baton
.entitlements_
));
2170 _scope({ plist_free(combined
); });
2171 if (plist_get_node_type(combined
) != PLIST_DICT
) {
2172 fprintf(stderr
, "ldid: Existing entitlements are in wrong format\n");
2176 auto merging(plist(entitlements
));
2177 _scope({ plist_free(merging
); });
2178 if (plist_get_node_type(merging
) != PLIST_DICT
) {
2179 fprintf(stderr
, "ldid: Entitlements need a root key of dict\n");
2183 plist_dict_iter
iterator(NULL
);
2184 plist_dict_new_iter(merging
, &iterator
);
2185 _scope({ free(iterator
); });
2189 plist_t
value(NULL
);
2190 plist_dict_next_item(merging
, iterator
, &key
, &value
);
2193 _scope({ free(key
); });
2194 plist_dict_set_item(combined
, key
, plist_copy(value
));
2197 baton
.derformat_
= der(combined
);
2201 plist_to_xml(combined
, &xml
, &size
);
2202 _scope({ free(xml
); });
2204 baton
.entitlements_
.assign(xml
, size
);
2207 if (!baton
.entitlements_
.empty()) {
2208 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
2209 alloc
+= sizeof(struct BlobIndex
);
2210 alloc
+= sizeof(struct Blob
);
2211 alloc
+= baton
.entitlements_
.size();
2214 if (!baton
.derformat_
.empty()) {
2215 special
= std::max(special
, CSSLOT_DERFORMAT
);
2216 alloc
+= sizeof(struct BlobIndex
);
2217 alloc
+= sizeof(struct Blob
);
2218 alloc
+= baton
.derformat_
.size();
2221 size_t directory(0);
2223 directory
+= sizeof(struct BlobIndex
);
2224 directory
+= sizeof(struct Blob
);
2225 directory
+= sizeof(struct CodeDirectory
);
2226 directory
+= identifier
.size() + 1;
2229 directory
+= team
.size() + 1;
2231 for (Algorithm
*algorithm
: GetAlgorithms())
2232 alloc
= Align(alloc
+ directory
+ (special
+ normal
) * algorithm
->size_
, 16);
2235 alloc
+= sizeof(struct BlobIndex
);
2236 alloc
+= sizeof(struct Blob
);
2237 alloc
+= certificate
;
2241 }), 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 {
2245 insert(blobs
, CSSLOT_REQUIREMENTS
, backing
);
2249 if (mach_header
.Swap(mach_header
->filetype
) == MH_EXECUTE
)
2250 execs
|= kSecCodeExecSegMainBinary
;
2252 if (!baton
.entitlements_
.empty()) {
2253 std::stringbuf data
;
2254 put(data
, baton
.entitlements_
.data(), baton
.entitlements_
.size());
2255 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
2257 auto entitlements(plist(baton
.entitlements_
));
2258 _scope({ plist_free(entitlements
); });
2259 if (plist_get_node_type(entitlements
) != PLIST_DICT
) {
2260 fprintf(stderr
, "ldid: Entitlements should be a plist dicionary\n");
2264 const auto entitled([&](const char *key
) {
2265 auto item(plist_dict_get_item(entitlements
, key
));
2266 if (plist_get_node_type(item
) != PLIST_BOOLEAN
)
2269 plist_get_bool_val(item
, &value
);
2273 if (entitled("get-task-allow"))
2274 execs
|= kSecCodeExecSegAllowUnsigned
;
2275 if (entitled("run-unsigned-code"))
2276 execs
|= kSecCodeExecSegAllowUnsigned
;
2277 if (entitled("com.apple.private.cs.debugger"))
2278 execs
|= kSecCodeExecSegDebugger
;
2279 if (entitled("dynamic-codesigning"))
2280 execs
|= kSecCodeExecSegJit
;
2281 if (entitled("com.apple.private.skip-library-validation"))
2282 execs
|= kSecCodeExecSegSkipLibraryVal
;
2283 if (entitled("com.apple.private.amfi.can-load-cdhash"))
2284 execs
|= kSecCodeExecSegCanLoadCdHash
;
2285 if (entitled("com.apple.private.amfi.can-execute-cdhash"))
2286 execs
|= kSecCodeExecSegCanExecCdHash
;
2289 if (!baton
.derformat_
.empty()) {
2290 std::stringbuf data
;
2291 put(data
, baton
.derformat_
.data(), baton
.derformat_
.size());
2292 insert(blobs
, CSSLOT_DERFORMAT
, CSMAGIC_EMBEDDED_DERFORMAT
, data
);
2297 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2298 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0) {
2299 auto &slot(posts
[CSSLOT_INFOSLOT
]);
2300 for (Algorithm
*algorithm
: GetAlgorithms())
2301 (*algorithm
)(slot
, data
, size
);
2306 for (Algorithm
*pointer
: GetAlgorithms()) {
2307 Algorithm
&algorithm(*pointer
);
2309 std::stringbuf data
;
2311 uint32_t special(0);
2312 _foreach (blob
, blobs
)
2313 special
= std::max(special
, blob
.first
);
2314 _foreach (slot
, posts
)
2315 special
= std::max(special
, slot
.first
);
2316 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
2318 CodeDirectory directory
;
2319 directory
.version
= Swap(uint32_t(0x00020400));
2320 directory
.flags
= Swap(uint32_t(flags
));
2321 directory
.nSpecialSlots
= Swap(special
);
2322 directory
.codeLimit
= Swap(uint32_t(limit
> UINT32_MAX
? UINT32_MAX
: limit
));
2323 directory
.nCodeSlots
= Swap(normal
);
2324 directory
.hashSize
= algorithm
.size_
;
2325 directory
.hashType
= algorithm
.type_
;
2326 directory
.platform
= platform
? 0x01 : 0x00;
2327 directory
.pageSize
= PageShift_
;
2328 directory
.spare2
= Swap(uint32_t(0));
2329 directory
.scatterOffset
= Swap(uint32_t(0));
2330 directory
.spare3
= Swap(uint32_t(0));
2331 directory
.codeLimit64
= Swap(uint64_t(limit
> UINT32_MAX
? limit
: 0));
2332 directory
.execSegBase
= Swap(uint64_t(left
));
2333 directory
.execSegLimit
= Swap(uint64_t(right
- left
));
2334 directory
.execSegFlags
= Swap(execs
);
2336 uint32_t offset(sizeof(Blob
) + sizeof(CodeDirectory
));
2338 directory
.identOffset
= Swap(uint32_t(offset
));
2339 offset
+= identifier
.size() + 1;
2342 directory
.teamIDOffset
= Swap(uint32_t(0));
2344 directory
.teamIDOffset
= Swap(uint32_t(offset
));
2345 offset
+= team
.size() + 1;
2348 offset
+= special
* algorithm
.size_
;
2349 directory
.hashOffset
= Swap(uint32_t(offset
));
2350 offset
+= normal
* algorithm
.size_
;
2352 put(data
, &directory
, sizeof(directory
));
2354 put(data
, identifier
.c_str(), identifier
.size() + 1);
2356 put(data
, team
.c_str(), team
.size() + 1);
2358 std::vector
<uint8_t> storage((special
+ normal
) * algorithm
.size_
);
2359 auto *hashes(&storage
[special
* algorithm
.size_
]);
2361 memset(storage
.data(), 0, special
* algorithm
.size_
);
2363 _foreach (blob
, blobs
) {
2364 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
2365 algorithm(hashes
- blob
.first
* algorithm
.size_
, local
, Swap(local
->length
));
2368 _foreach (slot
, posts
)
2369 memcpy(hashes
- slot
.first
* algorithm
.size_
, algorithm
[slot
.second
], algorithm
.size_
);
2373 for (size_t i
= 0; i
!= normal
- 1; ++i
) {
2374 algorithm(hashes
+ i
* algorithm
.size_
, (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
2375 progress(double(i
) / normal
);
2378 algorithm(hashes
+ (normal
- 1) * algorithm
.size_
, top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
2381 put(data
, storage
.data(), storage
.size());
2383 const auto &save(insert(blobs
, total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1, CSMAGIC_CODEDIRECTORY
, data
));
2384 algorithm(hash
, save
.data(), save
.size());
2390 auto plist(plist_new_dict());
2391 _scope({ plist_free(plist
); });
2393 auto cdhashes(plist_new_array());
2394 plist_dict_set_item(plist
, "cdhashes", cdhashes
);
2396 std::vector
<char> alternateCDSHA256
;
2397 std::vector
<char> alternateCDSHA1
;
2400 for (Algorithm
*pointer
: GetAlgorithms()) {
2401 Algorithm
&algorithm(*pointer
);
2404 const auto &blob(blobs
[total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1]);
2407 std::vector
<char> hash
;
2408 algorithm(hash
, blob
.data(), blob
.size());
2409 if (algorithm
.type_
== CS_HASHTYPE_SHA256_256
)
2410 alternateCDSHA256
= hash
;
2411 else if (algorithm
.type_
== CS_HASHTYPE_SHA160_160
)
2412 alternateCDSHA1
= hash
;
2415 plist_array_append_item(cdhashes
, plist_new_data(hash
.data(), hash
.size()));
2420 plist_to_xml(plist
, &xml
, &size
);
2421 _scope({ free(xml
); });
2423 std::stringbuf data
;
2424 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
2429 Signature
signature(stuff
, sign
, std::string(xml
, size
), alternateCDSHA1
, alternateCDSHA256
);
2430 Buffer
result(signature
);
2431 std::string
value(result
);
2432 put(data
, value
.data(), value
.size());
2434 const auto &save(insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
));
2435 _assert(save
.size() <= certificate
);
2438 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
2444 #ifndef LDID_NOTOOLS
2445 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
, const Progress
&progress
) {
2446 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2448 }), 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 {
2453 std::string
DiskFolder::Path(const std::string
&path
) const {
2454 return path_
+ path
;
2457 DiskFolder::DiskFolder(const std::string
&path
) :
2460 _assert_(path_
.size() != 0 && path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2463 DiskFolder::~DiskFolder() {
2464 if (!std::uncaught_exception())
2465 for (const auto &commit
: commit_
)
2466 Commit(commit
.first
, commit
.second
);
2470 std::string
readlink(const std::string
&path
) {
2471 for (size_t size(1024); ; size
*= 2) {
2475 int writ(_syscall(::readlink(path
.c_str(), &data
[0], data
.size())));
2476 if (size_t(writ
) >= size
)
2485 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 {
2486 std::string
path(Path(root
) + base
);
2488 DIR *dir(opendir(path
.c_str()));
2489 _assert(dir
!= NULL
);
2490 _scope({ _syscall(closedir(dir
)); });
2492 while (auto child
= readdir(dir
)) {
2493 std::string
name(child
->d_name
);
2494 if (name
== "." || name
== "..")
2496 if (Starts(name
, ".ldid."))
2503 _syscall(stat((path
+ name
).c_str(), &info
));
2504 if (S_ISDIR(info
.st_mode
))
2506 else if (S_ISREG(info
.st_mode
))
2509 _assert_(false, "st_mode=%x", info
.st_mode
);
2511 switch (child
->d_type
) {
2519 link(base
+ name
, fun([&]() { return readlink(path
+ name
); }));
2522 _assert_(false, "d_type=%u", child
->d_type
);
2527 Find(root
, base
+ name
+ "/", code
, link
);
2533 void DiskFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2539 auto from(Path(path
));
2540 commit_
[from
] = Temporary(save
, from
);
2545 bool DiskFolder::Look(const std::string
&path
) const {
2546 return _syscall(access(Path(path
).c_str(), R_OK
), ENOENT
) == 0;
2549 void DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2551 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
2552 _assert_(result
== &data
, "DiskFolder::Open(%s)", Path(path
).c_str());
2554 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2555 data
.pubseekpos(0, std::ios::in
);
2556 code(data
, length
, NULL
);
2559 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 {
2560 Find(path
, "", code
, link
);
2562 #endif // LDID_NOTOOLS
2564 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
2568 _assert_(path_
.size() == 0 || path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2571 std::string
SubFolder::Path(const std::string
&path
) const {
2572 return path_
+ path
;
2575 void SubFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2576 return parent_
.Save(Path(path
), edit
, flag
, code
);
2579 bool SubFolder::Look(const std::string
&path
) const {
2580 return parent_
.Look(Path(path
));
2583 void SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2584 return parent_
.Open(Path(path
), code
);
2587 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 {
2588 return parent_
.Find(Path(path
), code
, link
);
2591 std::string
UnionFolder::Map(const std::string
&path
) const {
2592 auto remap(remaps_
.find(path
));
2593 if (remap
== remaps_
.end())
2595 return remap
->second
;
2598 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 {
2599 if (file
.size() >= path
.size() && file
.substr(0, path
.size()) == path
)
2600 code(file
.substr(path
.size()));
2603 UnionFolder::UnionFolder(Folder
&parent
) :
2608 void UnionFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2609 return parent_
.Save(Map(path
), edit
, flag
, code
);
2612 bool UnionFolder::Look(const std::string
&path
) const {
2613 auto file(resets_
.find(path
));
2614 if (file
!= resets_
.end())
2616 return parent_
.Look(Map(path
));
2619 void UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2620 auto file(resets_
.find(path
));
2621 if (file
== resets_
.end())
2622 return parent_
.Open(Map(path
), code
);
2623 auto &entry(file
->second
);
2625 auto &data(*entry
.data_
);
2626 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2627 data
.pubseekpos(0, std::ios::in
);
2628 code(data
, length
, entry
.flag_
);
2631 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 {
2632 for (auto &reset
: resets_
)
2633 Map(path
, code
, reset
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2634 auto &entry(reset
.second
);
2635 auto &data(*entry
.data_
);
2636 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2637 data
.pubseekpos(0, std::ios::in
);
2638 code(data
, length
, entry
.flag_
);
2641 for (auto &remap
: remaps_
)
2642 Map(path
, code
, remap
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2643 parent_
.Open(remap
.second
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2644 code(data
, length
, flag
);
2648 parent_
.Find(path
, fun([&](const std::string
&name
) {
2649 if (deletes_
.find(path
+ name
) == deletes_
.end())
2651 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2652 if (deletes_
.find(path
+ name
) == deletes_
.end())
2657 #ifndef LDID_NOTOOLS
2658 static void copy(std::streambuf
&source
, std::streambuf
&target
, size_t length
, const Progress
&progress
) {
2662 char data
[4096 * 4];
2663 size_t writ(source
.sgetn(data
, sizeof(data
)));
2666 _assert(target
.sputn(data
, writ
) == writ
);
2668 progress(double(total
) / length
);
2672 static plist_t
plist(const std::string
&data
) {
2674 return plist_new_dict();
2675 plist_t
plist(NULL
);
2676 if (Starts(data
, "bplist00"))
2677 plist_from_bin(data
.data(), data
.size(), &plist
);
2679 plist_from_xml(data
.data(), data
.size(), &plist
);
2680 if (plist
== NULL
) {
2681 fprintf(stderr
, "ldid: Failed to parse plist\n");
2687 static void plist_d(std::streambuf
&buffer
, size_t length
, const Functor
<void (plist_t
)> &code
) {
2688 std::stringbuf data
;
2689 copy(buffer
, data
, length
, dummy_
);
2690 auto node(plist(data
.str()));
2691 _scope({ plist_free(node
); });
2692 if (plist_get_node_type(node
) != PLIST_DICT
) {
2693 fprintf(stderr
, "ldid: Unexpected plist type. Expected <dict>\n");
2699 static std::string
plist_s(plist_t node
) {
2702 if (plist_get_node_type(node
) != PLIST_STRING
) {
2703 fprintf(stderr
, "ldid: Unexpected plist type. Expected <string>\n");
2707 plist_get_string_val(node
, &data
);
2708 _scope({ free(data
); });
2723 std::vector
<std::string
> matches_
;
2726 Expression(const std::string
&code
) {
2727 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
) == 0, "regcomp()");
2728 matches_
.resize(regex_
.re_nsub
+ 1);
2735 bool operator ()(const std::string
&data
) {
2736 regmatch_t matches
[matches_
.size()];
2737 auto value(regexec(®ex_
, data
.c_str(), matches_
.size(), matches
, 0));
2738 if (value
== REG_NOMATCH
)
2740 _assert_(value
== 0, "regexec()");
2741 for (size_t i(0); i
!= matches_
.size(); ++i
)
2742 matches_
[i
].assign(data
.data() + matches
[i
].rm_so
, matches
[i
].rm_eo
- matches
[i
].rm_so
);
2746 const std::string
&operator [](size_t index
) const {
2747 return matches_
[index
];
2756 mutable std::unique_ptr
<Expression
> regex_
;
2758 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
2765 Rule(const Rule
&rhs
) :
2766 weight_(rhs
.weight_
),
2772 void Compile() const {
2773 regex_
.reset(new Expression(code_
));
2776 bool operator ()(const std::string
&data
) const {
2777 _assert(regex_
.get() != NULL
);
2778 return (*regex_
)(data
);
2781 bool operator <(const Rule
&rhs
) const {
2782 if (weight_
> rhs
.weight_
)
2784 if (weight_
< rhs
.weight_
)
2786 return mode_
> rhs
.mode_
;
2791 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
2792 return lhs
->code_
< rhs
->code_
;
2796 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
) {
2797 // XXX: this is a miserable fail
2798 std::stringbuf temp
;
2799 put(temp
, prefix
, size
);
2800 copy(buffer
, temp
, length
- size
, progress
);
2801 // XXX: this is a stupid hack
2802 pad(temp
, 0x10 - (length
& 0xf));
2803 auto data(temp
.str());
2805 HashProxy
proxy(hash
, save
);
2806 return Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, merge
, requirements
, key
, slots
, flags
, platform
, progress
);
2810 std::map
<std::string
, Hash
> files
;
2811 std::map
<std::string
, std::string
> links
;
2813 void Merge(const std::string
&root
, const State
&state
) {
2814 for (const auto &entry
: state
.files
)
2815 files
[root
+ entry
.first
] = entry
.second
;
2816 for (const auto &entry
: state
.links
)
2817 links
[root
+ entry
.first
] = entry
.second
;
2821 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
) {
2822 std::string executable
;
2823 std::string identifier
;
2827 std::string
info("Info.plist");
2829 SubFolder
folder(parent
, [&]() {
2830 if (parent
.Look(info
))
2833 if (parent
.Look("Contents/" + info
))
2835 else if (parent
.Look("Resources/" + info
)) {
2836 info
= "Resources/" + info
;
2839 fprintf(stderr
, "ldid: Could not find Info.plist\n");
2844 folder
.Open(info
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2845 plist_d(buffer
, length
, fun([&](plist_t node
) {
2846 plist_t
nodebuf(plist_dict_get_item(node
, "CFBundleExecutable"));
2847 if (nodebuf
== NULL
) {
2848 fprintf(stderr
, "ldid: Cannot find key CFBundleExecutable\n");
2851 executable
= plist_s(nodebuf
);
2852 nodebuf
= plist_dict_get_item(node
, "CFBundleIdentifier");
2853 if (nodebuf
== NULL
) {
2854 fprintf(stderr
, "ldid: Cannot find key CFBundleIdentifier\n");
2857 identifier
= plist_s(nodebuf
);
2861 if (mac
&& info
== "Info.plist")
2862 executable
= "MacOS/" + executable
;
2864 progress(root
+ "*");
2866 std::string entitlements
;
2867 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2868 // XXX: this is a miserable fail
2869 std::stringbuf temp
;
2870 copy(buffer
, temp
, length
, progress
);
2871 // XXX: this is a stupid hack
2872 pad(temp
, 0x10 - (length
& 0xf));
2873 auto data(temp
.str());
2874 entitlements
= alter(root
, Analyze(data
.data(), data
.size()));
2877 static const std::string
directory("_CodeSignature/");
2878 static const std::string
signature(directory
+ "CodeResources");
2880 std::map
<std::string
, std::multiset
<Rule
>> versions
;
2882 auto &rules1(versions
[""]);
2883 auto &rules2(versions
["2"]);
2885 const std::string
resources(mac
? "Resources/" : "");
2888 rules1
.insert(Rule
{1, NoMode
, "^" + (resources
== "" ? ".*" : resources
)});
2889 rules1
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2890 rules1
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2891 rules1
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2892 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
2896 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
2897 if (mac
) rules2
.insert(Rule
{20, NoMode
, "^" + resources
});
2898 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
2899 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2900 rules2
.insert(Rule
{1, NoMode
, "^.*"});
2901 rules2
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2902 rules2
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2903 if (!mac
) rules2
.insert(Rule
{1010, NoMode
, "^Base\\.lproj/"});
2904 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
2905 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
2906 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
2907 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
2908 if (mac
) rules2
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2909 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
2912 std::string
failure(mac
? "Contents/|Versions/[^/]*/Resources/" : "");
2913 Expression
nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure
+ ")Info\\.plist$");
2914 std::map
<std::string
, Bundle
> bundles
;
2916 folder
.Find("", fun([&](const std::string
&name
) {
2919 auto bundle(Split(name
).dir
);
2921 _assert(!bundle
.empty());
2922 bundle
= Split(bundle
.substr(0, bundle
.size() - 1)).dir
;
2924 SubFolder
subfolder(folder
, bundle
);
2927 bundles
[nested
[1]] = Sign(root
+ bundle
, subfolder
, key
, remote
, "", Starts(name
, "PlugIns/") ? alter
:
2928 static_cast<const Functor
<std::string (const std::string
&, const std::string
&)> &>(fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }))
2930 local
.Merge(bundle
, remote
);
2931 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2934 std::set
<std::string
> excludes
;
2936 auto exclude([&](const std::string
&name
) {
2937 // BundleDiskRep::adjustResources -> builder.addExclusion
2938 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
2941 for (const auto &bundle
: bundles
)
2942 if (Starts(name
, bundle
.first
+ "/")) {
2943 excludes
.insert(name
);
2950 folder
.Find("", fun([&](const std::string
&name
) {
2954 if (local
.files
.find(name
) != local
.files
.end())
2956 auto &hash(local
.files
[name
]);
2958 folder
.Open(name
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2959 progress(root
+ name
);
2970 auto size(most(data
, &header
.bytes
, sizeof(header
.bytes
)));
2972 if (name
!= "_WatchKitStub/WK" && size
== sizeof(header
.bytes
))
2973 switch (Swap(header
.magic
)) {
2975 // Java class file format
2976 if (Swap(header
.count
) >= 40)
2979 case MH_MAGIC
: case MH_MAGIC_64
:
2980 case MH_CIGAM
: case MH_CIGAM_64
:
2981 folder
.Save(name
, true, flag
, fun([&](std::streambuf
&save
) {
2983 Sign(header
.bytes
, size
, data
, hash
, save
, identifier
, "", false, "", key
, slots
, length
, 0, false, Progression(progress
, root
+ name
));
2988 folder
.Save(name
, false, flag
, fun([&](std::streambuf
&save
) {
2989 HashProxy
proxy(hash
, save
);
2990 put(proxy
, header
.bytes
, size
);
2991 copy(data
, proxy
, length
- size
, progress
);
2994 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2998 local
.links
[name
] = read();
3001 auto plist(plist_new_dict());
3002 _scope({ plist_free(plist
); });
3004 for (const auto &version
: versions
) {
3005 auto files(plist_new_dict());
3006 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
3008 for (const auto &rule
: version
.second
)
3011 bool old(&version
.second
== &rules1
);
3013 for (const auto &hash
: local
.files
)
3014 for (const auto &rule
: version
.second
)
3015 if (rule(hash
.first
)) {
3016 if (!old
&& mac
&& excludes
.find(hash
.first
) != excludes
.end());
3017 else if (old
&& rule
.mode_
== NoMode
)
3018 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
3019 else if (rule
.mode_
!= OmitMode
) {
3020 auto entry(plist_new_dict());
3021 plist_dict_set_item(entry
, "hash", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
3023 plist_dict_set_item(entry
, "hash2", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha256_
), sizeof(hash
.second
.sha256_
)));
3024 if (rule
.mode_
== OptionalMode
)
3025 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3026 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
3033 for (const auto &link
: local
.links
)
3034 for (const auto &rule
: version
.second
)
3035 if (rule(link
.first
)) {
3036 if (rule
.mode_
!= OmitMode
) {
3037 auto entry(plist_new_dict());
3038 plist_dict_set_item(entry
, "symlink", plist_new_string(link
.second
.c_str()));
3039 if (rule
.mode_
== OptionalMode
)
3040 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3041 plist_dict_set_item(files
, link
.first
.c_str(), entry
);
3048 for (const auto &bundle
: bundles
) {
3049 auto entry(plist_new_dict());
3050 plist_dict_set_item(entry
, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle
.second
.hash
.sha256_
), sizeof(bundle
.second
.hash
.sha256_
)));
3051 plist_dict_set_item(entry
, "requirement", plist_new_string("anchor apple generic"));
3052 plist_dict_set_item(files
, bundle
.first
.c_str(), entry
);
3056 for (const auto &version
: versions
) {
3057 auto rules(plist_new_dict());
3058 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
3060 std::multiset
<const Rule
*, RuleCode
> ordered
;
3061 for (const auto &rule
: version
.second
)
3062 ordered
.insert(&rule
);
3064 for (const auto &rule
: ordered
)
3065 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
3066 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
3068 auto entry(plist_new_dict());
3069 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
3071 switch (rule
->mode_
) {
3075 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
3078 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3081 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
3084 plist_dict_set_item(entry
, "top", plist_new_bool(true));
3088 if (rule
->weight_
>= 10000)
3089 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
3090 else if (rule
->weight_
!= 1)
3091 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
3095 folder
.Save(signature
, true, NULL
, fun([&](std::streambuf
&save
) {
3096 HashProxy
proxy(local
.files
[signature
], save
);
3099 plist_to_xml(plist
, &xml
, &size
);
3100 _scope({ free(xml
); });
3101 put(proxy
, xml
, size
);
3105 bundle
.path
= folder
.Path(executable
);
3107 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
3108 progress(root
+ executable
);
3109 folder
.Save(executable
, true, flag
, fun([&](std::streambuf
&save
) {
3111 slots
[1] = local
.files
.at(info
);
3112 slots
[3] = local
.files
.at(signature
);
3113 bundle
.hash
= Sign(NULL
, 0, buffer
, local
.files
[executable
], save
, identifier
, entitlements
, false, requirements
, key
, slots
, length
, 0, false, Progression(progress
, root
+ executable
));
3120 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
) {
3122 return Sign(root
, folder
, key
, local
, requirements
, alter
, progress
);
3128 std::string
Hex(const uint8_t *data
, size_t size
) {
3130 hex
.reserve(size
* 2);
3131 for (size_t i(0); i
!= size
; ++i
) {
3132 hex
+= "0123456789abcdef"[data
[i
] >> 4];
3133 hex
+= "0123456789abcdef"[data
[i
] & 0xf];
3138 static void usage(const char *argv0
) {
3139 fprintf(stderr
, "Link Identity Editor %s\n\n", LDID_VERSION
);
3140 fprintf(stderr
, "Usage: %s [-Acputype:subtype] [-a] [-C[adhoc | enforcement | expires | hard |\n", argv0
);
3141 fprintf(stderr
, " host | kill | library-validation | restrict | runtime]] [-D] [-d]\n");
3142 fprintf(stderr
, " [-Enum:file] [-e] [-H[sha1 | sha256]] [-h] [-Iname]\n");
3143 fprintf(stderr
, " [-Kkey.p12 [-Upassword]] [-M] [-P] [-Qrequirements.xml] [-q]\n");
3144 fprintf(stderr
, " [-r | -Sfile.xml | -s] [-u] [-arch arch_type] file ...\n");
3145 fprintf(stderr
, "Options:\n");
3146 fprintf(stderr
, " -S[file.xml] Pseudo-sign using the entitlements in file.xml\n");
3147 fprintf(stderr
, " -Kkey.p12 Sign using private key in key.p12\n");
3148 fprintf(stderr
, " -Upassword Use password to unlock key.p12\n");
3149 fprintf(stderr
, " -M Merge entitlements with any existing\n");
3150 fprintf(stderr
, " -h Print CDHash of file\n\n");
3151 fprintf(stderr
, "More information: 'man ldid'\n");
3154 void cleanupfunc(void) {
3155 for (const auto &temp
: cleanup
)
3156 remove(temp
.c_str());
3159 #ifndef LDID_NOTOOLS
3160 int main(int argc
, char *argv
[]) {
3161 std::atexit(cleanupfunc
);
3162 OpenSSL_add_all_algorithms();
3163 # if OPENSSL_VERSION_MAJOR >= 3
3164 OSSL_PROVIDER
*legacy
= OSSL_PROVIDER_load(NULL
, "legacy");
3165 OSSL_PROVIDER
*deflt
= OSSL_PROVIDER_load(NULL
, "default");
3173 little_
= endian
.byte
[0];
3197 bool platform(false);
3199 uint32_t flag_CPUType(_not(uint32_t));
3200 uint32_t flag_CPUSubtype(_not(uint32_t));
3202 const char *flag_I(NULL
);
3210 std::vector
<std::string
> files
;
3217 for (int argi(1); argi
!= argc
; ++argi
)
3218 if (argv
[argi
][0] != '-')
3219 files
.push_back(argv
[argi
]);
3220 else if (strcmp(argv
[argi
], "-arch") == 0) {
3221 bool foundarch
= false;
3225 fprintf(stderr
, "ldid: -arch must be followed by an architecture string\n");
3228 for (int i
= 0; archs
[i
].name
!= NULL
; i
++) {
3229 if (strcmp(archs
[i
].name
, argv
[argi
]) == 0) {
3230 flag_CPUType
= archs
[i
].cputype
;
3231 flag_CPUSubtype
= archs
[i
].cpusubtype
;
3239 fprintf(stderr
, "error: unknown architecture specification flag: -arch %s\n", argv
[argi
]);
3242 } else switch (argv
[argi
][1]) {
3244 if (flag_s
|| flag_S
) {
3245 fprintf(stderr
, "ldid: Can only specify one of -r, -S, -s\n");
3251 case 'e': flag_e
= true; break;
3254 const char *string
= argv
[argi
] + 2;
3255 const char *colon
= strchr(string
, ':');
3256 if (colon
== NULL
) {
3260 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3262 unsigned number(strtoul(string
, &arge
, 0));
3263 if (arge
!= colon
|| (number
== 0 && errno
== EINVAL
)) {
3267 auto &slot(slots
[number
]);
3268 for (Algorithm
*algorithm
: GetAlgorithms())
3269 (*algorithm
)(slot
, file
.data(), file
.size());
3272 case 'q': flag_q
= true; break;
3275 const char *hash
= argv
[argi
] + 2;
3284 if (strcmp(hash
, "sha1") == 0)
3286 else if (strcmp(hash
, "sha256") == 0)
3289 fprintf(stderr
, "ldid: only sha1 and sha256 are supported at this time\n");
3294 case 'h': flag_h
= true; break;
3297 const char *xml
= argv
[argi
] + 2;
3298 requirements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3301 case 'D': flag_D
= true; break;
3302 case 'd': flag_d
= true; break;
3304 case 'a': flag_a
= true; break;
3308 fprintf(stderr
, "ldid: -A can only be specified once\n");
3312 if (argv
[argi
][2] != '\0') {
3313 const char *cpu
= argv
[argi
] + 2;
3314 const char *colon
= strchr(cpu
, ':');
3315 if (colon
== NULL
) {
3320 flag_CPUType
= strtoul(cpu
, &arge
, 0);
3321 if (arge
!= colon
|| (flag_CPUType
== 0 && errno
== EINVAL
)) {
3325 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
3326 if (arge
!= argv
[argi
] + strlen(argv
[argi
]) || (flag_CPUSubtype
== 0 && errno
== EINVAL
)) {
3334 const char *name
= argv
[argi
] + 2;
3335 if (strcmp(name
, "host") == 0)
3336 flags
|= kSecCodeSignatureHost
;
3337 else if (strcmp(name
, "adhoc") == 0)
3338 flags
|= kSecCodeSignatureAdhoc
;
3339 else if (strcmp(name
, "hard") == 0)
3340 flags
|= kSecCodeSignatureForceHard
;
3341 else if (strcmp(name
, "kill") == 0)
3342 flags
|= kSecCodeSignatureForceKill
;
3343 else if (strcmp(name
, "expires") == 0)
3344 flags
|= kSecCodeSignatureForceExpiration
;
3345 else if (strcmp(name
, "restrict") == 0)
3346 flags
|= kSecCodeSignatureRestrict
;
3347 else if (strcmp(name
, "enforcement") == 0)
3348 flags
|= kSecCodeSignatureEnforcement
;
3349 else if (strcmp(name
, "library-validation") == 0)
3350 flags
|= kSecCodeSignatureLibraryValidation
;
3351 else if (strcmp(name
, "runtime") == 0)
3352 flags
|= kSecCodeSignatureRuntime
;
3354 fprintf(stderr
, "ldid: -C: Unsupported option\n");
3364 if (flag_r
|| flag_S
) {
3365 fprintf(stderr
, "ldid: Can only specify one of -r, -S, -s\n");
3369 entitlements
.clear();
3374 if (flag_r
|| flag_s
) {
3375 fprintf(stderr
, "ldid: Can only specify one of -r, -S, -s\n");
3379 if (argv
[argi
][2] != '\0') {
3380 const char *xml
= argv
[argi
] + 2;
3381 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3390 password
= argv
[argi
] + 2;
3394 if (argv
[argi
][2] != '\0')
3395 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3405 flag_I
= argv
[argi
] + 2;
3414 if (flag_I
!= NULL
&& !flag_S
) {
3415 fprintf(stderr
, "ldid: -I requires -S\n");
3422 size_t filei(0), filee(0);
3423 _foreach (file
, files
) try {
3424 std::string
path(file
);
3427 if (stat(path
.c_str(), &info
) == -1) {
3428 fprintf(stderr
, "ldid: %s: %s\n", path
.c_str(), strerror(errno
));
3432 if (S_ISDIR(info
.st_mode
)) {
3434 fprintf(stderr
, "ldid: Only -S can be used on directories\n");
3437 ldid::DiskFolder
folder(path
+ "/");
3438 path
+= "/" + Sign("", folder
, key
, requirements
, ldid::fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }), dummy_
).path
;
3439 } else if (flag_S
|| flag_r
) {
3440 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3442 std::filebuf output
;
3444 auto temp(Temporary(output
, split
));
3447 ldid::Unsign(input
.data(), input
.size(), output
, dummy_
);
3449 std::string
identifier(flag_I
?: split
.base
.c_str());
3450 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, flag_M
, requirements
, key
, slots
, flags
, platform
, dummy_
);
3456 Map
mapping(path
, flag_D
? true : false);
3457 FatHeader
fat_header(mapping
.data(), mapping
.size());
3459 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
3460 struct linkedit_data_command
*signature(NULL
);
3461 struct encryption_info_command
*encryption(NULL
);
3464 if (mach_header
.GetCPUType() != flag_CPUType
)
3466 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
3471 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
3473 _foreach (load_command
, mach_header
.GetLoadCommands()) {
3474 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
3476 if (cmd
== LC_CODE_SIGNATURE
)
3477 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
3478 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
3479 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
3480 else if (cmd
== LC_LOAD_DYLIB
) {
3481 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3482 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
3484 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
3487 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
3488 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
3494 if (flag_d
&& encryption
!= NULL
) {
3495 printf("cryptid=%d\n", mach_header
.Swap(encryption
->cryptid
));
3499 if (encryption
== NULL
) {
3500 fprintf(stderr
, "ldid: -D requires an encrypted binary\n");
3503 encryption
->cryptid
= mach_header
.Swap(0);
3506 if ((flag_e
|| flag_q
|| flag_h
) && signature
== NULL
) {
3507 fprintf(stderr
, "ldid: -e, -q, and -h requre a signed binary\n");
3512 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3514 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3515 uint8_t *blob
= top
+ data
;
3516 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3518 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3519 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
3520 uint32_t begin
= Swap(super
->index
[index
].offset
);
3521 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3522 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
3527 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3529 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3530 uint8_t *blob
= top
+ data
;
3531 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3533 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3534 if (Swap(super
->index
[index
].type
) == CSSLOT_REQUIREMENTS
) {
3535 uint32_t begin
= Swap(super
->index
[index
].offset
);
3536 struct Blob
*requirement
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3537 fwrite(requirement
, 1, Swap(requirement
->length
), stdout
);
3542 char *buf
= _syscall(realpath(file
.c_str(), NULL
));
3543 printf("Executable=%s\n", buf
);
3546 auto algorithms(GetAlgorithms());
3548 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3550 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3551 uint8_t *blob
= top
+ data
;
3552 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3555 CodeDirectory
*directory_
;
3557 Algorithm
&algorithm_
;
3562 std::map
<uint8_t, Candidate
> candidates
;
3564 for (size_t index(0); index
!= Swap(super
->count
); ++index
) {
3565 auto type(Swap(super
->index
[index
].type
));
3566 if ((type
== CSSLOT_CODEDIRECTORY
|| type
>= CSSLOT_ALTERNATE
) && type
!= CSSLOT_SIGNATURESLOT
) {
3567 uint32_t begin
= Swap(super
->index
[index
].offset
);
3568 uint32_t end
= index
+ 1 == Swap(super
->count
) ? Swap(super
->blob
.length
) : Swap(super
->index
[index
+ 1].offset
);
3569 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3570 auto type(directory
->hashType
);
3571 _assert(type
> 0 && type
<= algorithms
.size());
3572 auto &algorithm(*algorithms
[type
- 1]);
3573 uint8_t hash
[algorithm
.size_
];
3574 algorithm(hash
, blob
+ begin
, end
- begin
);
3575 candidates
.insert({type
, {directory
, end
- begin
, algorithm
, Hex(hash
, 20), begin
}});
3579 _assert(!candidates
.empty());
3580 auto best(candidates
.end());
3583 const auto directory(best
->second
.directory_
);
3584 const auto flags(Swap(directory
->flags
));
3586 printf("Identifier=%s\n", blob
+ best
->second
.offset
+ Swap(directory
->identOffset
));
3589 if (flags
& kSecCodeSignatureHost
)
3591 if (flags
& kSecCodeSignatureAdhoc
)
3593 if (flags
& kSecCodeSignatureForceHard
)
3595 if (flags
& kSecCodeSignatureForceKill
)
3597 if (flags
& kSecCodeSignatureForceExpiration
)
3598 names
+= ",expires";
3599 if (flags
& kSecCodeSignatureRestrict
)
3600 names
+= ",restrict";
3601 if (flags
& kSecCodeSignatureEnforcement
)
3602 names
+= ",enforcement";
3603 if (flags
& kSecCodeSignatureLibraryValidation
)
3604 names
+= ",library-validation";
3605 if (flags
& kSecCodeSignatureRuntime
)
3606 names
+= ",runtime";
3608 printf("CodeDirectory v=%x size=%zd flags=0x%x(%s) hashes=%d+%d location=embedded\n",
3609 Swap(directory
->version
), best
->second
.size_
, flags
, names
.empty() ? "none" : names
.c_str() + 1, Swap(directory
->nCodeSlots
), Swap(directory
->nSpecialSlots
));
3610 printf("Hash type=%s size=%d\n", best
->second
.algorithm_
.name(), directory
->hashSize
);
3612 std::string choices
;
3613 for (const auto &candidate
: candidates
) {
3614 auto choice(candidate
.second
.algorithm_
.name());
3617 printf("CandidateCDHash %s=%s\n", choice
, candidate
.second
.hash_
.c_str());
3619 printf("Hash choices=%s\n", choices
.c_str() + 1);
3621 printf("CDHash=%s\n", best
->second
.hash_
.c_str());
3626 } catch (const char *) {
3631 # if OPENSSL_VERSION_MAJOR >= 3
3632 OSSL_PROVIDER_unload(legacy
);
3633 OSSL_PROVIDER_unload(deflt
);
3638 #endif // LDID_NOTOOLS