planetbeing/xpwn — pull request #7 by Djayb6 (2013-12-08 20:41:38+00:00)
Title: remove the 16 extra bytes from the DATA section and fix Img3Elements padding

Here is a little story to explain my PR:

I was trying to generate the `PartialDigest` of an img3 file (iBSS from iPhone3,1_6.1.3_10B329) using `tss_get_partial_hash_from_file` function from `MobileDevice.framework`. It was working perfectly with the original iBSS, so I tried with the same iBSS which had been previously decrypted and re-encrypted with `xpwntool`, but this time it did not work:
`tss_get_partial_hash: ih_buffer_len(65928) + 8 is not a multiple of 64`, where `65928` is the SHSH offset.

As I was expecting both iBSSs to be identical (since I decrypted and encrypted back the iBSS without modifying the DATA section), I didn't understand in the first place why the SHSH offset from the original iBSS + 8 would be a multiple of 64 and not the one from the second iBSS.

By comparing both iBSSs, I found the following differences in the second iBSS:
- 16 extra bytes of zero's are appended to the end of the `DATA` section (which increased by 16 the total size of the img3, the total size minus the img3 header size, the SHSH offset size and the data size of the `DATA` section)
- in the second `KBAG` section, some padding bytes were replaced by bytes with random values.

The first issue was caused by the 16 extra bytes added in the `writeImg3` function, and the second issue was caused by the padding bytes array limited to 0x10 bytes in the `writeImg3Default`.
I fixed the first issue by removing those 16 extra bytes, and I fixed the second one by making the padding bytes array variable-length.