Start using clang-format for automatic source formatting.

This commit is contained in:
Victor M. Alvarez
2020-10-19 12:11:28 +02:00
141 changed files with 22765 additions and 24287 deletions
+158
View File
@@ -0,0 +1,158 @@
# clang-format configuration applied to all source files in this project.
# Requires clang-format version 10.0.0 or newer.
---
Language: Cpp
BasedOnStyle: Google
AccessModifierOffset: -1
AlignAfterOpenBracket: AlwaysBreak
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignConsecutiveMacros: true
AlignEscapedNewlines: Left
AlignOperands: true
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: true
AllowAllConstructorInitializersOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Inline
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: false
BinPackParameters: false
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: true
AfterEnum: false
AfterFunction: true
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: true
AfterUnion: false
AfterExternBlock: false
BeforeCatch: true
BeforeElse: true
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Allman
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: true
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^<ext/.*\.h>'
Priority: 2
- Regex: '^<.*\.h>'
Priority: 1
- Regex: '^<.*'
Priority: 2
- Regex: '.*'
Priority: 3
IncludeIsMainRegex: '([-_](test|unittest))?$'
IndentCaseLabels: false
IndentPPDirectives: None
IndentWidth: 2
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: "^\
begin_declarations|\
begin_struct.*$"
MacroBlockEnd: "^\
end_declarations|\
end_struct.*$"
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Never
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 100
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 1000
PointerAlignment: Left
RawStringFormats:
- Language: Cpp
Delimiters:
- cc
- CC
- cpp
- Cpp
- CPP
- 'c++'
- 'C++'
CanonicalDelimiter: ''
BasedOnStyle: google
- Language: TextProto
Delimiters:
- pb
- PB
- proto
- PROTO
EnclosingFunctions:
- EqualsProto
- EquivToProto
- PARSE_PARTIAL_TEXT_PROTO
- PARSE_TEST_PROTO
- PARSE_TEXT_PROTO
- ParseTextOrDie
- ParseTextProtoOrDie
CanonicalDelimiter: ''
BasedOnStyle: google
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: true
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Auto
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 8
UseTab: Never
...
+59 -73
View File
@@ -27,25 +27,21 @@ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <yara.h>
#include "args.h"
#define args_is_long_arg(arg) \
(arg[0] == '-' && arg[1] == '-' && arg[2] != '\0')
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <yara.h>
#define args_is_long_arg(arg) (arg[0] == '-' && arg[1] == '-' && arg[2] != '\0')
#define args_is_short_arg(arg) \
(arg[0] == '-' && arg[1] != '-' && arg[1] != '\0')
#define args_is_short_arg(arg) \
(arg[0] == '-' && arg[1] != '-' && arg[1] != '\0')
args_option_t* args_get_short_option(
args_option_t *options,
const char opt)
args_option_t* args_get_short_option(args_option_t* options, const char opt)
{
while (options->type != ARGS_OPT_END)
{
@@ -59,11 +55,9 @@ args_option_t* args_get_short_option(
}
args_option_t* args_get_long_option(
args_option_t *options,
const char* arg)
args_option_t* args_get_long_option(args_option_t* options, const char* arg)
{
arg += 2; // skip starting --
arg += 2; // skip starting --
while (options->type != ARGS_OPT_END)
{
@@ -90,52 +84,52 @@ args_error_type_t args_parse_option(
const char* opt_arg,
int* opt_arg_was_used)
{
char *endptr = NULL;
char* endptr = NULL;
if (opt_arg_was_used != NULL)
*opt_arg_was_used = 0;
*opt_arg_was_used = 0;
if (opt->count == opt->max_count)
return ARGS_ERROR_TOO_MANY;
switch (opt->type)
{
case ARGS_OPT_BOOLEAN:
*(bool*) opt->value = !(*(bool*) opt->value);
break;
case ARGS_OPT_BOOLEAN:
*(bool*) opt->value = !(*(bool*) opt->value);
break;
case ARGS_OPT_INTEGER:
case ARGS_OPT_INTEGER:
if (opt_arg == NULL)
return ARGS_ERROR_REQUIRED_INTEGER_ARG;
if (opt_arg == NULL)
return ARGS_ERROR_REQUIRED_INTEGER_ARG;
*(int*) opt->value = strtol(opt_arg, &endptr, 0);
*(int*) opt->value = strtol(opt_arg, &endptr, 0);
if (*endptr != '\0')
return ARGS_ERROR_REQUIRED_INTEGER_ARG;
if (*endptr != '\0')
return ARGS_ERROR_REQUIRED_INTEGER_ARG;
if (opt_arg_was_used != NULL)
*opt_arg_was_used = 1;
if (opt_arg_was_used != NULL)
*opt_arg_was_used = 1;
break;
break;
case ARGS_OPT_STRING:
case ARGS_OPT_STRING:
if (opt_arg == NULL)
return ARGS_ERROR_REQUIRED_STRING_ARG;
if (opt_arg == NULL)
return ARGS_ERROR_REQUIRED_STRING_ARG;
if (opt->max_count > 1)
((const char**)opt->value)[opt->count] = opt_arg;
else
*(const char**) opt->value = opt_arg;
if (opt->max_count > 1)
((const char**) opt->value)[opt->count] = opt_arg;
else
*(const char**) opt->value = opt_arg;
if (opt_arg_was_used != NULL)
*opt_arg_was_used = 1;
if (opt_arg_was_used != NULL)
*opt_arg_was_used = 1;
break;
break;
default:
assert(0);
default:
assert(0);
}
opt->count++;
@@ -144,37 +138,32 @@ args_error_type_t args_parse_option(
}
void args_print_error(
args_error_type_t error,
const char* option)
void args_print_error(args_error_type_t error, const char* option)
{
switch(error)
switch (error)
{
case ARGS_ERROR_UNKNOWN_OPT:
fprintf(stderr, "unknown option `%s`\n", option);
break;
case ARGS_ERROR_TOO_MANY:
fprintf(stderr, "too many `%s` options\n", option);
break;
case ARGS_ERROR_REQUIRED_INTEGER_ARG:
fprintf(stderr, "option `%s` requires an integer argument\n", option);
break;
case ARGS_ERROR_REQUIRED_STRING_ARG:
fprintf(stderr, "option `%s` requires a string argument\n", option);
break;
case ARGS_ERROR_UNEXPECTED_ARG:
fprintf(stderr, "option `%s` doesn't expect an argument\n", option);
break;
default:
return;
case ARGS_ERROR_UNKNOWN_OPT:
fprintf(stderr, "unknown option `%s`\n", option);
break;
case ARGS_ERROR_TOO_MANY:
fprintf(stderr, "too many `%s` options\n", option);
break;
case ARGS_ERROR_REQUIRED_INTEGER_ARG:
fprintf(stderr, "option `%s` requires an integer argument\n", option);
break;
case ARGS_ERROR_REQUIRED_STRING_ARG:
fprintf(stderr, "option `%s` requires a string argument\n", option);
break;
case ARGS_ERROR_UNEXPECTED_ARG:
fprintf(stderr, "option `%s` doesn't expect an argument\n", option);
break;
default:
return;
}
}
int args_parse(
args_option_t *options,
int argc,
const char **argv)
int args_parse(args_option_t* options, int argc, const char** argv)
{
args_error_type_t error = ARGS_ERROR_OK;
@@ -257,9 +246,7 @@ int args_parse(
}
void args_print_usage(
args_option_t *options,
int help_alignment)
void args_print_usage(args_option_t* options, int help_alignment)
{
char buffer[128];
@@ -278,8 +265,7 @@ void args_print_usage(
if (options->long_name != NULL)
len += sprintf(buffer + len, "--%s", options->long_name);
if (options->type == ARGS_OPT_STRING ||
options->type == ARGS_OPT_INTEGER)
if (options->type == ARGS_OPT_STRING || options->type == ARGS_OPT_INTEGER)
{
len += sprintf(
buffer + len,
+52 -44
View File
@@ -34,68 +34,76 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifdef __cplusplus
extern "C" {
extern "C"
{
#endif
typedef enum _args_error_type {
ARGS_ERROR_OK,
ARGS_ERROR_UNKNOWN_OPT,
ARGS_ERROR_TOO_MANY,
ARGS_ERROR_REQUIRED_INTEGER_ARG,
ARGS_ERROR_REQUIRED_STRING_ARG,
ARGS_ERROR_UNEXPECTED_ARG,
} args_error_type_t;
typedef enum _args_error_type
{
ARGS_ERROR_OK,
ARGS_ERROR_UNKNOWN_OPT,
ARGS_ERROR_TOO_MANY,
ARGS_ERROR_REQUIRED_INTEGER_ARG,
ARGS_ERROR_REQUIRED_STRING_ARG,
ARGS_ERROR_UNEXPECTED_ARG,
} args_error_type_t;
typedef enum _args_option_type {
// special
ARGS_OPT_END,
ARGS_OPT_GROUP,
// options with no arguments
ARGS_OPT_BOOLEAN,
// options with arguments (optional or required)
ARGS_OPT_INTEGER,
ARGS_OPT_STRING,
} args_option_type_t;
typedef enum _args_option_type
{
// special
ARGS_OPT_END,
ARGS_OPT_GROUP,
// options with no arguments
ARGS_OPT_BOOLEAN,
// options with arguments (optional or required)
ARGS_OPT_INTEGER,
ARGS_OPT_STRING,
} args_option_type_t;
typedef struct _args_option {
args_option_type_t type;
const char short_name;
const char *long_name;
void *value;
int max_count;
const char *help;
const char *type_help;
int count;
} args_option_t;
typedef struct _args_option
{
args_option_type_t type;
const char short_name;
const char *long_name;
void *value;
int max_count;
const char *help;
const char *type_help;
int count;
} args_option_t;
#define OPT_BOOLEAN(short_name, long_name, value, ...) \
{ ARGS_OPT_BOOLEAN, short_name, long_name, value, 1, __VA_ARGS__ }
#define OPT_BOOLEAN(short_name, long_name, value, ...) \
{ \
ARGS_OPT_BOOLEAN, short_name, long_name, value, 1, __VA_ARGS__ \
}
#define OPT_INTEGER(short_name, long_name, value, ...) \
{ ARGS_OPT_INTEGER, short_name, long_name, value, 1, __VA_ARGS__ }
#define OPT_INTEGER(short_name, long_name, value, ...) \
{ \
ARGS_OPT_INTEGER, short_name, long_name, value, 1, __VA_ARGS__ \
}
#define OPT_STRING_MULTI(short_name, long_name, value, max_count, ...) \
{ ARGS_OPT_STRING, short_name, long_name, value, max_count, __VA_ARGS__ }
#define OPT_STRING_MULTI(short_name, long_name, value, max_count, ...) \
{ \
ARGS_OPT_STRING, short_name, long_name, value, max_count, __VA_ARGS__ \
}
#define OPT_STRING(short_name, long_name, value, ...) \
OPT_STRING_MULTI(short_name, long_name, value, 1, __VA_ARGS__)
OPT_STRING_MULTI(short_name, long_name, value, 1, __VA_ARGS__)
#define OPT_END() { ARGS_OPT_END, 0 }
#define OPT_END() \
{ \
ARGS_OPT_END, 0 \
}
int args_parse(
args_option_t *options,
int argc,
const char **argv);
int args_parse(args_option_t *options, int argc, const char **argv);
void args_print_usage(
args_option_t *options,
int alignment);
void args_print_usage(args_option_t *options, int alignment);
#ifdef __cplusplus
+17 -17
View File
@@ -34,19 +34,20 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <stdbool.h>
#ifdef _WIN32
#include <io.h>
#define access _access_s
#include <io.h>
#define access _access_s
#else
#include <unistd.h>
#include <unistd.h>
#endif
#define exit_with_code(code) { result = code; goto _exit; }
#define exit_with_code(code) \
{ \
result = code; \
goto _exit; \
}
bool compile_files(
YR_COMPILER* compiler,
int argc,
const char** argv)
bool compile_files(YR_COMPILER* compiler, int argc, const char** argv)
{
for (int i = 0; i < argc - 1; i++)
{
@@ -69,7 +70,6 @@ bool compile_files(
// backslash.
if (colon && *(colon + 1) != '\\' && *(colon + 1) != '/')
{
file_name = colon + 1;
*colon = '\0';
ns = argv[i];
@@ -103,7 +103,7 @@ bool compile_files(
}
bool is_integer(const char *str)
bool is_integer(const char* str)
{
if (*str == '-')
str++;
@@ -111,7 +111,7 @@ bool is_integer(const char *str)
if (*str == '\0')
return false;
while(*str)
while (*str)
{
if (!isdigit(*str))
return false;
@@ -122,21 +122,21 @@ bool is_integer(const char *str)
}
bool is_float(const char *str)
bool is_float(const char* str)
{
bool has_dot = false;
if (*str == '-') // skip the minus sign if present
if (*str == '-') // skip the minus sign if present
str++;
if (*str == '.') // float can't start with a dot
if (*str == '.') // float can't start with a dot
return false;
while(*str)
while (*str)
{
if (*str == '.')
{
if (has_dot) // two dots, not a float
if (has_dot) // two dots, not a float
return false;
has_dot = true;
@@ -149,7 +149,7 @@ bool is_float(const char *str)
str++;
}
return has_dot; // to be float must contain a dot
return has_dot; // to be float must contain a dot
}
#endif
+47 -65
View File
@@ -41,65 +41,55 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "threading.h"
int mutex_init(
MUTEX* mutex)
int mutex_init(MUTEX* mutex)
{
#if defined(_WIN32) || defined(__CYGWIN__)
InitializeCriticalSection(mutex);
return 0;
#else
#if defined(_WIN32) || defined(__CYGWIN__)
InitializeCriticalSection(mutex);
return 0;
#else
return pthread_mutex_init(mutex, NULL);
#endif
#endif
}
void mutex_destroy(
MUTEX* mutex)
void mutex_destroy(MUTEX* mutex)
{
#if defined(_WIN32) || defined(__CYGWIN__)
#if defined(_WIN32) || defined(__CYGWIN__)
DeleteCriticalSection(mutex);
#else
#else
pthread_mutex_destroy(mutex);
#endif
#endif
}
void mutex_lock(
MUTEX* mutex)
void mutex_lock(MUTEX* mutex)
{
#if defined(_WIN32) || defined(__CYGWIN__)
#if defined(_WIN32) || defined(__CYGWIN__)
EnterCriticalSection(mutex);
#else
#else
pthread_mutex_lock(mutex);
#endif
#endif
}
void mutex_unlock(
MUTEX* mutex)
void mutex_unlock(MUTEX* mutex)
{
#if defined(_WIN32) || defined(__CYGWIN__)
#if defined(_WIN32) || defined(__CYGWIN__)
LeaveCriticalSection(mutex);
#else
#else
pthread_mutex_unlock(mutex);
#endif
#endif
}
int semaphore_init(
SEMAPHORE* semaphore,
int value)
int semaphore_init(SEMAPHORE* semaphore, int value)
{
#if defined(_WIN32) || defined(__CYGWIN__)
#if defined(_WIN32) || defined(__CYGWIN__)
*semaphore = CreateSemaphore(NULL, value, 65535, NULL);
if (*semaphore == NULL)
return GetLastError();
#elif defined(__FreeBSD__)
#elif defined(__FreeBSD__)
*semaphore = malloc(sizeof(sem_t));
if (*semaphore == NULL)
return errno;
return sem_init(*semaphore, 0, value);
#else
#else
// Mac OS X doesn't support unnamed semaphores via sem_init, that's why
// we use sem_open instead sem_init and immediately unlink the semaphore
// from the name. More info at:
@@ -107,10 +97,11 @@ int semaphore_init(
// http://stackoverflow.com/questions/1413785/sem-init-on-os-x
//
// Also create name for semaphore from PID because running multiple instances
// of YARA at the same time can cause that sem_open() was called in two processes
// simultaneously while neither of them had chance to call sem_unlink() yet.
// of YARA at the same time can cause that sem_open() was called in two
// processes simultaneously while neither of them had chance to call
// sem_unlink() yet.
char name[20];
snprintf(name, sizeof(name), "/yara.sem.%i", (int)getpid());
snprintf(name, sizeof(name), "/yara.sem.%i", (int) getpid());
*semaphore = sem_open(name, O_CREAT, S_IRUSR, value);
if (*semaphore == SEM_FAILED)
@@ -118,71 +109,62 @@ int semaphore_init(
if (sem_unlink(name) != 0)
return errno;
#endif
#endif
return 0;
}
void semaphore_destroy(
SEMAPHORE* semaphore)
void semaphore_destroy(SEMAPHORE* semaphore)
{
#if defined(_WIN32) || defined(__CYGWIN__)
#if defined(_WIN32) || defined(__CYGWIN__)
CloseHandle(*semaphore);
#elif defined(__FreeBSD__)
#elif defined(__FreeBSD__)
sem_close(*semaphore);
free(*semaphore);
#else
#else
sem_close(*semaphore);
#endif
#endif
}
void semaphore_wait(
SEMAPHORE* semaphore)
void semaphore_wait(SEMAPHORE* semaphore)
{
#if defined(_WIN32) || defined(__CYGWIN__)
#if defined(_WIN32) || defined(__CYGWIN__)
WaitForSingleObject(*semaphore, INFINITE);
#else
#else
sem_wait(*semaphore);
#endif
#endif
}
void semaphore_release(
SEMAPHORE* semaphore)
void semaphore_release(SEMAPHORE* semaphore)
{
#if defined(_WIN32) || defined(__CYGWIN__)
#if defined(_WIN32) || defined(__CYGWIN__)
ReleaseSemaphore(*semaphore, 1, NULL);
#else
#else
sem_post(*semaphore);
#endif
#endif
}
int create_thread(
THREAD* thread,
THREAD_START_ROUTINE start_routine,
void* param)
{
#if defined(_WIN32) || defined(__CYGWIN__)
#if defined(_WIN32) || defined(__CYGWIN__)
*thread = CreateThread(NULL, 0, start_routine, param, 0, NULL);
if (*thread == NULL)
return GetLastError();
else
return 0;
#else
#else
return pthread_create(thread, NULL, start_routine, param);
#endif
#endif
}
void thread_join(
THREAD* thread)
void thread_join(THREAD* thread)
{
#if defined(_WIN32) || defined(__CYGWIN__)
#if defined(_WIN32) || defined(__CYGWIN__)
WaitForSingleObject(*thread, INFINITE);
#else
#else
pthread_join(*thread, NULL);
#endif
#endif
}
+11 -22
View File
@@ -27,16 +27,15 @@ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef THREADING_H
#define THREADING_H
#if defined(_WIN32) || defined(__CYGWIN__)
#include <windows.h>
#else
#include <sys/stat.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/stat.h>
#endif
#if defined(_WIN32) || defined(__CYGWIN__)
@@ -52,41 +51,31 @@ typedef LPTHREAD_START_ROUTINE THREAD_START_ROUTINE;
typedef sem_t* SEMAPHORE;
typedef pthread_mutex_t MUTEX;
typedef pthread_t THREAD;
typedef void *(*THREAD_START_ROUTINE) (void *);
typedef void* (*THREAD_START_ROUTINE)(void*);
#endif
int mutex_init(
MUTEX* mutex);
int mutex_init(MUTEX* mutex);
void mutex_destroy(
MUTEX* mutex);
void mutex_destroy(MUTEX* mutex);
void mutex_lock(
MUTEX* mutex);
void mutex_lock(MUTEX* mutex);
void mutex_unlock(
MUTEX* mutex);
void mutex_unlock(MUTEX* mutex);
int semaphore_init(
SEMAPHORE* semaphore,
int value);
int semaphore_init(SEMAPHORE* semaphore, int value);
void semaphore_destroy(
SEMAPHORE* semaphore);
void semaphore_destroy(SEMAPHORE* semaphore);
void semaphore_wait(
SEMAPHORE* semaphore);
void semaphore_wait(SEMAPHORE* semaphore);
void semaphore_release(
SEMAPHORE* semaphore);
void semaphore_release(SEMAPHORE* semaphore);
int create_thread(
THREAD* thread,
THREAD_START_ROUTINE start_routine,
void* param);
void thread_join(
THREAD* thread);
void thread_join(THREAD* thread);
#endif
+300 -317
View File
File diff suppressed because it is too large Load Diff
+37 -56
View File
@@ -29,10 +29,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef _WIN32
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#else
@@ -40,22 +40,20 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endif
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <yara.h>
#include "args.h"
#include "common.h"
#ifndef MAX_PATH
#define MAX_PATH 256
#endif
#define MAX_ARGS_EXT_VAR 32
#define MAX_ARGS_EXT_VAR 32
typedef struct COMPILER_RESULTS
{
@@ -64,7 +62,6 @@ typedef struct COMPILER_RESULTS
} COMPILER_RESULTS;
static char* atom_quality_table;
static char* ext_vars[MAX_ARGS_EXT_VAR + 1];
static bool ignore_warnings = false;
@@ -73,36 +70,41 @@ static bool show_help = false;
static bool fail_on_warnings = false;
static int max_strings_per_rule = DEFAULT_MAX_STRINGS_PER_RULE;
#define USAGE_STRING \
"Usage: yarac [OPTION]... [NAMESPACE:]SOURCE_FILE... OUTPUT_FILE"
"Usage: yarac [OPTION]... [NAMESPACE:]SOURCE_FILE... OUTPUT_FILE"
args_option_t options[] =
{
OPT_STRING(0, "atom-quality-table", &atom_quality_table,
"path to a file with the atom quality table", "FILE"),
args_option_t options[] = {
OPT_STRING(
0,
"atom-quality-table",
&atom_quality_table,
"path to a file with the atom quality table",
"FILE"),
OPT_STRING_MULTI('d', "define", &ext_vars, MAX_ARGS_EXT_VAR,
"define external variable", "VAR=VALUE"),
OPT_STRING_MULTI(
'd',
"define",
&ext_vars,
MAX_ARGS_EXT_VAR,
"define external variable",
"VAR=VALUE"),
OPT_BOOLEAN(0, "fail-on-warnings", &fail_on_warnings,
"fail on warnings"),
OPT_BOOLEAN(0, "fail-on-warnings", &fail_on_warnings, "fail on warnings"),
OPT_BOOLEAN('h', "help", &show_help,
"show this help and exit"),
OPT_BOOLEAN('h', "help", &show_help, "show this help and exit"),
OPT_INTEGER(0, "max-strings-per-rule", &max_strings_per_rule,
"set maximum number of strings per rule (default=10000)", "NUMBER"),
OPT_INTEGER(
0,
"max-strings-per-rule",
&max_strings_per_rule,
"set maximum number of strings per rule (default=10000)",
"NUMBER"),
OPT_BOOLEAN('w', "no-warnings", &ignore_warnings,
"disable warnings"),
OPT_BOOLEAN('w', "no-warnings", &ignore_warnings, "disable warnings"),
OPT_BOOLEAN('v', "version", &show_version,
"show version information"),
OPT_END()
};
OPT_BOOLEAN('v', "version", &show_version, "show version information"),
OPT_END()};
static void report_error(
int error_level,
@@ -143,18 +145,11 @@ static void report_error(
else
{
fprintf(
stderr,
"%s(%d): %s: %s\n",
file_name,
line_number,
msg_type,
message);
stderr, "%s(%d): %s: %s\n", file_name, line_number, msg_type, message);
}
}
static bool define_external_variables(
YR_COMPILER* compiler)
static bool define_external_variables(YR_COMPILER* compiler)
{
for (int i = 0; ext_vars[i] != NULL; i++)
{
@@ -177,41 +172,27 @@ static bool define_external_variables(
if (is_float(value))
{
yr_compiler_define_float_variable(
compiler,
identifier,
atof(value));
yr_compiler_define_float_variable(compiler, identifier, atof(value));
}
else if (is_integer(value))
{
yr_compiler_define_integer_variable(
compiler,
identifier,
atoi(value));
yr_compiler_define_integer_variable(compiler, identifier, atoi(value));
}
else if (strcmp(value, "true") == 0 || strcmp(value, "false") == 0)
{
yr_compiler_define_boolean_variable(
compiler,
identifier,
strcmp(value, "true") == 0);
compiler, identifier, strcmp(value, "true") == 0);
}
else
{
yr_compiler_define_string_variable(
compiler,
identifier,
value);
yr_compiler_define_string_variable(compiler, identifier, value);
}
}
return true;
}
int main(
int argc,
const char** argv)
int main(int argc, const char** argv)
{
COMPILER_RESULTS cr;
+88 -178
View File
@@ -30,25 +30,22 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assert.h>
#include <stddef.h>
#include <string.h>
#include <yara/arena.h>
#include <yara/ahocorasick.h>
#include <yara/arena.h>
#include <yara/compiler.h>
#include <yara/error.h>
#include <yara/utils.h>
#include <yara/mem.h>
#include <yara/utils.h>
typedef struct _QUEUE_NODE
{
YR_AC_STATE* value;
struct _QUEUE_NODE* previous;
struct _QUEUE_NODE* next;
struct _QUEUE_NODE* previous;
struct _QUEUE_NODE* next;
} QUEUE_NODE;
typedef struct _QUEUE
{
QUEUE_NODE* head;
@@ -56,23 +53,18 @@ typedef struct _QUEUE
} QUEUE;
//
// _yr_ac_queue_push
//
// Pushes a state in a queue.
////////////////////////////////////////////////////////////////////////////////
// Pushes an automaton state into the tail of a queue.
//
// Args:
// QUEUE* queue - The queue
// YR_AC_STATE* state - The state
// queue: Pointer to the queue.
// state: Pointer to the state being pushed into the queue.
//
// Returns:
// ERROR_SUCCESS if succeed or the corresponding error code otherwise.
// ERROR_SUCCESS
// ERROR_INSUFFICIENT_MEMORY
//
static int _yr_ac_queue_push(
QUEUE* queue,
YR_AC_STATE* value)
static int _yr_ac_queue_push(QUEUE* queue, YR_AC_STATE* state)
{
QUEUE_NODE* pushed_node;
@@ -83,11 +75,11 @@ static int _yr_ac_queue_push(
pushed_node->previous = queue->tail;
pushed_node->next = NULL;
pushed_node->value = value;
pushed_node->value = state;
if (queue->tail != NULL)
queue->tail->next = pushed_node;
else // queue is empty
else // queue is empty
queue->head = pushed_node;
queue->tail = pushed_node;
@@ -95,21 +87,16 @@ static int _yr_ac_queue_push(
return ERROR_SUCCESS;
}
//
// _yr_ac_queue_pop
//
// Pops a state from a queue.
////////////////////////////////////////////////////////////////////////////////
// Pops an automaton state from the head of a queue.
//
// Args:
// QUEUE* queue - The queue
// queue: Pointer to the queue.
//
// Returns:
// Pointer to the poped state.
// Pointer to the poped state.
//
static YR_AC_STATE* _yr_ac_queue_pop(
QUEUE* queue)
static YR_AC_STATE* _yr_ac_queue_pop(QUEUE* queue)
{
YR_AC_STATE* result;
QUEUE_NODE* popped_node;
@@ -122,7 +109,7 @@ static YR_AC_STATE* _yr_ac_queue_pop(
if (queue->head)
queue->head->previous = NULL;
else // queue is empty
else // queue is empty
queue->tail = NULL;
result = popped_node->value;
@@ -131,43 +118,32 @@ static YR_AC_STATE* _yr_ac_queue_pop(
return result;
}
//
// _yr_ac_queue_is_empty
//
////////////////////////////////////////////////////////////////////////////////
// Checks if a queue is empty.
//
// Args:
// QUEUE* queue - The queue
// queue: Pointer to the queue.
//
// Returns:
// true if queue is empty, false otherwise.
// true if queue is empty, false otherwise.
//
static int _yr_ac_queue_is_empty(
QUEUE* queue)
static int _yr_ac_queue_is_empty(QUEUE* queue)
{
return queue->head == NULL;
}
//
// _yr_ac_next_state
//
////////////////////////////////////////////////////////////////////////////////
// Given an automaton state and an input symbol, returns the new state
// after reading the input symbol.
//
// Args:
// YR_AC_STATE* state - Automaton state
// uint8_t input - Input symbol
// state: Pointer to automaton state.
// input: Input symbol.
//
// Returns:
// Pointer to the next automaton state.
//
static YR_AC_STATE* _yr_ac_next_state(
YR_AC_STATE* state,
uint8_t input)
static YR_AC_STATE* _yr_ac_next_state(YR_AC_STATE* state, uint8_t input)
{
YR_AC_STATE* next_state = state->first_child;
@@ -182,24 +158,19 @@ static YR_AC_STATE* _yr_ac_next_state(
return NULL;
}
//
// _yr_ac_state_create
//
////////////////////////////////////////////////////////////////////////////////
// Creates a new automaton state, the automaton will transition from
// the given state to the new state after reading the input symbol.
//
// Args:
// YR_AC_STATE* state - Origin state
// uint8_t input - Input symbol
// state: Pointer to the origin state.
// input: Input symbol.
//
// Returns:
// YR_AC_STATE* pointer to the newly allocated state or NULL in case
// of error.
static YR_AC_STATE* _yr_ac_state_create(
YR_AC_STATE* state,
uint8_t input)
//
static YR_AC_STATE* _yr_ac_state_create(YR_AC_STATE* state, uint8_t input)
{
YR_AC_STATE* new_state = (YR_AC_STATE*) yr_malloc(sizeof(YR_AC_STATE));
@@ -218,13 +189,10 @@ static YR_AC_STATE* _yr_ac_state_create(
return new_state;
}
////////////////////////////////////////////////////////////////////////////////
// Destroys an automaton state.
//
// _yr_ac_state_destroy
//
static int _yr_ac_state_destroy(
YR_AC_STATE* state)
static int _yr_ac_state_destroy(YR_AC_STATE* state)
{
YR_AC_STATE* child_state = state->first_child;
@@ -240,16 +208,13 @@ static int _yr_ac_state_destroy(
return ERROR_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Create failure links for each automaton state.
//
// _yr_ac_create_failure_links
// This function must be called after all the strings have been added to the
// automaton with yr_ac_add_string.
//
// Create failure links for each automaton state. This function must
// be called after all the strings have been added to the automaton.
//
static int _yr_ac_create_failure_links(
YR_AC_AUTOMATON* automaton)
static int _yr_ac_create_failure_links(YR_AC_AUTOMATON* automaton)
{
YR_AC_STATE* current_state;
YR_AC_STATE* failure_state;
@@ -281,18 +246,15 @@ static int _yr_ac_create_failure_links(
// Traverse the trie in BFS order calculating the failure link
// for each state.
while (!_yr_ac_queue_is_empty(&queue))
{
current_state = _yr_ac_queue_pop(&queue);
match = yr_arena_ref_to_ptr(
automaton->arena, &current_state->matches_ref);
match = yr_arena_ref_to_ptr(automaton->arena, &current_state->matches_ref);
if (match != NULL)
{
// Find the last match in the list of matches.
while (match->next != NULL)
match = match->next;
while (match->next != NULL) match = match->next;
if (match->backtrack > 0)
match->next = yr_arena_ref_to_ptr(
@@ -315,8 +277,7 @@ static int _yr_ac_create_failure_links(
while (1)
{
temp_state = _yr_ac_next_state(
failure_state, transition_state->input);
temp_state = _yr_ac_next_state(failure_state, transition_state->input);
if (temp_state != NULL)
{
@@ -334,8 +295,7 @@ static int _yr_ac_create_failure_links(
assert(match != NULL);
// Find the last match in the list of matches.
while (match->next != NULL)
match = match->next;
while (match->next != NULL) match = match->next;
match->next = yr_arena_ref_to_ptr(
automaton->arena, &temp_state->matches_ref);
@@ -355,28 +315,22 @@ static int _yr_ac_create_failure_links(
failure_state = failure_state->failure;
}
}
} // while(1)
} // while(1)
transition_state = transition_state->siblings;
}
} // while(!__yr_ac_queue_is_empty(&queue))
} // while(!__yr_ac_queue_is_empty(&queue))
return ERROR_SUCCESS;
}
//
// _yr_ac_transitions_subset
//
////////////////////////////////////////////////////////////////////////////////
// Returns true if the transitions for state s2 are a subset of the transitions
// for state s1. In other words, if at state s2 input X is accepted, it must be
// accepted in s1 too.
//
static bool _yr_ac_transitions_subset(
YR_AC_STATE* s1,
YR_AC_STATE* s2)
static bool _yr_ac_transitions_subset(YR_AC_STATE* s1, YR_AC_STATE* s2)
{
uint8_t set[32];
@@ -403,17 +357,12 @@ static bool _yr_ac_transitions_subset(
return true;
}
//
// _yr_ac_optimize_failure_links
//
////////////////////////////////////////////////////////////////////////////////
// Removes unnecessary failure links.
//
static int _yr_ac_optimize_failure_links(
YR_AC_AUTOMATON* automaton)
static int _yr_ac_optimize_failure_links(YR_AC_AUTOMATON* automaton)
{
QUEUE queue = { NULL, NULL};
QUEUE queue = {NULL, NULL};
// Push root's children.
YR_AC_STATE* root_state = automaton->root;
@@ -448,16 +397,12 @@ static int _yr_ac_optimize_failure_links(
return ERROR_SUCCESS;
}
//
// _yr_ac_find_suitable_transition_table_slot
//
////////////////////////////////////////////////////////////////////////////////
// Find a place within the automaton's transition table where the transitions
// for the given state can be put. The function first create a bitmask for the
// state's transition table, then searches for an offset within the automaton's
// bitmask where the state's bitmask can be put without bit collisions.
//
static int _yr_ac_find_suitable_transition_table_slot(
YR_AC_AUTOMATON* automaton,
YR_ARENA* arena,
@@ -497,39 +442,31 @@ static int _yr_ac_find_suitable_transition_table_slot(
if (*slot > automaton->tables_size - 257)
{
FAIL_ON_ERROR(yr_arena_allocate_zeroed_memory(
arena,
YR_AC_TRANSITION_TABLE,
257 * sizeof(YR_AC_TRANSITION),
NULL));
FAIL_ON_ERROR(yr_arena_allocate_zeroed_memory(
arena, YR_AC_TRANSITION_TABLE, 257 * sizeof(YR_AC_TRANSITION), NULL));
FAIL_ON_ERROR(yr_arena_allocate_zeroed_memory(
arena,
YR_AC_STATE_MATCHES_TABLE,
257 * sizeof(uint8_t*),
NULL));
FAIL_ON_ERROR(yr_arena_allocate_zeroed_memory(
arena, YR_AC_STATE_MATCHES_TABLE, 257 * sizeof(uint8_t*), NULL));
size_t bm_len = YR_BITMASK_SIZE(automaton->tables_size) *
sizeof(YR_BITMASK);
size_t bm_len = YR_BITMASK_SIZE(automaton->tables_size) *
sizeof(YR_BITMASK);
size_t bm_len_incr = YR_BITMASK_SIZE(257) * sizeof(YR_BITMASK);
size_t bm_len_incr = YR_BITMASK_SIZE(257) * sizeof(YR_BITMASK);
automaton->bitmask = yr_realloc(automaton->bitmask, bm_len + bm_len_incr);
automaton->bitmask = yr_realloc(automaton->bitmask, bm_len + bm_len_incr);
if (automaton->bitmask == NULL)
return ERROR_INSUFFICIENT_MEMORY;
if (automaton->bitmask == NULL)
return ERROR_INSUFFICIENT_MEMORY;
memset((uint8_t*) automaton->bitmask + bm_len, 0, bm_len_incr);
memset((uint8_t*) automaton->bitmask + bm_len, 0, bm_len_incr);
automaton->tables_size += 257;
automaton->tables_size += 257;
}
return ERROR_SUCCESS;
}
//
// _yr_ac_build_transition_table
//
////////////////////////////////////////////////////////////////////////////////
// Builds the transition table for the automaton. The transition table (T) is a
// large array of 32-bits integers. Each state in the automaton is represented
// by an index S within the array. The integer stored in T[S] is the failure
@@ -584,9 +521,8 @@ static int _yr_ac_find_suitable_transition_table_slot(
// +-----------------------+---------+
//
// A more detailed description can be found in: http://goo.gl/lE6zG
static int _yr_ac_build_transition_table(
YR_AC_AUTOMATON* automaton)
//
static int _yr_ac_build_transition_table(YR_AC_AUTOMATON* automaton)
{
YR_AC_TRANSITION* t_table;
uint32_t* m_table;
@@ -596,7 +532,7 @@ static int _yr_ac_build_transition_table(
uint32_t slot;
QUEUE queue = { NULL, NULL };
QUEUE queue = {NULL, NULL};
// Both t_table and m_table have 512 slots initially, which is enough for the
// root node's transition table.
@@ -706,10 +642,7 @@ static int _yr_ac_build_transition_table(
return ERROR_SUCCESS;
}
//
// _yr_ac_print_automaton_state
//
////////////////////////////////////////////////////////////////////////////////
// Prints automaton state for debug purposes. This function is invoked by
// yr_ac_print_automaton, is not intended to be used stand-alone.
//
@@ -722,20 +655,23 @@ static void _yr_ac_print_automaton_state(
YR_AC_MATCH* match;
YR_AC_STATE* child_state;
for (int i = 0; i < state->depth; i++)
printf(" ");
for (int i = 0; i < state->depth; i++) printf(" ");
child_state = state->first_child;
child_count = 0;
while(child_state != NULL)
while (child_state != NULL)
{
child_count++;
child_state = child_state->siblings;
}
printf("%p childs:%d depth:%d failure:%p",
state, child_count, state->depth, state->failure);
printf(
"%p childs:%d depth:%d failure:%p",
state,
child_count,
state->depth,
state->failure);
match = yr_arena_ref_to_ptr(automaton->arena, &state->matches_ref);
@@ -743,8 +679,7 @@ static void _yr_ac_print_automaton_state(
{
printf("\n");
for (int i = 0; i < state->depth + 1; i++)
printf(" ");
for (int i = 0; i < state->depth + 1; i++) printf(" ");
printf("%s = ", match->string->identifier);
@@ -783,23 +718,17 @@ static void _yr_ac_print_automaton_state(
child_state = state->first_child;
while(child_state != NULL)
while (child_state != NULL)
{
_yr_ac_print_automaton_state(automaton, child_state);
child_state = child_state->siblings;
}
}
//
// yr_ac_automaton_create
//
////////////////////////////////////////////////////////////////////////////////
// Creates a new automaton
//
int yr_ac_automaton_create(
YR_ARENA* arena,
YR_AC_AUTOMATON** automaton)
int yr_ac_automaton_create(YR_ARENA* arena, YR_AC_AUTOMATON** automaton)
{
YR_AC_AUTOMATON* new_automaton;
YR_AC_STATE* root_state;
@@ -832,15 +761,10 @@ int yr_ac_automaton_create(
return ERROR_SUCCESS;
}
//
// yr_ac_automaton_destroy
//
////////////////////////////////////////////////////////////////////////////////
// Destroys automaton
//
int yr_ac_automaton_destroy(
YR_AC_AUTOMATON* automaton)
int yr_ac_automaton_destroy(YR_AC_AUTOMATON* automaton)
{
_yr_ac_state_destroy(automaton->root);
@@ -850,14 +774,10 @@ int yr_ac_automaton_destroy(
return ERROR_SUCCESS;
}
//
// yr_ac_add_string
//
////////////////////////////////////////////////////////////////////////////////
// Adds a string to the automaton. This function is invoked once for each
// string defined in the rules.
//
int yr_ac_add_string(
YR_AC_AUTOMATON* automaton,
YR_STRING* string,
@@ -919,29 +839,20 @@ int yr_ac_add_string(
return ERROR_SUCCESS;
}
//
// yr_ac_compile
//
////////////////////////////////////////////////////////////////////////////////
// Compiles the Aho-Corasick automaton, the resulting data structures are
// are written in the provided arena.
//
int yr_ac_compile(
YR_AC_AUTOMATON* automaton,
YR_ARENA* arena)
int yr_ac_compile(YR_AC_AUTOMATON* automaton, YR_ARENA* arena)
{
FAIL_ON_ERROR(_yr_ac_create_failure_links(automaton));
FAIL_ON_ERROR(_yr_ac_optimize_failure_links(automaton));
FAIL_ON_ERROR(_yr_ac_build_transition_table(automaton));
return ERROR_SUCCESS;
}
//
// yr_ac_print_automaton
//
////////////////////////////////////////////////////////////////////////////////
// Prints automaton for debug purposes.
//
void yr_ac_print_automaton(YR_AC_AUTOMATON* automaton)
@@ -950,4 +861,3 @@ void yr_ac_print_automaton(YR_AC_AUTOMATON* automaton)
_yr_ac_print_automaton_state(automaton, automaton->root);
printf("-------------------------------------------------------\n");
}
+127 -149
View File
@@ -27,13 +27,11 @@ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdarg.h>
#include <stddef.h>
#include <yara/arena.h>
#include <yara/mem.h>
#include <yara/error.h>
#include <yara/mem.h>
typedef struct YR_ARENA_FILE_HEADER YR_ARENA_FILE_HEADER;
typedef struct YR_ARENA_FILE_BUFFER YR_ARENA_FILE_BUFFER;
@@ -56,10 +54,7 @@ struct YR_ARENA_FILE_BUFFER
#pragma pack(pop)
//
// _yr_arena_make_ptr_relocatable
//
////////////////////////////////////////////////////////////////////////////////
// Tells the arena that certain offsets within a buffer contain relocatable
// pointers. The offsets are passed as a vararg list where the end of the
// list is indicated by the special value EOL (-1), offsets in the list are
@@ -67,15 +62,15 @@ struct YR_ARENA_FILE_BUFFER
// buffer.
//
// Args:
// [in] YR_ARENA* arena - Pointer the arena.
// [in] uint32_t buffer_id - Buffer number.
// [in] size_t base_offset - Base offset.
// [in] va_list offsets - List of offsets relative to base offset.
// arena: Pointer the arena.
// buffer_id: Buffer number.
// base_offset: Base offset.
// offsets: List of offsets relative to base offset.
//
// Returns:
// ERROR_SUCCESS if succeed or the corresponding error code otherwise.
// ERROR_SUCCESS
// ERROR_INSUFFICIENT_MEMORY
//
static int _yr_arena_make_ptr_relocatable(
YR_ARENA* arena,
uint32_t buffer_id,
@@ -113,26 +108,24 @@ static int _yr_arena_make_ptr_relocatable(
}
// Flags for _yr_arena_allocate_memory.
#define YR_ARENA_ZERO_MEMORY 1
#define YR_ARENA_ZERO_MEMORY 1
//
// _yr_arena_allocate_memory
//
////////////////////////////////////////////////////////////////////////////////
// Allocates memory in a buffer within the arena.
//
// Args:
// [in] YR_ARENA* arena - Pointer to the arena.
// [in] int flags - Flags.
// [in] uint32_t buffer_id - Buffer number.
// [in] size_t size - Size of the region to be allocated.
// [out] size_t* offset - Pointer to a variable where the function puts
// the offset within the buffer of the allocated
// region. The pointer can be NULL.
// arena: Pointer to the arena.
// flags: Flags. The only supported flag so far is YR_ARENA_ZERO_MEMORY.
// buffer_id: Buffer number.
// size : Size of the region to be allocated.
// [out] ref: Pointer to a YR_ARENA_REF that will be updated with the
// reference to the newly allocated region. The pointer can be
/// NULL.
// Returns:
// ERROR_SUCCESS if succeed or the corresponding error code if otherwise.
// ERROR_SUCCESS
// ERROR_INVALID_ARGUMENT
// ERROR_INSUFFICIENT_MEMORY
//
static int _yr_arena_allocate_memory(
YR_ARENA* arena,
int flags,
@@ -153,32 +146,32 @@ static int _yr_arena_allocate_memory(
{
size_t new_size = (b->size == 0) ? arena->initial_buffer_size : b->size * 2;
while (new_size < b->used + size)
new_size *= 2;
while (new_size < b->used + size) new_size *= 2;
uint8_t* new_data = yr_realloc(b->data, new_size);
if (new_data == NULL)
return ERROR_INSUFFICIENT_MEMORY;
// When yr_realloc uses the Windows API (HeapAlloc, HeapReAlloc) under the
// hood this is not necessary because HeapReAlloc already sets the new
// memory to zero.
#if !defined(_WIN32) && !defined(__CYGWIN__)
// When yr_realloc uses the Windows API (HeapAlloc, HeapReAlloc) it is not
// necessary to set the memory to zero because the API is called with the
// HEAP_ZERO_MEMORY flag.
#if !defined(_WIN32) && !defined(__CYGWIN__)
if (flags & YR_ARENA_ZERO_MEMORY)
memset(new_data + b->used, 0, new_size - b->used);
#endif
#endif
YR_RELOC* reloc = arena->reloc_list_head;
while (reloc != NULL)
{
// If the reloc entry is for the same buffer that is being relocated,
// the base pointer that we use to access the buffer must be new_data,
// as arena->buffers[reloc->buffer_id].data which is the same than
// b->data can't be accessed anymore after the call to yr_realloc.
uint8_t* base = buffer_id == reloc->buffer_id ?
new_data : arena->buffers[reloc->buffer_id].data;
// the base pointer that we use to access the buffer must be new_data
// as arena->buffers[reloc->buffer_id].data (which is the same than
// b->data) can't be accessed anymore after the call to yr_realloc.
uint8_t* base = buffer_id == reloc->buffer_id
? new_data
: arena->buffers[reloc->buffer_id].data;
// reloc_address holds the address inside the buffer where the pointer
// to be relocated resides.
@@ -213,20 +206,18 @@ static int _yr_arena_allocate_memory(
return ERROR_SUCCESS;
}
//
// yr_arena_create
//
////////////////////////////////////////////////////////////////////////////////
// Creates an arena with the specified number of buffers.
//
// Args:
// [in] int num_buffers - Number of buffers
// [in] size_t initial_buffer_size - Initial size of each buffer.
// [out] YR_ARENA** arena - Address of a YR_ARENA* pointer that
// will receive the address of the newly
// created arena.
// num_buffers: Number of buffers.
// initial_buffer_size: Initial size of each buffer.
// [out] arena: Address of a YR_ARENA* pointer that will receive the address
// of the newly created arena.
// Returns:
// ERROR_SUCCESS
// ERROR_INSUFFICIENT_MEMORY
//
int yr_arena_create(
int number_of_buffers,
size_t initial_buffer_size,
@@ -246,24 +237,26 @@ int yr_arena_create(
return ERROR_SUCCESS;
}
void yr_arena_acquire(
YR_ARENA* arena)
void yr_arena_acquire(YR_ARENA* arena)
{
arena->xrefs++;
}
////////////////////////////////////////////////////////////////////////////////
// Releases the arena.
//
// yr_arena_release
//
// Releases the arena. If the number of cross-references to this arena drops
// to zero the arena is destroyed and all its resources are freed.
// Decrements the cross-references counter for the arena, if the number of
// cross-references reaches zero the arena is destroyed and all its resources
// are freed.
//
// Args:
// [in] YR_ARENA* arena - Pointer to the arena.
// arena :Pointer to the arena.
//
int yr_arena_release(
YR_ARENA* arena)
// Returns:
// ERROR_SUCCESS
// ERROR_INSUFFICIENT_MEMORY
//
int yr_arena_release(YR_ARENA* arena)
{
arena->xrefs--;
@@ -290,18 +283,45 @@ int yr_arena_release(
return ERROR_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Allocates memory in a buffer within the arena.
//
// Args:
// arena: Pointer to the arena.
// buffer_id: Buffer number.
// size : Size of the region to be allocated.
// [out] offset: Pointer to a variable where the function puts the offset
// within the buffer of the allocated region. The pointer can
// be NULL.
// Returns:
// ERROR_SUCCESS
// ERROR_INVALID_ARGUMENT
// ERROR_INSUFFICIENT_MEMORY
//
int yr_arena_allocate_memory(
YR_ARENA* arena,
uint32_t buffer_id,
size_t size,
YR_ARENA_REF* ref)
{
return _yr_arena_allocate_memory(
arena, 0, buffer_id, size, ref);
return _yr_arena_allocate_memory(arena, 0, buffer_id, size, ref);
}
////////////////////////////////////////////////////////////////////////////////
// Allocates memory in a buffer within the arena and fill it with zeroes.
//
// Args:
// arena: Pointer to the arena.
// buffer_id: Buffer number.
// size : Size of the region to be allocated.
// [out] offset: Pointer to a variable where the function puts the offset
// within the buffer of the allocated region. The pointer can
// be NULL.
// Returns:
// ERROR_SUCCESS
// ERROR_INVALID_ARGUMENT
// ERROR_INSUFFICIENT_MEMORY
//
int yr_arena_allocate_zeroed_memory(
YR_ARENA* arena,
uint32_t buffer_id,
@@ -312,10 +332,7 @@ int yr_arena_allocate_zeroed_memory(
arena, YR_ARENA_ZERO_MEMORY, buffer_id, size, ref);
}
//
// yr_arena_allocate_struct
//
////////////////////////////////////////////////////////////////////////////////
// Allocates a structure within the arena. This function is similar to
// yr_arena_allocate_memory but additionally receives a variable-length
// list of offsets within the structure where pointers reside. This allows
@@ -334,21 +351,20 @@ int yr_arena_allocate_zeroed_memory(
// EOL);
//
// Args:
// [in] YR_ARENA* arena - Pointer to the arena.
// [in] uint32_t buffer_id - Buffer number.
// [in] size_t size - Size of the region to be allocated.
// [out] YR_ARENA_REF* ref - Pointer to a reference that will point to the
// newly allocated structure when the function
// returns. The pointer can be NULL if you don't
// need the reference.
// ... - Variable number of offsets relative to the
// beginning of the struct. Offsets are of type
// size_t.
// arena: Pointer to the arena.
// buffer_id: Buffer number.
// size: Size of the region to be allocated.
// [out] ref: Pointer to a reference that will point to the newly allocated
// structure when the function returns. The pointer can be NULL
// if you don't need the reference.
// ... Variable number of offsets relative to the beginning of the struct.
// These offsets are of type size_t.
//
// Returns:
// ERROR_SUCCESS if succeed or the corresponding error code otherwise.
// ERROR_SUCCESS
// ERROR_INVALID_ARGUMENT
// ERROR_INSUFFICIENT_MEMORY
//
int yr_arena_allocate_struct(
YR_ARENA* arena,
uint32_t buffer_id,
@@ -381,7 +397,6 @@ int yr_arena_allocate_struct(
return result;
}
void* yr_arena_get_ptr(
YR_ARENA* arena,
uint32_t buffer_id,
@@ -393,21 +408,14 @@ void* yr_arena_get_ptr(
return arena->buffers[buffer_id].data + offset;
}
yr_arena_off_t yr_arena_get_current_offset(
YR_ARENA* arena,
uint32_t buffer_id)
yr_arena_off_t yr_arena_get_current_offset(YR_ARENA* arena, uint32_t buffer_id)
{
assert(buffer_id < arena->num_buffers);
return arena->buffers[buffer_id].used;
}
int yr_arena_ptr_to_ref(
YR_ARENA* arena,
const void* address,
YR_ARENA_REF* ref)
int yr_arena_ptr_to_ref(YR_ARENA* arena, const void* address, YR_ARENA_REF* ref)
{
*ref = YR_ARENA_NULL_REF;
@@ -417,7 +425,7 @@ int yr_arena_ptr_to_ref(
for (int i = 0; i < arena->num_buffers; ++i)
{
if ((uint8_t*) address >= arena->buffers[i].data &&
(uint8_t*) address < arena->buffers[i].data + arena->buffers[i].used)
(uint8_t*) address < arena->buffers[i].data + arena->buffers[i].used)
{
ref->buffer_id = i;
ref->offset = (uint8_t*) address - arena->buffers[i].data;
@@ -428,58 +436,45 @@ int yr_arena_ptr_to_ref(
return 0;
}
void* yr_arena_ref_to_ptr(
YR_ARENA* arena,
YR_ARENA_REF* ref)
void* yr_arena_ref_to_ptr(YR_ARENA* arena, YR_ARENA_REF* ref)
{
if (YR_ARENA_IS_NULL_REF(*ref))
return NULL;
#if defined(__arm__)
#if defined(__arm__)
YR_ARENA_REF tmp_ref;
memcpy(&tmp_ref, ref, sizeof(YR_ARENA_REF));
ref = &tmp_ref;
#endif
#endif
return yr_arena_get_ptr(arena, ref->buffer_id, ref->offset);
}
//
// yr_arena_make_ptr_relocatable
//
////////////////////////////////////////////////////////////////////////////////
// Tells the arena that certain addresses contains a relocatable pointer.
//
// Args:
// YR_ARENA* arena - Pointer to the arena.
// uint32_t buffer_id - Buffer number.
// ... - Variable number of size_t arguments with offsets
// within the buffer.
// arena: Pointer to the arena.
// buffer_id: Buffer number.
// ... : Variable number of size_t arguments with offsets within the buffer.
//
// Returns:
// ERROR_SUCCESS if succeed or the corresponding error code otherwise.
//
int yr_arena_make_ptr_relocatable(
YR_ARENA* arena,
uint32_t buffer_id,
...)
int yr_arena_make_ptr_relocatable(YR_ARENA* arena, uint32_t buffer_id, ...)
{
int result;
va_list offsets;
va_start(offsets, buffer_id);
result = _yr_arena_make_ptr_relocatable(
arena, buffer_id, 0, offsets);
result = _yr_arena_make_ptr_relocatable(arena, buffer_id, 0, offsets);
va_end(offsets);
return result;
}
int yr_arena_write_data(
YR_ARENA* arena,
uint32_t buffer_id,
@@ -504,42 +499,32 @@ int yr_arena_write_data(
return ERROR_SUCCESS;
}
int yr_arena_write_string(
YR_ARENA* arena,
uint32_t buffer_id,
const char* string,
YR_ARENA_REF* ref)
{
return yr_arena_write_data(
arena, buffer_id, string, strlen(string) + 1, ref);
return yr_arena_write_data(arena, buffer_id, string, strlen(string) + 1, ref);
}
int yr_arena_write_uint32(
YR_ARENA* arena,
uint32_t buffer_id,
uint32_t integer,
YR_ARENA_REF* ref)
{
return yr_arena_write_data(
arena, buffer_id, &integer, sizeof(integer), ref);
return yr_arena_write_data(arena, buffer_id, &integer, sizeof(integer), ref);
}
int yr_arena_load_stream(
YR_STREAM* stream,
YR_ARENA** arena)
int yr_arena_load_stream(YR_STREAM* stream, YR_ARENA** arena)
{
YR_ARENA_FILE_HEADER hdr;
if (yr_stream_read(&hdr, sizeof(hdr), 1, stream) != 1)
return ERROR_INVALID_FILE;
if (hdr.magic[0] != 'Y' ||
hdr.magic[1] != 'A' ||
hdr.magic[2] != 'R' ||
if (hdr.magic[0] != 'Y' || hdr.magic[1] != 'A' || hdr.magic[2] != 'R' ||
hdr.magic[3] != 'A')
{
return ERROR_INVALID_FILE;
@@ -571,8 +556,7 @@ int yr_arena_load_stream(
YR_ARENA_REF ref;
FAIL_ON_ERROR_WITH_CLEANUP(
yr_arena_allocate_memory(
new_arena, i, buffers[i].size, &ref),
yr_arena_allocate_memory(new_arena, i, buffers[i].size, &ref),
yr_arena_release(new_arena))
void* ptr = yr_arena_get_ptr(new_arena, i, ref.offset);
@@ -604,10 +588,7 @@ int yr_arena_load_stream(
FAIL_ON_ERROR_WITH_CLEANUP(
yr_arena_make_ptr_relocatable(
new_arena,
ref.buffer_id,
ref.offset,
EOL),
new_arena, ref.buffer_id, ref.offset, EOL),
yr_arena_release(new_arena))
}
@@ -616,10 +597,7 @@ int yr_arena_load_stream(
return ERROR_SUCCESS;
}
int yr_arena_save_stream(
YR_ARENA* arena,
YR_STREAM* stream)
int yr_arena_save_stream(YR_ARENA* arena, YR_STREAM* stream)
{
YR_ARENA_FILE_HEADER hdr;
@@ -636,14 +614,14 @@ int yr_arena_save_stream(
// The first buffer in the file is after the header and the buffer table,
// calculate its offset accordingly.
uint64_t offset = sizeof(YR_ARENA_FILE_HEADER)
+ sizeof(YR_ARENA_FILE_BUFFER) * arena->num_buffers;
uint64_t offset = sizeof(YR_ARENA_FILE_HEADER) +
sizeof(YR_ARENA_FILE_BUFFER) * arena->num_buffers;
for (int i = 0; i < arena->num_buffers; ++i)
{
YR_ARENA_FILE_BUFFER buffer = {
.offset = offset,
.size = arena->buffers[i].used,
.offset = offset,
.size = arena->buffers[i].used,
};
if (yr_stream_write(&buffer, sizeof(buffer), 1, stream) != 1)
@@ -663,19 +641,19 @@ int yr_arena_save_stream(
{
// reloc_ptr is a pointer to the relocatable pointer, while *reloc_ptr
// is the relocatable pointer itself.
void** reloc_ptr = (void**) (
arena->buffers[reloc->buffer_id].data + reloc->offset);
void** reloc_ptr =
(void**) (arena->buffers[reloc->buffer_id].data + reloc->offset);
YR_ARENA_REF ref;
#if !defined(NDEBUG)
#if !defined(NDEBUG)
int found = yr_arena_ptr_to_ref(arena, *reloc_ptr, &ref);
// yr_arena_ptr_to_ref returns 0 if the relocatable pointer is pointing
// outside the arena, this should not happen.
assert(found);
#else
#else
yr_arena_ptr_to_ref(arena, *reloc_ptr, &ref);
#endif
#endif
// Replace the relocatable pointer with a reference that holds information
// about the buffer and offset where the relocatable pointer is pointing to.
@@ -701,15 +679,15 @@ int yr_arena_save_stream(
while (reloc != NULL)
{
YR_ARENA_REF ref = {
.buffer_id = reloc->buffer_id,
.offset = reloc->offset,
.buffer_id = reloc->buffer_id,
.offset = reloc->offset,
};
if (yr_stream_write(&ref, sizeof(ref), 1, stream) != 1)
return ERROR_WRITING_FILE;
void** reloc_ptr = (void**) (
arena->buffers[reloc->buffer_id].data + reloc->offset);
void** reloc_ptr =
(void**) (arena->buffers[reloc->buffer_id].data + reloc->offset);
// reloc_ptr is now pointing to a YR_ARENA_REF.
YR_ARENA_REF* ref_ptr = (YR_ARENA_REF*) reloc_ptr;
+302 -428
View File
File diff suppressed because it is too large Load Diff
+33 -56
View File
@@ -28,7 +28,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <string.h>
#include <yara/base64.h>
#include <yara/error.h>
#include <yara/mem.h>
@@ -36,9 +35,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <yara/sizedstr.h>
//
// _yr_modified_base64_encode
//
////////////////////////////////////////////////////////////////////////////////
// Given a pointer to a SIZED_STRING append 0, 1 or 2 bytes and base64 encode
// the string. The number of padding bytes is returned in "pad" and the caller
// is expected to trim the appropriate number of leading and trailing bytes.
@@ -80,8 +77,7 @@ static SIZED_STRING* _yr_modified_base64_encode(
// Prepend appropriate number of bytes and copy remaining input bytes into
// temporary buffer.
for (j = 0; j < i; j++)
tmp[j] = 'A';
for (j = 0; j < i; j++) tmp[j] = 'A';
memcpy(tmp + j, src, len);
src = tmp;
@@ -119,8 +115,7 @@ static SIZED_STRING* _yr_modified_base64_encode(
return out;
}
//
////////////////////////////////////////////////////////////////////////////////
// Given a base64 encoded string, return a new string with leading and trailing
// bytes stripped appropriately. The number of leading bytes to skip is always
// (i + 1) or zero when no leading bytes are added and the number of trailing
@@ -174,30 +169,17 @@ static SIZED_STRING* _yr_base64_get_base64_substring(
// RE metacharacters which need to be escaped when generating the final RE.
#define IS_METACHAR(x) \
(x == '\\' || \
x == '^' || \
x == '$' || \
x == '|' || \
x == '(' || \
x == ')' || \
x == '[' || \
x == ']' || \
x == '*' || \
x == '?' || \
x == '{' || \
x == ',' || \
x == '.' || \
x == '+' || \
x == '}')
#define IS_METACHAR(x) \
(x == '\\' || x == '^' || x == '$' || x == '|' || x == '(' || x == ')' || \
x == '[' || x == ']' || x == '*' || x == '?' || x == '{' || x == ',' || \
x == '.' || x == '+' || x == '}')
//
////////////////////////////////////////////////////////////////////////////////
// Given a SIZED_STRING return the number of characters which will need to be
// escaped when generating the final string to pass to the regexp compiler.
//
static int _yr_base64_count_escaped(
SIZED_STRING* str)
static int _yr_base64_count_escaped(SIZED_STRING* str)
{
uint32_t i;
int c = 0;
@@ -214,7 +196,7 @@ static int _yr_base64_count_escaped(
return c;
}
//
////////////////////////////////////////////////////////////////////////////////
// Create nodes representing the different encodings of a base64 string.
//
static int _yr_base64_create_nodes(
@@ -246,11 +228,11 @@ static int _yr_base64_create_nodes(
// Now take the encoded string and strip the bytes which are affected by
// the leading and trailing bytes of the plaintext.
FAIL_ON_NULL_WITH_CLEANUP(
final_str = _yr_base64_get_base64_substring(encoded_str, wide, i, pad),
{
yr_free(encoded_str);
yr_free(node);
});
final_str = _yr_base64_get_base64_substring(encoded_str, wide, i, pad),
{
yr_free(encoded_str);
yr_free(node);
});
yr_free(encoded_str);
@@ -275,12 +257,10 @@ static int _yr_base64_create_nodes(
return ERROR_SUCCESS;
}
//
////////////////////////////////////////////////////////////////////////////////
// Useful for printing the encoded strings.
//
void _yr_base64_print_nodes(
BASE64_NODE* head)
void _yr_base64_print_nodes(BASE64_NODE* head)
{
size_t i;
BASE64_NODE* p = head;
@@ -302,12 +282,10 @@ void _yr_base64_print_nodes(
return;
}
//
////////////////////////////////////////////////////////////////////////////////
// Destroy a list of base64 nodes.
//
static void _yr_base64_destroy_nodes(
BASE64_NODE* head)
static void _yr_base64_destroy_nodes(BASE64_NODE* head)
{
BASE64_NODE* p = head;
BASE64_NODE* next;
@@ -323,8 +301,7 @@ static void _yr_base64_destroy_nodes(
return;
}
//
////////////////////////////////////////////////////////////////////////////////
// Create the regexp that is the alternatives of each of the strings collected
// in the BASE64_NODE list.
//
@@ -333,12 +310,14 @@ int _yr_base64_create_regexp(
RE_AST** re_ast,
RE_ERROR* re_error)
{
BASE64_NODE* p = head;
char* re_str;
char* s;
uint32_t i;
uint32_t length = 0;
uint32_t c = 0; // The number of nodes in the list, used to know how many '|'.
BASE64_NODE* p = head;
// The number of nodes in the list, used to know how many '|'.
uint32_t c = 0;
while (p != NULL)
{
@@ -386,18 +365,16 @@ int _yr_base64_create_regexp(
*s = '\x00';
// Useful for debugging as long as the string has no NULL bytes in it. ;)
//printf("%s\n", re_str);
// printf("%s\n", re_str);
FAIL_ON_ERROR_WITH_CLEANUP(
yr_re_parse(re_str, re_ast, re_error),
yr_free(re_str));
yr_re_parse(re_str, re_ast, re_error), yr_free(re_str));
yr_free(re_str);
return ERROR_SUCCESS;
}
//
////////////////////////////////////////////////////////////////////////////////
// Given a string and an alphabet, generate the RE_AST suitable for representing
// the different encodings of the string. This means we generate
// "(ABCD|EFGH|IJKL)" and must be careful to escape any special characters as
@@ -427,7 +404,7 @@ int yr_base64_ast_from_string(
{
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_base64_create_nodes(wide_str, modifier.alphabet, 0, &head, &tail),
{
{ // Cleanup
strcpy(error->message, "Failure encoding base64 wide string");
yr_free(wide_str);
_yr_base64_destroy_nodes(head);
@@ -438,7 +415,7 @@ int yr_base64_ast_from_string(
{
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_base64_create_nodes(wide_str, modifier.alphabet, 1, &head, &tail),
{
{ // Cleanup
strcpy(error->message, "Failure encoding base64wide wide string");
yr_free(wide_str);
_yr_base64_destroy_nodes(head);
@@ -454,7 +431,7 @@ int yr_base64_ast_from_string(
{
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_base64_create_nodes(in_str, modifier.alphabet, 0, &head, &tail),
{
{ // Cleanup
strcpy(error->message, "Failure encoding base64 ascii string");
_yr_base64_destroy_nodes(head);
});
@@ -464,7 +441,7 @@ int yr_base64_ast_from_string(
{
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_base64_create_nodes(in_str, modifier.alphabet, 1, &head, &tail),
{
{ // Cleanup
strcpy(error->message, "Failure encoding base64wide ascii string");
_yr_base64_destroy_nodes(head);
});
@@ -478,7 +455,7 @@ int yr_base64_ast_from_string(
{
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_base64_create_nodes(in_str, modifier.alphabet, 0, &head, &tail),
{
{ // Cleanup
strcpy(error->message, "Failure encoding base64 string");
_yr_base64_destroy_nodes(head);
});
@@ -488,7 +465,7 @@ int yr_base64_ast_from_string(
{
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_base64_create_nodes(in_str, modifier.alphabet, 1, &head, &tail),
{
{ // Cleanup
strcpy(error->message, "Failure encoding base64wide string");
_yr_base64_destroy_nodes(head);
});
+13 -17
View File
@@ -28,13 +28,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <assert.h>
#include <yara/utils.h>
#include <yara/bitmask.h>
#include <yara/utils.h>
//
// yr_bitmask_find_non_colliding_offset
//
////////////////////////////////////////////////////////////////////////////////
// Find the smallest offset within bitmask A where bitmask B can be accommodated
// without bit collisions. A collision occurs when both bitmasks have a bit set
// to 1 at the same offset. This function assumes that the first bit in B is 1
@@ -48,18 +45,16 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// updates the value.
//
// Args:
// YR_BITMASK* a - Bitmask A
// YR_BITMASK* b - Bitmask B
// uint32_t len_a - Length of bitmask A in bits
// uint32_t len_b - Length of bitmask B in bits
// uint32_t* off_a - Address of an uint32_t indicating the offset within
// bitmask A where to start searching. In the first call
// to it must point to a 0 value. This function updates
// the value to use it in subsequent calls.
// a: Bitmask A
// b: Bitmask B
// len_a: Length of bitmask A in bits
// len_b: Length of bitmask B in bits
// off_a: Address of an uint32_t indicating the offset within bitmask A where
// to start searching. In the first call to it must point to a 0 value.
// This function updates the value to use it in subsequent calls.
// Returns:
// The smaller offset within bitmask A where bitmask B can be put.
// The smaller offset within bitmask A where bitmask B can be put.
//
uint32_t yr_bitmask_find_non_colliding_offset(
YR_BITMASK* a,
YR_BITMASK* b,
@@ -78,7 +73,8 @@ uint32_t yr_bitmask_find_non_colliding_offset(
// within such slots.
for (i = *off_a / YR_BITMASK_SLOT_BITS;
i <= len_a / YR_BITMASK_SLOT_BITS && a[i] == -1L;
i++);
i++)
;
*off_a = i;
@@ -102,7 +98,7 @@ uint32_t yr_bitmask_find_non_colliding_offset(
if ((i + k <= len_a / YR_BITMASK_SLOT_BITS) && (m & a[i + k]) != 0)
{
found = false;
break ;
break;
}
}
+270 -405
View File
File diff suppressed because it is too large Load Diff
+45 -61
View File
@@ -43,29 +43,21 @@ typedef MD5_CTX yr_md5_ctx;
typedef SHA_CTX yr_sha1_ctx;
typedef SHA256_CTX yr_sha256_ctx;
#define yr_md5_init(ctx) \
MD5_Init(ctx)
#define yr_md5_update(ctx,data,len) \
MD5_Update(ctx,data,len)
#define yr_md5_final(digest,ctx) \
MD5_Final(digest,ctx)
#define yr_md5_init(ctx) MD5_Init(ctx)
#define yr_md5_update(ctx, data, len) MD5_Update(ctx, data, len)
#define yr_md5_final(digest, ctx) MD5_Final(digest, ctx)
#define yr_sha1_init(ctx) \
SHA1_Init(ctx)
#define yr_sha1_update(ctx,data,len) \
SHA1_Update(ctx,data,len)
#define yr_sha1_final(digest,ctx) \
SHA1_Final(digest,ctx)
#define yr_sha1_init(ctx) SHA1_Init(ctx)
#define yr_sha1_update(ctx, data, len) SHA1_Update(ctx, data, len)
#define yr_sha1_final(digest, ctx) SHA1_Final(digest, ctx)
#define yr_sha256_init(ctx) \
SHA256_Init(ctx)
#define yr_sha256_update(ctx,data,len) \
SHA256_Update(ctx,data,len)
#define yr_sha256_final(digest,ctx) \
SHA256_Final(digest,ctx)
#define yr_sha256_init(ctx) SHA256_Init(ctx)
#define yr_sha256_update(ctx, data, len) SHA256_Update(ctx, data, len)
#define yr_sha256_final(digest, ctx) SHA256_Final(digest, ctx)
#elif defined(HAVE_WINCRYPT_H)
#include <windows.h>
#include <wincrypt.h>
HCRYPTPROV yr_cryptprov;
@@ -74,35 +66,36 @@ typedef HCRYPTHASH yr_md5_ctx;
typedef HCRYPTHASH yr_sha1_ctx;
typedef HCRYPTHASH yr_sha256_ctx;
#define yr_md5_init(ctx) \
CryptCreateHash(yr_cryptprov, CALG_MD5, 0, 0, ctx)
#define yr_md5_update(ctx,data,len) \
CryptHashData(*ctx, (const BYTE*)data, len, 0)
#define yr_md5_final(digest,ctx) { \
DWORD len = YR_MD5_LEN; \
CryptGetHashParam(*ctx, HP_HASHVAL, digest, &len, 0); \
CryptDestroyHash(*ctx); \
}
#define yr_md5_init(ctx) CryptCreateHash(yr_cryptprov, CALG_MD5, 0, 0, ctx)
#define yr_md5_update(ctx, data, len) \
CryptHashData(*ctx, (const BYTE*) data, len, 0)
#define yr_md5_final(digest, ctx) \
{ \
DWORD len = YR_MD5_LEN; \
CryptGetHashParam(*ctx, HP_HASHVAL, digest, &len, 0); \
CryptDestroyHash(*ctx); \
}
#define yr_sha1_init(ctx) \
CryptCreateHash(yr_cryptprov, CALG_SHA1, 0, 0, ctx)
#define yr_sha1_update(ctx,data,len) \
CryptHashData(*ctx, (const BYTE*)data, len, 0)
#define yr_sha1_final(digest,ctx) { \
DWORD len = YR_SHA1_LEN; \
CryptGetHashParam(*ctx, HP_HASHVAL, digest, &len, 0); \
CryptDestroyHash(*ctx); \
}
#define yr_sha1_init(ctx) CryptCreateHash(yr_cryptprov, CALG_SHA1, 0, 0, ctx)
#define yr_sha1_update(ctx, data, len) \
CryptHashData(*ctx, (const BYTE*) data, len, 0)
#define yr_sha1_final(digest, ctx) \
{ \
DWORD len = YR_SHA1_LEN; \
CryptGetHashParam(*ctx, HP_HASHVAL, digest, &len, 0); \
CryptDestroyHash(*ctx); \
}
#define yr_sha256_init(ctx) \
CryptCreateHash(yr_cryptprov, CALG_SHA_256, 0, 0, ctx)
#define yr_sha256_update(ctx,data,len) \
CryptHashData(*ctx, (const BYTE*)data, len, 0)
#define yr_sha256_final(digest,ctx) { \
DWORD len = YR_SHA256_LEN; \
CryptGetHashParam(*ctx, HP_HASHVAL, digest, &len, 0); \
CryptDestroyHash(*ctx); \
}
#define yr_sha256_update(ctx, data, len) \
CryptHashData(*ctx, (const BYTE*) data, len, 0)
#define yr_sha256_final(digest, ctx) \
{ \
DWORD len = YR_SHA256_LEN; \
CryptGetHashParam(*ctx, HP_HASHVAL, digest, &len, 0); \
CryptDestroyHash(*ctx); \
}
#elif defined(HAVE_COMMONCRYPTO_COMMONCRYPTO_H)
#include <CommonCrypto/CommonDigest.h>
@@ -111,26 +104,17 @@ typedef CC_MD5_CTX yr_md5_ctx;
typedef CC_SHA1_CTX yr_sha1_ctx;
typedef CC_SHA256_CTX yr_sha256_ctx;
#define yr_md5_init(ctx) \
CC_MD5_Init(ctx)
#define yr_md5_update(ctx,data,len) \
CC_MD5_Update(ctx, data, len)
#define yr_md5_final(digest,ctx) \
CC_MD5_Final(digest, ctx)
#define yr_md5_init(ctx) CC_MD5_Init(ctx)
#define yr_md5_update(ctx, data, len) CC_MD5_Update(ctx, data, len)
#define yr_md5_final(digest, ctx) CC_MD5_Final(digest, ctx)
#define yr_sha1_init(ctx) \
CC_SHA1_Init(ctx)
#define yr_sha1_update(ctx,data,len) \
CC_SHA1_Update(ctx, data, len)
#define yr_sha1_final(digest,ctx) \
CC_SHA1_Final(digest, ctx)
#define yr_sha1_init(ctx) CC_SHA1_Init(ctx)
#define yr_sha1_update(ctx, data, len) CC_SHA1_Update(ctx, data, len)
#define yr_sha1_final(digest, ctx) CC_SHA1_Final(digest, ctx)
#define yr_sha256_init(ctx) \
CC_SHA256_Init(ctx)
#define yr_sha256_update(ctx,data,len) \
CC_SHA256_Update(ctx, data, len)
#define yr_sha256_final(digest,ctx) \
CC_SHA256_Final(digest, ctx)
#define yr_sha256_init(ctx) CC_SHA256_Init(ctx)
#define yr_sha256_update(ctx, data, len) CC_SHA256_Update(ctx, data, len)
#define yr_sha256_final(digest, ctx) CC_SHA256_Final(digest, ctx)
#endif
+12 -10
View File
@@ -36,18 +36,20 @@ uint16_t _yr_bswap16(uint16_t x)
uint32_t _yr_bswap32(uint32_t x)
{
return ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >> 8) |
(((x) & 0x0000ff00) << 8) | (((x) & 0x000000ff) << 24));
return (
(((x) &0xff000000) >> 24) | (((x) &0x00ff0000) >> 8) |
(((x) &0x0000ff00) << 8) | (((x) &0x000000ff) << 24));
}
uint64_t _yr_bswap64(uint64_t x)
{
return ((((x) & 0xff00000000000000ull) >> 56)
| (((x) & 0x00ff000000000000ull) >> 40)
| (((x) & 0x0000ff0000000000ull) >> 24)
| (((x) & 0x000000ff00000000ull) >> 8)
| (((x) & 0x00000000ff000000ull) << 8)
| (((x) & 0x0000000000ff0000ull) << 24)
| (((x) & 0x000000000000ff00ull) << 40)
| (((x) & 0x00000000000000ffull) << 56));
return (
(((x) &0xff00000000000000ull) >> 56) |
(((x) &0x00ff000000000000ull) >> 40) |
(((x) &0x0000ff0000000000ull) >> 24) |
(((x) &0x000000ff00000000ull) >> 8) |
(((x) &0x00000000ff000000ull) << 8) |
(((x) &0x0000000000ff0000ull) << 24) |
(((x) &0x000000000000ff00ull) << 40) |
(((x) &0x00000000000000ffull) << 56));
}
+95 -86
View File
@@ -43,32 +43,37 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <excpt.h>
static LONG CALLBACK exception_handler(
PEXCEPTION_POINTERS ExceptionInfo)
static LONG CALLBACK exception_handler(PEXCEPTION_POINTERS ExceptionInfo)
{
switch(ExceptionInfo->ExceptionRecord->ExceptionCode)
switch (ExceptionInfo->ExceptionRecord->ExceptionCode)
{
case EXCEPTION_IN_PAGE_ERROR:
case EXCEPTION_ACCESS_VIOLATION:
return EXCEPTION_EXECUTE_HANDLER;
case EXCEPTION_IN_PAGE_ERROR:
case EXCEPTION_ACCESS_VIOLATION:
return EXCEPTION_EXECUTE_HANDLER;
}
return EXCEPTION_CONTINUE_SEARCH;
}
#define YR_TRYCATCH(_do_,_try_clause_,_catch_clause_) \
do \
{ \
if (_do_) \
{ \
__try \
{ _try_clause_ } \
__except(exception_handler(GetExceptionInformation())) \
{ _catch_clause_ } \
} \
else \
{ _try_clause_ } \
} while(0)
#define YR_TRYCATCH(_do_, _try_clause_, _catch_clause_) \
do \
{ \
if (_do_) \
{ \
__try \
{ \
_try_clause_ \
} \
__except (exception_handler(GetExceptionInformation())) \
{ \
_catch_clause_ \
} \
} \
else \
{ \
_try_clause_ \
} \
} while (0)
#else
@@ -76,48 +81,49 @@ static LONG CALLBACK exception_handler(
#include <setjmp.h>
static LONG CALLBACK exception_handler(
PEXCEPTION_POINTERS ExceptionInfo)
static LONG CALLBACK exception_handler(PEXCEPTION_POINTERS ExceptionInfo)
{
jmp_buf* jb_ptr;
switch(ExceptionInfo->ExceptionRecord->ExceptionCode)
switch (ExceptionInfo->ExceptionRecord->ExceptionCode)
{
case EXCEPTION_IN_PAGE_ERROR:
case EXCEPTION_ACCESS_VIOLATION:
jb_ptr = (jmp_buf*) yr_thread_storage_get_value(
&yr_trycatch_trampoline_tls);
case EXCEPTION_IN_PAGE_ERROR:
case EXCEPTION_ACCESS_VIOLATION:
jb_ptr =
(jmp_buf*) yr_thread_storage_get_value(&yr_trycatch_trampoline_tls);
if (jb_ptr != NULL)
longjmp(*jb_ptr, 1);
if (jb_ptr != NULL)
longjmp(*jb_ptr, 1);
}
return EXCEPTION_CONTINUE_SEARCH;
}
#define YR_TRYCATCH(_do_,_try_clause_,_catch_clause_) \
do \
{ \
if (_do_) \
{ \
jmp_buf jb; \
/* Store pointer to sigjmp_buf in TLS */ \
yr_thread_storage_set_value( \
&yr_trycatch_trampoline_tls, &jb); \
HANDLE exh = AddVectoredExceptionHandler(1, exception_handler); \
if (setjmp(jb) == 0) \
{ _try_clause_ } \
else \
{ _catch_clause_ } \
RemoveVectoredExceptionHandler(exh); \
yr_thread_storage_set_value( \
&yr_trycatch_trampoline_tls, NULL); \
} \
else \
{ \
_try_clause_ \
} \
} while(0)
#define YR_TRYCATCH(_do_, _try_clause_, _catch_clause_) \
do \
{ \
if (_do_) \
{ \
jmp_buf jb; \
/* Store pointer to sigjmp_buf in TLS */ \
yr_thread_storage_set_value(&yr_trycatch_trampoline_tls, &jb); \
HANDLE exh = AddVectoredExceptionHandler(1, exception_handler); \
if (setjmp(jb) == 0) \
{ \
_try_clause_ \
} \
else \
{ \
_catch_clause_ \
} \
RemoveVectoredExceptionHandler(exh); \
yr_thread_storage_set_value(&yr_trycatch_trampoline_tls, NULL); \
} \
else \
{ \
_try_clause_ \
} \
} while (0)
#endif
@@ -127,11 +133,12 @@ static LONG CALLBACK exception_handler(
#include <signal.h>
#include <yara/globals.h>
static void exception_handler(int sig) {
static void exception_handler(int sig)
{
if (sig == SIGBUS || sig == SIGSEGV)
{
jmp_buf* jb_ptr = (jmp_buf*) yr_thread_storage_get_value(
&yr_trycatch_trampoline_tls);
jmp_buf* jb_ptr =
(jmp_buf*) yr_thread_storage_get_value(&yr_trycatch_trampoline_tls);
if (jb_ptr != NULL)
siglongjmp(*jb_ptr, 1);
@@ -140,38 +147,40 @@ static void exception_handler(int sig) {
typedef struct sigaction sa;
#define YR_TRYCATCH(_do_,_try_clause_, _catch_clause_) \
do \
{ \
if (_do_) \
{ \
struct sigaction old_sigbus_act; \
struct sigaction old_sigsegv_act; \
struct sigaction act; \
sigjmp_buf jb; \
/* Store pointer to sigjmp_buf in TLS */ \
yr_thread_storage_set_value( \
&yr_trycatch_trampoline_tls, &jb); \
/* Set exception handler for SIGBUS and SIGSEGV*/ \
act.sa_handler = exception_handler; \
act.sa_flags = 0; /* SA_ONSTACK? */ \
sigfillset(&act.sa_mask); \
sigaction(SIGBUS, &act, &old_sigbus_act); \
sigaction(SIGSEGV, &act, &old_sigsegv_act); \
if (sigsetjmp(jb, 1) == 0) \
{ _try_clause_ } \
else \
{ _catch_clause_ } \
/* Stop capturing SIGBUS and SIGSEGV */ \
sigaction(SIGBUS, &old_sigbus_act, NULL); \
sigaction(SIGSEGV, &old_sigsegv_act, NULL); \
yr_thread_storage_set_value( \
&yr_trycatch_trampoline_tls, NULL); \
} \
else \
{ \
_try_clause_ \
} \
#define YR_TRYCATCH(_do_, _try_clause_, _catch_clause_) \
do \
{ \
if (_do_) \
{ \
struct sigaction old_sigbus_act; \
struct sigaction old_sigsegv_act; \
struct sigaction act; \
sigjmp_buf jb; \
/* Store pointer to sigjmp_buf in TLS */ \
yr_thread_storage_set_value(&yr_trycatch_trampoline_tls, &jb); \
/* Set exception handler for SIGBUS and SIGSEGV*/ \
act.sa_handler = exception_handler; \
act.sa_flags = 0; /* SA_ONSTACK? */ \
sigfillset(&act.sa_mask); \
sigaction(SIGBUS, &act, &old_sigbus_act); \
sigaction(SIGSEGV, &act, &old_sigsegv_act); \
if (sigsetjmp(jb, 1) == 0) \
{ \
_try_clause_ \
} \
else \
{ \
_catch_clause_ \
} \
/* Stop capturing SIGBUS and SIGSEGV */ \
sigaction(SIGBUS, &old_sigbus_act, NULL); \
sigaction(SIGSEGV, &old_sigsegv_act, NULL); \
yr_thread_storage_set_value(&yr_trycatch_trampoline_tls, NULL); \
} \
else \
{ \
_try_clause_ \
} \
} while (0)
#endif
+1338 -1365
View File
File diff suppressed because it is too large Load Diff
+91 -95
View File
@@ -28,11 +28,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <limits.h>
#include <yara/endian.h>
#include <yara/pe.h>
#include <yara/elf.h>
#include <yara/endian.h>
#include <yara/exec.h>
#include <yara/pe.h>
#include <yara/utils.h>
#ifndef NULL
@@ -40,10 +39,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endif
#ifndef MIN
#define MIN(x,y) ((x < y)?(x):(y))
#define MIN(x, y) ((x < y) ? (x) : (y))
#endif
PIMAGE_NT_HEADERS32 yr_get_pe_header(
const uint8_t* buffer,
size_t buffer_length)
@@ -64,14 +62,13 @@ PIMAGE_NT_HEADERS32 yr_get_pe_header(
if ((int32_t) yr_le32toh(mz_header->e_lfanew) < 0)
return NULL;
headers_size = yr_le32toh(mz_header->e_lfanew) + \
sizeof(pe_header->Signature) + \
sizeof(IMAGE_FILE_HEADER);
headers_size = yr_le32toh(mz_header->e_lfanew) +
sizeof(pe_header->Signature) + sizeof(IMAGE_FILE_HEADER);
if (buffer_length < headers_size)
return NULL;
pe_header = (PIMAGE_NT_HEADERS32) (buffer + yr_le32toh(mz_header->e_lfanew));
pe_header = (PIMAGE_NT_HEADERS32)(buffer + yr_le32toh(mz_header->e_lfanew));
headers_size += sizeof(IMAGE_OPTIONAL_HEADER32);
@@ -88,7 +85,6 @@ PIMAGE_NT_HEADERS32 yr_get_pe_header(
}
}
uint64_t yr_pe_rva_to_offset(
PIMAGE_NT_HEADERS32 pe_header,
uint64_t rva,
@@ -103,10 +99,11 @@ uint64_t yr_pe_rva_to_offset(
section_rva = 0;
section_offset = 0;
while(i < MIN(yr_le16toh(pe_header->FileHeader.NumberOfSections), 60))
while (i < MIN(yr_le16toh(pe_header->FileHeader.NumberOfSections), 60))
{
if ((uint8_t*) section - \
(uint8_t*) pe_header + sizeof(IMAGE_SECTION_HEADER) < buffer_length)
if ((uint8_t*) section - (uint8_t*) pe_header +
sizeof(IMAGE_SECTION_HEADER) <
buffer_length)
{
if (rva >= section->VirtualAddress &&
section_rva <= yr_le32toh(section->VirtualAddress))
@@ -127,10 +124,7 @@ uint64_t yr_pe_rva_to_offset(
return section_offset + (rva - section_rva);
}
int yr_get_elf_type(
const uint8_t* buffer,
size_t buffer_length)
int yr_get_elf_type(const uint8_t* buffer, size_t buffer_length)
{
elf_ident_t* elf_ident;
@@ -144,28 +138,28 @@ int yr_get_elf_type(
return 0;
}
switch (elf_ident->_class) {
case ELF_CLASS_32:
if (buffer_length < sizeof(elf32_header_t))
{
return 0;
}
break;
case ELF_CLASS_64:
if (buffer_length < sizeof(elf64_header_t))
{
return 0;
}
break;
default:
/* Unexpected class */
switch (elf_ident->_class)
{
case ELF_CLASS_32:
if (buffer_length < sizeof(elf32_header_t))
{
return 0;
}
break;
case ELF_CLASS_64:
if (buffer_length < sizeof(elf64_header_t))
{
return 0;
}
break;
default:
/* Unexpected class */
return 0;
}
return elf_ident->_class;
}
static uint64_t yr_elf_rva_to_offset_32(
elf32_header_t* elf_header,
uint64_t rva,
@@ -183,29 +177,32 @@ static uint64_t yr_elf_rva_to_offset_32(
// check to prevent integer wraps
if (ULONG_MAX - yr_le16toh(elf_header->ph_entry_count) <
sizeof(elf32_program_header_t) * yr_le16toh(elf_header->ph_entry_count))
sizeof(elf32_program_header_t) * yr_le16toh(elf_header->ph_entry_count))
return 0;
// check that 'ph_offset' doesn't wrap when added to the
// size of entries.
if(ULONG_MAX - yr_le32toh(elf_header->ph_offset) <
sizeof(elf32_program_header_t) * yr_le16toh(elf_header->ph_entry_count))
if (ULONG_MAX - yr_le32toh(elf_header->ph_offset) <
sizeof(elf32_program_header_t) * yr_le16toh(elf_header->ph_entry_count))
return 0;
// ensure we don't exceed the buffer size
if (yr_le32toh(elf_header->ph_offset) + sizeof(elf32_program_header_t) *
yr_le16toh(elf_header->ph_entry_count) > buffer_length)
if (yr_le32toh(elf_header->ph_offset) +
sizeof(elf32_program_header_t) *
yr_le16toh(elf_header->ph_entry_count) >
buffer_length)
return 0;
program = (elf32_program_header_t*)
((uint8_t*) elf_header + yr_le32toh(elf_header->ph_offset));
program =
(elf32_program_header_t*) ((uint8_t*) elf_header + yr_le32toh(elf_header->ph_offset));
for (i = 0; i < yr_le16toh(elf_header->ph_entry_count); i++)
{
if (rva >= yr_le32toh(program->virt_addr) &&
rva < yr_le32toh(program->virt_addr) + yr_le32toh(program->mem_size))
rva < yr_le32toh(program->virt_addr) + yr_le32toh(program->mem_size))
{
return yr_le32toh(program->offset) + (rva - yr_le32toh(program->virt_addr));
return yr_le32toh(program->offset) +
(rva - yr_le32toh(program->virt_addr));
}
program++;
@@ -223,18 +220,20 @@ static uint64_t yr_elf_rva_to_offset_32(
// check to prevent integer wraps
if (ULONG_MAX - yr_le16toh(elf_header->sh_entry_count) <
sizeof(elf32_section_header_t) * yr_le16toh(elf_header->sh_entry_count))
sizeof(elf32_section_header_t) * yr_le16toh(elf_header->sh_entry_count))
return 0;
// check that 'sh_offset' doesn't wrap when added to the
// size of entries.
if (ULONG_MAX - yr_le32toh(elf_header->sh_offset) <
sizeof(elf32_section_header_t) * yr_le16toh(elf_header->sh_entry_count))
sizeof(elf32_section_header_t) * yr_le16toh(elf_header->sh_entry_count))
return 0;
if (yr_le32toh(elf_header->sh_offset) + sizeof(elf32_section_header_t) *
yr_le16toh(elf_header->sh_entry_count) > buffer_length)
if (yr_le32toh(elf_header->sh_offset) +
sizeof(elf32_section_header_t) *
yr_le16toh(elf_header->sh_entry_count) >
buffer_length)
return 0;
section = (elf32_section_header_t*)
@@ -245,14 +244,16 @@ static uint64_t yr_elf_rva_to_offset_32(
if (yr_le32toh(section->type) != ELF_SHT_NULL &&
yr_le32toh(section->type) != ELF_SHT_NOBITS &&
rva >= yr_le32toh(section->addr) &&
rva < yr_le32toh(section->addr) + yr_le32toh(section->size))
rva < yr_le32toh(section->addr) + yr_le32toh(section->size))
{
// prevent integer wrapping with the return value
if (ULONG_MAX - yr_le32toh(section->offset) < (rva - yr_le32toh(section->addr)))
if (ULONG_MAX - yr_le32toh(section->offset) <
(rva - yr_le32toh(section->addr)))
return 0;
else
return yr_le32toh(section->offset) + (rva - yr_le32toh(section->addr));
return yr_le32toh(section->offset) +
(rva - yr_le32toh(section->addr));
}
section++;
@@ -260,10 +261,8 @@ static uint64_t yr_elf_rva_to_offset_32(
}
return 0;
}
static uint64_t yr_elf_rva_to_offset_64(
elf64_header_t* elf_header,
uint64_t rva,
@@ -281,24 +280,27 @@ static uint64_t yr_elf_rva_to_offset_64(
// check that 'ph_offset' doesn't wrap when added to the
// size of entries.
if(ULONG_MAX - yr_le64toh(elf_header->ph_offset) <
sizeof(elf64_program_header_t) * yr_le16toh(elf_header->ph_entry_count))
if (ULONG_MAX - yr_le64toh(elf_header->ph_offset) <
sizeof(elf64_program_header_t) * yr_le16toh(elf_header->ph_entry_count))
return 0;
// ensure we don't exceed the buffer size
if (yr_le64toh(elf_header->ph_offset) + sizeof(elf64_program_header_t) *
yr_le16toh(elf_header->ph_entry_count) > buffer_length)
if (yr_le64toh(elf_header->ph_offset) +
sizeof(elf64_program_header_t) *
yr_le16toh(elf_header->ph_entry_count) >
buffer_length)
return 0;
program = (elf64_program_header_t*)
((uint8_t*) elf_header + yr_le64toh(elf_header->ph_offset));
program =
(elf64_program_header_t*) ((uint8_t*) elf_header + yr_le64toh(elf_header->ph_offset));
for (i = 0; i < yr_le16toh(elf_header->ph_entry_count); i++)
{
if (rva >= yr_le64toh(program->virt_addr) &&
rva < yr_le64toh(program->virt_addr) + yr_le64toh(program->mem_size))
rva < yr_le64toh(program->virt_addr) + yr_le64toh(program->mem_size))
{
return yr_le64toh(program->offset) + (rva - yr_le64toh(program->virt_addr));
return yr_le64toh(program->offset) +
(rva - yr_le64toh(program->virt_addr));
}
program++;
@@ -315,23 +317,25 @@ static uint64_t yr_elf_rva_to_offset_64(
// check that 'sh_offset' doesn't wrap when added to the
// size of entries.
if(ULONG_MAX - yr_le64toh(elf_header->sh_offset) <
sizeof(elf64_section_header_t) * yr_le16toh(elf_header->sh_entry_count))
if (ULONG_MAX - yr_le64toh(elf_header->sh_offset) <
sizeof(elf64_section_header_t) * yr_le16toh(elf_header->sh_entry_count))
return 0;
if (yr_le64toh(elf_header->sh_offset) + sizeof(elf64_section_header_t) *
yr_le16toh(elf_header->sh_entry_count) > buffer_length)
if (yr_le64toh(elf_header->sh_offset) +
sizeof(elf64_section_header_t) *
yr_le16toh(elf_header->sh_entry_count) >
buffer_length)
return 0;
section = (elf64_section_header_t*)
((uint8_t*) elf_header + yr_le64toh(elf_header->sh_offset));
section =
(elf64_section_header_t*) ((uint8_t*) elf_header + yr_le64toh(elf_header->sh_offset));
for (i = 0; i < yr_le16toh(elf_header->sh_entry_count); i++)
{
if (yr_le32toh(section->type) != ELF_SHT_NULL &&
yr_le32toh(section->type) != ELF_SHT_NOBITS &&
rva >= yr_le64toh(section->addr) &&
rva < yr_le64toh(section->addr) + yr_le64toh(section->size))
rva < yr_le64toh(section->addr) + yr_le64toh(section->size))
{
return yr_le64toh(section->offset) + (rva - yr_le64toh(section->addr));
}
@@ -343,10 +347,7 @@ static uint64_t yr_elf_rva_to_offset_64(
return 0;
}
uint64_t yr_get_entry_point_offset(
const uint8_t* buffer,
size_t buffer_length)
uint64_t yr_get_entry_point_offset(const uint8_t* buffer, size_t buffer_length)
{
PIMAGE_NT_HEADERS32 pe_header;
elf32_header_t* elf_header32;
@@ -362,27 +363,22 @@ uint64_t yr_get_entry_point_offset(
buffer_length - ((uint8_t*) pe_header - buffer));
}
switch(yr_get_elf_type(buffer, buffer_length))
switch (yr_get_elf_type(buffer, buffer_length))
{
case ELF_CLASS_32:
elf_header32 = (elf32_header_t*) buffer;
return yr_elf_rva_to_offset_32(
elf_header32,
yr_le32toh(elf_header32->entry),
buffer_length);
case ELF_CLASS_32:
elf_header32 = (elf32_header_t*) buffer;
return yr_elf_rva_to_offset_32(
elf_header32, yr_le32toh(elf_header32->entry), buffer_length);
case ELF_CLASS_64:
elf_header64 = (elf64_header_t*) buffer;
return yr_elf_rva_to_offset_64(
elf_header64,
yr_le64toh(elf_header64->entry),
buffer_length);
case ELF_CLASS_64:
elf_header64 = (elf64_header_t*) buffer;
return yr_elf_rva_to_offset_64(
elf_header64, yr_le64toh(elf_header64->entry), buffer_length);
}
return YR_UNDEFINED;
}
uint64_t yr_get_entry_point_address(
const uint8_t* buffer,
size_t buffer_length,
@@ -403,23 +399,23 @@ uint64_t yr_get_entry_point_address(
// If file is executable ELF, not shared library.
switch(yr_get_elf_type(buffer, buffer_length))
switch (yr_get_elf_type(buffer, buffer_length))
{
case ELF_CLASS_32:
elf_header32 = (elf32_header_t*) buffer;
case ELF_CLASS_32:
elf_header32 = (elf32_header_t*) buffer;
if (elf_header32->type == ELF_ET_EXEC)
return elf_header32->entry;
if (elf_header32->type == ELF_ET_EXEC)
return elf_header32->entry;
break;
break;
case ELF_CLASS_64:
elf_header64 = (elf64_header_t*) buffer;
case ELF_CLASS_64:
elf_header64 = (elf64_header_t*) buffer;
if (elf_header64->type == ELF_ET_EXEC)
return elf_header64->entry;
if (elf_header64->type == ELF_ET_EXEC)
return elf_header64->entry;
break;
break;
}
return YR_UNDEFINED;
+65 -98
View File
@@ -32,64 +32,50 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#if defined(_WIN32) || defined(__CYGWIN__)
#include <windows.h>
#else
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#include <yara/filemap.h>
#include <yara/error.h>
#include <yara/filemap.h>
//
// yr_filemap_map
//
////////////////////////////////////////////////////////////////////////////////
// Maps a whole file into memory.
//
// Args:
// const char* file_path - Path of the file to map.
// YR_MAPPED_FILE* pmapped_file - Pointer to a YR_MAPPED_FILE that will be
// filled with information about the mapping.
// file_path: Path of the file to map.
// pmapped_file: Pointer to a YR_MAPPED_FILE that will be filled with
// information about the mapping.
// Returns:
// One of the following error codes:
// ERROR_SUCCESS
// ERROR_INVALID_ARGUMENT
// ERROR_COULD_NOT_OPEN_FILE
// ERROR_COULD_NOT_MAP_FILE
// ERROR_SUCCESS
// ERROR_INVALID_ARGUMENT
// ERROR_COULD_NOT_OPEN_FILE
// ERROR_COULD_NOT_MAP_FILE
//
YR_API int yr_filemap_map(
const char* file_path,
YR_MAPPED_FILE* pmapped_file)
YR_API int yr_filemap_map(const char* file_path, YR_MAPPED_FILE* pmapped_file)
{
return yr_filemap_map_ex(file_path, 0, 0, pmapped_file);
}
//
// yr_filemap_map_fd
//
////////////////////////////////////////////////////////////////////////////////
// Maps a portion of a file (specified by descriptor) into memory.
//
// Args:
// YR_FILE_DESCRIPTOR file - File descriptor representing the file to
// map
// off_t offset - File offset where the mapping will begin.
// This offset must be multiple of 1MB and not
// greater than the actual file size.
// size_t size - Number of bytes that will be mapped. If
// zero or greater than the actual file size
// all content until the end of the file will
// be mapped.
// YR_MAPPED_FILE* pmapped_file - Pointer to a YR_MAPPED_FILE struct that
// will be filled with the new mapping.
// file: File descriptor representing the file to map.
// offset: File offset where the mapping will begin. This offset must be
// multiple of 1MB and not greater than the actualfile size.
// size: Number of bytes that will be mapped. If zero or greater than the
// actual file size all content until the end of the file will be
// mapped.
// pmapped_file: Pointer to a YR_MAPPED_FILE struct that will be filled with
// the new mapping.
// Returns:
// One of the following error codes:
// ERROR_SUCCESS
// ERROR_INVALID_ARGUMENT
// ERROR_COULD_NOT_OPEN_FILE
// ERROR_COULD_NOT_MAP_FILE
// ERROR_SUCCESS
// ERROR_INVALID_ARGUMENT
// ERROR_COULD_NOT_OPEN_FILE
// ERROR_COULD_NOT_MAP_FILE
//
#if defined(_WIN32) || defined(__CYGWIN__)
YR_API int yr_filemap_map_fd(
@@ -112,11 +98,11 @@ YR_API int yr_filemap_map_fd(
if (GetFileSizeEx(pmapped_file->file, &fs))
{
#ifdef _WIN64
#ifdef _WIN64
file_size = fs.QuadPart;
#else
#else
file_size = fs.LowPart;
#endif
#endif
}
else
{
@@ -128,19 +114,14 @@ YR_API int yr_filemap_map_fd(
return ERROR_COULD_NOT_MAP_FILE;
if (size == 0)
size = (size_t) (file_size - offset);
size = (size_t)(file_size - offset);
pmapped_file->size = yr_min(size, (size_t) (file_size - offset));
pmapped_file->size = yr_min(size, (size_t)(file_size - offset));
if (pmapped_file->size != 0)
{
pmapped_file->mapping = CreateFileMapping(
pmapped_file->file,
NULL,
PAGE_READONLY,
0,
0,
NULL);
pmapped_file->file, NULL, PAGE_READONLY, 0, 0, NULL);
if (pmapped_file->mapping == NULL)
{
@@ -174,27 +155,27 @@ YR_API int yr_filemap_map_fd(
return ERROR_SUCCESS;
}
#else // POSIX
#else // POSIX
#define MAP_EXTRA_FLAGS 0
#if defined (__APPLE__)
#if defined(__APPLE__)
// MacOS defines some extra flags for mmap.The MAP_RESILIENT_CODESIGN allows
// to read from binaries whose code signature is invalid, without this flags
// any attempt to read from such binaries causes a crash, see:
// https://github.com/VirusTotal/yara/issues/1309.
//
// Also, reading from files in removable media that becomes unavailable crashes
// the program if the MAP_RESILIENT_MEDIA flag is not set.
// Also, reading from files in removable media that becomes unavailable
// crashes the program if the MAP_RESILIENT_MEDIA flag is not set.
#if defined(MAP_RESILIENT_CODESIGN)
#undef MAP_EXTRA_FLAGS
#if defined(MAP_RESILIENT_MEDIA)
#define MAP_EXTRA_FLAGS MAP_RESILIENT_CODESIGN | MAP_RESILIENT_MEDIA
#else
#define MAP_EXTRA_FLAGS MAP_RESILIENT_CODESIGN
#endif
#endif // #if defined(MAP_RESILIENT_CODESIGN)
#endif // #if defined (__APPLE__)
#undef MAP_EXTRA_FLAGS
#if defined(MAP_RESILIENT_MEDIA)
#define MAP_EXTRA_FLAGS MAP_RESILIENT_CODESIGN | MAP_RESILIENT_MEDIA
#else
#define MAP_EXTRA_FLAGS MAP_RESILIENT_CODESIGN
#endif
#endif // #if defined(MAP_RESILIENT_CODESIGN)
#endif // #if defined (__APPLE__)
YR_API int yr_filemap_map_fd(
YR_FILE_DESCRIPTOR file,
@@ -219,9 +200,9 @@ YR_API int yr_filemap_map_fd(
return ERROR_COULD_NOT_MAP_FILE;
if (size == 0)
size = (size_t) (st.st_size - offset);
size = (size_t)(st.st_size - offset);
pmapped_file->size = yr_min(size, (size_t) (st.st_size - offset));
pmapped_file->size = yr_min(size, (size_t)(st.st_size - offset));
if (pmapped_file->size != 0)
{
@@ -254,30 +235,24 @@ YR_API int yr_filemap_map_fd(
#endif
//
// yr_filemap_map_ex
//
////////////////////////////////////////////////////////////////////////////////
// Maps a portion of a file (specified by path) into memory.
//
// Args:
// const char* file_path - Path of the file to map.
// off_t offset - File offset where the mapping will begin.
// This offset must be multiple of 1MB and not
// greater than the actual file size.
// size_t size - Number of bytes that will be mapped. If
// zero or greater than the actual file size
// all content until the end of the file will
// be mapped.
// YR_MAPPED_FILE* pmapped_file - Pointer to a YR_MAPPED_FILE struct that
// will be filled with the new mapping.
// file_path: Path of the file to map.
// offset: File offset where the mapping will begin. This offset must be
// multiple of 1MB and not greater than the actualfile size.
// size: Number of bytes that will be mapped. If zero or greater than the
// actual file size all content until the end of the file will be
// mapped.
// pmapped_file: Pointer to a YR_MAPPED_FILE struct that will be filled with
// the new mapping.
// Returns:
// One of the following error codes:
// ERROR_SUCCESS
// ERROR_INVALID_ARGUMENT
// ERROR_COULD_NOT_OPEN_FILE
// ERROR_COULD_NOT_MAP_FILE
// ERROR_SUCCESS
// ERROR_INVALID_ARGUMENT
// ERROR_COULD_NOT_OPEN_FILE
// ERROR_COULD_NOT_MAP_FILE
//
#if defined(_WIN32) || defined(__CYGWIN__)
YR_API int yr_filemap_map_ex(
@@ -312,7 +287,7 @@ YR_API int yr_filemap_map_ex(
return result;
}
#else // POSIX
#else // POSIX
YR_API int yr_filemap_map_ex(
const char* file_path,
@@ -341,20 +316,15 @@ YR_API int yr_filemap_map_ex(
#endif
//
// yr_filemap_unmap
//
////////////////////////////////////////////////////////////////////////////////
// Unmaps a file mapping.
//
// Args:
// YR_MAPPED_FILE* pmapped_file - Pointer to a YR_MAPPED_FILE that struct.
// pmapped_file: Pointer to a YR_MAPPED_FILE that struct.
//
#ifdef WIN32
YR_API void yr_filemap_unmap_fd(
YR_MAPPED_FILE* pmapped_file)
YR_API void yr_filemap_unmap_fd(YR_MAPPED_FILE* pmapped_file)
{
if (pmapped_file->data != NULL)
UnmapViewOfFile(pmapped_file->data);
@@ -367,8 +337,7 @@ YR_API void yr_filemap_unmap_fd(
pmapped_file->size = 0;
}
YR_API void yr_filemap_unmap(
YR_MAPPED_FILE* pmapped_file)
YR_API void yr_filemap_unmap(YR_MAPPED_FILE* pmapped_file)
{
yr_filemap_unmap_fd(pmapped_file);
@@ -379,10 +348,9 @@ YR_API void yr_filemap_unmap(
}
}
#else // POSIX
#else // POSIX
YR_API void yr_filemap_unmap_fd(
YR_MAPPED_FILE* pmapped_file)
YR_API void yr_filemap_unmap_fd(YR_MAPPED_FILE* pmapped_file)
{
if (pmapped_file->data != NULL)
munmap((void*) pmapped_file->data, pmapped_file->size);
@@ -391,8 +359,7 @@ YR_API void yr_filemap_unmap_fd(
pmapped_file->size = 0;
}
YR_API void yr_filemap_unmap(
YR_MAPPED_FILE* pmapped_file)
YR_API void yr_filemap_unmap(YR_MAPPED_FILE* pmapped_file)
{
yr_filemap_unmap_fd(pmapped_file);
+3564 -3476
View File
File diff suppressed because it is too large Load Diff
+133 -134
View File
@@ -31,10 +31,10 @@
version 2.2 of Bison. */
#ifndef YY_YARA_YY_GRAMMAR_H_INCLUDED
# define YY_YARA_YY_GRAMMAR_H_INCLUDED
#define YY_YARA_YY_GRAMMAR_H_INCLUDED
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#define YYDEBUG 0
#endif
#if YYDEBUG
extern int yara_yydebug;
@@ -42,144 +42,144 @@ extern int yara_yydebug;
/* Token type. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
enum yytokentype
{
_END_OF_FILE_ = 0,
_END_OF_INCLUDED_FILE_ = 258,
_DOT_DOT_ = 259,
_RULE_ = 260,
_PRIVATE_ = 261,
_GLOBAL_ = 262,
_META_ = 263,
_STRINGS_ = 264,
_CONDITION_ = 265,
_IDENTIFIER_ = 266,
_STRING_IDENTIFIER_ = 267,
_STRING_COUNT_ = 268,
_STRING_OFFSET_ = 269,
_STRING_LENGTH_ = 270,
_STRING_IDENTIFIER_WITH_WILDCARD_ = 271,
_NUMBER_ = 272,
_DOUBLE_ = 273,
_INTEGER_FUNCTION_ = 274,
_TEXT_STRING_ = 275,
_HEX_STRING_ = 276,
_REGEXP_ = 277,
_ASCII_ = 278,
_WIDE_ = 279,
_XOR_ = 280,
_BASE64_ = 281,
_BASE64_WIDE_ = 282,
_NOCASE_ = 283,
_FULLWORD_ = 284,
_AT_ = 285,
_FILESIZE_ = 286,
_ENTRYPOINT_ = 287,
_ALL_ = 288,
_ANY_ = 289,
_IN_ = 290,
_OF_ = 291,
_FOR_ = 292,
_THEM_ = 293,
_MATCHES_ = 294,
_CONTAINS_ = 295,
_STARTSWITH_ = 296,
_ENDSWITH_ = 297,
_ICONTAINS_ = 298,
_ISTARTSWITH_ = 299,
_IENDSWITH_ = 300,
_IMPORT_ = 301,
_TRUE_ = 302,
_FALSE_ = 303,
_OR_ = 304,
_AND_ = 305,
_NOT_ = 306,
_EQ_ = 307,
_NEQ_ = 308,
_LT_ = 309,
_LE_ = 310,
_GT_ = 311,
_GE_ = 312,
_SHIFT_LEFT_ = 313,
_SHIFT_RIGHT_ = 314,
UNARY_MINUS = 315
};
#define YYTOKENTYPE
enum yytokentype
{
_END_OF_FILE_ = 0,
_END_OF_INCLUDED_FILE_ = 258,
_DOT_DOT_ = 259,
_RULE_ = 260,
_PRIVATE_ = 261,
_GLOBAL_ = 262,
_META_ = 263,
_STRINGS_ = 264,
_CONDITION_ = 265,
_IDENTIFIER_ = 266,
_STRING_IDENTIFIER_ = 267,
_STRING_COUNT_ = 268,
_STRING_OFFSET_ = 269,
_STRING_LENGTH_ = 270,
_STRING_IDENTIFIER_WITH_WILDCARD_ = 271,
_NUMBER_ = 272,
_DOUBLE_ = 273,
_INTEGER_FUNCTION_ = 274,
_TEXT_STRING_ = 275,
_HEX_STRING_ = 276,
_REGEXP_ = 277,
_ASCII_ = 278,
_WIDE_ = 279,
_XOR_ = 280,
_BASE64_ = 281,
_BASE64_WIDE_ = 282,
_NOCASE_ = 283,
_FULLWORD_ = 284,
_AT_ = 285,
_FILESIZE_ = 286,
_ENTRYPOINT_ = 287,
_ALL_ = 288,
_ANY_ = 289,
_IN_ = 290,
_OF_ = 291,
_FOR_ = 292,
_THEM_ = 293,
_MATCHES_ = 294,
_CONTAINS_ = 295,
_STARTSWITH_ = 296,
_ENDSWITH_ = 297,
_ICONTAINS_ = 298,
_ISTARTSWITH_ = 299,
_IENDSWITH_ = 300,
_IMPORT_ = 301,
_TRUE_ = 302,
_FALSE_ = 303,
_OR_ = 304,
_AND_ = 305,
_NOT_ = 306,
_EQ_ = 307,
_NEQ_ = 308,
_LT_ = 309,
_LE_ = 310,
_GT_ = 311,
_GE_ = 312,
_SHIFT_LEFT_ = 313,
_SHIFT_RIGHT_ = 314,
UNARY_MINUS = 315
};
#endif
/* Tokens. */
#define _END_OF_FILE_ 0
#define _END_OF_INCLUDED_FILE_ 258
#define _DOT_DOT_ 259
#define _RULE_ 260
#define _PRIVATE_ 261
#define _GLOBAL_ 262
#define _META_ 263
#define _STRINGS_ 264
#define _CONDITION_ 265
#define _IDENTIFIER_ 266
#define _STRING_IDENTIFIER_ 267
#define _STRING_COUNT_ 268
#define _STRING_OFFSET_ 269
#define _STRING_LENGTH_ 270
#define _END_OF_FILE_ 0
#define _END_OF_INCLUDED_FILE_ 258
#define _DOT_DOT_ 259
#define _RULE_ 260
#define _PRIVATE_ 261
#define _GLOBAL_ 262
#define _META_ 263
#define _STRINGS_ 264
#define _CONDITION_ 265
#define _IDENTIFIER_ 266
#define _STRING_IDENTIFIER_ 267
#define _STRING_COUNT_ 268
#define _STRING_OFFSET_ 269
#define _STRING_LENGTH_ 270
#define _STRING_IDENTIFIER_WITH_WILDCARD_ 271
#define _NUMBER_ 272
#define _DOUBLE_ 273
#define _INTEGER_FUNCTION_ 274
#define _TEXT_STRING_ 275
#define _HEX_STRING_ 276
#define _REGEXP_ 277
#define _ASCII_ 278
#define _WIDE_ 279
#define _XOR_ 280
#define _BASE64_ 281
#define _BASE64_WIDE_ 282
#define _NOCASE_ 283
#define _FULLWORD_ 284
#define _AT_ 285
#define _FILESIZE_ 286
#define _ENTRYPOINT_ 287
#define _ALL_ 288
#define _ANY_ 289
#define _IN_ 290
#define _OF_ 291
#define _FOR_ 292
#define _THEM_ 293
#define _MATCHES_ 294
#define _CONTAINS_ 295
#define _STARTSWITH_ 296
#define _ENDSWITH_ 297
#define _ICONTAINS_ 298
#define _ISTARTSWITH_ 299
#define _IENDSWITH_ 300
#define _IMPORT_ 301
#define _TRUE_ 302
#define _FALSE_ 303
#define _OR_ 304
#define _AND_ 305
#define _NOT_ 306
#define _EQ_ 307
#define _NEQ_ 308
#define _LT_ 309
#define _LE_ 310
#define _GT_ 311
#define _GE_ 312
#define _SHIFT_LEFT_ 313
#define _SHIFT_RIGHT_ 314
#define UNARY_MINUS 315
#define _NUMBER_ 272
#define _DOUBLE_ 273
#define _INTEGER_FUNCTION_ 274
#define _TEXT_STRING_ 275
#define _HEX_STRING_ 276
#define _REGEXP_ 277
#define _ASCII_ 278
#define _WIDE_ 279
#define _XOR_ 280
#define _BASE64_ 281
#define _BASE64_WIDE_ 282
#define _NOCASE_ 283
#define _FULLWORD_ 284
#define _AT_ 285
#define _FILESIZE_ 286
#define _ENTRYPOINT_ 287
#define _ALL_ 288
#define _ANY_ 289
#define _IN_ 290
#define _OF_ 291
#define _FOR_ 292
#define _THEM_ 293
#define _MATCHES_ 294
#define _CONTAINS_ 295
#define _STARTSWITH_ 296
#define _ENDSWITH_ 297
#define _ICONTAINS_ 298
#define _ISTARTSWITH_ 299
#define _IENDSWITH_ 300
#define _IMPORT_ 301
#define _TRUE_ 302
#define _FALSE_ 303
#define _OR_ 304
#define _AND_ 305
#define _NOT_ 306
#define _EQ_ 307
#define _NEQ_ 308
#define _LT_ 309
#define _LE_ 310
#define _GT_ 311
#define _GE_ 312
#define _SHIFT_LEFT_ 313
#define _SHIFT_RIGHT_ 314
#define UNARY_MINUS 315
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
#if !defined YYSTYPE && !defined YYSTYPE_IS_DECLARED
union YYSTYPE
{
#line 302 "grammar.y" /* yacc.c:1916 */
YR_EXPRESSION expression;
SIZED_STRING* sized_string;
char* c_string;
int64_t integer;
double double_;
YR_MODIFIER modifier;
YR_EXPRESSION expression;
SIZED_STRING* sized_string;
char* c_string;
int64_t integer;
double double_;
YR_MODIFIER modifier;
YR_ARENA_REF tag;
YR_ARENA_REF rule;
@@ -190,12 +190,11 @@ union YYSTYPE
};
typedef union YYSTYPE YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#define YYSTYPE_IS_TRIVIAL 1
#define YYSTYPE_IS_DECLARED 1
#endif
int yara_yyparse (void *yyscanner, YR_COMPILER* compiler);
int yara_yyparse(void* yyscanner, YR_COMPILER* compiler);
#endif /* !YY_YARA_YY_GRAMMAR_H_INCLUDED */
+69 -107
View File
@@ -29,69 +29,68 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assert.h>
#include <string.h>
#include <yara/utils.h>
#include <yara/integers.h>
#include <yara/hash.h>
#include <yara/mem.h>
#include <yara/error.h>
#include <yara/hash.h>
#include <yara/integers.h>
#include <yara/mem.h>
#include <yara/utils.h>
// Constant-time left rotate that does not invoke undefined behavior.
// http://blog.regehr.org/archives/1063
static uint32_t rotl32(uint32_t x, uint32_t shift) {
static uint32_t rotl32(uint32_t x, uint32_t shift)
{
assert(shift < 32);
return (x << shift) | (x >> (-shift & 31));
}
#define ROTATE_INT32(x, shift) \
rotl32(x, shift % 32)
#define ROTATE_INT32(x, shift) rotl32(x, shift % 32)
uint32_t byte_to_int32[] =
{
0xC3113E7F,0x4C353C5F,0x7423810B,0x258D264E,0xDAD39DED,0x75D0B694,0x98CE1216,
0x93334482,0xC5C48EA5,0xF57E0E8B,0x5D7F3723,0x396B1B24,0xA8883D9F,0xB2A74A00,
0xF8E171AE,0x3F01FBAB,0x5C1840CB,0xDDD833C4,0x8D8CCA34,0x32EF223A,0x1A05B871,
0x9A9B6BFC,0x50406A0C,0xE7E1FC04,0x5E07D7F6,0x80B83660,0x20892A62,0xB2C6FEA6,
0x6CEC7CAA,0x182F764B,0x3B0353E7,0x57FC2520,0x4B6812D4,0xACB654E4,0x23C75C04,
0xB1DCD731,0xE3AF0733,0xF2366D39,0xC729671B,0xFF3BE6F2,0xABA37E34,0x3CDAFA38,
0xAAD18D03,0xA8D35345,0x08E9A92C,0xF9324059,0x42D821BE,0x1BC152DD,0x5588811C,
0x874A1F9A,0x6E83E9CD,0xDA6F3AF8,0x965D4670,0xA7A565C0,0x68D8A9AF,0xFC8FD8FD,
0x8FF99FF9,0x4C9B42AE,0x2D066A8D,0x4D1802F7,0x557032B2,0x12BCF371,0xDC29D5AE,
0x72EA361F,0xE2835B0B,0xDFC58966,0x13B0F34D,0x3FA02BCD,0xBF282E3D,0x7DC877F5,
0xF4848A32,0x861E35F5,0x7FFA0D7F,0x515F2E4E,0x6B235D5C,0x55F46E24,0x35AD2C99,
0x072654A8,0x05163F0F,0x9317B11A,0xAED1FC10,0x989444F0,0xDB3E1814,0x446C0CF1,
0x660BF511,0x2F227D3A,0xFDBA0539,0xC649E621,0x5204D7CE,0x5FA386D0,0xE5F22005,
0x97B6C8A1,0x4AB69EC2,0x5C7CA70D,0x39A48EC6,0x7BACF378,0x8D0ED3D1,0xE39DE582,
0xC5FBE2AB,0x37E3D2D0,0x06F44724,0x73144144,0xBA57E905,0xB05B4307,0xAEED8D97,
0xA68CCAC4,0xE30DA57E,0xED0F194B,0x8C2B9B7A,0x814575D5,0x79588493,0x81D3712A,
0x3FA892F2,0x80F0BB94,0x44EAF51A,0x4E05F1D4,0xFC69F858,0x775E8D60,0x22B20DD7,
0x170A87EA,0x1077DE52,0x3D5EC9FB,0x0B6EB1E5,0xF2F9CCAF,0xA76C7DEB,0xD8C2D873,
0xF438C592,0x6239FEEC,0x26D3D2A9,0x30F6FADF,0x4B2984CC,0x6257F3DA,0x0E0583E2,
0x143E5E61,0xBB2732BF,0x9653217A,0x027A84EA,0x95C9AE8B,0x89B8B82B,0x9F286485,
0x29F622FE,0x52A3196B,0x8392D95F,0x33A79167,0xF5DEE92A,0x6E397DB9,0x11931C01,
0x8DD2CD3B,0xF9E6003D,0xAB955AF4,0xD38725F9,0xDCF6F8AE,0x7667A958,0xE67AD995,
0xB7CF979A,0xD88EBE5B,0x5BA889F0,0x078BDD90,0x447238F9,0x3135F672,0x187B95A8,
0x0B7D5751,0xACD59D2A,0x9C5D1929,0x579E5022,0xEA90499B,0x59901800,0x82237DB5,
0x7A375509,0xACA9A22A,0xEC96E649,0x69339DB0,0x081D0D9B,0xD72FB8B9,0xA4184653,
0xC057321D,0xED19CAB9,0xB48F1E3E,0xB9DAC51E,0xDAED2FC7,0x7598CBBD,0x208DF346,
0x044BE6EC,0x1C63E6EB,0xA15F64C1,0xE024A061,0x68309584,0x0758A68D,0xF274E9AE,
0x0ABEA0CC,0xED4FB267,0x63D6EC46,0x9F28E026,0xF0694A17,0x9D6E9115,0xC4600FAD,
0x5B121E99,0xD6B4A13B,0xF5364B8A,0x8514B254,0x0182F8DD,0xDB09F90B,0x78C70B32,
0xD8EC3B02,0x8CD7084D,0xA4439838,0x72F35A3D,0x200B48A5,0xE2351444,0xA5552F5F,
0xD8C1E746,0x0FE5EF3C,0xB6A47063,0x61F4E68B,0x08FED99B,0x7E461445,0x43CB8380,
0x28BA03C8,0x21A7A2E2,0x43437ED6,0x2A9E6670,0x89B4A106,0xC6C2F4EE,0x9C4063CC,
0x2FA0DF6C,0xB54DC409,0xCF01538F,0x616431D7,0x02CB0E4D,0x44FFF425,0xAAD5188E,
0x0742E9BC,0xFFF41353,0x130F0A15,0x787BDC10,0x4A327B72,0x702989F7,0x5F704798,
0x8156A1BB,0x2BCA3E74,0x1911A8C4,0x5E1F27D3,0x07949DC7,0xF24C2056,0xB4299EE6,
0x9C7045D9,0xA8BF6307,0x7454AAD2,0x256425E5,0xD87DEF67,0xCFE95452,0xE7548DF7,
0xA84956C7,0xD8402C60,0xCFBD0373,0x6B6CDAFE
};
uint32_t byte_to_int32[] = {
0xC3113E7F, 0x4C353C5F, 0x7423810B, 0x258D264E, 0xDAD39DED, 0x75D0B694,
0x98CE1216, 0x93334482, 0xC5C48EA5, 0xF57E0E8B, 0x5D7F3723, 0x396B1B24,
0xA8883D9F, 0xB2A74A00, 0xF8E171AE, 0x3F01FBAB, 0x5C1840CB, 0xDDD833C4,
0x8D8CCA34, 0x32EF223A, 0x1A05B871, 0x9A9B6BFC, 0x50406A0C, 0xE7E1FC04,
0x5E07D7F6, 0x80B83660, 0x20892A62, 0xB2C6FEA6, 0x6CEC7CAA, 0x182F764B,
0x3B0353E7, 0x57FC2520, 0x4B6812D4, 0xACB654E4, 0x23C75C04, 0xB1DCD731,
0xE3AF0733, 0xF2366D39, 0xC729671B, 0xFF3BE6F2, 0xABA37E34, 0x3CDAFA38,
0xAAD18D03, 0xA8D35345, 0x08E9A92C, 0xF9324059, 0x42D821BE, 0x1BC152DD,
0x5588811C, 0x874A1F9A, 0x6E83E9CD, 0xDA6F3AF8, 0x965D4670, 0xA7A565C0,
0x68D8A9AF, 0xFC8FD8FD, 0x8FF99FF9, 0x4C9B42AE, 0x2D066A8D, 0x4D1802F7,
0x557032B2, 0x12BCF371, 0xDC29D5AE, 0x72EA361F, 0xE2835B0B, 0xDFC58966,
0x13B0F34D, 0x3FA02BCD, 0xBF282E3D, 0x7DC877F5, 0xF4848A32, 0x861E35F5,
0x7FFA0D7F, 0x515F2E4E, 0x6B235D5C, 0x55F46E24, 0x35AD2C99, 0x072654A8,
0x05163F0F, 0x9317B11A, 0xAED1FC10, 0x989444F0, 0xDB3E1814, 0x446C0CF1,
0x660BF511, 0x2F227D3A, 0xFDBA0539, 0xC649E621, 0x5204D7CE, 0x5FA386D0,
0xE5F22005, 0x97B6C8A1, 0x4AB69EC2, 0x5C7CA70D, 0x39A48EC6, 0x7BACF378,
0x8D0ED3D1, 0xE39DE582, 0xC5FBE2AB, 0x37E3D2D0, 0x06F44724, 0x73144144,
0xBA57E905, 0xB05B4307, 0xAEED8D97, 0xA68CCAC4, 0xE30DA57E, 0xED0F194B,
0x8C2B9B7A, 0x814575D5, 0x79588493, 0x81D3712A, 0x3FA892F2, 0x80F0BB94,
0x44EAF51A, 0x4E05F1D4, 0xFC69F858, 0x775E8D60, 0x22B20DD7, 0x170A87EA,
0x1077DE52, 0x3D5EC9FB, 0x0B6EB1E5, 0xF2F9CCAF, 0xA76C7DEB, 0xD8C2D873,
0xF438C592, 0x6239FEEC, 0x26D3D2A9, 0x30F6FADF, 0x4B2984CC, 0x6257F3DA,
0x0E0583E2, 0x143E5E61, 0xBB2732BF, 0x9653217A, 0x027A84EA, 0x95C9AE8B,
0x89B8B82B, 0x9F286485, 0x29F622FE, 0x52A3196B, 0x8392D95F, 0x33A79167,
0xF5DEE92A, 0x6E397DB9, 0x11931C01, 0x8DD2CD3B, 0xF9E6003D, 0xAB955AF4,
0xD38725F9, 0xDCF6F8AE, 0x7667A958, 0xE67AD995, 0xB7CF979A, 0xD88EBE5B,
0x5BA889F0, 0x078BDD90, 0x447238F9, 0x3135F672, 0x187B95A8, 0x0B7D5751,
0xACD59D2A, 0x9C5D1929, 0x579E5022, 0xEA90499B, 0x59901800, 0x82237DB5,
0x7A375509, 0xACA9A22A, 0xEC96E649, 0x69339DB0, 0x081D0D9B, 0xD72FB8B9,
0xA4184653, 0xC057321D, 0xED19CAB9, 0xB48F1E3E, 0xB9DAC51E, 0xDAED2FC7,
0x7598CBBD, 0x208DF346, 0x044BE6EC, 0x1C63E6EB, 0xA15F64C1, 0xE024A061,
0x68309584, 0x0758A68D, 0xF274E9AE, 0x0ABEA0CC, 0xED4FB267, 0x63D6EC46,
0x9F28E026, 0xF0694A17, 0x9D6E9115, 0xC4600FAD, 0x5B121E99, 0xD6B4A13B,
0xF5364B8A, 0x8514B254, 0x0182F8DD, 0xDB09F90B, 0x78C70B32, 0xD8EC3B02,
0x8CD7084D, 0xA4439838, 0x72F35A3D, 0x200B48A5, 0xE2351444, 0xA5552F5F,
0xD8C1E746, 0x0FE5EF3C, 0xB6A47063, 0x61F4E68B, 0x08FED99B, 0x7E461445,
0x43CB8380, 0x28BA03C8, 0x21A7A2E2, 0x43437ED6, 0x2A9E6670, 0x89B4A106,
0xC6C2F4EE, 0x9C4063CC, 0x2FA0DF6C, 0xB54DC409, 0xCF01538F, 0x616431D7,
0x02CB0E4D, 0x44FFF425, 0xAAD5188E, 0x0742E9BC, 0xFFF41353, 0x130F0A15,
0x787BDC10, 0x4A327B72, 0x702989F7, 0x5F704798, 0x8156A1BB, 0x2BCA3E74,
0x1911A8C4, 0x5E1F27D3, 0x07949DC7, 0xF24C2056, 0xB4299EE6, 0x9C7045D9,
0xA8BF6307, 0x7454AAD2, 0x256425E5, 0xD87DEF67, 0xCFE95452, 0xE7548DF7,
0xA84956C7, 0xD8402C60, 0xCFBD0373, 0x6B6CDAFE};
uint32_t yr_hash(
uint32_t seed,
const void* buffer,
size_t len)
uint32_t yr_hash(uint32_t seed, const void* buffer, size_t len)
{
const uint8_t* b = (uint8_t*) buffer;
@@ -111,12 +110,11 @@ uint32_t yr_hash(
return result;
}
// _yr_hash_table_lookup
//
////////////////////////////////////////////////////////////////////////////////
// Return the value associated to a given key and optionally remove it from
// the hash table. Key can be any byte sequence, namespace is a null-terminated
// string, and remove is a boolean.
//
static void* _yr_hash_table_lookup(
YR_HASH_TABLE* table,
const void* key,
@@ -140,13 +138,13 @@ static void* _yr_hash_table_lookup(
while (entry != NULL)
{
int key_match = (
(entry->key_length == key_length) &&
(memcmp(entry->key, key, key_length) == 0));
int key_match =
((entry->key_length == key_length) &&
(memcmp(entry->key, key, key_length) == 0));
int ns_match = (
(entry->ns == ns) ||
(entry->ns != NULL && ns != NULL && strcmp(entry->ns, ns) == 0));
int ns_match =
((entry->ns == ns) ||
(entry->ns != NULL && ns != NULL && strcmp(entry->ns, ns) == 0));
if (key_match && ns_match)
{
@@ -176,10 +174,7 @@ static void* _yr_hash_table_lookup(
return NULL;
}
YR_API int yr_hash_table_create(
int size,
YR_HASH_TABLE** table)
YR_API int yr_hash_table_create(int size, YR_HASH_TABLE** table)
{
YR_HASH_TABLE* new_table;
int i;
@@ -192,15 +187,13 @@ YR_API int yr_hash_table_create(
new_table->size = size;
for (i = 0; i < size; i++)
new_table->buckets[i] = NULL;
for (i = 0; i < size; i++) new_table->buckets[i] = NULL;
*table = new_table;
return ERROR_SUCCESS;
}
YR_API void yr_hash_table_clean(
YR_HASH_TABLE* table,
YR_HASH_TABLE_FREE_VALUE_FUNC free_value)
@@ -237,7 +230,6 @@ YR_API void yr_hash_table_clean(
}
}
YR_API void yr_hash_table_destroy(
YR_HASH_TABLE* table,
YR_HASH_TABLE_FREE_VALUE_FUNC free_value)
@@ -246,7 +238,6 @@ YR_API void yr_hash_table_destroy(
yr_free(table);
}
YR_API void* yr_hash_table_lookup_raw_key(
YR_HASH_TABLE* table,
const void* key,
@@ -256,7 +247,6 @@ YR_API void* yr_hash_table_lookup_raw_key(
return _yr_hash_table_lookup(table, key, key_length, ns, false);
}
YR_API void* yr_hash_table_remove_raw_key(
YR_HASH_TABLE* table,
const void* key,
@@ -266,7 +256,6 @@ YR_API void* yr_hash_table_remove_raw_key(
return _yr_hash_table_lookup(table, key, key_length, ns, true);
}
YR_API int yr_hash_table_add_raw_key(
YR_HASH_TABLE* table,
const void* key,
@@ -325,48 +314,31 @@ YR_API int yr_hash_table_add_raw_key(
return ERROR_SUCCESS;
}
YR_API void* yr_hash_table_lookup(
YR_HASH_TABLE* table,
const char* key,
const char* ns)
{
return yr_hash_table_lookup_raw_key(
table,
(void*) key,
strlen(key),
ns);
return yr_hash_table_lookup_raw_key(table, (void*) key, strlen(key), ns);
}
YR_API void* yr_hash_table_remove(
YR_HASH_TABLE* table,
const char* key,
const char* ns)
{
return yr_hash_table_remove_raw_key(
table,
(void*) key,
strlen(key),
ns);
return yr_hash_table_remove_raw_key(table, (void*) key, strlen(key), ns);
}
YR_API int yr_hash_table_add(
YR_HASH_TABLE* table,
const char* key,
const char* ns,
void* value)
{
return yr_hash_table_add_raw_key(
table,
(void*) key,
strlen(key),
ns,
value);
return yr_hash_table_add_raw_key(table, (void*) key, strlen(key), ns, value);
}
YR_API int yr_hash_table_add_uint32(
YR_HASH_TABLE* table,
const char* key,
@@ -374,27 +346,18 @@ YR_API int yr_hash_table_add_uint32(
uint32_t value)
{
return yr_hash_table_add_uint32_raw_key(
table,
(void*) key,
strlen(key),
ns,
value);
table, (void*) key, strlen(key), ns, value);
}
YR_API uint32_t yr_hash_table_lookup_uint32(
YR_HASH_TABLE* table,
const char* key,
const char* ns)
{
return yr_hash_table_lookup_uint32_raw_key(
table,
(void*) key,
strlen(key),
ns);
table, (void*) key, strlen(key), ns);
}
YR_API int yr_hash_table_add_uint32_raw_key(
YR_HASH_TABLE* table,
const void* key,
@@ -410,10 +373,9 @@ YR_API int yr_hash_table_add_uint32_raw_key(
// hash table once the integer is casted to a pointer. This is undone
// by yr_hash_table_lookup_uint32.
return yr_hash_table_add_raw_key(
table, key, key_length, ns, (void*) (size_t) (value + 1));
table, key, key_length, ns, (void*) (size_t)(value + 1));
}
YR_API uint32_t yr_hash_table_lookup_uint32_raw_key(
YR_HASH_TABLE* table,
const void* key,
@@ -427,5 +389,5 @@ YR_API uint32_t yr_hash_table_lookup_uint32_raw_key(
// Remove one from the pointer before converting back to integer, see
// comment in yr_hash_table_add_uint32.
return (uint32_t) (size_t) ((uint8_t*) ptr - 1);
return (uint32_t)(size_t)((uint8_t*) ptr - 1);
}
+967 -959
View File
File diff suppressed because it is too large Load Diff
+15 -16
View File
@@ -31,10 +31,10 @@
version 2.2 of Bison. */
#ifndef YY_HEX_YY_HEX_GRAMMAR_H_INCLUDED
# define YY_HEX_YY_HEX_GRAMMAR_H_INCLUDED
#define YY_HEX_YY_HEX_GRAMMAR_H_INCLUDED
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#define YYDEBUG 0
#endif
#if YYDEBUG
extern int hex_yydebug;
@@ -42,21 +42,21 @@ extern int hex_yydebug;
/* Token type. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
enum yytokentype
{
_BYTE_ = 258,
_MASKED_BYTE_ = 259,
_NUMBER_ = 260
};
#define YYTOKENTYPE
enum yytokentype
{
_BYTE_ = 258,
_MASKED_BYTE_ = 259,
_NUMBER_ = 260
};
#endif
/* Tokens. */
#define _BYTE_ 258
#define _BYTE_ 258
#define _MASKED_BYTE_ 259
#define _NUMBER_ 260
#define _NUMBER_ 260
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
#if !defined YYSTYPE && !defined YYSTYPE_IS_DECLARED
union YYSTYPE
{
@@ -69,12 +69,11 @@ union YYSTYPE
};
typedef union YYSTYPE YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#define YYSTYPE_IS_TRIVIAL 1
#define YYSTYPE_IS_DECLARED 1
#endif
int hex_yyparse (void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env);
int hex_yyparse(void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env);
#endif /* !YY_HEX_YY_HEX_GRAMMAR_H_INCLUDED */
+1301 -1310
View File
File diff suppressed because it is too large Load Diff
+7 -7
View File
@@ -30,16 +30,16 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YR_YARA_H
#define YR_YARA_H
#include "yara/utils.h"
#include "yara/filemap.h"
#include "yara/compiler.h"
#include "yara/error.h"
#include "yara/filemap.h"
#include "yara/hash.h"
#include "yara/libyara.h"
#include "yara/mem.h"
#include "yara/modules.h"
#include "yara/object.h"
#include "yara/libyara.h"
#include "yara/error.h"
#include "yara/stream.h"
#include "yara/hash.h"
#include "yara/scanner.h"
#include "yara/mem.h"
#include "yara/stream.h"
#include "yara/utils.h"
#endif
+12 -23
View File
@@ -30,35 +30,29 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef _AHOCORASICK_H
#define _AHOCORASICK_H
#include <yara/limits.h>
#include <yara/atoms.h>
#include <yara/limits.h>
#include <yara/types.h>
// Number of bits dedicated to store the offset of the slot relative to its
// own state.
#define YR_AC_SLOT_OFFSET_BITS 9
#define YR_AC_SLOT_OFFSET_BITS 9
// Max number of slots in the transition table. This is the maximum number of
// slots that can be addressed with 23-bit indexes.
#define YR_AC_MAX_TRANSITION_TABLE_SIZE 0x800000
#define YR_AC_MAX_TRANSITION_TABLE_SIZE 0x800000
#define YR_AC_ROOT_STATE 0
#define YR_AC_NEXT_STATE(t) (t >> YR_AC_SLOT_OFFSET_BITS)
#define YR_AC_INVALID_TRANSITION(t, c) (((t) & 0x1FF) != c)
#define YR_AC_ROOT_STATE 0
#define YR_AC_NEXT_STATE(t) (t >> YR_AC_SLOT_OFFSET_BITS)
#define YR_AC_INVALID_TRANSITION(t, c) (((t) &0x1FF) != c)
#define YR_AC_MAKE_TRANSITION(state, code) \
((YR_AC_TRANSITION) \
((((YR_AC_TRANSITION) state) << YR_AC_SLOT_OFFSET_BITS) | (code)))
((YR_AC_TRANSITION)( \
(((YR_AC_TRANSITION) state) << YR_AC_SLOT_OFFSET_BITS) | (code)))
int yr_ac_automaton_create(YR_ARENA* arena, YR_AC_AUTOMATON** automaton);
int yr_ac_automaton_create(
YR_ARENA* arena,
YR_AC_AUTOMATON** automaton);
int yr_ac_automaton_destroy(
YR_AC_AUTOMATON* automaton);
int yr_ac_automaton_destroy(YR_AC_AUTOMATON* automaton);
int yr_ac_add_string(
YR_AC_AUTOMATON* automaton,
@@ -67,13 +61,8 @@ int yr_ac_add_string(
YR_ATOM_LIST_ITEM* atom,
YR_ARENA* arena);
int yr_ac_compile(YR_AC_AUTOMATON* automaton, YR_ARENA* arena);
int yr_ac_compile(
YR_AC_AUTOMATON* automaton,
YR_ARENA* arena);
void yr_ac_print_automaton(
YR_AC_AUTOMATON* automaton);
void yr_ac_print_automaton(YR_AC_AUTOMATON* automaton);
#endif
+15 -47
View File
@@ -31,19 +31,19 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define YR_ARENA_H
#include <stddef.h>
#include <yara/limits.h>
#include <yara/integers.h>
#include <yara/limits.h>
#include <yara/stream.h>
#define EOL ((uint32_t) -1)
#define YR_ARENA_FILE_VERSION 18
#define YR_ARENA_FILE_VERSION 18
#define YR_ARENA_NULL_REF \
(YR_ARENA_REF){ UINT32_MAX, UINT32_MAX }
#define YR_ARENA_NULL_REF \
(YR_ARENA_REF) { UINT32_MAX, UINT32_MAX }
#define YR_ARENA_IS_NULL_REF(ref) \
(memcmp(&(ref), &YR_ARENA_NULL_REF, sizeof(YR_ARENA_NULL_REF)) == 0)
(memcmp(&(ref), &YR_ARENA_NULL_REF, sizeof(YR_ARENA_NULL_REF)) == 0)
typedef uint32_t yr_arena_off_t;
@@ -72,7 +72,6 @@ struct YR_ARENA_REF
#pragma pack(pop)
struct YR_ARENA_BUFFER
{
// Pointer the buffer's data.
@@ -85,7 +84,6 @@ struct YR_ARENA_BUFFER
size_t used;
};
struct YR_RELOC
{
// Buffer ID associated to this relocation entry.
@@ -98,7 +96,6 @@ struct YR_RELOC
struct YR_RELOC* next;
};
/*
YR_ARENA is the structure that represents an arena.
@@ -140,8 +137,8 @@ in the structure are relocatable pointers.
struct YR_ARENA
{
// Number of users of this arena. This is set to one when the arena is created,
// and can be incremented by calling yr_arena_acquire. On each call
// Number of users of this arena. This is set to one when the arena is
// created, and can be incremented by calling yr_arena_acquire. On each call
// to yr_arena_release it gets decremented by one, if xrefs reaches zero
// the buffers and the YR_ARENA structures are freed.
int xrefs;
@@ -162,7 +159,6 @@ struct YR_ARENA
YR_RELOC* reloc_list_tail;
};
// Creates an arena with the specified number of buffers and takes ownership of
// it. Initially each buffer is empty, the first time that some data is written
// into a buffer at least initial_buffer_size are reserved for the buffer.
@@ -171,17 +167,12 @@ int yr_arena_create(
size_t initial_buffer_size,
YR_ARENA** arena);
// Takes ownership of the arena.
void yr_arena_acquire(
YR_ARENA* arena);
void yr_arena_acquire(YR_ARENA* arena);
// Release ownership of the arena. If the number of owners drops to zero the
// arena is destroyed and all its resources are freed.
int yr_arena_release(
YR_ARENA* arena);
int yr_arena_release(YR_ARENA* arena);
// Given a reference to some data within the arena, it returns a pointer to
// the data. This pointer is valid only until the next call to any of the
@@ -189,10 +180,7 @@ int yr_arena_release(
// yr_arena_allocate_xxx and yr_arena_write_xxx. These functions can cause
// the buffer to be moved to different memory location and the pointer won't
// valid any longer.
void* yr_arena_ref_to_ptr(
YR_ARENA* arena,
YR_ARENA_REF* ref);
void* yr_arena_ref_to_ptr(YR_ARENA* arena, YR_ARENA_REF* ref);
// Given a pointer into the arena, it returns a reference to it. The reference
// can be used with yr_arena_ref_to_ptr to obtain a pointer again. Unlike
@@ -203,7 +191,6 @@ int yr_arena_ptr_to_ref(
const void* address,
YR_ARENA_REF* ref);
// Given a buffer number and an offset within the buffer, returns a pointer
// to that offset. The same limitations explained for yr_arena_ref_to_ptr
// applies for the pointers returned by this function.
@@ -212,11 +199,7 @@ void* yr_arena_get_ptr(
uint32_t buffer_id,
yr_arena_off_t offset);
yr_arena_off_t yr_arena_get_current_offset(
YR_ARENA* arena,
uint32_t buffer_id);
yr_arena_off_t yr_arena_get_current_offset(YR_ARENA* arena, uint32_t buffer_id);
int yr_arena_allocate_memory(
YR_ARENA* arena,
@@ -224,14 +207,12 @@ int yr_arena_allocate_memory(
size_t size,
YR_ARENA_REF* ref);
int yr_arena_allocate_zeroed_memory(
YR_ARENA* arena,
uint32_t buffer_id,
size_t size,
YR_ARENA_REF* ref);
int yr_arena_allocate_struct(
YR_ARENA* arena,
uint32_t buffer_id,
@@ -239,12 +220,7 @@ int yr_arena_allocate_struct(
YR_ARENA_REF* ref,
...);
int yr_arena_make_ptr_relocatable(
YR_ARENA* arena,
uint32_t buffer_id,
...);
int yr_arena_make_ptr_relocatable(YR_ARENA* arena, uint32_t buffer_id, ...);
int yr_arena_write_data(
YR_ARENA* arena,
@@ -253,28 +229,20 @@ int yr_arena_write_data(
size_t size,
YR_ARENA_REF* ref);
int yr_arena_write_string(
YR_ARENA* arena,
uint32_t buffer_id,
const char* string,
YR_ARENA_REF* ref);
int yr_arena_write_uint32(
YR_ARENA* arena,
uint32_t buffer_id,
uint32_t integer,
YR_ARENA_REF* ref);
int yr_arena_load_stream(YR_STREAM* stream, YR_ARENA** arena);
int yr_arena_load_stream(
YR_STREAM* stream,
YR_ARENA** arena);
int yr_arena_save_stream(YR_ARENA* arena, YR_STREAM* stream);
int yr_arena_save_stream(
YR_ARENA* arena,
YR_STREAM* stream);
#endif // YR_ARENA_H
#endif // YR_ARENA_H
+9 -33
View File
@@ -33,9 +33,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <yara/limits.h>
#include <yara/re.h>
#define ATOM_TREE_LEAF 1
#define ATOM_TREE_AND 2
#define ATOM_TREE_OR 3
#define ATOM_TREE_LEAF 1
#define ATOM_TREE_AND 2
#define ATOM_TREE_OR 3
typedef struct YR_ATOM YR_ATOM;
typedef struct YR_ATOM_TREE_NODE YR_ATOM_TREE_NODE;
@@ -46,7 +46,6 @@ typedef struct YR_ATOM_LIST_ITEM YR_ATOM_LIST_ITEM;
typedef struct YR_ATOM_QUALITY_TABLE_ENTRY YR_ATOM_QUALITY_TABLE_ENTRY;
typedef struct YR_ATOMS_CONFIG YR_ATOMS_CONFIG;
struct YR_ATOM
{
uint8_t length;
@@ -68,13 +67,11 @@ struct YR_ATOM_TREE_NODE
YR_ATOM_TREE_NODE* next_sibling;
};
struct YR_ATOM_TREE
{
YR_ATOM_TREE_NODE* root_node;
};
struct YR_ATOM_LIST_ITEM
{
YR_ATOM atom;
@@ -87,7 +84,6 @@ struct YR_ATOM_LIST_ITEM
YR_ATOM_LIST_ITEM* next;
};
#pragma pack(push)
#pragma pack(1)
@@ -99,11 +95,7 @@ struct YR_ATOM_QUALITY_TABLE_ENTRY
#pragma pack(pop)
typedef int (*YR_ATOMS_QUALITY_FUNC)(
YR_ATOMS_CONFIG* config,
YR_ATOM* atom);
typedef int (*YR_ATOMS_QUALITY_FUNC)(YR_ATOMS_CONFIG* config, YR_ATOM* atom);
struct YR_ATOMS_CONFIG
{
@@ -115,7 +107,6 @@ struct YR_ATOMS_CONFIG
bool free_quality_table;
};
int yr_atoms_extract_from_re(
YR_ATOMS_CONFIG* config,
RE_AST* re_ast,
@@ -123,7 +114,6 @@ int yr_atoms_extract_from_re(
YR_ATOM_LIST_ITEM** atoms,
int* min_atom_quality);
int yr_atoms_extract_from_string(
YR_ATOMS_CONFIG* config,
uint8_t* string,
@@ -132,28 +122,14 @@ int yr_atoms_extract_from_string(
YR_ATOM_LIST_ITEM** atoms,
int* min_atom_quality);
int yr_atoms_extract_triplets(RE_NODE* re_node, YR_ATOM_LIST_ITEM** atoms);
int yr_atoms_extract_triplets(
RE_NODE* re_node,
YR_ATOM_LIST_ITEM** atoms);
int yr_atoms_heuristic_quality(YR_ATOMS_CONFIG* config, YR_ATOM* atom);
int yr_atoms_table_quality(YR_ATOMS_CONFIG* config, YR_ATOM* atom);
int yr_atoms_heuristic_quality(
YR_ATOMS_CONFIG* config,
YR_ATOM* atom);
int yr_atoms_min_quality(YR_ATOMS_CONFIG* config, YR_ATOM_LIST_ITEM* atom_list);
int yr_atoms_table_quality(
YR_ATOMS_CONFIG* config,
YR_ATOM* atom);
int yr_atoms_min_quality(
YR_ATOMS_CONFIG* config,
YR_ATOM_LIST_ITEM* atom_list);
void yr_atoms_list_destroy(
YR_ATOM_LIST_ITEM* list_head);
void yr_atoms_list_destroy(YR_ATOM_LIST_ITEM* list_head);
#endif
+3 -4
View File
@@ -30,18 +30,17 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YR_BASE64_H
#define YR_BASE64_H
#include <yara/types.h>
#include <yara/re.h>
#include <yara/sizedstr.h>
#include <yara/types.h>
typedef struct BASE64_NODE BASE64_NODE;
struct BASE64_NODE {
struct BASE64_NODE
{
SIZED_STRING* str;
int escaped;
BASE64_NODE* next;
};
int yr_base64_ast_from_string(
+21 -26
View File
@@ -53,43 +53,38 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define YR_BITMASK unsigned long
#define YR_BITMASK_SLOT_BITS (sizeof(YR_BITMASK) * 8)
#define YR_BITMASK_SIZE(n) (((n) / (YR_BITMASK_SLOT_BITS)) + 1)
#define YR_BITMASK_SLOT_BITS (sizeof(YR_BITMASK) * 8)
#define YR_BITMASK_SIZE(n) (((n) / (YR_BITMASK_SLOT_BITS)) + 1)
#define yr_bitmask_set(bm, i) \
do { \
#define yr_bitmask_set(bm, i) \
do \
{ \
(bm)[(i) / YR_BITMASK_SLOT_BITS] |= 1UL << ((i) % YR_BITMASK_SLOT_BITS); \
} while(0)
} while (0)
#define yr_bitmask_clear(bm, i) \
do \
{ \
(bm)[(i) / YR_BITMASK_SLOT_BITS] &= ~( \
1UL << ((i) % YR_BITMASK_SLOT_BITS)); \
} while (0)
#define yr_bitmask_clear(bm, i) \
do { \
(bm)[(i) / YR_BITMASK_SLOT_BITS] &= ~(1UL << ((i) % YR_BITMASK_SLOT_BITS)); \
} while(0)
#define yr_bitmask_clear_all(bm) \
memset(bm, 0, sizeof(bm))
#define yr_bitmask_clear_all(bm) memset(bm, 0, sizeof(bm))
#define yr_bitmask_is_set(bm, i) \
( \
(bm)[(i) / YR_BITMASK_SLOT_BITS] & (1UL << ((i) % YR_BITMASK_SLOT_BITS)) \
)
((bm)[(i) / YR_BITMASK_SLOT_BITS] & (1UL << ((i) % YR_BITMASK_SLOT_BITS)))
#define yr_bitmask_is_not_set(bm, i) (!yr_bitmask_is_set(bm, i))
#define yr_bitmask_print(bm) \
{ \
int i; \
for (i = 0; i < sizeof(bm) / sizeof(bm[0]); i++) { \
printf("%016lX\n", bm[i]); \
} \
#define yr_bitmask_print(bm) \
{ \
int i; \
for (i = 0; i < sizeof(bm) / sizeof(bm[0]); i++) \
{ \
printf("%016lX\n", bm[i]); \
} \
}
uint32_t yr_bitmask_find_non_colliding_offset(
YR_BITMASK* a,
YR_BITMASK* b,
+79 -127
View File
@@ -30,62 +30,56 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YR_COMPILER_H
#define YR_COMPILER_H
#include <stdio.h>
#include <setjmp.h>
#include <stdio.h>
#include <yara/ahocorasick.h>
#include <yara/arena.h>
#include <yara/filemap.h>
#include <yara/hash.h>
#include <yara/utils.h>
#include <yara/filemap.h>
#define YARA_ERROR_LEVEL_ERROR 0
#define YARA_ERROR_LEVEL_WARNING 1
// Expression type constants are powers of two because they are used as flags.
#define EXPRESSION_TYPE_UNKNOWN 0
#define EXPRESSION_TYPE_BOOLEAN 1
#define EXPRESSION_TYPE_INTEGER 2
#define EXPRESSION_TYPE_STRING 4
#define EXPRESSION_TYPE_REGEXP 8
#define EXPRESSION_TYPE_OBJECT 16
#define EXPRESSION_TYPE_FLOAT 32
#define EXPRESSION_TYPE_UNKNOWN 0
#define EXPRESSION_TYPE_BOOLEAN 1
#define EXPRESSION_TYPE_INTEGER 2
#define EXPRESSION_TYPE_STRING 4
#define EXPRESSION_TYPE_REGEXP 8
#define EXPRESSION_TYPE_OBJECT 16
#define EXPRESSION_TYPE_FLOAT 32
// The compiler uses an arena to store the data it generates during the
// compilation. Each buffer in the arena is used for storing a different type
// of data. The following identifiers indicate the purpose of each buffer.
#define YR_NAMESPACES_TABLE 0
#define YR_RULES_TABLE 1
#define YR_METAS_TABLE 2
#define YR_STRINGS_TABLE 3
#define YR_EXTERNAL_VARIABLES_TABLE 4
#define YR_SZ_POOL 5
#define YR_CODE_SECTION 6
#define YR_RE_CODE_SECTION 7
#define YR_AC_TRANSITION_TABLE 8
#define YR_AC_STATE_MATCHES_TABLE 9
#define YR_AC_STATE_MATCHES_POOL 10
#define YR_SUMMARY_SECTION 11
#define YR_NAMESPACES_TABLE 0
#define YR_RULES_TABLE 1
#define YR_METAS_TABLE 2
#define YR_STRINGS_TABLE 3
#define YR_EXTERNAL_VARIABLES_TABLE 4
#define YR_SZ_POOL 5
#define YR_CODE_SECTION 6
#define YR_RE_CODE_SECTION 7
#define YR_AC_TRANSITION_TABLE 8
#define YR_AC_STATE_MATCHES_TABLE 9
#define YR_AC_STATE_MATCHES_POOL 10
#define YR_SUMMARY_SECTION 11
// This is the number of buffers used by the compiler, should match the number
// of items in the list above.
#define YR_NUM_SECTIONS 12
#define YR_NUM_SECTIONS 12
// Number of variables used by loops. This doesn't include user defined
// variables.
#define YR_INTERNAL_LOOP_VARS 3
#define YR_INTERNAL_LOOP_VARS 3
typedef struct _YR_EXPRESSION
{
int type;
union {
union
{
int64_t integer;
YR_OBJECT* object;
YR_ARENA_REF sized_string_ref;
@@ -96,14 +90,14 @@ typedef struct _YR_EXPRESSION
// to the identifier within YR_SZ_POOL. When the identifier is in YR_SZ_POOL
// a pointer can't be used as the YR_SZ_POOL can be moved to a different
// memory location.
struct {
struct
{
const char* ptr;
YR_ARENA_REF ref;
} identifier ;
} identifier;
} YR_EXPRESSION;
typedef void (*YR_COMPILER_CALLBACK_FUNC)(
int error_level,
const char* file_name,
@@ -112,26 +106,22 @@ typedef void (*YR_COMPILER_CALLBACK_FUNC)(
const char* message,
void* user_data);
typedef const char* (*YR_COMPILER_INCLUDE_CALLBACK_FUNC)(
const char* include_name,
const char* calling_rule_filename,
const char* calling_rule_namespace,
void* user_data);
typedef void (*YR_COMPILER_INCLUDE_FREE_FUNC)(
const char* callback_result_ptr,
void* user_data);
typedef void (*YR_COMPILER_RE_AST_CALLBACK_FUNC)(
const YR_RULE* rule,
const char* string_identifier,
const RE_AST* re_ast,
void* user_data);
typedef struct _YR_FIXUP
{
YR_ARENA_REF ref;
@@ -139,7 +129,6 @@ typedef struct _YR_FIXUP
} YR_FIXUP;
// Each "for" loop in the condition has an associated context which holds
// information about loop, like the target address for the jump instruction
// that goes back to the beginning of the loop and the local variables used
@@ -154,16 +143,15 @@ typedef struct _YR_LOOP_CONTEXT
// vars_count is the number of local variables defined by the loop, and vars
// is an array of expressions with the identifier and type for each of those
// local variables.
int vars_count;
YR_EXPRESSION vars[YR_MAX_LOOP_VARS];
int vars_count;
YR_EXPRESSION vars[YR_MAX_LOOP_VARS];
// vars_internal_count is the number of variables used by the loop which are
// not defined by the rule itself but that are necessary for keeping the
// loop's state. One example is the iteration counter.
int vars_internal_count;
int vars_internal_count;
} YR_LOOP_CONTEXT;
typedef struct _YR_COMPILER
{
// Arena that contains the data generated by the compiled. The arena has
@@ -229,84 +217,75 @@ typedef struct _YR_COMPILER
// Pointer to a YR_RULES structure that represents the compiled rules. This
// is what yr_compiler_get_rules returns. Once these rules are generated you
// can't call any of the yr_compiler_add_xxx functions.
YR_RULES* rules;
YR_RULES* rules;
int errors;
int current_line;
int last_error;
int last_error_line;
int errors;
int current_line;
int last_error;
int last_error_line;
jmp_buf error_recovery;
jmp_buf error_recovery;
YR_AC_AUTOMATON* automaton;
YR_HASH_TABLE* rules_table;
YR_HASH_TABLE* objects_table;
YR_HASH_TABLE* strings_table;
YR_AC_AUTOMATON* automaton;
YR_HASH_TABLE* rules_table;
YR_HASH_TABLE* objects_table;
YR_HASH_TABLE* strings_table;
// Hash table that contains all the strings that has been written to the
// YR_SZ_POOL buffer in the compiler's arena. Values in the hash table are
// the offset within the YR_SZ_POOL where the string resides. This allows to
// know is some string has already been written in order to reuse instead of
// writting it again.
YR_HASH_TABLE* sz_table;
YR_HASH_TABLE* sz_table;
YR_FIXUP* fixup_stack_head;
YR_FIXUP* fixup_stack_head;
int num_namespaces;
int num_namespaces;
YR_LOOP_CONTEXT loop[YR_MAX_LOOP_NESTING];
int loop_index;
int loop_for_of_var_index;
YR_LOOP_CONTEXT loop[YR_MAX_LOOP_NESTING];
int loop_index;
int loop_for_of_var_index;
char* file_name_stack[YR_MAX_INCLUDE_DEPTH];
int file_name_stack_ptr;
char* file_name_stack[YR_MAX_INCLUDE_DEPTH];
int file_name_stack_ptr;
char last_error_extra_info[YR_MAX_COMPILER_ERROR_EXTRA_INFO];
char last_error_extra_info[YR_MAX_COMPILER_ERROR_EXTRA_INFO];
char lex_buf[YR_LEX_BUF_SIZE];
char* lex_buf_ptr;
unsigned short lex_buf_len;
char lex_buf[YR_LEX_BUF_SIZE];
char* lex_buf_ptr;
unsigned short lex_buf_len;
char include_base_dir[MAX_PATH];
void* user_data;
void* incl_clbk_user_data;
void* re_ast_clbk_user_data;
char include_base_dir[MAX_PATH];
void* user_data;
void* incl_clbk_user_data;
void* re_ast_clbk_user_data;
YR_COMPILER_CALLBACK_FUNC callback;
YR_COMPILER_INCLUDE_CALLBACK_FUNC include_callback;
YR_COMPILER_INCLUDE_FREE_FUNC include_free;
YR_COMPILER_RE_AST_CALLBACK_FUNC re_ast_callback;
YR_ATOMS_CONFIG atoms_config;
YR_COMPILER_CALLBACK_FUNC callback;
YR_COMPILER_INCLUDE_CALLBACK_FUNC include_callback;
YR_COMPILER_INCLUDE_FREE_FUNC include_free;
YR_COMPILER_RE_AST_CALLBACK_FUNC re_ast_callback;
YR_ATOMS_CONFIG atoms_config;
} YR_COMPILER;
#define yr_compiler_set_error_extra_info(compiler, info) \
strlcpy( \
compiler->last_error_extra_info, \
info, \
sizeof(compiler->last_error_extra_info)); \
strlcpy( \
compiler->last_error_extra_info, \
info, \
sizeof(compiler->last_error_extra_info));
#define yr_compiler_set_error_extra_info_fmt(compiler, fmt, ...) \
snprintf( \
compiler->last_error_extra_info, \
sizeof(compiler->last_error_extra_info), \
fmt, __VA_ARGS__);
snprintf( \
compiler->last_error_extra_info, \
sizeof(compiler->last_error_extra_info), \
fmt, \
__VA_ARGS__);
int _yr_compiler_push_file_name(YR_COMPILER* compiler, const char* file_name);
int _yr_compiler_push_file_name(
YR_COMPILER* compiler,
const char* file_name);
void _yr_compiler_pop_file_name(
YR_COMPILER* compiler);
int _yr_compiler_get_var_frame(
YR_COMPILER* compiler);
void _yr_compiler_pop_file_name(YR_COMPILER* compiler);
int _yr_compiler_get_var_frame(YR_COMPILER* compiler);
const char* _yr_compiler_default_include_callback(
const char* include_name,
@@ -314,121 +293,94 @@ const char* _yr_compiler_default_include_callback(
const char* calling_rule_namespace,
void* user_data);
YR_RULE* _yr_compiler_get_rule_by_idx(
YR_COMPILER* compiler, uint32_t rule_idx);
YR_RULE* _yr_compiler_get_rule_by_idx(YR_COMPILER* compiler, uint32_t rule_idx);
int _yr_compiler_store_string(
YR_COMPILER* compiler,
const char* string,
YR_ARENA_REF* ref);
int _yr_compiler_store_data(
YR_COMPILER* compiler,
const void* data,
size_t data_length,
YR_ARENA_REF* ref);
YR_API int yr_compiler_create(YR_COMPILER** compiler);
YR_API int yr_compiler_create(
YR_COMPILER** compiler);
YR_API void yr_compiler_destroy(
YR_COMPILER* compiler);
YR_API void yr_compiler_destroy(YR_COMPILER* compiler);
YR_API void yr_compiler_set_callback(
YR_COMPILER* compiler,
YR_COMPILER_CALLBACK_FUNC callback,
void* user_data);
YR_API void yr_compiler_set_include_callback(
YR_COMPILER* compiler,
YR_COMPILER_INCLUDE_CALLBACK_FUNC include_callback,
YR_COMPILER_INCLUDE_FREE_FUNC include_free,
void* user_data);
YR_API void yr_compiler_set_re_ast_callback(
YR_COMPILER* compiler,
YR_COMPILER_RE_AST_CALLBACK_FUNC re_ast_callback,
void* user_data);
YR_API void yr_compiler_set_atom_quality_table(
YR_COMPILER* compiler,
const void* table,
int entries,
unsigned char warning_threshold);
YR_API int yr_compiler_load_atom_quality_table(
YR_COMPILER* compiler,
const char* filename,
unsigned char warning_threshold);
YR_API int yr_compiler_add_file(
YR_COMPILER* compiler,
FILE* rules_file,
const char* namespace_,
const char* file_name);
YR_API int yr_compiler_add_fd(
YR_COMPILER* compiler,
YR_FILE_DESCRIPTOR rules_fd,
const char* namespace_,
const char* file_name);
YR_API int yr_compiler_add_string(
YR_COMPILER* compiler,
const char* rules_string,
const char* namespace_);
YR_API char* yr_compiler_get_error_message(
YR_COMPILER* compiler,
char* buffer,
int buffer_size);
YR_API char* yr_compiler_get_current_file_name(
YR_COMPILER* compiler);
YR_API char* yr_compiler_get_current_file_name(YR_COMPILER* compiler);
YR_API int yr_compiler_define_integer_variable(
YR_COMPILER* compiler,
const char* identifier,
int64_t value);
YR_API int yr_compiler_define_boolean_variable(
YR_COMPILER* compiler,
const char* identifier,
int value);
YR_API int yr_compiler_define_float_variable(
YR_COMPILER* compiler,
const char* identifier,
double value);
YR_API int yr_compiler_define_string_variable(
YR_COMPILER* compiler,
const char* identifier,
const char* value);
YR_API int yr_compiler_get_rules(
YR_COMPILER* compiler,
YR_RULES** rules);
YR_API int yr_compiler_get_rules(YR_COMPILER* compiler, YR_RULES** rules);
#endif
+91 -83
View File
@@ -2,7 +2,6 @@
#define _DEX_H
#include <stdlib.h>
#include <yara/integers.h>
#include <yara/types.h>
@@ -12,123 +11,132 @@
#define DEX_FILE_MAGIC_038 "dex\n038\x00"
#define DEX_FILE_MAGIC_039 "dex\n039\x00"
#pragma pack(push,1)
#pragma pack(push, 1)
typedef struct
{
uint8_t magic[8];
uint32_t checksum;
uint8_t signature[20];
uint32_t file_size;
uint32_t header_size;
uint32_t endian_tag;
uint32_t link_size;
uint32_t link_offset;
uint32_t map_offset;
uint32_t string_ids_size;
uint32_t string_ids_offset;
uint32_t type_ids_size;
uint32_t type_ids_offset;
uint32_t proto_ids_size;
uint32_t proto_ids_offset;
uint32_t field_ids_size;
uint32_t field_ids_offset;
uint32_t method_ids_size;
uint32_t method_ids_offset;
uint32_t class_defs_size;
uint32_t class_defs_offset;
uint32_t data_size;
uint32_t data_offset;
uint8_t magic[8];
uint32_t checksum;
uint8_t signature[20];
uint32_t file_size;
uint32_t header_size;
uint32_t endian_tag;
uint32_t link_size;
uint32_t link_offset;
uint32_t map_offset;
uint32_t string_ids_size;
uint32_t string_ids_offset;
uint32_t type_ids_size;
uint32_t type_ids_offset;
uint32_t proto_ids_size;
uint32_t proto_ids_offset;
uint32_t field_ids_size;
uint32_t field_ids_offset;
uint32_t method_ids_size;
uint32_t method_ids_offset;
uint32_t class_defs_size;
uint32_t class_defs_offset;
uint32_t data_size;
uint32_t data_offset;
} dex_header_t;
typedef struct {
uint32_t string_data_offset;
typedef struct
{
uint32_t string_data_offset;
} string_id_item_t;
typedef struct {
uint32_t utf16_size;
typedef struct
{
uint32_t utf16_size;
} string_data_item_t;
typedef struct {
uint32_t descriptor_idx;
typedef struct
{
uint32_t descriptor_idx;
} type_id_item_t;
typedef struct {
uint32_t shorty_idx;
uint32_t return_type_idx;
uint32_t parameters_offset;
typedef struct
{
uint32_t shorty_idx;
uint32_t return_type_idx;
uint32_t parameters_offset;
} proto_id_item_t;
typedef struct {
uint16_t class_idx;
uint16_t type_idx;
uint32_t name_idx;
typedef struct
{
uint16_t class_idx;
uint16_t type_idx;
uint32_t name_idx;
} field_id_item_t;
typedef struct {
uint16_t class_idx;
uint16_t proto_idx;
uint32_t name_idx;
typedef struct
{
uint16_t class_idx;
uint16_t proto_idx;
uint32_t name_idx;
} method_id_item_t;
typedef struct {
uint32_t class_idx;
uint32_t access_flags;
uint32_t super_class_idx;
uint32_t interfaces_offset;
uint32_t source_file_idx;
uint32_t annotations_offset;
uint32_t class_data_offset;
uint32_t static_values_offset;
typedef struct
{
uint32_t class_idx;
uint32_t access_flags;
uint32_t super_class_idx;
uint32_t interfaces_offset;
uint32_t source_file_idx;
uint32_t annotations_offset;
uint32_t class_data_offset;
uint32_t static_values_offset;
} class_id_item_t;
typedef struct {
uint32_t static_fields_size;
uint32_t instance_fields_size;
uint32_t direct_methods_size;
uint32_t virtual_methods_size;
typedef struct
{
uint32_t static_fields_size;
uint32_t instance_fields_size;
uint32_t direct_methods_size;
uint32_t virtual_methods_size;
} class_data_item_t;
typedef struct {
uint32_t field_idx_diff;
uint32_t access_flags;
typedef struct
{
uint32_t field_idx_diff;
uint32_t access_flags;
} encoded_field_t;
typedef struct {
uint32_t method_idx_diff;
uint32_t access_flags;
uint32_t code_off;
typedef struct
{
uint32_t method_idx_diff;
uint32_t access_flags;
uint32_t code_off;
} encoded_method_t;
typedef struct {
uint16_t registers_size;
uint16_t ins_size;
uint16_t outs_size;
uint16_t tries_size;
uint32_t debug_info_off;
uint32_t insns_size;
typedef struct
{
uint16_t registers_size;
uint16_t ins_size;
uint16_t outs_size;
uint16_t tries_size;
uint32_t debug_info_off;
uint32_t insns_size;
} code_item_t;
typedef struct {
uint16_t type;
uint16_t unused;
uint32_t size;
uint32_t offset;
typedef struct
{
uint16_t type;
uint16_t unused;
uint32_t size;
uint32_t offset;
} map_item_t;
typedef struct _DEX
{
const uint8_t* data;
size_t data_size;
dex_header_t *header;
dex_header_t* header;
YR_OBJECT* object;
} DEX;
#define fits_in_dex(dex, pointer, size) \
((size_t) size <= dex->data_size && \
(uint8_t*) (pointer) >= dex->data && \
#define fits_in_dex(dex, pointer, size) \
((size_t) size <= dex->data_size && (uint8_t*) (pointer) >= dex->data && \
(uint8_t*) (pointer) <= dex->data + dex->data_size - size)
#define struct_fits_in_dex(dex, pointer, struct_type) \
@@ -136,4 +144,4 @@ typedef struct _DEX
#pragma pack(pop)
#endif
#endif
+234 -209
View File
@@ -1,25 +1,28 @@
#ifndef YR_DOTNET_H
#define YR_DOTNET_H
#include <yara/pe.h>
#pragma pack(push, 1)
//
// CLI header.
// ECMA-335 Section II.25.3.3
//
typedef struct _CLI_HEADER {
DWORD Size; // Called "Cb" in documentation.
WORD MajorRuntimeVersion;
WORD MinorRuntimeVersion;
IMAGE_DATA_DIRECTORY MetaData;
DWORD Flags;
DWORD EntryPointToken;
IMAGE_DATA_DIRECTORY Resources;
IMAGE_DATA_DIRECTORY StrongNameSignature;
ULONGLONG CodeManagerTable;
IMAGE_DATA_DIRECTORY VTableFixups;
ULONGLONG ExportAddressTableJumps;
ULONGLONG ManagedNativeHeader;
typedef struct _CLI_HEADER
{
DWORD Size; // Called "Cb" in documentation.
WORD MajorRuntimeVersion;
WORD MinorRuntimeVersion;
IMAGE_DATA_DIRECTORY MetaData;
DWORD Flags;
DWORD EntryPointToken;
IMAGE_DATA_DIRECTORY Resources;
IMAGE_DATA_DIRECTORY StrongNameSignature;
ULONGLONG CodeManagerTable;
IMAGE_DATA_DIRECTORY VTableFixups;
ULONGLONG ExportAddressTableJumps;
ULONGLONG ManagedNativeHeader;
} CLI_HEADER, *PCLI_HEADER;
#define NET_METADATA_MAGIC 0x424a5342
@@ -30,13 +33,14 @@ typedef struct _CLI_HEADER {
//
// Note: This is only part of the struct, as the rest of it is variable length.
//
typedef struct _NET_METADATA {
DWORD Magic;
WORD MajorVersion;
WORD MinorVersion;
DWORD Reserved;
DWORD Length;
char Version[0];
typedef struct _NET_METADATA
{
DWORD Magic;
WORD MajorVersion;
WORD MinorVersion;
DWORD Reserved;
DWORD Length;
char Version[0];
} NET_METADATA, *PNET_METADATA;
#define DOTNET_STREAM_NAME_SIZE 32
@@ -45,74 +49,75 @@ typedef struct _NET_METADATA {
// CLI Stream Header
// ECMA-335 Section II.24.2.2
//
typedef struct _STREAM_HEADER {
DWORD Offset;
DWORD Size;
char Name[0];
typedef struct _STREAM_HEADER
{
DWORD Offset;
DWORD Size;
char Name[0];
} STREAM_HEADER, *PSTREAM_HEADER;
//
// CLI #~ Stream Header
// ECMA-335 Section II.24.2.6
//
typedef struct _TILDE_HEADER {
DWORD Reserved1;
BYTE MajorVersion;
BYTE MinorVersion;
BYTE HeapSizes;
BYTE Reserved2;
ULONGLONG Valid;
ULONGLONG Sorted;
typedef struct _TILDE_HEADER
{
DWORD Reserved1;
BYTE MajorVersion;
BYTE MinorVersion;
BYTE HeapSizes;
BYTE Reserved2;
ULONGLONG Valid;
ULONGLONG Sorted;
} TILDE_HEADER, *PTILDE_HEADER;
// These are the bit positions in Valid which will be set if the table
// exists.
#define BIT_MODULE 0x00
#define BIT_TYPEREF 0x01
#define BIT_TYPEDEF 0x02
#define BIT_FIELDPTR 0x03 // Not documented in ECMA-335
#define BIT_FIELD 0x04
#define BIT_METHODDEFPTR 0x05 // Not documented in ECMA-335
#define BIT_METHODDEF 0x06
#define BIT_PARAMPTR 0x07 // Not documented in ECMA-335
#define BIT_PARAM 0x08
#define BIT_INTERFACEIMPL 0x09
#define BIT_MEMBERREF 0x0A
#define BIT_CONSTANT 0x0B
#define BIT_CUSTOMATTRIBUTE 0x0C
#define BIT_FIELDMARSHAL 0x0D
#define BIT_DECLSECURITY 0x0E
#define BIT_CLASSLAYOUT 0x0F
#define BIT_FIELDLAYOUT 0x10
#define BIT_STANDALONESIG 0x11
#define BIT_EVENTMAP 0x12
#define BIT_EVENTPTR 0x13 // Not documented in ECMA-335
#define BIT_EVENT 0x14
#define BIT_PROPERTYMAP 0x15
#define BIT_PROPERTYPTR 0x16 // Not documented in ECMA-335
#define BIT_PROPERTY 0x17
#define BIT_METHODSEMANTICS 0x18
#define BIT_METHODIMPL 0x19
#define BIT_MODULEREF 0x1A
#define BIT_TYPESPEC 0x1B
#define BIT_IMPLMAP 0x1C
#define BIT_FIELDRVA 0x1D
#define BIT_ENCLOG 0x1E // Not documented in ECMA-335
#define BIT_ENCMAP 0x1F // Not documented in ECMA-335
#define BIT_ASSEMBLY 0x20
#define BIT_ASSEMBLYPROCESSOR 0x21
#define BIT_ASSEMBLYOS 0x22
#define BIT_ASSEMBLYREF 0x23
#define BIT_ASSEMBLYREFPROCESSOR 0x24
#define BIT_ASSEMBLYREFOS 0x25
#define BIT_FILE 0x26
#define BIT_EXPORTEDTYPE 0x27
#define BIT_MANIFESTRESOURCE 0x28
#define BIT_NESTEDCLASS 0x29
#define BIT_GENERICPARAM 0x2A
#define BIT_METHODSPEC 0x2B
#define BIT_GENERICPARAMCONSTRAINT 0x2C
#define BIT_MODULE 0x00
#define BIT_TYPEREF 0x01
#define BIT_TYPEDEF 0x02
#define BIT_FIELDPTR 0x03 // Not documented in ECMA-335
#define BIT_FIELD 0x04
#define BIT_METHODDEFPTR 0x05 // Not documented in ECMA-335
#define BIT_METHODDEF 0x06
#define BIT_PARAMPTR 0x07 // Not documented in ECMA-335
#define BIT_PARAM 0x08
#define BIT_INTERFACEIMPL 0x09
#define BIT_MEMBERREF 0x0A
#define BIT_CONSTANT 0x0B
#define BIT_CUSTOMATTRIBUTE 0x0C
#define BIT_FIELDMARSHAL 0x0D
#define BIT_DECLSECURITY 0x0E
#define BIT_CLASSLAYOUT 0x0F
#define BIT_FIELDLAYOUT 0x10
#define BIT_STANDALONESIG 0x11
#define BIT_EVENTMAP 0x12
#define BIT_EVENTPTR 0x13 // Not documented in ECMA-335
#define BIT_EVENT 0x14
#define BIT_PROPERTYMAP 0x15
#define BIT_PROPERTYPTR 0x16 // Not documented in ECMA-335
#define BIT_PROPERTY 0x17
#define BIT_METHODSEMANTICS 0x18
#define BIT_METHODIMPL 0x19
#define BIT_MODULEREF 0x1A
#define BIT_TYPESPEC 0x1B
#define BIT_IMPLMAP 0x1C
#define BIT_FIELDRVA 0x1D
#define BIT_ENCLOG 0x1E // Not documented in ECMA-335
#define BIT_ENCMAP 0x1F // Not documented in ECMA-335
#define BIT_ASSEMBLY 0x20
#define BIT_ASSEMBLYPROCESSOR 0x21
#define BIT_ASSEMBLYOS 0x22
#define BIT_ASSEMBLYREF 0x23
#define BIT_ASSEMBLYREFPROCESSOR 0x24
#define BIT_ASSEMBLYREFOS 0x25
#define BIT_FILE 0x26
#define BIT_EXPORTEDTYPE 0x27
#define BIT_MANIFESTRESOURCE 0x28
#define BIT_NESTEDCLASS 0x29
#define BIT_GENERICPARAM 0x2A
#define BIT_METHODSPEC 0x2B
#define BIT_GENERICPARAMCONSTRAINT 0x2C
// These are not documented in ECMA-335 nor is it clear what the format is.
// They are for debugging information as far as I can tell.
//#define BIT_DOCUMENT 0x30
@@ -123,7 +128,6 @@ typedef struct _TILDE_HEADER {
//#define BIT_IMPORTSCOPE 0x35
//#define BIT_STATEMACHINEMETHOD 0x36
//
// Element types. Note this is not a complete list as we aren't parsing all of
// them. This only includes the ones we care about.
@@ -131,7 +135,6 @@ typedef struct _TILDE_HEADER {
//
#define ELEMENT_TYPE_STRING 0x0E
// The string length of a typelib attribute is at most 0xFF.
#define MAX_TYPELIB_SIZE 0xFF
@@ -139,84 +142,96 @@ typedef struct _TILDE_HEADER {
// Module table
// ECMA-335 Section II.22.30
//
typedef struct _MODULE_TABLE {
WORD Generation;
union {
WORD Name_Short;
DWORD Name_Long;
} Name;
union {
WORD Mvid_Short;
DWORD Mvid_Long;
} Mvid;
union {
WORD EncId_Short;
DWORD EncId_Long;
} EncId;
union {
WORD EncBaseId_Short;
DWORD EncBaseId_Long;
} EncBaseId;
typedef struct _MODULE_TABLE
{
WORD Generation;
union
{
WORD Name_Short;
DWORD Name_Long;
} Name;
union
{
WORD Mvid_Short;
DWORD Mvid_Long;
} Mvid;
union
{
WORD EncId_Short;
DWORD EncId_Long;
} EncId;
union
{
WORD EncBaseId_Short;
DWORD EncBaseId_Long;
} EncBaseId;
} MODULE_TABLE, *PMODULE_TABLE;
//
// Assembly Table
// ECMA-335 Section II.22.2
//
typedef struct _ASSEMBLY_TABLE {
DWORD HashAlgId;
WORD MajorVersion;
WORD MinorVersion;
WORD BuildNumber;
WORD RevisionNumber;
DWORD Flags;
union {
WORD PublicKey_Short;
DWORD PublicKey_Long;
} PublicKey;
union {
WORD Name_Short;
DWORD Name_Long;
} Name;
typedef struct _ASSEMBLY_TABLE
{
DWORD HashAlgId;
WORD MajorVersion;
WORD MinorVersion;
WORD BuildNumber;
WORD RevisionNumber;
DWORD Flags;
union
{
WORD PublicKey_Short;
DWORD PublicKey_Long;
} PublicKey;
union
{
WORD Name_Short;
DWORD Name_Long;
} Name;
} ASSEMBLY_TABLE, *PASSEMBLY_TABLE;
//
// Assembly Reference Table
// ECMA-335 Section II.22.5
//
typedef struct _ASSEMBLYREF_TABLE {
WORD MajorVersion;
WORD MinorVersion;
WORD BuildNumber;
WORD RevisionNumber;
DWORD Flags;
union {
WORD PublicKeyOrToken_Short;
DWORD PublicKeyOrToken_Long;
} PublicKeyOrToken;
union {
WORD Name_Short;
DWORD Name_Long;
} Name;
typedef struct _ASSEMBLYREF_TABLE
{
WORD MajorVersion;
WORD MinorVersion;
WORD BuildNumber;
WORD RevisionNumber;
DWORD Flags;
union
{
WORD PublicKeyOrToken_Short;
DWORD PublicKeyOrToken_Long;
} PublicKeyOrToken;
union
{
WORD Name_Short;
DWORD Name_Long;
} Name;
} ASSEMBLYREF_TABLE, *PASSEMBLYREF_TABLE;
//
// Manifest Resource Table
// ECMA-335 Section II.22.24
//
typedef struct _MANIFESTRESOURCE_TABLE {
DWORD Offset;
DWORD Flags;
union {
WORD Name_Short;
DWORD Name_Long;
} Name;
union {
WORD Implementation_Short;
DWORD Implementation_Long;
} Implementation;
typedef struct _MANIFESTRESOURCE_TABLE
{
DWORD Offset;
DWORD Flags;
union
{
WORD Name_Short;
DWORD Name_Long;
} Name;
union
{
WORD Implementation_Short;
DWORD Implementation_Long;
} Implementation;
} MANIFESTRESOURCE_TABLE, *PMANIFESTRESOURCE_TABLE;
//
@@ -225,10 +240,12 @@ typedef struct _MANIFESTRESOURCE_TABLE {
//
// This is a short table, but necessary because the field size can change.
//
typedef struct _MODULEREF_TABLE {
union {
WORD Name_Short;
DWORD Name_Long;
typedef struct _MODULEREF_TABLE
{
union
{
WORD Name_Short;
DWORD Name_Long;
} Name;
} MODULEREF_TABLE, *PMODULEREF_TABLE;
@@ -236,112 +253,120 @@ typedef struct _MODULEREF_TABLE {
// FieldRVA Table
// ECMA-335 Section II.22.18
//
typedef struct _FIELDRVA_TABLE {
DWORD RVA;
union {
WORD Field_Short;
DWORD Field_LONG;
} Field;
typedef struct _FIELDRVA_TABLE
{
DWORD RVA;
union
{
WORD Field_Short;
DWORD Field_LONG;
} Field;
} FIELDRVA_TABLE, *PFIELDRVA_TABLE;
//
// CustomAttribute Table
// ECMA-335 Section II.22.10
//
typedef struct _CUSTOMATTRIBUTE_TABLE {
union {
typedef struct _CUSTOMATTRIBUTE_TABLE
{
union
{
WORD Parent_Short;
DWORD Parent_Long;
} Parent;
union {
union
{
WORD Type_Short;
DWORD Type_Long;
} Type;
union {
union
{
WORD Value_Short;
DWORD Value_Long;
} Value;
} CUSTOMATTRIBUTE_TABLE, *PCUSTOMATTRIBUTE_TABLE;
//
// Constant TAble
// ECMA-335 Section II.22.9
//
typedef struct _CONSTANT_TABLE {
typedef struct _CONSTANT_TABLE
{
WORD Type;
union {
union
{
WORD Parent_Short;
DWORD Parent_Long;
} Parent;
union {
union
{
WORD Value_Short;
DWORD Value_Long;
} Value;
} CONSTANT_TABLE, *PCONSTANT_TABLE;
// Used to return offsets to the various headers.
typedef struct _STREAMS {
PSTREAM_HEADER guid;
PSTREAM_HEADER tilde;
PSTREAM_HEADER string;
PSTREAM_HEADER blob;
PSTREAM_HEADER us;
typedef struct _STREAMS
{
PSTREAM_HEADER guid;
PSTREAM_HEADER tilde;
PSTREAM_HEADER string;
PSTREAM_HEADER blob;
PSTREAM_HEADER us;
} STREAMS, *PSTREAMS;
// Used to return the value of parsing a #US or #Blob entry.
// ECMA-335 Section II.24.2.4
typedef struct _BLOB_PARSE_RESULT {
uint8_t size; // Number of bytes parsed. This is the new offset.
DWORD length; // Value of the bytes parsed. This is the blob length.
typedef struct _BLOB_PARSE_RESULT
{
uint8_t size; // Number of bytes parsed. This is the new offset.
DWORD length; // Value of the bytes parsed. This is the blob length.
} BLOB_PARSE_RESULT, *PBLOB_PARSE_RESULT;
// Used to store the number of rows of each table.
typedef struct _ROWS {
uint32_t module;
uint32_t moduleref;
uint32_t assemblyref;
uint32_t typeref;
uint32_t methoddef;
uint32_t memberref;
uint32_t typedef_;
uint32_t typespec;
uint32_t field;
uint32_t param;
uint32_t property;
uint32_t interfaceimpl;
uint32_t event;
uint32_t standalonesig;
uint32_t assembly;
uint32_t file;
uint32_t exportedtype;
uint32_t manifestresource;
uint32_t genericparam;
uint32_t genericparamconstraint;
uint32_t methodspec;
uint32_t assemblyrefprocessor;
typedef struct _ROWS
{
uint32_t module;
uint32_t moduleref;
uint32_t assemblyref;
uint32_t typeref;
uint32_t methoddef;
uint32_t memberref;
uint32_t typedef_;
uint32_t typespec;
uint32_t field;
uint32_t param;
uint32_t property;
uint32_t interfaceimpl;
uint32_t event;
uint32_t standalonesig;
uint32_t assembly;
uint32_t file;
uint32_t exportedtype;
uint32_t manifestresource;
uint32_t genericparam;
uint32_t genericparamconstraint;
uint32_t methodspec;
uint32_t assemblyrefprocessor;
} ROWS, *PROWS;
// Used to store the index sizes for the various tables.
typedef struct _INDEX_SIZES {
uint8_t string;
uint8_t guid;
uint8_t blob;
uint8_t field;
uint8_t methoddef;
uint8_t memberref;
uint8_t param;
uint8_t event;
uint8_t typedef_;
uint8_t property;
uint8_t moduleref;
uint8_t assemblyrefprocessor;
uint8_t assemblyref;
uint8_t genericparam;
typedef struct _INDEX_SIZES
{
uint8_t string;
uint8_t guid;
uint8_t blob;
uint8_t field;
uint8_t methoddef;
uint8_t memberref;
uint8_t param;
uint8_t event;
uint8_t typedef_;
uint8_t property;
uint8_t moduleref;
uint8_t assemblyrefprocessor;
uint8_t assemblyref;
uint8_t genericparam;
} INDEX_SIZES, *PINDEX_SIZES;
#pragma pack(pop)
+182 -195
View File
@@ -32,7 +32,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <yara/integers.h>
// 32-bit ELF base types
typedef uint32_t elf32_addr_t;
@@ -48,123 +47,122 @@ typedef uint64_t elf64_off_t;
typedef uint32_t elf64_word_t;
typedef uint64_t elf64_xword_t;
#define ELF_MAGIC 0x464C457F
#define ELF_MAGIC 0x464C457F
#define ELF_ET_NONE 0x0000 // no type
#define ELF_ET_REL 0x0001 // relocatable
#define ELF_ET_EXEC 0x0002 // executable
#define ELF_ET_DYN 0x0003 // Shared-Object-File
#define ELF_ET_CORE 0x0004 // Corefile
#define ELF_ET_LOPROC 0xFF00 // Processor-specific
#define ELF_ET_HIPROC 0x00FF // Processor-specific
#define ELF_ET_NONE 0x0000 // no type
#define ELF_ET_REL 0x0001 // relocatable
#define ELF_ET_EXEC 0x0002 // executable
#define ELF_ET_DYN 0x0003 // Shared-Object-File
#define ELF_ET_CORE 0x0004 // Corefile
#define ELF_ET_LOPROC 0xFF00 // Processor-specific
#define ELF_ET_HIPROC 0x00FF // Processor-specific
#define ELF_EM_NONE 0x0000 // no type
#define ELF_EM_M32 0x0001 // AT&T WE 32100
#define ELF_EM_SPARC 0x0002 // SPARC
#define ELF_EM_386 0x0003 // Intel 80386
#define ELF_EM_68K 0x0004 // Motorola 68000
#define ELF_EM_88K 0x0005 // Motorola 88000
#define ELF_EM_860 0x0007 // Intel 80860
#define ELF_EM_MIPS 0x0008 // MIPS I Architecture
#define ELF_EM_MIPS_RS3_LE 0x000A // MIPS RS3000 Little-endian
#define ELF_EM_PPC 0x0014 // PowerPC
#define ELF_EM_PPC64 0x0015 // 64-bit PowerPC
#define ELF_EM_ARM 0x0028 // ARM
#define ELF_EM_X86_64 0x003E // AMD/Intel x86_64
#define ELF_EM_AARCH64 0x00B7 // 64-bit ARM
#define ELF_EM_NONE 0x0000 // no type
#define ELF_EM_M32 0x0001 // AT&T WE 32100
#define ELF_EM_SPARC 0x0002 // SPARC
#define ELF_EM_386 0x0003 // Intel 80386
#define ELF_EM_68K 0x0004 // Motorola 68000
#define ELF_EM_88K 0x0005 // Motorola 88000
#define ELF_EM_860 0x0007 // Intel 80860
#define ELF_EM_MIPS 0x0008 // MIPS I Architecture
#define ELF_EM_MIPS_RS3_LE 0x000A // MIPS RS3000 Little-endian
#define ELF_EM_PPC 0x0014 // PowerPC
#define ELF_EM_PPC64 0x0015 // 64-bit PowerPC
#define ELF_EM_ARM 0x0028 // ARM
#define ELF_EM_X86_64 0x003E // AMD/Intel x86_64
#define ELF_EM_AARCH64 0x00B7 // 64-bit ARM
#define ELF_CLASS_NONE 0x0000
#define ELF_CLASS_32 0x0001 // 32bit file
#define ELF_CLASS_64 0x0002 // 64bit file
#define ELF_CLASS_NONE 0x0000
#define ELF_CLASS_32 0x0001 // 32bit file
#define ELF_CLASS_64 0x0002 // 64bit file
#define ELF_DATA_NONE 0x0000
#define ELF_DATA_2LSB 0x0001
#define ELF_DATA_2MSB 0x002
#define ELF_DATA_NONE 0x0000
#define ELF_DATA_2LSB 0x0001
#define ELF_DATA_2MSB 0x002
#define ELF_SHT_NULL 0 // Section header table entry unused
#define ELF_SHT_PROGBITS 1 // Program data
#define ELF_SHT_SYMTAB 2 // Symbol table
#define ELF_SHT_STRTAB 3 // String table
#define ELF_SHT_RELA 4 // Relocation entries with addends
#define ELF_SHT_HASH 5 // Symbol hash table
#define ELF_SHT_DYNAMIC 6 // Dynamic linking information
#define ELF_SHT_NOTE 7 // Notes
#define ELF_SHT_NOBITS 8 // Program space with no data (bss)
#define ELF_SHT_REL 9 // Relocation entries, no addends
#define ELF_SHT_SHLIB 10 // Reserved
#define ELF_SHT_DYNSYM 11 // Dynamic linker symbol table
#define ELF_SHT_NUM 12 // Number of defined types
#define ELF_SHT_NULL 0 // Section header table entry unused
#define ELF_SHT_PROGBITS 1 // Program data
#define ELF_SHT_SYMTAB 2 // Symbol table
#define ELF_SHT_STRTAB 3 // String table
#define ELF_SHT_RELA 4 // Relocation entries with addends
#define ELF_SHT_HASH 5 // Symbol hash table
#define ELF_SHT_DYNAMIC 6 // Dynamic linking information
#define ELF_SHT_NOTE 7 // Notes
#define ELF_SHT_NOBITS 8 // Program space with no data (bss)
#define ELF_SHT_REL 9 // Relocation entries, no addends
#define ELF_SHT_SHLIB 10 // Reserved
#define ELF_SHT_DYNSYM 11 // Dynamic linker symbol table
#define ELF_SHT_NUM 12 // Number of defined types
#define ELF_SHF_WRITE 0x1 // Section is writable
#define ELF_SHF_ALLOC 0x2 // Section is present during execution
#define ELF_SHF_EXECINSTR 0x4 // Section contains executable instructions
#define ELF_SHF_WRITE 0x1 // Section is writable
#define ELF_SHF_ALLOC 0x2 // Section is present during execution
#define ELF_SHF_EXECINSTR 0x4 // Section contains executable instructions
#define ELF_SHN_LORESERVE 0xFF00
#define ELF_SHN_LORESERVE 0xFF00
#define ELF_PT_NULL 0 // The array element is unused
#define ELF_PT_LOAD 1 // Loadable segment
#define ELF_PT_DYNAMIC 2 // Segment contains dynamic linking info
#define ELF_PT_INTERP 3 // Contains interpreter pathname
#define ELF_PT_NOTE 4 // Location & size of auxiliary info
#define ELF_PT_SHLIB 5 // Reserved, unspecified semantics
#define ELF_PT_PHDR 6 // Location and size of program header table
#define ELF_PT_TLS 7 // Thread-Local Storage
#define ELF_PT_GNU_EH_FRAME 0x6474e550
#define ELF_PT_GNU_STACK 0x6474e551
#define ELF_PT_NULL 0 // The array element is unused
#define ELF_PT_LOAD 1 // Loadable segment
#define ELF_PT_DYNAMIC 2 // Segment contains dynamic linking info
#define ELF_PT_INTERP 3 // Contains interpreter pathname
#define ELF_PT_NOTE 4 // Location & size of auxiliary info
#define ELF_PT_SHLIB 5 // Reserved, unspecified semantics
#define ELF_PT_PHDR 6 // Location and size of program header table
#define ELF_PT_TLS 7 // Thread-Local Storage
#define ELF_PT_GNU_EH_FRAME 0x6474e550
#define ELF_PT_GNU_STACK 0x6474e551
#define ELF_DT_NULL 0 // End of the dynamic entries
#define ELF_DT_NEEDED 1 // Name of needed library
#define ELF_DT_PLTRELSZ 2 // Size in bytes of PLT relocs
#define ELF_DT_PLTGOT 3 // Processor defined value */
#define ELF_DT_HASH 4 // Address of symbol hash table
#define ELF_DT_STRTAB 5 // Address of string table
#define ELF_DT_SYMTAB 6 // Address of symbol table
#define ELF_DT_RELA 7 // Address of Rela relocs
#define ELF_DT_RELASZ 8 // Total size of Rela relocs
#define ELF_DT_RELAENT 9 // Size of one Rela reloc
#define ELF_DT_STRSZ 10 // Size of string table
#define ELF_DT_SYMENT 11 // Size of one symbol table entry
#define ELF_DT_INIT 12 // Address of init function
#define ELF_DT_FINI 13 // Address of termination function
#define ELF_DT_SONAME 14 // Name of shared object
#define ELF_DT_RPATH 15 // Library search path (deprecated)
#define ELF_DT_SYMBOLIC 16 // Start symbol search here
#define ELF_DT_REL 17 // Address of Rel relocs
#define ELF_DT_RELSZ 18 // Total size of Rel relocs
#define ELF_DT_RELENT 19 // Size of one Rel reloc
#define ELF_DT_PLTREL 20 // Type of reloc in PLT
#define ELF_DT_DEBUG 21 // For debugging; unspecified
#define ELF_DT_TEXTREL 22 // Reloc might modify .text
#define ELF_DT_JMPREL 23 // Address of PLT relocs
#define ELF_DT_BIND_NOW 24 // Process relocations of object
#define ELF_DT_INIT_ARRAY 25 // Array with addresses of init fct
#define ELF_DT_FINI_ARRAY 26 // Array with addresses of fini fct
#define ELF_DT_INIT_ARRAYSZ 27 // Size in bytes of DT_INIT_ARRAY
#define ELF_DT_FINI_ARRAYSZ 28 // Size in bytes of DT_FINI_ARRAY
#define ELF_DT_RUNPATH 29 // Library search path
#define ELF_DT_FLAGS 30 // Flags for the object being loaded
#define ELF_DT_ENCODING 32 // Start of encoded range
#define ELF_DT_NULL 0 // End of the dynamic entries
#define ELF_DT_NEEDED 1 // Name of needed library
#define ELF_DT_PLTRELSZ 2 // Size in bytes of PLT relocs
#define ELF_DT_PLTGOT 3 // Processor defined value */
#define ELF_DT_HASH 4 // Address of symbol hash table
#define ELF_DT_STRTAB 5 // Address of string table
#define ELF_DT_SYMTAB 6 // Address of symbol table
#define ELF_DT_RELA 7 // Address of Rela relocs
#define ELF_DT_RELASZ 8 // Total size of Rela relocs
#define ELF_DT_RELAENT 9 // Size of one Rela reloc
#define ELF_DT_STRSZ 10 // Size of string table
#define ELF_DT_SYMENT 11 // Size of one symbol table entry
#define ELF_DT_INIT 12 // Address of init function
#define ELF_DT_FINI 13 // Address of termination function
#define ELF_DT_SONAME 14 // Name of shared object
#define ELF_DT_RPATH 15 // Library search path (deprecated)
#define ELF_DT_SYMBOLIC 16 // Start symbol search here
#define ELF_DT_REL 17 // Address of Rel relocs
#define ELF_DT_RELSZ 18 // Total size of Rel relocs
#define ELF_DT_RELENT 19 // Size of one Rel reloc
#define ELF_DT_PLTREL 20 // Type of reloc in PLT
#define ELF_DT_DEBUG 21 // For debugging; unspecified
#define ELF_DT_TEXTREL 22 // Reloc might modify .text
#define ELF_DT_JMPREL 23 // Address of PLT relocs
#define ELF_DT_BIND_NOW 24 // Process relocations of object
#define ELF_DT_INIT_ARRAY 25 // Array with addresses of init fct
#define ELF_DT_FINI_ARRAY 26 // Array with addresses of fini fct
#define ELF_DT_INIT_ARRAYSZ 27 // Size in bytes of DT_INIT_ARRAY
#define ELF_DT_FINI_ARRAYSZ 28 // Size in bytes of DT_FINI_ARRAY
#define ELF_DT_RUNPATH 29 // Library search path
#define ELF_DT_FLAGS 30 // Flags for the object being loaded
#define ELF_DT_ENCODING 32 // Start of encoded range
#define ELF_STT_NOTYPE 0 // Symbol type is unspecified
#define ELF_STT_OBJECT 1 // Symbol is a data object
#define ELF_STT_FUNC 2 // Symbol is a code object
#define ELF_STT_SECTION 3 // Symbol associated with a section
#define ELF_STT_FILE 4 // Symbol's name is file name
#define ELF_STT_COMMON 5 // Symbol is a common data object
#define ELF_STT_TLS 6 // Symbol is thread-local data object
#define ELF_STT_NOTYPE 0 // Symbol type is unspecified
#define ELF_STT_OBJECT 1 // Symbol is a data object
#define ELF_STT_FUNC 2 // Symbol is a code object
#define ELF_STT_SECTION 3 // Symbol associated with a section
#define ELF_STT_FILE 4 // Symbol's name is file name
#define ELF_STT_COMMON 5 // Symbol is a common data object
#define ELF_STT_TLS 6 // Symbol is thread-local data object
#define ELF_STB_LOCAL 0 // Local symbol
#define ELF_STB_GLOBAL 1 // Global symbol
#define ELF_STB_WEAK 2 // Weak symbol
#define ELF_STB_LOCAL 0 // Local symbol
#define ELF_STB_GLOBAL 1 // Global symbol
#define ELF_STB_WEAK 2 // Weak symbol
#define ELF_PF_X 0x1 // Segment is executable
#define ELF_PF_W 0x2 // Segment is writable
#define ELF_PF_R 0x4 // Segment is readable
#define ELF_PF_X 0x1 // Segment is executable
#define ELF_PF_W 0x2 // Segment is writable
#define ELF_PF_R 0x4 // Segment is readable
#define ELF_PN_XNUM 0xffff
#define ELF_PN_XNUM 0xffff
#pragma pack(push,1)
#pragma pack(push, 1)
typedef struct
{
@@ -177,147 +175,136 @@ typedef struct
} elf_ident_t;
typedef struct
{
elf_ident_t ident;
elf32_half_t type;
elf32_half_t machine;
elf32_word_t version;
elf32_addr_t entry;
elf32_off_t ph_offset;
elf32_off_t sh_offset;
elf32_word_t flags;
elf32_half_t header_size;
elf32_half_t ph_entry_size;
elf32_half_t ph_entry_count;
elf32_half_t sh_entry_size;
elf32_half_t sh_entry_count;
elf32_half_t sh_str_table_index;
elf_ident_t ident;
elf32_half_t type;
elf32_half_t machine;
elf32_word_t version;
elf32_addr_t entry;
elf32_off_t ph_offset;
elf32_off_t sh_offset;
elf32_word_t flags;
elf32_half_t header_size;
elf32_half_t ph_entry_size;
elf32_half_t ph_entry_count;
elf32_half_t sh_entry_size;
elf32_half_t sh_entry_count;
elf32_half_t sh_str_table_index;
} elf32_header_t;
typedef struct
{
elf_ident_t ident;
elf64_half_t type;
elf64_half_t machine;
elf64_word_t version;
elf64_addr_t entry;
elf64_off_t ph_offset;
elf64_off_t sh_offset;
elf64_word_t flags;
elf64_half_t header_size;
elf64_half_t ph_entry_size;
elf64_half_t ph_entry_count;
elf64_half_t sh_entry_size;
elf64_half_t sh_entry_count;
elf64_half_t sh_str_table_index;
elf_ident_t ident;
elf64_half_t type;
elf64_half_t machine;
elf64_word_t version;
elf64_addr_t entry;
elf64_off_t ph_offset;
elf64_off_t sh_offset;
elf64_word_t flags;
elf64_half_t header_size;
elf64_half_t ph_entry_size;
elf64_half_t ph_entry_count;
elf64_half_t sh_entry_size;
elf64_half_t sh_entry_count;
elf64_half_t sh_str_table_index;
} elf64_header_t;
typedef struct
{
elf32_word_t type;
elf32_off_t offset;
elf32_addr_t virt_addr;
elf32_addr_t phys_addr;
elf32_word_t file_size;
elf32_word_t mem_size;
elf32_word_t flags;
elf32_word_t alignment;
elf32_word_t type;
elf32_off_t offset;
elf32_addr_t virt_addr;
elf32_addr_t phys_addr;
elf32_word_t file_size;
elf32_word_t mem_size;
elf32_word_t flags;
elf32_word_t alignment;
} elf32_program_header_t;
typedef struct
{
elf64_word_t type;
elf64_word_t flags;
elf64_off_t offset;
elf64_addr_t virt_addr;
elf64_addr_t phys_addr;
elf64_xword_t file_size;
elf64_xword_t mem_size;
elf64_xword_t alignment;
elf64_word_t type;
elf64_word_t flags;
elf64_off_t offset;
elf64_addr_t virt_addr;
elf64_addr_t phys_addr;
elf64_xword_t file_size;
elf64_xword_t mem_size;
elf64_xword_t alignment;
} elf64_program_header_t;
typedef struct
{
elf32_word_t name;
elf32_word_t type;
elf32_word_t flags;
elf32_addr_t addr;
elf32_off_t offset;
elf32_word_t size;
elf32_word_t link;
elf32_word_t info;
elf32_word_t align;
elf32_word_t entry_size;
elf32_word_t name;
elf32_word_t type;
elf32_word_t flags;
elf32_addr_t addr;
elf32_off_t offset;
elf32_word_t size;
elf32_word_t link;
elf32_word_t info;
elf32_word_t align;
elf32_word_t entry_size;
} elf32_section_header_t;
typedef struct
{
elf64_word_t name;
elf64_word_t type;
elf64_xword_t flags;
elf64_addr_t addr;
elf64_off_t offset;
elf64_xword_t size;
elf64_word_t link;
elf64_word_t info;
elf64_xword_t align;
elf64_xword_t entry_size;
elf64_word_t name;
elf64_word_t type;
elf64_xword_t flags;
elf64_addr_t addr;
elf64_off_t offset;
elf64_xword_t size;
elf64_word_t link;
elf64_word_t info;
elf64_xword_t align;
elf64_xword_t entry_size;
} elf64_section_header_t;
typedef struct
{
elf32_word_t tag;
elf32_word_t val;
elf32_word_t tag;
elf32_word_t val;
} elf32_dyn_t;
typedef struct
{
elf64_xword_t tag;
elf64_xword_t val;
elf64_xword_t tag;
elf64_xword_t val;
} elf64_dyn_t;
typedef struct
{
elf32_word_t name;
elf32_addr_t value;
elf32_word_t size;
unsigned char info;
unsigned char other;
elf32_half_t shndx;
elf32_word_t name;
elf32_addr_t value;
elf32_word_t size;
unsigned char info;
unsigned char other;
elf32_half_t shndx;
} elf32_sym_t;
typedef struct
{
elf32_word_t name;
unsigned char info;
unsigned char other;
elf32_half_t shndx;
elf64_addr_t value;
elf64_xword_t size;
elf32_word_t name;
unsigned char info;
unsigned char other;
elf32_half_t shndx;
elf64_addr_t value;
elf64_xword_t size;
} elf64_sym_t;
#pragma pack(pop)
#endif
+13 -17
View File
@@ -32,31 +32,29 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <yara/integers.h>
#if defined(__has_builtin)
# if __has_builtin(__builtin_bswap16)
# define yr_bswap16(x) __builtin_bswap16(x)
# endif
#if __has_builtin(__builtin_bswap16)
#define yr_bswap16(x) __builtin_bswap16(x)
#endif
#endif
#if !defined(yr_bswap16) && defined(_MSC_VER)
# define yr_bswap16(x) _byteswap_ushort(x)
#define yr_bswap16(x) _byteswap_ushort(x)
#endif
#if !defined(yr_bswap16)
uint16_t _yr_bswap16(uint16_t x);
# define yr_bswap16(x) _yr_bswap16(x)
#define yr_bswap16(x) _yr_bswap16(x)
#endif
#if defined(__has_builtin)
# if __has_builtin(__builtin_bswap32)
# define yr_bswap32(x) __builtin_bswap32(x)
# endif
#if __has_builtin(__builtin_bswap32)
#define yr_bswap32(x) __builtin_bswap32(x)
#endif
#endif
#if !defined(yr_bswap32) && defined(_MSC_VER)
# define yr_bswap32(x) _byteswap_ulong(x)
#define yr_bswap32(x) _byteswap_ulong(x)
#endif
#if !defined(yr_bswap32)
@@ -64,15 +62,14 @@ uint32_t _yr_bswap32(uint32_t x);
#define yr_bswap32(x) _yr_bswap32(x)
#endif
#if defined(__has_builtin)
# if __has_builtin(__builtin_bswap64)
# define yr_bswap64(x) __builtin_bswap64(x)
# endif
#if __has_builtin(__builtin_bswap64)
#define yr_bswap64(x) __builtin_bswap64(x)
#endif
#endif
#if !defined(yr_bswap64) && defined(_MSC_VER)
# define yr_bswap64(x) _byteswap_uint64(x)
#define yr_bswap64(x) _byteswap_uint64(x)
#endif
#if !defined(yr_bswap64)
@@ -80,7 +77,6 @@ uint64_t _yr_bswap64(uint64_t x);
#define yr_bswap64(x) _yr_bswap64(x)
#endif
#if defined(WORDS_BIGENDIAN)
#define yr_le16toh(x) yr_bswap16(x)
#define yr_le32toh(x) yr_bswap32(x)
+91 -87
View File
@@ -37,104 +37,108 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endif
#ifndef ERROR_SUCCESS
#define ERROR_SUCCESS 0
#define ERROR_SUCCESS 0
#endif
// ERROR_INSUFICIENT_MEMORY is misspelled but it's kept for backward
// compatibility, as some other programs can be using it in this form.
#define ERROR_INSUFICIENT_MEMORY 1
#define ERROR_INSUFICIENT_MEMORY 1
#define ERROR_INSUFFICIENT_MEMORY 1
#define ERROR_COULD_NOT_ATTACH_TO_PROCESS 2
#define ERROR_COULD_NOT_OPEN_FILE 3
#define ERROR_COULD_NOT_MAP_FILE 4
#define ERROR_INVALID_FILE 6
#define ERROR_CORRUPT_FILE 7
#define ERROR_UNSUPPORTED_FILE_VERSION 8
#define ERROR_INVALID_REGULAR_EXPRESSION 9
#define ERROR_INVALID_HEX_STRING 10
#define ERROR_SYNTAX_ERROR 11
#define ERROR_LOOP_NESTING_LIMIT_EXCEEDED 12
#define ERROR_DUPLICATED_LOOP_IDENTIFIER 13
#define ERROR_DUPLICATED_IDENTIFIER 14
#define ERROR_DUPLICATED_TAG_IDENTIFIER 15
#define ERROR_DUPLICATED_META_IDENTIFIER 16
#define ERROR_DUPLICATED_STRING_IDENTIFIER 17
#define ERROR_UNREFERENCED_STRING 18
#define ERROR_UNDEFINED_STRING 19
#define ERROR_UNDEFINED_IDENTIFIER 20
#define ERROR_MISPLACED_ANONYMOUS_STRING 21
#define ERROR_INCLUDES_CIRCULAR_REFERENCE 22
#define ERROR_INCLUDE_DEPTH_EXCEEDED 23
#define ERROR_WRONG_TYPE 24
#define ERROR_EXEC_STACK_OVERFLOW 25
#define ERROR_SCAN_TIMEOUT 26
#define ERROR_TOO_MANY_SCAN_THREADS 27
#define ERROR_CALLBACK_ERROR 28
#define ERROR_INVALID_ARGUMENT 29
#define ERROR_TOO_MANY_MATCHES 30
#define ERROR_INTERNAL_FATAL_ERROR 31
#define ERROR_NESTED_FOR_OF_LOOP 32
#define ERROR_INVALID_FIELD_NAME 33
#define ERROR_UNKNOWN_MODULE 34
#define ERROR_NOT_A_STRUCTURE 35
#define ERROR_NOT_INDEXABLE 36
#define ERROR_NOT_A_FUNCTION 37
#define ERROR_INVALID_FORMAT 38
#define ERROR_TOO_MANY_ARGUMENTS 39
#define ERROR_WRONG_ARGUMENTS 40
#define ERROR_WRONG_RETURN_TYPE 41
#define ERROR_DUPLICATED_STRUCTURE_MEMBER 42
#define ERROR_EMPTY_STRING 43
#define ERROR_DIVISION_BY_ZERO 44
#define ERROR_REGULAR_EXPRESSION_TOO_LARGE 45
#define ERROR_TOO_MANY_RE_FIBERS 46
#define ERROR_COULD_NOT_READ_PROCESS_MEMORY 47
#define ERROR_INVALID_EXTERNAL_VARIABLE_TYPE 48
#define ERROR_REGULAR_EXPRESSION_TOO_COMPLEX 49
#define ERROR_INVALID_MODULE_NAME 50
#define ERROR_TOO_MANY_STRINGS 51
#define ERROR_INTEGER_OVERFLOW 52
#define ERROR_CALLBACK_REQUIRED 53
#define ERROR_INVALID_OPERAND 54
#define ERROR_COULD_NOT_READ_FILE 55
#define ERROR_DUPLICATED_EXTERNAL_VARIABLE 56
#define ERROR_INVALID_MODULE_DATA 57
#define ERROR_WRITING_FILE 58
#define ERROR_INVALID_MODIFIER 59
#define ERROR_DUPLICATED_MODIFIER 60
#define ERROR_INSUFFICIENT_MEMORY 1
#define ERROR_COULD_NOT_ATTACH_TO_PROCESS 2
#define ERROR_COULD_NOT_OPEN_FILE 3
#define ERROR_COULD_NOT_MAP_FILE 4
#define ERROR_INVALID_FILE 6
#define ERROR_CORRUPT_FILE 7
#define ERROR_UNSUPPORTED_FILE_VERSION 8
#define ERROR_INVALID_REGULAR_EXPRESSION 9
#define ERROR_INVALID_HEX_STRING 10
#define ERROR_SYNTAX_ERROR 11
#define ERROR_LOOP_NESTING_LIMIT_EXCEEDED 12
#define ERROR_DUPLICATED_LOOP_IDENTIFIER 13
#define ERROR_DUPLICATED_IDENTIFIER 14
#define ERROR_DUPLICATED_TAG_IDENTIFIER 15
#define ERROR_DUPLICATED_META_IDENTIFIER 16
#define ERROR_DUPLICATED_STRING_IDENTIFIER 17
#define ERROR_UNREFERENCED_STRING 18
#define ERROR_UNDEFINED_STRING 19
#define ERROR_UNDEFINED_IDENTIFIER 20
#define ERROR_MISPLACED_ANONYMOUS_STRING 21
#define ERROR_INCLUDES_CIRCULAR_REFERENCE 22
#define ERROR_INCLUDE_DEPTH_EXCEEDED 23
#define ERROR_WRONG_TYPE 24
#define ERROR_EXEC_STACK_OVERFLOW 25
#define ERROR_SCAN_TIMEOUT 26
#define ERROR_TOO_MANY_SCAN_THREADS 27
#define ERROR_CALLBACK_ERROR 28
#define ERROR_INVALID_ARGUMENT 29
#define ERROR_TOO_MANY_MATCHES 30
#define ERROR_INTERNAL_FATAL_ERROR 31
#define ERROR_NESTED_FOR_OF_LOOP 32
#define ERROR_INVALID_FIELD_NAME 33
#define ERROR_UNKNOWN_MODULE 34
#define ERROR_NOT_A_STRUCTURE 35
#define ERROR_NOT_INDEXABLE 36
#define ERROR_NOT_A_FUNCTION 37
#define ERROR_INVALID_FORMAT 38
#define ERROR_TOO_MANY_ARGUMENTS 39
#define ERROR_WRONG_ARGUMENTS 40
#define ERROR_WRONG_RETURN_TYPE 41
#define ERROR_DUPLICATED_STRUCTURE_MEMBER 42
#define ERROR_EMPTY_STRING 43
#define ERROR_DIVISION_BY_ZERO 44
#define ERROR_REGULAR_EXPRESSION_TOO_LARGE 45
#define ERROR_TOO_MANY_RE_FIBERS 46
#define ERROR_COULD_NOT_READ_PROCESS_MEMORY 47
#define ERROR_INVALID_EXTERNAL_VARIABLE_TYPE 48
#define ERROR_REGULAR_EXPRESSION_TOO_COMPLEX 49
#define ERROR_INVALID_MODULE_NAME 50
#define ERROR_TOO_MANY_STRINGS 51
#define ERROR_INTEGER_OVERFLOW 52
#define ERROR_CALLBACK_REQUIRED 53
#define ERROR_INVALID_OPERAND 54
#define ERROR_COULD_NOT_READ_FILE 55
#define ERROR_DUPLICATED_EXTERNAL_VARIABLE 56
#define ERROR_INVALID_MODULE_DATA 57
#define ERROR_WRITING_FILE 58
#define ERROR_INVALID_MODIFIER 59
#define ERROR_DUPLICATED_MODIFIER 60
#define FAIL_ON_ERROR(x) \
{ \
int result = (x); \
if (result != ERROR_SUCCESS) \
return result; \
}
#define FAIL_ON_ERROR(x) { \
int result = (x); \
if (result != ERROR_SUCCESS) \
return result; \
}
#define FAIL_ON_ERROR_WITH_CLEANUP(x, cleanup) { \
int result = (x); \
if (result != ERROR_SUCCESS) { \
cleanup; \
return result; \
} \
}
#define FAIL_ON_NULL_WITH_CLEANUP(x, cleanup) { \
if ((x) == NULL) { \
cleanup; \
return ERROR_INSUFFICIENT_MEMORY; \
} \
}
#define FAIL_ON_ERROR_WITH_CLEANUP(x, cleanup) \
{ \
int result = (x); \
if (result != ERROR_SUCCESS) \
{ \
cleanup; \
return result; \
} \
}
#define FAIL_ON_NULL_WITH_CLEANUP(x, cleanup) \
{ \
if ((x) == NULL) \
{ \
cleanup; \
return ERROR_INSUFFICIENT_MEMORY; \
} \
}
#ifdef NDEBUG
#define assertf(expr, msg, ...) ((void)0)
#define assertf(expr, msg, ...) ((void) 0)
#else
#define assertf(expr, msg, ...) \
if(!(expr)) { \
fprintf(stderr, "%s:%d: " msg "\n", __FILE__, __LINE__, ##__VA_ARGS__); \
abort(); \
}
#define assertf(expr, msg, ...) \
if (!(expr)) \
{ \
fprintf(stderr, "%s:%d: " msg "\n", __FILE__, __LINE__, ##__VA_ARGS__); \
abort(); \
}
#endif
#endif
+139 -145
View File
@@ -31,166 +31,160 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define YR_EXEC_H
#include <yara/hash.h>
#include <yara/rules.h>
#include <yara/scan.h>
#include <yara/types.h>
#include <yara/rules.h>
#define YR_UNDEFINED 0xFFFABADAFABADAFFLL
#define IS_UNDEFINED(x) ((size_t)(x) == (size_t) YR_UNDEFINED)
#define YR_UNDEFINED 0xFFFABADAFABADAFFLL
#define IS_UNDEFINED(x) ((size_t)(x) == (size_t) YR_UNDEFINED)
#define OP_ERROR 0
#define OP_HALT 255
#define OP_NOP 254
#define OP_ERROR 0
#define OP_HALT 255
#define OP_NOP 254
#define OP_AND 1
#define OP_OR 2
#define OP_NOT 3
#define OP_BITWISE_NOT 4
#define OP_BITWISE_AND 5
#define OP_BITWISE_OR 6
#define OP_BITWISE_XOR 7
#define OP_SHL 8
#define OP_SHR 9
#define OP_MOD 10
#define OP_INT_TO_DBL 11
#define OP_STR_TO_BOOL 12
#define OP_PUSH 13
#define OP_POP 14
#define OP_CALL 15
#define OP_OBJ_LOAD 16
#define OP_OBJ_VALUE 17
#define OP_OBJ_FIELD 18
#define OP_INDEX_ARRAY 19
#define OP_COUNT 20
#define OP_LENGTH 21
#define OP_FOUND 22
#define OP_FOUND_AT 23
#define OP_FOUND_IN 24
#define OP_OFFSET 25
#define OP_OF 26
#define OP_PUSH_RULE 27
#define OP_INIT_RULE 28
#define OP_MATCH_RULE 29
#define OP_INCR_M 30
#define OP_CLEAR_M 31
#define OP_ADD_M 32
#define OP_POP_M 33
#define OP_PUSH_M 34
#define OP_SET_M 35
#define OP_SWAPUNDEF 36
#define OP_FILESIZE 37
#define OP_ENTRYPOINT 38
#define OP_UNUSED 39
#define OP_MATCHES 40
#define OP_IMPORT 41
#define OP_LOOKUP_DICT 42
#define OP_JUNDEF 43 /* Not used */
#define OP_JUNDEF_P 44
#define OP_JNUNDEF 45
#define OP_JNUNDEF_P 46 /* Not used */
#define OP_JFALSE 47
#define OP_JFALSE_P 48
#define OP_JTRUE 49
#define OP_JTRUE_P 50
#define OP_JL_P 51
#define OP_JLE_P 52
#define OP_ITER_NEXT 53
#define OP_ITER_START_ARRAY 54
#define OP_ITER_START_DICT 55
#define OP_ITER_START_INT_RANGE 56
#define OP_ITER_START_INT_ENUM 57
#define OP_JZ 58
#define OP_JZ_P 59
#define OP_PUSH_8 60
#define OP_PUSH_16 61
#define OP_PUSH_32 62
#define OP_PUSH_U 63
#define OP_CONTAINS 64
#define OP_STARTSWITH 65
#define OP_ENDSWITH 66
#define OP_ICONTAINS 67
#define OP_ISTARTSWITH 68
#define OP_IENDSWITH 69
#define OP_AND 1
#define OP_OR 2
#define OP_NOT 3
#define OP_BITWISE_NOT 4
#define OP_BITWISE_AND 5
#define OP_BITWISE_OR 6
#define OP_BITWISE_XOR 7
#define OP_SHL 8
#define OP_SHR 9
#define OP_MOD 10
#define OP_INT_TO_DBL 11
#define OP_STR_TO_BOOL 12
#define OP_PUSH 13
#define OP_POP 14
#define OP_CALL 15
#define OP_OBJ_LOAD 16
#define OP_OBJ_VALUE 17
#define OP_OBJ_FIELD 18
#define OP_INDEX_ARRAY 19
#define OP_COUNT 20
#define OP_LENGTH 21
#define OP_FOUND 22
#define OP_FOUND_AT 23
#define OP_FOUND_IN 24
#define OP_OFFSET 25
#define OP_OF 26
#define OP_PUSH_RULE 27
#define OP_INIT_RULE 28
#define OP_MATCH_RULE 29
#define OP_INCR_M 30
#define OP_CLEAR_M 31
#define OP_ADD_M 32
#define OP_POP_M 33
#define OP_PUSH_M 34
#define OP_SET_M 35
#define OP_SWAPUNDEF 36
#define OP_FILESIZE 37
#define OP_ENTRYPOINT 38
// Unused opcode 39
#define OP_MATCHES 40
#define OP_IMPORT 41
#define OP_LOOKUP_DICT 42
#define OP_JUNDEF 43 /* Not used */
#define OP_JUNDEF_P 44
#define OP_JNUNDEF 45
#define OP_JNUNDEF_P 46 /* Not used */
#define OP_JFALSE 47
#define OP_JFALSE_P 48
#define OP_JTRUE 49
#define OP_JTRUE_P 50
#define OP_JL_P 51
#define OP_JLE_P 52
#define OP_ITER_NEXT 53
#define OP_ITER_START_ARRAY 54
#define OP_ITER_START_DICT 55
#define OP_ITER_START_INT_RANGE 56
#define OP_ITER_START_INT_ENUM 57
#define OP_JZ 58
#define OP_JZ_P 59
#define OP_PUSH_8 60
#define OP_PUSH_16 61
#define OP_PUSH_32 62
#define OP_PUSH_U 63
#define OP_CONTAINS 64
#define OP_STARTSWITH 65
#define OP_ENDSWITH 66
#define OP_ICONTAINS 67
#define OP_ISTARTSWITH 68
#define OP_IENDSWITH 69
#define _OP_EQ 0
#define _OP_NEQ 1
#define _OP_LT 2
#define _OP_GT 3
#define _OP_LE 4
#define _OP_GE 5
#define _OP_ADD 6
#define _OP_SUB 7
#define _OP_MUL 8
#define _OP_DIV 9
#define _OP_MINUS 10
#define _OP_EQ 0
#define _OP_NEQ 1
#define _OP_LT 2
#define _OP_GT 3
#define _OP_LE 4
#define _OP_GE 5
#define _OP_ADD 6
#define _OP_SUB 7
#define _OP_MUL 8
#define _OP_DIV 9
#define _OP_MINUS 10
#define OP_INT_BEGIN 100
#define OP_INT_EQ (OP_INT_BEGIN + _OP_EQ)
#define OP_INT_NEQ (OP_INT_BEGIN + _OP_NEQ)
#define OP_INT_LT (OP_INT_BEGIN + _OP_LT)
#define OP_INT_GT (OP_INT_BEGIN + _OP_GT)
#define OP_INT_LE (OP_INT_BEGIN + _OP_LE)
#define OP_INT_GE (OP_INT_BEGIN + _OP_GE)
#define OP_INT_ADD (OP_INT_BEGIN + _OP_ADD)
#define OP_INT_SUB (OP_INT_BEGIN + _OP_SUB)
#define OP_INT_MUL (OP_INT_BEGIN + _OP_MUL)
#define OP_INT_DIV (OP_INT_BEGIN + _OP_DIV)
#define OP_INT_MINUS (OP_INT_BEGIN + _OP_MINUS)
#define OP_INT_END OP_INT_MINUS
#define OP_DBL_BEGIN 120
#define OP_DBL_EQ (OP_DBL_BEGIN + _OP_EQ)
#define OP_DBL_NEQ (OP_DBL_BEGIN + _OP_NEQ)
#define OP_DBL_LT (OP_DBL_BEGIN + _OP_LT)
#define OP_DBL_GT (OP_DBL_BEGIN + _OP_GT)
#define OP_DBL_LE (OP_DBL_BEGIN + _OP_LE)
#define OP_DBL_GE (OP_DBL_BEGIN + _OP_GE)
#define OP_DBL_ADD (OP_DBL_BEGIN + _OP_ADD)
#define OP_DBL_SUB (OP_DBL_BEGIN + _OP_SUB)
#define OP_DBL_MUL (OP_DBL_BEGIN + _OP_MUL)
#define OP_DBL_DIV (OP_DBL_BEGIN + _OP_DIV)
#define OP_DBL_MINUS (OP_DBL_BEGIN + _OP_MINUS)
#define OP_DBL_END OP_DBL_MINUS
#define OP_INT_BEGIN 100
#define OP_INT_EQ (OP_INT_BEGIN + _OP_EQ)
#define OP_INT_NEQ (OP_INT_BEGIN + _OP_NEQ)
#define OP_INT_LT (OP_INT_BEGIN + _OP_LT)
#define OP_INT_GT (OP_INT_BEGIN + _OP_GT)
#define OP_INT_LE (OP_INT_BEGIN + _OP_LE)
#define OP_INT_GE (OP_INT_BEGIN + _OP_GE)
#define OP_INT_ADD (OP_INT_BEGIN + _OP_ADD)
#define OP_INT_SUB (OP_INT_BEGIN + _OP_SUB)
#define OP_INT_MUL (OP_INT_BEGIN + _OP_MUL)
#define OP_INT_DIV (OP_INT_BEGIN + _OP_DIV)
#define OP_INT_MINUS (OP_INT_BEGIN + _OP_MINUS)
#define OP_INT_END OP_INT_MINUS
#define OP_STR_BEGIN 140
#define OP_STR_EQ (OP_STR_BEGIN + _OP_EQ)
#define OP_STR_NEQ (OP_STR_BEGIN + _OP_NEQ)
#define OP_STR_LT (OP_STR_BEGIN + _OP_LT)
#define OP_STR_GT (OP_STR_BEGIN + _OP_GT)
#define OP_STR_LE (OP_STR_BEGIN + _OP_LE)
#define OP_STR_GE (OP_STR_BEGIN + _OP_GE)
#define OP_STR_END OP_STR_GE
#define OP_DBL_BEGIN 120
#define OP_DBL_EQ (OP_DBL_BEGIN + _OP_EQ)
#define OP_DBL_NEQ (OP_DBL_BEGIN + _OP_NEQ)
#define OP_DBL_LT (OP_DBL_BEGIN + _OP_LT)
#define OP_DBL_GT (OP_DBL_BEGIN + _OP_GT)
#define OP_DBL_LE (OP_DBL_BEGIN + _OP_LE)
#define OP_DBL_GE (OP_DBL_BEGIN + _OP_GE)
#define OP_DBL_ADD (OP_DBL_BEGIN + _OP_ADD)
#define OP_DBL_SUB (OP_DBL_BEGIN + _OP_SUB)
#define OP_DBL_MUL (OP_DBL_BEGIN + _OP_MUL)
#define OP_DBL_DIV (OP_DBL_BEGIN + _OP_DIV)
#define OP_DBL_MINUS (OP_DBL_BEGIN + _OP_MINUS)
#define OP_DBL_END OP_DBL_MINUS
#define OP_STR_BEGIN 140
#define OP_STR_EQ (OP_STR_BEGIN + _OP_EQ)
#define OP_STR_NEQ (OP_STR_BEGIN + _OP_NEQ)
#define OP_STR_LT (OP_STR_BEGIN + _OP_LT)
#define OP_STR_GT (OP_STR_BEGIN + _OP_GT)
#define OP_STR_LE (OP_STR_BEGIN + _OP_LE)
#define OP_STR_GE (OP_STR_BEGIN + _OP_GE)
#define OP_STR_END OP_STR_GE
#define IS_INT_OP(x) ((x) >= OP_INT_BEGIN && (x) <= OP_INT_END)
#define IS_DBL_OP(x) ((x) >= OP_DBL_BEGIN && (x) <= OP_DBL_END)
#define IS_STR_OP(x) ((x) >= OP_STR_BEGIN && (x) <= OP_STR_END)
#define OP_READ_INT 240
#define OP_INT8 (OP_READ_INT + 0)
#define OP_INT16 (OP_READ_INT + 1)
#define OP_INT32 (OP_READ_INT + 2)
#define OP_UINT8 (OP_READ_INT + 3)
#define OP_UINT16 (OP_READ_INT + 4)
#define OP_UINT32 (OP_READ_INT + 5)
#define OP_INT8BE (OP_READ_INT + 6)
#define OP_INT16BE (OP_READ_INT + 7)
#define OP_INT32BE (OP_READ_INT + 8)
#define OP_UINT8BE (OP_READ_INT + 9)
#define OP_UINT16BE (OP_READ_INT + 10)
#define OP_UINT32BE (OP_READ_INT + 11)
#define IS_INT_OP(x) ((x) >= OP_INT_BEGIN && (x) <= OP_INT_END)
#define IS_DBL_OP(x) ((x) >= OP_DBL_BEGIN && (x) <= OP_DBL_END)
#define IS_STR_OP(x) ((x) >= OP_STR_BEGIN && (x) <= OP_STR_END)
#define OP_READ_INT 240
#define OP_INT8 (OP_READ_INT + 0)
#define OP_INT16 (OP_READ_INT + 1)
#define OP_INT32 (OP_READ_INT + 2)
#define OP_UINT8 (OP_READ_INT + 3)
#define OP_UINT16 (OP_READ_INT + 4)
#define OP_UINT32 (OP_READ_INT + 5)
#define OP_INT8BE (OP_READ_INT + 6)
#define OP_INT16BE (OP_READ_INT + 7)
#define OP_INT32BE (OP_READ_INT + 8)
#define OP_UINT8BE (OP_READ_INT + 9)
#define OP_UINT16BE (OP_READ_INT + 10)
#define OP_UINT32BE (OP_READ_INT + 11)
#define OPERATION(operator, op1, op2) \
(IS_UNDEFINED(op1) || IS_UNDEFINED(op2)) ? (YR_UNDEFINED) : (op1 operator op2)
(IS_UNDEFINED(op1) || IS_UNDEFINED(op2)) ? (YR_UNDEFINED) : (op1 operator op2)
#define COMPARISON(operator, op1, op2) \
(IS_UNDEFINED(op1) || IS_UNDEFINED(op2)) ? (0) : (op1 operator op2)
(IS_UNDEFINED(op1) || IS_UNDEFINED(op2)) ? (0) : (op1 operator op2)
int yr_execute_code(
YR_SCAN_CONTEXT* context);
int yr_execute_code(YR_SCAN_CONTEXT* context);
#endif
+1 -4
View File
@@ -30,10 +30,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YR_EXEFILES_H
#define YR_EXEFILES_H
uint64_t yr_get_entry_point_offset(
const uint8_t* buffer,
size_t buffer_length);
uint64_t yr_get_entry_point_offset(const uint8_t* buffer, size_t buffer_length);
uint64_t yr_get_entry_point_address(
const uint8_t* buffer,
+11 -16
View File
@@ -34,32 +34,29 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#if defined(_WIN32) || defined(__CYGWIN__)
#include <windows.h>
#define YR_FILE_DESCRIPTOR HANDLE
#define YR_FILE_DESCRIPTOR HANDLE
#else
#define YR_FILE_DESCRIPTOR int
#define YR_FILE_DESCRIPTOR int
#endif
#include <stdlib.h>
#include <yara/integers.h>
#include <yara/utils.h>
typedef struct _YR_MAPPED_FILE
{
YR_FILE_DESCRIPTOR file;
size_t size;
const uint8_t* data;
#if defined(_WIN32) || defined(__CYGWIN__)
HANDLE mapping;
#endif
YR_FILE_DESCRIPTOR file;
size_t size;
const uint8_t* data;
#if defined(_WIN32) || defined(__CYGWIN__)
HANDLE mapping;
#endif
} YR_MAPPED_FILE;
YR_API int yr_filemap_map(
const char* file_path,
YR_MAPPED_FILE* pmapped_file);
YR_API int yr_filemap_map(const char* file_path, YR_MAPPED_FILE* pmapped_file);
YR_API int yr_filemap_map_fd(
@@ -76,11 +73,9 @@ YR_API int yr_filemap_map_ex(
YR_MAPPED_FILE* pmapped_file);
YR_API void yr_filemap_unmap(
YR_MAPPED_FILE* pmapped_file);
YR_API void yr_filemap_unmap(YR_MAPPED_FILE* pmapped_file);
YR_API void yr_filemap_unmap_fd(
YR_MAPPED_FILE* pmapped_file);
YR_API void yr_filemap_unmap_fd(YR_MAPPED_FILE* pmapped_file);
#endif
+3 -3
View File
@@ -46,9 +46,9 @@ extern uint8_t yr_altercase[256];
#else
#define YR_DEBUG_FPRINTF(VERBOSITY, FORMAT, ...) \
if (yr_debug_verbosity >= VERBOSITY) \
{ \
fprintf(FORMAT, __VA_ARGS__); \
if (yr_debug_verbosity >= VERBOSITY) \
{ \
fprintf(FORMAT, __VA_ARGS__); \
}
// Default is 0 for production, which means be silent, else verbose.
+3 -9
View File
@@ -31,9 +31,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define YR_HASH_H
#include <stddef.h>
#include <yara/utils.h>
#include <yara/integers.h>
#include <yara/utils.h>
typedef struct _YR_HASH_TABLE_ENTRY
{
@@ -59,15 +58,10 @@ typedef struct _YR_HASH_TABLE
typedef int (*YR_HASH_TABLE_FREE_VALUE_FUNC)(void* value);
uint32_t yr_hash(
uint32_t seed,
const void* buffer,
size_t len);
uint32_t yr_hash(uint32_t seed, const void* buffer, size_t len);
YR_API int yr_hash_table_create(
int size,
YR_HASH_TABLE** table);
YR_API int yr_hash_table_create(int size, YR_HASH_TABLE** table);
YR_API void yr_hash_table_clean(
+20 -24
View File
@@ -43,15 +43,15 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#undef YY_DECL
#undef LEX_ENV
#define yyparse hex_yyparse
#define yylex hex_yylex
#define yyerror hex_yyerror
#define yyfatal hex_yyfatal
#define yychar hex_yychar
#define yydebug hex_yydebug
#define yynerrs hex_yynerrs
#define yyget_extra hex_yyget_extra
#define yyget_lineno hex_yyget_lineno
#define yyparse hex_yyparse
#define yylex hex_yylex
#define yyerror hex_yyerror
#define yyfatal hex_yyfatal
#define yychar hex_yychar
#define yydebug hex_yydebug
#define yynerrs hex_yynerrs
#define yyget_extra hex_yyget_extra
#define yyget_lineno hex_yyget_lineno
#ifndef YY_TYPEDEF_YY_SCANNER_T
@@ -79,36 +79,32 @@ typedef struct _HEX_LEX_ENVIRONMENT
// own function instead of the one provided by default.
#define YY_FATAL_ERROR(msg) hex_yyfatal(yyscanner, msg)
#define LEX_ENV ((HEX_LEX_ENVIRONMENT*) lex_env)
#define LEX_ENV ((HEX_LEX_ENVIRONMENT*) lex_env)
#include <hex_grammar.h>
#define YY_DECL int hex_yylex \
(YYSTYPE * yylval_param , yyscan_t yyscanner, HEX_LEX_ENVIRONMENT* lex_env)
#define YY_DECL \
int hex_yylex( \
YYSTYPE* yylval_param, yyscan_t yyscanner, HEX_LEX_ENVIRONMENT* lex_env)
YY_EXTRA_TYPE yyget_extra(
yyscan_t yyscanner);
YY_EXTRA_TYPE yyget_extra(yyscan_t yyscanner);
int yylex(
YYSTYPE* yylval_param,
yyscan_t yyscanner,
HEX_LEX_ENVIRONMENT* lex_env);
int yyparse(
void *yyscanner,
HEX_LEX_ENVIRONMENT *lex_env);
int yyparse(void* yyscanner, HEX_LEX_ENVIRONMENT* lex_env);
void yyerror(
yyscan_t yyscanner,
HEX_LEX_ENVIRONMENT* lex_env,
const char *error_message);
const char* error_message);
void yyfatal(
yyscan_t yyscanner,
const char *error_message);
void yyfatal(yyscan_t yyscanner, const char* error_message);
int yr_parse_hex_string(
const char* hex_string,
RE_AST** re_ast,
RE_ERROR* error);
const char* hex_string,
RE_AST** re_ast,
RE_ERROR* error);
+27 -25
View File
@@ -31,24 +31,26 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define YR_INTEGERS_H
#if ( defined( _MSC_VER ) && ( _MSC_VER < 1600 ) ) || ( defined( __BORLANDC__ ) && ( __BORLANDC__ <= 0x0560 ) )
#if (defined(_MSC_VER) && (_MSC_VER < 1600)) || \
(defined(__BORLANDC__) && (__BORLANDC__ <= 0x0560))
#ifdef __cplusplus
extern "C" {
extern "C"
{
#endif
// Microsoft Visual Studio C++ before Visual Studio 2010 or earlier versions of
// the Borland C++ Builder do not support the (u)int#_t type definitions but
// have __int# definitions instead
// Microsoft Visual Studio C++ before Visual Studio 2010 or earlier versions
// of the Borland C++ Builder do not support the (u)int#_t type definitions
// but have __int# definitions instead
typedef __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
typedef __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#ifdef __cplusplus
}
@@ -56,51 +58,51 @@ typedef unsigned __int64 uint64_t;
#ifndef INT8_MIN
#define INT8_MIN (-127i8 - 1)
#define INT8_MIN (-127i8 - 1)
#endif
#ifndef INT8_MIN
#define INT16_MIN (-32767i16 - 1)
#define INT16_MIN (-32767i16 - 1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647i32 - 1)
#define INT32_MIN (-2147483647i32 - 1)
#endif
#ifndef INT64_MIN
#define INT64_MIN (-9223372036854775807i64 - 1)
#define INT64_MIN (-9223372036854775807i64 - 1)
#endif
#ifndef INT8_MAX
#define INT8_MAX 127i8
#define INT8_MAX 127i8
#endif
#ifndef INT16_MAX
#define INT16_MAX 32767i16
#define INT16_MAX 32767i16
#endif
#ifndef INT32_MAX
#define INT32_MAX 2147483647i32
#define INT32_MAX 2147483647i32
#endif
#ifndef INT64_MAX
#define INT64_MAX 9223372036854775807i64
#define INT64_MAX 9223372036854775807i64
#endif
#ifndef UINT8_MAX
#define UINT8_MAX 0xffui8
#define UINT8_MAX 0xffui8
#endif
#ifndef UINT16_MAX
#define UINT16_MAX 0xffffui16
#define UINT16_MAX 0xffffui16
#endif
#ifndef UINT32_MAX
#define UINT32_MAX 0xffffffffui32
#define UINT32_MAX 0xffffffffui32
#endif
#ifndef UINT64_MAX
#define UINT64_MAX 0xffffffffffffffffui64
#define UINT64_MAX 0xffffffffffffffffui64
#endif
#else
+22 -34
View File
@@ -44,16 +44,16 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#undef YY_FATAL_ERROR
#undef YY_EXTRA_TYPE
#define yyparse yara_yyparse
#define yylex yara_yylex
#define yyerror yara_yyerror
#define yyfatal yara_yyfatal
#define yywarning yara_yywarning
#define yychar yara_yychar
#define yydebug yara_yydebug
#define yynerrs yara_yynerrs
#define yyget_extra yara_yyget_extra
#define yyget_lineno yara_yyget_lineno
#define yyparse yara_yyparse
#define yylex yara_yylex
#define yyerror yara_yyerror
#define yyfatal yara_yyfatal
#define yywarning yara_yywarning
#define yychar yara_yychar
#define yydebug yara_yydebug
#define yynerrs yara_yynerrs
#define yyget_extra yara_yyget_extra
#define yyget_lineno yara_yyget_lineno
#ifndef YY_TYPEDEF_YY_SCANNER_T
@@ -63,8 +63,9 @@ typedef void* yyscan_t;
union YYSTYPE;
#define YY_DECL int yylex( \
union YYSTYPE* yylval_param, yyscan_t yyscanner, YR_COMPILER* compiler)
#define YY_DECL \
int yylex( \
union YYSTYPE* yylval_param, yyscan_t yyscanner, YR_COMPILER* compiler)
#define YY_FATAL_ERROR(msg) yara_yyfatal(yyscanner, msg)
@@ -81,35 +82,22 @@ int yylex(
yyscan_t yyscanner,
YR_COMPILER* compiler);
int yyparse(
void *yyscanner,
YR_COMPILER* compiler);
int yyparse(void* yyscanner, YR_COMPILER* compiler);
void yyerror(
yyscan_t yyscanner,
YR_COMPILER* compiler,
const char *error_message);
const char* error_message);
void yywarning(
yyscan_t yyscanner,
const char *message_fmt,
...) YR_PRINTF_LIKE(2, 3);
void yywarning(yyscan_t yyscanner, const char* message_fmt, ...)
YR_PRINTF_LIKE(2, 3);
void yyfatal(
yyscan_t yyscanner,
const char *error_message);
void yyfatal(yyscan_t yyscanner, const char* error_message);
YY_EXTRA_TYPE yyget_extra(
yyscan_t yyscanner);
YY_EXTRA_TYPE yyget_extra(yyscan_t yyscanner);
int yr_lex_parse_rules_string(
const char* rules_string,
YR_COMPILER* compiler);
int yr_lex_parse_rules_string(const char* rules_string, YR_COMPILER* compiler);
int yr_lex_parse_rules_file(
FILE* rules_file,
YR_COMPILER* compiler);
int yr_lex_parse_rules_file(FILE* rules_file, YR_COMPILER* compiler);
int yr_lex_parse_rules_fd(
YR_FILE_DESCRIPTOR rules_fd,
YR_COMPILER* compiler);
int yr_lex_parse_rules_fd(YR_FILE_DESCRIPTOR rules_fd, YR_COMPILER* compiler);
+12 -13
View File
@@ -32,22 +32,21 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <yara/utils.h>
#define YR_MAJOR_VERSION 4
#define YR_MINOR_VERSION 0
#define YR_MICRO_VERSION 2
#define YR_MAJOR_VERSION 4
#define YR_MINOR_VERSION 0
#define YR_MICRO_VERSION 2
#define version_str(s) _version_str(s)
#define version_str(s) _version_str(s)
#define _version_str(s) #s
// Version as a string
#define YR_VERSION version_str(YR_MAJOR_VERSION) \
"." version_str(YR_MINOR_VERSION) \
"." version_str(YR_MICRO_VERSION)
#define YR_VERSION \
version_str(YR_MAJOR_VERSION) "." version_str( \
YR_MINOR_VERSION) "." version_str(YR_MICRO_VERSION)
// Version as a single 4-byte hex number, e.g. 0x030401 == 3.4.1.
#define YR_VERSION_HEX ((YR_MAJOR_VERSION << 16) | \
(YR_MINOR_VERSION << 8) | \
(YR_MICRO_VERSION << 0))
#define YR_VERSION_HEX \
((YR_MAJOR_VERSION << 16) | (YR_MINOR_VERSION << 8) | (YR_MICRO_VERSION << 0))
// Enumerated type listing configuration options
@@ -62,9 +61,9 @@ typedef enum _YR_CONFIG_NAME
} YR_CONFIG_NAME;
#define DEFAULT_STACK_SIZE 16384
#define DEFAULT_MAX_STRINGS_PER_RULE 10000
#define DEFAULT_MAX_MATCH_DATA 512
#define DEFAULT_STACK_SIZE 16384
#define DEFAULT_MAX_STRINGS_PER_RULE 10000
#define DEFAULT_MAX_MATCH_DATA 512
YR_API int yr_initialize(void);
+9 -9
View File
@@ -58,14 +58,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Capacity of the buffer used for storing compiler error messages. Messages
// will be truncated at this size.
#ifndef YR_MAX_COMPILER_ERROR_EXTRA_INFO
#define YR_MAX_COMPILER_ERROR_EXTRA_INFO 256
#define YR_MAX_COMPILER_ERROR_EXTRA_INFO 256
#endif
// Maximum size for the substring (atoms) extracted from strings and regular
// expressions and put into the Aho-Corasick automaton. The maximum allows size
// for this constant is 255.
#ifndef YR_MAX_ATOM_LENGTH
#define YR_MAX_ATOM_LENGTH 4
#define YR_MAX_ATOM_LENGTH 4
#endif
#ifndef YR_MAX_ATOM_QUALITY
@@ -82,12 +82,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// must specify the threshold when calling yr_compiler_set_atom_quality_table.
#ifndef YR_ATOM_QUALITY_WARNING_THRESHOLD
#define YR_ATOM_QUALITY_WARNING_THRESHOLD \
YR_MAX_ATOM_QUALITY - 20 * YR_MAX_ATOM_LENGTH + 38
YR_MAX_ATOM_QUALITY - 20 * YR_MAX_ATOM_LENGTH + 38
#endif
// If a rule generates more than this number of atoms a warning is shown.
#ifndef YR_ATOMS_PER_RULE_WARNING_THRESHOLD
#define YR_ATOMS_PER_RULE_WARNING_THRESHOLD 10000
#define YR_ATOMS_PER_RULE_WARNING_THRESHOLD 10000
#endif
// Maximum number of nested "for" loops in rule. Rules ith nested loops
@@ -131,8 +131,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Regular expressions like /foo.{x,y}bar/ are split in two separate ones /foo/
// and /bar/ if x is larger than YR_STRING_CHAINING_THRESHOLD. This also applies to
// hex strings like { 01 02 03 [x-y] 004 05 06 }.
// and /bar/ if x is larger than YR_STRING_CHAINING_THRESHOLD. This also applies
// to hex strings like { 01 02 03 [x-y] 004 05 06 }.
#ifndef YR_STRING_CHAINING_THRESHOLD
#define YR_STRING_CHAINING_THRESHOLD 200
#endif
@@ -145,9 +145,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Each time an atom is found it means that we have a potential match for some
// string, and that match must be verified. The time spent in verifying those
// matches is measured in one out of YR_MATCH_VERIFICATION_PROFILING_RATE matches.
// The time is not measured for all matches because measuring it is expensive
// by itself and match verification is a frequent operation.
// matches is measured in one out of YR_MATCH_VERIFICATION_PROFILING_RATE
// matches. The time is not measured for all matches because measuring it is
// expensive by itself and match verification is a frequent operation.
#ifndef YR_MATCH_VERIFICATION_PROFILING_RATE
#define YR_MATCH_VERIFICATION_PROFILING_RATE 1024
#endif
+245 -244
View File
@@ -34,255 +34,256 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Mach-O file format magic constants
#define MH_MAGIC 0xfeedface
#define MH_CIGAM 0xcefaedfe
#define MH_MAGIC_64 0xfeedfacf
#define MH_CIGAM_64 0xcffaedfe
#define MH_MAGIC 0xfeedface
#define MH_CIGAM 0xcefaedfe
#define MH_MAGIC_64 0xfeedfacf
#define MH_CIGAM_64 0xcffaedfe
// Mach-O universal binary magic constants
#define FAT_MAGIC 0xcafebabe
#define FAT_CIGAM 0xbebafeca
#define FAT_MAGIC_64 0xcafebabf
#define FAT_CIGAM_64 0xbfbafeca
#define FAT_MAGIC 0xcafebabe
#define FAT_CIGAM 0xbebafeca
#define FAT_MAGIC_64 0xcafebabf
#define FAT_CIGAM_64 0xbfbafeca
// Mach-O 64-bit masks
#define CPU_ARCH_ABI64 0x01000000 // 64-bit ABI mask (for cputype)
#define CPU_SUBTYPE_LIB64 0x80000000 // 64-bit library mask (for cpusubtype)
#define CPU_ARCH_ABI64 0x01000000 // 64-bit ABI mask (for cputype)
#define CPU_SUBTYPE_LIB64 0x80000000 // 64-bit library mask (for cpusubtype)
// Mach-O CPU types
#define CPU_TYPE_MC680X0 0x00000006 // Motorola 68000
#define CPU_TYPE_I386 0x00000007 // AMD/Intel x86
#define CPU_TYPE_X86 0x00000007 // AMD/Intel x86
#define CPU_TYPE_X86_64 0x01000007 // AMD/Intel x86-64
#define CPU_TYPE_MIPS 0x00000008 // MIPS
#define CPU_TYPE_MC98000 0x0000000a // Motorola PowerPC
#define CPU_TYPE_HPPA 0x0000000b // HP PA-RISC
#define CPU_TYPE_ARM 0x0000000c // ARM
#define CPU_TYPE_ARM64 0x0100000c // ARM 64-bit
#define CPU_TYPE_MC88000 0x0000000d // Motorola 88000
#define CPU_TYPE_SPARC 0x0000000e // SPARC
#define CPU_TYPE_I860 0x0000000f // Intel i860
#define CPU_TYPE_ALPHA 0x00000010 // DEC Alpha
#define CPU_TYPE_POWERPC 0x00000012 // PowerPC
#define CPU_TYPE_POWERPC64 0x01000012 // PowerPC 64-bit
#define CPU_TYPE_MC680X0 0x00000006 // Motorola 68000
#define CPU_TYPE_I386 0x00000007 // AMD/Intel x86
#define CPU_TYPE_X86 0x00000007 // AMD/Intel x86
#define CPU_TYPE_X86_64 0x01000007 // AMD/Intel x86-64
#define CPU_TYPE_MIPS 0x00000008 // MIPS
#define CPU_TYPE_MC98000 0x0000000a // Motorola PowerPC
#define CPU_TYPE_HPPA 0x0000000b // HP PA-RISC
#define CPU_TYPE_ARM 0x0000000c // ARM
#define CPU_TYPE_ARM64 0x0100000c // ARM 64-bit
#define CPU_TYPE_MC88000 0x0000000d // Motorola 88000
#define CPU_TYPE_SPARC 0x0000000e // SPARC
#define CPU_TYPE_I860 0x0000000f // Intel i860
#define CPU_TYPE_ALPHA 0x00000010 // DEC Alpha
#define CPU_TYPE_POWERPC 0x00000012 // PowerPC
#define CPU_TYPE_POWERPC64 0x01000012 // PowerPC 64-bit
// Mach-O Intel CPU sub-types
#define CPU_SUBTYPE_INTEL_MODEL_ALL 0x00
#define CPU_SUBTYPE_386 0x03
#define CPU_SUBTYPE_486 0x04
#define CPU_SUBTYPE_486SX 0x84
#define CPU_SUBTYPE_586 0x05
#define CPU_SUBTYPE_PENT 0x05
#define CPU_SUBTYPE_PENTPRO 0x16
#define CPU_SUBTYPE_PENTII_M3 0x36
#define CPU_SUBTYPE_PENTII_M5 0x56
#define CPU_SUBTYPE_CELERON 0x67
#define CPU_SUBTYPE_CELERON_MOBILE 0x77
#define CPU_SUBTYPE_PENTIUM_3 0x08
#define CPU_SUBTYPE_PENTIUM_3_M 0x18
#define CPU_SUBTYPE_PENTIUM_3_XEON 0x28
#define CPU_SUBTYPE_PENTIUM_M 0x09
#define CPU_SUBTYPE_PENTIUM_4 0x0a
#define CPU_SUBTYPE_PENTIUM_4_M 0x1a
#define CPU_SUBTYPE_ITANIUM 0x0b
#define CPU_SUBTYPE_ITANIUM_2 0x1b
#define CPU_SUBTYPE_XEON 0x0c
#define CPU_SUBTYPE_XEON_MP 0x1c
#define CPU_SUBTYPE_INTEL_MODEL_ALL 0x00
#define CPU_SUBTYPE_386 0x03
#define CPU_SUBTYPE_486 0x04
#define CPU_SUBTYPE_486SX 0x84
#define CPU_SUBTYPE_586 0x05
#define CPU_SUBTYPE_PENT 0x05
#define CPU_SUBTYPE_PENTPRO 0x16
#define CPU_SUBTYPE_PENTII_M3 0x36
#define CPU_SUBTYPE_PENTII_M5 0x56
#define CPU_SUBTYPE_CELERON 0x67
#define CPU_SUBTYPE_CELERON_MOBILE 0x77
#define CPU_SUBTYPE_PENTIUM_3 0x08
#define CPU_SUBTYPE_PENTIUM_3_M 0x18
#define CPU_SUBTYPE_PENTIUM_3_XEON 0x28
#define CPU_SUBTYPE_PENTIUM_M 0x09
#define CPU_SUBTYPE_PENTIUM_4 0x0a
#define CPU_SUBTYPE_PENTIUM_4_M 0x1a
#define CPU_SUBTYPE_ITANIUM 0x0b
#define CPU_SUBTYPE_ITANIUM_2 0x1b
#define CPU_SUBTYPE_XEON 0x0c
#define CPU_SUBTYPE_XEON_MP 0x1c
// Mach-O ARM CPU sub-types
#define CPU_SUBTYPE_ARM_ALL 0x00
#define CPU_SUBTYPE_ARM_V4T 0x05
#define CPU_SUBTYPE_ARM_V6 0x06
#define CPU_SUBTYPE_ARM_V5 0x07
#define CPU_SUBTYPE_ARM_V5TEJ 0x07
#define CPU_SUBTYPE_ARM_XSCALE 0x08
#define CPU_SUBTYPE_ARM_V7 0x09
#define CPU_SUBTYPE_ARM_V7F 0x0a
#define CPU_SUBTYPE_ARM_V7S 0x0b
#define CPU_SUBTYPE_ARM_V7K 0x0c
#define CPU_SUBTYPE_ARM_V6M 0x0e
#define CPU_SUBTYPE_ARM_V7M 0x0f
#define CPU_SUBTYPE_ARM_V7EM 0x10
#define CPU_SUBTYPE_ARM_ALL 0x00
#define CPU_SUBTYPE_ARM_V4T 0x05
#define CPU_SUBTYPE_ARM_V6 0x06
#define CPU_SUBTYPE_ARM_V5 0x07
#define CPU_SUBTYPE_ARM_V5TEJ 0x07
#define CPU_SUBTYPE_ARM_XSCALE 0x08
#define CPU_SUBTYPE_ARM_V7 0x09
#define CPU_SUBTYPE_ARM_V7F 0x0a
#define CPU_SUBTYPE_ARM_V7S 0x0b
#define CPU_SUBTYPE_ARM_V7K 0x0c
#define CPU_SUBTYPE_ARM_V6M 0x0e
#define CPU_SUBTYPE_ARM_V7M 0x0f
#define CPU_SUBTYPE_ARM_V7EM 0x10
// Mach-O ARM 64-bit CPU sub-types
#define CPU_SUBTYPE_ARM64_ALL 0x00
#define CPU_SUBTYPE_ARM64_ALL 0x00
// Mach-O SPARC CPU sub-types
#define CPU_SUBTYPE_SPARC_ALL 0x00
#define CPU_SUBTYPE_SPARC_ALL 0x00
// Mach-O PowerPC CPU sub-types
#define CPU_SUBTYPE_POWERPC_ALL 0x00
#define CPU_SUBTYPE_MC980000_ALL 0x00
#define CPU_SUBTYPE_POWERPC_601 0x01
#define CPU_SUBTYPE_MC98601 0x01
#define CPU_SUBTYPE_POWERPC_602 0x02
#define CPU_SUBTYPE_POWERPC_603 0x03
#define CPU_SUBTYPE_POWERPC_603e 0x04
#define CPU_SUBTYPE_POWERPC_603ev 0x05
#define CPU_SUBTYPE_POWERPC_604 0x06
#define CPU_SUBTYPE_POWERPC_604e 0x07
#define CPU_SUBTYPE_POWERPC_620 0x08
#define CPU_SUBTYPE_POWERPC_750 0x09
#define CPU_SUBTYPE_POWERPC_7400 0x0a
#define CPU_SUBTYPE_POWERPC_7450 0x0b
#define CPU_SUBTYPE_POWERPC_970 0x64
#define CPU_SUBTYPE_POWERPC_ALL 0x00
#define CPU_SUBTYPE_MC980000_ALL 0x00
#define CPU_SUBTYPE_POWERPC_601 0x01
#define CPU_SUBTYPE_MC98601 0x01
#define CPU_SUBTYPE_POWERPC_602 0x02
#define CPU_SUBTYPE_POWERPC_603 0x03
#define CPU_SUBTYPE_POWERPC_603e 0x04
#define CPU_SUBTYPE_POWERPC_603ev 0x05
#define CPU_SUBTYPE_POWERPC_604 0x06
#define CPU_SUBTYPE_POWERPC_604e 0x07
#define CPU_SUBTYPE_POWERPC_620 0x08
#define CPU_SUBTYPE_POWERPC_750 0x09
#define CPU_SUBTYPE_POWERPC_7400 0x0a
#define CPU_SUBTYPE_POWERPC_7450 0x0b
#define CPU_SUBTYPE_POWERPC_970 0x64
// Mach-O file types
#define MH_OBJECT 0x01 // Object file
#define MH_EXECUTE 0x02 // Executable file
#define MH_FVMLIB 0x03 // Fixed VM shared library
#define MH_CORE 0x04 // Core dump file
#define MH_PRELOAD 0x05 // Preloaded executable file
#define MH_DYLIB 0x06 // Dynamic shared library
#define MH_DYLINKER 0x07 // Dynamic linker shared library
#define MH_BUNDLE 0x08 // Bundle file
#define MH_DYLIB_STUB 0x09 // Dynamic shared library stub
#define MH_DSYM 0x0a // Companion debug sections file
#define MH_KEXT_BUNDLE 0x0b // Kernel extension
#define MH_OBJECT 0x01 // Object file
#define MH_EXECUTE 0x02 // Executable file
#define MH_FVMLIB 0x03 // Fixed VM shared library
#define MH_CORE 0x04 // Core dump file
#define MH_PRELOAD 0x05 // Preloaded executable file
#define MH_DYLIB 0x06 // Dynamic shared library
#define MH_DYLINKER 0x07 // Dynamic linker shared library
#define MH_BUNDLE 0x08 // Bundle file
#define MH_DYLIB_STUB 0x09 // Dynamic shared library stub
#define MH_DSYM 0x0a // Companion debug sections file
#define MH_KEXT_BUNDLE 0x0b // Kernel extension
// Mach-O file flags
#define MH_NOUNDEFS 0x00000001
#define MH_INCRLINK 0x00000002
#define MH_DYLDLINK 0x00000004
#define MH_BINDATLOAD 0x00000008
#define MH_PREBOUND 0x00000010
#define MH_SPLIT_SEGS 0x00000020
#define MH_LAZY_INIT 0x00000040
#define MH_TWOLEVEL 0x00000080
#define MH_FORCE_FLAT 0x00000100
#define MH_NOMULTIDEFS 0x00000200
#define MH_NOFIXPREBINDING 0x00000400
#define MH_PREBINDABLE 0x00000800
#define MH_ALLMODSBOUND 0x00001000
#define MH_SUBSECTIONS_VIA_SYMBOLS 0x00002000
#define MH_CANONICAL 0x00004000
#define MH_WEAK_DEFINES 0x00008000
#define MH_BINDS_TO_WEAK 0x00010000
#define MH_ALLOW_STACK_EXECUTION 0x00020000
#define MH_ROOT_SAFE 0x00040000
#define MH_SETUID_SAFE 0x00080000
#define MH_NO_REEXPORTED_DYLIBS 0x00100000
#define MH_PIE 0x00200000
#define MH_DEAD_STRIPPABLE_DYLIB 0x00400000
#define MH_HAS_TLV_DESCRIPTORS 0x00800000
#define MH_NO_HEAP_EXECUTION 0x01000000
#define MH_APP_EXTENSION_SAFE 0x02000000
#define MH_NOUNDEFS 0x00000001
#define MH_INCRLINK 0x00000002
#define MH_DYLDLINK 0x00000004
#define MH_BINDATLOAD 0x00000008
#define MH_PREBOUND 0x00000010
#define MH_SPLIT_SEGS 0x00000020
#define MH_LAZY_INIT 0x00000040
#define MH_TWOLEVEL 0x00000080
#define MH_FORCE_FLAT 0x00000100
#define MH_NOMULTIDEFS 0x00000200
#define MH_NOFIXPREBINDING 0x00000400
#define MH_PREBINDABLE 0x00000800
#define MH_ALLMODSBOUND 0x00001000
#define MH_SUBSECTIONS_VIA_SYMBOLS 0x00002000
#define MH_CANONICAL 0x00004000
#define MH_WEAK_DEFINES 0x00008000
#define MH_BINDS_TO_WEAK 0x00010000
#define MH_ALLOW_STACK_EXECUTION 0x00020000
#define MH_ROOT_SAFE 0x00040000
#define MH_SETUID_SAFE 0x00080000
#define MH_NO_REEXPORTED_DYLIBS 0x00100000
#define MH_PIE 0x00200000
#define MH_DEAD_STRIPPABLE_DYLIB 0x00400000
#define MH_HAS_TLV_DESCRIPTORS 0x00800000
#define MH_NO_HEAP_EXECUTION 0x01000000
#define MH_APP_EXTENSION_SAFE 0x02000000
// Mach-O load commands
#define LC_SEGMENT 0x00000001
#define LC_SYMTAB 0x00000002
#define LC_SYMSEG 0x00000003
#define LC_THREAD 0x00000004
#define LC_UNIXTHREAD 0x00000005
#define LC_LOADFVMLIB 0x00000006
#define LC_IDFVMLIB 0x00000007
#define LC_IDENT 0x00000008
#define LC_FVMFILE 0x00000009
#define LC_PREPAGE 0x0000000a
#define LC_DYSYMTAB 0x0000000b
#define LC_LOAD_DYLIB 0x0000000c
#define LC_ID_DYLIB 0x0000000d
#define LC_LOAD_DYLINKER 0x0000000e
#define LC_ID_DYLINKER 0x0000000f
#define LC_PREBOUND_DYLIB 0x00000010
#define LC_ROUTINES 0x00000011
#define LC_SUB_FRAMEWORK 0x00000012
#define LC_SUB_UMBRELLA 0x00000013
#define LC_SUB_CLIENT 0x00000014
#define LC_SUB_LIBRARY 0x00000015
#define LC_TWOLEVEL_HINTS 0x00000016
#define LC_PREBIND_CKSUM 0x00000017
#define LC_LOAD_WEAK_DYLIB 0x80000018
#define LC_SEGMENT_64 0x00000019
#define LC_ROUTINES_64 0x0000001A
#define LC_UUID 0x0000001B
#define LC_RPATH 0x8000001C
#define LC_CODE_SIGNATURE 0x0000001D
#define LC_SEGMENT_SPLIT_INFO 0x0000001E
#define LC_REEXPORT_DYLIB 0x8000001F
#define LC_LAZY_LOAD_DYLIB 0x00000020
#define LC_ENCRYPTION_INFO 0x00000021
#define LC_DYLD_INFO 0x00000022
#define LC_DYLD_INFO_ONLY 0x80000022
#define LC_LOAD_UPWARD_DYLIB 0x80000023
#define LC_VERSION_MIN_MACOSX 0x00000024
#define LC_VERSION_MIN_IPHONEOS 0x00000025
#define LC_FUNCTION_STARTS 0x00000026
#define LC_DYLD_ENVIRONMENT 0x00000027
#define LC_MAIN 0x80000028
#define LC_DATA_IN_CODE 0x00000029
#define LC_SOURCE_VERSION 0x0000002A
#define LC_DYLIB_CODE_SIGN_DRS 0x0000002B
#define LC_ENCRYPTION_INFO_64 0x0000002C
#define LC_LINKER_OPTION 0x0000002D
#define LC_LINKER_OPTIMIZATION_HINT 0x0000002E
#define LC_VERSION_MIN_TVOS 0x0000002F
#define LC_VERSION_MIN_WATCHOS 0x00000030
#define LC_SEGMENT 0x00000001
#define LC_SYMTAB 0x00000002
#define LC_SYMSEG 0x00000003
#define LC_THREAD 0x00000004
#define LC_UNIXTHREAD 0x00000005
#define LC_LOADFVMLIB 0x00000006
#define LC_IDFVMLIB 0x00000007
#define LC_IDENT 0x00000008
#define LC_FVMFILE 0x00000009
#define LC_PREPAGE 0x0000000a
#define LC_DYSYMTAB 0x0000000b
#define LC_LOAD_DYLIB 0x0000000c
#define LC_ID_DYLIB 0x0000000d
#define LC_LOAD_DYLINKER 0x0000000e
#define LC_ID_DYLINKER 0x0000000f
#define LC_PREBOUND_DYLIB 0x00000010
#define LC_ROUTINES 0x00000011
#define LC_SUB_FRAMEWORK 0x00000012
#define LC_SUB_UMBRELLA 0x00000013
#define LC_SUB_CLIENT 0x00000014
#define LC_SUB_LIBRARY 0x00000015
#define LC_TWOLEVEL_HINTS 0x00000016
#define LC_PREBIND_CKSUM 0x00000017
#define LC_LOAD_WEAK_DYLIB 0x80000018
#define LC_SEGMENT_64 0x00000019
#define LC_ROUTINES_64 0x0000001A
#define LC_UUID 0x0000001B
#define LC_RPATH 0x8000001C
#define LC_CODE_SIGNATURE 0x0000001D
#define LC_SEGMENT_SPLIT_INFO 0x0000001E
#define LC_REEXPORT_DYLIB 0x8000001F
#define LC_LAZY_LOAD_DYLIB 0x00000020
#define LC_ENCRYPTION_INFO 0x00000021
#define LC_DYLD_INFO 0x00000022
#define LC_DYLD_INFO_ONLY 0x80000022
#define LC_LOAD_UPWARD_DYLIB 0x80000023
#define LC_VERSION_MIN_MACOSX 0x00000024
#define LC_VERSION_MIN_IPHONEOS 0x00000025
#define LC_FUNCTION_STARTS 0x00000026
#define LC_DYLD_ENVIRONMENT 0x00000027
#define LC_MAIN 0x80000028
#define LC_DATA_IN_CODE 0x00000029
#define LC_SOURCE_VERSION 0x0000002A
#define LC_DYLIB_CODE_SIGN_DRS 0x0000002B
#define LC_ENCRYPTION_INFO_64 0x0000002C
#define LC_LINKER_OPTION 0x0000002D
#define LC_LINKER_OPTIMIZATION_HINT 0x0000002E
#define LC_VERSION_MIN_TVOS 0x0000002F
#define LC_VERSION_MIN_WATCHOS 0x00000030
// Segment flags
#define SG_HIGHVM 0x00000001 // Use high part of VM (stack)
#define SG_FVMLIB 0x00000002 // Allocated by a fixed VM library
#define SG_NORELOC 0x00000004 // No associated relocations
#define SG_PROTECTED_VERSION_1 0x00000008 // Segment is encryption protected
#define SG_HIGHVM 0x00000001 // Use high part of VM (stack)
#define SG_FVMLIB 0x00000002 // Allocated by a fixed VM library
#define SG_NORELOC 0x00000004 // No associated relocations
#define SG_PROTECTED_VERSION_1 0x00000008 // Segment is encryption protected
// Section flag masks
#define SECTION_TYPE 0x000000ff // Section type mask
#define SECTION_ATTRIBUTES 0xffffff00 // Section attributes mask
#define SECTION_TYPE 0x000000ff // Section type mask
#define SECTION_ATTRIBUTES 0xffffff00 // Section attributes mask
// Section type (use SECTION_TYPE mask)
#define S_REGULAR 0x00
#define S_ZEROFILL 0x01
#define S_CSTRING_LITERALS 0x02
#define S_4BYTE_LITERALS 0x03
#define S_8BYTE_LITERALS 0x04
#define S_LITERAL_POINTERS 0x05
#define S_NON_LAZY_SYMBOL_POINTERS 0x06
#define S_LAZY_SYMBOL_POINTERS 0x07
#define S_SYMBOL_STUBS 0x08
#define S_MOD_INIT_FUNC_POINTERS 0x09
#define S_MOD_TERM_FUNC_POINTERS 0x0a
#define S_COALESCED 0x0b
#define S_GB_ZEROFILL 0x0c
#define S_INTERPOSING 0x0d
#define S_16BYTE_LITERALS 0x0e
#define S_DTRACE_DOF 0x0f
#define S_LAZY_DYLIB_SYMBOL_POINTERS 0x10
#define S_THREAD_LOCAL_REGULAR 0x11
#define S_THREAD_LOCAL_ZEROFILL 0x12
#define S_THREAD_LOCAL_VARIABLES 0x13
#define S_THREAD_LOCAL_VARIABLE_POINTERS 0x14
#define S_THREAD_LOCAL_INIT_FUNCTION_POINTERS 0x15
#define S_REGULAR 0x00
#define S_ZEROFILL 0x01
#define S_CSTRING_LITERALS 0x02
#define S_4BYTE_LITERALS 0x03
#define S_8BYTE_LITERALS 0x04
#define S_LITERAL_POINTERS 0x05
#define S_NON_LAZY_SYMBOL_POINTERS 0x06
#define S_LAZY_SYMBOL_POINTERS 0x07
#define S_SYMBOL_STUBS 0x08
#define S_MOD_INIT_FUNC_POINTERS 0x09
#define S_MOD_TERM_FUNC_POINTERS 0x0a
#define S_COALESCED 0x0b
#define S_GB_ZEROFILL 0x0c
#define S_INTERPOSING 0x0d
#define S_16BYTE_LITERALS 0x0e
#define S_DTRACE_DOF 0x0f
#define S_LAZY_DYLIB_SYMBOL_POINTERS 0x10
#define S_THREAD_LOCAL_REGULAR 0x11
#define S_THREAD_LOCAL_ZEROFILL 0x12
#define S_THREAD_LOCAL_VARIABLES 0x13
#define S_THREAD_LOCAL_VARIABLE_POINTERS 0x14
#define S_THREAD_LOCAL_INIT_FUNCTION_POINTERS 0x15
// Section attributes (use SECTION_ATTRIBUTES mask)
#define S_ATTR_PURE_INSTRUCTIONS 0x80000000 // Only pure instructions
#define S_ATTR_NO_TOC 0x40000000 // Contains coalesced symbols
#define S_ATTR_STRIP_STATIC_SYMS 0x20000000 // Can strip static symbols
#define S_ATTR_NO_DEAD_STRIP 0x10000000 // No dead stripping
#define S_ATTR_LIVE_SUPPORT 0x08000000 // Live blocks support
#define S_ATTR_SELF_MODIFYING_CODE 0x04000000 // Self modifying code
#define S_ATTR_DEBUG 0x02000000 // Debug section
#define S_ATTR_SOME_INSTRUCTIONS 0x00000400 // Some machine instructions
#define S_ATTR_EXT_RELOC 0x00000200 // Has external relocations
#define S_ATTR_LOC_RELOC 0x00000100 // Has local relocations
#define S_ATTR_PURE_INSTRUCTIONS 0x80000000 // Only pure instructions
#define S_ATTR_NO_TOC 0x40000000 // Contains coalesced symbols
#define S_ATTR_STRIP_STATIC_SYMS 0x20000000 // Can strip static symbols
#define S_ATTR_NO_DEAD_STRIP 0x10000000 // No dead stripping
#define S_ATTR_LIVE_SUPPORT 0x08000000 // Live blocks support
#define S_ATTR_SELF_MODIFYING_CODE 0x04000000 // Self modifying code
#define S_ATTR_DEBUG 0x02000000 // Debug section
#define S_ATTR_SOME_INSTRUCTIONS 0x00000400 // Some machine instructions
#define S_ATTR_EXT_RELOC 0x00000200 // Has external relocations
#define S_ATTR_LOC_RELOC 0x00000100 // Has local relocations
#pragma pack(push,1)
#pragma pack(push, 1)
typedef struct {
typedef struct
{
uint32_t magic;
uint32_t cputype;
uint32_t cpusubtype;
@@ -292,8 +293,8 @@ typedef struct {
uint32_t flags;
} yr_mach_header_32_t;
typedef struct {
typedef struct
{
uint32_t magic;
uint32_t cputype;
uint32_t cpusubtype;
@@ -304,14 +305,14 @@ typedef struct {
uint32_t reserved;
} yr_mach_header_64_t;
typedef struct {
typedef struct
{
uint32_t cmd;
uint32_t cmdsize;
} yr_load_command_t;
typedef struct {
typedef struct
{
uint32_t cmd;
uint32_t cmdsize;
char segname[16];
@@ -325,8 +326,8 @@ typedef struct {
uint32_t flags;
} yr_segment_command_32_t;
typedef struct {
typedef struct
{
uint32_t cmd;
uint32_t cmdsize;
char segname[16];
@@ -340,8 +341,8 @@ typedef struct {
uint32_t flags;
} yr_segment_command_64_t;
typedef struct {
typedef struct
{
char sectname[16];
char segname[16];
uint32_t addr;
@@ -355,8 +356,8 @@ typedef struct {
uint32_t reserved2;
} yr_section_32_t;
typedef struct {
typedef struct
{
char sectname[16];
char segname[16];
uint64_t addr;
@@ -371,23 +372,23 @@ typedef struct {
uint32_t reserved3;
} yr_section_64_t;
typedef struct {
typedef struct
{
uint32_t cmd;
uint32_t cmdsize;
uint8_t uuid[16];
} yr_uuid_command_t;
typedef struct {
typedef struct
{
uint32_t cmd;
uint32_t cmdsize;
uint64_t entryoff;
uint64_t stacksize;
} yr_entry_point_command_t;
typedef struct {
typedef struct
{
uint32_t cmd;
uint32_t cmdsize;
uint32_t flavor;
@@ -395,8 +396,8 @@ typedef struct {
// cpu_thread_state
} yr_thread_command_t;
typedef struct {
typedef struct
{
uint32_t eax;
uint32_t ebx;
uint32_t ecx;
@@ -415,8 +416,8 @@ typedef struct {
uint32_t gs;
} yr_x86_thread_state_t;
typedef struct {
typedef struct
{
uint32_t r[13];
uint32_t sp;
uint32_t lr;
@@ -424,8 +425,8 @@ typedef struct {
uint32_t cpsr;
} yr_arm_thread_state_t;
typedef struct {
typedef struct
{
uint32_t srr0;
uint32_t srr1;
uint32_t r[32];
@@ -437,8 +438,8 @@ typedef struct {
uint32_t vrsavead;
} yr_ppc_thread_state_t;
typedef struct {
typedef struct
{
uint32_t psr;
uint32_t pc;
uint32_t npc;
@@ -460,8 +461,8 @@ typedef struct {
uint32_t o7;
} yr_sparc_thread_state_t;
typedef struct {
typedef struct
{
uint32_t dreg[8];
uint32_t areg[8];
uint16_t pad;
@@ -469,8 +470,8 @@ typedef struct {
uint32_t pc;
} yr_m68k_thread_state_t;
typedef struct {
typedef struct
{
uint32_t r1;
uint32_t r2;
uint32_t r3;
@@ -507,8 +508,8 @@ typedef struct {
uint32_t nip;
} yr_m88k_thread_state_t;
typedef struct {
typedef struct
{
uint64_t rax;
uint64_t rbx;
uint64_t rcx;
@@ -532,8 +533,8 @@ typedef struct {
uint64_t gs;
} yr_x86_thread_state64_t;
typedef struct {
typedef struct
{
uint64_t r[29];
uint64_t fp;
uint64_t lr;
@@ -542,8 +543,8 @@ typedef struct {
uint64_t cpsr;
} yr_arm_thread_state64_t;
typedef struct {
typedef struct
{
uint64_t srr0;
uint64_t srr1;
uint64_t r[32];
@@ -554,14 +555,14 @@ typedef struct {
uint32_t vrsave;
} yr_ppc_thread_state64_t;
typedef struct {
typedef struct
{
uint32_t magic;
uint32_t nfat_arch;
} yr_fat_header_t;
typedef struct {
typedef struct
{
uint32_t cputype;
uint32_t cpusubtype;
uint32_t offset;
@@ -569,8 +570,8 @@ typedef struct {
uint32_t align;
} yr_fat_arch_32_t;
typedef struct {
typedef struct
{
uint32_t cputype;
uint32_t cpusubtype;
uint64_t offset;
+10 -18
View File
@@ -34,36 +34,28 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifdef DMALLOC
#define yr_malloc malloc
#define yr_calloc calloc
#define yr_malloc malloc
#define yr_calloc calloc
#define yr_realloc realloc
#define yr_free free
#define yr_strdup strdup
#define yr_free free
#define yr_strdup strdup
#define yr_strndup strndup
#include <dmalloc.h>
#else
void* yr_calloc(
size_t count,
size_t size);
void* yr_calloc(size_t count, size_t size);
void* yr_malloc(
size_t size);
void* yr_malloc(size_t size);
void* yr_realloc(
void* ptr,
size_t size);
void* yr_realloc(void* ptr, size_t size);
void yr_free(
void *ptr);
void yr_free(void* ptr);
char* yr_strdup(
const char *str);
char* yr_strdup(const char* str);
char* yr_strndup(
const char *str, size_t n);
char* yr_strndup(const char* str, size_t n);
#endif
+182 -297
View File
@@ -31,361 +31,258 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define YR_MODULES_H
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <yara/utils.h>
#include <yara/limits.h>
#include <yara/error.h>
#include <yara/exec.h>
#include <yara/types.h>
#include <yara/re.h>
#include <yara/object.h>
#include <yara/libyara.h>
#include <yara/limits.h>
#include <yara/object.h>
#include <yara/re.h>
#include <yara/types.h>
#include <yara/utils.h>
// Concatenation that macro-expands its arguments.
#define YR_CONCAT(arg1, arg2) _YR_CONCAT(arg1, arg2) // expands the arguments.
#define _YR_CONCAT(arg1, arg2) arg1 ## arg2 // do the actual concatenation.
#define YR_CONCAT(arg1, arg2) _YR_CONCAT(arg1, arg2) // expands the arguments.
#define _YR_CONCAT(arg1, arg2) arg1##arg2 // do the actual concatenation.
#define module_declarations YR_CONCAT(MODULE_NAME, __declarations)
#define module_load YR_CONCAT(MODULE_NAME, __load)
#define module_unload YR_CONCAT(MODULE_NAME, __unload)
#define module_initialize YR_CONCAT(MODULE_NAME, __initialize)
#define module_finalize YR_CONCAT(MODULE_NAME, __finalize)
#define begin_declarations \
int module_declarations(YR_OBJECT* module) { \
YR_OBJECT* stack[64]; \
int stack_top = 0; \
stack[stack_top] = module;
#define module_load YR_CONCAT(MODULE_NAME, __load)
#define module_unload YR_CONCAT(MODULE_NAME, __unload)
#define module_initialize YR_CONCAT(MODULE_NAME, __initialize)
#define module_finalize YR_CONCAT(MODULE_NAME, __finalize)
#define begin_declarations \
int module_declarations(YR_OBJECT* module) \
{ \
YR_OBJECT* stack[64]; \
int stack_top = 0; \
stack[stack_top] = module;
#define end_declarations \
return ERROR_SUCCESS; }
#define begin_struct(name) { \
YR_OBJECT* structure; \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_STRUCTURE, \
name, \
stack[stack_top], \
&structure)); \
assertf( \
stack_top < sizeof(stack)/sizeof(stack[0]) - 1, \
"too many nested structures"); \
stack[++stack_top] = structure; \
return ERROR_SUCCESS; \
}
#define begin_struct_array(name) { \
YR_OBJECT* structure; \
YR_OBJECT* array; \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_ARRAY, \
name, \
stack[stack_top], \
&array)); \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_STRUCTURE, \
name, \
array, \
&structure)); \
assertf( \
stack_top < sizeof(stack)/sizeof(stack[0]) - 1, \
"too many nested structures"); \
stack[++stack_top] = structure; \
#define begin_struct(name) \
{ \
YR_OBJECT* structure; \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_STRUCTURE, name, stack[stack_top], &structure)); \
assertf( \
stack_top < sizeof(stack) / sizeof(stack[0]) - 1, \
"too many nested structures"); \
stack[++stack_top] = structure; \
}
#define begin_struct_dictionary(name) { \
YR_OBJECT* structure; \
YR_OBJECT* array; \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_DICTIONARY, \
name, \
stack[stack_top], \
&array)); \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_STRUCTURE, \
name, \
array, \
&structure)); \
assertf( \
stack_top < sizeof(stack)/sizeof(stack[0]) - 1, \
"too many nested structures"); \
stack[++stack_top] = structure; \
#define begin_struct_array(name) \
{ \
YR_OBJECT* structure; \
YR_OBJECT* array; \
FAIL_ON_ERROR( \
yr_object_create(OBJECT_TYPE_ARRAY, name, stack[stack_top], &array)); \
FAIL_ON_ERROR( \
yr_object_create(OBJECT_TYPE_STRUCTURE, name, array, &structure)); \
assertf( \
stack_top < sizeof(stack) / sizeof(stack[0]) - 1, \
"too many nested structures"); \
stack[++stack_top] = structure; \
}
#define begin_struct_dictionary(name) \
{ \
YR_OBJECT* structure; \
YR_OBJECT* array; \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_DICTIONARY, name, stack[stack_top], &array)); \
FAIL_ON_ERROR( \
yr_object_create(OBJECT_TYPE_STRUCTURE, name, array, &structure)); \
assertf( \
stack_top < sizeof(stack) / sizeof(stack[0]) - 1, \
"too many nested structures"); \
stack[++stack_top] = structure; \
}
#define end_struct(name) { \
#define end_struct(name) \
{ \
assert(stack[stack_top]->type == OBJECT_TYPE_STRUCTURE); \
assertf( \
strcmp(stack[stack_top]->identifier, name) == 0, \
"unbalanced begin_struct/end_struct"); \
stack_top--; \
assertf( \
strcmp(stack[stack_top]->identifier, name) == 0, \
"unbalanced begin_struct/end_struct"); \
stack_top--; \
}
#define end_struct_array(name) \
end_struct \
(name)
#define end_struct_array(name) end_struct(name)
#define end_struct_dictionary(name) \
end_struct \
(name)
#define end_struct_dictionary(name) end_struct(name)
#define declare_integer(name) { \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_INTEGER, \
name, \
stack[stack_top], \
NULL)); \
#define declare_integer(name) \
{ \
FAIL_ON_ERROR( \
yr_object_create(OBJECT_TYPE_INTEGER, name, stack[stack_top], NULL)); \
}
#define declare_integer_array(name) { \
YR_OBJECT* array; \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_ARRAY, \
name, \
stack[stack_top], \
&array)); \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_INTEGER, \
name, \
array, \
NULL)); \
#define declare_integer_array(name) \
{ \
YR_OBJECT* array; \
FAIL_ON_ERROR( \
yr_object_create(OBJECT_TYPE_ARRAY, name, stack[stack_top], &array)); \
FAIL_ON_ERROR(yr_object_create(OBJECT_TYPE_INTEGER, name, array, NULL)); \
}
#define declare_integer_dictionary(name) { \
YR_OBJECT* dict; \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_DICTIONARY, \
name, \
stack[stack_top], \
&dict)); \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_INTEGER, \
name, \
dict, \
NULL)); \
#define declare_integer_dictionary(name) \
{ \
YR_OBJECT* dict; \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_DICTIONARY, name, stack[stack_top], &dict)); \
FAIL_ON_ERROR(yr_object_create(OBJECT_TYPE_INTEGER, name, dict, NULL)); \
}
#define declare_float(name) { \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_FLOAT, \
name, \
stack[stack_top], \
NULL)); \
#define declare_float(name) \
{ \
FAIL_ON_ERROR( \
yr_object_create(OBJECT_TYPE_FLOAT, name, stack[stack_top], NULL)); \
}
#define declare_float_array(name) { \
YR_OBJECT* array; \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_ARRAY, \
name, \
stack[stack_top], \
&array)); \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_FLOAT, \
name, \
array, \
NULL)); \
#define declare_float_array(name) \
{ \
YR_OBJECT* array; \
FAIL_ON_ERROR( \
yr_object_create(OBJECT_TYPE_ARRAY, name, stack[stack_top], &array)); \
FAIL_ON_ERROR(yr_object_create(OBJECT_TYPE_FLOAT, name, array, NULL)); \
}
#define declare_float_dictionary(name) { \
YR_OBJECT* dict; \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_DICTIONARY, \
name, \
stack[stack_top], \
&dict)); \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_FLOAT, \
name, \
dict, \
NULL)); \
#define declare_float_dictionary(name) \
{ \
YR_OBJECT* dict; \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_DICTIONARY, name, stack[stack_top], &dict)); \
FAIL_ON_ERROR(yr_object_create(OBJECT_TYPE_FLOAT, name, dict, NULL)); \
}
#define declare_string(name) { \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_STRING, \
name, \
stack[stack_top], \
NULL)); \
#define declare_string(name) \
{ \
FAIL_ON_ERROR( \
yr_object_create(OBJECT_TYPE_STRING, name, stack[stack_top], NULL)); \
}
#define declare_string_array(name) { \
YR_OBJECT* array; \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_ARRAY, \
name, \
stack[stack_top], \
&array)); \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_STRING, \
name, \
array, \
NULL)); \
#define declare_string_array(name) \
{ \
YR_OBJECT* array; \
FAIL_ON_ERROR( \
yr_object_create(OBJECT_TYPE_ARRAY, name, stack[stack_top], &array)); \
FAIL_ON_ERROR(yr_object_create(OBJECT_TYPE_STRING, name, array, NULL)); \
}
#define declare_string_dictionary(name) { \
YR_OBJECT* dict; \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_DICTIONARY, \
name, \
stack[stack_top], \
&dict)); \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_STRING, \
name, \
dict, \
NULL)); \
#define declare_string_dictionary(name) \
{ \
YR_OBJECT* dict; \
FAIL_ON_ERROR(yr_object_create( \
OBJECT_TYPE_DICTIONARY, name, stack[stack_top], &dict)); \
FAIL_ON_ERROR(yr_object_create(OBJECT_TYPE_STRING, name, dict, NULL)); \
}
#define declare_function(name, args_fmt, ret_fmt, func) \
{ \
YR_OBJECT* function; \
FAIL_ON_ERROR(yr_object_function_create( \
name, args_fmt, ret_fmt, func, stack[stack_top], &function)); \
}
#define declare_function(name, args_fmt, ret_fmt, func) { \
YR_OBJECT* function; \
FAIL_ON_ERROR(yr_object_function_create( \
name, \
args_fmt, \
ret_fmt, \
func, \
stack[stack_top], \
&function)); \
}
#define define_function(func) \
int func( \
YR_VALUE* __args, \
YR_SCAN_CONTEXT* __context, \
YR_OBJECT_FUNCTION* __function_obj)
#define sized_string_argument(n) (__args[n - 1].ss)
#define define_function(func) \
int func ( \
YR_VALUE* __args, \
YR_SCAN_CONTEXT* __context, \
YR_OBJECT_FUNCTION* __function_obj)
#define string_argument(n) (sized_string_argument(n)->c_string)
#define integer_argument(n) (__args[n - 1].i)
#define sized_string_argument(n) \
(__args[n-1].ss)
#define float_argument(n) (__args[n - 1].d)
#define string_argument(n) \
(sized_string_argument(n)->c_string)
#define regexp_argument(n) ((RE*) (__args[n - 1].re))
#define integer_argument(n) \
(__args[n-1].i)
#define float_argument(n) \
(__args[n-1].d)
#define regexp_argument(n) \
((RE*)(__args[n-1].re))
#define module() yr_object_get_root((YR_OBJECT*) __function_obj)
#define parent() (__function_obj->parent)
#define scan_context() (__context)
#define foreach_memory_block(iterator, block) \
for (block = iterator->first(iterator); \
block != NULL; \
block = iterator->next(iterator)) \
#define module() yr_object_get_root((YR_OBJECT*) __function_obj)
#define parent() (__function_obj->parent)
#define scan_context() (__context)
#define foreach_memory_block(iterator, block) \
for (block = iterator->first(iterator); block != NULL; \
block = iterator->next(iterator))
#define first_memory_block(context) \
(context)->iterator->first((context)->iterator)
(context)->iterator->first((context)->iterator)
#define is_undefined(object, ...) \
yr_object_has_undefined_value(object, __VA_ARGS__)
yr_object_has_undefined_value(object, __VA_ARGS__)
#define get_object(object, ...) yr_object_lookup(object, 0, __VA_ARGS__)
#define get_object(object, ...) \
yr_object_lookup(object, 0, __VA_ARGS__)
#define get_integer(object, ...) yr_object_get_integer(object, __VA_ARGS__)
#define get_float(object, ...) yr_object_get_float(object, __VA_ARGS__)
#define get_integer(object, ...) \
yr_object_get_integer(object, __VA_ARGS__)
#define get_float(object, ...) \
yr_object_get_float(object, __VA_ARGS__)
#define get_string(object, ...) \
yr_object_get_string(object, __VA_ARGS__)
#define get_string(object, ...) yr_object_get_string(object, __VA_ARGS__)
#define set_integer(value, object, ...) \
yr_object_set_integer(value, object, __VA_ARGS__)
yr_object_set_integer(value, object, __VA_ARGS__)
#define set_float(value, object, ...) \
yr_object_set_float(value, object, __VA_ARGS__)
yr_object_set_float(value, object, __VA_ARGS__)
#define set_sized_string(value, len, object, ...) \
yr_object_set_string(value, len, object, __VA_ARGS__)
yr_object_set_string(value, len, object, __VA_ARGS__)
#define set_string(value, object, ...) \
set_sized_string(value, (value == NULL) ? 0 : strlen(value), object, __VA_ARGS__)
set_sized_string( \
value, (value == NULL) ? 0 : strlen(value), object, __VA_ARGS__)
#define return_integer(integer) \
{ \
assertf( \
__function_obj->return_obj->type == OBJECT_TYPE_INTEGER, \
"return type differs from function declaration"); \
return yr_object_set_integer((integer), __function_obj->return_obj, NULL); \
}
#define return_integer(integer) { \
assertf( \
__function_obj->return_obj->type == OBJECT_TYPE_INTEGER, \
"return type differs from function declaration"); \
return yr_object_set_integer( \
(integer), \
__function_obj->return_obj, \
NULL); \
}
#define return_float(double_) \
{ \
double d = (double) (double_); \
assertf( \
__function_obj->return_obj->type == OBJECT_TYPE_FLOAT, \
"return type differs from function declaration"); \
return yr_object_set_float( \
(d != (double) YR_UNDEFINED) ? d : NAN, \
__function_obj->return_obj, \
NULL); \
}
#define return_string(string) \
{ \
char* s = (char*) (string); \
assertf( \
__function_obj->return_obj->type == OBJECT_TYPE_STRING, \
"return type differs from function declaration"); \
return yr_object_set_string( \
(s != (char*) YR_UNDEFINED) ? s : NULL, \
(s != (char*) YR_UNDEFINED) ? strlen(s) : 0, \
__function_obj->return_obj, \
NULL); \
}
#define return_float(double_) { \
double d = (double) (double_); \
assertf( \
__function_obj->return_obj->type == OBJECT_TYPE_FLOAT, \
"return type differs from function declaration"); \
return yr_object_set_float( \
(d != (double) YR_UNDEFINED) ? d : NAN, \
__function_obj->return_obj, \
NULL); \
}
typedef int (*YR_EXT_INITIALIZE_FUNC)(YR_MODULE* module);
typedef int (*YR_EXT_FINALIZE_FUNC)(YR_MODULE* module);
#define return_string(string) { \
char* s = (char*) (string); \
assertf( \
__function_obj->return_obj->type == OBJECT_TYPE_STRING, \
"return type differs from function declaration"); \
return yr_object_set_string( \
(s != (char*) YR_UNDEFINED) ? s : NULL, \
(s != (char*) YR_UNDEFINED) ? strlen(s) : 0, \
__function_obj->return_obj, \
NULL); \
}
typedef int (*YR_EXT_INITIALIZE_FUNC)(
YR_MODULE* module);
typedef int (*YR_EXT_FINALIZE_FUNC)(
YR_MODULE* module);
typedef int (*YR_EXT_DECLARATIONS_FUNC)(
YR_OBJECT* module_object);
typedef int (*YR_EXT_DECLARATIONS_FUNC)(YR_OBJECT* module_object);
typedef int (*YR_EXT_LOAD_FUNC)(
YR_SCAN_CONTEXT* context,
@@ -393,10 +290,7 @@ typedef int (*YR_EXT_LOAD_FUNC)(
void* module_data,
size_t module_data_size);
typedef int (*YR_EXT_UNLOAD_FUNC)(
YR_OBJECT* module_object);
typedef int (*YR_EXT_UNLOAD_FUNC)(YR_OBJECT* module_object);
struct YR_MODULE
{
@@ -409,7 +303,6 @@ struct YR_MODULE
YR_EXT_FINALIZE_FUNC finalize;
};
struct YR_MODULE_IMPORT
{
const char* module_name;
@@ -417,24 +310,16 @@ struct YR_MODULE_IMPORT
size_t module_data_size;
};
int yr_modules_initialize(void);
int yr_modules_finalize(void);
int yr_modules_do_declarations(
const char* module_name,
YR_OBJECT* main_structure);
int yr_modules_load(const char* module_name, YR_SCAN_CONTEXT* context);
int yr_modules_load(
const char* module_name,
YR_SCAN_CONTEXT* context);
int yr_modules_unload_all(
YR_SCAN_CONTEXT* context);
int yr_modules_unload_all(YR_SCAN_CONTEXT* context);
#endif
+4 -13
View File
@@ -9,19 +9,10 @@
typedef struct YR_NOTEBOOK YR_NOTEBOOK;
int yr_notebook_create(size_t page_size, YR_NOTEBOOK** pool);
int yr_notebook_create(
size_t page_size,
YR_NOTEBOOK** pool);
int yr_notebook_destroy(YR_NOTEBOOK* pool);
void* yr_notebook_alloc(YR_NOTEBOOK* notebook, size_t size);
int yr_notebook_destroy(
YR_NOTEBOOK* pool);
void* yr_notebook_alloc(
YR_NOTEBOOK* notebook,
size_t size);
#endif // YR_NOTEBOOK_H
#endif // YR_NOTEBOOK_H
+31 -83
View File
@@ -31,7 +31,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define YR_OBJECT_H
#ifdef _MSC_VER
#include <float.h>
#ifndef isnan
#define isnan _isnan
@@ -42,25 +41,23 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endif
#ifndef NAN
#define NAN (INFINITY-INFINITY)
#define NAN (INFINITY - INFINITY)
#endif
#endif
#endif
#include <yara/utils.h>
#include <yara/types.h>
#include <yara/sizedstr.h>
#include <yara/types.h>
#include <yara/utils.h>
#define OBJECT_CREATE 1
#define OBJECT_TYPE_INTEGER 1
#define OBJECT_TYPE_STRING 2
#define OBJECT_TYPE_STRUCTURE 3
#define OBJECT_TYPE_ARRAY 4
#define OBJECT_TYPE_FUNCTION 5
#define OBJECT_TYPE_DICTIONARY 6
#define OBJECT_TYPE_FLOAT 7
#define OBJECT_CREATE 1
#define OBJECT_TYPE_INTEGER 1
#define OBJECT_TYPE_STRING 2
#define OBJECT_TYPE_STRUCTURE 3
#define OBJECT_TYPE_ARRAY 4
#define OBJECT_TYPE_FUNCTION 5
#define OBJECT_TYPE_DICTIONARY 6
#define OBJECT_TYPE_FLOAT 7
int yr_object_create(
int8_t type,
@@ -68,11 +65,7 @@ int yr_object_create(
YR_OBJECT* parent,
YR_OBJECT** object);
void yr_object_set_canary(
YR_OBJECT* object,
int canary);
void yr_object_set_canary(YR_OBJECT* object, int canary);
int yr_object_function_create(
const char* identifier,
@@ -82,25 +75,15 @@ int yr_object_function_create(
YR_OBJECT* parent,
YR_OBJECT** function);
int yr_object_from_external_variable(
YR_EXTERNAL_VARIABLE* external,
YR_OBJECT** object);
void yr_object_destroy(YR_OBJECT* object);
void yr_object_destroy(
YR_OBJECT* object);
int yr_object_copy(
YR_OBJECT* object,
YR_OBJECT** object_copy);
YR_OBJECT* yr_object_lookup_field(
YR_OBJECT* object,
const char* field_name);
int yr_object_copy(YR_OBJECT* object, YR_OBJECT** object_copy);
YR_OBJECT* yr_object_lookup_field(YR_OBJECT* object, const char* field_name);
YR_OBJECT* yr_object_lookup(
YR_OBJECT* root,
@@ -108,28 +91,17 @@ YR_OBJECT* yr_object_lookup(
const char* pattern,
...) YR_PRINTF_LIKE(3, 4);
bool yr_object_has_undefined_value(YR_OBJECT* object, const char* field, ...)
YR_PRINTF_LIKE(2, 3);
bool yr_object_has_undefined_value(
YR_OBJECT* object,
const char* field,
...) YR_PRINTF_LIKE(2, 3);
double yr_object_get_float(YR_OBJECT* object, const char* field, ...)
YR_PRINTF_LIKE(2, 3);
double yr_object_get_float(
YR_OBJECT* object,
const char* field,
...) YR_PRINTF_LIKE(2, 3);
int64_t yr_object_get_integer(
YR_OBJECT* object,
const char* field,
...) YR_PRINTF_LIKE(2, 3);
SIZED_STRING* yr_object_get_string(
YR_OBJECT* object,
const char* field,
...) YR_PRINTF_LIKE(2, 3);
int64_t yr_object_get_integer(YR_OBJECT* object, const char* field, ...)
YR_PRINTF_LIKE(2, 3);
SIZED_STRING* yr_object_get_string(YR_OBJECT* object, const char* field, ...)
YR_PRINTF_LIKE(2, 3);
int yr_object_set_integer(
int64_t value,
@@ -137,13 +109,8 @@ int yr_object_set_integer(
const char* field,
...) YR_PRINTF_LIKE(3, 4);
int yr_object_set_float(
double value,
YR_OBJECT* object,
const char* field,
...) YR_PRINTF_LIKE(3, 4);
int yr_object_set_float(double value, YR_OBJECT* object, const char* field, ...)
YR_PRINTF_LIKE(3, 4);
int yr_object_set_string(
const char* value,
@@ -152,48 +119,29 @@ int yr_object_set_string(
const char* field,
...) YR_PRINTF_LIKE(4, 5);
int yr_object_array_length(YR_OBJECT* object);
int yr_object_array_length(
YR_OBJECT* object);
YR_OBJECT* yr_object_array_get_item(
YR_OBJECT* object,
int flags,
int index);
int yr_object_array_set_item(
YR_OBJECT* object,
YR_OBJECT* item,
int index);
YR_OBJECT* yr_object_array_get_item(YR_OBJECT* object, int flags, int index);
int yr_object_array_set_item(YR_OBJECT* object, YR_OBJECT* item, int index);
YR_OBJECT* yr_object_dict_get_item(
YR_OBJECT* object,
int flags,
const char* key);
int yr_object_dict_set_item(
YR_OBJECT* object,
YR_OBJECT* item,
const char* key);
int yr_object_structure_set_member(YR_OBJECT* object, YR_OBJECT* member);
int yr_object_structure_set_member(
YR_OBJECT* object,
YR_OBJECT* member);
YR_OBJECT* yr_object_get_root(
YR_OBJECT* object);
YR_OBJECT* yr_object_get_root(YR_OBJECT* object);
YR_API void yr_object_print_data(
YR_OBJECT* object,
int indent,
int print_identifier);
#endif
+2 -25
View File
@@ -30,16 +30,13 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YR_PARSER_H
#define YR_PARSER_H
#include "lexer.h"
int yr_parser_emit(
yyscan_t yyscanner,
uint8_t instruction,
YR_ARENA_REF* instruction_ref);
int yr_parser_emit_with_arg(
yyscan_t yyscanner,
uint8_t instruction,
@@ -47,7 +44,6 @@ int yr_parser_emit_with_arg(
YR_ARENA_REF* instruction_ref,
YR_ARENA_REF* argument_ref);
int yr_parser_emit_with_arg_int32(
yyscan_t yyscanner,
uint8_t instruction,
@@ -55,7 +51,6 @@ int yr_parser_emit_with_arg_int32(
YR_ARENA_REF* instruction_ref,
YR_ARENA_REF* argument_ref);
int yr_parser_emit_with_arg_double(
yyscan_t yyscanner,
uint8_t instruction,
@@ -63,7 +58,6 @@ int yr_parser_emit_with_arg_double(
YR_ARENA_REF* instruction_ref,
YR_ARENA_REF* argument_ref);
int yr_parser_emit_with_arg_reloc(
yyscan_t yyscanner,
uint8_t instruction,
@@ -71,42 +65,33 @@ int yr_parser_emit_with_arg_reloc(
YR_ARENA_REF* instruction_ref,
YR_ARENA_REF* argument_ref);
int yr_parser_emit_push_const(
yyscan_t yyscanner,
uint64_t argument);
int yr_parser_emit_push_const(yyscan_t yyscanner, uint64_t argument);
int yr_parser_check_types(
YR_COMPILER* compiler,
YR_OBJECT_FUNCTION* function,
const char* actual_args_fmt);
int yr_parser_lookup_string(
yyscan_t yyscanner,
const char* identifier,
YR_STRING** string);
int yr_parser_lookup_loop_variable(
yyscan_t yyscanner,
const char* identifier,
YR_EXPRESSION*);
int yr_parser_reduce_rule_declaration_phase_1(
yyscan_t yyscanner,
int32_t flags,
const char* identifier,
YR_ARENA_REF* rule_ref);
int yr_parser_reduce_rule_declaration_phase_2(
yyscan_t yyscanner,
YR_ARENA_REF* rule_ref);
int yr_parser_reduce_string_declaration(
yyscan_t yyscanner,
YR_MODIFIER modifier,
@@ -114,7 +99,6 @@ int yr_parser_reduce_string_declaration(
SIZED_STRING* str,
YR_ARENA_REF* string_ref);
int yr_parser_reduce_meta_declaration(
yyscan_t yyscanner,
int32_t type,
@@ -123,29 +107,22 @@ int yr_parser_reduce_meta_declaration(
int64_t integer,
YR_ARENA_REF* meta_ref);
int yr_parser_reduce_string_identifier(
yyscan_t yyscanner,
const char* identifier,
uint8_t instruction,
uint64_t at_offset);
int yr_parser_emit_pushes_for_strings(
yyscan_t yyscanner,
const char* identifier);
int yr_parser_reduce_external(
yyscan_t yyscanner,
const char* identifier,
uint8_t instruction);
int yr_parser_reduce_import(
yyscan_t yyscanner,
SIZED_STRING* module_name);
int yr_parser_reduce_import(yyscan_t yyscanner, SIZED_STRING* module_name);
int yr_parser_reduce_operation(
yyscan_t yyscanner,
+378 -357
View File
@@ -45,68 +45,66 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// These definitions are not present in older Windows headers.
#ifndef IMAGE_FILE_MACHINE_ARMNT
#define IMAGE_FILE_MACHINE_ARMNT 0x01c4
#define IMAGE_FILE_MACHINE_ARMNT 0x01c4
#endif
#ifndef IMAGE_FILE_MACHINE_ARM64
#define IMAGE_FILE_MACHINE_ARM64 0xaa64
#define IMAGE_FILE_MACHINE_ARM64 0xaa64
#endif
#else
#include <stdlib.h>
#include <yara/integers.h>
typedef uint8_t BYTE;
typedef uint16_t WORD;
typedef uint32_t DWORD;
typedef int32_t LONG;
typedef uint32_t ULONG;
typedef uint64_t ULONGLONG;
typedef uint8_t BYTE;
typedef uint16_t WORD;
typedef uint32_t DWORD;
typedef int32_t LONG;
typedef uint32_t ULONG;
typedef uint64_t ULONGLONG;
#ifndef _MAC
#define IMAGE_DOS_SIGNATURE 0x5A4D // MZ
#define IMAGE_OS2_SIGNATURE 0x454E // NE
#define IMAGE_OS2_SIGNATURE_LE 0x454C // LE
#define IMAGE_VXD_SIGNATURE 0x454C // LE
#define IMAGE_NT_SIGNATURE 0x00004550 // PE00
#define IMAGE_DOS_SIGNATURE 0x5A4D // MZ
#define IMAGE_OS2_SIGNATURE 0x454E // NE
#define IMAGE_OS2_SIGNATURE_LE 0x454C // LE
#define IMAGE_VXD_SIGNATURE 0x454C // LE
#define IMAGE_NT_SIGNATURE 0x00004550 // PE00
#else
#define IMAGE_DOS_SIGNATURE 0x4D5A // MZ
#define IMAGE_OS2_SIGNATURE 0x4E45 // NE
#define IMAGE_OS2_SIGNATURE_LE 0x4C45 // LE
#define IMAGE_NT_SIGNATURE 0x50450000 // PE00
#define IMAGE_DOS_SIGNATURE 0x4D5A // MZ
#define IMAGE_OS2_SIGNATURE 0x4E45 // NE
#define IMAGE_OS2_SIGNATURE_LE 0x4C45 // LE
#define IMAGE_NT_SIGNATURE 0x50450000 // PE00
#endif
#pragma pack(push, 2)
typedef struct _IMAGE_DOS_HEADER { // DOS .EXE header
WORD e_magic; // Magic number
WORD e_cblp; // Bytes on last page of file
WORD e_cp; // Pages in file
WORD e_crlc; // Relocations
WORD e_cparhdr; // Size of header in paragraphs
WORD e_minalloc; // Minimum extra paragraphs needed
WORD e_maxalloc; // Maximum extra paragraphs needed
WORD e_ss; // Initial (relative) SS value
WORD e_sp; // Initial SP value
WORD e_csum; // Checksum
WORD e_ip; // Initial IP value
WORD e_cs; // Initial (relative) CS value
WORD e_lfarlc; // File address of relocation table
WORD e_ovno; // Overlay number
WORD e_res[4]; // Reserved words
WORD e_oemid; // OEM identifier (for e_oeminfo)
WORD e_oeminfo; // OEM information; e_oemid specific
WORD e_res2[10]; // Reserved words
LONG e_lfanew; // File address of new exe header
} IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
typedef struct _IMAGE_DOS_HEADER
{ // DOS .EXE header
WORD e_magic; // Magic number
WORD e_cblp; // Bytes on last page of file
WORD e_cp; // Pages in file
WORD e_crlc; // Relocations
WORD e_cparhdr; // Size of header in paragraphs
WORD e_minalloc; // Minimum extra paragraphs needed
WORD e_maxalloc; // Maximum extra paragraphs needed
WORD e_ss; // Initial (relative) SS value
WORD e_sp; // Initial SP value
WORD e_csum; // Checksum
WORD e_ip; // Initial IP value
WORD e_cs; // Initial (relative) CS value
WORD e_lfarlc; // File address of relocation table
WORD e_ovno; // Overlay number
WORD e_res[4]; // Reserved words
WORD e_oemid; // OEM identifier (for e_oeminfo)
WORD e_oeminfo; // OEM information; e_oemid specific
WORD e_res2[10]; // Reserved words
LONG e_lfanew; // File address of new exe header
} IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
#pragma pack(pop)
@@ -114,301 +112,317 @@ typedef struct _IMAGE_DOS_HEADER { // DOS .EXE header
// File header format.
//
#pragma pack(push,4)
#pragma pack(push, 4)
typedef struct _IMAGE_FILE_HEADER {
WORD Machine;
WORD NumberOfSections;
DWORD TimeDateStamp;
DWORD PointerToSymbolTable;
DWORD NumberOfSymbols;
WORD SizeOfOptionalHeader;
WORD Characteristics;
typedef struct _IMAGE_FILE_HEADER
{
WORD Machine;
WORD NumberOfSections;
DWORD TimeDateStamp;
DWORD PointerToSymbolTable;
DWORD NumberOfSymbols;
WORD SizeOfOptionalHeader;
WORD Characteristics;
} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
#define IMAGE_SIZEOF_FILE_HEADER 20
// Relocation info stripped from file.
#define IMAGE_FILE_RELOCS_STRIPPED 0x0001
// File is executable (i.e. no unresolved external references).
#define IMAGE_FILE_EXECUTABLE_IMAGE 0x0002
// Line numbers stripped from file.
#define IMAGE_FILE_LINE_NUMS_STRIPPED 0x0004
// Local symbols stripped from file.
#define IMAGE_FILE_LOCAL_SYMS_STRIPPED 0x0008
// Aggressively trim working set
#define IMAGE_FILE_AGGRESIVE_WS_TRIM 0x0010
// App can handle >2gb addresses
#define IMAGE_FILE_LARGE_ADDRESS_AWARE 0x0020
// Bytes of machine word are reversed.
#define IMAGE_FILE_BYTES_REVERSED_LO 0x0080
// 32 bit word machine.
#define IMAGE_FILE_32BIT_MACHINE 0x0100
// Debugging info stripped from file in .DBG file
#define IMAGE_FILE_DEBUG_STRIPPED 0x0200
// If Image is on removable media, copy and run from the swap file.
#define IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP 0x0400
// If Image is on Net, copy and run from the swap file.
#define IMAGE_FILE_NET_RUN_FROM_SWAP 0x0800
// System File.
#define IMAGE_FILE_SYSTEM 0x1000
// File is a DLL.s
#define IMAGE_FILE_DLL 0x2000
// File should only be run on a UP machine
#define IMAGE_FILE_UP_SYSTEM_ONLY 0x4000
// Bytes of machine word are reversed.
#define IMAGE_FILE_BYTES_REVERSED_HI 0x8000
#define IMAGE_SIZEOF_FILE_HEADER 20
#define IMAGE_FILE_RELOCS_STRIPPED 0x0001 // Relocation info stripped from file.
#define IMAGE_FILE_EXECUTABLE_IMAGE 0x0002 // File is executable (i.e. no unresolved external references).
#define IMAGE_FILE_LINE_NUMS_STRIPPED 0x0004 // Line numbers stripped from file.
#define IMAGE_FILE_LOCAL_SYMS_STRIPPED 0x0008 // Local symbols stripped from file.
#define IMAGE_FILE_AGGRESIVE_WS_TRIM 0x0010 // Aggressively trim working set
#define IMAGE_FILE_LARGE_ADDRESS_AWARE 0x0020 // App can handle >2gb addresses
#define IMAGE_FILE_BYTES_REVERSED_LO 0x0080 // Bytes of machine word are reversed.
#define IMAGE_FILE_32BIT_MACHINE 0x0100 // 32 bit word machine.
#define IMAGE_FILE_DEBUG_STRIPPED 0x0200 // Debugging info stripped from file in .DBG file
#define IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP 0x0400 // If Image is on removable media, copy and run from the swap file.
#define IMAGE_FILE_NET_RUN_FROM_SWAP 0x0800 // If Image is on Net, copy and run from the swap file.
#define IMAGE_FILE_SYSTEM 0x1000 // System File.
#define IMAGE_FILE_DLL 0x2000 // File is a DLL.
#define IMAGE_FILE_UP_SYSTEM_ONLY 0x4000 // File should only be run on a UP machine
#define IMAGE_FILE_BYTES_REVERSED_HI 0x8000 // Bytes of machine word are reversed.
#define IMAGE_FILE_MACHINE_UNKNOWN 0x0000
#define IMAGE_FILE_MACHINE_AM33 0x01d3
#define IMAGE_FILE_MACHINE_AMD64 0x8664
#define IMAGE_FILE_MACHINE_ARM 0x01c0
#define IMAGE_FILE_MACHINE_ARMNT 0x01c4
#define IMAGE_FILE_MACHINE_ARM64 0xaa64
#define IMAGE_FILE_MACHINE_EBC 0x0ebc
#define IMAGE_FILE_MACHINE_I386 0x014c
#define IMAGE_FILE_MACHINE_IA64 0x0200
#define IMAGE_FILE_MACHINE_M32R 0x9041
#define IMAGE_FILE_MACHINE_MIPS16 0x0266
#define IMAGE_FILE_MACHINE_MIPSFPU 0x0366
#define IMAGE_FILE_MACHINE_MIPSFPU16 0x0466
#define IMAGE_FILE_MACHINE_POWERPC 0x01f0
#define IMAGE_FILE_MACHINE_POWERPCFP 0x01f1
#define IMAGE_FILE_MACHINE_R4000 0x0166
#define IMAGE_FILE_MACHINE_SH3 0x01a2
#define IMAGE_FILE_MACHINE_SH3DSP 0x01a3
#define IMAGE_FILE_MACHINE_SH4 0x01a6
#define IMAGE_FILE_MACHINE_SH5 0x01a8
#define IMAGE_FILE_MACHINE_THUMB 0x01c2
#define IMAGE_FILE_MACHINE_WCEMIPSV2 0x0169
#define IMAGE_FILE_MACHINE_UNKNOWN 0x0000
#define IMAGE_FILE_MACHINE_AM33 0x01d3
#define IMAGE_FILE_MACHINE_AMD64 0x8664
#define IMAGE_FILE_MACHINE_ARM 0x01c0
#define IMAGE_FILE_MACHINE_ARMNT 0x01c4
#define IMAGE_FILE_MACHINE_ARM64 0xaa64
#define IMAGE_FILE_MACHINE_EBC 0x0ebc
#define IMAGE_FILE_MACHINE_I386 0x014c
#define IMAGE_FILE_MACHINE_IA64 0x0200
#define IMAGE_FILE_MACHINE_M32R 0x9041
#define IMAGE_FILE_MACHINE_MIPS16 0x0266
#define IMAGE_FILE_MACHINE_MIPSFPU 0x0366
#define IMAGE_FILE_MACHINE_MIPSFPU16 0x0466
#define IMAGE_FILE_MACHINE_POWERPC 0x01f0
#define IMAGE_FILE_MACHINE_POWERPCFP 0x01f1
#define IMAGE_FILE_MACHINE_R4000 0x0166
#define IMAGE_FILE_MACHINE_SH3 0x01a2
#define IMAGE_FILE_MACHINE_SH3DSP 0x01a3
#define IMAGE_FILE_MACHINE_SH4 0x01a6
#define IMAGE_FILE_MACHINE_SH5 0x01a8
#define IMAGE_FILE_MACHINE_THUMB 0x01c2
#define IMAGE_FILE_MACHINE_WCEMIPSV2 0x0169
// Section characteristics
#define IMAGE_SCN_CNT_CODE 0x00000020
#define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
#define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
#define IMAGE_SCN_GPREL 0x00008000
#define IMAGE_SCN_MEM_16BIT 0x00020000
#define IMAGE_SCN_LNK_NRELOC_OVFL 0x01000000
#define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
#define IMAGE_SCN_MEM_NOT_CACHED 0x04000000
#define IMAGE_SCN_MEM_NOT_PAGED 0x08000000
#define IMAGE_SCN_MEM_SHARED 0x10000000
#define IMAGE_SCN_MEM_EXECUTE 0x20000000
#define IMAGE_SCN_MEM_READ 0x40000000
#define IMAGE_SCN_MEM_WRITE 0x80000000
#define IMAGE_SCN_CNT_CODE 0x00000020
#define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
#define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
#define IMAGE_SCN_GPREL 0x00008000
#define IMAGE_SCN_MEM_16BIT 0x00020000
#define IMAGE_SCN_LNK_NRELOC_OVFL 0x01000000
#define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
#define IMAGE_SCN_MEM_NOT_CACHED 0x04000000
#define IMAGE_SCN_MEM_NOT_PAGED 0x08000000
#define IMAGE_SCN_MEM_SHARED 0x10000000
#define IMAGE_SCN_MEM_EXECUTE 0x20000000
#define IMAGE_SCN_MEM_READ 0x40000000
#define IMAGE_SCN_MEM_WRITE 0x80000000
//
// Directory format.
//
typedef struct _IMAGE_DATA_DIRECTORY {
DWORD VirtualAddress;
DWORD Size;
typedef struct _IMAGE_DATA_DIRECTORY
{
DWORD VirtualAddress;
DWORD Size;
} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
#define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16
#define IMAGE_DIRECTORY_ENTRY_EXPORT 0 // Export Directory
#define IMAGE_DIRECTORY_ENTRY_IMPORT 1 // Import Directory
#define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 // Resource Directory
#define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 // Exception Directory
#define IMAGE_DIRECTORY_ENTRY_SECURITY 4 // Security Directory
#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 // Base Relocation Table
#define IMAGE_DIRECTORY_ENTRY_DEBUG 6 // Debug Directory
#define IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 // (X86 usage)
#define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 // Architecture Specific Data
#define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 // RVA of GP
#define IMAGE_DIRECTORY_ENTRY_TLS 9 // TLS Directory
#define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 // Load Configuration Directory
#define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 // Bound Import Directory in headers
#define IMAGE_DIRECTORY_ENTRY_IAT 12 // Import Address Table
#define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 // Delay Load Import Descriptors
#define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 // COM Runtime descriptor
#define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16
#define IMAGE_DIRECTORY_ENTRY_EXPORT 0
#define IMAGE_DIRECTORY_ENTRY_IMPORT 1
#define IMAGE_DIRECTORY_ENTRY_RESOURCE 2
#define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3
#define IMAGE_DIRECTORY_ENTRY_SECURITY 4
#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5
#define IMAGE_DIRECTORY_ENTRY_DEBUG 6
#define IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7
#define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7
#define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8
#define IMAGE_DIRECTORY_ENTRY_TLS 9
#define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10
#define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11
#define IMAGE_DIRECTORY_ENTRY_IAT 12
#define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13
#define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14
//
// Optional header format.
//
typedef struct _IMAGE_OPTIONAL_HEADER32 {
WORD Magic;
BYTE MajorLinkerVersion;
BYTE MinorLinkerVersion;
DWORD SizeOfCode;
DWORD SizeOfInitializedData;
DWORD SizeOfUninitializedData;
DWORD AddressOfEntryPoint;
DWORD BaseOfCode;
DWORD BaseOfData;
DWORD ImageBase;
DWORD SectionAlignment;
DWORD FileAlignment;
WORD MajorOperatingSystemVersion;
WORD MinorOperatingSystemVersion;
WORD MajorImageVersion;
WORD MinorImageVersion;
WORD MajorSubsystemVersion;
WORD MinorSubsystemVersion;
DWORD Win32VersionValue;
DWORD SizeOfImage;
DWORD SizeOfHeaders;
DWORD CheckSum;
WORD Subsystem;
WORD DllCharacteristics;
DWORD SizeOfStackReserve;
DWORD SizeOfStackCommit;
DWORD SizeOfHeapReserve;
DWORD SizeOfHeapCommit;
DWORD LoaderFlags;
DWORD NumberOfRvaAndSizes;
IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
typedef struct _IMAGE_OPTIONAL_HEADER32
{
WORD Magic;
BYTE MajorLinkerVersion;
BYTE MinorLinkerVersion;
DWORD SizeOfCode;
DWORD SizeOfInitializedData;
DWORD SizeOfUninitializedData;
DWORD AddressOfEntryPoint;
DWORD BaseOfCode;
DWORD BaseOfData;
DWORD ImageBase;
DWORD SectionAlignment;
DWORD FileAlignment;
WORD MajorOperatingSystemVersion;
WORD MinorOperatingSystemVersion;
WORD MajorImageVersion;
WORD MinorImageVersion;
WORD MajorSubsystemVersion;
WORD MinorSubsystemVersion;
DWORD Win32VersionValue;
DWORD SizeOfImage;
DWORD SizeOfHeaders;
DWORD CheckSum;
WORD Subsystem;
WORD DllCharacteristics;
DWORD SizeOfStackReserve;
DWORD SizeOfStackCommit;
DWORD SizeOfHeapReserve;
DWORD SizeOfHeapCommit;
DWORD LoaderFlags;
DWORD NumberOfRvaAndSizes;
IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
} IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32;
typedef struct _IMAGE_OPTIONAL_HEADER64 {
WORD Magic;
BYTE MajorLinkerVersion;
BYTE MinorLinkerVersion;
DWORD SizeOfCode;
DWORD SizeOfInitializedData;
DWORD SizeOfUninitializedData;
DWORD AddressOfEntryPoint;
DWORD BaseOfCode;
ULONGLONG ImageBase;
DWORD SectionAlignment;
DWORD FileAlignment;
WORD MajorOperatingSystemVersion;
WORD MinorOperatingSystemVersion;
WORD MajorImageVersion;
WORD MinorImageVersion;
WORD MajorSubsystemVersion;
WORD MinorSubsystemVersion;
DWORD Win32VersionValue;
DWORD SizeOfImage;
DWORD SizeOfHeaders;
DWORD CheckSum;
WORD Subsystem;
WORD DllCharacteristics;
ULONGLONG SizeOfStackReserve;
ULONGLONG SizeOfStackCommit;
ULONGLONG SizeOfHeapReserve;
ULONGLONG SizeOfHeapCommit;
DWORD LoaderFlags;
DWORD NumberOfRvaAndSizes;
IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
typedef struct _IMAGE_OPTIONAL_HEADER64
{
WORD Magic;
BYTE MajorLinkerVersion;
BYTE MinorLinkerVersion;
DWORD SizeOfCode;
DWORD SizeOfInitializedData;
DWORD SizeOfUninitializedData;
DWORD AddressOfEntryPoint;
DWORD BaseOfCode;
ULONGLONG ImageBase;
DWORD SectionAlignment;
DWORD FileAlignment;
WORD MajorOperatingSystemVersion;
WORD MinorOperatingSystemVersion;
WORD MajorImageVersion;
WORD MinorImageVersion;
WORD MajorSubsystemVersion;
WORD MinorSubsystemVersion;
DWORD Win32VersionValue;
DWORD SizeOfImage;
DWORD SizeOfHeaders;
DWORD CheckSum;
WORD Subsystem;
WORD DllCharacteristics;
ULONGLONG SizeOfStackReserve;
ULONGLONG SizeOfStackCommit;
ULONGLONG SizeOfHeapReserve;
ULONGLONG SizeOfHeapCommit;
DWORD LoaderFlags;
DWORD NumberOfRvaAndSizes;
IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
} IMAGE_OPTIONAL_HEADER64, *PIMAGE_OPTIONAL_HEADER64;
#define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0x10b
#define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b
#define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0x10b
#define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b
typedef struct _IMAGE_NT_HEADERS32 {
DWORD Signature;
IMAGE_FILE_HEADER FileHeader;
IMAGE_OPTIONAL_HEADER32 OptionalHeader;
typedef struct _IMAGE_NT_HEADERS32
{
DWORD Signature;
IMAGE_FILE_HEADER FileHeader;
IMAGE_OPTIONAL_HEADER32 OptionalHeader;
} IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32;
typedef struct _IMAGE_NT_HEADERS64 {
DWORD Signature;
IMAGE_FILE_HEADER FileHeader;
IMAGE_OPTIONAL_HEADER64 OptionalHeader;
typedef struct _IMAGE_NT_HEADERS64
{
DWORD Signature;
IMAGE_FILE_HEADER FileHeader;
IMAGE_OPTIONAL_HEADER64 OptionalHeader;
} IMAGE_NT_HEADERS64, *PIMAGE_NT_HEADERS64;
// IMAGE_FIRST_SECTION doesn't need 32/64 versions since the file header is
// the same either way.
#define IMAGE_FIRST_SECTION( ntheader ) ((PIMAGE_SECTION_HEADER) \
((BYTE*) ntheader + \
offsetof(IMAGE_NT_HEADERS32, OptionalHeader) + \
yr_le16toh(((PIMAGE_NT_HEADERS32)(ntheader))->FileHeader.SizeOfOptionalHeader) \
))
#define IMAGE_FIRST_SECTION(ntheader) \
((PIMAGE_SECTION_HEADER)( \
(BYTE*) ntheader + offsetof(IMAGE_NT_HEADERS32, OptionalHeader) + \
yr_le16toh(((PIMAGE_NT_HEADERS32)(ntheader)) \
->FileHeader.SizeOfOptionalHeader)))
// Subsystem Values
#define IMAGE_SUBSYSTEM_UNKNOWN 0
#define IMAGE_SUBSYSTEM_NATIVE 1
#define IMAGE_SUBSYSTEM_WINDOWS_GUI 2
#define IMAGE_SUBSYSTEM_WINDOWS_CUI 3
#define IMAGE_SUBSYSTEM_OS2_CUI 5
#define IMAGE_SUBSYSTEM_POSIX_CUI 7
#define IMAGE_SUBSYSTEM_NATIVE_WINDOWS 8
#define IMAGE_SUBSYSTEM_WINDOWS_CE_GUI 9
#define IMAGE_SUBSYSTEM_EFI_APPLICATION 10
#define IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER 11
#define IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER 12
#define IMAGE_SUBSYSTEM_EFI_ROM_IMAGE 13
#define IMAGE_SUBSYSTEM_XBOX 14
#define IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION 16
#define IMAGE_SUBSYSTEM_UNKNOWN 0
#define IMAGE_SUBSYSTEM_NATIVE 1
#define IMAGE_SUBSYSTEM_WINDOWS_GUI 2
#define IMAGE_SUBSYSTEM_WINDOWS_CUI 3
#define IMAGE_SUBSYSTEM_OS2_CUI 5
#define IMAGE_SUBSYSTEM_POSIX_CUI 7
#define IMAGE_SUBSYSTEM_NATIVE_WINDOWS 8
#define IMAGE_SUBSYSTEM_WINDOWS_CE_GUI 9
#define IMAGE_SUBSYSTEM_EFI_APPLICATION 10
#define IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER 11
#define IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER 12
#define IMAGE_SUBSYSTEM_EFI_ROM_IMAGE 13
#define IMAGE_SUBSYSTEM_XBOX 14
#define IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION 16
// DllCharacteristics values
#define IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE 0x0040
#define IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY 0x0080
#define IMAGE_DLLCHARACTERISTICS_NX_COMPAT 0x0100
#define IMAGE_DLLCHARACTERISTICS_NO_ISOLATION 0x0200
#define IMAGE_DLLCHARACTERISTICS_NO_SEH 0x0400
#define IMAGE_DLLCHARACTERISTICS_NO_BIND 0x0800
#define IMAGE_DLLCHARACTERISTICS_WDM_DRIVER 0x2000
#define IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE 0x8000
#define IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE 0x0040
#define IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY 0x0080
#define IMAGE_DLLCHARACTERISTICS_NX_COMPAT 0x0100
#define IMAGE_DLLCHARACTERISTICS_NO_ISOLATION 0x0200
#define IMAGE_DLLCHARACTERISTICS_NO_SEH 0x0400
#define IMAGE_DLLCHARACTERISTICS_NO_BIND 0x0800
#define IMAGE_DLLCHARACTERISTICS_WDM_DRIVER 0x2000
#define IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE 0x8000
//
// Section header format.
//
#define IMAGE_SIZEOF_SHORT_NAME 8
#define IMAGE_SIZEOF_SHORT_NAME 8
typedef struct _IMAGE_SECTION_HEADER {
BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
union {
DWORD PhysicalAddress;
DWORD VirtualSize;
} Misc;
DWORD VirtualAddress;
DWORD SizeOfRawData;
DWORD PointerToRawData;
DWORD PointerToRelocations;
DWORD PointerToLinenumbers;
WORD NumberOfRelocations;
WORD NumberOfLinenumbers;
DWORD Characteristics;
typedef struct _IMAGE_SECTION_HEADER
{
BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
union
{
DWORD PhysicalAddress;
DWORD VirtualSize;
} Misc;
DWORD VirtualAddress;
DWORD SizeOfRawData;
DWORD PointerToRawData;
DWORD PointerToRelocations;
DWORD PointerToLinenumbers;
WORD NumberOfRelocations;
WORD NumberOfLinenumbers;
DWORD Characteristics;
} IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
#define IMAGE_SIZEOF_SECTION_HEADER 40
#define IMAGE_SIZEOF_SECTION_HEADER 40
typedef struct _IMAGE_EXPORT_DIRECTORY {
DWORD Characteristics;
DWORD TimeDateStamp;
WORD MajorVersion;
WORD MinorVersion;
DWORD Name;
DWORD Base;
DWORD NumberOfFunctions;
DWORD NumberOfNames;
DWORD AddressOfFunctions;
DWORD AddressOfNames;
DWORD AddressOfNameOrdinals;
typedef struct _IMAGE_EXPORT_DIRECTORY
{
DWORD Characteristics;
DWORD TimeDateStamp;
WORD MajorVersion;
WORD MinorVersion;
DWORD Name;
DWORD Base;
DWORD NumberOfFunctions;
DWORD NumberOfNames;
DWORD AddressOfFunctions;
DWORD AddressOfNames;
DWORD AddressOfNameOrdinals;
} IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY;
typedef struct _IMAGE_IMPORT_DESCRIPTOR {
union {
DWORD Characteristics;
DWORD OriginalFirstThunk;
} ;
DWORD TimeDateStamp;
DWORD ForwarderChain;
DWORD Name;
DWORD FirstThunk;
typedef struct _IMAGE_IMPORT_DESCRIPTOR
{
union
{
DWORD Characteristics;
DWORD OriginalFirstThunk;
};
DWORD TimeDateStamp;
DWORD ForwarderChain;
DWORD Name;
DWORD FirstThunk;
} IMAGE_IMPORT_DESCRIPTOR, *PIMAGE_IMPORT_DESCRIPTOR;
typedef struct _IMAGE_IMPORT_BY_NAME {
typedef struct _IMAGE_IMPORT_BY_NAME
{
WORD Hint;
BYTE Name[1];
} IMAGE_IMPORT_BY_NAME, *PIMAGE_IMPORT_BY_NAME;
typedef struct _IMAGE_THUNK_DATA32 {
union {
typedef struct _IMAGE_THUNK_DATA32
{
union
{
DWORD ForwarderString;
DWORD Function;
DWORD Ordinal;
@@ -417,12 +431,13 @@ typedef struct _IMAGE_THUNK_DATA32 {
} IMAGE_THUNK_DATA32, *PIMAGE_THUNK_DATA32;
#define IMAGE_ORDINAL_FLAG32 0x80000000
#define IMAGE_ORDINAL_FLAG64 0x8000000000000000L
#define IMAGE_ORDINAL_FLAG32 0x80000000
#define IMAGE_ORDINAL_FLAG64 0x8000000000000000L
typedef struct _IMAGE_THUNK_DATA64 {
union {
typedef struct _IMAGE_THUNK_DATA64
{
union
{
ULONGLONG ForwarderString;
ULONGLONG Function;
ULONGLONG Ordinal;
@@ -431,84 +446,88 @@ typedef struct _IMAGE_THUNK_DATA64 {
} IMAGE_THUNK_DATA64, *PIMAGE_THUNK_DATA64;
typedef struct _IMAGE_RESOURCE_DIRECTORY_ENTRY {
DWORD Name;
DWORD OffsetToData;
typedef struct _IMAGE_RESOURCE_DIRECTORY_ENTRY
{
DWORD Name;
DWORD OffsetToData;
} IMAGE_RESOURCE_DIRECTORY_ENTRY, *PIMAGE_RESOURCE_DIRECTORY_ENTRY;
typedef struct _IMAGE_RESOURCE_DATA_ENTRY
{
DWORD OffsetToData;
DWORD Size;
DWORD CodePage;
DWORD Reserved;
} IMAGE_RESOURCE_DATA_ENTRY, *PIMAGE_RESOURCE_DATA_ENTRY;
typedef struct _IMAGE_RESOURCE_DATA_ENTRY {
DWORD OffsetToData;
DWORD Size;
DWORD CodePage;
DWORD Reserved;
} IMAGE_RESOURCE_DATA_ENTRY,*PIMAGE_RESOURCE_DATA_ENTRY;
typedef struct _IMAGE_RESOURCE_DIRECTORY {
DWORD Characteristics;
DWORD TimeDateStamp;
WORD MajorVersion;
WORD MinorVersion;
WORD NumberOfNamedEntries;
WORD NumberOfIdEntries;
typedef struct _IMAGE_RESOURCE_DIRECTORY
{
DWORD Characteristics;
DWORD TimeDateStamp;
WORD MajorVersion;
WORD MinorVersion;
WORD NumberOfNamedEntries;
WORD NumberOfIdEntries;
} IMAGE_RESOURCE_DIRECTORY, *PIMAGE_RESOURCE_DIRECTORY;
#define IMAGE_DEBUG_TYPE_UNKNOWN 0
#define IMAGE_DEBUG_TYPE_COFF 1
#define IMAGE_DEBUG_TYPE_CODEVIEW 2
#define IMAGE_DEBUG_TYPE_FPO 3
#define IMAGE_DEBUG_TYPE_MISC 4
#define IMAGE_DEBUG_TYPE_EXCEPTION 5
#define IMAGE_DEBUG_TYPE_FIXUP 6
#define IMAGE_DEBUG_TYPE_BORLAND 9
#define IMAGE_DEBUG_TYPE_UNKNOWN 0
#define IMAGE_DEBUG_TYPE_COFF 1
#define IMAGE_DEBUG_TYPE_CODEVIEW 2
#define IMAGE_DEBUG_TYPE_FPO 3
#define IMAGE_DEBUG_TYPE_MISC 4
#define IMAGE_DEBUG_TYPE_EXCEPTION 5
#define IMAGE_DEBUG_TYPE_FIXUP 6
#define IMAGE_DEBUG_TYPE_BORLAND 9
typedef struct _IMAGE_DEBUG_DIRECTORY {
DWORD Characteristics;
DWORD TimeDateStamp;
WORD MajorVersion;
WORD MinorVersion;
DWORD Type;
DWORD SizeOfData;
DWORD AddressOfRawData;
DWORD PointerToRawData;
typedef struct _IMAGE_DEBUG_DIRECTORY
{
DWORD Characteristics;
DWORD TimeDateStamp;
WORD MajorVersion;
WORD MinorVersion;
DWORD Type;
DWORD SizeOfData;
DWORD AddressOfRawData;
DWORD PointerToRawData;
} IMAGE_DEBUG_DIRECTORY, *PIMAGE_DEBUG_DIRECTORY;
#pragma pack(pop)
#endif // _WIN32
#define CVINFO_PDB70_CVSIGNATURE 0x53445352 // "RSDS"
#define CVINFO_PDB20_CVSIGNATURE 0x3031424e // "NB10"
#define CVINFO_PDB70_CVSIGNATURE 0x53445352 // "RSDS"
#define CVINFO_PDB20_CVSIGNATURE 0x3031424e // "NB10"
typedef struct _CV_HEADER {
DWORD dwSignature;
DWORD dwOffset;
typedef struct _CV_HEADER
{
DWORD dwSignature;
DWORD dwOffset;
} CV_HEADER, *PCV_HEADER;
typedef struct _CV_INFO_PDB20 {
CV_HEADER CvHeader;
DWORD dwSignature;
DWORD dwAge;
BYTE PdbFileName[1];
typedef struct _CV_INFO_PDB20
{
CV_HEADER CvHeader;
DWORD dwSignature;
DWORD dwAge;
BYTE PdbFileName[1];
} CV_INFO_PDB20, *PCV_INFO_PDB20;
typedef struct _CV_INFO_PDB70 {
DWORD CvSignature;
DWORD Signature[4];
DWORD Age;
BYTE PdbFileName[1];
typedef struct _CV_INFO_PDB70
{
DWORD CvSignature;
DWORD Signature[4];
DWORD Age;
BYTE PdbFileName[1];
} CV_INFO_PDB70, *PCV_INFO_PDB70;
typedef struct _VERSION_INFO {
WORD Length;
WORD ValueLength;
WORD Type;
char Key[0];
typedef struct _VERSION_INFO
{
WORD Length;
WORD ValueLength;
WORD Type;
char Key[0];
} VERSION_INFO, *PVERSION_INFO;
#define MAX_PE_CERTS 16
#define WIN_CERT_REVISION_1_0 0x0100
@@ -519,42 +538,44 @@ typedef struct _VERSION_INFO {
#define WIN_CERT_TYPE_RESERVED_1 0x0003
#define WIN_CERT_TYPE_TS_STACK_SIGNED 0x0004
#define WIN_CERTIFICATE_HEADER_SIZE 8
#define WIN_CERTIFICATE_HEADER_SIZE 8
typedef struct _WIN_CERTIFICATE {
DWORD Length;
WORD Revision;
WORD CertificateType;
BYTE Certificate[0];
typedef struct _WIN_CERTIFICATE
{
DWORD Length;
WORD Revision;
WORD CertificateType;
BYTE Certificate[0];
} WIN_CERTIFICATE, *PWIN_CERTIFICATE;
#define SPC_NESTED_SIGNATURE_OBJID "1.3.6.1.4.1.311.2.4.1"
#define SPC_NESTED_SIGNATURE_OBJID "1.3.6.1.4.1.311.2.4.1"
//
// Rich signature.
// http://www.ntcore.com/files/richsign.htm
//
#define RICH_VERSION_ID(id_version) (id_version >> 16)
#define RICH_VERSION_ID(id_version) (id_version >> 16)
#define RICH_VERSION_VERSION(id_version) (id_version & 0xFFFF)
typedef struct _RICH_VERSION_INFO {
DWORD id_version; //tool id and version (use RICH_VERSION_ID and RICH_VERSION_VERSION macros)
DWORD times; //number of times this tool was used
typedef struct _RICH_VERSION_INFO
{
DWORD id_version; // tool id and version (use RICH_VERSION_ID and
// RICH_VERSION_VERSION macros)
DWORD times; // number of times this tool was used
} RICH_VERSION_INFO, *PRICH_VERSION_INFO;
typedef struct _RICH_SIGNATURE {
DWORD dans;
DWORD key1;
DWORD key2;
DWORD key3;
RICH_VERSION_INFO versions[0];
typedef struct _RICH_SIGNATURE
{
DWORD dans;
DWORD key1;
DWORD key2;
DWORD key3;
RICH_VERSION_INFO versions[0];
} RICH_SIGNATURE, *PRICH_SIGNATURE;
#define RICH_DANS 0x536e6144 // "DanS"
#define RICH_RICH 0x68636952 // "Rich"
#define RICH_DANS 0x536e6144 // "DanS"
#define RICH_RICH 0x68636952 // "Rich"
#pragma pack(pop)
#endif
+22 -30
View File
@@ -3,17 +3,17 @@
#include <yara/pe.h>
#define MAX_PE_SECTIONS 96
#define MAX_PE_SECTIONS 96
#define IS_64BITS_PE(pe) \
(yr_le16toh(pe->header64->OptionalHeader.Magic) == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
#define IS_64BITS_PE(pe) \
(yr_le16toh(pe->header64->OptionalHeader.Magic) == \
IMAGE_NT_OPTIONAL_HDR64_MAGIC)
#define OptionalHeader(pe,field) \
(IS_64BITS_PE(pe) ? \
pe->header64->OptionalHeader.field : \
pe->header->OptionalHeader.field)
#define OptionalHeader(pe, field) \
(IS_64BITS_PE(pe) ? pe->header64->OptionalHeader.field \
: pe->header->OptionalHeader.field)
//
@@ -25,10 +25,10 @@
typedef struct _IMPORTED_DLL
{
char *name;
char* name;
struct _IMPORT_FUNCTION *functions;
struct _IMPORTED_DLL *next;
struct _IMPORT_FUNCTION* functions;
struct _IMPORTED_DLL* next;
} IMPORTED_DLL, *PIMPORTED_DLL;
@@ -43,11 +43,11 @@ typedef struct _IMPORTED_DLL
typedef struct _IMPORT_FUNCTION
{
char *name;
char* name;
uint8_t has_ordinal;
uint16_t ordinal;
struct _IMPORT_FUNCTION *next;
struct _IMPORT_FUNCTION* next;
} IMPORT_FUNCTION, *PIMPORT_FUNCTION;
@@ -57,7 +57,8 @@ typedef struct _PE
const uint8_t* data;
size_t data_size;
union {
union
{
PIMAGE_NT_HEADERS32 header;
PIMAGE_NT_HEADERS64 header64;
};
@@ -71,33 +72,24 @@ typedef struct _PE
} PE;
#define fits_in_pe(pe, pointer, size) \
((size_t) size <= pe->data_size && \
(uint8_t*) (pointer) >= pe->data && \
(uint8_t*) (pointer) <= pe->data + pe->data_size - size)
#define fits_in_pe(pe, pointer, size) \
((size_t) size <= pe->data_size && (uint8_t*) (pointer) >= pe->data && \
(uint8_t*) (pointer) <= pe->data + pe->data_size - size)
#define struct_fits_in_pe(pe, pointer, struct_type) \
fits_in_pe(pe, pointer, sizeof(struct_type))
fits_in_pe(pe, pointer, sizeof(struct_type))
PIMAGE_NT_HEADERS32 pe_get_header(
const uint8_t* data,
size_t data_size);
PIMAGE_NT_HEADERS32 pe_get_header(const uint8_t* data, size_t data_size);
PIMAGE_DATA_DIRECTORY pe_get_directory_entry(
PE* pe,
int entry);
PIMAGE_DATA_DIRECTORY pe_get_directory_entry(PE* pe, int entry);
int64_t pe_rva_to_offset(
PE* pe,
uint64_t rva);
int64_t pe_rva_to_offset(PE* pe, uint64_t rva);
char *ord_lookup(
char *dll,
uint16_t ord);
char* ord_lookup(char* dll, uint16_t ord);
#if HAVE_LIBCRYPTO
+6 -6
View File
@@ -32,19 +32,19 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <yara/types.h>
typedef struct _YR_PROC_ITERATOR_CTX {
const uint8_t* buffer;
size_t buffer_size;
typedef struct _YR_PROC_ITERATOR_CTX
{
const uint8_t* buffer;
size_t buffer_size;
YR_MEMORY_BLOCK current_block;
void* proc_info;
void* proc_info;
} YR_PROC_ITERATOR_CTX;
YR_API int yr_process_open_iterator(
int pid,
YR_MEMORY_BLOCK_ITERATOR* iterator);
YR_API int yr_process_close_iterator(
YR_MEMORY_BLOCK_ITERATOR* iterator);
YR_API int yr_process_close_iterator(YR_MEMORY_BLOCK_ITERATOR* iterator);
YR_API YR_MEMORY_BLOCK* yr_process_get_first_memory_block(
YR_MEMORY_BLOCK_ITERATOR* iterator);
+62 -102
View File
@@ -31,53 +31,51 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define YR_RE_H
#include <ctype.h>
#include <yara/utils.h>
#include <yara/types.h>
#include <yara/arena.h>
#include <yara/sizedstr.h>
#include <yara/types.h>
#include <yara/utils.h>
#define RE_NODE_LITERAL 1
#define RE_NODE_MASKED_LITERAL 2
#define RE_NODE_ANY 3
#define RE_NODE_CONCAT 4
#define RE_NODE_ALT 5
#define RE_NODE_RANGE 6
#define RE_NODE_STAR 7
#define RE_NODE_PLUS 8
#define RE_NODE_CLASS 9
#define RE_NODE_WORD_CHAR 10
#define RE_NODE_NON_WORD_CHAR 11
#define RE_NODE_SPACE 12
#define RE_NODE_NON_SPACE 13
#define RE_NODE_DIGIT 14
#define RE_NODE_NON_DIGIT 15
#define RE_NODE_EMPTY 16
#define RE_NODE_ANCHOR_START 17
#define RE_NODE_ANCHOR_END 18
#define RE_NODE_WORD_BOUNDARY 19
#define RE_NODE_NON_WORD_BOUNDARY 20
#define RE_NODE_RANGE_ANY 21
#define RE_NODE_LITERAL 1
#define RE_NODE_MASKED_LITERAL 2
#define RE_NODE_ANY 3
#define RE_NODE_CONCAT 4
#define RE_NODE_ALT 5
#define RE_NODE_RANGE 6
#define RE_NODE_STAR 7
#define RE_NODE_PLUS 8
#define RE_NODE_CLASS 9
#define RE_NODE_WORD_CHAR 10
#define RE_NODE_NON_WORD_CHAR 11
#define RE_NODE_SPACE 12
#define RE_NODE_NON_SPACE 13
#define RE_NODE_DIGIT 14
#define RE_NODE_NON_DIGIT 15
#define RE_NODE_EMPTY 16
#define RE_NODE_ANCHOR_START 17
#define RE_NODE_ANCHOR_END 18
#define RE_NODE_WORD_BOUNDARY 19
#define RE_NODE_NON_WORD_BOUNDARY 20
#define RE_NODE_RANGE_ANY 21
#define RE_OPCODE_ANY 0xA0
#define RE_OPCODE_LITERAL 0xA2
#define RE_OPCODE_MASKED_LITERAL 0xA4
#define RE_OPCODE_CLASS 0xA5
#define RE_OPCODE_WORD_CHAR 0xA7
#define RE_OPCODE_NON_WORD_CHAR 0xA8
#define RE_OPCODE_SPACE 0xA9
#define RE_OPCODE_NON_SPACE 0xAA
#define RE_OPCODE_DIGIT 0xAB
#define RE_OPCODE_NON_DIGIT 0xAC
#define RE_OPCODE_MATCH 0xAD
#define RE_OPCODE_ANY 0xA0
#define RE_OPCODE_LITERAL 0xA2
#define RE_OPCODE_MASKED_LITERAL 0xA4
#define RE_OPCODE_CLASS 0xA5
#define RE_OPCODE_WORD_CHAR 0xA7
#define RE_OPCODE_NON_WORD_CHAR 0xA8
#define RE_OPCODE_SPACE 0xA9
#define RE_OPCODE_NON_SPACE 0xAA
#define RE_OPCODE_DIGIT 0xAB
#define RE_OPCODE_NON_DIGIT 0xAC
#define RE_OPCODE_MATCH 0xAD
#define RE_OPCODE_MATCH_AT_END 0xB0
#define RE_OPCODE_MATCH_AT_START 0xB1
#define RE_OPCODE_WORD_BOUNDARY 0xB2
#define RE_OPCODE_NON_WORD_BOUNDARY 0xB3
#define RE_OPCODE_REPEAT_ANY_GREEDY 0xB4
#define RE_OPCODE_REPEAT_ANY_UNGREEDY 0xB5
#define RE_OPCODE_MATCH_AT_END 0xB0
#define RE_OPCODE_MATCH_AT_START 0xB1
#define RE_OPCODE_WORD_BOUNDARY 0xB2
#define RE_OPCODE_NON_WORD_BOUNDARY 0xB3
#define RE_OPCODE_REPEAT_ANY_GREEDY 0xB4
#define RE_OPCODE_REPEAT_ANY_UNGREEDY 0xB5
#define RE_OPCODE_SPLIT_A 0xC0
#define RE_OPCODE_SPLIT_B 0xC1
@@ -87,17 +85,15 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define RE_OPCODE_REPEAT_START_UNGREEDY 0xC5
#define RE_OPCODE_REPEAT_END_UNGREEDY 0xC6
#define RE_FLAGS_FAST_REGEXP 0x02
#define RE_FLAGS_BACKWARDS 0x04
#define RE_FLAGS_EXHAUSTIVE 0x08
#define RE_FLAGS_WIDE 0x10
#define RE_FLAGS_NO_CASE 0x20
#define RE_FLAGS_SCAN 0x40
#define RE_FLAGS_DOT_ALL 0x80
#define RE_FLAGS_GREEDY 0x400
#define RE_FLAGS_UNGREEDY 0x800
#define RE_FLAGS_FAST_REGEXP 0x02
#define RE_FLAGS_BACKWARDS 0x04
#define RE_FLAGS_EXHAUSTIVE 0x08
#define RE_FLAGS_WIDE 0x10
#define RE_FLAGS_NO_CASE 0x20
#define RE_FLAGS_SCAN 0x40
#define RE_FLAGS_DOT_ALL 0x80
#define RE_FLAGS_GREEDY 0x400
#define RE_FLAGS_UNGREEDY 0x800
typedef int RE_MATCH_CALLBACK_FUNC(
const uint8_t* match,
@@ -105,22 +101,15 @@ typedef int RE_MATCH_CALLBACK_FUNC(
int flags,
void* args);
int yr_re_ast_create(
RE_AST** re_ast);
int yr_re_ast_create(RE_AST** re_ast);
void yr_re_ast_destroy(
RE_AST* re_ast);
void yr_re_ast_destroy(RE_AST* re_ast);
void yr_re_ast_print(
RE_AST* re_ast);
void yr_re_ast_print(RE_AST* re_ast);
SIZED_STRING* yr_re_ast_extract_literal(
RE_AST* re_ast);
int yr_re_ast_contains_dot_star(
RE_AST* re_ast);
SIZED_STRING* yr_re_ast_extract_literal(RE_AST* re_ast);
int yr_re_ast_contains_dot_star(RE_AST* re_ast);
int yr_re_ast_split_at_chaining_point(
RE_AST* re_ast,
@@ -128,30 +117,15 @@ int yr_re_ast_split_at_chaining_point(
int32_t* min_gap,
int32_t* max_gap);
int yr_re_ast_emit_code(RE_AST* re_ast, YR_ARENA* arena, int backwards_code);
int yr_re_ast_emit_code(
RE_AST* re_ast,
YR_ARENA* arena,
int backwards_code);
RE_NODE* yr_re_node_create(int type);
void yr_re_node_destroy(RE_NODE* node);
RE_NODE* yr_re_node_create(
int type);
void yr_re_node_destroy(
RE_NODE* node);
void yr_re_node_append_child(
RE_NODE* node,
RE_NODE* child);
void yr_re_node_prepend_child(
RE_NODE* node,
RE_NODE* child);
void yr_re_node_append_child(RE_NODE* node, RE_NODE* child);
void yr_re_node_prepend_child(RE_NODE* node, RE_NODE* child);
int yr_re_exec(
YR_SCAN_CONTEXT* context,
@@ -164,7 +138,6 @@ int yr_re_exec(
void* callback_args,
int* matches);
int yr_re_fast_exec(
YR_SCAN_CONTEXT* context,
const uint8_t* code,
@@ -176,18 +149,9 @@ int yr_re_fast_exec(
void* callback_args,
int* matches);
int yr_re_parse(const char* re_string, RE_AST** re_ast, RE_ERROR* error);
int yr_re_parse(
const char* re_string,
RE_AST** re_ast,
RE_ERROR* error);
int yr_re_parse_hex(
const char* hex_string,
RE_AST** re_ast,
RE_ERROR* error);
int yr_re_parse_hex(const char* hex_string, RE_AST** re_ast, RE_ERROR* error);
int yr_re_compile(
const char* re_string,
@@ -196,10 +160,6 @@ int yr_re_compile(
YR_ARENA_REF* ref,
RE_ERROR* error);
int yr_re_match(
YR_SCAN_CONTEXT* context,
RE* re,
const char* target);
int yr_re_match(YR_SCAN_CONTEXT* context, RE* re, const char* target);
#endif
+20 -32
View File
@@ -1,4 +1,4 @@
/*
/*
Copyright (c) 2013. The YARA Authors. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -41,17 +41,15 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#undef YY_DECL
#undef LEX_ENV
#define yyparse re_yyparse
#define yylex re_yylex
#define yyerror re_yyerror
#define yyfatal re_yyfatal
#define yychar re_yychar
#define yydebug re_yydebug
#define yynerrs re_yynerrs
#define yyget_extra re_yyget_extra
#define yyget_lineno re_yyget_lineno
#define yyparse re_yyparse
#define yylex re_yylex
#define yyerror re_yyerror
#define yyfatal re_yyfatal
#define yychar re_yychar
#define yydebug re_yydebug
#define yynerrs re_yynerrs
#define yyget_extra re_yyget_extra
#define yyget_lineno re_yyget_lineno
#ifndef YY_TYPEDEF_YY_SCANNER_T
#define YY_TYPEDEF_YY_SCANNER_T
@@ -61,7 +59,6 @@ typedef void* yyscan_t;
#define YY_EXTRA_TYPE RE_AST*
#define YY_USE_CONST
typedef struct _RE_LEX_ENVIRONMENT
{
RE_CLASS re_class;
@@ -70,8 +67,7 @@ typedef struct _RE_LEX_ENVIRONMENT
} RE_LEX_ENVIRONMENT;
#define LEX_ENV ((RE_LEX_ENVIRONMENT*) lex_env)
#define LEX_ENV ((RE_LEX_ENVIRONMENT*) lex_env)
// The default behavior when a fatal error occurs in the parser is calling
// exit(YY_EXIT_FAILURE) for terminating the process. This is not acceptable
@@ -82,32 +78,24 @@ typedef struct _RE_LEX_ENVIRONMENT
#include <re_grammar.h>
#define YY_DECL int re_yylex \
(YYSTYPE * yylval_param , yyscan_t yyscanner, RE_LEX_ENVIRONMENT* lex_env)
#define YY_DECL \
int re_yylex( \
YYSTYPE* yylval_param, yyscan_t yyscanner, RE_LEX_ENVIRONMENT* lex_env)
YY_EXTRA_TYPE yyget_extra(
yyscan_t yyscanner);
YY_EXTRA_TYPE yyget_extra(yyscan_t yyscanner);
int yylex(
YYSTYPE* yylval_param,
yyscan_t yyscanner,
RE_LEX_ENVIRONMENT* lex_env);
int yyparse(
void *yyscanner,
RE_LEX_ENVIRONMENT *lex_env);
void yyerror(
yyscan_t yyscanner,
RE_LEX_ENVIRONMENT* lex_env,
const char *error_message);
const char* error_message);
void yyfatal(
yyscan_t yyscanner,
const char *error_message);
void yyfatal(yyscan_t yyscanner, const char* error_message);
int yr_parse_re_string(
const char* re_string,
RE_AST** re_ast,
RE_ERROR* error);
int yyparse(void* yyscanner, RE_LEX_ENVIRONMENT* lex_env);
int yr_parse_re_string(const char* re_string, RE_AST** re_ast, RE_ERROR* error);
+36 -76
View File
@@ -30,52 +30,44 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YR_RULES_H
#define YR_RULES_H
#include <yara/filemap.h>
#include <yara/types.h>
#include <yara/utils.h>
#include <yara/filemap.h>
#define CALLBACK_MSG_RULE_MATCHING 1
#define CALLBACK_MSG_RULE_NOT_MATCHING 2
#define CALLBACK_MSG_SCAN_FINISHED 3
#define CALLBACK_MSG_IMPORT_MODULE 4
#define CALLBACK_MSG_MODULE_IMPORTED 5
#define CALLBACK_MSG_RULE_MATCHING 1
#define CALLBACK_MSG_RULE_NOT_MATCHING 2
#define CALLBACK_MSG_SCAN_FINISHED 3
#define CALLBACK_MSG_IMPORT_MODULE 4
#define CALLBACK_MSG_MODULE_IMPORTED 5
#define CALLBACK_CONTINUE 0
#define CALLBACK_ABORT 1
#define CALLBACK_ERROR 2
#define yr_rule_tags_foreach(rule, tag_name) \
for (tag_name = rule->tags; \
tag_name != NULL && *tag_name != '\0'; \
tag_name += strlen(tag_name) + 1)
#define CALLBACK_CONTINUE 0
#define CALLBACK_ABORT 1
#define CALLBACK_ERROR 2
#define yr_rule_tags_foreach(rule, tag_name) \
for (tag_name = rule->tags; tag_name != NULL && *tag_name != '\0'; \
tag_name += strlen(tag_name) + 1)
#define yr_rule_metas_foreach(rule, meta) \
for (meta = rule->metas; \
meta != NULL; \
meta = META_IS_LAST_IN_RULE(meta) ? NULL : meta + 1)
for (meta = rule->metas; meta != NULL; \
meta = META_IS_LAST_IN_RULE(meta) ? NULL : meta + 1)
#define yr_rule_strings_foreach(rule, string) \
for (string = rule->strings; string != NULL; \
string = STRING_IS_LAST_IN_RULE(string) ? NULL : string + 1)
#define yr_rule_strings_foreach(rule, string) \
for (string = rule->strings; \
string != NULL; \
string = STRING_IS_LAST_IN_RULE(string) ? NULL : string + 1)
#define yr_string_matches_foreach(context, string, match) \
for (match = context->matches[string->idx].head; \
match != NULL; \
match = match->next) \
/* private matches are skipped */ \
if (match->is_private) { continue; } \
else /* user code block goes here */
#define yr_string_matches_foreach(context, string, match) \
for (match = context->matches[string->idx].head; match != NULL; \
match = match->next) \
/* private matches are skipped */ \
if (match->is_private) \
{ \
continue; \
} \
else /* user code block goes here */
#define yr_rules_foreach(rules, rule) \
for (rule = rules->rules_list_head; !RULE_IS_NULL(rule); rule++)
for (rule = rules->rules_list_head; !RULE_IS_NULL(rule); rule++)
YR_API int yr_rules_scan_mem_blocks(
YR_RULES* rules,
@@ -85,7 +77,6 @@ YR_API int yr_rules_scan_mem_blocks(
void* user_data,
int timeout);
YR_API int yr_rules_scan_mem(
YR_RULES* rules,
const uint8_t* buffer,
@@ -95,7 +86,6 @@ YR_API int yr_rules_scan_mem(
void* user_data,
int timeout);
YR_API int yr_rules_scan_file(
YR_RULES* rules,
const char* filename,
@@ -104,7 +94,6 @@ YR_API int yr_rules_scan_file(
void* user_data,
int timeout);
YR_API int yr_rules_scan_fd(
YR_RULES* rules,
YR_FILE_DESCRIPTOR fd,
@@ -113,7 +102,6 @@ YR_API int yr_rules_scan_fd(
void* user_data,
int timeout);
YR_API int yr_rules_scan_proc(
YR_RULES* rules,
int pid,
@@ -122,70 +110,42 @@ YR_API int yr_rules_scan_proc(
void* user_data,
int timeout);
YR_API int yr_rules_save(YR_RULES* rules, const char* filename);
YR_API int yr_rules_save(
YR_RULES* rules,
const char* filename);
YR_API int yr_rules_save_stream(YR_RULES* rules, YR_STREAM* stream);
YR_API int yr_rules_load(const char* filename, YR_RULES** rules);
YR_API int yr_rules_save_stream(
YR_RULES* rules,
YR_STREAM* stream);
YR_API int yr_rules_load(
const char* filename,
YR_RULES** rules);
YR_API int yr_rules_load_stream(
YR_STREAM* stream,
YR_RULES** rules);
YR_API int yr_rules_destroy(
YR_RULES* rules);
YR_API int yr_rules_load_stream(YR_STREAM* stream, YR_RULES** rules);
YR_API int yr_rules_destroy(YR_RULES* rules);
YR_API int yr_rules_define_integer_variable(
YR_RULES* rules,
const char* identifier,
int64_t value);
YR_API int yr_rules_define_boolean_variable(
YR_RULES* rules,
const char* identifier,
int value);
YR_API int yr_rules_define_float_variable(
YR_RULES* rules,
const char* identifier,
double value);
YR_API int yr_rules_define_string_variable(
YR_RULES* rules,
const char* identifier,
const char* value);
YR_API int yr_rules_get_stats(YR_RULES* rules, YR_RULES_STATS* stats);
YR_API int yr_rules_get_stats(
YR_RULES* rules,
YR_RULES_STATS *stats);
YR_API void yr_rule_disable(YR_RULE* rule);
YR_API void yr_rule_enable(YR_RULE* rule);
YR_API void yr_rule_disable(
YR_RULE* rule);
YR_API void yr_rule_enable(
YR_RULE* rule);
int yr_rules_from_arena(
YR_ARENA* arena,
YR_RULES** rules);
int yr_rules_from_arena(YR_ARENA* arena, YR_RULES** rules);
#endif
+5 -6
View File
@@ -35,12 +35,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Flags used with yr_scanner_set_flags and yr_rules_scan_xxx functions.
//
#define SCAN_FLAGS_FAST_MODE 1
#define SCAN_FLAGS_PROCESS_MEMORY 2
#define SCAN_FLAGS_NO_TRYCATCH 4
#define SCAN_FLAGS_REPORT_RULES_MATCHING 8
#define SCAN_FLAGS_REPORT_RULES_NOT_MATCHING 16
#define SCAN_FLAGS_FAST_MODE 1
#define SCAN_FLAGS_PROCESS_MEMORY 2
#define SCAN_FLAGS_NO_TRYCATCH 4
#define SCAN_FLAGS_REPORT_RULES_MATCHING 8
#define SCAN_FLAGS_REPORT_RULES_NOT_MATCHING 16
int yr_scan_verify_match(
YR_SCAN_CONTEXT* context,
+11 -50
View File
@@ -34,109 +34,70 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <yara/types.h>
#include <yara/utils.h>
typedef YR_SCAN_CONTEXT YR_SCANNER;
YR_API int yr_scanner_create(YR_RULES* rules, YR_SCANNER** scanner);
YR_API int yr_scanner_create(
YR_RULES* rules,
YR_SCANNER** scanner);
YR_API void yr_scanner_destroy(
YR_SCANNER* scanner);
YR_API void yr_scanner_destroy(YR_SCANNER* scanner);
YR_API void yr_scanner_set_callback(
YR_SCANNER* scanner,
YR_CALLBACK_FUNC callback,
void* user_data);
YR_API void yr_scanner_set_timeout(YR_SCANNER* scanner, int timeout);
YR_API void yr_scanner_set_timeout(
YR_SCANNER* scanner,
int timeout);
YR_API void yr_scanner_set_flags(
YR_SCANNER* scanner,
int flags);
YR_API void yr_scanner_set_flags(YR_SCANNER* scanner, int flags);
YR_API int yr_scanner_define_integer_variable(
YR_SCANNER* scanner,
const char* identifier,
int64_t value);
YR_API int yr_scanner_define_boolean_variable(
YR_SCANNER* scanner,
const char* identifier,
int value);
YR_API int yr_scanner_define_float_variable(
YR_SCANNER* scanner,
const char* identifier,
double value);
YR_API int yr_scanner_define_string_variable(
YR_SCANNER* scanner,
const char* identifier,
const char* value);
YR_API int yr_scanner_scan_mem_blocks(
YR_SCANNER* scanner,
YR_MEMORY_BLOCK_ITERATOR* iterator);
extern int (*_yr_scanner_scan_mem)(
YR_SCANNER* scanner,
const uint8_t* buffer,
size_t buffer_size);
YR_API int yr_scanner_scan_mem(
YR_SCANNER* scanner,
const uint8_t* buffer,
size_t buffer_size);
YR_API int yr_scanner_scan_file(YR_SCANNER* scanner, const char* filename);
YR_API int yr_scanner_scan_file(
YR_SCANNER* scanner,
const char* filename);
YR_API int yr_scanner_scan_fd(YR_SCANNER* scanner, YR_FILE_DESCRIPTOR fd);
YR_API int yr_scanner_scan_proc(YR_SCANNER* scanner, int pid);
YR_API int yr_scanner_scan_fd(
YR_SCANNER* scanner,
YR_FILE_DESCRIPTOR fd);
YR_API int yr_scanner_scan_proc(
YR_SCANNER* scanner,
int pid);
YR_API YR_RULE* yr_scanner_last_error_rule(
YR_SCANNER* scanner);
YR_API YR_STRING* yr_scanner_last_error_string(
YR_SCANNER* scanner);
YR_API YR_RULE* yr_scanner_last_error_rule(YR_SCANNER* scanner);
YR_API YR_STRING* yr_scanner_last_error_string(YR_SCANNER* scanner);
YR_API YR_RULE_PROFILING_INFO* yr_scanner_get_profiling_info(
YR_SCANNER* scanner);
YR_API void yr_scanner_reset_profiling_info(YR_SCANNER* scanner);
YR_API void yr_scanner_reset_profiling_info(
YR_SCANNER* scanner);
YR_API int yr_scanner_print_profiling_info(
YR_SCANNER* scanner);
YR_API int yr_scanner_print_profiling_info(YR_SCANNER* scanner);
#endif
+13 -43
View File
@@ -32,11 +32,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <stdbool.h>
#include <stddef.h>
#include <yara/integers.h>
#define SIZED_STRING_FLAGS_NO_CASE 1
#define SIZED_STRING_FLAGS_DOT_ALL 2
#define SIZED_STRING_FLAGS_NO_CASE 1
#define SIZED_STRING_FLAGS_DOT_ALL 2
#pragma pack(push)
#pragma pack(1)
@@ -57,55 +56,26 @@ typedef struct _SIZED_STRING
#pragma pack(pop)
int ss_compare(SIZED_STRING* s1, SIZED_STRING* s2);
int ss_compare(
SIZED_STRING* s1,
SIZED_STRING* s2);
int ss_icompare(SIZED_STRING* s1, SIZED_STRING* s2);
bool ss_contains(SIZED_STRING* s1, SIZED_STRING* s2);
int ss_icompare(
SIZED_STRING* s1,
SIZED_STRING* s2);
bool ss_icontains(SIZED_STRING* s1, SIZED_STRING* s2);
bool ss_startswith(SIZED_STRING* s1, SIZED_STRING* s2);
bool ss_contains(
SIZED_STRING* s1,
SIZED_STRING* s2);
bool ss_istartswith(SIZED_STRING* s1, SIZED_STRING* s2);
bool ss_endswith(SIZED_STRING* s1, SIZED_STRING* s2);
bool ss_icontains(
SIZED_STRING* s1,
SIZED_STRING* s2);
bool ss_iendswith(SIZED_STRING* s1, SIZED_STRING* s2);
SIZED_STRING* ss_dup(SIZED_STRING* s);
bool ss_startswith(
SIZED_STRING* s1,
SIZED_STRING* s2);
SIZED_STRING* ss_new(const char* s);
bool ss_istartswith(
SIZED_STRING* s1,
SIZED_STRING* s2);
bool ss_endswith(
SIZED_STRING* s1,
SIZED_STRING* s2);
bool ss_iendswith(
SIZED_STRING* s1,
SIZED_STRING* s2);
SIZED_STRING* ss_dup(
SIZED_STRING* s);
SIZED_STRING* ss_new(
const char* s);
SIZED_STRING* ss_convert_to_wide(
SIZED_STRING* s);
SIZED_STRING* ss_convert_to_wide(SIZED_STRING* s);
#endif
+15 -27
View File
@@ -34,39 +34,27 @@ typedef struct YR_STACK YR_STACK;
struct YR_STACK
{
// Pointer to a heap-allocated array containing the void* values put in
// in the stack. This array starts with a fixed size and it's grown as
// required when new items are pushed into the stack.
void* items;
// Pointer to a heap-allocated array containing the void* values put in
// in the stack. This array starts with a fixed size and it's grown as
// required when new items are pushed into the stack.
void* items;
// Current capacity (i.e: the number of items that fit into the array)
int capacity;
// Current capacity (i.e: the number of items that fit into the array)
int capacity;
// Size of each individual item in the stack.
int item_size;
// Size of each individual item in the stack.
int item_size;
// Index of the stack's top in the items array.
int top;
// Index of the stack's top in the items array.
int top;
};
int yr_stack_create(int initial_capacity, int item_size, YR_STACK** stack);
int yr_stack_create(
int initial_capacity,
int item_size,
YR_STACK** stack);
void yr_stack_destroy(YR_STACK* stack);
int yr_stack_push(YR_STACK* stack, void* item);
void yr_stack_destroy(
YR_STACK* stack);
int yr_stack_pop(YR_STACK* stack, void* item);
int yr_stack_push(
YR_STACK* stack,
void* item);
int yr_stack_pop(
YR_STACK* stack,
void* item);
#endif
#endif
+4 -6
View File
@@ -61,7 +61,8 @@ typedef struct _YR_STOPWATCH
typedef struct _YR_STOPWATCH
{
union {
union
{
struct timeval tv_start;
struct timespec ts_start;
};
@@ -70,14 +71,11 @@ typedef struct _YR_STOPWATCH
#endif
// yr_stopwatch_start starts measuring time.
void yr_stopwatch_start(
YR_STOPWATCH* stopwatch);
void yr_stopwatch_start(YR_STOPWATCH* stopwatch);
// yr_stopwatch_elapsed_ns returns the number of nanoseconds elapsed
// since the last call to yr_stopwatch_start.
uint64_t yr_stopwatch_elapsed_ns(
YR_STOPWATCH* stopwatch);
uint64_t yr_stopwatch_elapsed_ns(YR_STOPWATCH* stopwatch);
#endif
+1 -9
View File
@@ -38,14 +38,12 @@ typedef size_t (*YR_STREAM_READ_FUNC)(
size_t count,
void* user_data);
typedef size_t (*YR_STREAM_WRITE_FUNC)(
const void* ptr,
size_t size,
size_t count,
void* user_data);
typedef struct _YR_STREAM
{
void* user_data;
@@ -55,13 +53,7 @@ typedef struct _YR_STREAM
} YR_STREAM;
size_t yr_stream_read(
void* ptr,
size_t size,
size_t count,
YR_STREAM* stream);
size_t yr_stream_read(void* ptr, size_t size, size_t count, YR_STREAM* stream);
size_t yr_stream_write(
const void* ptr,
+10 -33
View File
@@ -33,10 +33,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <yara/integers.h>
#if defined(_WIN32)
#if !defined(PRIu64)
@@ -55,7 +53,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define PRId64 "I64d"
#endif
#if !defined (PRIi32)
#if !defined(PRIi32)
#define PRIi32 "I32i"
#endif
@@ -63,7 +61,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <inttypes.h>
#endif
// Cygwin already has these functions.
#if defined(_WIN32) && !defined(__CYGWIN__)
#if defined(_MSC_VER) && _MSC_VER < 1900
@@ -73,52 +70,32 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endif
#endif
#define strcasecmp _stricmp
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
#endif
uint64_t xtoi(
const char* hexstr);
uint64_t xtoi(const char* hexstr);
#if !HAVE_STRLCPY && !defined(strlcpy)
size_t strlcpy(
char *dst,
const char *src,
size_t size);
size_t strlcpy(char* dst, const char* src, size_t size);
#endif
#if !HAVE_STRLCAT && !defined(strlcat)
size_t strlcat(
char *dst,
const char *src,
size_t size);
size_t strlcat(char* dst, const char* src, size_t size);
#endif
#if !HAVE_MEMMEM && !defined(memmem)
void* memmem(
const void *haystack,
const void* haystack,
size_t haystack_size,
const void *needle,
const void* needle,
size_t needle_size);
#endif
int strnlen_w(const char* w_str);
int strnlen_w(
const char* w_str);
int strcmp_w(const char* w_str, const char* str);
int strcmp_w(
const char* w_str,
const char* str);
size_t strlcpy_w(
char* dst,
const char* w_src,
size_t n);
size_t strlcpy_w(char* dst, const char* w_src, size_t n);
#endif
-2
View File
@@ -30,8 +30,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YR_MUTEX_H
#define YR_MUTEX_H
#if defined(_WIN32) || defined(__CYGWIN__)
#include <windows.h>
+112 -192
View File
@@ -30,159 +30,127 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef YR_TYPES_H
#define YR_TYPES_H
#include <stdbool.h>
#include <yara/arena.h>
#include <yara/bitmask.h>
#include <yara/limits.h>
#include <yara/hash.h>
#include <yara/utils.h>
#include <yara/limits.h>
#include <yara/sizedstr.h>
#include <yara/stopwatch.h>
#include <yara/threading.h>
#include <yara/utils.h>
#include "notebook.h"
#define DECLARE_REFERENCE(type, name) \
union { \
type name; \
YR_ARENA_REF name##_; \
} YR_ALIGN(8)
union \
{ \
type name; \
YR_ARENA_REF name##_; \
} YR_ALIGN(8)
// Flags for YR_RULE
#define RULE_FLAGS_PRIVATE 0x01
#define RULE_FLAGS_GLOBAL 0x02
#define RULE_FLAGS_NULL 0x04
#define RULE_FLAGS_DISABLED 0x08
#define RULE_FLAGS_PRIVATE 0x01
#define RULE_FLAGS_GLOBAL 0x02
#define RULE_FLAGS_NULL 0x04
#define RULE_FLAGS_DISABLED 0x08
#define RULE_IS_PRIVATE(x) \
(((x)->flags) & RULE_FLAGS_PRIVATE)
#define RULE_IS_PRIVATE(x) (((x)->flags) & RULE_FLAGS_PRIVATE)
#define RULE_IS_GLOBAL(x) \
(((x)->flags) & RULE_FLAGS_GLOBAL)
#define RULE_IS_GLOBAL(x) (((x)->flags) & RULE_FLAGS_GLOBAL)
#define RULE_IS_NULL(x) \
(((x)->flags) & RULE_FLAGS_NULL)
#define RULE_IS_DISABLED(x) \
(((x)->flags) & RULE_FLAGS_DISABLED)
#define RULE_IS_NULL(x) (((x)->flags) & RULE_FLAGS_NULL)
#define RULE_IS_DISABLED(x) (((x)->flags) & RULE_FLAGS_DISABLED)
// Flags for YR_STRING
#define STRING_FLAGS_REFERENCED 0x01
#define STRING_FLAGS_HEXADECIMAL 0x02
#define STRING_FLAGS_NO_CASE 0x04
#define STRING_FLAGS_ASCII 0x08
#define STRING_FLAGS_WIDE 0x10
#define STRING_FLAGS_REGEXP 0x20
#define STRING_FLAGS_FAST_REGEXP 0x40
#define STRING_FLAGS_FULL_WORD 0x80
#define STRING_FLAGS_ANONYMOUS 0x100
#define STRING_FLAGS_SINGLE_MATCH 0x200
#define STRING_FLAGS_LITERAL 0x400
#define STRING_FLAGS_FITS_IN_ATOM 0x800
#define STRING_FLAGS_LAST_IN_RULE 0x1000
#define STRING_FLAGS_CHAIN_PART 0x2000
#define STRING_FLAGS_CHAIN_TAIL 0x4000
#define STRING_FLAGS_FIXED_OFFSET 0x8000
#define STRING_FLAGS_GREEDY_REGEXP 0x10000
#define STRING_FLAGS_DOT_ALL 0x20000
#define STRING_FLAGS_DISABLED 0x40000
#define STRING_FLAGS_XOR 0x80000
#define STRING_FLAGS_PRIVATE 0x100000
#define STRING_FLAGS_BASE64 0x200000
#define STRING_FLAGS_BASE64_WIDE 0x400000
#define STRING_FLAGS_REFERENCED 0x01
#define STRING_FLAGS_HEXADECIMAL 0x02
#define STRING_FLAGS_NO_CASE 0x04
#define STRING_FLAGS_ASCII 0x08
#define STRING_FLAGS_WIDE 0x10
#define STRING_FLAGS_REGEXP 0x20
#define STRING_FLAGS_FAST_REGEXP 0x40
#define STRING_FLAGS_FULL_WORD 0x80
#define STRING_FLAGS_ANONYMOUS 0x100
#define STRING_FLAGS_SINGLE_MATCH 0x200
#define STRING_FLAGS_LITERAL 0x400
#define STRING_FLAGS_FITS_IN_ATOM 0x800
#define STRING_FLAGS_LAST_IN_RULE 0x1000
#define STRING_FLAGS_CHAIN_PART 0x2000
#define STRING_FLAGS_CHAIN_TAIL 0x4000
#define STRING_FLAGS_FIXED_OFFSET 0x8000
#define STRING_FLAGS_GREEDY_REGEXP 0x10000
#define STRING_FLAGS_DOT_ALL 0x20000
#define STRING_FLAGS_DISABLED 0x40000
#define STRING_FLAGS_XOR 0x80000
#define STRING_FLAGS_PRIVATE 0x100000
#define STRING_FLAGS_BASE64 0x200000
#define STRING_FLAGS_BASE64_WIDE 0x400000
#define STRING_IS_HEX(x) \
(((x)->flags) & STRING_FLAGS_HEXADECIMAL)
#define STRING_IS_HEX(x) (((x)->flags) & STRING_FLAGS_HEXADECIMAL)
#define STRING_IS_NO_CASE(x) \
(((x)->flags) & STRING_FLAGS_NO_CASE)
#define STRING_IS_NO_CASE(x) (((x)->flags) & STRING_FLAGS_NO_CASE)
#define STRING_IS_DOT_ALL(x) \
(((x)->flags) & STRING_FLAGS_DOT_ALL)
#define STRING_IS_DOT_ALL(x) (((x)->flags) & STRING_FLAGS_DOT_ALL)
#define STRING_IS_ASCII(x) \
(((x)->flags) & STRING_FLAGS_ASCII)
#define STRING_IS_ASCII(x) (((x)->flags) & STRING_FLAGS_ASCII)
#define STRING_IS_WIDE(x) \
(((x)->flags) & STRING_FLAGS_WIDE)
#define STRING_IS_WIDE(x) (((x)->flags) & STRING_FLAGS_WIDE)
#define STRING_IS_REGEXP(x) \
(((x)->flags) & STRING_FLAGS_REGEXP)
#define STRING_IS_REGEXP(x) (((x)->flags) & STRING_FLAGS_REGEXP)
#define STRING_IS_GREEDY_REGEXP(x) \
(((x)->flags) & STRING_FLAGS_GREEDY_REGEXP)
#define STRING_IS_GREEDY_REGEXP(x) (((x)->flags) & STRING_FLAGS_GREEDY_REGEXP)
#define STRING_IS_FULL_WORD(x) \
(((x)->flags) & STRING_FLAGS_FULL_WORD)
#define STRING_IS_FULL_WORD(x) (((x)->flags) & STRING_FLAGS_FULL_WORD)
#define STRING_IS_ANONYMOUS(x) \
(((x)->flags) & STRING_FLAGS_ANONYMOUS)
#define STRING_IS_ANONYMOUS(x) (((x)->flags) & STRING_FLAGS_ANONYMOUS)
#define STRING_IS_REFERENCED(x) \
(((x)->flags) & STRING_FLAGS_REFERENCED)
#define STRING_IS_REFERENCED(x) (((x)->flags) & STRING_FLAGS_REFERENCED)
#define STRING_IS_SINGLE_MATCH(x) \
(((x)->flags) & STRING_FLAGS_SINGLE_MATCH)
#define STRING_IS_SINGLE_MATCH(x) (((x)->flags) & STRING_FLAGS_SINGLE_MATCH)
#define STRING_IS_FIXED_OFFSET(x) \
(((x)->flags) & STRING_FLAGS_FIXED_OFFSET)
#define STRING_IS_FIXED_OFFSET(x) (((x)->flags) & STRING_FLAGS_FIXED_OFFSET)
#define STRING_IS_LITERAL(x) \
(((x)->flags) & STRING_FLAGS_LITERAL)
#define STRING_IS_LITERAL(x) (((x)->flags) & STRING_FLAGS_LITERAL)
#define STRING_IS_FAST_REGEXP(x) \
(((x)->flags) & STRING_FLAGS_FAST_REGEXP)
#define STRING_IS_FAST_REGEXP(x) (((x)->flags) & STRING_FLAGS_FAST_REGEXP)
#define STRING_IS_CHAIN_PART(x) \
(((x)->flags) & STRING_FLAGS_CHAIN_PART)
#define STRING_IS_CHAIN_PART(x) (((x)->flags) & STRING_FLAGS_CHAIN_PART)
#define STRING_IS_CHAIN_TAIL(x) \
(((x)->flags) & STRING_FLAGS_CHAIN_TAIL)
#define STRING_IS_CHAIN_TAIL(x) (((x)->flags) & STRING_FLAGS_CHAIN_TAIL)
#define STRING_IS_LAST_IN_RULE(x) \
(((x)->flags) & STRING_FLAGS_LAST_IN_RULE)
#define STRING_IS_LAST_IN_RULE(x) (((x)->flags) & STRING_FLAGS_LAST_IN_RULE)
#define STRING_FITS_IN_ATOM(x) \
(((x)->flags) & STRING_FLAGS_FITS_IN_ATOM)
#define STRING_FITS_IN_ATOM(x) (((x)->flags) & STRING_FLAGS_FITS_IN_ATOM)
#define STRING_IS_DISABLED(x) \
(((x)->flags) & STRING_FLAGS_DISABLED)
#define STRING_IS_DISABLED(x) (((x)->flags) & STRING_FLAGS_DISABLED)
#define STRING_IS_XOR(x) \
(((x)->flags) & STRING_FLAGS_XOR)
#define STRING_IS_XOR(x) (((x)->flags) & STRING_FLAGS_XOR)
#define STRING_IS_BASE64(x) \
(((x)->flags) & STRING_FLAGS_BASE64)
#define STRING_IS_BASE64(x) (((x)->flags) & STRING_FLAGS_BASE64)
#define STRING_IS_BASE64_WIDE(x) \
(((x)->flags) & STRING_FLAGS_BASE64_WIDE)
#define STRING_IS_BASE64_WIDE(x) (((x)->flags) & STRING_FLAGS_BASE64_WIDE)
#define STRING_IS_PRIVATE(x) \
(((x)->flags) & STRING_FLAGS_PRIVATE)
#define STRING_IS_PRIVATE(x) (((x)->flags) & STRING_FLAGS_PRIVATE)
#define META_TYPE_INTEGER 1
#define META_TYPE_STRING 2
#define META_TYPE_BOOLEAN 3
#define META_TYPE_INTEGER 1
#define META_TYPE_STRING 2
#define META_TYPE_BOOLEAN 3
#define META_FLAGS_LAST_IN_RULE 1
#define META_IS_LAST_IN_RULE(x) (((x)->flags) & META_FLAGS_LAST_IN_RULE)
#define META_FLAGS_LAST_IN_RULE 1
#define META_IS_LAST_IN_RULE(x) \
(((x)->flags) & META_FLAGS_LAST_IN_RULE)
#define EXTERNAL_VARIABLE_TYPE_NULL 0
#define EXTERNAL_VARIABLE_TYPE_FLOAT 1
#define EXTERNAL_VARIABLE_TYPE_INTEGER 2
#define EXTERNAL_VARIABLE_TYPE_BOOLEAN 3
#define EXTERNAL_VARIABLE_TYPE_STRING 4
#define EXTERNAL_VARIABLE_TYPE_MALLOC_STRING 5
#define EXTERNAL_VARIABLE_TYPE_NULL 0
#define EXTERNAL_VARIABLE_TYPE_FLOAT 1
#define EXTERNAL_VARIABLE_TYPE_INTEGER 2
#define EXTERNAL_VARIABLE_TYPE_BOOLEAN 3
#define EXTERNAL_VARIABLE_TYPE_STRING 4
#define EXTERNAL_VARIABLE_TYPE_MALLOC_STRING 5
#define EXTERNAL_VARIABLE_IS_NULL(x) \
((x) != NULL ? (x)->type == EXTERNAL_VARIABLE_TYPE_NULL : true)
((x) != NULL ? (x)->type == EXTERNAL_VARIABLE_TYPE_NULL : true)
typedef struct RE RE;
typedef struct RE_AST RE_AST;
@@ -236,7 +204,7 @@ typedef struct YR_MODIFIER YR_MODIFIER;
typedef struct YR_ITERATOR YR_ITERATOR;
typedef uint32_t YR_AC_TRANSITION;
typedef uint32_t YR_AC_TRANSITION;
#pragma pack(push)
#pragma pack(8)
@@ -255,7 +223,6 @@ struct YR_NAMESPACE
YR_ALIGN(8) uint32_t idx;
};
struct YR_META
{
DECLARE_REFERENCE(const char*, identifier);
@@ -266,7 +233,6 @@ struct YR_META
int32_t flags;
};
struct YR_STRING
{
// Flags, see STRING_FLAGS_XXX macros defined above.
@@ -318,7 +284,6 @@ struct YR_STRING
DECLARE_REFERENCE(const char*, identifier);
};
struct YR_RULE
{
int32_t flags;
@@ -333,7 +298,6 @@ struct YR_RULE
DECLARE_REFERENCE(YR_NAMESPACE*, ns);
};
struct YR_SUMMARY
{
uint32_t num_rules;
@@ -341,12 +305,12 @@ struct YR_SUMMARY
uint32_t num_namespaces;
};
struct YR_EXTERNAL_VARIABLE
{
int32_t type;
YR_ALIGN(8) union {
YR_ALIGN(8) union
{
int64_t i;
double f;
char* s;
@@ -355,7 +319,6 @@ struct YR_EXTERNAL_VARIABLE
DECLARE_REFERENCE(const char*, identifier);
};
struct YR_AC_MATCH
{
DECLARE_REFERENCE(YR_STRING*, string);
@@ -366,11 +329,11 @@ struct YR_AC_MATCH
// When the Aho-Corasick automaton reaches some state that has associated
// matches, the current position in the input buffer is a few bytes past
// the point where the match actually occurs, for example, when looking for
// string "bar" in "foobarbaz", when the automaton reaches the state associated
// to the ending "r" in "bar, which is the one that has a match, the current
// position in the input is 6 (the "b" after the "r"), but the match is at
// position 3. The backtrack field indicates how many bytes the scanner has
// to go back to find the point where the match actually start.
// string "bar" in "foobarbaz", when the automaton reaches the state
// associated to the ending "r" in "bar, which is the one that has a match,
// the current position in the input is 6 (the "b" after the "r"), but the
// match is at position 3. The backtrack field indicates how many bytes the
// scanner has to go back to find the point where the match actually start.
//
// YR_ALIGN(8) forces the backtrack field to be treated as a 8-bytes field
// and therefore the struct's size is 40 bytes. This is necessary only for
@@ -380,7 +343,6 @@ struct YR_AC_MATCH
#pragma pack(pop)
//
// Structs defined below are never stored in the compiled rules file
//
@@ -389,13 +351,15 @@ struct RE_NODE
{
int type;
union {
union
{
int value;
int count;
int start;
};
union {
union
{
int mask;
int end;
};
@@ -413,26 +377,22 @@ struct RE_NODE
YR_ARENA_REF backward_code_ref;
};
struct RE_CLASS
{
uint8_t negated;
uint8_t bitmap[32];
};
struct RE_AST
{
uint32_t flags;
RE_NODE* root_node;
};
// Disable warning due to zero length array in Microsoft's compiler
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4200)
#pragma warning(disable : 4200)
#endif
struct RE
@@ -445,18 +405,16 @@ struct RE
#pragma warning(pop)
#endif
struct RE_ERROR
{
char message[384];
};
struct RE_FIBER
{
const uint8_t* ip; // instruction pointer
int32_t sp; // stack pointer
int32_t rc; // repeat counter
const uint8_t* ip; // instruction pointer
int32_t sp; // stack pointer
int32_t rc; // repeat counter
RE_FIBER* prev;
RE_FIBER* next;
@@ -464,30 +422,26 @@ struct RE_FIBER
uint16_t stack[RE_MAX_STACK];
};
struct RE_FIBER_LIST
{
RE_FIBER* head;
RE_FIBER* tail;
};
struct RE_FIBER_POOL
{
int fiber_count;
RE_FIBER_LIST fibers;
};
struct YR_MODIFIER
{
int32_t flags;
uint8_t xor_min;
uint8_t xor_max;
SIZED_STRING *alphabet;
SIZED_STRING* alphabet;
};
struct YR_MATCHES
{
YR_MATCH* head;
@@ -496,12 +450,11 @@ struct YR_MATCHES
int32_t count;
};
struct YR_MATCH
{
int64_t base; // Base address for the match
int64_t offset; // Offset relative to base for the match
int32_t match_length; // Match length
int64_t base; // Base address for the match
int64_t offset; // Offset relative to base for the match
int32_t match_length; // Match length
int32_t data_length;
// Pointer to a buffer containing a portion of the matched data. The size of
@@ -520,7 +473,6 @@ struct YR_MATCH
bool is_private;
};
struct YR_AC_STATE
{
YR_AC_STATE* failure;
@@ -537,7 +489,6 @@ struct YR_AC_STATE
uint32_t t_table_slot;
};
struct YR_AC_MATCH_LIST_ENTRY
{
uint16_t backtrack;
@@ -550,7 +501,6 @@ struct YR_AC_MATCH_LIST_ENTRY
YR_AC_MATCH_LIST_ENTRY* next;
};
struct YR_AC_AUTOMATON
{
// Arena used by this automaton to store the transition and match tables.
@@ -572,7 +522,6 @@ struct YR_AC_AUTOMATON
YR_AC_STATE* root;
};
struct YR_RULES
{
YR_ARENA* arena;
@@ -597,7 +546,6 @@ struct YR_RULES
uint32_t num_namespaces;
};
struct YR_RULES_STATS
{
// Total number of rules
@@ -629,7 +577,6 @@ struct YR_RULES_STATS
uint32_t ac_tables_size;
};
//
// YR_PROFILING_INFO contains profiling information for a rule.
//
@@ -649,7 +596,6 @@ struct YR_PROFILING_INFO
uint64_t exec_time;
};
//
// YR_RULE_PROFILING_INFO is the structure returned by
// yr_scanner_get_profiling_info
@@ -660,15 +606,12 @@ struct YR_RULE_PROFILING_INFO
uint64_t cost;
};
typedef const uint8_t* (*YR_MEMORY_BLOCK_FETCH_DATA_FUNC)(
YR_MEMORY_BLOCK* self);
typedef YR_MEMORY_BLOCK* (*YR_MEMORY_BLOCK_ITERATOR_FUNC)(
YR_MEMORY_BLOCK_ITERATOR* self);
struct YR_MEMORY_BLOCK
{
size_t size;
@@ -679,23 +622,20 @@ struct YR_MEMORY_BLOCK
YR_MEMORY_BLOCK_FETCH_DATA_FUNC fetch_data;
};
struct YR_MEMORY_BLOCK_ITERATOR
{
void* context;
YR_MEMORY_BLOCK_ITERATOR_FUNC first;
YR_MEMORY_BLOCK_ITERATOR_FUNC next;
YR_MEMORY_BLOCK_ITERATOR_FUNC first;
YR_MEMORY_BLOCK_ITERATOR_FUNC next;
};
typedef int (*YR_CALLBACK_FUNC)(
YR_SCAN_CONTEXT* context,
int message,
void* message_data,
void* user_data);
struct YR_SCAN_CONTEXT
{
// File size of the file being scanned.
@@ -739,7 +679,7 @@ struct YR_SCAN_CONTEXT
// Notebook used for storing YR_MATCH structures associated to the matches
// found.
YR_NOTEBOOK * matches_notebook;
YR_NOTEBOOK* matches_notebook;
// Stopwatch used for measuring the time elapsed during the scan.
YR_STOPWATCH stopwatch;
@@ -772,7 +712,6 @@ struct YR_SCAN_CONTEXT
YR_PROFILING_INFO* profiling_info;
};
union YR_VALUE
{
int64_t i;
@@ -787,19 +726,17 @@ union YR_VALUE
struct YR_VALUE_STACK
{
int32_t sp;
int32_t capacity;
int32_t sp;
int32_t capacity;
YR_VALUE* items;
};
#define OBJECT_COMMON_FIELDS \
int canary; \
int8_t type; \
const char* identifier; \
YR_OBJECT* parent; \
void* data;
int canary; \
int8_t type; \
const char* identifier; \
YR_OBJECT* parent; \
void* data;
struct YR_OBJECT
{
@@ -807,14 +744,12 @@ struct YR_OBJECT
YR_VALUE value;
};
struct YR_OBJECT_STRUCTURE
{
OBJECT_COMMON_FIELDS
YR_STRUCTURE_MEMBER* members;
};
struct YR_OBJECT_ARRAY
{
OBJECT_COMMON_FIELDS
@@ -822,7 +757,6 @@ struct YR_OBJECT_ARRAY
YR_ARRAY_ITEMS* items;
};
struct YR_OBJECT_DICTIONARY
{
OBJECT_COMMON_FIELDS
@@ -830,13 +764,11 @@ struct YR_OBJECT_DICTIONARY
YR_DICTIONARY_ITEMS* items;
};
typedef int (*YR_MODULE_FUNC)(
YR_VALUE* args,
YR_SCAN_CONTEXT* context,
YR_OBJECT_FUNCTION* function_obj);
struct YR_OBJECT_FUNCTION
{
OBJECT_COMMON_FIELDS
@@ -849,20 +781,17 @@ struct YR_OBJECT_FUNCTION
} prototypes[YR_MAX_OVERLOADED_FUNCTIONS];
};
#define object_as_structure(obj) ((YR_OBJECT_STRUCTURE*) (obj))
#define object_as_array(obj) ((YR_OBJECT_ARRAY*) (obj))
#define object_as_dictionary(obj) ((YR_OBJECT_DICTIONARY*) (obj))
#define object_as_function(obj) ((YR_OBJECT_FUNCTION*) (obj))
struct YR_STRUCTURE_MEMBER
{
YR_OBJECT* object;
YR_STRUCTURE_MEMBER* next;
};
struct YR_ARRAY_ITEMS
{
// Capacity is the size of the objects array.
@@ -875,20 +804,18 @@ struct YR_ARRAY_ITEMS
YR_OBJECT* objects[1];
};
struct YR_DICTIONARY_ITEMS
{
int used;
int free;
struct {
struct
{
SIZED_STRING* key;
YR_OBJECT* obj;
} objects[1];
};
// Iterators are used in loops of the form:
//
// for <any|all|number> <identifier> in <iterator> : ( <expression> )
@@ -921,16 +848,13 @@ struct YR_DICTIONARY_ITEMS
// | . . . |
//
// We can't use the YR_UNDEFINED value in the stack as an indicator of the end
// of the iterator, because it's legitimate for an iterator to return YR_UNDEFINED
// items in the middle of the iteration.
// of the iterator, because it's legitimate for an iterator to return
// YR_UNDEFINED items in the middle of the iteration.
//
// The "next" function should return ERROR_SUCCESS if everything went fine or
// an error code in case of error.
typedef int (*YR_ITERATOR_NEXT_FUNC)(
YR_ITERATOR* self,
YR_VALUE_STACK* stack);
typedef int (*YR_ITERATOR_NEXT_FUNC)(YR_ITERATOR* self, YR_VALUE_STACK* stack);
struct YR_ARRAY_ITERATOR
{
@@ -938,21 +862,18 @@ struct YR_ARRAY_ITERATOR
int index;
};
struct YR_DICT_ITERATOR
{
YR_OBJECT* dict;
int index;
};
struct YR_INT_RANGE_ITERATOR
{
int64_t next;
int64_t last;
};
struct YR_INT_ENUM_ITERATOR
{
int next;
@@ -960,12 +881,12 @@ struct YR_INT_ENUM_ITERATOR
int64_t items[1];
};
struct YR_ITERATOR
{
YR_ITERATOR_NEXT_FUNC next;
union {
union
{
struct YR_ARRAY_ITERATOR array_it;
struct YR_DICT_ITERATOR dict_it;
struct YR_INT_RANGE_ITERATOR int_range_it;
@@ -973,5 +894,4 @@ struct YR_ITERATOR
};
};
#endif
+54 -48
View File
@@ -27,7 +27,6 @@ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef YR_UTILS_H
#define YR_UTILS_H
@@ -42,9 +41,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <stdbool.h>
#else
#ifndef __cplusplus
#define bool int
#define true 1
#define false 0
#define bool int
#define true 1
#define false 0
#endif /* __cplusplus */
#endif
@@ -54,38 +53,36 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define EXTERNC
#endif
#if defined(_WIN32) || defined(__CYGWIN__)
#ifdef YR_BUILDING_DLL
#ifdef __GNUC__
#define YR_API EXTERNC __attribute__((dllexport))
#define YR_DEPRECATED_API EXTERNC __attribute__((deprecated))
#else
#define YR_API EXTERNC __declspec(dllexport)
#define YR_DEPRECATED_API EXTERNC __declspec(deprecated)
#endif
#elif defined(YR_IMPORTING_DLL)
#ifdef __GNUC__
#define YR_API EXTERNC __attribute__((dllimport))
#define YR_DEPRECATED_API EXTERNC __attribute__((deprecated))
#else
#define YR_API EXTERNC __declspec(dllimport)
#define YR_DEPRECATED_API EXTERNC __declspec(deprecated)
#endif
#else
#define YR_API EXTERNC
#define YR_DEPRECATED_API EXTERNC
#endif
#ifdef YR_BUILDING_DLL
#ifdef __GNUC__
#define YR_API EXTERNC __attribute__((dllexport))
#define YR_DEPRECATED_API EXTERNC __attribute__((deprecated))
#else
#if __GNUC__ >= 4
#define YR_API EXTERNC __attribute__((visibility ("default")))
#define YR_DEPRECATED_API YR_API __attribute__((deprecated))
#else
#define YR_API EXTERNC
#define YR_DEPRECATED_API EXTERNC
#endif
#define YR_API EXTERNC __declspec(dllexport)
#define YR_DEPRECATED_API EXTERNC __declspec(deprecated)
#endif
#elif defined(YR_IMPORTING_DLL)
#ifdef __GNUC__
#define YR_API EXTERNC __attribute__((dllimport))
#define YR_DEPRECATED_API EXTERNC __attribute__((deprecated))
#else
#define YR_API EXTERNC __declspec(dllimport)
#define YR_DEPRECATED_API EXTERNC __declspec(deprecated)
#endif
#else
#define YR_API EXTERNC
#define YR_DEPRECATED_API EXTERNC
#endif
#else
#if __GNUC__ >= 4
#define YR_API EXTERNC __attribute__((visibility("default")))
#define YR_DEPRECATED_API YR_API __attribute__((deprecated))
#else
#define YR_API EXTERNC
#define YR_DEPRECATED_API EXTERNC
#endif
#endif
#if defined(__GNUC__)
#define YR_ALIGN(n) __attribute__((aligned(n)))
@@ -104,21 +101,28 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define yr_min(x, y) (((x) < (y)) ? (x) : (y))
#define yr_max(x, y) (((x) > (y)) ? (x) : (y))
#define yr_swap(x, y, T) do { T temp = x; x = y; y = temp; } while (0)
#define yr_swap(x, y, T) \
do \
{ \
T temp = x; \
x = y; \
y = temp; \
} while (0)
#ifdef NDEBUG
#define assertf(expr, msg, ...) ((void)0)
#define assertf(expr, msg, ...) ((void) 0)
#else
#include <stdlib.h>
#define assertf(expr, msg, ...) \
if(!(expr)) { \
fprintf(stderr, "%s:%d: " msg "\n", __FILE__, __LINE__, ##__VA_ARGS__); \
abort(); \
}
#define assertf(expr, msg, ...) \
if (!(expr)) \
{ \
fprintf(stderr, "%s:%d: " msg "\n", __FILE__, __LINE__, ##__VA_ARGS__); \
abort(); \
}
#endif
@@ -127,17 +131,19 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ensure compatibility with the CHAR_BIT constant used in these definitions.
#define YR_BITARRAY_SET(uchar_array_base, bitnum) \
(((uchar_array_base)[(bitnum)/CHAR_BIT]) = \
((uchar_array_base)[(bitnum)/CHAR_BIT] | (1 << ((bitnum) % CHAR_BIT))))
(((uchar_array_base)[(bitnum) / CHAR_BIT]) = \
((uchar_array_base)[(bitnum) / CHAR_BIT] | \
(1 << ((bitnum) % CHAR_BIT))))
#define YR_BITARRAY_UNSET(uchar_array_base, bitnum) \
(((uchar_array_base)[(bitnum)/CHAR_BIT]) = \
((uchar_array_base)[(bitnum)/CHAR_BIT] & (~(1 << ((bitnum) % CHAR_BIT)))))
(((uchar_array_base)[(bitnum) / CHAR_BIT]) = \
((uchar_array_base)[(bitnum) / CHAR_BIT] & \
(~(1 << ((bitnum) % CHAR_BIT)))))
#define YR_BITARRAY_TEST(uchar_array_base, bitnum) \
(((uchar_array_base)[(bitnum)/CHAR_BIT] & (1 << ((bitnum) % CHAR_BIT))) != 0)
#define YR_BITARRAY_TEST(uchar_array_base, bitnum) \
(((uchar_array_base)[(bitnum) / CHAR_BIT] & (1 << ((bitnum) % CHAR_BIT))) != \
0)
#define YR_BITARRAY_NCHARS(bitnum) \
(((bitnum)+(CHAR_BIT-1))/CHAR_BIT)
#define YR_BITARRAY_NCHARS(bitnum) (((bitnum) + (CHAR_BIT - 1)) / CHAR_BIT)
#endif
+64 -87
View File
@@ -31,15 +31,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <jemalloc/jemalloc.h>
#endif
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <yara/globals.h>
#include <stdio.h>
#include <string.h>
#include <yara/error.h>
#include <yara/re.h>
#include <yara/modules.h>
#include <yara/globals.h>
#include <yara/mem.h>
#include <yara/modules.h>
#include <yara/re.h>
#include <yara/threading.h>
#include "crypto.h"
@@ -59,15 +58,14 @@ static struct yr_config_var
{
union
{
size_t sz;
size_t sz;
uint32_t ui32;
uint64_t ui64;
char* str;
char *str;
};
} yr_cfgs[YR_CONFIG_LAST];
// Global variables. See globals.h for their descriptions.
uint8_t yr_lowercase[256];
@@ -89,18 +87,12 @@ uint64_t yr_debug_verbosity = YR_DEBUG_VERBOSITY;
static YR_MUTEX *openssl_locks;
static void _thread_id(CRYPTO_THREADID *id)
{
CRYPTO_THREADID_set_numeric(id, (unsigned long) yr_current_thread_id());
}
static void _locking_function(
int mode,
int n,
const char *file,
int line)
static void _locking_function(int mode, int n, const char *file, int line)
{
if (mode & CRYPTO_LOCK)
yr_mutex_lock(&openssl_locks[n]);
@@ -110,21 +102,16 @@ static void _locking_function(
#endif
//
// yr_initialize
//
////////////////////////////////////////////////////////////////////////////////
// Should be called by main thread before using any other
// function from libyara.
//
YR_API int yr_initialize(void)
{
uint32_t def_stack_size = DEFAULT_STACK_SIZE;
uint32_t def_max_strings_per_rule = DEFAULT_MAX_STRINGS_PER_RULE;
uint32_t def_max_match_data = DEFAULT_MAX_MATCH_DATA;
int i;
init_count++;
if (init_count > 1)
@@ -134,7 +121,7 @@ YR_API int yr_initialize(void)
// canaries.
srand((unsigned) time(NULL));
for (i = 0; i < 256; i++)
for (int i = 0; i < 256; i++)
{
if (i >= 'a' && i <= 'z')
yr_altercase[i] = i - 32;
@@ -150,56 +137,54 @@ YR_API int yr_initialize(void)
FAIL_ON_ERROR(yr_thread_storage_create(&yr_yyfatal_trampoline_tls));
FAIL_ON_ERROR(yr_thread_storage_create(&yr_trycatch_trampoline_tls));
#if defined HAVE_LIBCRYPTO && OPENSSL_VERSION_NUMBER < 0x10100000L
#if defined HAVE_LIBCRYPTO && OPENSSL_VERSION_NUMBER < 0x10100000L
openssl_locks = (YR_MUTEX*) OPENSSL_malloc(
openssl_locks = (YR_MUTEX *) OPENSSL_malloc(
CRYPTO_num_locks() * sizeof(YR_MUTEX));
for (i = 0; i < CRYPTO_num_locks(); i++)
for (int i = 0; i < CRYPTO_num_locks(); i++)
yr_mutex_create(&openssl_locks[i]);
CRYPTO_THREADID_set_callback(_thread_id);
CRYPTO_set_locking_callback(_locking_function);
#elif defined(HAVE_WINCRYPT_H)
#elif defined(HAVE_WINCRYPT_H)
if (!CryptAcquireContext(&yr_cryptprov, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
if (!CryptAcquireContext(
&yr_cryptprov, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
{
return ERROR_INTERNAL_FATAL_ERROR;
}
#elif defined(HAVE_COMMON_CRYPTO)
#elif defined(HAVE_COMMON_CRYPTO)
...
#endif
#endif
FAIL_ON_ERROR(yr_modules_initialize());
// Initialize default configuration options
FAIL_ON_ERROR(yr_set_configuration(
YR_CONFIG_STACK_SIZE, &def_stack_size));
FAIL_ON_ERROR(yr_set_configuration(YR_CONFIG_STACK_SIZE, &def_stack_size));
FAIL_ON_ERROR(yr_set_configuration(
YR_CONFIG_MAX_STRINGS_PER_RULE, &def_max_strings_per_rule));
FAIL_ON_ERROR(yr_set_configuration(
YR_CONFIG_MAX_MATCH_DATA, &def_max_match_data));
FAIL_ON_ERROR(
yr_set_configuration(YR_CONFIG_MAX_MATCH_DATA, &def_max_match_data));
return ERROR_SUCCESS;
}
//
// yr_finalize
//
////////////////////////////////////////////////////////////////////////////////
// Should be called by main thread before exiting.
//
YR_API int yr_finalize(void)
{
#if defined HAVE_LIBCRYPTO && OPENSSL_VERSION_NUMBER < 0x10100000L
#if defined HAVE_LIBCRYPTO && OPENSSL_VERSION_NUMBER < 0x10100000L
int i;
#endif
#endif
// yr_finalize shouldn't be called without calling yr_initialize first
@@ -211,96 +196,88 @@ YR_API int yr_finalize(void)
if (init_count > 0)
return ERROR_SUCCESS;
#if defined HAVE_LIBCRYPTO && OPENSSL_VERSION_NUMBER < 0x10100000L
#if defined HAVE_LIBCRYPTO && OPENSSL_VERSION_NUMBER < 0x10100000L
for (i = 0; i < CRYPTO_num_locks(); i ++)
yr_mutex_destroy(&openssl_locks[i]);
for (i = 0; i < CRYPTO_num_locks(); i++) yr_mutex_destroy(&openssl_locks[i]);
OPENSSL_free(openssl_locks);
CRYPTO_THREADID_set_callback(NULL);
CRYPTO_set_locking_callback(NULL);
#elif defined(HAVE_WINCRYPT_H)
#elif defined(HAVE_WINCRYPT_H)
CryptReleaseContext(yr_cryptprov, 0);
#endif
#endif
FAIL_ON_ERROR(yr_thread_storage_destroy(&yr_yyfatal_trampoline_tls));
FAIL_ON_ERROR(yr_thread_storage_destroy(&yr_trycatch_trampoline_tls));
FAIL_ON_ERROR(yr_modules_finalize());
FAIL_ON_ERROR(yr_heap_free());
#if defined(JEMALLOC)
#if defined(JEMALLOC)
malloc_stats_print(NULL, NULL, NULL);
mallctl("prof.dump", NULL, NULL, NULL, 0);
#endif
#endif
return ERROR_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Sets a configuration option.
//
// yr_set_configuration
//
// Sets a configuration option. This function receives a configuration name,
// as defined by the YR_CONFIG_NAME enum, and a pointer to the value being
// set. The type of the value depends on the configuration name.
// This function receives a configuration name, as defined by the YR_CONFIG_NAME
// enum, and a pointer to the value being set. The type of the value depends on
// the configuration name.
//
// Args:
// YR_CONFIG_NAME name - Any of the values defined by the YR_CONFIG_NAME
// enum. Possible values are:
// name: Any of the values defined by the YR_CONFIG_NAME enum. Possible values
// are:
// YR_CONFIG_STACK_SIZE data type: uint32_t
// YR_CONFIG_MAX_STRINGS_PER_RULE data type: uint32_t
// YR_CONFIG_MAX_MATCH_DATA data type: uint32_t
//
// YR_CONFIG_STACK_SIZE data type: uint32_t
// YR_CONFIG_MAX_STRINGS_PER_RULE data type: uint32_t
// YR_CONFIG_MAX_MATCH_DATA data type: uint32_t
//
// void *src - Pointer to the value being set for the option.
// src: Pointer to the value being set for the option.
//
// Returns:
// An error code.
YR_API int yr_set_configuration(
YR_CONFIG_NAME name,
void *src)
// ERROR_SUCCESS
// ERROR_INTERNAL_FATAL_ERROR
//
YR_API int yr_set_configuration(YR_CONFIG_NAME name, void *src)
{
if (src == NULL)
return ERROR_INTERNAL_FATAL_ERROR;
switch (name)
{ // lump all the cases using same types together in one cascade
case YR_CONFIG_STACK_SIZE:
case YR_CONFIG_MAX_STRINGS_PER_RULE:
case YR_CONFIG_MAX_MATCH_DATA:
yr_cfgs[name].ui32 = *(uint32_t*) src;
break;
{ // lump all the cases using same types together in one cascade
case YR_CONFIG_STACK_SIZE:
case YR_CONFIG_MAX_STRINGS_PER_RULE:
case YR_CONFIG_MAX_MATCH_DATA:
yr_cfgs[name].ui32 = *(uint32_t *) src;
break;
default:
return ERROR_INTERNAL_FATAL_ERROR;
default:
return ERROR_INTERNAL_FATAL_ERROR;
}
return ERROR_SUCCESS;
}
YR_API int yr_get_configuration(
YR_CONFIG_NAME name,
void *dest)
YR_API int yr_get_configuration(YR_CONFIG_NAME name, void *dest)
{
if (dest == NULL)
return ERROR_INTERNAL_FATAL_ERROR;
switch (name)
{ // lump all the cases using same types together in one cascade
case YR_CONFIG_STACK_SIZE:
case YR_CONFIG_MAX_STRINGS_PER_RULE:
case YR_CONFIG_MAX_MATCH_DATA:
*(uint32_t*) dest = yr_cfgs[name].ui32;
break;
{ // lump all the cases using same types together in one cascade
case YR_CONFIG_STACK_SIZE:
case YR_CONFIG_MAX_STRINGS_PER_RULE:
case YR_CONFIG_MAX_MATCH_DATA:
*(uint32_t *) dest = yr_cfgs[name].ui32;
break;
default:
return ERROR_INTERNAL_FATAL_ERROR;
default:
return ERROR_INTERNAL_FATAL_ERROR;
}
return ERROR_SUCCESS;
+11 -25
View File
@@ -27,13 +27,13 @@ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <yara/mem.h>
#include <yara/error.h>
#include <yara/mem.h>
#if defined(_WIN32) || defined(__CYGWIN__)
#include <windows.h>
#include <string.h>
#include <windows.h>
static HANDLE hHeap;
@@ -47,7 +47,6 @@ int yr_heap_alloc(void)
return ERROR_SUCCESS;
}
int yr_heap_free(void)
{
if (HeapDestroy(hHeap))
@@ -56,19 +55,16 @@ int yr_heap_free(void)
return ERROR_INTERNAL_FATAL_ERROR;
}
void* yr_calloc(size_t count, size_t size)
{
return (void*) HeapAlloc(hHeap, HEAP_ZERO_MEMORY, count * size);
}
void* yr_malloc(size_t size)
{
return (void*) HeapAlloc(hHeap, HEAP_ZERO_MEMORY, size);
}
void* yr_realloc(void* ptr, size_t size)
{
if (ptr == NULL)
@@ -77,17 +73,15 @@ void* yr_realloc(void* ptr, size_t size)
return (void*) HeapReAlloc(hHeap, HEAP_ZERO_MEMORY, ptr, size);
}
void yr_free(void* ptr)
{
HeapFree(hHeap, 0, ptr);
}
char* yr_strdup(const char *str)
char* yr_strdup(const char* str)
{
size_t len = strlen(str);
char *dup = (char*) yr_malloc(len + 1);
char* dup = (char*) yr_malloc(len + 1);
if (dup == NULL)
return NULL;
@@ -98,11 +92,10 @@ char* yr_strdup(const char *str)
return (char*) dup;
}
char* yr_strndup(const char *str, size_t n)
char* yr_strndup(const char* str, size_t n)
{
size_t len = strnlen(str, n);
char *dup = (char*) yr_malloc(len + 1);
char* dup = (char*) yr_malloc(len + 1);
if (dup == NULL)
return NULL;
@@ -110,58 +103,51 @@ char* yr_strndup(const char *str, size_t n)
memcpy(dup, str, len);
dup[len] = '\0';
return (char *) dup;
return (char*) dup;
}
#else
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int yr_heap_alloc(void)
{
return ERROR_SUCCESS;
}
int yr_heap_free(void)
{
return ERROR_SUCCESS;
}
void* yr_calloc(size_t count, size_t size)
{
return calloc(count, size);
}
void* yr_malloc(size_t size)
{
return malloc(size);
}
void* yr_realloc(void* ptr, size_t size)
{
return realloc(ptr, size);
}
void yr_free(void *ptr)
void yr_free(void* ptr)
{
free(ptr);
}
char* yr_strdup(const char *str)
char* yr_strdup(const char* str)
{
return strdup(str);
}
char* yr_strndup(const char *str, size_t n)
char* yr_strndup(const char* str, size_t n)
{
return strndup(str, n);
}
+28 -57
View File
@@ -28,44 +28,38 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <yara/exec.h>
#include <yara/modules.h>
#include <yara/libyara.h>
#include <yara/modules.h>
#define MODULE(name) \
int name ## __declarations(YR_OBJECT* module); \
int name ## __load(YR_SCAN_CONTEXT* context, \
YR_OBJECT* module, \
void* module_data, \
size_t module_data_size); \
int name ## __unload(YR_OBJECT* main_structure); \
int name ## __initialize(YR_MODULE* module); \
int name ## __finalize(YR_MODULE* module);
#define MODULE(name) \
int name##__declarations(YR_OBJECT* module); \
int name##__load( \
YR_SCAN_CONTEXT* context, \
YR_OBJECT* module, \
void* module_data, \
size_t module_data_size); \
int name##__unload(YR_OBJECT* main_structure); \
int name##__initialize(YR_MODULE* module); \
int name##__finalize(YR_MODULE* module);
#include <modules/module_list>
#undef MODULE
#define MODULE(name) \
{#name, \
name##__declarations, \
name##__load, \
name##__unload, \
name##__initialize, \
name##__finalize},
#define MODULE(name) \
{ \
#name, \
name##__declarations, \
name##__load, \
name##__unload, \
name##__initialize, \
name##__finalize \
},
YR_MODULE yr_modules_table[] =
{
#include <modules/module_list>
YR_MODULE yr_modules_table[] = {
#include <modules/module_list>
};
#undef MODULE
int yr_modules_initialize()
{
int i;
@@ -81,7 +75,6 @@ int yr_modules_initialize()
return ERROR_SUCCESS;
}
int yr_modules_finalize()
{
int i;
@@ -97,7 +90,6 @@ int yr_modules_finalize()
return ERROR_SUCCESS;
}
int yr_modules_do_declarations(
const char* module_name,
YR_OBJECT* main_structure)
@@ -113,19 +105,14 @@ int yr_modules_do_declarations(
return ERROR_UNKNOWN_MODULE;
}
int yr_modules_load(
const char* module_name,
YR_SCAN_CONTEXT* context)
int yr_modules_load(const char* module_name, YR_SCAN_CONTEXT* context)
{
int i, result;
YR_MODULE_IMPORT mi;
YR_OBJECT* module_structure = (YR_OBJECT*) yr_hash_table_lookup(
context->objects_table,
module_name,
NULL);
context->objects_table, module_name, NULL);
// if module_structure != NULL, the module was already
// loaded, return successfully without doing nothing.
@@ -136,10 +123,7 @@ int yr_modules_load(
// not loaded yet
FAIL_ON_ERROR(yr_object_create(
OBJECT_TYPE_STRUCTURE,
module_name,
NULL,
&module_structure));
OBJECT_TYPE_STRUCTURE, module_name, NULL, &module_structure));
// initialize canary for module's top-level structure, every other object
// within the module inherits the same canary.
@@ -150,10 +134,7 @@ int yr_modules_load(
mi.module_data_size = 0;
result = context->callback(
context,
CALLBACK_MSG_IMPORT_MODULE,
&mi,
context->user_data);
context, CALLBACK_MSG_IMPORT_MODULE, &mi, context->user_data);
if (result == CALLBACK_ERROR)
{
@@ -167,10 +148,7 @@ int yr_modules_load(
FAIL_ON_ERROR_WITH_CLEANUP(
yr_hash_table_add(
context->objects_table,
module_name,
NULL,
module_structure),
context->objects_table, module_name, NULL, module_structure),
yr_object_destroy(module_structure));
for (i = 0; i < sizeof(yr_modules_table) / sizeof(YR_MODULE); i++)
@@ -178,10 +156,7 @@ int yr_modules_load(
if (strcmp(yr_modules_table[i].name, module_name) == 0)
{
result = yr_modules_table[i].load(
context,
module_structure,
mi.module_data,
mi.module_data_size);
context, module_structure, mi.module_data, mi.module_data_size);
if (result != ERROR_SUCCESS)
return result;
@@ -200,18 +175,14 @@ int yr_modules_load(
return ERROR_SUCCESS;
}
int yr_modules_unload_all(
YR_SCAN_CONTEXT* context)
int yr_modules_unload_all(YR_SCAN_CONTEXT* context)
{
int i;
for (i = 0; i < sizeof(yr_modules_table) / sizeof(YR_MODULE); i++)
{
YR_OBJECT* module_structure = (YR_OBJECT*) yr_hash_table_remove(
context->objects_table,
yr_modules_table[i].name,
NULL);
context->objects_table, yr_modules_table[i].name, NULL);
if (module_structure != NULL)
{
+29 -48
View File
@@ -28,12 +28,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <string.h>
#include <jansson.h>
#include <yara/re.h>
#include <string.h>
#include <yara/modules.h>
#include <yara/re.h>
#if defined(_WIN32) || defined(__CYGWIN__)
@@ -105,8 +103,8 @@ define_function(network_dns_lookup)
}
#define METHOD_GET 0x01
#define METHOD_POST 0x02
#define METHOD_GET 0x01
#define METHOD_POST 0x02
uint64_t http_request(
@@ -131,7 +129,7 @@ uint64_t http_request(
{
if (((methods & METHOD_GET && strcasecmp(method, "get") == 0) ||
(methods & METHOD_POST && strcasecmp(method, "post") == 0)) &&
yr_re_match(context, uri_regexp, uri) > 0)
yr_re_match(context, uri_regexp, uri) > 0)
{
result = 1;
break;
@@ -145,34 +143,22 @@ uint64_t http_request(
define_function(network_http_request)
{
return_integer(
http_request(
scan_context(),
parent(),
regexp_argument(1),
METHOD_GET | METHOD_POST));
return_integer(http_request(
scan_context(), parent(), regexp_argument(1), METHOD_GET | METHOD_POST));
}
define_function(network_http_get)
{
return_integer(
http_request(
scan_context(),
parent(),
regexp_argument(1),
METHOD_GET));
http_request(scan_context(), parent(), regexp_argument(1), METHOD_GET));
}
define_function(network_http_post)
{
return_integer(
http_request(
scan_context(),
parent(),
regexp_argument(1),
METHOD_POST));
http_request(scan_context(), parent(), regexp_argument(1), METHOD_POST));
}
@@ -227,7 +213,8 @@ define_function(network_tcp)
{
if (yr_re_match(context, regexp_argument(1), dst) > 0)
{
if ((int64_t)dport == integer_argument(2)) {
if ((int64_t) dport == integer_argument(2))
{
result = 1;
break;
}
@@ -263,7 +250,8 @@ define_function(network_udp)
{
if (yr_re_match(context, regexp_argument(1), dst) > 0)
{
if ((int64_t)dport == integer_argument(2)) {
if ((int64_t) dport == integer_argument(2))
{
result = 1;
break;
}
@@ -279,7 +267,6 @@ define_function(network_udp)
// checks for regex match on user-agent
define_function(network_http_user_agent)
{
YR_SCAN_CONTEXT* context = scan_context();
YR_OBJECT* network_obj = parent();
@@ -356,7 +343,6 @@ define_function(filesystem_file_access)
}
define_function(sync_mutex)
{
YR_SCAN_CONTEXT* context = scan_context();
@@ -381,9 +367,8 @@ define_function(sync_mutex)
}
begin_declarations;
begin_struct("network");
begin_declarations
begin_struct("network")
declare_function("dns_lookup", "r", "i", network_dns_lookup);
declare_function("http_get", "r", "i", network_http_get);
declare_function("http_post", "r", "i", network_http_post);
@@ -392,32 +377,29 @@ begin_declarations;
declare_function("host", "r", "i", network_host);
declare_function("tcp", "ri", "i", network_tcp);
declare_function("udp", "ri", "i", network_udp);
end_struct("network");
end_struct("network")
begin_struct("registry");
begin_struct("registry")
declare_function("key_access", "r", "i", registry_key_access);
end_struct("registry");
end_struct("registry")
begin_struct("filesystem");
begin_struct("filesystem")
declare_function("file_access", "r", "i", filesystem_file_access);
end_struct("filesystem");
end_struct("filesystem")
begin_struct("sync");
declare_function("mutex", "r", "i", sync_mutex);
end_struct("sync");
end_declarations;
begin_struct("sync")
declare_function("mutex", "r", "i", sync_mutex)
end_struct("sync")
end_declarations
int module_initialize(
YR_MODULE* module)
int module_initialize(YR_MODULE* module)
{
return ERROR_SUCCESS;
}
int module_finalize(
YR_MODULE* module)
int module_finalize(YR_MODULE* module)
{
return ERROR_SUCCESS;
}
@@ -445,11 +427,11 @@ int module_load(
json = json_loadb(
(const char*) module_data,
module_data_size,
#if JANSSON_VERSION_HEX >= 0x020600
#if JANSSON_VERSION_HEX >= 0x020600
JSON_ALLOW_NUL,
#else
#else
0,
#endif
#endif
&json_error);
if (json == NULL)
@@ -482,4 +464,3 @@ int module_unload(YR_OBJECT* module)
return ERROR_SUCCESS;
}
+5 -10
View File
@@ -31,22 +31,18 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define MODULE_NAME demo
begin_declarations;
begin_declarations
declare_string("greeting");
end_declarations;
end_declarations
int module_initialize(
YR_MODULE* module)
int module_initialize(YR_MODULE* module)
{
return ERROR_SUCCESS;
}
int module_finalize(
YR_MODULE* module)
int module_finalize(YR_MODULE* module)
{
return ERROR_SUCCESS;
}
@@ -64,8 +60,7 @@ int module_load(
}
int module_unload(
YR_OBJECT* module_object)
int module_unload(YR_OBJECT* module_object)
{
return ERROR_SUCCESS;
}
+445 -340
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+398 -379
View File
@@ -29,21 +29,18 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <limits.h>
#include <string.h>
#include <yara/elf.h>
#include <yara/endian.h>
#include <yara/modules.h>
#include <yara/mem.h>
#include <yara/modules.h>
#include <yara/utils.h>
#define MODULE_NAME elf
#define CLASS_DATA(c,d) ((c << 8) | d)
#define CLASS_DATA(c, d) ((c << 8) | d)
int get_elf_class_data(
const uint8_t* buffer,
size_t buffer_length)
int get_elf_class_data(const uint8_t* buffer, size_t buffer_length)
{
elf_ident_t* elf_ident;
@@ -69,11 +66,11 @@ static bool is_valid_ptr(
uint64_t ptr_size) // ptr_size can be 64bit even in 32bit systems.
{
return ptr >= base && ptr_size <= size &&
((char*) ptr) + ptr_size <= ((char*) base) + size;
((char*) ptr) + ptr_size <= ((char*) base) + size;
}
#define IS_VALID_PTR(base, size, ptr) \
is_valid_ptr(base, size, ptr, sizeof(*ptr))
is_valid_ptr(base, size, ptr, sizeof(*ptr))
//
// Returns a string table entry for the index or NULL if the entry is out
@@ -112,312 +109,336 @@ static const char* str_table_entry(
return str_entry;
}
#define ELF_SIZE_OF_SECTION_TABLE(bits,bo,h) \
#define ELF_SIZE_OF_SECTION_TABLE(bits, bo, h) \
(sizeof(elf##bits##_section_header_t) * yr_##bo##16toh(h->sh_entry_count))
#define ELF_SIZE_OF_PROGRAM_TABLE(bits,bo,h) \
#define ELF_SIZE_OF_PROGRAM_TABLE(bits, bo, h) \
(sizeof(elf##bits##_program_header_t) * yr_##bo##16toh(h->ph_entry_count))
#define ELF_RVA_TO_OFFSET(bits,bo) \
uint64_t elf_rva_to_offset_##bits##_##bo( \
elf##bits##_header_t* elf_header, \
uint64_t rva, \
size_t elf_size) \
{ \
if (yr_##bo##16toh(elf_header->type) == ELF_ET_EXEC) \
{ \
int i; \
\
elf##bits##_program_header_t* program; \
\
/* check that ph_offset doesn't wrap when added to SIZE_OF_PROGRAM_TABLE */\
\
if(ULONG_MAX - yr_##bo##bits##toh(elf_header->ph_offset) < \
ELF_SIZE_OF_PROGRAM_TABLE(bits,bo,elf_header)) \
{ \
return YR_UNDEFINED; \
} \
\
if (yr_##bo##bits##toh(elf_header->ph_offset) == 0 || \
yr_##bo##bits##toh(elf_header->ph_offset) > elf_size || \
yr_##bo##bits##toh(elf_header->ph_offset) + \
ELF_SIZE_OF_PROGRAM_TABLE(bits,bo,elf_header) > elf_size || \
yr_##bo##16toh(elf_header->ph_entry_count) == 0) \
{ \
return YR_UNDEFINED; \
} \
\
program = (elf##bits##_program_header_t*) \
((uint8_t*) elf_header + yr_##bo##bits##toh(elf_header->ph_offset)); \
\
for (i = 0; i < yr_##bo##16toh(elf_header->ph_entry_count); i++) \
{ \
if (rva >= yr_##bo##bits##toh(program->virt_addr) && \
rva < yr_##bo##bits##toh(program->virt_addr) + \
yr_##bo##bits##toh(program->mem_size)) \
{ \
return yr_##bo##bits##toh(program->offset) + \
(rva - yr_##bo##bits##toh(program->virt_addr)); \
} \
\
program++; \
} \
} \
else \
{ \
int i; \
\
elf##bits##_section_header_t* section; \
\
/* check that sh_offset doesn't wrap when added to SIZE_OF_SECTION_TABLE */\
\
if(ULONG_MAX - yr_##bo##bits##toh(elf_header->sh_offset) < \
ELF_SIZE_OF_SECTION_TABLE(bits,bo,elf_header)) \
{ \
return YR_UNDEFINED; \
} \
\
if (yr_##bo##bits##toh(elf_header->sh_offset) == 0 || \
yr_##bo##bits##toh(elf_header->sh_offset) > elf_size || \
yr_##bo##bits##toh(elf_header->sh_offset) + \
ELF_SIZE_OF_SECTION_TABLE(bits,bo,elf_header) > elf_size || \
yr_##bo##16toh(elf_header->sh_entry_count) == 0) \
{ \
return YR_UNDEFINED; \
} \
\
section = (elf##bits##_section_header_t*) \
((uint8_t*) elf_header + yr_##bo##bits##toh(elf_header->sh_offset)); \
\
for (i = 0; i < yr_##bo##16toh(elf_header->sh_entry_count); i++) \
{ \
if (yr_##bo##32toh(section->type) != ELF_SHT_NULL && \
yr_##bo##32toh(section->type) != ELF_SHT_NOBITS && \
rva >= yr_##bo##bits##toh(section->addr) && \
rva < yr_##bo##bits##toh(section->addr) + \
yr_##bo##bits##toh(section->size)) \
{ \
return yr_##bo##bits##toh(section->offset) + \
(rva - yr_##bo##bits##toh(section->addr)); \
} \
\
section++; \
} \
} \
return YR_UNDEFINED; \
}
#define ELF_RVA_TO_OFFSET(bits, bo) \
uint64_t elf_rva_to_offset_##bits##_##bo( \
elf##bits##_header_t* elf_header, uint64_t rva, size_t elf_size) \
{ \
if (yr_##bo##16toh(elf_header->type) == ELF_ET_EXEC) \
{ \
int i; \
\
elf##bits##_program_header_t* program; \
\
/* check that ph_offset doesn't wrap when added to SIZE_OF_PROGRAM_TABLE \
*/ \
\
if (ULONG_MAX - yr_##bo##bits##toh(elf_header->ph_offset) < \
ELF_SIZE_OF_PROGRAM_TABLE(bits, bo, elf_header)) \
{ \
return YR_UNDEFINED; \
} \
\
if (yr_##bo##bits##toh(elf_header->ph_offset) == 0 || \
yr_##bo##bits##toh(elf_header->ph_offset) > elf_size || \
yr_##bo##bits##toh(elf_header->ph_offset) + \
ELF_SIZE_OF_PROGRAM_TABLE(bits, bo, elf_header) > \
elf_size || \
yr_##bo##16toh(elf_header->ph_entry_count) == 0) \
{ \
return YR_UNDEFINED; \
} \
\
program = (elf##bits##_program_header_t*) \
((uint8_t*) elf_header + yr_##bo##bits##toh(elf_header->ph_offset)); \
\
for (i = 0; i < yr_##bo##16toh(elf_header->ph_entry_count); i++) \
{ \
if (rva >= yr_##bo##bits##toh(program->virt_addr) && \
rva < yr_##bo##bits##toh(program->virt_addr) + \
yr_##bo##bits##toh(program->mem_size)) \
{ \
return yr_##bo##bits##toh(program->offset) + \
(rva - yr_##bo##bits##toh(program->virt_addr)); \
} \
\
program++; \
} \
} \
else \
{ \
int i; \
\
elf##bits##_section_header_t* section; \
\
/* check that sh_offset doesn't wrap when added to SIZE_OF_SECTION_TABLE \
*/ \
\
if (ULONG_MAX - yr_##bo##bits##toh(elf_header->sh_offset) < \
ELF_SIZE_OF_SECTION_TABLE(bits, bo, elf_header)) \
{ \
return YR_UNDEFINED; \
} \
\
if (yr_##bo##bits##toh(elf_header->sh_offset) == 0 || \
yr_##bo##bits##toh(elf_header->sh_offset) > elf_size || \
yr_##bo##bits##toh(elf_header->sh_offset) + \
ELF_SIZE_OF_SECTION_TABLE(bits, bo, elf_header) > \
elf_size || \
yr_##bo##16toh(elf_header->sh_entry_count) == 0) \
{ \
return YR_UNDEFINED; \
} \
\
section = (elf##bits##_section_header_t*) \
((uint8_t*) elf_header + yr_##bo##bits##toh(elf_header->sh_offset)); \
\
for (i = 0; i < yr_##bo##16toh(elf_header->sh_entry_count); i++) \
{ \
if (yr_##bo##32toh(section->type) != ELF_SHT_NULL && \
yr_##bo##32toh(section->type) != ELF_SHT_NOBITS && \
rva >= yr_##bo##bits##toh(section->addr) && \
rva < yr_##bo##bits##toh(section->addr) + \
yr_##bo##bits##toh(section->size)) \
{ \
return yr_##bo##bits##toh(section->offset) + \
(rva - yr_##bo##bits##toh(section->addr)); \
} \
\
section++; \
} \
} \
return YR_UNDEFINED; \
}
#define PARSE_ELF_HEADER(bits,bo) \
void parse_elf_header_##bits##_##bo( \
elf##bits##_header_t* elf, \
uint64_t base_address, \
size_t elf_size, \
int flags, \
YR_OBJECT* elf_obj) \
{ \
unsigned int i, j; \
const char* elf_raw = (const char*) elf; \
uint16_t str_table_index = yr_##bo##16toh(elf->sh_str_table_index); \
\
const char* sym_table = NULL; \
const char* sym_str_table = NULL; \
\
uint##bits##_t sym_table_size = 0; \
uint##bits##_t sym_str_table_size = 0; \
\
elf##bits##_section_header_t* section_table; \
elf##bits##_section_header_t* section; \
elf##bits##_program_header_t* segment; \
\
set_integer(yr_##bo##16toh(elf->type), elf_obj, "type"); \
set_integer(yr_##bo##16toh(elf->machine), elf_obj, "machine"); \
set_integer(yr_##bo##bits##toh(elf->sh_offset), elf_obj, \
"sh_offset"); \
set_integer(yr_##bo##16toh(elf->sh_entry_size), elf_obj, \
"sh_entry_size"); \
set_integer(yr_##bo##16toh(elf->sh_entry_count), elf_obj, \
"number_of_sections"); \
set_integer(yr_##bo##bits##toh(elf->ph_offset), elf_obj, \
"ph_offset"); \
set_integer(yr_##bo##16toh(elf->ph_entry_size), elf_obj, \
"ph_entry_size"); \
set_integer(yr_##bo##16toh(elf->ph_entry_count), elf_obj, \
"number_of_segments"); \
\
if (yr_##bo##bits##toh(elf->entry) != 0) \
{ \
set_integer( \
flags & SCAN_FLAGS_PROCESS_MEMORY ? \
base_address + yr_##bo##bits##toh(elf->entry) : \
elf_rva_to_offset_##bits##_##bo( \
elf, yr_##bo##bits##toh(elf->entry), elf_size), \
elf_obj, "entry_point"); \
} \
\
if (yr_##bo##16toh(elf->sh_entry_count) < ELF_SHN_LORESERVE && \
str_table_index < yr_##bo##16toh(elf->sh_entry_count) && \
yr_##bo##bits##toh(elf->sh_offset) < elf_size && \
yr_##bo##bits##toh(elf->sh_offset) + \
yr_##bo##16toh(elf->sh_entry_count) * \
sizeof(elf##bits##_section_header_t) <= elf_size) \
{ \
const char* str_table = NULL; \
\
section_table = (elf##bits##_section_header_t*) \
(elf_raw + yr_##bo##bits##toh(elf->sh_offset)); \
\
if (yr_##bo##bits##toh(section_table[str_table_index].offset) < elf_size) \
{ \
str_table = elf_raw + yr_##bo##bits##toh( \
section_table[str_table_index].offset); \
} \
\
section = section_table; \
\
for (i = 0; i < yr_##bo##16toh(elf->sh_entry_count); i++, section++) \
{ \
set_integer(yr_##bo##32toh(section->type), elf_obj, \
"sections[%i].type", i); \
set_integer(yr_##bo##bits##toh(section->flags), elf_obj, \
"sections[%i].flags", i); \
set_integer(yr_##bo##bits##toh(section->addr), elf_obj, \
"sections[%i].address", i); \
set_integer(yr_##bo##bits##toh(section->size), elf_obj, \
"sections[%i].size", i); \
set_integer(yr_##bo##bits##toh(section->offset), elf_obj, \
"sections[%i].offset", i); \
\
if (yr_##bo##32toh(section->name) < elf_size && str_table > elf_raw) \
{ \
const char* section_name = str_table_entry( \
str_table, \
elf_raw + elf_size, \
yr_##bo##32toh(section->name)); \
\
if (section_name) \
set_string(section_name, elf_obj, "sections[%i].name", i); \
} \
\
if (yr_##bo##32toh(section->type) == ELF_SHT_SYMTAB && \
yr_##bo##32toh(section->link) < elf->sh_entry_count) \
{ \
elf##bits##_section_header_t* string_section = \
section_table + yr_##bo##32toh(section->link); \
\
if (IS_VALID_PTR(elf, elf_size, string_section) && \
yr_##bo##32toh(string_section->type) == ELF_SHT_STRTAB) \
{ \
sym_table = elf_raw + yr_##bo##bits##toh(section->offset); \
sym_str_table = elf_raw + yr_##bo##bits##toh(string_section->offset);\
sym_table_size = yr_##bo##bits##toh(section->size); \
sym_str_table_size = yr_##bo##bits##toh(string_section->size); \
} \
} \
} \
\
if (is_valid_ptr(elf, elf_size, sym_str_table, sym_str_table_size) && \
is_valid_ptr(elf, elf_size, sym_table, sym_table_size)) \
{ \
elf##bits##_sym_t* sym = (elf##bits##_sym_t*) sym_table; \
\
for (j = 0; j < sym_table_size / sizeof(elf##bits##_sym_t); j++, sym++) \
{ \
const char* sym_name = str_table_entry( \
sym_str_table, \
sym_str_table + sym_str_table_size, \
yr_##bo##32toh(sym->name)); \
\
if (sym_name) \
set_string(sym_name, elf_obj, "symtab[%i].name", j); \
\
set_integer(sym->info >> 4, elf_obj, \
"symtab[%i].bind", j); \
set_integer(sym->info & 0xf, elf_obj, \
"symtab[%i].type", j); \
set_integer(yr_##bo##16toh(sym->shndx), elf_obj, \
"symtab[%i].shndx", j); \
set_integer(yr_##bo##bits##toh(sym->value), elf_obj, \
"symtab[%i].value", j); \
set_integer(yr_##bo##bits##toh(sym->size), elf_obj, \
"symtab[%i].size", j); \
} \
\
set_integer(j, elf_obj, "symtab_entries"); \
} \
} \
\
if (yr_##bo##16toh(elf->ph_entry_count) > 0 && \
yr_##bo##16toh(elf->ph_entry_count) < ELF_PN_XNUM && \
yr_##bo##bits##toh(elf->ph_offset) < elf_size && \
yr_##bo##bits##toh(elf->ph_offset) + \
yr_##bo##16toh(elf->ph_entry_count) * \
sizeof(elf##bits##_program_header_t) <= elf_size) \
{ \
segment = (elf##bits##_program_header_t*) \
(elf_raw + yr_##bo##bits##toh(elf->ph_offset)); \
\
for (i = 0; i < yr_##bo##16toh(elf->ph_entry_count); i++, segment++) \
{ \
set_integer( \
yr_##bo##32toh(segment->type), elf_obj, "segments[%i].type", i); \
set_integer( \
yr_##bo##32toh(segment->flags), elf_obj, "segments[%i].flags", i); \
set_integer( \
yr_##bo##bits##toh(segment->offset), elf_obj, \
"segments[%i].offset", i); \
set_integer( \
yr_##bo##bits##toh(segment->virt_addr), elf_obj, \
"segments[%i].virtual_address", i); \
set_integer( \
yr_##bo##bits##toh(segment->phys_addr), elf_obj, \
"segments[%i].physical_address", i); \
set_integer( \
yr_##bo##bits##toh(segment->file_size), elf_obj, \
"segments[%i].file_size", i); \
set_integer( \
yr_##bo##bits##toh(segment->mem_size), elf_obj, \
"segments[%i].memory_size", i); \
set_integer( \
yr_##bo##bits##toh(segment->alignment), elf_obj, \
"segments[%i].alignment", i); \
\
if (yr_##bo##32toh(segment->type) == ELF_PT_DYNAMIC) \
{ \
elf##bits##_dyn_t* dyn = (elf##bits##_dyn_t*) \
(elf_raw + yr_##bo##bits##toh(segment->offset)); \
\
for (j = 0; IS_VALID_PTR(elf, elf_size, dyn); dyn++, j++) \
{ \
set_integer( \
yr_##bo##bits##toh(dyn->tag), elf_obj, "dynamic[%i].type", j); \
set_integer( \
yr_##bo##bits##toh(dyn->val), elf_obj, "dynamic[%i].val", j); \
\
if (dyn->tag == ELF_DT_NULL) \
{ \
j++; \
break; \
} \
} \
set_integer(j, elf_obj, "dynamic_section_entries"); \
} \
} \
} \
}
#define PARSE_ELF_HEADER(bits, bo) \
void parse_elf_header_##bits##_##bo( \
elf##bits##_header_t* elf, \
uint64_t base_address, \
size_t elf_size, \
int flags, \
YR_OBJECT* elf_obj) \
{ \
unsigned int i, j; \
const char* elf_raw = (const char*) elf; \
uint16_t str_table_index = yr_##bo##16toh(elf->sh_str_table_index); \
\
const char* sym_table = NULL; \
const char* sym_str_table = NULL; \
\
uint##bits##_t sym_table_size = 0; \
uint##bits##_t sym_str_table_size = 0; \
\
elf##bits##_section_header_t* section_table; \
elf##bits##_section_header_t* section; \
elf##bits##_program_header_t* segment; \
\
set_integer(yr_##bo##16toh(elf->type), elf_obj, "type"); \
set_integer(yr_##bo##16toh(elf->machine), elf_obj, "machine"); \
set_integer(yr_##bo##bits##toh(elf->sh_offset), elf_obj, "sh_offset"); \
set_integer(yr_##bo##16toh(elf->sh_entry_size), elf_obj, "sh_entry_size"); \
set_integer( \
yr_##bo##16toh(elf->sh_entry_count), elf_obj, "number_of_sections"); \
set_integer(yr_##bo##bits##toh(elf->ph_offset), elf_obj, "ph_offset"); \
set_integer(yr_##bo##16toh(elf->ph_entry_size), elf_obj, "ph_entry_size"); \
set_integer( \
yr_##bo##16toh(elf->ph_entry_count), elf_obj, "number_of_segments"); \
\
if (yr_##bo##bits##toh(elf->entry) != 0) \
{ \
set_integer( \
flags& SCAN_FLAGS_PROCESS_MEMORY \
? base_address + yr_##bo##bits##toh(elf->entry) \
: elf_rva_to_offset_##bits##_##bo( \
elf, yr_##bo##bits##toh(elf->entry), elf_size), \
elf_obj, \
"entry_point"); \
} \
\
if (yr_##bo##16toh(elf->sh_entry_count) < ELF_SHN_LORESERVE && \
str_table_index < yr_##bo##16toh(elf->sh_entry_count) && \
yr_##bo##bits##toh(elf->sh_offset) < elf_size && \
yr_##bo##bits##toh(elf->sh_offset) + \
yr_##bo##16toh(elf->sh_entry_count) * \
sizeof(elf##bits##_section_header_t) <= \
elf_size) \
{ \
const char* str_table = NULL; \
\
section_table = \
(elf##bits##_section_header_t*) (elf_raw + yr_##bo##bits##toh(elf->sh_offset)); \
\
if (yr_##bo##bits##toh(section_table[str_table_index].offset) < \
elf_size) \
{ \
str_table = elf_raw + \
yr_##bo##bits##toh(section_table[str_table_index].offset); \
} \
\
section = section_table; \
\
for (i = 0; i < yr_##bo##16toh(elf->sh_entry_count); i++, section++) \
{ \
set_integer( \
yr_##bo##32toh(section->type), elf_obj, "sections[%i].type", i); \
set_integer( \
yr_##bo##bits##toh(section->flags), \
elf_obj, \
"sections[%i].flags", \
i); \
set_integer( \
yr_##bo##bits##toh(section->addr), \
elf_obj, \
"sections[%i].address", \
i); \
set_integer( \
yr_##bo##bits##toh(section->size), \
elf_obj, \
"sections[%i].size", \
i); \
set_integer( \
yr_##bo##bits##toh(section->offset), \
elf_obj, \
"sections[%i].offset", \
i); \
\
if (yr_##bo##32toh(section->name) < elf_size && str_table > elf_raw) \
{ \
const char* section_name = str_table_entry( \
str_table, elf_raw + elf_size, yr_##bo##32toh(section->name)); \
\
if (section_name) \
set_string(section_name, elf_obj, "sections[%i].name", i); \
} \
\
if (yr_##bo##32toh(section->type) == ELF_SHT_SYMTAB && \
yr_##bo##32toh(section->link) < elf->sh_entry_count) \
{ \
elf##bits##_section_header_t* string_section = section_table + \
yr_##bo##32toh( \
section->link); \
\
if (IS_VALID_PTR(elf, elf_size, string_section) && \
yr_##bo##32toh(string_section->type) == ELF_SHT_STRTAB) \
{ \
sym_table = elf_raw + yr_##bo##bits##toh(section->offset); \
sym_str_table = elf_raw + \
yr_##bo##bits##toh(string_section->offset); \
sym_table_size = yr_##bo##bits##toh(section->size); \
sym_str_table_size = yr_##bo##bits##toh(string_section->size); \
} \
} \
} \
\
if (is_valid_ptr(elf, elf_size, sym_str_table, sym_str_table_size) && \
is_valid_ptr(elf, elf_size, sym_table, sym_table_size)) \
{ \
elf##bits##_sym_t* sym = (elf##bits##_sym_t*) sym_table; \
\
for (j = 0; j < sym_table_size / sizeof(elf##bits##_sym_t); \
j++, sym++) \
{ \
const char* sym_name = str_table_entry( \
sym_str_table, \
sym_str_table + sym_str_table_size, \
yr_##bo##32toh(sym->name)); \
\
if (sym_name) \
set_string(sym_name, elf_obj, "symtab[%i].name", j); \
\
set_integer(sym->info >> 4, elf_obj, "symtab[%i].bind", j); \
set_integer(sym->info & 0xf, elf_obj, "symtab[%i].type", j); \
set_integer( \
yr_##bo##16toh(sym->shndx), elf_obj, "symtab[%i].shndx", j); \
set_integer( \
yr_##bo##bits##toh(sym->value), elf_obj, "symtab[%i].value", j); \
set_integer( \
yr_##bo##bits##toh(sym->size), elf_obj, "symtab[%i].size", j); \
} \
\
set_integer(j, elf_obj, "symtab_entries"); \
} \
} \
\
if (yr_##bo##16toh(elf->ph_entry_count) > 0 && \
yr_##bo##16toh(elf->ph_entry_count) < ELF_PN_XNUM && \
yr_##bo##bits##toh(elf->ph_offset) < elf_size && \
yr_##bo##bits##toh(elf->ph_offset) + \
yr_##bo##16toh(elf->ph_entry_count) * \
sizeof(elf##bits##_program_header_t) <= \
elf_size) \
{ \
segment = \
(elf##bits##_program_header_t*) (elf_raw + yr_##bo##bits##toh(elf->ph_offset)); \
\
for (i = 0; i < yr_##bo##16toh(elf->ph_entry_count); i++, segment++) \
{ \
set_integer( \
yr_##bo##32toh(segment->type), elf_obj, "segments[%i].type", i); \
set_integer( \
yr_##bo##32toh(segment->flags), elf_obj, "segments[%i].flags", i); \
set_integer( \
yr_##bo##bits##toh(segment->offset), \
elf_obj, \
"segments[%i].offset", \
i); \
set_integer( \
yr_##bo##bits##toh(segment->virt_addr), \
elf_obj, \
"segments[%i].virtual_address", \
i); \
set_integer( \
yr_##bo##bits##toh(segment->phys_addr), \
elf_obj, \
"segments[%i].physical_address", \
i); \
set_integer( \
yr_##bo##bits##toh(segment->file_size), \
elf_obj, \
"segments[%i].file_size", \
i); \
set_integer( \
yr_##bo##bits##toh(segment->mem_size), \
elf_obj, \
"segments[%i].memory_size", \
i); \
set_integer( \
yr_##bo##bits##toh(segment->alignment), \
elf_obj, \
"segments[%i].alignment", \
i); \
\
if (yr_##bo##32toh(segment->type) == ELF_PT_DYNAMIC) \
{ \
elf##bits##_dyn_t* dyn = \
(elf##bits##_dyn_t*) (elf_raw + yr_##bo##bits##toh(segment->offset)); \
\
for (j = 0; IS_VALID_PTR(elf, elf_size, dyn); dyn++, j++) \
{ \
set_integer( \
yr_##bo##bits##toh(dyn->tag), elf_obj, "dynamic[%i].type", j); \
set_integer( \
yr_##bo##bits##toh(dyn->val), elf_obj, "dynamic[%i].val", j); \
\
if (dyn->tag == ELF_DT_NULL) \
{ \
j++; \
break; \
} \
} \
set_integer(j, elf_obj, "dynamic_section_entries"); \
} \
} \
} \
}
ELF_RVA_TO_OFFSET(32,le);
ELF_RVA_TO_OFFSET(64,le);
ELF_RVA_TO_OFFSET(32,be);
ELF_RVA_TO_OFFSET(64,be);
ELF_RVA_TO_OFFSET(32, le);
ELF_RVA_TO_OFFSET(64, le);
ELF_RVA_TO_OFFSET(32, be);
ELF_RVA_TO_OFFSET(64, be);
PARSE_ELF_HEADER(32,le);
PARSE_ELF_HEADER(64,le);
PARSE_ELF_HEADER(32,be);
PARSE_ELF_HEADER(64,be);
PARSE_ELF_HEADER(32, le);
PARSE_ELF_HEADER(64, le);
PARSE_ELF_HEADER(32, be);
PARSE_ELF_HEADER(64, be);
begin_declarations;
begin_declarations
declare_integer("ET_NONE");
declare_integer("ET_REL");
declare_integer("ET_EXEC");
@@ -468,14 +489,14 @@ begin_declarations;
declare_integer("ph_offset");
declare_integer("ph_entry_size");
begin_struct_array("sections");
begin_struct_array("sections")
declare_integer("type");
declare_integer("flags");
declare_integer("address");
declare_string("name");
declare_integer("size");
declare_integer("offset");
end_struct_array("sections");
end_struct_array("sections")
declare_integer("PT_NULL");
declare_integer("PT_LOAD");
@@ -537,7 +558,7 @@ begin_declarations;
declare_integer("PF_W");
declare_integer("PF_R");
begin_struct_array("segments");
begin_struct_array("segments")
declare_integer("type");
declare_integer("flags");
declare_integer("offset");
@@ -546,36 +567,34 @@ begin_declarations;
declare_integer("file_size");
declare_integer("memory_size");
declare_integer("alignment");
end_struct_array("segments");
end_struct_array("segments")
declare_integer("dynamic_section_entries");
begin_struct_array("dynamic");
begin_struct_array("dynamic")
declare_integer("type");
declare_integer("val");
end_struct_array("dynamic");
end_struct_array("dynamic")
declare_integer("symtab_entries");
begin_struct_array("symtab");
begin_struct_array("symtab")
declare_string("name");
declare_integer("value");
declare_integer("size");
declare_integer("type");
declare_integer("bind");
declare_integer("shndx");
end_struct_array("symtab");
end_struct_array("symtab")
end_declarations;
end_declarations
int module_initialize(
YR_MODULE* module)
int module_initialize(YR_MODULE* module)
{
return ERROR_SUCCESS;
}
int module_finalize(
YR_MODULE* module)
int module_finalize(YR_MODULE* module)
{
return ERROR_SUCCESS;
}
@@ -698,87 +717,87 @@ int module_load(
if (block_data == NULL)
continue;
switch(get_elf_class_data(block_data, block->size))
switch (get_elf_class_data(block_data, block->size))
{
case CLASS_DATA(ELF_CLASS_32, ELF_DATA_2LSB):
case CLASS_DATA(ELF_CLASS_32, ELF_DATA_2LSB):
if (block->size > sizeof(elf32_header_t))
if (block->size > sizeof(elf32_header_t))
{
elf_header32 = (elf32_header_t*) block_data;
if (!(context->flags & SCAN_FLAGS_PROCESS_MEMORY) ||
yr_le16toh(elf_header32->type) == ELF_ET_EXEC)
{
elf_header32 = (elf32_header_t*) block_data;
if (!(context->flags & SCAN_FLAGS_PROCESS_MEMORY) ||
yr_le16toh(elf_header32->type) == ELF_ET_EXEC)
{
parse_elf_header_32_le(
elf_header32,
block->base,
block->size,
context->flags,
module_object);
}
parse_elf_header_32_le(
elf_header32,
block->base,
block->size,
context->flags,
module_object);
}
}
break;
break;
case CLASS_DATA(ELF_CLASS_32, ELF_DATA_2MSB):
case CLASS_DATA(ELF_CLASS_32, ELF_DATA_2MSB):
if (block->size > sizeof(elf32_header_t))
if (block->size > sizeof(elf32_header_t))
{
elf_header32 = (elf32_header_t*) block_data;
if (!(context->flags & SCAN_FLAGS_PROCESS_MEMORY) ||
yr_be16toh(elf_header32->type) == ELF_ET_EXEC)
{
elf_header32 = (elf32_header_t*) block_data;
if (!(context->flags & SCAN_FLAGS_PROCESS_MEMORY) ||
yr_be16toh(elf_header32->type) == ELF_ET_EXEC)
{
parse_elf_header_32_be(
elf_header32,
block->base,
block->size,
context->flags,
module_object);
}
parse_elf_header_32_be(
elf_header32,
block->base,
block->size,
context->flags,
module_object);
}
}
break;
break;
case CLASS_DATA(ELF_CLASS_64,ELF_DATA_2LSB):
case CLASS_DATA(ELF_CLASS_64, ELF_DATA_2LSB):
if (block->size > sizeof(elf64_header_t))
if (block->size > sizeof(elf64_header_t))
{
elf_header64 = (elf64_header_t*) block_data;
if (!(context->flags & SCAN_FLAGS_PROCESS_MEMORY) ||
yr_le16toh(elf_header64->type) == ELF_ET_EXEC)
{
elf_header64 = (elf64_header_t*) block_data;
if (!(context->flags & SCAN_FLAGS_PROCESS_MEMORY) ||
yr_le16toh(elf_header64->type) == ELF_ET_EXEC)
{
parse_elf_header_64_le(
elf_header64,
block->base,
block->size,
context->flags,
module_object);
}
parse_elf_header_64_le(
elf_header64,
block->base,
block->size,
context->flags,
module_object);
}
}
break;
break;
case CLASS_DATA(ELF_CLASS_64,ELF_DATA_2MSB):
case CLASS_DATA(ELF_CLASS_64, ELF_DATA_2MSB):
if (block->size > sizeof(elf64_header_t))
if (block->size > sizeof(elf64_header_t))
{
elf_header64 = (elf64_header_t*) block_data;
if (!(context->flags & SCAN_FLAGS_PROCESS_MEMORY) ||
yr_be16toh(elf_header64->type) == ELF_ET_EXEC)
{
elf_header64 = (elf64_header_t*) block_data;
if (!(context->flags & SCAN_FLAGS_PROCESS_MEMORY) ||
yr_be16toh(elf_header64->type) == ELF_ET_EXEC)
{
parse_elf_header_64_be(
elf_header64,
block->base,
block->size,
context->flags,
module_object);
}
parse_elf_header_64_be(
elf_header64,
block->base,
block->size,
context->flags,
module_object);
}
}
break;
break;
}
}
+241 -143
View File
@@ -27,11 +27,11 @@ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "../crypto.h"
#include <yara/globals.h>
#include <yara/mem.h>
#include <yara/modules.h>
#include <yara/globals.h>
#include "../crypto.h"
#define MODULE_NAME hash
@@ -45,50 +45,49 @@ typedef struct _CACHE_KEY
const uint32_t crc32_tab[] = {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
};
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d};
static void digest_to_ascii(
@@ -118,13 +117,16 @@ static char* get_from_cache(
key.length = length;
char* result = (char*) yr_hash_table_lookup_raw_key(
hash_table,
&key,
sizeof(key),
ns);
hash_table, &key, sizeof(key), ns);
YR_DEBUG_FPRINTF(2, stderr, "+ %s(offset=%" PRIi64 " length=%" PRIi64 ") {} = %p\n",
__FUNCTION__, offset, length, result);
YR_DEBUG_FPRINTF(
2,
stderr,
"+ %s(offset=%" PRIi64 " length=%" PRIi64 ") {} = %p\n",
__FUNCTION__,
offset,
length,
result);
return result;
}
@@ -149,14 +151,17 @@ static int add_to_cache(
return ERROR_INSUFFICIENT_MEMORY;
int result = yr_hash_table_add_raw_key(
hash_table,
&key,
sizeof(key),
ns,
(void*) copy);
hash_table, &key, sizeof(key), ns, (void*) copy);
YR_DEBUG_FPRINTF(2, stderr, "+ %s(offset=%" PRIi64 " length=%" PRIi64 " digest=%s) {} = %d\n",
__FUNCTION__, offset, length, digest, result);
YR_DEBUG_FPRINTF(
2,
stderr,
"+ %s(offset=%" PRIi64 " length=%" PRIi64 " digest=%s) {} = %d\n",
__FUNCTION__,
offset,
length,
digest,
result);
return result;
}
@@ -176,8 +181,13 @@ define_function(string_md5)
digest_to_ascii(digest, digest_ascii, YR_MD5_LEN);
YR_DEBUG_FPRINTF(2, stderr, "+ %s() {} = 0x%s // s->length=%u\n",
__FUNCTION__, digest_ascii, s->length);
YR_DEBUG_FPRINTF(
2,
stderr,
"+ %s() {} = 0x%s // s->length=%u\n",
__FUNCTION__,
digest_ascii,
s->length);
return_string(digest_ascii);
}
@@ -197,8 +207,13 @@ define_function(string_sha256)
digest_to_ascii(digest, digest_ascii, YR_SHA256_LEN);
YR_DEBUG_FPRINTF(2, stderr, "+ %s() {} = 0x%s // s->length=%u\n",
__FUNCTION__, digest_ascii, s->length);
YR_DEBUG_FPRINTF(
2,
stderr,
"+ %s() {} = 0x%s // s->length=%u\n",
__FUNCTION__,
digest_ascii,
s->length);
return_string(digest_ascii);
}
@@ -218,8 +233,13 @@ define_function(string_sha1)
digest_to_ascii(digest, digest_ascii, YR_SHA1_LEN);
YR_DEBUG_FPRINTF(2, stderr, "+ %s() {} = 0x%s // s->length=%u\n",
__FUNCTION__, digest_ascii, s->length);
YR_DEBUG_FPRINTF(
2,
stderr,
"+ %s() {} = 0x%s // s->length=%u\n",
__FUNCTION__,
digest_ascii,
s->length);
return_string(digest_ascii);
}
@@ -232,11 +252,15 @@ define_function(string_checksum32)
SIZED_STRING* s = sized_string_argument(1);
uint32_t checksum = 0;
for (i = 0; i < s->length; i++)
checksum += (uint8_t)(s->c_string[i]);
for (i = 0; i < s->length; i++) checksum += (uint8_t)(s->c_string[i]);
YR_DEBUG_FPRINTF(2, stderr, "+ %s() {} = 0x%x // s->length=%u\n",
__FUNCTION__, checksum, s->length);
YR_DEBUG_FPRINTF(
2,
stderr,
"+ %s() {} = 0x%x // s->length=%u\n",
__FUNCTION__,
checksum,
s->length);
return_integer(checksum);
}
@@ -256,18 +280,24 @@ define_function(data_md5)
YR_MEMORY_BLOCK* block = first_memory_block(context);
YR_MEMORY_BLOCK_ITERATOR* iterator = context->iterator;
int64_t arg_offset = integer_argument(1); // offset where to start
int64_t arg_length = integer_argument(2); // length of bytes we want hash on
int64_t arg_offset = integer_argument(1); // offset where to start
int64_t arg_length = integer_argument(2); // length of bytes we want hash on
int64_t offset = arg_offset;
int64_t length = arg_length;
YR_DEBUG_FPRINTF(2, stderr, "+ %s(offset=%" PRIi64 " length=%" PRIi64 ") {\n",
__FUNCTION__, offset, length);
YR_DEBUG_FPRINTF(
2,
stderr,
"+ %s(offset=%" PRIi64 " length=%" PRIi64 ") {\n",
__FUNCTION__,
offset,
length);
if (block == NULL)
{
YR_DEBUG_FPRINTF(2, stderr, "} // %s() = YR_UNDEFINED // block == NULL\n", __FUNCTION__);
YR_DEBUG_FPRINTF(
2, stderr, "} // %s() = YR_UNDEFINED // block == NULL\n", __FUNCTION__);
return_string(YR_UNDEFINED);
}
@@ -275,16 +305,24 @@ define_function(data_md5)
if (offset < 0 || length < 0 || offset < block->base)
{
YR_DEBUG_FPRINTF(2, stderr, "} // %s() = YR_UNDEFINED // bad offset / length\n", __FUNCTION__);
YR_DEBUG_FPRINTF(
2,
stderr,
"} // %s() = YR_UNDEFINED // bad offset / length\n",
__FUNCTION__);
return_string(YR_UNDEFINED);
}
cached_ascii_digest = get_from_cache(
module(), "md5", arg_offset, arg_length);
cached_ascii_digest = get_from_cache(module(), "md5", arg_offset, arg_length);
if (cached_ascii_digest != NULL)
{
YR_DEBUG_FPRINTF(2, stderr, "} // %s() = %s (cached)\n", __FUNCTION__, cached_ascii_digest);
YR_DEBUG_FPRINTF(
2,
stderr,
"} // %s() = %s (cached)\n",
__FUNCTION__,
cached_ascii_digest);
return_string(cached_ascii_digest);
}
@@ -292,16 +330,15 @@ define_function(data_md5)
{
// if desired block within current block
if (offset >= block->base &&
offset < block->base + block->size)
if (offset >= block->base && offset < block->base + block->size)
{
const uint8_t* block_data = block->fetch_data(block);
if (block_data != NULL)
{
size_t data_offset = (size_t) (offset - block->base);
size_t data_offset = (size_t)(offset - block->base);
size_t data_len = (size_t) yr_min(
length, (size_t) (block->size - data_offset));
length, (size_t)(block->size - data_offset));
offset += data_len;
length -= data_len;
@@ -319,7 +356,11 @@ define_function(data_md5)
// range contains gaps of undefined data the checksum is
// undefined.
YR_DEBUG_FPRINTF(2, stderr, "} // %s() = YR_UNDEFINED // past_first_block\n", __FUNCTION__);
YR_DEBUG_FPRINTF(
2,
stderr,
"} // %s() = YR_UNDEFINED // past_first_block\n",
__FUNCTION__);
return_string(YR_UNDEFINED);
}
@@ -329,7 +370,11 @@ define_function(data_md5)
if (!past_first_block)
{
YR_DEBUG_FPRINTF(2, stderr, "} // %s() = YR_UNDEFINED // !past_first_block\n", __FUNCTION__);
YR_DEBUG_FPRINTF(
2,
stderr,
"} // %s() = YR_UNDEFINED // !past_first_block\n",
__FUNCTION__);
return_string(YR_UNDEFINED);
}
@@ -355,8 +400,8 @@ define_function(data_sha1)
int past_first_block = false;
int64_t arg_offset = integer_argument(1); // offset where to start
int64_t arg_length = integer_argument(2); // length of bytes we want hash on
int64_t arg_offset = integer_argument(1); // offset where to start
int64_t arg_length = integer_argument(2); // length of bytes we want hash on
int64_t offset = arg_offset;
int64_t length = arg_length;
@@ -365,12 +410,18 @@ define_function(data_sha1)
YR_MEMORY_BLOCK* block = first_memory_block(context);
YR_MEMORY_BLOCK_ITERATOR* iterator = context->iterator;
YR_DEBUG_FPRINTF(2, stderr, "+ %s(offset=%" PRIi64 " length=%" PRIi64 ") {\n",
__FUNCTION__, offset, length);
YR_DEBUG_FPRINTF(
2,
stderr,
"+ %s(offset=%" PRIi64 " length=%" PRIi64 ") {\n",
__FUNCTION__,
offset,
length);
if (block == NULL)
{
YR_DEBUG_FPRINTF(2, stderr, "} // %s() = YR_UNDEFINED // block == NULL\n", __FUNCTION__);
YR_DEBUG_FPRINTF(
2, stderr, "} // %s() = YR_UNDEFINED // block == NULL\n", __FUNCTION__);
return_string(YR_UNDEFINED);
}
@@ -378,7 +429,11 @@ define_function(data_sha1)
if (offset < 0 || length < 0 || offset < block->base)
{
YR_DEBUG_FPRINTF(2, stderr, "} // %s() = YR_UNDEFINED // bad offset / length\n", __FUNCTION__);
YR_DEBUG_FPRINTF(
2,
stderr,
"} // %s() = YR_UNDEFINED // bad offset / length\n",
__FUNCTION__);
return_string(YR_UNDEFINED);
}
@@ -387,23 +442,27 @@ define_function(data_sha1)
if (cached_ascii_digest != NULL)
{
YR_DEBUG_FPRINTF(2, stderr, "} // %s() = %s (cached)\n", __FUNCTION__, cached_ascii_digest);
YR_DEBUG_FPRINTF(
2,
stderr,
"} // %s() = %s (cached)\n",
__FUNCTION__,
cached_ascii_digest);
return_string(cached_ascii_digest);
}
foreach_memory_block(iterator, block)
{
// if desired block within current block
if (offset >= block->base &&
offset < block->base + block->size)
if (offset >= block->base && offset < block->base + block->size)
{
const uint8_t* block_data = block->fetch_data(block);
if (block_data != NULL)
{
size_t data_offset = (size_t) (offset - block->base);
size_t data_offset = (size_t)(offset - block->base);
size_t data_len = (size_t) yr_min(
length, (size_t) block->size - data_offset);
length, (size_t) block->size - data_offset);
offset += data_len;
length -= data_len;
@@ -421,7 +480,11 @@ define_function(data_sha1)
// range contains gaps of undefined data the checksum is
// undefined.
YR_DEBUG_FPRINTF(2, stderr, "} // %s() = YR_UNDEFINED // past_first_block\n", __FUNCTION__);
YR_DEBUG_FPRINTF(
2,
stderr,
"} // %s() = YR_UNDEFINED // past_first_block\n",
__FUNCTION__);
return_string(YR_UNDEFINED);
}
@@ -431,7 +494,11 @@ define_function(data_sha1)
if (!past_first_block)
{
YR_DEBUG_FPRINTF(2, stderr, "} // %s() = YR_UNDEFINED // !past_first_block\n", __FUNCTION__);
YR_DEBUG_FPRINTF(
2,
stderr,
"} // %s() = YR_UNDEFINED // !past_first_block\n",
__FUNCTION__);
return_string(YR_UNDEFINED);
}
@@ -457,8 +524,8 @@ define_function(data_sha256)
int past_first_block = false;
int64_t arg_offset = integer_argument(1); // offset where to start
int64_t arg_length = integer_argument(2); // length of bytes we want hash on
int64_t arg_offset = integer_argument(1); // offset where to start
int64_t arg_length = integer_argument(2); // length of bytes we want hash on
int64_t offset = arg_offset;
int64_t length = arg_length;
@@ -467,12 +534,18 @@ define_function(data_sha256)
YR_MEMORY_BLOCK* block = first_memory_block(context);
YR_MEMORY_BLOCK_ITERATOR* iterator = context->iterator;
YR_DEBUG_FPRINTF(2, stderr, "+ %s(offset=%" PRIi64 " length=%" PRIi64 ") {\n",
__FUNCTION__, offset, length);
YR_DEBUG_FPRINTF(
2,
stderr,
"+ %s(offset=%" PRIi64 " length=%" PRIi64 ") {\n",
__FUNCTION__,
offset,
length);
if (block == NULL)
{
YR_DEBUG_FPRINTF(2, stderr, "} // %s() = YR_UNDEFINED // block == NULL\n", __FUNCTION__);
YR_DEBUG_FPRINTF(
2, stderr, "} // %s() = YR_UNDEFINED // block == NULL\n", __FUNCTION__);
return_string(YR_UNDEFINED);
}
@@ -480,7 +553,11 @@ define_function(data_sha256)
if (offset < 0 || length < 0 || offset < block->base)
{
YR_DEBUG_FPRINTF(2, stderr, "} // %s() = YR_UNDEFINED // bad offset / length\n", __FUNCTION__);
YR_DEBUG_FPRINTF(
2,
stderr,
"} // %s() = YR_UNDEFINED // bad offset / length\n",
__FUNCTION__);
return_string(YR_UNDEFINED);
}
@@ -489,21 +566,25 @@ define_function(data_sha256)
if (cached_ascii_digest != NULL)
{
YR_DEBUG_FPRINTF(2, stderr, "} // %s() = %s (cached)\n", __FUNCTION__, cached_ascii_digest);
YR_DEBUG_FPRINTF(
2,
stderr,
"} // %s() = %s (cached)\n",
__FUNCTION__,
cached_ascii_digest);
return_string(cached_ascii_digest);
}
foreach_memory_block(iterator, block)
{
// if desired block within current block
if (offset >= block->base &&
offset < block->base + block->size)
if (offset >= block->base && offset < block->base + block->size)
{
const uint8_t* block_data = block->fetch_data(block);
if (block_data != NULL)
{
size_t data_offset = (size_t) (offset - block->base);
size_t data_offset = (size_t)(offset - block->base);
size_t data_len = (size_t) yr_min(length, block->size - data_offset);
offset += data_len;
@@ -522,7 +603,11 @@ define_function(data_sha256)
// range contains gaps of undefined data the checksum is
// undefined.
YR_DEBUG_FPRINTF(2, stderr, "} // %s() = YR_UNDEFINED // past_first_block\n", __FUNCTION__);
YR_DEBUG_FPRINTF(
2,
stderr,
"} // %s() = YR_UNDEFINED // past_first_block\n",
__FUNCTION__);
return_string(YR_UNDEFINED);
}
@@ -532,7 +617,11 @@ define_function(data_sha256)
if (!past_first_block)
{
YR_DEBUG_FPRINTF(2, stderr, "} // %s() = YR_UNDEFINED // !past_first_block\n", __FUNCTION__);
YR_DEBUG_FPRINTF(
2,
stderr,
"} // %s() = YR_UNDEFINED // !past_first_block\n",
__FUNCTION__);
return_string(YR_UNDEFINED);
}
@@ -550,11 +639,16 @@ define_function(data_sha256)
define_function(data_checksum32)
{
int64_t offset = integer_argument(1); // offset where to start
int64_t length = integer_argument(2); // length of bytes we want hash on
int64_t offset = integer_argument(1); // offset where to start
int64_t length = integer_argument(2); // length of bytes we want hash on
YR_DEBUG_FPRINTF(2, stderr, "+ %s(offset=%" PRIi64 " length=%" PRIi64 ") {\n",
__FUNCTION__, offset, length);
YR_DEBUG_FPRINTF(
2,
stderr,
"+ %s(offset=%" PRIi64 " length=%" PRIi64 ") {\n",
__FUNCTION__,
offset,
length);
YR_SCAN_CONTEXT* context = scan_context();
YR_MEMORY_BLOCK* block = first_memory_block(context);
@@ -571,8 +665,7 @@ define_function(data_checksum32)
foreach_memory_block(iterator, block)
{
if (offset >= block->base &&
offset < block->base + block->size)
if (offset >= block->base && offset < block->base + block->size)
{
const uint8_t* block_data = block->fetch_data(block);
@@ -580,7 +673,7 @@ define_function(data_checksum32)
{
size_t i;
size_t data_offset = (size_t) (offset - block->base);
size_t data_offset = (size_t)(offset - block->base);
size_t data_len = (size_t) yr_min(length, block->size - data_offset);
offset += data_len;
@@ -622,10 +715,16 @@ define_function(string_crc32)
uint32_t checksum = 0xFFFFFFFF;
for (i = 0; i < s->length; i++)
checksum = crc32_tab[(checksum ^ (uint8_t)s->c_string[i]) & 0xFF] ^ (checksum >> 8);
checksum = crc32_tab[(checksum ^ (uint8_t) s->c_string[i]) & 0xFF] ^
(checksum >> 8);
YR_DEBUG_FPRINTF(2, stderr, "+ %s() {} = 0x%x // s->length=%u\n",
__FUNCTION__, checksum ^ 0xFFFFFFFF, s->length);
YR_DEBUG_FPRINTF(
2,
stderr,
"+ %s() {} = 0x%x // s->length=%u\n",
__FUNCTION__,
checksum ^ 0xFFFFFFFF,
s->length);
return_integer(checksum ^ 0xFFFFFFFF);
}
@@ -633,16 +732,21 @@ define_function(string_crc32)
define_function(data_crc32)
{
int64_t offset = integer_argument(1); // offset where to start
int64_t length = integer_argument(2); // length of bytes we want hash on
int64_t offset = integer_argument(1); // offset where to start
int64_t length = integer_argument(2); // length of bytes we want hash on
uint32_t checksum = 0xFFFFFFFF;
YR_SCAN_CONTEXT* context = scan_context();
YR_MEMORY_BLOCK* block = first_memory_block(context);
YR_MEMORY_BLOCK_ITERATOR* iterator = context->iterator;
YR_DEBUG_FPRINTF(2, stderr, "+ %s(offset=%" PRIi64 " length=%" PRIi64 ") {\n",
__FUNCTION__, offset, length);
YR_DEBUG_FPRINTF(
2,
stderr,
"+ %s(offset=%" PRIi64 " length=%" PRIi64 ") {\n",
__FUNCTION__,
offset,
length);
int past_first_block = false;
@@ -654,8 +758,7 @@ define_function(data_crc32)
foreach_memory_block(iterator, block)
{
if (offset >= block->base &&
offset < block->base + block->size)
if (offset >= block->base && offset < block->base + block->size)
{
const uint8_t* block_data = block->fetch_data(block);
@@ -663,14 +766,16 @@ define_function(data_crc32)
{
size_t i;
size_t data_offset = (size_t) (offset - block->base);
size_t data_offset = (size_t)(offset - block->base);
size_t data_len = (size_t) yr_min(length, block->size - data_offset);
offset += data_len;
length -= data_len;
for (i = 0; i < data_len; i++)
checksum = crc32_tab[(checksum ^ *(block_data + data_offset + i)) & 0xFF] ^ (checksum >> 8);
checksum =
crc32_tab[(checksum ^ *(block_data + data_offset + i)) & 0xFF] ^
(checksum >> 8);
}
past_first_block = true;
@@ -693,14 +798,13 @@ define_function(data_crc32)
if (!past_first_block)
return_integer(YR_UNDEFINED);
YR_DEBUG_FPRINTF(2, stderr, "} // %s() = 0x%x\n", __FUNCTION__, checksum ^ 0xFFFFFFFF);
YR_DEBUG_FPRINTF(
2, stderr, "} // %s() = 0x%x\n", __FUNCTION__, checksum ^ 0xFFFFFFFF);
return_integer(checksum ^ 0xFFFFFFFF);
}
begin_declarations;
begin_declarations
declare_function("md5", "ii", "s", data_md5);
declare_function("md5", "s", "s", string_md5);
@@ -715,12 +819,10 @@ begin_declarations;
declare_function("crc32", "ii", "i", data_crc32);
declare_function("crc32", "s", "i", string_crc32);
end_declarations;
end_declarations
int module_initialize(
YR_MODULE* module)
int module_initialize(YR_MODULE* module)
{
YR_DEBUG_FPRINTF(2, stderr, "+ %s() {}\n", __FUNCTION__);
@@ -728,8 +830,7 @@ int module_initialize(
}
int module_finalize(
YR_MODULE* module)
int module_finalize(YR_MODULE* module)
{
YR_DEBUG_FPRINTF(2, stderr, "+ %s() {}\n", __FUNCTION__);
@@ -755,17 +856,14 @@ int module_load(
}
int module_unload(
YR_OBJECT* module_object)
int module_unload(YR_OBJECT* module_object)
{
YR_DEBUG_FPRINTF(2, stderr, "+ %s() {}\n", __FUNCTION__);
YR_HASH_TABLE* hash_table = (YR_HASH_TABLE*) module_object->data;
if (hash_table != NULL)
yr_hash_table_destroy(
hash_table,
(YR_HASH_TABLE_FREE_VALUE_FUNC) yr_free);
yr_hash_table_destroy(hash_table, (YR_HASH_TABLE_FREE_VALUE_FUNC) yr_free);
return ERROR_SUCCESS;
}
+210 -248
View File
@@ -27,30 +27,26 @@ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <yara/macho.h>
#include <yara/endian.h>
#include <yara/modules.h>
#include <yara/macho.h>
#include <yara/mem.h>
#include <yara/modules.h>
#define MODULE_NAME macho
// Check for Mach-O binary magic constant.
int is_macho_file_block(
const uint32_t* magic)
int is_macho_file_block(const uint32_t* magic)
{
return *magic == MH_MAGIC
|| *magic == MH_CIGAM
|| *magic == MH_MAGIC_64
|| *magic == MH_CIGAM_64;
return *magic == MH_MAGIC || *magic == MH_CIGAM || *magic == MH_MAGIC_64 ||
*magic == MH_CIGAM_64;
}
// Check if file is for 32-bit architecture.
int macho_is_32(
const uint8_t* magic)
int macho_is_32(const uint8_t* magic)
{
// Magic must be [CE]FAEDFE or FEEDFA[CE].
return magic[0] == 0xce || magic[3] == 0xce;
@@ -59,8 +55,7 @@ int macho_is_32(
// Check if file is for big-endian architecture.
int macho_is_big(
const uint8_t* magic)
int macho_is_big(const uint8_t* magic)
{
// Magic must be [FE]EDFACE or [FE]EDFACF.
return magic[0] == 0xfe;
@@ -69,37 +64,29 @@ int macho_is_big(
// Check for Mach-O fat binary magic constant.
int is_fat_macho_file_block(
const uint32_t* magic)
int is_fat_macho_file_block(const uint32_t* magic)
{
return *magic == FAT_MAGIC
|| *magic == FAT_CIGAM
|| *magic == FAT_MAGIC_64
|| *magic == FAT_CIGAM_64;
return *magic == FAT_MAGIC || *magic == FAT_CIGAM || *magic == FAT_MAGIC_64 ||
*magic == FAT_CIGAM_64;
}
// Check if file is 32-bit fat file.
int macho_fat_is_32(
const uint8_t* magic)
int macho_fat_is_32(const uint8_t* magic)
{
// Magic must be CAFEBA[BE].
return magic[3] == 0xbe;
}
static int should_swap_bytes(
const uint32_t magic)
static int should_swap_bytes(const uint32_t magic)
{
return magic == MH_CIGAM
|| magic == MH_CIGAM_64
|| magic == FAT_CIGAM
|| magic == FAT_CIGAM_64;
return magic == MH_CIGAM || magic == MH_CIGAM_64 || magic == FAT_CIGAM ||
magic == FAT_CIGAM_64;
}
static void swap_mach_header(
yr_mach_header_64_t *mh)
static void swap_mach_header(yr_mach_header_64_t* mh)
{
// Don't swap the magic number so we can tell if swapping is needed
mh->cputype = yr_bswap32(mh->cputype);
@@ -114,14 +101,14 @@ static void swap_mach_header(
}
static void swap_load_command(yr_load_command_t *lc)
static void swap_load_command(yr_load_command_t* lc)
{
lc->cmd = yr_bswap32(lc->cmd);
lc->cmdsize = yr_bswap32(lc->cmdsize);
}
static void swap_segment_command(yr_segment_command_32_t *sg)
static void swap_segment_command(yr_segment_command_32_t* sg)
{
sg->cmd = yr_bswap32(sg->cmd);
sg->cmdsize = yr_bswap32(sg->cmdsize);
@@ -136,7 +123,7 @@ static void swap_segment_command(yr_segment_command_32_t *sg)
}
static void swap_segment_command_64(yr_segment_command_64_t *sg)
static void swap_segment_command_64(yr_segment_command_64_t* sg)
{
sg->cmd = yr_bswap32(sg->cmd);
sg->cmdsize = yr_bswap32(sg->cmdsize);
@@ -151,7 +138,7 @@ static void swap_segment_command_64(yr_segment_command_64_t *sg)
}
static void swap_section(yr_section_32_t *sec)
static void swap_section(yr_section_32_t* sec)
{
sec->addr = yr_bswap32(sec->addr);
sec->size = yr_bswap32(sec->size);
@@ -165,7 +152,7 @@ static void swap_section(yr_section_32_t *sec)
}
static void swap_section_64(yr_section_64_t *sec)
static void swap_section_64(yr_section_64_t* sec)
{
sec->addr = yr_bswap64(sec->addr);
sec->size = yr_bswap64(sec->size);
@@ -190,10 +177,7 @@ static void swap_entry_point_command(yr_entry_point_command_t* ep_command)
// Convert virtual address to file offset. Segments have to be already loaded.
bool macho_rva_to_offset(
uint64_t address,
uint64_t* result,
YR_OBJECT* object)
bool macho_rva_to_offset(uint64_t address, uint64_t* result, YR_OBJECT* object)
{
uint64_t segment_count = get_integer(object, "number_of_segments");
@@ -216,10 +200,7 @@ bool macho_rva_to_offset(
// Convert file offset to virtual address. Segments have to be already loaded.
int macho_offset_to_rva(
uint64_t offset,
uint64_t* result,
YR_OBJECT* object)
int macho_offset_to_rva(uint64_t offset, uint64_t* result, YR_OBJECT* object)
{
uint64_t segment_count = get_integer(object, "number_of_segments");
@@ -249,71 +230,71 @@ void macho_handle_unixthread(
{
int should_swap = should_swap_bytes(get_integer(object, "magic"));
bool is64 = false;
command = (void*)((uint8_t*)command + sizeof(yr_thread_command_t));
command = (void*) ((uint8_t*) command + sizeof(yr_thread_command_t));
uint64_t address = 0;
switch (get_integer(object, "cputype"))
{
case CPU_TYPE_MC680X0:
{
yr_m68k_thread_state_t* m68k_state = (yr_m68k_thread_state_t*)command;
address = m68k_state->pc;
break;
}
case CPU_TYPE_MC88000:
{
yr_m88k_thread_state_t* m88k_state = (yr_m88k_thread_state_t*)command;
address = m88k_state->xip;
break;
}
case CPU_TYPE_SPARC:
{
yr_sparc_thread_state_t* sparc_state = (yr_sparc_thread_state_t*)command;
address = sparc_state->pc;
break;
}
case CPU_TYPE_POWERPC:
{
yr_ppc_thread_state_t* ppc_state = (yr_ppc_thread_state_t*)command;
address = ppc_state->srr0;
break;
}
case CPU_TYPE_X86:
{
yr_x86_thread_state_t* x86_state = (yr_x86_thread_state_t*)command;
address = x86_state->eip;
break;
}
case CPU_TYPE_ARM:
{
yr_arm_thread_state_t* arm_state = (yr_arm_thread_state_t*)command;
address = arm_state->pc;
break;
}
case CPU_TYPE_X86_64:
{
yr_x86_thread_state64_t* x64_state = (yr_x86_thread_state64_t*)command;
address = x64_state->rip;
is64 = true;
break;
}
case CPU_TYPE_ARM64:
{
yr_arm_thread_state64_t* arm64_state = (yr_arm_thread_state64_t*)command;
address = arm64_state->pc;
is64 = true;
break;
}
case CPU_TYPE_POWERPC64:
{
yr_ppc_thread_state64_t* ppc64_state = (yr_ppc_thread_state64_t*)command;
address = ppc64_state->srr0;
is64 = true;
break;
}
case CPU_TYPE_MC680X0:
{
yr_m68k_thread_state_t* m68k_state = (yr_m68k_thread_state_t*) command;
address = m68k_state->pc;
break;
}
case CPU_TYPE_MC88000:
{
yr_m88k_thread_state_t* m88k_state = (yr_m88k_thread_state_t*) command;
address = m88k_state->xip;
break;
}
case CPU_TYPE_SPARC:
{
yr_sparc_thread_state_t* sparc_state = (yr_sparc_thread_state_t*) command;
address = sparc_state->pc;
break;
}
case CPU_TYPE_POWERPC:
{
yr_ppc_thread_state_t* ppc_state = (yr_ppc_thread_state_t*) command;
address = ppc_state->srr0;
break;
}
case CPU_TYPE_X86:
{
yr_x86_thread_state_t* x86_state = (yr_x86_thread_state_t*) command;
address = x86_state->eip;
break;
}
case CPU_TYPE_ARM:
{
yr_arm_thread_state_t* arm_state = (yr_arm_thread_state_t*) command;
address = arm_state->pc;
break;
}
case CPU_TYPE_X86_64:
{
yr_x86_thread_state64_t* x64_state = (yr_x86_thread_state64_t*) command;
address = x64_state->rip;
is64 = true;
break;
}
case CPU_TYPE_ARM64:
{
yr_arm_thread_state64_t* arm64_state = (yr_arm_thread_state64_t*) command;
address = arm64_state->pc;
is64 = true;
break;
}
case CPU_TYPE_POWERPC64:
{
yr_ppc_thread_state64_t* ppc64_state = (yr_ppc_thread_state64_t*) command;
address = ppc64_state->srr0;
is64 = true;
break;
}
default:
return;
default:
return;
}
if (should_swap)
@@ -372,7 +353,7 @@ void macho_handle_main(
// Load segment and its sections.
void macho_handle_segment(
const uint8_t *command,
const uint8_t* command,
const unsigned i,
YR_OBJECT* object)
{
@@ -383,8 +364,8 @@ void macho_handle_segment(
if (should_swap)
swap_segment_command(&sg);
set_sized_string(sg.segname, strnlen(sg.segname, 16),
object, "segments[%i].segname", i);
set_sized_string(
sg.segname, strnlen(sg.segname, 16), object, "segments[%i].segname", i);
set_integer(sg.vmaddr, object, "segments[%i].vmaddr", i);
set_integer(sg.vmsize, object, "segments[%i].vmsize", i);
@@ -404,42 +385,44 @@ void macho_handle_segment(
if (sg.cmdsize < parsed_size)
break;
memcpy(&sec,
command + sizeof(yr_segment_command_32_t) + (j * sizeof(yr_section_32_t)),
sizeof(yr_section_32_t));
memcpy(
&sec,
command + sizeof(yr_segment_command_32_t) +
(j * sizeof(yr_section_32_t)),
sizeof(yr_section_32_t));
if (should_swap)
swap_section(&sec);
set_sized_string(
sec.segname, strnlen(sec.segname, 16), object,
"segments[%i].sections[%i].segname", i, j);
sec.segname,
strnlen(sec.segname, 16),
object,
"segments[%i].sections[%i].segname",
i,
j);
set_sized_string(
sec.sectname, strnlen(sec.sectname, 16), object,
"segments[%i].sections[%i].sectname", i, j);
sec.sectname,
strnlen(sec.sectname, 16),
object,
"segments[%i].sections[%i].sectname",
i,
j);
set_integer(
sec.addr, object,
"segments[%i].sections[%i].addr", i, j);
set_integer(sec.addr, object, "segments[%i].sections[%i].addr", i, j);
set_integer(
sec.size, object, "segments[%i].sections[%i].size", i, j);
set_integer(sec.size, object, "segments[%i].sections[%i].size", i, j);
set_integer(
sec.offset, object, "segments[%i].sections[%i].offset", i, j);
set_integer(sec.offset, object, "segments[%i].sections[%i].offset", i, j);
set_integer(
sec.align, object, "segments[%i].sections[%i].align", i, j);
set_integer(sec.align, object, "segments[%i].sections[%i].align", i, j);
set_integer(
sec.reloff, object, "segments[%i].sections[%i].reloff", i, j);
set_integer(sec.reloff, object, "segments[%i].sections[%i].reloff", i, j);
set_integer(
sec.nreloc, object, "segments[%i].sections[%i].nreloc", i, j);
set_integer(sec.nreloc, object, "segments[%i].sections[%i].nreloc", i, j);
set_integer(
sec.flags, object, "segments[%i].sections[%i].flags", i, j);
set_integer(sec.flags, object, "segments[%i].sections[%i].flags", i, j);
set_integer(
sec.reserved1, object, "segments[%i].sections[%i].reserved1", i, j);
@@ -450,7 +433,7 @@ void macho_handle_segment(
}
void macho_handle_segment_64(
const uint8_t *command,
const uint8_t* command,
const unsigned i,
YR_OBJECT* object)
{
@@ -461,8 +444,8 @@ void macho_handle_segment_64(
if (should_swap)
swap_segment_command_64(&sg);
set_sized_string(sg.segname, strnlen(sg.segname, 16),
object, "segments[%i].segname", i);
set_sized_string(
sg.segname, strnlen(sg.segname, 16), object, "segments[%i].segname", i);
set_integer(sg.vmaddr, object, "segments[%i].vmaddr", i);
set_integer(sg.vmsize, object, "segments[%i].vmsize", i);
@@ -481,41 +464,44 @@ void macho_handle_segment_64(
if (sg.cmdsize < parsed_size)
break;
memcpy(&sec,
command + sizeof(yr_segment_command_64_t) + (j * sizeof(yr_section_64_t)),
sizeof(yr_section_64_t));
memcpy(
&sec,
command + sizeof(yr_segment_command_64_t) +
(j * sizeof(yr_section_64_t)),
sizeof(yr_section_64_t));
if (should_swap)
swap_section_64(&sec);
set_sized_string(
sec.segname, strnlen(sec.segname, 16), object,
"segments[%i].sections[%i].segname", i, j);
sec.segname,
strnlen(sec.segname, 16),
object,
"segments[%i].sections[%i].segname",
i,
j);
set_sized_string(
sec.sectname, strnlen(sec.sectname, 16), object,
"segments[%i].sections[%i].sectname", i, j);
sec.sectname,
strnlen(sec.sectname, 16),
object,
"segments[%i].sections[%i].sectname",
i,
j);
set_integer(
sec.addr, object, "segments[%i].sections[%i].addr", i, j);
set_integer(sec.addr, object, "segments[%i].sections[%i].addr", i, j);
set_integer(
sec.size, object, "segments[%i].sections[%i].size", i, j);
set_integer(sec.size, object, "segments[%i].sections[%i].size", i, j);
set_integer(
sec.offset, object, "segments[%i].sections[%i].offset", i, j);
set_integer(sec.offset, object, "segments[%i].sections[%i].offset", i, j);
set_integer(
sec.align, object, "segments[%i].sections[%i].align", i, j);
set_integer(sec.align, object, "segments[%i].sections[%i].align", i, j);
set_integer(
sec.reloff, object, "segments[%i].sections[%i].reloff", i, j);
set_integer(sec.reloff, object, "segments[%i].sections[%i].reloff", i, j);
set_integer(
sec.nreloc, object, "segments[%i].sections[%i].nreloc", i, j);
set_integer(sec.nreloc, object, "segments[%i].sections[%i].nreloc", i, j);
set_integer(
sec.flags, object, "segments[%i].sections[%i].flags", i, j);
set_integer(sec.flags, object, "segments[%i].sections[%i].flags", i, j);
set_integer(
sec.reserved1, object, "segments[%i].sections[%i].reserved1", i, j);
@@ -537,9 +523,8 @@ void macho_parse_file(
YR_OBJECT* object,
YR_SCAN_CONTEXT* context)
{
size_t header_size = macho_is_32(data)?
sizeof(yr_mach_header_32_t):
sizeof(yr_mach_header_64_t);
size_t header_size = macho_is_32(data) ? sizeof(yr_mach_header_32_t)
: sizeof(yr_mach_header_64_t);
if (size < header_size)
return;
@@ -572,7 +557,7 @@ void macho_parse_file(
uint64_t seg_count = 0;
uint64_t parsed_size = header_size;
uint8_t *command = (uint8_t*)(data + header_size);
uint8_t* command = (uint8_t*) (data + header_size);
yr_load_command_t command_struct;
@@ -586,18 +571,18 @@ void macho_parse_file(
if (size < header_size + command_struct.cmdsize)
break;
switch(command_struct.cmd)
switch (command_struct.cmd)
{
case LC_SEGMENT:
{
macho_handle_segment(command, seg_count++, object);
break;
}
case LC_SEGMENT_64:
{
macho_handle_segment_64(command, seg_count++, object);
break;
}
case LC_SEGMENT:
{
macho_handle_segment(command, seg_count++, object);
break;
}
case LC_SEGMENT_64:
{
macho_handle_segment_64(command, seg_count++, object);
break;
}
}
command += command_struct.cmdsize;
@@ -608,7 +593,7 @@ void macho_parse_file(
// The second command parsing pass handles others, who use segment count.
parsed_size = header_size;
command = (uint8_t*)(data + header_size);
command = (uint8_t*) (data + header_size);
for (unsigned i = 0; i < header.ncmds; i++)
{
@@ -620,18 +605,18 @@ void macho_parse_file(
if (size < header_size + command_struct.cmdsize)
break;
switch(command_struct.cmd)
switch (command_struct.cmd)
{
case LC_UNIXTHREAD:
{
macho_handle_unixthread(command, object, context);
break;
}
case LC_MAIN:
{
macho_handle_main(command, object, context);
break;
}
case LC_UNIXTHREAD:
{
macho_handle_unixthread(command, object, context);
break;
}
case LC_MAIN:
{
macho_handle_main(command, object, context);
break;
}
}
command += command_struct.cmdsize;
@@ -648,10 +633,10 @@ void macho_load_fat_arch_header(
uint32_t num,
yr_fat_arch_64_t* arch)
{
if (macho_fat_is_32(data)) {
if (macho_fat_is_32(data))
{
yr_fat_arch_32_t* arch32 =
(yr_fat_arch_32_t*)(data + sizeof(yr_fat_header_t) +
(num * sizeof(yr_fat_arch_32_t)));
(yr_fat_arch_32_t*) (data + sizeof(yr_fat_header_t) + (num * sizeof(yr_fat_arch_32_t)));
arch->cputype = yr_be32toh(arch32->cputype);
arch->cpusubtype = yr_be32toh(arch32->cpusubtype);
arch->offset = yr_be32toh(arch32->offset);
@@ -659,10 +644,10 @@ void macho_load_fat_arch_header(
arch->align = yr_be32toh(arch32->align);
arch->reserved = 0;
}
else {
else
{
yr_fat_arch_64_t* arch64 =
(yr_fat_arch_64_t*)(data + sizeof(yr_fat_header_t) +
(num * sizeof(yr_fat_arch_64_t)));
(yr_fat_arch_64_t*) (data + sizeof(yr_fat_header_t) + (num * sizeof(yr_fat_arch_64_t)));
arch->cputype = yr_be32toh(arch64->cputype);
arch->cpusubtype = yr_be32toh(arch64->cpusubtype);
arch->offset = yr_be64toh(arch64->offset);
@@ -711,22 +696,24 @@ void macho_parse_fat_file(
set_integer(arch.reserved, object, "fat_arch[%i].reserved", i);
if (size < arch.offset + arch.size)
continue;
continue;
/* Force 'file' array entry creation. */
set_integer(YR_UNDEFINED, object, "file[%i].magic", i);
/* Get specific Mach-O file data. */
macho_parse_file(data + arch.offset, arch.size,
get_object(object, "file[%i]", i), context);
macho_parse_file(
data + arch.offset,
arch.size,
get_object(object, "file[%i]", i),
context);
}
}
// Sets all necessary Mach-O constants and definitions.
void macho_set_definitions(
YR_OBJECT* object)
void macho_set_definitions(YR_OBJECT* object)
{
// Magic constants
@@ -764,11 +751,11 @@ void macho_set_definitions(
// CPU sub-types
set_integer(CPU_SUBTYPE_INTEL_MODEL_ALL, object,
"CPU_SUBTYPE_INTEL_MODEL_ALL");
set_integer(CPU_SUBTYPE_386, object,"CPU_SUBTYPE_386");
set_integer(CPU_SUBTYPE_386, object,"CPU_SUBTYPE_I386_ALL");
set_integer(CPU_SUBTYPE_386, object,"CPU_SUBTYPE_X86_64_ALL");
set_integer(
CPU_SUBTYPE_INTEL_MODEL_ALL, object, "CPU_SUBTYPE_INTEL_MODEL_ALL");
set_integer(CPU_SUBTYPE_386, object, "CPU_SUBTYPE_386");
set_integer(CPU_SUBTYPE_386, object, "CPU_SUBTYPE_I386_ALL");
set_integer(CPU_SUBTYPE_386, object, "CPU_SUBTYPE_X86_64_ALL");
set_integer(CPU_SUBTYPE_486, object, "CPU_SUBTYPE_486");
set_integer(CPU_SUBTYPE_486SX, object, "CPU_SUBTYPE_486SX");
set_integer(CPU_SUBTYPE_586, object, "CPU_SUBTYPE_586");
@@ -777,12 +764,10 @@ void macho_set_definitions(
set_integer(CPU_SUBTYPE_PENTII_M3, object, "CPU_SUBTYPE_PENTII_M3");
set_integer(CPU_SUBTYPE_PENTII_M5, object, "CPU_SUBTYPE_PENTII_M5");
set_integer(CPU_SUBTYPE_CELERON, object, "CPU_SUBTYPE_CELERON");
set_integer(CPU_SUBTYPE_CELERON_MOBILE, object,
"CPU_SUBTYPE_CELERON_MOBILE");
set_integer(CPU_SUBTYPE_CELERON_MOBILE, object, "CPU_SUBTYPE_CELERON_MOBILE");
set_integer(CPU_SUBTYPE_PENTIUM_3, object, "CPU_SUBTYPE_PENTIUM_3");
set_integer(CPU_SUBTYPE_PENTIUM_3_M, object, "CPU_SUBTYPE_PENTIUM_3_M");
set_integer(CPU_SUBTYPE_PENTIUM_3_XEON, object,
"CPU_SUBTYPE_PENTIUM_3_XEON");
set_integer(CPU_SUBTYPE_PENTIUM_3_XEON, object, "CPU_SUBTYPE_PENTIUM_3_XEON");
set_integer(CPU_SUBTYPE_PENTIUM_M, object, "CPU_SUBTYPE_PENTIUM_M");
set_integer(CPU_SUBTYPE_PENTIUM_4, object, "CPU_SUBTYPE_PENTIUM_4");
set_integer(CPU_SUBTYPE_PENTIUM_4_M, object, "CPU_SUBTYPE_PENTIUM_4_M");
@@ -850,8 +835,7 @@ void macho_set_definitions(
set_integer(MH_NOFIXPREBINDING, object, "MH_NOFIXPREBINDING");
set_integer(MH_PREBINDABLE, object, "MH_PREBINDABLE");
set_integer(MH_ALLMODSBOUND, object, "MH_ALLMODSBOUND");
set_integer(MH_SUBSECTIONS_VIA_SYMBOLS, object,
"MH_SUBSECTIONS_VIA_SYMBOLS");
set_integer(MH_SUBSECTIONS_VIA_SYMBOLS, object, "MH_SUBSECTIONS_VIA_SYMBOLS");
set_integer(MH_CANONICAL, object, "MH_CANONICAL");
set_integer(MH_WEAK_DEFINES, object, "MH_WEAK_DEFINES");
set_integer(MH_BINDS_TO_WEAK, object, "MH_BINDS_TO_WEAK");
@@ -884,8 +868,7 @@ void macho_set_definitions(
set_integer(S_CSTRING_LITERALS, object, "S_CSTRING_LITERALS");
set_integer(S_4BYTE_LITERALS, object, "S_4BYTE_LITERALS");
set_integer(S_8BYTE_LITERALS, object, "S_8BYTE_LITERALS");
set_integer(S_NON_LAZY_SYMBOL_POINTERS, object,
"S_NON_LAZY_SYMBOL_POINTERS");
set_integer(S_NON_LAZY_SYMBOL_POINTERS, object, "S_NON_LAZY_SYMBOL_POINTERS");
set_integer(S_LAZY_SYMBOL_POINTERS, object, "S_LAZY_SYMBOL_POINTERS");
set_integer(S_LITERAL_POINTERS, object, "S_LITERAL_POINTERS");
set_integer(S_SYMBOL_STUBS, object, "S_SYMBOL_STUBS");
@@ -896,15 +879,19 @@ void macho_set_definitions(
set_integer(S_INTERPOSING, object, "S_INTERPOSING");
set_integer(S_16BYTE_LITERALS, object, "S_16BYTE_LITERALS");
set_integer(S_DTRACE_DOF, object, "S_DTRACE_DOF");
set_integer(S_LAZY_DYLIB_SYMBOL_POINTERS, object,
"S_LAZY_DYLIB_SYMBOL_POINTERS");
set_integer(
S_LAZY_DYLIB_SYMBOL_POINTERS, object, "S_LAZY_DYLIB_SYMBOL_POINTERS");
set_integer(S_THREAD_LOCAL_REGULAR, object, "S_THREAD_LOCAL_REGULAR");
set_integer(S_THREAD_LOCAL_ZEROFILL, object, "S_THREAD_LOCAL_ZEROFILL");
set_integer(S_THREAD_LOCAL_VARIABLES, object, "S_THREAD_LOCAL_VARIABLES");
set_integer(S_THREAD_LOCAL_VARIABLE_POINTERS, object,
"S_THREAD_LOCAL_VARIABLE_POINTERS");
set_integer(S_THREAD_LOCAL_INIT_FUNCTION_POINTERS, object,
"S_THREAD_LOCAL_INIT_FUNCTION_POINTERS");
set_integer(
S_THREAD_LOCAL_VARIABLE_POINTERS,
object,
"S_THREAD_LOCAL_VARIABLE_POINTERS");
set_integer(
S_THREAD_LOCAL_INIT_FUNCTION_POINTERS,
object,
"S_THREAD_LOCAL_INIT_FUNCTION_POINTERS");
// Section attributes
@@ -913,8 +900,7 @@ void macho_set_definitions(
set_integer(S_ATTR_STRIP_STATIC_SYMS, object, "S_ATTR_STRIP_STATIC_SYMS");
set_integer(S_ATTR_NO_DEAD_STRIP, object, "S_ATTR_NO_DEAD_STRIP");
set_integer(S_ATTR_LIVE_SUPPORT, object, "S_ATTR_LIVE_SUPPORT");
set_integer(S_ATTR_SELF_MODIFYING_CODE, object,
"S_ATTR_SELF_MODIFYING_CODE");
set_integer(S_ATTR_SELF_MODIFYING_CODE, object, "S_ATTR_SELF_MODIFYING_CODE");
set_integer(S_ATTR_DEBUG, object, "S_ATTR_DEBUG");
set_integer(S_ATTR_SOME_INSTRUCTIONS, object, "S_ATTR_SOME_INSTRUCTIONS");
set_integer(S_ATTR_EXT_RELOC, object, "S_ATTR_EXT_RELOC");
@@ -1023,29 +1009,24 @@ define_function(ep_for_arch_subtype)
}
begin_declarations;
begin_declarations
// Magic constants
declare_integer("MH_MAGIC");
declare_integer("MH_CIGAM");
declare_integer("MH_MAGIC_64");
declare_integer("MH_CIGAM_64");
// Fat magic constants
declare_integer("FAT_MAGIC");
declare_integer("FAT_CIGAM");
declare_integer("FAT_MAGIC_64");
declare_integer("FAT_CIGAM_64");
// 64-bit masks
declare_integer("CPU_ARCH_ABI64");
declare_integer("CPU_SUBTYPE_LIB64");
// CPU types
declare_integer("CPU_TYPE_MC680X0");
declare_integer("CPU_TYPE_X86");
declare_integer("CPU_TYPE_I386");
@@ -1060,7 +1041,6 @@ begin_declarations;
declare_integer("CPU_TYPE_POWERPC64");
// CPU sub-types
declare_integer("CPU_SUBTYPE_INTEL_MODEL_ALL");
declare_integer("CPU_SUBTYPE_386");
declare_integer("CPU_SUBTYPE_I386_ALL");
@@ -1116,7 +1096,6 @@ begin_declarations;
declare_integer("CPU_SUBTYPE_POWERPC_970");
// File types
declare_integer("MH_OBJECT");
declare_integer("MH_EXECUTE");
declare_integer("MH_FVMLIB");
@@ -1130,7 +1109,6 @@ begin_declarations;
declare_integer("MH_KEXT_BUNDLE");
// Header flags
declare_integer("MH_NOUNDEFS");
declare_integer("MH_INCRLINK");
declare_integer("MH_DYLDLINK");
@@ -1159,19 +1137,16 @@ begin_declarations;
declare_integer("MH_APP_EXTENSION_SAFE");
// Segment flags
declare_integer("SG_HIGHVM");
declare_integer("SG_FVMLIB");
declare_integer("SG_NORELOC");
declare_integer("SG_PROTECTED_VERSION_1");
// Section masks
declare_integer("SECTION_TYPE");
declare_integer("SECTION_ATTRIBUTES");
// Section types
declare_integer("S_REGULAR");
declare_integer("S_ZEROFILL");
declare_integer("S_CSTRING_LITERALS");
@@ -1196,7 +1171,6 @@ begin_declarations;
declare_integer("S_THREAD_LOCAL_INIT_FUNCTION_POINTERS");
// Section attributes
declare_integer("S_ATTR_PURE_INSTRUCTIONS");
declare_integer("S_ATTR_NO_TOC");
declare_integer("S_ATTR_STRIP_STATIC_SYMS");
@@ -1209,7 +1183,6 @@ begin_declarations;
declare_integer("S_ATTR_LOC_RELOC");
// Header
declare_integer("magic");
declare_integer("cputype");
declare_integer("cpusubtype");
@@ -1220,10 +1193,9 @@ begin_declarations;
declare_integer("reserved");
// Segments and nested sections
declare_integer("number_of_segments");
begin_struct_array("segments");
begin_struct_array("segments")
declare_string("segname");
declare_integer("vmaddr");
declare_integer("vmsize");
@@ -1233,7 +1205,8 @@ begin_declarations;
declare_integer("initprot");
declare_integer("nsects");
declare_integer("flags");
begin_struct_array("sections");
begin_struct_array("sections")
declare_string("sectname");
declare_string("segname");
declare_integer("addr");
@@ -1247,32 +1220,28 @@ begin_declarations;
declare_integer("reserved2");
declare_integer("reserved3");
end_struct_array("sections");
end_struct_array("segments");
end_struct_array("segments")
// Entry point and stack size
declare_integer("entry_point");
declare_integer("stack_size");
// Mach-O fat binary header
declare_integer("fat_magic");
declare_integer("nfat_arch");
begin_struct_array("fat_arch");
begin_struct_array("fat_arch")
declare_integer("cputype");
declare_integer("cpusubtype");
declare_integer("offset");
declare_integer("size");
declare_integer("align");
end_struct_array("fat_arch");
end_struct_array("fat_arch")
// Included Mach-O files (must be same as single file structure above)
begin_struct_array("file");
begin_struct_array("file")
// Single file header
declare_integer("magic");
declare_integer("cputype");
declare_integer("cpusubtype");
@@ -1283,10 +1252,9 @@ begin_declarations;
declare_integer("reserved");
// Segments and nested sections
declare_integer("number_of_segments");
begin_struct_array("segments");
begin_struct_array("segments")
declare_string("segname");
declare_integer("vmaddr");
declare_integer("vmsize");
@@ -1296,7 +1264,7 @@ begin_declarations;
declare_integer("initprot");
declare_integer("nsects");
declare_integer("flags");
begin_struct_array("sections");
begin_struct_array("sections")
declare_string("sectname");
declare_string("segname");
declare_integer("addr");
@@ -1310,32 +1278,27 @@ begin_declarations;
declare_integer("reserved2");
declare_integer("reserved3");
end_struct_array("sections");
end_struct_array("segments");
end_struct_array("segments")
// Entry point and stack size
declare_integer("entry_point");
declare_integer("stack_size");
end_struct_array("file");
// Mach-O fat binary helper functions
declare_function("file_index_for_arch", "i", "i", file_index_type);
declare_function("file_index_for_arch", "ii", "i", file_index_subtype);
declare_function("entry_point_for_arch", "i", "i", ep_for_arch_type);
declare_function("entry_point_for_arch", "ii", "i", ep_for_arch_subtype);
end_declarations
end_declarations;
int module_initialize(
YR_MODULE* module)
int module_initialize(YR_MODULE* module)
{
return ERROR_SUCCESS;
}
int module_finalize(
YR_MODULE* module)
int module_finalize(YR_MODULE* module)
{
return ERROR_SUCCESS;
}
@@ -1374,8 +1337,7 @@ int module_load(
return ERROR_SUCCESS;
}
int module_unload(
YR_OBJECT* module_object)
int module_unload(YR_OBJECT* module_object)
{
return ERROR_SUCCESS;
}
+11 -20
View File
@@ -33,9 +33,9 @@ The original idea and inspiration for this module comes from Armin Buescher.
*/
#include <magic.h>
#include <yara/mem.h>
#include <yara/modules.h>
#include <magic.h>
#define MODULE_NAME magic
@@ -50,7 +50,7 @@ typedef struct
const char* cached_type;
const char* cached_mime_type;
} MAGIC_CACHE ;
} MAGIC_CACHE;
static int get_cache(MAGIC_CACHE** cache)
@@ -71,8 +71,8 @@ static int get_cache(MAGIC_CACHE** cache)
if (magic_load((*cache)->magic_cookie, NULL) != 0)
{
magic_close((*cache)->magic_cookie);
return ERROR_INTERNAL_FATAL_ERROR;
magic_close((*cache)->magic_cookie);
return ERROR_INTERNAL_FATAL_ERROR;
}
(*cache)->cached_type = NULL;
@@ -108,9 +108,7 @@ define_function(magic_mime_type)
magic_setflags(cache->magic_cookie, MAGIC_MIME_TYPE);
cache->cached_mime_type = magic_buffer(
cache->magic_cookie,
block_data,
block->size);
cache->magic_cookie, block_data, block->size);
}
}
@@ -144,9 +142,7 @@ define_function(magic_type)
magic_setflags(cache->magic_cookie, 0);
cache->cached_type = magic_buffer(
cache->magic_cookie,
block_data,
block->size);
cache->magic_cookie, block_data, block->size);
}
}
@@ -156,23 +152,19 @@ define_function(magic_type)
return_string((char*) cache->cached_type);
}
begin_declarations;
begin_declarations
declare_function("mime_type", "", "s", magic_mime_type);
declare_function("type", "", "s", magic_type);
end_declarations;
end_declarations
int module_initialize(
YR_MODULE* module)
int module_initialize(YR_MODULE* module)
{
return yr_thread_storage_create(&magic_tls);
}
int module_finalize(
YR_MODULE* module)
int module_finalize(YR_MODULE* module)
{
MAGIC_CACHE* cache = (MAGIC_CACHE*) yr_thread_storage_get_value(&magic_tls);
@@ -196,8 +188,7 @@ int module_load(
}
int module_unload(
YR_OBJECT* module)
int module_unload(YR_OBJECT* module)
{
MAGIC_CACHE* cache = (MAGIC_CACHE*) yr_thread_storage_get_value(&magic_tls);
+28 -42
View File
@@ -28,10 +28,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <math.h>
#include <yara/utils.h>
#include <yara/modules.h>
#include <yara/mem.h>
#include <yara/modules.h>
#include <yara/utils.h>
#define MODULE_NAME math
@@ -89,8 +88,8 @@ define_function(data_entropy)
uint32_t* data;
int64_t offset = integer_argument(1); // offset where to start
int64_t length = integer_argument(2); // length of bytes we want entropy on
int64_t offset = integer_argument(1); // offset where to start
int64_t length = integer_argument(2); // length of bytes we want entropy on
YR_SCAN_CONTEXT* context = scan_context();
YR_MEMORY_BLOCK* block = first_memory_block(context);
@@ -106,12 +105,11 @@ define_function(data_entropy)
foreach_memory_block(iterator, block)
{
if (offset >= block->base &&
offset < block->base + block->size)
if (offset >= block->base && offset < block->base + block->size)
{
size_t data_offset = (size_t) (offset - block->base);
size_t data_offset = (size_t)(offset - block->base);
size_t data_len = (size_t) yr_min(
length, (size_t) (block->size - data_offset));
length, (size_t)(block->size - data_offset));
const uint8_t* block_data = block->fetch_data(block);
@@ -178,8 +176,7 @@ define_function(string_deviation)
size_t i;
for (i = 0; i < s->length; i++)
sum += fabs(((double) s->c_string[i]) - mean);
for (i = 0; i < s->length; i++) sum += fabs(((double) s->c_string[i]) - mean);
return_float(sum / s->length);
}
@@ -211,12 +208,10 @@ define_function(data_deviation)
foreach_memory_block(iterator, block)
{
if (offset >= block->base &&
offset < block->base + block->size)
if (offset >= block->base && offset < block->base + block->size)
{
data_offset = (size_t)(offset - block->base);
data_len = (size_t)yr_min(
length, (size_t)(block->size - data_offset));
data_len = (size_t) yr_min(length, (size_t)(block->size - data_offset));
block_data = block->fetch_data(block);
if (block_data == NULL)
@@ -227,7 +222,7 @@ define_function(data_deviation)
length -= data_len;
for (i = 0; i < data_len; i++)
sum += fabs(((double)* (block_data + data_offset + i)) - mean);
sum += fabs(((double) *(block_data + data_offset + i)) - mean);
past_first_block = true;
}
@@ -259,8 +254,7 @@ define_function(string_mean)
SIZED_STRING* s = sized_string_argument(1);
for (i = 0; i < s->length; i++)
sum += (double) s->c_string[i];
for (i = 0; i < s->length; i++) sum += (double) s->c_string[i];
return_float(sum / s->length);
}
@@ -286,12 +280,11 @@ define_function(data_mean)
foreach_memory_block(iterator, block)
{
if (offset >= block->base &&
offset < block->base + block->size)
if (offset >= block->base && offset < block->base + block->size)
{
size_t data_offset = (size_t) (offset - block->base);
size_t data_offset = (size_t)(offset - block->base);
size_t data_len = (size_t) yr_min(
length, (size_t) (block->size - data_offset));
length, (size_t)(block->size - data_offset));
const uint8_t* block_data = block->fetch_data(block);
@@ -303,7 +296,7 @@ define_function(data_mean)
length -= data_len;
for (i = 0; i < data_len; i++)
sum += (double)* (block_data + data_offset + i);
sum += (double) *(block_data + data_offset + i);
past_first_block = true;
}
@@ -354,12 +347,11 @@ define_function(data_serial_correlation)
foreach_memory_block(iterator, block)
{
if (offset >= block->base &&
offset < block->base + block->size)
if (offset >= block->base && offset < block->base + block->size)
{
size_t data_offset = (size_t)(offset - block->base);
size_t data_len = (size_t) yr_min(
length, (size_t) (block->size - data_offset));
length, (size_t)(block->size - data_offset));
const uint8_t* block_data = block->fetch_data(block);
@@ -372,7 +364,7 @@ define_function(data_serial_correlation)
for (i = 0; i < data_len; i++)
{
sccun = (double)* (block_data + data_offset + i);
sccun = (double) *(block_data + data_offset + i);
scct1 += scclast * sccun;
scct2 += sccun;
scct3 += sccun * sccun;
@@ -471,14 +463,13 @@ define_function(data_monte_carlo_pi)
foreach_memory_block(iterator, block)
{
if (offset >= block->base &&
offset < block->base + block->size)
if (offset >= block->base && offset < block->base + block->size)
{
unsigned int monte[6];
size_t data_offset = (size_t) (offset - block->base);
size_t data_offset = (size_t)(offset - block->base);
size_t data_len = (size_t) yr_min(
length, (size_t) (block->size - data_offset));
length, (size_t)(block->size - data_offset));
const uint8_t* block_data = block->fetch_data(block);
@@ -490,7 +481,7 @@ define_function(data_monte_carlo_pi)
for (i = 0; i < data_len; i++)
{
monte[i % 6] = (unsigned int)* (block_data + data_offset + i);
monte[i % 6] = (unsigned int) *(block_data + data_offset + i);
if (i % 6 == 5)
{
@@ -615,8 +606,7 @@ define_function(max)
}
begin_declarations;
begin_declarations
declare_float("MEAN_BYTES");
declare_function("in_range", "fff", "i", in_range);
declare_function("deviation", "iif", "f", data_deviation);
@@ -631,19 +621,16 @@ begin_declarations;
declare_function("entropy", "s", "f", string_entropy);
declare_function("min", "ii", "i", min);
declare_function("max", "ii", "i", max);
end_declarations;
end_declarations
int module_initialize(
YR_MODULE* module)
int module_initialize(YR_MODULE* module)
{
return ERROR_SUCCESS;
}
int module_finalize(
YR_MODULE* module)
int module_finalize(YR_MODULE* module)
{
return ERROR_SUCCESS;
}
@@ -660,8 +647,7 @@ int module_load(
}
int module_unload(
YR_OBJECT* module_object)
int module_unload(YR_OBJECT* module_object)
{
return ERROR_SUCCESS;
}
+168 -89
View File
@@ -2,23 +2,24 @@
/* Generated by the protoc-gen-yara. DO NOT EDIT! */
#include <yara/mem.h>
#include <yara/modules.h>
#include "modules/pb_tests/pb_tests.pb-c.h"
#define MODULE_NAME pb_tests
static void* _pb_alloc(void *allocator_data, size_t size)
static void* _pb_alloc(void* allocator_data, size_t size)
{
return yr_malloc(size);
}
static void _pb_free(void *allocator_data, void *pointer)
static void _pb_free(void* allocator_data, void* pointer)
{
return yr_free(pointer);
}
begin_declarations;
begin_struct("struct");
begin_struct("enum");
begin_declarations
begin_struct("struct")
begin_struct("enum")
declare_integer("FIRST");
declare_integer("SECOND");
end_struct("enum");
@@ -32,48 +33,45 @@ begin_declarations;
declare_integer("f_bool");
declare_string("f_string");
declare_string("f_bytes");
begin_struct_array("f_struct_array");
begin_struct_array("f_struct_array")
declare_string("f_string");
declare_integer("f_enum");
begin_struct("f_nested_struct");
begin_struct("f_nested_struct")
declare_integer("f_int32");
declare_string("f_string");
end_struct("f_nested_struct");
begin_struct_array("f_nested_struct_array");
end_struct("f_nested_struct")
begin_struct_array("f_nested_struct_array")
declare_integer("f_int32");
declare_string("f_string");
end_struct_array("f_nested_struct_array");
end_struct_array("f_struct_array");
end_struct_array("f_struct_array")
declare_integer_dictionary("f_map_int32");
declare_integer_dictionary("f_map_bool");
declare_string_dictionary("f_map_string");
declare_float_dictionary("f_map_float");
begin_struct_dictionary("f_map_struct");
begin_struct_dictionary("f_map_struct")
declare_integer("f_int32");
declare_integer("f_int64");
end_struct_dictionary("f_map_struct");
end_struct_dictionary("f_map_struct")
declare_string("f_oneof_string");
begin_struct("f_oneof_struct");
begin_struct("f_oneof_struct")
declare_integer("f_int32");
declare_integer("f_int64");
end_struct("f_oneof_struct");
end_struct("f_oneof_struct")
declare_string("f_yara_name");
end_declarations;
end_declarations
int module_initialize(
YR_MODULE* module)
int module_initialize(YR_MODULE* module)
{
return ERROR_SUCCESS;
}
int module_finalize(
YR_MODULE* module)
int module_finalize(YR_MODULE* module)
{
return ERROR_SUCCESS;
}
int module_unload(
YR_OBJECT* module_object)
int module_unload(YR_OBJECT* module_object)
{
return ERROR_SUCCESS;
}
@@ -92,7 +90,8 @@ int module_load(
if (module_data == NULL)
return ERROR_SUCCESS;
Test__RootMessage* pb = test__root_message__unpack(&allocator, module_data_size, module_data);
Test__RootMessage* pb = test__root_message__unpack(
&allocator, module_data_size, module_data);
if (pb == NULL)
return ERROR_INVALID_MODULE_DATA;
@@ -100,134 +99,214 @@ int module_load(
set_integer(0, module_object, "struct.enum.FIRST");
set_integer(1, module_object, "struct.enum.SECOND");
if (pb->has_f_int32) {
if (pb->has_f_int32)
{
set_integer(pb->f_int32, module_object, "f_int32");
}
if (pb->has_f_int64) {
if (pb->has_f_int64)
{
set_integer(pb->f_int64, module_object, "f_int64");
}
if (pb->has_f_sint32) {
if (pb->has_f_sint32)
{
set_integer(pb->f_sint32, module_object, "f_sint32");
}
if (pb->has_f_sint64) {
if (pb->has_f_sint64)
{
set_integer(pb->f_sint64, module_object, "f_sint64");
}
if (pb->has_f_sfixed32) {
if (pb->has_f_sfixed32)
{
set_integer(pb->f_sfixed32, module_object, "f_sfixed32");
}
if (pb->has_f_sfixed64) {
if (pb->has_f_sfixed64)
{
set_integer(pb->f_sfixed64, module_object, "f_sfixed64");
}
if (pb->has_f_bool) {
if (pb->has_f_bool)
{
set_integer(pb->f_bool, module_object, "f_bool");
}
set_string(pb->f_string, module_object, "f_string");
set_sized_string((const char *) pb->f_bytes.data, pb->f_bytes.len, module_object, "f_bytes");
set_sized_string(
(const char*) pb->f_bytes.data,
pb->f_bytes.len,
module_object,
"f_bytes");
for (int i = 0; i < pb->n_f_struct_array; i++) {
for (int i = 0; i < pb->n_f_struct_array; i++)
{
if (pb->f_struct_array[i] != NULL)
{
set_string(
pb->f_struct_array[i]->f_string,
module_object,
"f_struct_array[%i].f_string",
i);
if (pb->f_struct_array[i] != NULL) {
set_string(pb->f_struct_array[i]->f_string, module_object, "f_struct_array[%i].f_string", i);
if (pb->f_struct_array[i]->has_f_enum) {
set_integer(pb->f_struct_array[i]->f_enum, module_object, "f_struct_array[%i].f_enum", i);
if (pb->f_struct_array[i]->has_f_enum)
{
set_integer(
pb->f_struct_array[i]->f_enum,
module_object,
"f_struct_array[%i].f_enum",
i);
}
if (pb->f_struct_array[i]->f_nested_struct != NULL) {
if (pb->f_struct_array[i]->f_nested_struct->has_f_int32) {
set_integer(pb->f_struct_array[i]->f_nested_struct->f_int32, module_object, "f_struct_array[%i].f_nested_struct.f_int32", i);
if (pb->f_struct_array[i]->f_nested_struct != NULL)
{
if (pb->f_struct_array[i]->f_nested_struct->has_f_int32)
{
set_integer(
pb->f_struct_array[i]->f_nested_struct->f_int32,
module_object,
"f_struct_array[%i].f_nested_struct.f_int32",
i);
}
set_string(pb->f_struct_array[i]->f_nested_struct->f_string, module_object, "f_struct_array[%i].f_nested_struct.f_string", i);
set_string(
pb->f_struct_array[i]->f_nested_struct->f_string,
module_object,
"f_struct_array[%i].f_nested_struct.f_string",
i);
}
for (int j = 0; j < pb->f_struct_array[i]->n_f_nested_struct_array; j++) {
if (pb->f_struct_array[i]->f_nested_struct_array[j] != NULL) {
if (pb->f_struct_array[i]->f_nested_struct_array[j]->has_f_int32) {
set_integer(pb->f_struct_array[i]->f_nested_struct_array[j]->f_int32, module_object, "f_struct_array[%i].f_nested_struct_array[%i].f_int32", i, j);
for (int j = 0; j < pb->f_struct_array[i]->n_f_nested_struct_array; j++)
{
if (pb->f_struct_array[i]->f_nested_struct_array[j] != NULL)
{
if (pb->f_struct_array[i]->f_nested_struct_array[j]->has_f_int32)
{
set_integer(
pb->f_struct_array[i]->f_nested_struct_array[j]->f_int32,
module_object,
"f_struct_array[%i].f_nested_struct_array[%i].f_int32",
i,
j);
}
set_string(pb->f_struct_array[i]->f_nested_struct_array[j]->f_string, module_object, "f_struct_array[%i].f_nested_struct_array[%i].f_string", i, j);
set_string(
pb->f_struct_array[i]->f_nested_struct_array[j]->f_string,
module_object,
"f_struct_array[%i].f_nested_struct_array[%i].f_string",
i,
j);
}
}
}
}
for (int i = 0; i < pb->n_f_map_int32; i++) {
if (pb->f_map_int32[i] != NULL) {
if (pb->f_map_int32[i]->has_value) {
set_integer(pb->f_map_int32[i]->value, module_object, "f_map_int32[%s]", pb->f_map_int32[i]->key);
for (int i = 0; i < pb->n_f_map_int32; i++)
{
if (pb->f_map_int32[i] != NULL)
{
if (pb->f_map_int32[i]->has_value)
{
set_integer(
pb->f_map_int32[i]->value,
module_object,
"f_map_int32[%s]",
pb->f_map_int32[i]->key);
}
}
}
for (int i = 0; i < pb->n_f_map_bool; i++) {
if (pb->f_map_bool[i] != NULL) {
if (pb->f_map_bool[i]->has_value) {
set_integer(pb->f_map_bool[i]->value, module_object, "f_map_bool[%s]", pb->f_map_bool[i]->key);
for (int i = 0; i < pb->n_f_map_bool; i++)
{
if (pb->f_map_bool[i] != NULL)
{
if (pb->f_map_bool[i]->has_value)
{
set_integer(
pb->f_map_bool[i]->value,
module_object,
"f_map_bool[%s]",
pb->f_map_bool[i]->key);
}
}
}
for (int i = 0; i < pb->n_f_map_string; i++) {
if (pb->f_map_string[i] != NULL) {
set_string(pb->f_map_string[i]->value, module_object, "f_map_string[%s]", pb->f_map_string[i]->key);
for (int i = 0; i < pb->n_f_map_string; i++)
{
if (pb->f_map_string[i] != NULL)
{
set_string(
pb->f_map_string[i]->value,
module_object,
"f_map_string[%s]",
pb->f_map_string[i]->key);
}
}
for (int i = 0; i < pb->n_f_map_float; i++) {
if (pb->f_map_float[i] != NULL) {
if (pb->f_map_float[i]->has_value) {
set_float(pb->f_map_float[i]->value, module_object, "f_map_float[%s]", pb->f_map_float[i]->key);
for (int i = 0; i < pb->n_f_map_float; i++)
{
if (pb->f_map_float[i] != NULL)
{
if (pb->f_map_float[i]->has_value)
{
set_float(
pb->f_map_float[i]->value,
module_object,
"f_map_float[%s]",
pb->f_map_float[i]->key);
}
}
}
for (int i = 0; i < pb->n_f_map_struct; i++) {
if (pb->f_map_struct[i] != NULL) {
if (pb->f_map_struct[i]->value != NULL) {
if (pb->f_map_struct[i]->value->has_f_int32) {
set_integer(pb->f_map_struct[i]->value->f_int32, module_object, "f_map_struct[%s].f_int32", pb->f_map_struct[i]->key);
for (int i = 0; i < pb->n_f_map_struct; i++)
{
if (pb->f_map_struct[i] != NULL)
{
if (pb->f_map_struct[i]->value != NULL)
{
if (pb->f_map_struct[i]->value->has_f_int32)
{
set_integer(
pb->f_map_struct[i]->value->f_int32,
module_object,
"f_map_struct[%s].f_int32",
pb->f_map_struct[i]->key);
}
if (pb->f_map_struct[i]->value->has_f_int64) {
set_integer(pb->f_map_struct[i]->value->f_int64, module_object, "f_map_struct[%s].f_int64", pb->f_map_struct[i]->key);
if (pb->f_map_struct[i]->value->has_f_int64)
{
set_integer(
pb->f_map_struct[i]->value->f_int64,
module_object,
"f_map_struct[%s].f_int64",
pb->f_map_struct[i]->key);
}
}
}
}
if (pb->f_oneof_case == 20) {
if (pb->f_oneof_case == 20)
{
set_string(pb->f_oneof_string, module_object, "f_oneof_string");
}
if (pb->f_oneof_case == 21) {
if (pb->f_oneof_struct != NULL) {
if (pb->f_oneof_struct->has_f_int32) {
set_integer(pb->f_oneof_struct->f_int32, module_object, "f_oneof_struct.f_int32");
if (pb->f_oneof_case == 21)
{
if (pb->f_oneof_struct != NULL)
{
if (pb->f_oneof_struct->has_f_int32)
{
set_integer(
pb->f_oneof_struct->f_int32,
module_object,
"f_oneof_struct.f_int32");
}
if (pb->f_oneof_struct->has_f_int64) {
set_integer(pb->f_oneof_struct->f_int64, module_object, "f_oneof_struct.f_int64");
if (pb->f_oneof_struct->has_f_int64)
{
set_integer(
pb->f_oneof_struct->f_int64,
module_object,
"f_oneof_struct.f_int64");
}
}
}
File diff suppressed because it is too large Load Diff
+33
View File
@@ -0,0 +1,33 @@
Generating a module from a Protocol Buffer
[Protocol Buffers](https://developers.google.com/protocol-buffers) (protobufs)
are Google's language-neutral, platform-idependent mechanism for serializing
structured data. The first thing you need to do for using protobuf is defining
your data structures, for example:
message Employee {
int32 id = 1;
string name = 2;
int32 age = 3
string email = 4;
}
Once you have defined your data structure, you use a protobuf compiler to
automatically generate the code that will marshal/unmarshall the data structure
into/from a bytes sequence. The protobuf compiler is able to generate code in
multiple languages, including C/C++, Python, Java and Go.
Now imagine that you can pass the marshalled data structure to YARA, and create
rules based in that data. Like for example:
import "vt_employee"
rule virustotal_employee_under_25
{
condition:
vt_employee.age < 25 and
vt_employee.email matches /*.@virustotal\.com/
}
Neat, right?
+509 -653
View File
File diff suppressed because it is too large Load Diff
+1583 -1591
View File
File diff suppressed because it is too large Load Diff
+24 -32
View File
@@ -85,10 +85,7 @@ define_function(empty)
define_function(match)
{
return_integer(
yr_re_match(
scan_context(),
regexp_argument(1),
string_argument(2)));
yr_re_match(scan_context(), regexp_argument(1), string_argument(2)));
}
@@ -98,52 +95,50 @@ define_function(foobar)
switch (arg)
{
case 1:
return_string("foo");
break;
case 2:
return_string("bar");
break;
case 1:
return_string("foo");
break;
case 2:
return_string("bar");
break;
}
return_string("oops")
}
begin_declarations;
begin_struct("constants");
begin_declarations
begin_struct("constants")
declare_integer("one");
declare_integer("two");
declare_string("foo");
declare_string("empty");
end_struct("constants");
end_struct("constants")
begin_struct("undefined");
begin_struct("undefined")
declare_integer("i");
declare_float("f");
end_struct("undefined");
declare_string("module_data")
end_struct("undefined")
declare_string("module_data");
declare_integer_array("integer_array");
declare_string_array("string_array");
declare_integer_dictionary("integer_dict");
declare_string_dictionary("string_dict");
begin_struct_array("struct_array");
begin_struct_array("struct_array")
declare_integer("i");
declare_string("s");
end_struct_array("struct_array");
end_struct_array("struct_array")
begin_struct_dictionary("struct_dict");
begin_struct_dictionary("struct_dict")
declare_integer("i");
declare_string("s");
end_struct_dictionary("struct_dict");
begin_struct_dictionary("empty_struct_dict");
begin_struct_dictionary("empty_struct_dict")
declare_integer("unused");
end_struct_dictionary("empty_struct_dict");
end_struct_dictionary("empty_struct_dict")
declare_function("match", "rs", "i", match);
declare_function("isum", "ii", "i", isum_2);
@@ -153,19 +148,16 @@ begin_declarations;
declare_function("length", "s", "i", length);
declare_function("empty", "", "s", empty);
declare_function("foobar", "i", "s", foobar);
end_declarations;
end_declarations
int module_initialize(
YR_MODULE* module)
int module_initialize(YR_MODULE* module)
{
return ERROR_SUCCESS;
}
int module_finalize(
YR_MODULE* module)
int module_finalize(YR_MODULE* module)
{
return ERROR_SUCCESS;
}
@@ -200,7 +192,8 @@ int module_load(
set_string("foo", module_object, "struct_dict[%s].s", "foo");
set_integer(1, module_object, "struct_dict[%s].i", "foo");
if (module_data_size > 0 && module_data != NULL) {
if (module_data_size > 0 && module_data != NULL)
{
set_sized_string(
(const char*) module_data,
module_data_size,
@@ -212,8 +205,7 @@ int module_load(
}
int module_unload(
YR_OBJECT* module_object)
int module_unload(YR_OBJECT* module_object)
{
// Fail if module_unload is called twice with the same module_object
if (module_object->data == (void*) 0xFABADA)
+4 -10
View File
@@ -28,7 +28,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <time.h>
#include <yara/modules.h>
#define MODULE_NAME time
@@ -43,22 +42,18 @@ define_function(now)
}
begin_declarations;
begin_declarations
declare_function("now", "", "i", now);
end_declarations;
int module_initialize(
YR_MODULE* module)
int module_initialize(YR_MODULE* module)
{
return ERROR_SUCCESS;
}
int module_finalize(
YR_MODULE* module)
int module_finalize(YR_MODULE* module)
{
return ERROR_SUCCESS;
}
@@ -74,8 +69,7 @@ int module_load(
}
int module_unload(
YR_OBJECT* module_object)
int module_unload(YR_OBJECT* module_object)
{
return ERROR_SUCCESS;
}
+42 -28
View File
@@ -1,5 +1,3 @@
#include <stdint.h>
/*
Copyright (c) 2020. The YARA Authors. All Rights Reserved.
@@ -30,16 +28,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <assert.h>
#include <stdint.h>
#include <yara/error.h>
#include <yara/mem.h>
#include <yara/notebook.h>
// Forward declaration of YR_NOTEBOOK_PAGE.
typedef struct YR_NOTEBOOK_PAGE YR_NOTEBOOK_PAGE;
// A notebook is a data structure that can be used for allocating memory
// space in the same way malloc() would do. However, the buffers returned
// by yr_notebook_alloc() are backed by a larger buffer reserved by the notebook
@@ -47,20 +43,18 @@ typedef struct YR_NOTEBOOK_PAGE YR_NOTEBOOK_PAGE;
// via yr_notebook_alloc() with space taken from the current page, or creates
// a new page when necessary. It's recommended that the page size is at least
// 4x the size of the buffers you plan to allocate with yr_notebook_alloc().
//
// Once the notebook is destroyed all the pages are freed, and consequently
// all the buffers allocated via yr_notebook_alloc().
struct YR_NOTEBOOK
{
// Size of each page in the notebook.
size_t page_size;
// Pointer to the first page in the book, this also the most recently
// Pointer to the first page in the book, this is also the most recently
// created page, the one that is being filled.
YR_NOTEBOOK_PAGE* page_list_head;
};
// YR_NOTEBOOK_PAGE
struct YR_NOTEBOOK_PAGE
{
// Amount of bytes in the page that are actually used.
@@ -71,13 +65,19 @@ struct YR_NOTEBOOK_PAGE
uint8_t data[0];
};
////////////////////////////////////////////////////////////////////////////////
// Creates a new notebook. The notebook initially has a single page of the
// specified size, but more pages are created if needed.
int yr_notebook_create(
size_t page_size,
YR_NOTEBOOK** pool)
//
// Args:
// page_size: Size of each page in the notebook.
// notebook: Address of a pointer to the newly created notebook.
//
// Returns:
// ERROR_SUCCESS
// ERROR_INSUFFICIENT_MEMORY
//
int yr_notebook_create(size_t page_size, YR_NOTEBOOK** notebook)
{
YR_NOTEBOOK* new_notebook = yr_malloc(sizeof(YR_NOTEBOOK));
@@ -97,17 +97,23 @@ int yr_notebook_create(
new_notebook->page_list_head->used = 0;
new_notebook->page_list_head->next = NULL;
*pool = new_notebook;
*notebook = new_notebook;
return ERROR_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Destroys a notebook and frees all the notebook's pages.
int yr_notebook_destroy(
YR_NOTEBOOK* pool)
//
// Args:
// notebook: Pointer to the notebook being destroyed.
//
// Returns:
// ERROR_SUCCESS
//
int yr_notebook_destroy(YR_NOTEBOOK* notebook)
{
YR_NOTEBOOK_PAGE* page = pool->page_list_head;
YR_NOTEBOOK_PAGE* page = notebook->page_list_head;
while (page != NULL)
{
@@ -116,15 +122,23 @@ int yr_notebook_destroy(
page = next;
}
yr_free(pool);
yr_free(notebook);
return ERROR_SUCCESS;
}
void* yr_notebook_alloc(
YR_NOTEBOOK* notebook,
size_t size)
////////////////////////////////////////////////////////////////////////////////
// Allocates a memory buffer from a notebook. The memory is freed when the
// notebook is destroyed, allocated buffers can't be freed individually.
//
// Args:
// notebook: Pointer to the notebook.
// size: Size of the allocated memory.
//
// Returns:
// Pointer to the allocated memory, or NULL if the allocation fails.
//
void* yr_notebook_alloc(YR_NOTEBOOK* notebook, size_t size)
{
// The requested memory size can't be larger than a notebook's page.
assert(size <= notebook->page_size);
@@ -144,10 +158,10 @@ void* yr_notebook_alloc(
notebook->page_list_head = new_page;
}
void *ptr = notebook->page_list_head->data + notebook->page_list_head->used;
void* ptr = notebook->page_list_head->data + notebook->page_list_head->used;
// In ARM make sure the alignment of the returned buffer is 4 bytes.
#if defined(__arm__)
// In ARM make sure the alignment of the returned buffer is 4 bytes.
#if defined(__arm__)
uintptr_t misalignment = (uintptr_t) ptr & 3;
if (misalignment)
@@ -155,7 +169,7 @@ void* yr_notebook_alloc(
size += 4 - misalignment;
ptr += 4 - misalignment;
}
#endif
#endif
notebook->page_list_head->used += size;
+351 -433
View File
File diff suppressed because it is too large Load Diff
+126 -235
View File
@@ -27,29 +27,25 @@ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <limits.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>
#include <yara/ahocorasick.h>
#include <yara/arena.h>
#include <yara/base64.h>
#include <yara/re.h>
#include <yara/error.h>
#include <yara/exec.h>
#include <yara/integers.h>
#include <yara/mem.h>
#include <yara/modules.h>
#include <yara/object.h>
#include <yara/parser.h>
#include <yara/re.h>
#include <yara/strutils.h>
#include <yara/utils.h>
#include <yara/modules.h>
#include <yara/parser.h>
#include <yara/mem.h>
#include <yara/integers.h>
#define todigit(x) ((x) >='A'&& (x) <='F')? \
((uint8_t) (x - 'A' + 10)) : \
((uint8_t) (x - '0'))
#define todigit(x) \
((x) >= 'A' && (x) <= 'F') ? ((uint8_t)(x - 'A' + 10)) : ((uint8_t)(x - '0'))
int yr_parser_emit(
yyscan_t yyscanner,
@@ -64,7 +60,6 @@ int yr_parser_emit(
instruction_ref);
}
int yr_parser_emit_with_arg_double(
yyscan_t yyscanner,
uint8_t instruction,
@@ -90,7 +85,6 @@ int yr_parser_emit_with_arg_double(
return result;
}
int yr_parser_emit_with_arg_int32(
yyscan_t yyscanner,
uint8_t instruction,
@@ -116,7 +110,6 @@ int yr_parser_emit_with_arg_int32(
return result;
}
int yr_parser_emit_with_arg(
yyscan_t yyscanner,
uint8_t instruction,
@@ -142,7 +135,6 @@ int yr_parser_emit_with_arg(
return result;
}
int yr_parser_emit_with_arg_reloc(
yyscan_t yyscanner,
uint8_t instruction,
@@ -174,10 +166,7 @@ int yr_parser_emit_with_arg_reloc(
if (result == ERROR_SUCCESS)
result = yr_arena_make_ptr_relocatable(
yyget_extra(yyscanner)->arena,
YR_CODE_SECTION,
ref.offset,
EOL);
yyget_extra(yyscanner)->arena, YR_CODE_SECTION, ref.offset, EOL);
if (argument_ref != NULL)
*argument_ref = ref;
@@ -185,7 +174,6 @@ int yr_parser_emit_with_arg_reloc(
return result;
}
int yr_parser_emit_pushes_for_strings(
yyscan_t yyscanner,
const char* identifier)
@@ -212,8 +200,7 @@ int yr_parser_emit_pushes_for_strings(
string_identifier = string->identifier;
target_identifier = identifier;
while (*target_identifier != '\0' &&
*string_identifier != '\0' &&
while (*target_identifier != '\0' && *string_identifier != '\0' &&
*target_identifier == *string_identifier)
{
target_identifier++;
@@ -221,14 +208,9 @@ int yr_parser_emit_pushes_for_strings(
}
if ((*target_identifier == '\0' && *string_identifier == '\0') ||
*target_identifier == '*')
*target_identifier == '*')
{
yr_parser_emit_with_arg_reloc(
yyscanner,
OP_PUSH,
string,
NULL,
NULL);
yr_parser_emit_with_arg_reloc(yyscanner, OP_PUSH, string, NULL, NULL);
string->flags |= STRING_FLAGS_REFERENCED;
string->flags &= ~STRING_FLAGS_FIXED_OFFSET;
@@ -239,19 +221,16 @@ int yr_parser_emit_pushes_for_strings(
if (matching == 0)
{
yr_compiler_set_error_extra_info(compiler, identifier)
return ERROR_UNDEFINED_STRING;
yr_compiler_set_error_extra_info(
compiler, identifier) return ERROR_UNDEFINED_STRING;
}
return ERROR_SUCCESS;
}
int yr_parser_emit_push_const(
yyscan_t yyscanner,
uint64_t argument)
int yr_parser_emit_push_const(yyscan_t yyscanner, uint64_t argument)
{
uint64_t u = (uint64_t)argument;
uint64_t u = (uint64_t) argument;
uint8_t buf[9];
int bufsz = 1;
if (u == YR_UNDEFINED)
@@ -262,34 +241,30 @@ int yr_parser_emit_push_const(
{
buf[0] = OP_PUSH_8;
bufsz += sizeof(uint8_t);
buf[1] = (uint8_t)argument;
buf[1] = (uint8_t) argument;
}
else if (u <= 0xffff)
{
buf[0] = OP_PUSH_16;
bufsz += sizeof(uint16_t);
*((uint16_t*)(buf+1)) = (uint16_t)argument;
*((uint16_t*) (buf + 1)) = (uint16_t) argument;
}
else if (u <= 0xffffffff)
{
buf[0] = OP_PUSH_32;
bufsz += sizeof(uint32_t);
*((uint32_t*)(buf+1)) = (uint32_t)argument;
*((uint32_t*) (buf + 1)) = (uint32_t) argument;
}
else {
else
{
buf[0] = OP_PUSH;
bufsz += sizeof(uint64_t);
*((uint64_t*)(buf+1)) = (uint64_t)argument;
*((uint64_t*) (buf + 1)) = (uint64_t) argument;
}
return yr_arena_write_data(
yyget_extra(yyscanner)->arena,
YR_CODE_SECTION,
buf,
bufsz,
NULL);
yyget_extra(yyscanner)->arena, YR_CODE_SECTION, buf, bufsz, NULL);
}
int yr_parser_check_types(
YR_COMPILER* compiler,
YR_OBJECT_FUNCTION* function,
@@ -308,10 +283,9 @@ int yr_parser_check_types(
yr_compiler_set_error_extra_info(compiler, function->identifier)
return ERROR_WRONG_ARGUMENTS;
return ERROR_WRONG_ARGUMENTS;
}
int yr_parser_lookup_string(
yyscan_t yyscanner,
const char* identifier,
@@ -338,15 +312,12 @@ int yr_parser_lookup_string(
yr_compiler_set_error_extra_info(compiler, identifier)
*string = NULL;
* string = NULL;
return ERROR_UNDEFINED_STRING;
}
//
// yr_parser_lookup_loop_variable
//
////////////////////////////////////////////////////////////////////////////////
// Searches for a variable with the given identifier in the scope of the current
// "for" loop. In case of nested "for" loops the identifier is searched starting
// at the top-level loop and going down thorough the nested loops until the
@@ -376,14 +347,14 @@ int yr_parser_lookup_loop_variable(
for (j = 0; j < compiler->loop[i].vars_count; j++)
{
if (compiler->loop[i].vars[j].identifier.ptr != NULL &&
strcmp(identifier, compiler->loop[i].vars[j].identifier.ptr) == 0)
{
if (expr != NULL)
*expr = compiler->loop[i].vars[j];
if (compiler->loop[i].vars[j].identifier.ptr != NULL &&
strcmp(identifier, compiler->loop[i].vars[j].identifier.ptr) == 0)
{
if (expr != NULL)
*expr = compiler->loop[i].vars[j];
return var_offset + j;
}
return var_offset + j;
}
}
var_offset += compiler->loop[i].vars_count;
@@ -392,7 +363,6 @@ int yr_parser_lookup_loop_variable(
return -1;
}
static int _yr_parser_write_string(
const char* identifier,
YR_MODIFIER modifier,
@@ -426,11 +396,9 @@ static int _yr_parser_write_string(
YR_ARENA_REF ref;
FAIL_ON_ERROR(_yr_compiler_store_string(
compiler, identifier, &ref));
FAIL_ON_ERROR(_yr_compiler_store_string(compiler, identifier, &ref));
string->identifier = (const char*) yr_arena_ref_to_ptr(
compiler->arena, &ref);
string->identifier = (const char*) yr_arena_ref_to_ptr(compiler->arena, &ref);
if (modifier.flags & STRING_FLAGS_HEXADECIMAL ||
modifier.flags & STRING_FLAGS_REGEXP ||
@@ -472,7 +440,7 @@ static int _yr_parser_write_string(
result = _yr_compiler_store_data(
compiler,
literal_string->c_string,
literal_string->length + 1, // +1 to include terminating NULL
literal_string->length + 1, // +1 to include terminating NULL
&ref);
string->length = (uint32_t) literal_string->length;
@@ -492,13 +460,11 @@ static int _yr_parser_write_string(
else
{
// Emit forwards code
result = yr_re_ast_emit_code(
re_ast, compiler->arena, false);
result = yr_re_ast_emit_code(re_ast, compiler->arena, false);
// Emit backwards code
if (result == ERROR_SUCCESS)
result = yr_re_ast_emit_code(
re_ast, compiler->arena, true);
result = yr_re_ast_emit_code(re_ast, compiler->arena, true);
if (result == ERROR_SUCCESS)
result = yr_atoms_extract_from_re(
@@ -581,24 +547,20 @@ int yr_parser_reduce_string_declaration(
// Determine if a string with the same identifier was already defined
// by searching for the identifier in strings_table.
uint32_t string_idx = yr_hash_table_lookup_uint32(
compiler->strings_table,
identifier,
NULL);
compiler->strings_table, identifier, NULL);
// The string was already defined, return an error.
if (string_idx != UINT32_MAX)
{
result = ERROR_DUPLICATED_STRING_IDENTIFIER;
yr_compiler_set_error_extra_info(compiler, identifier)
goto _exit;
yr_compiler_set_error_extra_info(compiler, identifier) goto _exit;
}
// Empty strings are not allowed
if (str->length == 0)
{
result = ERROR_EMPTY_STRING;
yr_compiler_set_error_extra_info(compiler, identifier)
goto _exit;
yr_compiler_set_error_extra_info(compiler, identifier) goto _exit;
}
// If string identifier is $ this is an anonymous string, if not add the
@@ -633,9 +595,8 @@ int yr_parser_reduce_string_declaration(
if (modifier.flags & STRING_FLAGS_XOR &&
modifier.flags & STRING_FLAGS_NO_CASE)
{
result = ERROR_INVALID_MODIFIER;
yr_compiler_set_error_extra_info(compiler, "xor nocase")
goto _exit;
result = ERROR_INVALID_MODIFIER;
yr_compiler_set_error_extra_info(compiler, "xor nocase") goto _exit;
}
// base64 and nocase together is not implemented.
@@ -643,13 +604,11 @@ int yr_parser_reduce_string_declaration(
(modifier.flags & STRING_FLAGS_BASE64 ||
modifier.flags & STRING_FLAGS_BASE64_WIDE))
{
result = ERROR_INVALID_MODIFIER;
yr_compiler_set_error_extra_info(
compiler,
modifier.flags & STRING_FLAGS_BASE64 ?
"base64 nocase" :
"base64wide nocase")
goto _exit;
result = ERROR_INVALID_MODIFIER;
yr_compiler_set_error_extra_info(
compiler,
modifier.flags & STRING_FLAGS_BASE64 ? "base64 nocase"
: "base64wide nocase") goto _exit;
}
// base64 and fullword together is not implemented.
@@ -657,13 +616,12 @@ int yr_parser_reduce_string_declaration(
(modifier.flags & STRING_FLAGS_BASE64 ||
modifier.flags & STRING_FLAGS_BASE64_WIDE))
{
result = ERROR_INVALID_MODIFIER;
yr_compiler_set_error_extra_info(
compiler,
modifier.flags & STRING_FLAGS_BASE64 ?
"base64 fullword" :
"base64wide fullword")
goto _exit;
result = ERROR_INVALID_MODIFIER;
yr_compiler_set_error_extra_info(
compiler,
modifier.flags & STRING_FLAGS_BASE64
? "base64 fullword"
: "base64wide fullword") goto _exit;
}
// base64 and xor together is not implemented.
@@ -671,13 +629,11 @@ int yr_parser_reduce_string_declaration(
(modifier.flags & STRING_FLAGS_BASE64 ||
modifier.flags & STRING_FLAGS_BASE64_WIDE))
{
result = ERROR_INVALID_MODIFIER;
yr_compiler_set_error_extra_info(
compiler,
modifier.flags & STRING_FLAGS_BASE64 ?
"base64 xor" :
"base64wide xor")
goto _exit;
result = ERROR_INVALID_MODIFIER;
yr_compiler_set_error_extra_info(
compiler,
modifier.flags & STRING_FLAGS_BASE64 ? "base64 xor"
: "base64wide xor") goto _exit;
}
if (!(modifier.flags & STRING_FLAGS_WIDE) &&
@@ -702,7 +658,6 @@ int yr_parser_reduce_string_declaration(
// and unmarked later if required.
modifier.flags |= STRING_FLAGS_FIXED_OFFSET;
if (modifier.flags & STRING_FLAGS_HEXADECIMAL ||
modifier.flags & STRING_FLAGS_REGEXP ||
modifier.flags & STRING_FLAGS_BASE64 ||
@@ -721,15 +676,14 @@ int yr_parser_reduce_string_declaration(
message,
sizeof(message),
"invalid %s \"%s\": %s",
(modifier.flags & STRING_FLAGS_HEXADECIMAL) ?
"hex string" : "regular expression",
(modifier.flags & STRING_FLAGS_HEXADECIMAL) ? "hex string"
: "regular expression",
identifier,
re_error.message);
yr_compiler_set_error_extra_info(
compiler, message)
yr_compiler_set_error_extra_info(compiler, message)
goto _exit;
goto _exit;
}
if (re_ast->flags & RE_FLAGS_FAST_REGEXP)
@@ -749,28 +703,27 @@ int yr_parser_reduce_string_declaration(
{
result = ERROR_INVALID_REGULAR_EXPRESSION;
yr_compiler_set_error_extra_info(compiler,
yr_compiler_set_error_extra_info(
compiler,
"greedy and ungreedy quantifiers can't be mixed in a regular "
"expression")
goto _exit;
goto _exit;
}
if (yr_re_ast_contains_dot_star(re_ast))
{
yywarning(
yyscanner,
"%s contains .* or .+, consider using .{,N} or .{1,N} with a reasonable value for N",
"%s contains .* or .+, consider using .{,N} or .{1,N} with a "
"reasonable value for N",
identifier);
}
if (compiler->re_ast_callback != NULL)
{
compiler->re_ast_callback(
current_rule,
identifier,
re_ast,
compiler->re_ast_clbk_user_data);
current_rule, identifier, re_ast, compiler->re_ast_clbk_user_data);
}
*string_ref = YR_ARENA_NULL_REF;
@@ -882,14 +835,13 @@ _exit:
return result;
}
int yr_parser_reduce_rule_declaration_phase_1(
yyscan_t yyscanner,
int32_t flags,
const char* identifier,
YR_ARENA_REF* rule_ref)
{
YR_FIXUP *fixup;
YR_FIXUP* fixup;
YR_COMPILER* compiler = yyget_extra(yyscanner);
YR_NAMESPACE* ns = (YR_NAMESPACE*) yr_arena_get_ptr(
@@ -898,19 +850,14 @@ int yr_parser_reduce_rule_declaration_phase_1(
compiler->current_namespace_idx * sizeof(struct YR_NAMESPACE));
if (yr_hash_table_lookup_uint32(
compiler->rules_table,
identifier,
ns->name) != UINT32_MAX ||
yr_hash_table_lookup(
compiler->objects_table,
identifier,
NULL) != NULL)
compiler->rules_table, identifier, ns->name) != UINT32_MAX ||
yr_hash_table_lookup(compiler->objects_table, identifier, NULL) != NULL)
{
// A rule or variable with the same identifier already exists, return the
// appropriate error.
yr_compiler_set_error_extra_info(compiler, identifier)
return ERROR_DUPLICATED_IDENTIFIER;
yr_compiler_set_error_extra_info(
compiler, identifier) return ERROR_DUPLICATED_IDENTIFIER;
}
FAIL_ON_ERROR(yr_arena_allocate_struct(
@@ -929,10 +876,7 @@ int yr_parser_reduce_rule_declaration_phase_1(
YR_ARENA_REF ref;
FAIL_ON_ERROR(_yr_compiler_store_string(
compiler,
identifier,
&ref));
FAIL_ON_ERROR(_yr_compiler_store_string(compiler, identifier, &ref));
rule->identifier = (const char*) yr_arena_ref_to_ptr(compiler->arena, &ref);
rule->flags = flags;
@@ -953,11 +897,7 @@ int yr_parser_reduce_rule_declaration_phase_1(
// its final value.
FAIL_ON_ERROR(yr_parser_emit_with_arg_int32(
yyscanner,
OP_INIT_RULE,
0,
NULL,
&jmp_offset_ref));
yyscanner, OP_INIT_RULE, 0, NULL, &jmp_offset_ref));
FAIL_ON_ERROR(yr_arena_write_data(
compiler->arena,
@@ -980,10 +920,7 @@ int yr_parser_reduce_rule_declaration_phase_1(
yr_hash_table_clean(compiler->strings_table, NULL);
FAIL_ON_ERROR(yr_hash_table_add_uint32(
compiler->rules_table,
identifier,
ns->name,
compiler->current_rule_idx));
compiler->rules_table, identifier, ns->name, compiler->current_rule_idx));
return ERROR_SUCCESS;
}
@@ -995,13 +932,12 @@ int yr_parser_reduce_rule_declaration_phase_2(
uint32_t max_strings_per_rule;
uint32_t strings_in_rule = 0;
YR_FIXUP *fixup;
YR_FIXUP* fixup;
YR_STRING* string;
YR_COMPILER* compiler = yyget_extra(yyscanner);
yr_get_configuration(
YR_CONFIG_MAX_STRINGS_PER_RULE,
(void*) &max_strings_per_rule);
YR_CONFIG_MAX_STRINGS_PER_RULE, (void*) &max_strings_per_rule);
YR_RULE* rule = (YR_RULE*) yr_arena_ref_to_ptr(compiler->arena, rule_ref);
@@ -1021,37 +957,32 @@ int yr_parser_reduce_rule_declaration_phase_2(
// chained_to == NULL) must be referenced. All other fragments
// are never marked as referenced.
if (!STRING_IS_REFERENCED(string) &&
string->chained_to == NULL)
if (!STRING_IS_REFERENCED(string) && string->chained_to == NULL)
{
yr_compiler_set_error_extra_info(compiler, string->identifier)
return ERROR_UNREFERENCED_STRING;
yr_compiler_set_error_extra_info(
compiler, string->identifier) return ERROR_UNREFERENCED_STRING;
}
strings_in_rule++;
if (strings_in_rule > max_strings_per_rule)
{
yr_compiler_set_error_extra_info(compiler, rule->identifier)
return ERROR_TOO_MANY_STRINGS;
yr_compiler_set_error_extra_info(
compiler, rule->identifier) return ERROR_TOO_MANY_STRINGS;
}
}
FAIL_ON_ERROR(yr_parser_emit_with_arg(
yyscanner,
OP_MATCH_RULE,
compiler->current_rule_idx,
NULL,
NULL));
yyscanner, OP_MATCH_RULE, compiler->current_rule_idx, NULL, NULL));
fixup = compiler->fixup_stack_head;
int32_t* jmp_offset_addr = (int32_t*) yr_arena_ref_to_ptr(
compiler->arena, &fixup->ref);
int32_t jmp_offset = \
yr_arena_get_current_offset(compiler->arena, YR_CODE_SECTION) -
fixup->ref.offset + 1;
int32_t jmp_offset = yr_arena_get_current_offset(
compiler->arena, YR_CODE_SECTION) -
fixup->ref.offset + 1;
*jmp_offset_addr = jmp_offset;
@@ -1066,7 +997,6 @@ int yr_parser_reduce_rule_declaration_phase_2(
return ERROR_SUCCESS;
}
int yr_parser_reduce_string_identifier(
yyscan_t yyscanner,
const char* identifier,
@@ -1076,16 +1006,12 @@ int yr_parser_reduce_string_identifier(
YR_STRING* string;
YR_COMPILER* compiler = yyget_extra(yyscanner);
if (strcmp(identifier, "$") == 0) // is an anonymous string ?
if (strcmp(identifier, "$") == 0) // is an anonymous string ?
{
if (compiler->loop_for_of_var_index >= 0) // inside a loop ?
if (compiler->loop_for_of_var_index >= 0) // inside a loop ?
{
yr_parser_emit_with_arg(
yyscanner,
OP_PUSH_M,
compiler->loop_for_of_var_index,
NULL,
NULL);
yyscanner, OP_PUSH_M, compiler->loop_for_of_var_index, NULL, NULL);
yr_parser_emit(yyscanner, instruction, NULL);
@@ -1123,15 +1049,10 @@ int yr_parser_reduce_string_identifier(
}
else
{
FAIL_ON_ERROR(yr_parser_lookup_string(
yyscanner, identifier, &string));
FAIL_ON_ERROR(yr_parser_lookup_string(yyscanner, identifier, &string));
FAIL_ON_ERROR(yr_parser_emit_with_arg_reloc(
yyscanner,
OP_PUSH,
string,
NULL,
NULL));
FAIL_ON_ERROR(
yr_parser_emit_with_arg_reloc(yyscanner, OP_PUSH, string, NULL, NULL));
if (instruction != OP_FOUND)
string->flags &= ~STRING_FLAGS_SINGLE_MATCH;
@@ -1166,7 +1087,6 @@ int yr_parser_reduce_string_identifier(
return ERROR_SUCCESS;
}
int yr_parser_reduce_meta_declaration(
yyscan_t yyscanner,
int32_t type,
@@ -1192,19 +1112,13 @@ int yr_parser_reduce_meta_declaration(
meta->type = type;
meta->integer = integer;
FAIL_ON_ERROR(_yr_compiler_store_string(
compiler,
identifier,
&ref));
FAIL_ON_ERROR(_yr_compiler_store_string(compiler, identifier, &ref));
meta->identifier = (const char*) yr_arena_ref_to_ptr(compiler->arena, &ref);
if (string != NULL)
{
FAIL_ON_ERROR(_yr_compiler_store_string(
compiler,
string,
&ref));
FAIL_ON_ERROR(_yr_compiler_store_string(compiler, string, &ref));
meta->string = (const char*) yr_arena_ref_to_ptr(compiler->arena, &ref);
}
@@ -1218,9 +1132,7 @@ int yr_parser_reduce_meta_declaration(
return ERROR_SUCCESS;
}
static int _yr_parser_valid_module_name(
SIZED_STRING* module_name)
static int _yr_parser_valid_module_name(SIZED_STRING* module_name)
{
if (module_name->length == 0)
return false;
@@ -1231,10 +1143,7 @@ static int _yr_parser_valid_module_name(
return true;
}
int yr_parser_reduce_import(
yyscan_t yyscanner,
SIZED_STRING* module_name)
int yr_parser_reduce_import(yyscan_t yyscanner, SIZED_STRING* module_name)
{
int result;
@@ -1244,8 +1153,8 @@ int yr_parser_reduce_import(
if (!_yr_parser_valid_module_name(module_name))
{
yr_compiler_set_error_extra_info(compiler, module_name->c_string)
return ERROR_INVALID_MODULE_NAME;
yr_compiler_set_error_extra_info(
compiler, module_name->c_string) return ERROR_INVALID_MODULE_NAME;
}
YR_NAMESPACE* ns = (YR_NAMESPACE*) yr_arena_get_ptr(
@@ -1254,9 +1163,7 @@ int yr_parser_reduce_import(
compiler->current_namespace_idx * sizeof(struct YR_NAMESPACE));
module_structure = (YR_OBJECT*) yr_hash_table_lookup(
compiler->objects_table,
module_name->c_string,
ns->name);
compiler->objects_table, module_name->c_string, ns->name);
// if module already imported, do nothing
@@ -1264,10 +1171,7 @@ int yr_parser_reduce_import(
return ERROR_SUCCESS;
FAIL_ON_ERROR(yr_object_create(
OBJECT_TYPE_STRUCTURE,
module_name->c_string,
NULL,
&module_structure));
OBJECT_TYPE_STRUCTURE, module_name->c_string, NULL, &module_structure));
FAIL_ON_ERROR(yr_hash_table_add(
compiler->objects_table,
@@ -1275,20 +1179,15 @@ int yr_parser_reduce_import(
ns->name,
module_structure));
result = yr_modules_do_declarations(
module_name->c_string,
module_structure);
result = yr_modules_do_declarations(module_name->c_string, module_structure);
if (result == ERROR_UNKNOWN_MODULE)
yr_compiler_set_error_extra_info(compiler, module_name->c_string)
if (result != ERROR_SUCCESS)
return result;
if (result != ERROR_SUCCESS) return result;
FAIL_ON_ERROR(_yr_compiler_store_string(
compiler,
module_name->c_string,
&ref));
FAIL_ON_ERROR(
_yr_compiler_store_string(compiler, module_name->c_string, &ref));
FAIL_ON_ERROR(yr_parser_emit_with_arg_reloc(
yyscanner,
@@ -1300,26 +1199,23 @@ int yr_parser_reduce_import(
return ERROR_SUCCESS;
}
static int _yr_parser_operator_to_opcode(
const char* op,
int expression_type)
static int _yr_parser_operator_to_opcode(const char* op, int expression_type)
{
int opcode = 0;
switch(expression_type)
switch (expression_type)
{
case EXPRESSION_TYPE_INTEGER:
opcode = OP_INT_BEGIN;
break;
case EXPRESSION_TYPE_FLOAT:
opcode = OP_DBL_BEGIN;
break;
case EXPRESSION_TYPE_STRING:
opcode = OP_STR_BEGIN;
break;
default:
assert(false);
case EXPRESSION_TYPE_INTEGER:
opcode = OP_INT_BEGIN;
break;
case EXPRESSION_TYPE_FLOAT:
opcode = OP_DBL_BEGIN;
break;
case EXPRESSION_TYPE_STRING:
opcode = OP_STR_BEGIN;
break;
default:
assert(false);
}
if (op[0] == '<')
@@ -1368,7 +1264,6 @@ static int _yr_parser_operator_to_opcode(
return OP_ERROR;
}
int yr_parser_reduce_operation(
yyscan_t yyscanner,
const char* op,
@@ -1406,35 +1301,31 @@ int yr_parser_reduce_operation(
}
FAIL_ON_ERROR(yr_parser_emit(
yyscanner,
_yr_parser_operator_to_opcode(op, expression_type),
NULL));
yyscanner, _yr_parser_operator_to_opcode(op, expression_type), NULL));
}
else if (left_operand.type == EXPRESSION_TYPE_STRING &&
right_operand.type == EXPRESSION_TYPE_STRING)
else if (
left_operand.type == EXPRESSION_TYPE_STRING &&
right_operand.type == EXPRESSION_TYPE_STRING)
{
int opcode = _yr_parser_operator_to_opcode(op, EXPRESSION_TYPE_STRING);
if (opcode != OP_ERROR)
{
FAIL_ON_ERROR(yr_parser_emit(
yyscanner,
opcode,
NULL));
FAIL_ON_ERROR(yr_parser_emit(yyscanner, opcode, NULL));
}
else
{
yr_compiler_set_error_extra_info_fmt(
compiler, "strings don't support \"%s\" operation", op)
return ERROR_WRONG_TYPE;
return ERROR_WRONG_TYPE;
}
}
else
{
yr_compiler_set_error_extra_info(compiler, "type mismatch")
return ERROR_WRONG_TYPE;
return ERROR_WRONG_TYPE;
}
return ERROR_SUCCESS;
+7 -11
View File
@@ -28,21 +28,19 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <yara/error.h>
#include <yara/proc.h>
#include <yara/mem.h>
#include <yara/globals.h>
#include <yara/mem.h>
#include <yara/proc.h>
int _yr_process_attach(int, YR_PROC_ITERATOR_CTX*);
int _yr_process_detach(YR_PROC_ITERATOR_CTX*);
YR_API int yr_process_open_iterator(
int pid,
YR_MEMORY_BLOCK_ITERATOR* iterator)
YR_API int yr_process_open_iterator(int pid, YR_MEMORY_BLOCK_ITERATOR* iterator)
{
YR_DEBUG_FPRINTF(2, stderr, "+ %s(pid=%d) {}\n", __FUNCTION__, pid);
YR_PROC_ITERATOR_CTX* context = (YR_PROC_ITERATOR_CTX*) \
yr_malloc(sizeof(YR_PROC_ITERATOR_CTX));
YR_PROC_ITERATOR_CTX* context = (YR_PROC_ITERATOR_CTX*) yr_malloc(
sizeof(YR_PROC_ITERATOR_CTX));
if (context == NULL)
return ERROR_INSUFFICIENT_MEMORY;
@@ -60,15 +58,13 @@ YR_API int yr_process_open_iterator(
context->proc_info = NULL;
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_process_attach(pid, context),
yr_free(context));
_yr_process_attach(pid, context), yr_free(context));
return ERROR_SUCCESS;
}
YR_API int yr_process_close_iterator(
YR_MEMORY_BLOCK_ITERATOR* iterator)
YR_API int yr_process_close_iterator(YR_MEMORY_BLOCK_ITERATOR* iterator)
{
YR_DEBUG_FPRINTF(2, stderr, "+ %s() {}\n", __FUNCTION__);
+20 -25
View File
@@ -29,30 +29,25 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#if defined(USE_FREEBSD_PROC)
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <yara/error.h>
#include <yara/proc.h>
#include <yara/mem.h>
#include <yara/proc.h>
typedef struct _YR_PROC_INFO {
int pid;
typedef struct _YR_PROC_INFO
{
int pid;
struct ptrace_vm_entry vm_entry;
} YR_PROC_INFO;
int _yr_process_attach(
int pid,
YR_PROC_ITERATOR_CTX* context)
int _yr_process_attach(int pid, YR_PROC_ITERATOR_CTX* context)
{
int status;
@@ -85,8 +80,7 @@ int _yr_process_attach(
}
int _yr_process_detach(
YR_PROC_ITERATOR_CTX* context)
int _yr_process_detach(YR_PROC_ITERATOR_CTX* context)
{
YR_PROC_INFO* proc_info = (YR_PROC_INFO*) context->proc_info;
@@ -97,8 +91,7 @@ int _yr_process_detach(
}
YR_API const uint8_t* yr_process_fetch_memory_block_data(
YR_MEMORY_BLOCK* block)
YR_API const uint8_t* yr_process_fetch_memory_block_data(YR_MEMORY_BLOCK* block)
{
YR_PROC_ITERATOR_CTX* context = (YR_PROC_ITERATOR_CTX*) block->context;
YR_PROC_INFO* proc_info = (YR_PROC_INFO*) context->proc_info;
@@ -123,11 +116,11 @@ YR_API const uint8_t* yr_process_fetch_memory_block_data(
}
io_desc.piod_op = PIOD_READ_D;
io_desc.piod_offs = (void*)block->base;
io_desc.piod_addr = (void*)context->buffer;
io_desc.piod_offs = (void*) block->base;
io_desc.piod_addr = (void*) context->buffer;
io_desc.piod_len = block->size;
if (ptrace(PT_IO, proc_info->pid, (char*)&io_desc, 0) == -1)
if (ptrace(PT_IO, proc_info->pid, (char*) &io_desc, 0) == -1)
{
return NULL;
}
@@ -147,13 +140,15 @@ YR_API YR_MEMORY_BLOCK* yr_process_get_next_memory_block(
proc_info->vm_entry.pve_path = buf;
proc_info->vm_entry.pve_pathlen = sizeof(buf);
if (ptrace(PT_VM_ENTRY, proc_info->pid, (char*)(&proc_info->vm_entry), 0) == -1) {
if (ptrace(PT_VM_ENTRY, proc_info->pid, (char*) (&proc_info->vm_entry), 0) ==
-1)
{
return NULL;
}
context->current_block.base = proc_info->vm_entry.pve_start;
context->current_block.size =
proc_info->vm_entry.pve_end - proc_info->vm_entry.pve_start + 1;
context->current_block.size = proc_info->vm_entry.pve_end -
proc_info->vm_entry.pve_start + 1;
return &context->current_block;
}
+27 -26
View File
@@ -29,29 +29,27 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#if defined(USE_LINUX_PROC)
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
#include <yara/error.h>
#include <yara/proc.h>
#include <yara/mem.h>
#include <yara/globals.h>
#include <yara/mem.h>
#include <yara/proc.h>
typedef struct _YR_PROC_INFO {
int pid;
int mem_fd;
FILE* maps;
typedef struct _YR_PROC_INFO
{
int pid;
int mem_fd;
FILE* maps;
} YR_PROC_INFO;
int _yr_process_attach(
int pid,
YR_PROC_ITERATOR_CTX* context)
int _yr_process_attach(int pid, YR_PROC_ITERATOR_CTX* context)
{
char buffer[256];
@@ -92,8 +90,7 @@ int _yr_process_attach(
}
int _yr_process_detach(
YR_PROC_ITERATOR_CTX* context)
int _yr_process_detach(YR_PROC_ITERATOR_CTX* context)
{
YR_PROC_INFO* proc_info = (YR_PROC_INFO*) context->proc_info;
@@ -104,8 +101,7 @@ int _yr_process_detach(
}
YR_API const uint8_t* yr_process_fetch_memory_block_data(
YR_MEMORY_BLOCK* block)
YR_API const uint8_t* yr_process_fetch_memory_block_data(YR_MEMORY_BLOCK* block)
{
const uint8_t* result = NULL;
@@ -126,21 +122,22 @@ YR_API const uint8_t* yr_process_fetch_memory_block_data(
else
{
context->buffer_size = 0;
goto _exit; // return NULL;
goto _exit; // return NULL;
}
}
if (pread(proc_info->mem_fd,
(void *) context->buffer,
block->size,
block->base) == -1)
if (pread(
proc_info->mem_fd,
(void*) context->buffer,
block->size,
block->base) == -1)
{
goto _exit; // return NULL;
goto _exit; // return NULL;
}
result = context->buffer;
_exit:;
_exit:;
YR_DEBUG_FPRINTF(2, stderr, "+ %s() {} = %p\n", __FUNCTION__, result);
@@ -159,14 +156,18 @@ YR_API YR_MEMORY_BLOCK* yr_process_get_next_memory_block(
if (fgets(buffer, sizeof(buffer), proc_info->maps) != NULL)
{
sscanf(buffer, "%"SCNx64"-%"SCNx64, &begin, &end);
sscanf(buffer, "%" SCNx64 "-%" SCNx64, &begin, &end);
context->current_block.base = begin;
context->current_block.size = end - begin;
YR_DEBUG_FPRINTF(2, stderr,
YR_DEBUG_FPRINTF(
2,
stderr,
"+ %s() {} // .base=0x%" PRIx64 " .size=%lu\n",
__FUNCTION__, context->current_block.base, context->current_block.size);
__FUNCTION__,
context->current_block.base,
context->current_block.size);
return &context->current_block;
}
+16 -18
View File
@@ -33,20 +33,18 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <mach/mach_vm.h>
#include <mach/vm_region.h>
#include <mach/vm_statistics.h>
#include <yara/error.h>
#include <yara/mem.h>
#include <yara/proc.h>
#include <yara/error.h>
typedef struct _YR_PROC_INFO {
task_t task;
typedef struct _YR_PROC_INFO
{
task_t task;
} YR_PROC_INFO;
int _yr_process_attach(
int pid,
YR_PROC_ITERATOR_CTX* context)
int _yr_process_attach(int pid, YR_PROC_ITERATOR_CTX* context)
{
YR_PROC_INFO* proc_info = (YR_PROC_INFO*) yr_malloc(sizeof(YR_PROC_INFO));
@@ -67,8 +65,7 @@ int _yr_process_attach(
}
int _yr_process_detach(
YR_PROC_ITERATOR_CTX* context)
int _yr_process_detach(YR_PROC_ITERATOR_CTX* context)
{
YR_PROC_INFO* proc_info = context->proc_info;
@@ -79,8 +76,7 @@ int _yr_process_detach(
}
YR_API const uint8_t* yr_process_fetch_memory_block_data(
YR_MEMORY_BLOCK* block)
YR_API const uint8_t* yr_process_fetch_memory_block_data(YR_MEMORY_BLOCK* block)
{
YR_PROC_ITERATOR_CTX* context = (YR_PROC_ITERATOR_CTX*) block->context;
YR_PROC_INFO* proc_info = context->proc_info;
@@ -105,11 +101,11 @@ YR_API const uint8_t* yr_process_fetch_memory_block_data(
}
if (vm_read_overwrite(
proc_info->task,
(vm_address_t) block->base,
block->size,
(vm_address_t) context->buffer,
&size) != KERN_SUCCESS)
proc_info->task,
(vm_address_t) block->base,
block->size,
(vm_address_t) context->buffer,
&size) != KERN_SUCCESS)
{
return NULL;
}
@@ -129,8 +125,10 @@ YR_API YR_MEMORY_BLOCK* yr_process_get_next_memory_block(
mach_port_t object;
vm_region_basic_info_data_64_t info;
vm_size_t size = 0;
vm_address_t address = (vm_address_t) \
context->current_block.base + context->current_block.size;
vm_address_t address = (vm_address_t) context->current_block.base +
context->current_block.size;
do
{
info_count = VM_REGION_BASIC_INFO_COUNT_64;
+3 -7
View File
@@ -32,21 +32,17 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <yara/error.h>
#include <yara/proc.h>
int _yr_process_attach(
int pid,
YR_PROC_ITERATOR_CTX* context)
int _yr_process_attach(int pid, YR_PROC_ITERATOR_CTX* context)
{
return ERROR_COULD_NOT_ATTACH_TO_PROCESS;
}
int _yr_process_detach(
YR_PROC_ITERATOR_CTX* context)
int _yr_process_detach(YR_PROC_ITERATOR_CTX* context)
{
return ERROR_INVALID_ARGUMENT;
}
YR_API const uint8_t* yr_process_fetch_memory_block_data(
YR_MEMORY_BLOCK* block)
YR_API const uint8_t* yr_process_fetch_memory_block_data(YR_MEMORY_BLOCK* block)
{
return NULL;
}
+17 -21
View File
@@ -29,32 +29,30 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#if defined(USE_OPENBSD_PROC)
#include <sys/types.h>
#include <errno.h>
#include <sys/ptrace.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <yara/error.h>
#include <yara/proc.h>
#include <yara/mem.h>
#include <yara/proc.h>
typedef struct _YR_PROC_INFO {
int pid;
uint64_t old_end;
typedef struct _YR_PROC_INFO
{
int pid;
uint64_t old_end;
struct kinfo_vmentry vm_entry;
} YR_PROC_INFO;
int _yr_process_attach(
int pid,
YR_PROC_ITERATOR_CTX* context)
int _yr_process_attach(int pid, YR_PROC_ITERATOR_CTX* context)
{
int status;
size_t len = sizeof(struct kinfo_vmentry);
int mib[] = { CTL_KERN, KERN_PROC_VMMAP, pid };
int mib[] = {CTL_KERN, KERN_PROC_VMMAP, pid};
YR_PROC_INFO* proc_info = (YR_PROC_INFO*) yr_malloc(sizeof(YR_PROC_INFO));
if (proc_info == NULL)
@@ -91,8 +89,7 @@ int _yr_process_attach(
}
int _yr_process_detach(
YR_PROC_ITERATOR_CTX* context)
int _yr_process_detach(YR_PROC_ITERATOR_CTX* context)
{
YR_PROC_INFO* proc_info = (YR_PROC_INFO*) context->proc_info;
@@ -102,8 +99,7 @@ int _yr_process_detach(
}
YR_API const uint8_t* yr_process_fetch_memory_block_data(
YR_MEMORY_BLOCK* block)
YR_API const uint8_t* yr_process_fetch_memory_block_data(YR_MEMORY_BLOCK* block)
{
YR_PROC_ITERATOR_CTX* context = (YR_PROC_ITERATOR_CTX*) block->context;
YR_PROC_INFO* proc_info = (YR_PROC_INFO*) context->proc_info;
@@ -129,11 +125,11 @@ YR_API const uint8_t* yr_process_fetch_memory_block_data(
}
io_desc.piod_op = PIOD_READ_D;
io_desc.piod_offs = (void*)block->base;
io_desc.piod_addr = (void*)context->buffer;
io_desc.piod_offs = (void*) block->base;
io_desc.piod_addr = (void*) context->buffer;
io_desc.piod_len = block->size;
if (ptrace(PT_IO, proc_info->pid, (char*)&io_desc, 0) == -1)
if (ptrace(PT_IO, proc_info->pid, (char*) &io_desc, 0) == -1)
return NULL;
return context->buffer;
@@ -146,7 +142,7 @@ YR_API YR_MEMORY_BLOCK* yr_process_get_next_memory_block(
YR_PROC_ITERATOR_CTX* context = (YR_PROC_ITERATOR_CTX*) iterator->context;
YR_PROC_INFO* proc_info = (YR_PROC_INFO*) context->proc_info;
int mib[] = { CTL_KERN, KERN_PROC_VMMAP, proc_info->pid };
int mib[] = {CTL_KERN, KERN_PROC_VMMAP, proc_info->pid};
size_t len = sizeof(struct kinfo_vmentry);
if (sysctl(mib, 3, &proc_info->vm_entry, &len, NULL, 0) < 0)
@@ -158,8 +154,8 @@ YR_API YR_MEMORY_BLOCK* yr_process_get_next_memory_block(
proc_info->old_end = proc_info->vm_entry.kve_end;
context->current_block.base = proc_info->vm_entry.kve_start;
context->current_block.size =
proc_info->vm_entry.kve_end - proc_info->vm_entry.kve_start;
context->current_block.size = proc_info->vm_entry.kve_end -
proc_info->vm_entry.kve_start;
proc_info->vm_entry.kve_start = proc_info->vm_entry.kve_start + 1;
+23 -34
View File
@@ -30,20 +30,18 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#if defined(USE_WINDOWS_PROC)
#include <windows.h>
#include <yara/mem.h>
#include <yara/error.h>
#include <yara/mem.h>
#include <yara/proc.h>
typedef struct _YR_PROC_INFO {
HANDLE hProcess;
SYSTEM_INFO si;
typedef struct _YR_PROC_INFO
{
HANDLE hProcess;
SYSTEM_INFO si;
} YR_PROC_INFO;
int _yr_process_attach(
int pid,
YR_PROC_ITERATOR_CTX* context)
int _yr_process_attach(int pid, YR_PROC_ITERATOR_CTX* context)
{
TOKEN_PRIVILEGES tokenPriv;
LUID luidDebug;
@@ -62,21 +60,14 @@ int _yr_process_attach(
tokenPriv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(
hToken,
FALSE,
&tokenPriv,
sizeof(tokenPriv),
NULL,
NULL);
hToken, FALSE, &tokenPriv, sizeof(tokenPriv), NULL, NULL);
}
if (hToken != NULL)
CloseHandle(hToken);
proc_info->hProcess = OpenProcess(
PROCESS_VM_READ | PROCESS_QUERY_INFORMATION,
FALSE,
pid);
PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
if (proc_info->hProcess == NULL)
{
@@ -92,18 +83,16 @@ int _yr_process_attach(
}
int _yr_process_detach(
YR_PROC_ITERATOR_CTX* context)
int _yr_process_detach(YR_PROC_ITERATOR_CTX* context)
{
YR_PROC_INFO* proc_info = (YR_PROC_INFO*)context->proc_info;
YR_PROC_INFO* proc_info = (YR_PROC_INFO*) context->proc_info;
CloseHandle(proc_info->hProcess);
return ERROR_SUCCESS;
}
YR_API const uint8_t* yr_process_fetch_memory_block_data(
YR_MEMORY_BLOCK* block)
YR_API const uint8_t* yr_process_fetch_memory_block_data(YR_MEMORY_BLOCK* block)
{
SIZE_T read;
@@ -129,14 +118,14 @@ YR_API const uint8_t* yr_process_fetch_memory_block_data(
}
if (ReadProcessMemory(
proc_info->hProcess,
(LPCVOID) block->base,
(LPVOID) context->buffer,
(SIZE_T) block->size,
&read) == FALSE)
{
return NULL;
}
proc_info->hProcess,
(LPCVOID) block->base,
(LPVOID) context->buffer,
(SIZE_T) block->size,
&read) == FALSE)
{
return NULL;
}
return context->buffer;
}
@@ -149,8 +138,8 @@ YR_API YR_MEMORY_BLOCK* yr_process_get_next_memory_block(
YR_PROC_INFO* proc_info = (YR_PROC_INFO*) context->proc_info;
MEMORY_BASIC_INFORMATION mbi;
PVOID address = (PVOID) (context->current_block.base + \
context->current_block.size);
PVOID address = (PVOID)(
context->current_block.base + context->current_block.size);
while (address < proc_info->si.lpMaximumApplicationAddress &&
VirtualQueryEx(proc_info->hProcess, address, &mbi, sizeof(mbi)) != 0)
@@ -182,8 +171,8 @@ YR_API YR_MEMORY_BLOCK* yr_process_get_first_memory_block(
YR_PROC_INFO* proc_info = (YR_PROC_INFO*) context->proc_info;
context->current_block.size = 0;
context->current_block.base = \
(size_t) proc_info->si.lpMinimumApplicationAddress;
context->current_block.base = (size_t)
proc_info->si.lpMinimumApplicationAddress;
return yr_process_get_next_memory_block(iterator);
}
+544 -741
View File
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More