IOS signature types include Development, ad-hoc, In-house and App Store. And packaging process involves all kinds of certificates, Provision Profile, entitlements, CertificateSigningRequest, p12, AppID… There are a lot of concepts. This paper will start from the principle of packaged signature, and sort out the whole process of complete signature. Finally, it will explain the realization of re-signature and what points need to be paid attention to in the signature mechanism.

To ensure that App distribution platforms are controllable and that all apps installed on iOS devices are officially approved by Apple, Apple has established the iOS signature packaging mechanism. To understand the implementation of the iOS signature mechanism, let’s start with the principle of the signature mechanism.

1. Signature principle

1.1 Asymmetric encryption

Network data transmission can use symmetric encryption and asymmetric encryption security protection in the form of symmetric encryption is index according to the sender and the receiver (B) (A) both sides add the decryption key is consistent, but this will increase the insecurity of key distribution itself: such as how to guarantee the key in the process of transfer is not leaked.

In asymmetric encryption, A and B hold A pair of public and private keys for encryption and decryption. The public and private keys appear in pairs. For a private key, there is only one corresponding public key. The private key is confidential and public, but the private key cannot be derived from the public key. The files encrypted with the private key can be decrypted using the public key, and the files encrypted with the public key can be decrypted only using the private key. The encryption process is as follows:

  1. The sender (A) first generates A pair of public and private key pairs. The private key is kept by the sender and the public key is distributed randomly (every iOS device terminal actually contains Apple’s public key).

  2. When sending data, the sender uses the private key to encrypt the original data into ciphertext transmission (encryption package IPA).

  3. After receiving the ciphertext, the recipient (B) decrypts the data using the obtained public key to obtain the data content (iOS device authentication installation IPA).

1.2 Data Signature

Two problems are mainly solved here, one is the size of the encrypted data and the other is how to verify the validity of the public key.

1.2.1 Summary of information

As mentioned above, ipA packets will be authenticated by encryption and decryption during iOS packaging and installation. However, the size of ipA installation package is often more than ten M, and several GIGABytes are large. Therefore, it will be very inefficient to encrypt and decrypt such a large amount of data. Information summary solves the problem of too large encrypted data. Its principle is to obtain a hash value of information content through a formula that is difficult to be backward deduced. It has the following characteristics:

  • The size of the calculated hash value is fixed and not affected by the size of the original information content.
  • Irreversible, the original information cannot be inferred from the hash value (in fact, MD5 and SHA-1 algorithms have been proven to be deciphered);
  • Uniqueness, the original information content is the same, then the hash value is the same; The original data is different, and there will be no duplicate hashing results.

Using the message digest technology When encrypting and transmitting data, the sender calculates the message digest using the hash algorithm, encrypts the message digest, and sends the message and the message digest (encrypted).

After receiving the data, the receiver first decrypts and obtains the abstract content, then calculates the information summary of the file content according to the same hash algorithm, and finally matches whether the received hash value is consistent with the calculated hash value. If the hash value is consistent, it indicates that the transmission process is secure.

In this way, the calculation process of encryption and decryption of the whole original data is avoided, thus improving the verification efficiency.

1.2.2 Signing Certificates

In asymmetric encryption, the public key is public and available to everyone, thus causing insecurity. For example, active attacker C impersonates data sender A and distributes its disguised public key to data receiver B, so as to monitor the communication between A and B, or to inject the communication data between A and B.

In order to ensure the security of obtaining public keys, CA Certificate Authority is introduced here. CA is an authority certifying the validity of public keys (Apple belongs to CA authentication authority). It issues a digital certificate to each user who uses the public key. The digital certificate proves that the user listed in the certificate has the public key listed in the certificate. The user uses the CA’s public key to verify the signature on the digital certificate. If the verification succeeds, the public key contained in the certificate is considered valid.

CA authentication ensures the security of users’ public keys. IOS packaging requires uploading the. CertSigningRequest file to The Apple Developer Center and configuring various.

2. The iOS’s signature

2.1 Key Concepts

  • CertSigningRequest file. Generate a. CertSigningRequest file from the Mac keystring access. This process generates a pair of key pairs from the Mac terminal. The private key is stored in the Mac and the public key is contained in the. Then upload the. CertSigningRequest file to the Apple background, that is, the Apple Developer Center, to generate the corresponding development certificate or issue the certificate (.cer file).

  • Cer file: a certificate generated after Apple uses the Apple private key to sign the Mac public key on the background.

  • P12 file: a key pair private key generated on the Mac. Since the private key is locally private, you can use it. P12 exports the private key to other team members.

  • Identifiers. Click Create App IDs and check the permissions included in your App: APNs, HealthKit, iCloud, etc.

  • Entitlements. App use to a variety of permissions (APNs, HealthKit, iCloud, etc.), also need Apple verification can take effect after, Apple will unify these permissions switch known as Entitlements. When first checked permissions in Xcode, entitlements in the project will automatically generate a. Entitlements file, inside a record of the permissions that App has.

  • Profiles. The.cer file only declares the type of certificate, such as Apple Development, Apple Distribution, APNs push, etc., but what certificate is packaged, what AppID is, what features are included in the packaged App, and which devices can be installed on? The Provisioning Profile (.mobileprovision) is used. The Apple backend combines all this information and signs it using the Apple private key to create the Provisioning Profile:

