How do I write a program that, by itself, can detect that it has been changed?
The short answer is to create a hash or program key, and the program encrypts and stores this key inside itself. From time to time, the program will make a checksum by itself and compare it to this hash / key. If there is a difference, then handle it accordingly.
There are many, many ways to do this. There are many very smart engineers out there who know how to get around this if that's what you are trying to avoid.
source to share
The simplest way would be to use a hash function to generate a shortcode that digests the entire program and then test that.
It would be pretty easy to debug the code and replace the hash value to undermine this.
The best way would be to create a digital signature with your private key and with the public key in the program to verify it.
This will require changing the public key and hash, as well as understanding the program, or changing the program's code itself to undermine verification.
Anything you can do in the above case makes it difficult to disrupt, but it will be possible with some effort. I would suggest looking into cryptographic techniques and copy protection for more information according to your specific case.
source to share
Do you mean that the program 'foo' needs to be able to detect if any part of it has changed before / at runtime? It is not the responsibility of the program, its responsibility for the security hooks in the target OS.
For example, if the installed and trusted "foo" has the signature "xyz1234", the kernel should refuse to run the modified (or completely new) "foo". The same goes for "foo" while it is running in memory. Check out the Safe Execution Path and TPE to get started.
Better to ask how to sign your released version of 'foo' which depends on your target platform.
source to share
I would ask an external tool to do the check. This problem reminds me of the task of writing a program that prints itself . In Bash, you can do something like this:
#!/bin/bash
cat $0
which actually asks for an external tool to do the job. This is to somehow solve the problem, going away from solving the problem ...
source to share
The best option would be to sign code - either with a tool supplied by your local friendly OS (for example, if you're targeting Windows, you probably want to look at Authenticode , where the OS handles spoofing), or by porting your own option for storing hashes MD5 and comparisons
It is important to remember that bets are disabled if someone injects a thread into your process (to potentially kill your current checks, etc.), or if they break the compiled application to bypass said checks.
source to share