//Reference: https://iphelix.medium.com/open-security-training-introduction-to-software-exploits-uninitialized-variable-overflow-811a7cd75bd8

#include <stdio.h>
#import <stdio.h>
#import <string.h>
#import <stdlib.h>
#import <unistd.h>
#import <errno.h>


int login(void)
{
        char username[32];
        char password[32];
        printf("username at: %p\n", &username);
        printf("Username: ");
        fgets(username,32,stdin);
        fflush(stdin);

        if (strlen(username) > 8){
        FILE *fp;
        /* opening file for reading */
        fp = fopen("hax.bin" , "rb");
        if(fp == NULL) {
        perror("Error opening file");
        return(-1);
        }
        if( fgets (username, 32, fp)!=NULL ) {
        /* writing content to stdout */
        puts(username);
        }
        fclose(fp);
        }       


        printf("Password: ");
        fgets(password,32,stdin);
        
        if (strcmp(username, "admin\n") == 0
                && strcmp(password, "password@123\n") == 0)
        {
                printf("Login successful\n");
                return 0;
        }else{
                printf("password not compliant, printing error\n");
                printf("username at: %p\n", &username);
                printf("password at %p\n", &password);
                return -1;
        }

}

int log_error(int farray, char *msg)
{
        char *err, *mesg;
        char buffer[24];
        printf("mesg: %p\n", mesg);
        memset(buffer,0x00,sizeof(buffer));
        sprintf(buffer, "Error: %s", mesg);
        printf("%s\n", buffer);
        return 0;
}

int main(void)

{
        printf("Address of main function is %p\n", &main);
        switch(login())
        {
                case -1:
                        log_error(-1,"Unable to login");
                        break;
                default:
                        break;
        }
        return 0;
}