2.2 AppStore signature

Before releasing an App to AppStore, it needs to be reviewed by Apple background. After the review, Apple background will encrypt and sign the App data with Apple private key to generate IPA package. After downloading an App from AppStore, users use the built-in Apple public key to decrypt and verify that the App is successfully installed. Since the whole process of uploading, reviewing, downloading and installing AppStore distribution is in Apple’s ecological chain, only one verification is required to ensure security.

2.3 Other Signatures

Downloading and installing an App from the AppStore requires only one digital signature to ensure security, but There are other ways apple can install it:

  • Connect devices to Xcode for debugging installation during development
  • Ad-hoc internal test installation requires device UDID to be obtained and registered first, and there is a maximum limit of 100 devices
  • In-house is distributed within the enterprise. The number of installed devices is unlimited. After the installation, you need to select the trust certificate In the Settings

How does Apple ensure the security of the App installation process? The answer is dual signature, where Apple uses the aforementioned local Mac key pair and Apple background key pair to digitally sign multiple times to keep the whole process under control.

  1. Mac keystring access Generates a pair of public and private key pairs locally. The default values are public key L and private key L (L: Local).

  2. Apple already has A pair of public and private key pairs. The private key A is in the Apple background, and the public key A is built into every iOS device terminal (A: Apple).

  3. Upload public key L to the Apple background, and use private key A to digitally sign public key L to generate A signing certificate. Cer, The private key L is also used to sign additional information (what certificate is packaged, AppID, what features are included with the packaged App, and which devices can be installed on) to generate a Provisioning Profile, Then download the. Cer and Provisioning Profile and install it on the Mac.

  4. Compile and package app, select signature certificate. Cer, and the package instruction will automatically find the private key L corresponding to the certificate (it can be matched because key pairs appear in pairs, and the premise is that there must already be a local private key L, that is, the installation of P12), and then use the private key L to sign app.

    • The signature data consists of two parts: the Mach-O executable writes the signature directly to this file, and the other resource files are stored in the _CodeSignature directory. You can save the resulting.ipa file as a.zip file, extract it, right-click the.app file in the Payload folder, and see the signature data.

    • In addition, for the dynamic libraries and plug-ins (Plugins, Watch, Frameworks folder) contained in App, each of them will be signed separately and their respective mach-O executable files and _CodeSignature will be generated during the signing process.

    • Signature data refers to the code content, all resource files contained in the App, as long as there is any change in them, they must be re-signed to be valid.

  5. During the packaging process, the description file Provisioning Profile named Embedded. Mobileprovision is put into the packaging app.

  6. During the installation and startup, the iOS device uses the built-in public key A to verify whether embedded. Mobileprovision is valid (whether the device is included in the allowed installation list), and checks whether the signature of the. Cer certificate is valid (whether the certificate has expired), and obtains the public key L.

  7. Embedded. Mobileprovision verification, using public key L decrypt verify APP signature information: AppID is corresponding, entitlements switch is consistent with APP entitlements, etc.

  8. All verification passed, installation/startup completed.

The above process is the process of developing and debugging, ad-hoc, in-house and other ways to package and install App. The only difference is that the matching rules of device IDs In step 5 are inconsistent. Development and debugging only install the current joint adjustment equipment; Ad-hoc can be installed on devices already registered with a developer account, up to 100 per year; In-house has no limit on the number of devices and is often used to distribute apps within an enterprise.

3. The IPA packet is re-signed

Ipa package re-signature mainly applies to non-App Store installation packages. The App Store distributes the IPA file to the Apple background for review. After passing the ipA file, the Apple private key is used to encrypt the IPA file and then the ipA file can be released for installation. However, ipA packages generated by development and debugging, ad-hoc, in-house and other distribution channels do not have the step of Apple background verification, which means you can re-sign any. App,.ipa files.

Reviewing the signing process, the key step (④⑤) to actually sign the IPA package is done locally on the Mac. There are three conditions that need to be met during the signing process: App (the product of software code compilation), P12 certificate, and Provisioning Profile. The content of the App is dynamically changing, so Apple will not verify it, and in fact, there is no need to verify it, because in the development and debugging process, the developed App must be constantly changing. If the App Store needs to be launched, Apple only needs to check and verify the content of the App in the review stage. Other distribution channels are out of its reach. P12 and Provisioning Profiles are downloaded and installed, in most cases created by administrators, then exported and distributed to team members.

3.1 Signing Instructions

The iOS signature calls the

codesign

