To sign our binaries with Authenticode I am using Microsoft’s signtool. Unfortunatelly, it is not really descriptive in some error codes it returns.
In my case, I have been replacing resources in some native binaries, which were already signed. Of course, this will break existing Authenticode signature, but the signature is still there.
Signature is just one of sections in the EXE/DLL file and this section stays there, even if the file signature is invalid.
Signtool unfortunatelly cannot resign an file which is already signed and is always returning same error 0x800700C1.
SignTool Error: SignedCode::Sign returned error: 0x800700C1
This error is in fact ERROR_BAD_EXE_FORMAT.
So, I needed to remove existing signature from an binary file.
One interesting tool called delcert is already writen and works pretty nice to solve this and has source code included:
After quick look into the C++ source, it is in fact does nothing magic. It is using Win32 API from ImageHlp library (which takes case of loading of binaries).
Interesting functions there are: ImageRemoveCertificate, which needs to be followed by MapAndLoad/UnMapAndLoad pair to clear section from PE headers.
After removing signature, signtool has no complains and signs the file nicely.
One step back to the ERROR_BAD_EXE_FORMAT error code
In your Microsoft SDK Program Files, you will probably have X86 and x64 versions of signtool (one in Program Files (x86), another in Program Files).
So depending on your binary bitness (32bit vx 64bit) you have to call proper signtool, otherwise you will get the original error.
To check the bitness, you can use dumpbin.exe which comes with Visual Studio (VC\bin folder) when you start it with
dumpbin.exe /headers myapp.exe
you should see a line like:
14C machine (x86)
or for 64bit version:
8664 machine (x64)