Search code examples
c++sha1

stack check fail in sha-1 c++


I'm having a __stack_chk_fail in the main thread. I have no idea why is this happening?

Stack Flow

I got the codes from this website: http://www.packetizer.com/security/sha1/
Im trying to add a function to compute the digest of a file using the example.

.h file

#include <stdio.h>
#include <string>
std::string digestFile( char *filename );

.cpp file

std::string SHA1::digestFile( char *filename )
{
    Reset();

    FILE *fp = NULL;
    if (!(fp = fopen(filename, "rb")))
    {
        printf("sha: unable to open file %s\n", filename);
        return NULL;
    }

    char c = fgetc(fp);
    while(!feof(fp))
    {
        Input(c);
        c = fgetc(fp);
    }

    fclose(fp);

    unsigned message_digest[5];
    if (!Result(message_digest))
    { printf("sha: could not compute message digest for %s\n", filename); }

    std::string hash;
    for (int i = 0; i < 5; i++)
    {
        char buffer[8];
        int count = sprintf(buffer, "%08x", message_digest[i]);
        if (count != 8)
        { printf("converting unsiged to char ERROR"); }

        hash.append(buffer);
    }

    return hash;
}

Solution

  • __stack_chk_fail occurs when you write to invalid address.

    It turns out you do:

        char buffer[8];
        int count = sprintf(buffer, "%08x", message_digest[i]);
    

    C strings are NUL-terminated. That means that when sprintf writes 8 digits, it adds 9-th char, '\0'. But buffer only has space for 8 chars, so the 9-th goes past the end of the buffer.

    You need char buffer[9]. Or do it the C++ way with std::stringstream, which does not involve any fixed sizes and thus no risk of buffer overrun.