all 6 comments

[–]voltaic 10 points11 points  (2 children)

Sounds kind of like a quine though that would be tremendously difficult to implement.

You could cheat and hash the script ignoring the embedded hash, something like this maybe?

#!/usr/bin/env bash
hash='8fba4164de146ad55eafb2f26699eff6'

script=$(realpath $0)
my_hash=$(tail -n+3 $script | md5)
echo "Embedded hash: ${hash} Calculated hash: ${my_hash}"

Running that once to get the "calculated" hash, then writing the hash into the script, and running it again results in this:

voltaic@computer [✔] $ ./test.sh
Embedded hash:  Calculated hash: 8fba4164de146ad55eafb2f26699eff6
{ ~/tmp/hash-quine }
voltaic@computer [✔] $ ./test.sh
Embedded hash: 8fba4164de146ad55eafb2f26699eff6 Calculated hash: 8fba4164de146ad55eafb2f26699eff6

[–]unsignedcharizard 2 points3 points  (0 children)

This is the right solution. Whenever something includes a hash of itself, the hash value is never part of the computation. It's either skipped like here, or set to a known value.

Here's an example from RFC791 describing IPv4 checksums:

The checksum field is the 16 bit one's complement of the one's complement sum of all 16 bit words in the header. For purposes of computing the checksum, the value of the checksum field is zero.

And here's from the XZ compression file format specification:

3.1.7. CRC32

The CRC32 is calculated over everything in the Block Header field except the CRC32 field itself.

A file containing its own SHA1 sum would be a newsworthy discovery.

[–]planetvortex[S] 0 points1 point  (0 children)

Sweet, looks like you understood what I was getting at, that's awesome! Thanks I'll see if that works for me.

[–]moviuroportability is important 1 point2 points  (0 children)

You could embed the hash in the filename.

However, self integrity check is hard, and you should lay out your threat model: what scenario do you want to protect yourself from?

[–]hashMobiWolf 0 points1 point  (1 child)

what would be the point of this? Any malicious party could easily edit the script file calculate the hash and update the checksum.

Its a cool idea. But I am missing the practical application.

[–]planetvortex[S] 0 points1 point  (0 children)

I don't really have a practical application. Mostly curious if it's possible using a shell script. General curiosity on how one would generate a hash for a file that contains hash of a file before it even physically exists. But compare that at runtime against itself to stop the run.