# MAC terminal input: codesign --help
codesign --help
Usage: codesign -s identity [-fv*] [-o flags] [-r reqs] [-i ident] path ... # sign
codesign -v [-v*] [-R=<req string>|-R <req file path>] path|[+]pid ... # verify
codesign -d [options] path ... # display contents
codesign -h pid ... # display hosting paths
Copy the code

You can also see the signature details by looking at Xcode’s build log

# signature instruction
codesign -f -s "IPhone Distribution: XXX (certificate name)"-- Entitlements. Plist (Profile Profile) XXX. App (signature app)Copy the code

3.2 heavy signature

  • Obtain the IPA packet to be re-signed first. Note that the IPA packet must be unencrypted. If you download ipA from the App Store, you need to crack the shell and decrypt it before re-signing it. You can also download ipA from jailbreak platform. Rename the.ipa to.zip, right-click it, and extract it. This will generate a Payload folder that contains the.app file.

  • Rename the Provisioning Profile corresponding to the signing certificate to Embedded. Mobileprovision and copy it to the Payload folder. At the same time, right-click the. App file to display the package contents and copy the embedded. Mobileprovision file to the. App folder to replace the original embedded.

  • Entitlements. Plist is a signature file exported from the Profile configuration corresponding to the signature certificate, it has the same function as the xxx. xcent file in the Xcode signature log in the previous screenshot. Terminal CD Path to Payload folder, execute the command

    # CD XXX /Payload
    
    security cms -D -i embedded.mobileprovision
    Copy the code

    Will print out the content of the Profile configuration, find /

    Entitlements
    , and then the

    Entitlements
    following


    copy the content of Entitlements to new entitlements. Plist file (can generate plist file through Xcode, select Property List type), entitlements. Plist file to Payload folder.

    
             
              ... 
             
    <key>Entitlements</key>
    <dict>
                <key>application-identifier</key>
        <string>xxx</string>
                <key>keychain-access-groups</key>
        <array>
                <string>xxx</string>
        </array>
                <key>get-task-allow</key>
        <false/>
                <key>com.apple.developer.team-identifier</key>
        <string>xxx</string>
    </dict>
    
    Copy the code

  • The signed certificate name can be viewed from the keychain center after the certificate is installed

    Or use the following command on the terminal to view:

    security find-identity -v -p codesigning
    Copy the code

  • The preparation is complete and the signature is re-signed. Right click app to display package contents, check dynamic libraries and Plugins (Plugins, Watch, Frameworks folder), remove Plugins and Watch folders for personal certificates because personal certificates cannot sign Extention. If Frameworks exist, the signing instruction is executed, and if there are more than one, each of the Frameworks is re-signed.

  • codesign -fs "Signature Certificate Name" "Frameworks/xxx.framework (dynamic library path)"
    Copy the code

  • Finally, re-sign the APP

  • codesign -f -s "IPhone Distribution: XXX (certificate name)"-- Entitlements. Plist (Profile Profile) XXX. App (signature app)Copy the code

  • You can download the ipA file from iTunes, iTools, or any other way to install it on your iOS device.

3.3 Inject code to re-sign

  • Ipa code injection is generally implemented through dynamic libraries. Select New TARTETS – Framework & Library – Framework in Xcode and add custom code to the Framework, usually using Runtime to inject additional functionality. Finally, the framework is selected to support the framework, and the final dynamic library is compiled.

  • Right-click any. App that needs to be re-signed to display the package contents, and then copy the dynamic library to the Framework folder (or create a new one). However, at this time, the dynamic library has not established an association with APP, and the dynamic library needs to be injected into MachO to take effect. Injection Use the Yololib tool, download and compile yololib, and copy the production command to /usr/local/bin or another PATH in $PATH to use the Yololib directive on the terminal

    ## Use the yololib tool to inject dynamic libraries
    
    yololib "MachO file path" "Dynamic library path to inject"
    Copy the code

    After successful injection, all the Framework is signed, and finally the APP is re-signed, and then the IPA file is generated.

    Here is a script for re-signing, CJCodeSign. To learn more about the signing directive, click here.

3.4 Reflection on re-signature

The iOS re-signing implementation can see that there is no strong relationship between the private key resources used for signing (including the. Cer certificate and Provisioning Profile configuration) and the actual signing app package, which causes two problems.

  1. .cerCertificate andProvisioning ProfileThe configuration is used to distribute signatures for other apps, especially for in-house enterprise certificates, which can be distributed without limit. Once Apple detects this type of signature violation, it can either revoke the certificate or cancel the enterprise developer account! That’s why it’s important to keep it tight, rightp12,Provisioning ProfileCauses of outgoing files.
  2. Self-owned apps are re-signed after the code is injected, such as multiple applications, plug-ins, malicious packet capture, etc. There seems to be no better way to protect against this kind of application than checking the Bundle ID and adding whitelist search to the App dynamic library. Of course, this has involved the direction of reverse protection, I have not in-depth understanding of this, interested students can participate in the discussion.

Finish the full!

Finally, attach the re-signing script address: CJCodeSign