Untitled

 avatar
unknown
plain_text
6 months ago
2.8 kB
3
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>

#define ERROR 1
#define PROC_INDEX 0
#define PATH_INDEX 1
#define SIGN_INDEX 2
#pragma warning(disable : 4996)

int isElf(FILE* file);
int checkInfected(FILE* file, char* sign);
void findSign(char* path, char* sign);
char* getFullPath(char* parent, char* child);
int getFileLength(FILE* file);

int main(int argc, char* argv[])
{
	int errorInFiles = 0;
	if (argc != 3)
	{
		printf("Usage: %s <dir path> <virus signature file>\n", argv[PROC_INDEX]);
		return ERROR;
	}
	FILE* virusSign = fopen(argv[SIGN_INDEX], "rb");
	if (!virusSign)
	{
		printf("Error opening signature file!\n");
		errorInFiles = ERROR;
	}
	DIR* path = opendir(argv[PATH_INDEX]);
	if (!path)
	{
		printf("Error opening path directory file!\n");
		errorInFiles = ERROR;
	}
	if (errorInFiles) return ERROR;
	
	findSign(path,argv[PATH_INDEX], virusSign);

	fclose(virusSign);
	closedir(path);
	
	return 0;
}

int isElf(FILE* file)
{
	char* header = malloc(strlen("ELF"));
	fread(header, sizeof(unsigned char), strlen("ELF"), file);
	if (!strncmp(header, "ELF",3))	return 1;
	return 0;
}

int checkInfected(FILE* file, FILE* signFile)
{
	int streak = 0, flag = 0;
	char fileChar = 0, signChar = 0;
	fseek(signFile, 0, SEEK_SET);
	fseek(file, 0, SEEK_SET);
	int len = getFileLength(signFile);
	do
	{
		fread(&fileChar, sizeof(unsigned char), 1, file);
		fread(&signChar, sizeof(unsigned char), 1, signFile);
		if (signChar == fileChar)
		{
			streak++;
		}
		else
		{
			if (streak == len) flag = 1;
			streak = 0;
			fseek(signFile, 0, SEEK_SET);
		}
	} while (!feof(file) && !feof(signFile) && !flag);
	if (streak >= len || flag) return 1;
	return 0;
}

void findSign(DIR* currDir,char* path, FILE* sign)
{
	struct dirent* entry;
	DIR* dir;
	FILE* fp;
	char* entryPath;
	while ((entry = readdir(currDir)) != 0)
	{
		if (!strcmp(".", entry->d_name) || !strcmp("..", entry->d_name)) continue;
		entryPath = getFullPath(path, entry->d_name);
		if ((dir = opendir(entryPath)))
		{
			findSign(dir,entryPath, sign);
			closedir(dir);
		}
		else if ((fp = fopen(entryPath, "rb")))
		{
			if (isElf(fp))
			{
				if (checkInfected(fp, sign))	printf("%s is infected!\n", entryPath);
			}
			fclose(fp);
		}
	}
}

char* getFullPath(char* parent, char* child)
{
	char* fullName = malloc(strlen(parent) + strlen(child) + 1);
	memset(fullName, 0, strlen(parent) + strlen(child) + 1);
	strncpy(fullName, parent, strlen(parent));
	strncat(fullName, "/", 1);
	strncat(fullName, child, strlen(child));
	return fullName;
}

int getFileLength(FILE* file)
{
	int len = 0;
	fseek(file, 0, SEEK_END);
	len = ftell(file);
	fseek(file, 0, SEEK_SET);
	return len;
}
Editor is loading...
Leave a Comment