├── data └── .gitkeep ├── .gitattributes ├── code ├── models │ ├── __init__.py │ ├── Augmenter.py │ ├── Basics.py │ ├── Chen2018.py │ ├── Nataraj2011.py │ ├── Raff2017.py │ └── Le2018.py ├── output │ └── .gitkeep ├── vendor │ └── __init__.py ├── gist-requirements.txt ├── __init__.py ├── requirements.txt └── src │ ├── gen_headerless_dataset.py │ ├── gen_dataset_npz.py │ ├── gen_injected_dataset_npz.py │ └── run_ml_model.py ├── dependencies └── pyleargist-2.0.5 │ ├── VERSION.txt │ ├── src │ ├── pyleargist.egg-info │ │ ├── dependency_links.txt │ │ ├── top_level.txt │ │ ├── SOURCES.txt │ │ └── PKG-INFO │ ├── leargist.pxd │ └── leargist.pyx │ ├── setup.cfg │ ├── MANIFEST.in │ ├── install.sh │ ├── lear_gist │ ├── ar.ppm │ ├── Makefile │ ├── standalone_image.h │ ├── gist.h │ ├── README │ ├── standalone_image.c │ ├── compute_gist.c │ └── gist.c │ ├── setup.py │ ├── README.txt │ └── PKG-INFO ├── .gitmodules ├── .dockerignore ├── .gitignore ├── run.sh ├── Dockerfile ├── README.md └── LICENSE /data/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /code/models/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /code/output/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /code/vendor/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /code/gist-requirements.txt: -------------------------------------------------------------------------------- 1 | Pillow==2.2.1 2 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/VERSION.txt: -------------------------------------------------------------------------------- 1 | 2.0.5 2 | 3 | -------------------------------------------------------------------------------- /code/__init__.py: -------------------------------------------------------------------------------- 1 | from models import * 2 | from vendor import * 3 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/src/pyleargist.egg-info/dependency_links.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/src/pyleargist.egg-info/top_level.txt: -------------------------------------------------------------------------------- 1 | leargist 2 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/setup.cfg: -------------------------------------------------------------------------------- 1 | [egg_info] 2 | tag_build = 3 | tag_date = 0 4 | tag_svn_revision = 0 5 | 6 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.txt 2 | recursive-include lear_gist README Makefile *.c *.h ar.ppm 3 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/install.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | python setup.py build 4 | sudo python setup.py install 5 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "code/vendor/pe_injector"] 2 | path = code/vendor/pe_injector 3 | url = https://github.com/adeilsonsilva/pe-modifier 4 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/lear_gist/ar.ppm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adeilsonsilva/malware-injection/HEAD/dependencies/pyleargist-2.0.5/lear_gist/ar.ppm -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | # Avoid sending following directories to build context 2 | .git/ 3 | data/ 4 | lib/ 5 | lib64/ 6 | share/ 7 | bin/ 8 | .vscode/ 9 | code/output/ 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore datasets contents 2 | data/**/ 3 | data/*.zip 4 | data/*.npz 5 | dependencies/pyleargist-2.0.5/build/ 6 | dependencies/pyleargist-2.0.5/dist/ 7 | lib/ 8 | lib64 9 | pyvenv.cfg 10 | share/ 11 | .vscode/ 12 | bin/ 13 | **/__pycache__/ 14 | code/output/**/ 15 | -------------------------------------------------------------------------------- /code/requirements.txt: -------------------------------------------------------------------------------- 1 | keras==2.6.0 2 | tensorflow==2.6.0 3 | Cython==0.29.21 4 | opencv-python==4.2.0.34 5 | numpy==1.19.2 6 | pandas==1.1.2 7 | pefile==2019.4.18 8 | #Pillow==2.2.1 # GIST dependencies 9 | scikit-image==0.17.2 10 | scikit_learn==0.23.2 11 | setuptools==41.0.1 12 | bounded-pool-executor==0.0.3 13 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/src/pyleargist.egg-info/SOURCES.txt: -------------------------------------------------------------------------------- 1 | COPYING.txt 2 | MANIFEST.in 3 | README.txt 4 | VERSION.txt 5 | setup.cfg 6 | setup.py 7 | lear_gist/Makefile 8 | lear_gist/README 9 | lear_gist/ar.ppm 10 | lear_gist/compute_gist.c 11 | lear_gist/gist.c 12 | lear_gist/gist.h 13 | lear_gist/standalone_image.c 14 | lear_gist/standalone_image.h 15 | src/leargist.pyx 16 | src/pyleargist.egg-info/PKG-INFO 17 | src/pyleargist.egg-info/SOURCES.txt 18 | src/pyleargist.egg-info/dependency_links.txt 19 | src/pyleargist.egg-info/top_level.txt -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/src/leargist.pxd: -------------------------------------------------------------------------------- 1 | cdef extern from "stdlib.h" nogil: 2 | void *memmove(void *str1, void *str2, size_t n) 3 | 4 | cdef extern from "standalone_image.h": 5 | ctypedef struct color_image_t: 6 | int width 7 | int height 8 | float *c1 # R 9 | float *c2 # G 10 | float *c3 # B 11 | 12 | cdef color_image_t* color_image_new(int width, int height) 13 | cdef void color_image_delete(color_image_t *image) 14 | 15 | cdef extern from "gist.h": 16 | cdef float* color_gist_scaletab(color_image_t* src, int nblocks, int n_scale, int* n_orientations) 17 | cdef void free_desc(float *d) 18 | 19 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/lear_gist/Makefile: -------------------------------------------------------------------------------- 1 | # Lear's GIST implementation, version 1.0, (c) INRIA 2009, Licence: GPL 2 | 3 | 4 | all: compute_gist 5 | 6 | WFFTINC= 7 | WFFTLIB= 8 | # WFFTINC=-I/scratch/adonis/mordelet/install/include 9 | # WFFTLIB=-L/scratch/adonis/mordelet/install/lib 10 | 11 | 12 | # gist.c: ../../descriptors/gist.c 13 | # cp $< $@ 14 | 15 | 16 | gist.o: gist.c gist.h standalone_image.h 17 | gcc -c -Wall -g $< $(WFFTINC) -DUSE_GIST -DSTANDALONE_GIST 18 | 19 | standalone_image.o: standalone_image.c standalone_image.h 20 | gcc -c -Wall -g $< 21 | 22 | compute_gist: compute_gist.c gist.o standalone_image.o 23 | gcc -Wall -g -o $@ $^ $(WFFTLIB) -lfftw3f 24 | 25 | 26 | 27 | clean: 28 | rm -f *.o compute_gist 29 | 30 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | IMAGE_NAME='malware-injection:latest' 4 | CONTAINER_NICKNAME='okearo' 5 | 6 | # Build container image 7 | docker build -t $IMAGE_NAME . 8 | 9 | # Remove past runs 10 | docker rm $CONTAINER_NICKNAME 11 | 12 | # Run container 13 | # Using at most 5 CPU cores 14 | # Setting container name to run commands later 15 | # Mounting a read-only volume with code to easy up development 16 | # Mounting a volume with datasets 17 | # Run with an interative bash session 18 | docker run \ 19 | --cpuset-cpus="0-4" \ 20 | --gpus all \ 21 | --name $CONTAINER_NICKNAME \ 22 | --hostname $CONTAINER_NICKNAME \ 23 | -v $(pwd)/code:/usr/src/app/code \ 24 | -v $(pwd)/data:/usr/data \ 25 | -i -t $IMAGE_NAME bash 26 | 27 | -------------------------------------------------------------------------------- /code/models/Augmenter.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import os 3 | 4 | from vendor.pe_injector.injector import PEInjector 5 | from vendor.pe_injector.shifter import PEShifter 6 | 7 | def ToNumpyByteArray(data): 8 | return np.frombuffer(data, dtype=np.uint8) 9 | 10 | class RandomPadding(object): 11 | 12 | def __init__(self, length): 13 | assert isinstance(length, int) 14 | self.length = length 15 | 16 | def __call__(self, sample): 17 | buffer = io.BytesIO(sample) 18 | 19 | buffer.write(os.urandom(self.length)) 20 | buffer.seek(0) 21 | data = buffer.read() 22 | buffer.close() 23 | 24 | return ToNumpyByteArray(data) 25 | 26 | class RandomInjection(object): 27 | 28 | def __init__(self, injection_type): 29 | assert isinstance(injection_type, tuple) 30 | self.n_bytes, self.n_sections = injection_type 31 | 32 | def __call__(self, sample): 33 | injector = PEInjector(sample, 34 | self.n_bytes, 35 | n_sections_to_inject=self.n_sections) 36 | 37 | return ToNumpyByteArray(injector.run()) 38 | 39 | class RandomReorder(object): 40 | 41 | def __init__(self): 42 | return 43 | 44 | def __call__(self, sample): 45 | shifter = PEShifter(sample) 46 | 47 | return ToNumpyByteArray(shifter.run()) 48 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | from setuptools.extension import Extension 3 | from Cython.Distutils import build_ext 4 | import sys, os 5 | import numpy as np 6 | 7 | version = open('VERSION.txt').read().strip() 8 | 9 | setup(name='pyleargist', 10 | version=version, 11 | description="GIST Image descriptor for scene recognition", 12 | long_description=open('README.txt').read(), 13 | classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers 14 | keywords=('image-processing computer-vision scene-recognition'), 15 | author='Olivier Grisel', 16 | author_email='olivier.grisel@ensta.org', 17 | url='http://www.bitbucket.org/ogrisel/pyleargist/src/tip/', 18 | license='PSL', 19 | package_dir={'': 'src'}, 20 | cmdclass = {"build_ext": build_ext}, 21 | ext_modules=[ 22 | Extension( 23 | 'leargist', [ 24 | 'lear_gist/standalone_image.c', 25 | 'lear_gist/gist.c', 26 | 'src/leargist.pyx', 27 | ], 28 | libraries=['m', 'fftw3f'], 29 | include_dirs=[np.get_include(), 'lear_gist',], 30 | extra_compile_args=['-DUSE_GIST', '-DSTANDALONE_GIST'], 31 | ), 32 | ], 33 | ) 34 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/lear_gist/standalone_image.h: -------------------------------------------------------------------------------- 1 | /* Lear's GIST implementation, version 1.0, (c) INRIA 2009, Licence: GPL */ 2 | 3 | 4 | 5 | #ifndef STANDALONE_IMAGE_H 6 | #define STANDALONE_IMAGE_H 7 | 8 | /**************************************************************************** 9 | * Image structures 10 | */ 11 | 12 | 13 | 14 | typedef struct { 15 | int width,height; /* dimensions */ 16 | int stride; /* width of image in memory */ 17 | 18 | float *data; /* data in latin reading order */ 19 | } image_t; 20 | 21 | typedef struct { 22 | int width,height; /* here, stride = width */ 23 | 24 | float *c1; /* R */ 25 | float *c2; /* G */ 26 | float *c3; /* B */ 27 | 28 | } color_image_t; 29 | 30 | image_t *image_new(int width, int height); 31 | 32 | image_t *image_cpy(image_t *src); 33 | 34 | void image_delete(image_t *image); 35 | 36 | 37 | color_image_t *color_image_new(int width, int height); 38 | 39 | color_image_t *color_image_cpy(color_image_t *src); 40 | 41 | void color_image_delete(color_image_t *image); 42 | 43 | 44 | typedef struct { 45 | int size; /* Number of images in the list */ 46 | int alloc_size; /* Number of allocated images */ 47 | 48 | image_t **data; /* List of images */ 49 | 50 | } image_list_t; 51 | 52 | 53 | image_list_t *image_list_new(void); 54 | 55 | void image_list_append(image_list_t *list, image_t *image); 56 | 57 | void image_list_delete(image_list_t *list); 58 | 59 | 60 | #endif 61 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Build from a recent python3 version (64 bit python required for Tensorflow) 2 | FROM nvidia/cuda:11.4.2-cudnn8-devel-ubuntu20.04 3 | 4 | RUN export DEBIAN_FRONTEND=noninteractive; \ 5 | apt-get update && \ 6 | apt-get install -y \ 7 | # Code is in python 8 | python3 python3-pip python3-dev python3-venv\ 9 | # OpenCV dependencies 10 | libsm6 libxext6 libxrender-dev \ 11 | # GIST dependencies 12 | build-essential libfftw3-3 libfftw3-bin libfftw3-dev libjpeg-dev zlib1g-dev libglib2.0-0 13 | 14 | # Create directories 15 | RUN mkdir -p /usr/src/app/code 16 | WORKDIR /usr/src/app/code/ 17 | 18 | # Install required python modules first, to use pip caching 19 | ADD code/requirements.txt /usr/src/app/code 20 | RUN pip3 install --upgrade pip 21 | RUN pip3 install -r requirements.txt 22 | RUN pip3 install \ 23 | torch==1.12.0+cu113 \ 24 | torchvision==0.13.0+cu113 \ 25 | -f https://download.pytorch.org/whl/torch_stable.html 26 | 27 | # Setup GIST dependencies 28 | COPY dependencies/ /usr/src/app/dependencies 29 | WORKDIR /usr/src/app/dependencies/pyleargist-2.0.5/ 30 | RUN ls -la . 31 | RUN python3 setup.py build 32 | RUN python3 setup.py install 33 | 34 | # Set NVIDIA environment variables 35 | ENV NVIDIA_VISIBLE_DEVICES all 36 | ENV NVIDIA_DRIVER_CAPABILITIES compute,utility 37 | 38 | # Set code folder to PYTHONPATH 39 | ENV PYTHONPATH "${PYTHONPATH}:/usr/src/app/code" 40 | 41 | # Set workdir back to code 42 | WORKDIR /usr/src/app/code 43 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/lear_gist/gist.h: -------------------------------------------------------------------------------- 1 | /* Lear's GIST implementation, version 1.0, (c) INRIA 2009, Licence: GPL */ 2 | 3 | 4 | #ifndef GIST_H_INCLUDED 5 | #define GIST_H_INCLUDED 6 | 7 | 8 | #include "standalone_image.h" 9 | 10 | 11 | /*! Graylevel GIST for various scales. Based on Torralba's Matlab 12 | * implementation. http://people.csail.mit.edu/torralba/code/spatialenvelope/ 13 | * 14 | * Descriptor size is w*w*sum(n_orientations[i],i=0..n_scale-1) 15 | * 16 | * @param src Source image 17 | * @param w Number of bins in x and y axis 18 | */ 19 | 20 | float *bw_gist_scaletab(image_t *src, int nblocks, int n_scale, const int *n_orientations); 21 | 22 | /*! @brief implementation of grayscale GIST descriptor. 23 | * Descriptor size is w*w*(a+b+c) 24 | * 25 | * @param src Source image 26 | * @param w Number of bins in x and y axis 27 | */ 28 | float *bw_gist(image_t *scr, int nblocks, int a, int b, int c); 29 | 30 | /*! @brief implementation of color GIST descriptor. 31 | * 32 | * @param src Source image 33 | * @param w Number of bins in x and y axis 34 | */ 35 | float *color_gist(color_image_t *src, int nblocks, int a, int b, int c); 36 | 37 | /*! Color GIST for various scales. Based on Torralba's Matlab 38 | * implementation. http://people.csail.mit.edu/torralba/code/spatialenvelope/ */ 39 | 40 | float *color_gist_scaletab(color_image_t *src, int nblocks, int n_scale, const int *n_orientations); 41 | 42 | void free_desc(float *d); 43 | 44 | 45 | #endif 46 | -------------------------------------------------------------------------------- /code/models/Basics.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | 4 | from .Data import Logger 5 | from .Data import MalImgDataset 6 | 7 | class MachineLearningModel: 8 | """ 9 | A class that defines common attributes for the ML models of this work. 10 | """ 11 | 12 | def __init__(self, path, model_name, ext='png', batch_size=64): 13 | self.logger = Logger() 14 | self.logger.info("Initializing basic ML model.") 15 | self.data_handler = MalImgDataset(path, ext, batch_size=batch_size) 16 | self.model_name = model_name 17 | self.model_paths = [] 18 | self.ext = ext 19 | self.results = {} 20 | 21 | def get_tmp_model_path(self): 22 | return self.data_handler.tmp_model_output_path + '/' + self.model_name 23 | 24 | def get_model_path(self): 25 | return self.data_handler.output_path + self.model_name 26 | 27 | def backup_old_model(self): 28 | if (os.path.isfile(self.get_model_path())): 29 | file_timestamp = time.ctime(os.path.getmtime(self.get_model_path())) 30 | os.rename(self.get_model_path(), self.get_model_path() + '_' + file_timestamp + '.backup') 31 | 32 | def test_injected(self, base_path, subdir, sections=5, bytes=5): 33 | return 34 | 35 | def save_model(self): 36 | return 37 | 38 | def load_model(self): 39 | return 40 | 41 | ######################## 42 | ### ABSTRACT METHDOS ### 43 | ######################## 44 | def build_graph(self): 45 | return 46 | 47 | def train(self): 48 | return 49 | 50 | def _train(self): 51 | return 52 | 53 | def _test(self): 54 | return 55 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/lear_gist/README: -------------------------------------------------------------------------------- 1 | 2 | 3 | What is this 4 | ============ 5 | 6 | This is a library and an exectuable that reimplement A. Torralba's 7 | GIST image descriptor in C. The original Matlab implementation is 8 | here: 9 | 10 | http://people.csail.mit.edu/torralba/code/spatialenvelope/ 11 | 12 | How to compile 13 | ============== 14 | 15 | The library depends on fftw3. It is available at: 16 | 17 | http://www.fftw.org/ 18 | 19 | or along with your Linux distribution. Versions 3.1.2 and 3.2.1 work. 20 | 21 | If it is installed in a non-standard location, set the WFFTINC and 22 | WFFTLIB accordingly in the Makefile. 23 | 24 | The code compiles on linux 32 and 64 bit with gcc 4.2.1. It has not 25 | been tested on other platforms. 26 | 27 | How to test 28 | =========== 29 | 30 | The library comes with a mini-executable that computes the GIST 31 | descriptor of a PPM image. To test: 32 | 33 | ./compute_gist ar.ppm 34 | 35 | Should display 960 float values that start with: 36 | 37 | 0.0579 0.1926 0.0933 0.0662 .... 38 | 39 | and end with 40 | 41 | .... 0.0563 0.0575 0.0640 42 | 43 | The code works on non-square images, but it is of little interest: 44 | descriptors computed on images of different sizes are not comparable. 45 | 46 | The library should compute the exact same descriptor as the Matlab 47 | version. Be careful that encoding a small image in JPEG (even with the 48 | maximum quality factor) changes the descriptor. 49 | 50 | Quizz: where does the ar.ppm test image come from? 51 | 52 | Who made it 53 | =========== 54 | 55 | The library was developed in 2009 in the Lear group at INRIA. It was 56 | used in 57 | 58 | @INPROCEEDINGS{JDSAS09, 59 | author = {Matthijs Douze and Herve Jegou and Harsimrat Singh and Laurent Amsaleg 60 | and Cordelia Schmid}, 61 | title = {Evaluation of GIST descriptors for web-scale image search}, 62 | booktitle = {civr}, 63 | year = {2009}, 64 | } 65 | 66 | Licence: GPL 67 | 68 | Comments, complaints to: matthijs.douze@inria.fr 69 | 70 | History 71 | ======= 72 | 73 | jan 2009: Reimplementation of GIST added to Lear's internal image 74 | processing library by Christophe Smekens. 75 | 76 | jul 2009: Standalone version packaged by Matthijs Douze 77 | 78 | 79 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/lear_gist/standalone_image.c: -------------------------------------------------------------------------------- 1 | /* Lear's GIST implementation, version 1.0, (c) INRIA 2009, Licence: GPL */ 2 | #include 3 | #include 4 | 5 | 6 | #include "standalone_image.h" 7 | 8 | #define NEWA(type,n) (type*)malloc(sizeof(type)*(n)) 9 | #define NEW(type) NEWA(type,1) 10 | 11 | image_t *image_new(int width, int height) { 12 | image_t *im=NEW(image_t); 13 | im->width=im->stride=width; 14 | im->height=height; 15 | int wh=width*height; 16 | im->data=NEWA(float,wh); 17 | return im; 18 | } 19 | 20 | image_t *image_cpy(image_t *src) { 21 | image_t *im=image_new(src->width,src->height); 22 | memcpy(im->data,src->data,sizeof(*(src->data))*src->width*src->height); 23 | return im; 24 | } 25 | 26 | void image_delete(image_t *im) { 27 | free(im->data); 28 | free(im); 29 | } 30 | 31 | 32 | color_image_t *color_image_new(int width, int height) { 33 | color_image_t *im=NEW(color_image_t); 34 | im->width=width; 35 | im->height=height; 36 | int wh=width*height; 37 | im->c1=NEWA(float,wh); 38 | im->c2=NEWA(float,wh); 39 | im->c3=NEWA(float,wh); 40 | return im; 41 | } 42 | 43 | color_image_t *color_image_cpy(color_image_t *src) { 44 | color_image_t *im=color_image_new(src->width,src->height); 45 | memcpy(im->c1,src->c1,sizeof(*(src->c1))*src->width*src->height); 46 | memcpy(im->c2,src->c2,sizeof(*(src->c1))*src->width*src->height); 47 | memcpy(im->c3,src->c3,sizeof(*(src->c1))*src->width*src->height); 48 | return im; 49 | } 50 | 51 | void color_image_delete(color_image_t *im) { 52 | free(im->c1); 53 | free(im->c2); 54 | free(im->c3); 55 | free(im); 56 | } 57 | 58 | 59 | 60 | image_list_t *image_list_new(void) { 61 | image_list_t *list=NEW(image_list_t); 62 | list->size=list->alloc_size=0; 63 | list->data=NULL; 64 | return list; 65 | } 66 | 67 | void image_list_append(image_list_t *list, image_t *image) { 68 | if(list->size==list->alloc_size) { 69 | list->alloc_size=(list->alloc_size+1)*3/2; 70 | list->data=realloc(list->data,sizeof(*list->data)*list->alloc_size); 71 | } 72 | list->data[list->size++]=image; 73 | } 74 | 75 | void image_list_delete(image_list_t *list) { 76 | int i; 77 | 78 | for(i=0;isize;i++) 79 | image_delete(list->data[i]); 80 | free(list->data); 81 | free(list); 82 | } 83 | 84 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/README.txt: -------------------------------------------------------------------------------- 1 | Python Wrapper for the LEAR image descriptor implementation 2 | =========================================================== 3 | 4 | :author: 5 | 6 | Library to compute GIST global image descriptors to be used to compare pictures 7 | based on their content (to be used global scene recognition and categorization). 8 | 9 | The GIST image descriptor theoritical definition can be found on A. Torralba's 10 | page: http://people.csail.mit.edu/torralba/code/spatialenvelope/ 11 | 12 | The source code of the C implementation is included in the ``lear_gist`` 13 | subfolder. See http://lear.inrialpes.fr/software for the original project 14 | information. 15 | 16 | pyleargist is licensed under the GPL, the same license as the original C 17 | project. 18 | 19 | 20 | Install 21 | ------- 22 | 23 | Install libfftw3 with development headers (http://www.fftw.org), python dev 24 | headers, gcc, the Python Imaging Library (PIL) and numpy. 25 | 26 | Build locally for testing:: 27 | 28 | % python setup.py buid_ext -i 29 | % export PYTHONPATH=`pwd`/src 30 | 31 | Build and install system wide:: 32 | 33 | % python setup.py build 34 | % sudo python setup.py install 35 | 36 | 37 | Usage 38 | ----- 39 | 40 | Here is a sample session in a python shell once the library is installed:: 41 | 42 | >>> from PIL import Image 43 | >>> import leargist 44 | 45 | >>> im = Image.open('lear_gist/ar.ppm') 46 | >>> descriptors = leargist.color_gist(im) 47 | 48 | >>> descriptors.shape 49 | (960,) 50 | 51 | >>> descriptors.dtype 52 | dtype('float32') 53 | 54 | >>> descriptors[:4] 55 | array([ 0.05786307, 0.19255637, 0.09331483, 0.06622448], dtype=float32) 56 | 57 | 58 | The GIST descriptors (fixed size, 960 by default) can then be used as an 59 | euclidian space to cluster images based on their content. 60 | 61 | This dimension can then be reduced to a 32 or 64 bits semantic hash by using 62 | Locality Sensitive Hashing, Spectral Hashing or Stacked Denoising Autoencoders. 63 | 64 | A sample implementation of picture semantic hashing with SDAs is showcased in 65 | the libsgd library: http://code.oliviergrisel.name/libsgd 66 | 67 | Changes 68 | ------- 69 | 70 | - 1.1.0: 2010/03/25 - fix segmentation fault bug, thx to S. Campion 71 | 72 | - 1.0.1: 2009/10/10 - added missing missing MANIFEST 73 | 74 | - 1.0.0: 2009/10/10 - initial release 75 | 76 | -------------------------------------------------------------------------------- /code/src/gen_headerless_dataset.py: -------------------------------------------------------------------------------- 1 | # Import Python modules 2 | import argparse 3 | import os 4 | import numpy as np 5 | import sys 6 | import pefile 7 | 8 | # Import User packages 9 | from models.Data import MalImgDataset 10 | 11 | def get_args(argv=None): 12 | parser = argparse.ArgumentParser(description="Paper Title") 13 | 14 | parser.add_argument( 15 | '-i', 16 | '--input', 17 | required=True, 18 | help='Path to input malware dataset folder.' 19 | ) 20 | parser.add_argument( 21 | '-o', 22 | '--output', 23 | required=True, 24 | help='Path to save dataset files at.' 25 | ) 26 | parser.add_argument( 27 | '-e', 28 | '--extension', 29 | choices=[ 30 | 'png', 31 | 'exe', 32 | ], 33 | required=True, 34 | help='Dataset file extension.' 35 | ) 36 | 37 | return parser.parse_args(argv) 38 | 39 | def gen_dataset(data_handler, base_path): 40 | images = [] 41 | labels = [] 42 | data_array = data_handler.get_all_data() 43 | for s_tuple in data_array: 44 | exe_path = s_tuple[0] 45 | # Search class map for class name with given label 46 | label = [k for (k, v) in data_handler.class_map.items() if v == s_tuple[1]][0] 47 | 48 | save_path = os.path.abspath(f"{base_path}/{label}") 49 | if not os.path.isdir(save_path): 50 | print(f"Creating {save_path}") 51 | os.makedirs(save_path) 52 | 53 | # use malware only 54 | # if label == 1: 55 | # continue 56 | 57 | m_pe = pefile.PE(exe_path) 58 | 59 | # We need to retrieve the size of the header 60 | # If we call pe.get_data() with no parameters it returns the whole header 61 | # https://github.com/erocarrera/pefile/blob/c9e8c59b56cfa14dbeca8cb9e33d3d84056102a6/pefile.py#L5848 62 | header_size = len(m_pe.get_data()) 63 | bin_stream = np.fromfile(exe_path, dtype='uint8') 64 | 65 | _hash = exe_path.split('/')[-1] 66 | 67 | file_path = os.path.abspath(f"{save_path}/{_hash}") 68 | # print(file_path) 69 | bin_stream[header_size:].tofile(file_path) 70 | 71 | 72 | def main(args): 73 | 74 | input_path = os.path.abspath(args.input) 75 | output_path = os.path.abspath(args.output) 76 | 77 | # Check if path exists 78 | if not os.path.isdir(input_path): 79 | raise Exception("The provided path is not a valid dataset.") 80 | 81 | data_handler = MalImgDataset(input_path, args.extension) 82 | data_handler.split_dataset() 83 | data_handler.compute_fold_split() 84 | 85 | gen_dataset(data_handler, args.output) 86 | 87 | if __name__ == "__main__": 88 | arguments = get_args() 89 | 90 | main(arguments) 91 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/src/leargist.pyx: -------------------------------------------------------------------------------- 1 | from libc.stdlib cimport free 2 | 3 | from cpython cimport PyObject, Py_INCREF 4 | import cython 5 | 6 | cimport leargist 7 | import numpy as np 8 | cimport numpy as np 9 | np.import_array() 10 | 11 | cdef extern from "stdlib.h" nogil: 12 | void *memmove(void *str1, void *str2, size_t n) 13 | 14 | cdef extern from "standalone_image.h": 15 | ctypedef struct color_image_t: 16 | int width 17 | int height 18 | float *c1 # R 19 | float *c2 # G 20 | float *c3 # B 21 | cdef color_image_t* color_image_new(int width, int height) 22 | cdef void color_image_delete(color_image_t *image) 23 | 24 | cdef extern from "gist.h": 25 | cdef float* color_gist_scaletab(color_image_t* src, int nblocks, int n_scale, int* n_orientations) 26 | cdef void free_desc(float *d) 27 | 28 | def color_gist(im, nblocks=4, orientations=(8, 8, 4)): 29 | """Compute the GIST descriptor of an RGB image""" 30 | scales = len(orientations) 31 | orientations = np.array(orientations, dtype=np.int32) 32 | 33 | # check minimum image size 34 | if im.size[0] < 8 or im.size[1] < 8: 35 | raise ValueError( 36 | "image size should at least be (8, 8), got %r" % (im.size,)) 37 | 38 | # ensure the image is encoded in RGB 39 | im = im.convert(mode='RGB') 40 | 41 | # build the lear_gist color image C datastructure 42 | arr = np.fromstring(im.tostring(), np.uint8) 43 | arr.shape = list(im.size) + [3] 44 | arr = arr.transpose(2, 0, 1) 45 | arr = np.ascontiguousarray(arr, dtype=np.float32) 46 | 47 | width, height = im.size 48 | cdef leargist.color_image_t* _c_color_image_t = leargist.color_image_new(width, height) 49 | 50 | 51 | size = width * height * cython.sizeof(cython.float) 52 | memmove(_c_color_image_t.c1, np.PyArray_DATA(arr[0]), size ) 53 | memmove(_c_color_image_t.c2, np.PyArray_DATA(arr[1]), size ) 54 | memmove(_c_color_image_t.c3, np.PyArray_DATA(arr[2]), size ) 55 | 56 | cdef int nb = nblocks 57 | cdef int s = scales 58 | cdef int* no = np.PyArray_DATA(orientations) 59 | array = leargist.color_gist_scaletab(_c_color_image_t, nb, s, no) 60 | leargist.color_image_delete(_c_color_image_t) 61 | 62 | cdef np.npy_intp dim = nblocks * nblocks * orientations.sum() * 3 63 | cdef np.ndarray g = np.PyArray_SimpleNewFromData(1, &dim, np.NPY_FLOAT, 64 | array) 65 | r = g.copy() 66 | free(array) 67 | return r 68 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/lear_gist/compute_gist.c: -------------------------------------------------------------------------------- 1 | /* Lear's GIST implementation, version 1.0, (c) INRIA 2009, Licence: GPL */ 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | 8 | #include "gist.h" 9 | 10 | 11 | 12 | static color_image_t *load_ppm(const char *fname) { 13 | FILE *f=fopen(fname,"r"); 14 | if(!f) { 15 | perror("could not open infile"); 16 | exit(1); 17 | } 18 | int width,height,maxval; 19 | if(fscanf(f,"P6 %d %d %d",&width,&height,&maxval)!=3 || 20 | maxval!=255) { 21 | fprintf(stderr,"Error: input not a raw PPM with maxval 255\n"); 22 | exit(1); 23 | } 24 | fgetc(f); /* eat the newline */ 25 | color_image_t *im=color_image_new(width,height); 26 | 27 | int i; 28 | for(i=0;ic1[i]=fgetc(f); 30 | im->c2[i]=fgetc(f); 31 | im->c3[i]=fgetc(f); 32 | } 33 | 34 | fclose(f); 35 | return im; 36 | } 37 | 38 | 39 | static void usage(void) { 40 | fprintf(stderr,"compute_gist options... [infilename]\n" 41 | "infile is a PPM raw file\n" 42 | "options:\n" 43 | "[-nblocks nb] use a grid of nb*nb cells (default 4)\n" 44 | "[-orientationsPerScale o_1,..,o_n] use n scales and compute o_i orientations for scale i\n" 45 | ); 46 | 47 | exit(1); 48 | } 49 | 50 | 51 | 52 | int main(int argc,char **args) { 53 | 54 | const char *infilename="/dev/stdin"; 55 | int nblocks=4; 56 | int n_scale=3; 57 | int orientations_per_scale[50]={8,8,4}; 58 | 59 | 60 | while(*++args) { 61 | const char *a=*args; 62 | 63 | if(!strcmp(a,"-h")) usage(); 64 | else if(!strcmp(a,"-nblocks")) { 65 | if(!sscanf(*++args,"%d",&nblocks)) { 66 | fprintf(stderr,"could not parse %s argument",a); 67 | usage(); 68 | } 69 | } else if(!strcmp(a,"-orientationsPerScale")) { 70 | char *c; 71 | n_scale=0; 72 | for(c=strtok(*++args,",");c;c=strtok(NULL,",")) { 73 | if(!sscanf(c,"%d",&orientations_per_scale[n_scale++])) { 74 | fprintf(stderr,"could not parse %s argument",a); 75 | usage(); 76 | } 77 | } 78 | } else { 79 | infilename=a; 80 | } 81 | } 82 | 83 | color_image_t *im=load_ppm(infilename); 84 | 85 | float *desc=color_gist_scaletab(im,nblocks,n_scale,orientations_per_scale); 86 | 87 | int i; 88 | 89 | int descsize=0; 90 | /* compute descriptor size */ 91 | for(i=0;i 13 | 14 | Library to compute GIST global image descriptors to be used to compare pictures 15 | based on their content (to be used global scene recognition and categorization). 16 | 17 | The GIST image descriptor theoritical definition can be found on A. Torralba's 18 | page: http://people.csail.mit.edu/torralba/code/spatialenvelope/ 19 | 20 | The source code of the C implementation is included in the ``lear_gist`` 21 | subfolder. See http://lear.inrialpes.fr/software for the original project 22 | information. 23 | 24 | pyleargist is licensed under the GPL, the same license as the original C 25 | project. 26 | 27 | 28 | Install 29 | ------- 30 | 31 | Install libfftw3 with development headers (http://www.fftw.org), python dev 32 | headers, gcc, the Python Imaging Library (PIL) and numpy. 33 | 34 | Build locally for testing:: 35 | 36 | % python setup.py buid_ext -i 37 | % export PYTHONPATH=`pwd`/src 38 | 39 | Build and install system wide:: 40 | 41 | % python setup.py build 42 | % sudo python setup.py install 43 | 44 | 45 | Usage 46 | ----- 47 | 48 | Here is a sample session in a python shell once the library is installed:: 49 | 50 | >>> from PIL import Image 51 | >>> import leargist 52 | 53 | >>> im = Image.open('lear_gist/ar.ppm') 54 | >>> descriptors = leargist.color_gist(im) 55 | 56 | >>> descriptors.shape 57 | (960,) 58 | 59 | >>> descriptors.dtype 60 | dtype('float32') 61 | 62 | >>> descriptors[:4] 63 | array([ 0.05786307, 0.19255637, 0.09331483, 0.06622448], dtype=float32) 64 | 65 | 66 | The GIST descriptors (fixed size, 960 by default) can then be used as an 67 | euclidian space to cluster images based on their content. 68 | 69 | This dimension can then be reduced to a 32 or 64 bits semantic hash by using 70 | Locality Sensitive Hashing, Spectral Hashing or Stacked Denoising Autoencoders. 71 | 72 | A sample implementation of picture semantic hashing with SDAs is showcased in 73 | the libsgd library: http://code.oliviergrisel.name/libsgd 74 | 75 | Changes 76 | ------- 77 | 78 | - 1.1.0: 2010/03/25 - fix segmentation fault bug, thx to S. Campion 79 | 80 | - 1.0.1: 2009/10/10 - added missing missing MANIFEST 81 | 82 | - 1.0.0: 2009/10/10 - initial release 83 | 84 | 85 | Keywords: image-processing computer-vision scene-recognition 86 | Platform: UNKNOWN 87 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/src/pyleargist.egg-info/PKG-INFO: -------------------------------------------------------------------------------- 1 | Metadata-Version: 1.0 2 | Name: pyleargist 3 | Version: 2.0.5 4 | Summary: GIST Image descriptor for scene recognition 5 | Home-page: http://www.bitbucket.org/ogrisel/pyleargist/src/tip/ 6 | Author: Olivier Grisel 7 | Author-email: olivier.grisel@ensta.org 8 | License: PSL 9 | Description: Python Wrapper for the LEAR image descriptor implementation 10 | =========================================================== 11 | 12 | :author: 13 | 14 | Library to compute GIST global image descriptors to be used to compare pictures 15 | based on their content (to be used global scene recognition and categorization). 16 | 17 | The GIST image descriptor theoritical definition can be found on A. Torralba's 18 | page: http://people.csail.mit.edu/torralba/code/spatialenvelope/ 19 | 20 | The source code of the C implementation is included in the ``lear_gist`` 21 | subfolder. See http://lear.inrialpes.fr/software for the original project 22 | information. 23 | 24 | pyleargist is licensed under the GPL, the same license as the original C 25 | project. 26 | 27 | 28 | Install 29 | ------- 30 | 31 | Install libfftw3 with development headers (http://www.fftw.org), python dev 32 | headers, gcc, the Python Imaging Library (PIL) and numpy. 33 | 34 | Build locally for testing:: 35 | 36 | % python setup.py buid_ext -i 37 | % export PYTHONPATH=`pwd`/src 38 | 39 | Build and install system wide:: 40 | 41 | % python setup.py build 42 | % sudo python setup.py install 43 | 44 | 45 | Usage 46 | ----- 47 | 48 | Here is a sample session in a python shell once the library is installed:: 49 | 50 | >>> from PIL import Image 51 | >>> import leargist 52 | 53 | >>> im = Image.open('lear_gist/ar.ppm') 54 | >>> descriptors = leargist.color_gist(im) 55 | 56 | >>> descriptors.shape 57 | (960,) 58 | 59 | >>> descriptors.dtype 60 | dtype('float32') 61 | 62 | >>> descriptors[:4] 63 | array([ 0.05786307, 0.19255637, 0.09331483, 0.06622448], dtype=float32) 64 | 65 | 66 | The GIST descriptors (fixed size, 960 by default) can then be used as an 67 | euclidian space to cluster images based on their content. 68 | 69 | This dimension can then be reduced to a 32 or 64 bits semantic hash by using 70 | Locality Sensitive Hashing, Spectral Hashing or Stacked Denoising Autoencoders. 71 | 72 | A sample implementation of picture semantic hashing with SDAs is showcased in 73 | the libsgd library: http://code.oliviergrisel.name/libsgd 74 | 75 | Changes 76 | ------- 77 | 78 | - 1.1.0: 2010/03/25 - fix segmentation fault bug, thx to S. Campion 79 | 80 | - 1.0.1: 2009/10/10 - added missing missing MANIFEST 81 | 82 | - 1.0.0: 2009/10/10 - initial release 83 | 84 | 85 | Keywords: image-processing computer-vision scene-recognition 86 | Platform: UNKNOWN 87 | -------------------------------------------------------------------------------- /code/src/gen_injected_dataset_npz.py: -------------------------------------------------------------------------------- 1 | # Import Python modules 2 | import argparse 3 | import os 4 | import numpy as np 5 | import sys 6 | import random 7 | 8 | # Import User packages 9 | from models.Data import MalImgDataset 10 | 11 | def get_args(argv=None): 12 | parser = argparse.ArgumentParser(description="Paper Title") 13 | 14 | parser.add_argument( 15 | '-i', 16 | '--input', 17 | required=True, 18 | help='Path to input malware dataset folder.' 19 | ) 20 | parser.add_argument( 21 | '-o', 22 | '--output', 23 | required=True, 24 | help='Path to save npz file at.' 25 | ) 26 | parser.add_argument( 27 | '-t', 28 | '--type', 29 | choices=[ 30 | 'raw', 31 | 'sequences', 32 | 'image', 33 | ], 34 | required=True, 35 | help='Data type to be interpreted.' 36 | ) 37 | parser.add_argument( 38 | '-e', 39 | '--extension', 40 | choices=[ 41 | 'png', 42 | 'exe', 43 | ], 44 | required=True, 45 | help='Dataset file extension.' 46 | ) 47 | parser.add_argument( 48 | '-m', 49 | '--method', 50 | choices=[ 51 | 'binary', 52 | 'family', 53 | ], 54 | required=True, 55 | help='Dataset type.' 56 | ) 57 | parser.add_argument( 58 | '-d', 59 | '--datatype', 60 | choices=[ 61 | 'random', 62 | 'adversarial', 63 | ], 64 | required=True, 65 | help='Data type to be injected.' 66 | ) 67 | parser.add_argument( 68 | "-nb", 69 | "--number_of_bytes", 70 | type=int, 71 | default=1, 72 | help="Multiplier of FileAlignment" 73 | ) 74 | parser.add_argument( 75 | "-ns", 76 | "--number_of_sections", 77 | type=int, 78 | default=1, 79 | help="Number of injected sections" 80 | ) 81 | 82 | return parser.parse_args(argv) 83 | 84 | def load_raw_exe_data(data_handler, random_data=False, binary=False, n_injected_sections=1, n_bytes=1): 85 | images = [] 86 | labels = [] 87 | data_array = np.array(data_handler.get_all_data()) 88 | 89 | if binary == True: 90 | # If using a binary dataset inject only the malware class 91 | valid_labels = ['1'] 92 | else: 93 | valid_labels = [str(x[1]) for x in list(data_handler.class_map.items())] 94 | 95 | for str_label in valid_labels: 96 | label = int(str_label) 97 | print(f"Injecting in class {[k for (k, v) in data_handler.class_map.items() if v == label][0]}") 98 | 99 | # Split paths into positive and negative samples (one against all) 100 | # use malware only 101 | malware_paths = data_array[np.where(data_array[:, 1] == str_label)][:,0] 102 | 103 | benigns_data = data_array[np.where(data_array[:, 1] != str_label)] 104 | benigns_paths = benigns_data[:,0] 105 | benigns_set_size = benigns_paths.shape[0] 106 | 107 | for exe_path in malware_paths: 108 | if random_data == False: 109 | # Select a random negative as source for data injection 110 | benigns_sample = benigns_paths[random.randint(0, benigns_set_size-1)] 111 | # print(f"[@] Injecting {exe_path} with {benigns_sample}.") 112 | else: 113 | benigns_sample = None 114 | 115 | # Inject malware with benign data 116 | bin_stream = data_handler.inject_from_file(exe_path, 117 | benigns_sample, 118 | n_injected_sections=n_injected_sections, 119 | n_bytes=n_bytes, 120 | height=None, 121 | width=None, 122 | return_raw=True) 123 | images.append(bin_stream) 124 | labels.append(label) 125 | 126 | # Add benigns without injecting 127 | if binary is True: 128 | print(f"Saving benign samples") 129 | X, y = data_handler.load_raw_exe(benigns_data, categorical_y=False) 130 | for k in range(X.shape[0]): 131 | images.append(X[k]) 132 | labels.append(y[k]) 133 | 134 | return np.array(images, dtype=object), labels, data_handler.class_map 135 | 136 | 137 | def main(args): 138 | 139 | # Check if path exists 140 | if not os.path.isdir(args.input): 141 | raise Exception("The provided path is not a valid dataset.") 142 | 143 | use_random_data = True if args.datatype == 'random' else False 144 | binary_dataset = True if args.method == 'binary' else False 145 | 146 | data_handler = MalImgDataset(args.input, args.extension) 147 | data_handler.split_dataset() 148 | data_handler.compute_fold_split() 149 | 150 | if args.extension == 'exe' and args.type == 'raw': 151 | X, y, class_map = load_raw_exe_data(data_handler, 152 | random_data=use_random_data, 153 | binary=binary_dataset, 154 | n_injected_sections=args.number_of_sections, 155 | n_bytes=args.number_of_bytes) 156 | print(f"Data: {X.shape} x {len(y)}") 157 | print(f"Classes: {class_map}") 158 | 159 | os.chdir(sys.path[0]) 160 | print(f"Current: {os.getcwd()}") 161 | 162 | np.savez(args.output, X=X, y=y, class_map=class_map) 163 | 164 | if __name__ == "__main__": 165 | arguments = get_args() 166 | 167 | main(arguments) 168 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | On deceiving malware classification with section injection 2 | === 3 | 4 | This repo provides the official implementation for "On deceiving malware classification with section injection", available at: https://arxiv.org/abs/2208.06092 5 | 6 | # Installation 7 | 8 | Clone the project. 9 | ```bash 10 | git clone https://github.com/adeilsonsilva/malware-injection 11 | ``` 12 | ## Using the Docker Container 13 | 14 | > Copy your datasets to [`data`](data/) directory, as the container will have a volume attached to it. 15 | 16 | Run the following script to build and run the image: 17 | ```bash 18 | ./run.sh 19 | ``` 20 | 21 | If you run this script, you're all set to use the machine learning models. To use GIST, you're better off using the virtual environment (it requires some quirk and outdated libraries). 22 | 23 | ## Using a virtual environment 24 | 25 | ```bash 26 | python3 -m venv . 27 | source bin/activate 28 | pip3 install --user -r gist-requirements.txt 29 | 30 | # * Do whatever you want * 31 | 32 | deactivate # quit from venv 33 | ``` 34 | 35 | ## External Dependencies 36 | 37 | ### Data injection 38 | 39 | This repo depends on [pe-modifier](https://github.com/adeilsonsilva/pe-modifier/) as git a submodule. Remember to install it by using: 40 | 41 | ```bash 42 | git submodule update --init 43 | ``` 44 | 45 | ### Drivers NVIDIA 46 | > Our models were trained using **Tensorflow GPU 2.3.0**, which uses **CUDA 10.1** [[Source]](https://www.tensorflow.org/install/source#linux). To proceed with instalation: 47 | 48 | * You can use `nvidia-docker` to run the provided container with 49 | host GPUs, assuming you have everything setup locally. Check out nvidia-docker [from its source](https://github.com/NVIDIA/nvidia-docker) or install it using [this script](dependencies/install_nvidia-docker.sh). 50 | 51 | * You can use [this script](dependencies/install_cuda_10.1.sh) to install all nvidia drives and cuda 10.1 locally on your machine. 52 | 53 | ## Internal Libraries 54 | 55 | 56 | ### Running without Docker 57 | 58 | If you don't want to use docker (you should!), make sure to install following libraries: 59 | ``` 60 | python3 61 | python3-pip 62 | libfftw3-3 63 | ``` 64 | 65 | Then proceed with python requirements to use the machine learning models: 66 | ``` 67 | cd code 68 | pip3 install -r requirements.txt 69 | ``` 70 | 71 | #### GIST 72 | 73 | If you're interested in using GIST algorithm, install its dependencies: 74 | ``` 75 | cd code 76 | pip3 install -r gist-requirements.txt 77 | cd ../dependencies/pyleargist-2.0.5/ 78 | python3 setup.py build 79 | python3 setup.py install --user 80 | ``` 81 | 82 | # Usage 83 | 84 | ## Running the code 85 | 86 | This project is structured to use separate scripts. They are all in `code` directory, change to it in case you are **not** using the docker container. 87 | 88 | The main scripts for training/handling data are inside `src`: 89 | 90 | ```bash 91 | ├── src 92 | │   ├── gen_dataset_npz.py # Converts a existing dataset to npz 93 | │   ├── gen_headerless_dataset.py # Generate a headerless version of the dataset 94 | │   ├── gen_injected_dataset_npz.py # Generates an injected dataset (.npz) 95 | │   └── run_ml_model.py # Main script used for training/testing. 96 | ``` 97 | 98 | You can also check `models` directory to check used architectures: 99 | 100 | ```bash 101 | ├── models 102 | │   ├── Augmenter.py # Module with code used for data augmentation (data injection/reordering) 103 | │   ├── Chen2018.py # Module with Inception architecture 104 | │   ├── Data.py # Main data handler module with various wrappers 105 | │   ├── Le2018.py # Module with cnn/lstm variations 106 | │   ├── Nataraj2011.py # Module with KNN 107 | ``` 108 | 109 | # Citation 110 | 111 | To cite the paper, kindly use the following BibTex entry: 112 | ``` 113 | @misc{Silva2022, 114 | doi = {10.48550/ARXIV.2208.06092}, 115 | url = {https://arxiv.org/abs/2208.06092}, 116 | author = {da Silva, Adeilson Antonio and Segundo, Mauricio Pamplona}, 117 | keywords = {Cryptography and Security (cs.CR), Machine Learning (cs.LG), FOS: Computer and information sciences, FOS: Computer and information sciences}, 118 | title = {On deceiving malware classification with section injection}, 119 | publisher = {arXiv}, 120 | year = {2022}, 121 | copyright = {Creative Commons Attribution Non Commercial No Derivatives 4.0 International} 122 | } 123 | ``` 124 | 125 | # Troubleshooting 126 | 127 | ## A. My dataset is not loaded correctly 128 | 129 | ### A.1 - The required architecture needed for the dataset handler is: 130 | 131 | ```bash 132 | dataset/ 133 | ├── benign 134 | │   ├── sample1.exe 135 | │   ├── ... 136 | │   └── sampleN.exe 137 | └── malware 138 | ├── sample1.exe 139 | ├── ... 140 | └── sampleN.exe 141 | 142 | ``` 143 | 144 | If you are not going for the binary problem check if your families are in the [allowed list](./code/models/Data.py). 145 | 146 | ## Different performances using png vs exe using BiCNN-LSTM 147 | 148 | ``` 149 | # Load as image 150 | image = cv2.imread(path_img, cv2.IMREAD_GRAYSCALE) 151 | image_reshaped = image.reshape(image.shape[0]*image.shape[1], 1) 152 | image_final = cv2.resize(image_reshaped, (height, width)) 153 | ``` 154 | 155 | ``` 156 | # Load as exe 157 | bin_stream = np.fromfile(path_exe, dtype='uint8') 158 | bin_stream_reshaped = bin_stream.reshape(bin_stream.shape[0], 1) 159 | bin_final = cv2.resize(bin_stream, (height, width)) 160 | ``` 161 | 1. Those methods may produce different results. `np.fromfile` is not adequate for opening png images, it does not read all bytes. Use it strictly for opening binary (or txt) files, as per its [documentation](https://numpy.org/doc/stable/reference/generated/numpy.fromfile.html) 162 | 2. When converting to exe's to images using Nataraj's method, some bytes at the end of the file might be discarded, so if you load both an image and an exe using the methods above their results after reshaping/resizing might not be the same. 163 | 164 | 165 | # License 166 | ``` 167 | Copyright 2022 Adeilson Silva 168 | 169 | Licensed under the Apache License, Version 2.0 (the "License"); 170 | you may not use this file except in compliance with the License. 171 | You may obtain a copy of the License at 172 | 173 | http://www.apache.org/licenses/LICENSE-2.0 174 | 175 | Unless required by applicable law or agreed to in writing, software 176 | distributed under the License is distributed on an "AS IS" BASIS, 177 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 178 | See the License for the specific language governing permissions and 179 | limitations under the License. 180 | -------------------------------------------------------------------------------- /code/src/run_ml_model.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright 2022 Adeilson Silva 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # ========================================================================= 17 | 18 | # Import Python modules 19 | import argparse 20 | import os 21 | 22 | # Import User packages 23 | from models import Data 24 | from models import Chen2018 25 | from models import Le2018 26 | from models import Nataraj2011 27 | from models import Raff2017 28 | from models.Augmenter import RandomInjection, RandomReorder 29 | 30 | def get_args(argv=None): 31 | parser = argparse.ArgumentParser(description="Paper Title") 32 | 33 | parser.add_argument( 34 | '-p', 35 | '--path', 36 | required=True, 37 | help='Path to malware dataset folder.' 38 | ) 39 | parser.add_argument( 40 | '-t', 41 | '--technique', 42 | choices=[ 43 | 'knn_gist', 44 | 'knn_lbp', 45 | 'malconv', 46 | 'le2018-cnn', 47 | 'le2018-cnn-lstm', 48 | 'le2018-cnn-lstm-bidirectional', 49 | 'inceptionv1', 50 | ], 51 | required=True, 52 | help='Technique to be trained/tested.' 53 | ) 54 | parser.add_argument( 55 | "-f", 56 | "--folds", 57 | type=int, 58 | default=1, 59 | help="Number of folds to be used." 60 | ) 61 | parser.add_argument( 62 | "-sm", 63 | "--split_method", 64 | choices=[ 65 | 'nataraj', 66 | 'stratified_kfold', 67 | 'regular_kfold', 68 | ], 69 | default='nataraj', 70 | help="Method use to split the dataset samples in train/validation/test." 71 | ) 72 | parser.add_argument( 73 | "-e", 74 | "--extension", 75 | required=True, 76 | help="File extension of dataset files" 77 | ) 78 | parser.add_argument( 79 | "-w", 80 | "--width", 81 | type=int, 82 | default=1e4, 83 | help="Width to be used for cnn-lstm model" 84 | ) 85 | parser.add_argument( 86 | "-m", 87 | "--max_epochs", 88 | type=int, 89 | default=200, 90 | help="Maximum number of epochs" 91 | ) 92 | parser.add_argument( 93 | "-pa", 94 | "--patience", 95 | type=int, 96 | default=10, 97 | help="Maximum number of epochs" 98 | ) 99 | parser.add_argument( 100 | "-bs", 101 | "--batch_size", 102 | type=int, 103 | default=512, 104 | help="Size of each training batch" 105 | ) 106 | parser.add_argument( 107 | "--use-subset", 108 | default=False, 109 | help="Use subset" 110 | ) 111 | parser.add_argument( 112 | "--test-only", 113 | default=False, 114 | help="Path to model to be tested" 115 | ) 116 | parser.add_argument( 117 | "--reuse-test", 118 | default=False, 119 | help="Path to model to be tested" 120 | ) 121 | parser.add_argument( 122 | "--test-injected", 123 | default=False, 124 | help="Path to injected dataset to be tested" 125 | ) 126 | parser.add_argument( 127 | "--injected-subdir", 128 | default=False, 129 | help="Path to injected dataset to be tested" 130 | ) 131 | parser.add_argument( 132 | "--online-injection", 133 | default=False, 134 | help="Sets if the test set should be used for injection tests" 135 | ) 136 | parser.add_argument( 137 | "--binarize", 138 | default=None, 139 | type=str, 140 | help="Sets if the dataset should be binarized." 141 | ) 142 | parser.add_argument( 143 | '--test-npz', 144 | nargs='+', 145 | help='List of npz datasets to be tested', 146 | default=[], 147 | required=False 148 | ) 149 | parser.add_argument( 150 | '--augment', 151 | choices=[ 152 | 'reorder', 153 | 'inject', 154 | ], 155 | default=[], 156 | nargs='+', 157 | help='List of augmentation methods to be performed', 158 | required=False 159 | ) 160 | 161 | return parser.parse_args(argv) 162 | 163 | def main(args): 164 | 165 | allowed_extensions =[ 166 | 'png', 167 | 'exe', 168 | 'npz' 169 | ] 170 | 171 | augmenters = [] 172 | for augment_option in args.augment: 173 | if augment_option == 'inject': 174 | augmenters.append(RandomInjection((5,5))) 175 | if augment_option == 'reorder': 176 | augmenters.append(RandomReorder()) 177 | 178 | # Check if path exists 179 | if not os.path.isdir(args.path): 180 | raise Exception("The provided path is not a valid dataset.") 181 | if args.extension not in allowed_extensions: 182 | raise Exception("{} is not a valid extension.".format(args.extension)) 183 | 184 | # Run training method 185 | try: 186 | # Define which technique will be used 187 | if args.technique == 'knn_gist': 188 | model = Nataraj2011.KNN(args.path, 189 | ext=args.extension, 190 | descriptor='GIST') 191 | elif args.technique == 'knn_lbp': 192 | model = Nataraj2011.KNN(args.path, 193 | ext=args.extension, 194 | descriptor='LBP', 195 | height=256, 196 | width=256) 197 | elif args.technique == 'malconv': 198 | model = Raff2017.Malconv(args.path, 199 | max_len=args.width, 200 | max_epochs=args.max_epochs, 201 | patience=args.patience, 202 | batch_size=args.batch_size) 203 | elif args.technique == 'le2018-cnn': 204 | model = Le2018.CNN(args.path, 205 | args.extension, 206 | max_len=args.width, 207 | max_epochs=args.max_epochs, 208 | patience=args.patience, 209 | batch_size=args.batch_size, 210 | use_lstm=False, 211 | use_lstm_bidirectional=False) 212 | elif args.technique == 'le2018-cnn-lstm': 213 | model = Le2018.CNN(args.path, 214 | args.extension, 215 | max_len=args.width, 216 | max_epochs=args.max_epochs, 217 | patience=args.patience, 218 | batch_size=args.batch_size, 219 | use_lstm=True, 220 | use_lstm_bidirectional=False) 221 | elif args.technique == 'le2018-cnn-lstm-bidirectional': 222 | model = Le2018.CNN(args.path, 223 | args.extension, 224 | max_len=args.width, 225 | max_epochs=args.max_epochs, 226 | patience=args.patience, 227 | batch_size=args.batch_size, 228 | use_lstm=True, 229 | use_lstm_bidirectional=True) 230 | elif args.technique == 'inceptionv1': 231 | model = Chen2018.InceptionV1(args.path, 232 | args.extension, 233 | max_epochs=args.max_epochs, 234 | patience=10, 235 | batch_size=64, 236 | height=299, 237 | width=299, 238 | learning_rate=1e-4, 239 | lr_treshold=1e-5) 240 | else: 241 | raise Exception("The technique '{}' is not defined!".format(args.technique)) 242 | 243 | if (args.test_only is not False): 244 | model_path = os.path.abspath(args.test_only) 245 | if not args.test_npz: 246 | if not args.reuse_test: 247 | model.test(path=model_path) 248 | else: 249 | with open(args.reuse_test, 'r') as test_file: 250 | # Test files are saved as 'path,label' 251 | test_data = [(i.rstrip().split(',')[0], int(i.rstrip().split(',')[1]) ) for i in test_file.readlines()] 252 | model._test(0, model_path, test_data) 253 | else: 254 | for npz in args.test_npz: 255 | model._test_injected(npz, 0, model_path=model_path) 256 | else: 257 | model.train(n_folds=args.folds, 258 | split_method=args.split_method, 259 | use_subset=args.use_subset, 260 | test_npz=args.test_npz, 261 | augmenters=augmenters) 262 | if (args.test_injected is not False and args.injected_subdir is not False): 263 | model.test_injected(args.test_injected, args.injected_subdir, sections=5, bytes=5, bytes_start=1, bytes_increment=1) 264 | if (args.online_injection is not False): 265 | model.test_online_injection() 266 | except KeyboardInterrupt: 267 | raise Exception("***** Ctrl+C received! EOF") 268 | 269 | return 0 270 | 271 | if __name__ == "__main__": 272 | arguments = get_args() 273 | main_logger = Data.Logger() 274 | 275 | main(arguments) 276 | # try: 277 | # main(arguments) 278 | # except Exception as instance: 279 | # main_logger.exception(instance) 280 | -------------------------------------------------------------------------------- /code/models/Chen2018.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import tensorflow as tf 3 | from tensorflow import keras 4 | from sklearn.metrics import accuracy_score 5 | from keras import backend as K 6 | 7 | from .Basics import MachineLearningModel 8 | 9 | class InceptionV1(MachineLearningModel): 10 | 11 | def __init__( 12 | self, 13 | path, 14 | ext='png', 15 | height=-1, 16 | width=-1, 17 | channels=1, 18 | max_epochs=5000, 19 | patience=50, 20 | batch_size=1, 21 | learning_rate=1e-3, 22 | lr_decay=1e-1, 23 | lr_treshold=1e-7 24 | ): 25 | """ 26 | Parameters 27 | ---------- 28 | path : str 29 | Path to malware dataset 30 | ext : str 31 | File extension of dataset files (default 'png') 32 | height : int 33 | Height of the malware image (default -1 [We wanna use original dimensions]) 34 | width : int 35 | Width of the malware image (default -1 [We wanna use original dimensions]) 36 | channels : int 37 | Number of image's channels (default 1) 38 | max_epochs : int 39 | Number of max epochs to be run (default 5000) 40 | patience : int 41 | Early stopping criteria. If improvement is not made for epochs (default 10) 42 | batch_size : int 43 | Batch size (default 1 [Images have different dimensions]) 44 | learning_rate : float 45 | Model's learning rate (default 1e-3) 46 | lr_decay : float 47 | Model's learning rate decay parameter (default 1e-1) 48 | lr_treshold : float 49 | Model's learning rate treshold to stop training (default 1e-7) 50 | """ 51 | 52 | # We save the epoch where the best acc occurs (early stopping) 53 | self.best_epoch = -1 54 | 55 | self.height = height 56 | self.width = width 57 | self.channels = channels 58 | self.max_epochs = max_epochs 59 | self.initial_patience = patience 60 | self.patience = patience 61 | self.batch_size = batch_size 62 | self.lr_initial = learning_rate 63 | self.lr_training = learning_rate 64 | self.lr_decay = lr_decay 65 | self.lr_treshold = lr_treshold 66 | 67 | # Init parent class 68 | MachineLearningModel.__init__(self, path, 'model_inceptionv3_', ext) 69 | 70 | def reset_learning_rate(self): 71 | """ 72 | Set Learning Rate to initial value. 73 | """ 74 | 75 | self.lr_training = self.lr_initial 76 | 77 | return 78 | 79 | def build_graph(self, input_shape, output_shape): 80 | """ 81 | Build tensorflow graph. 82 | """ 83 | print("*** Building tensorflow Graph.") 84 | print("================================================") 85 | K.set_learning_phase(0) 86 | 87 | # Some GPUs have memory issues running a model this big. It might help 88 | # limiting the memory usage per process 89 | # IMPORTANT: models have to be loaded AFTER SETTING THE SESSION for keras! 90 | # Otherwise, their weights will be unavailable in the threads after the session there has been set 91 | # https://github.com/tensorflow/tensorflow/issues/28287 92 | config = tf.ConfigProto() 93 | config.gpu_options.per_process_gpu_memory_fraction = 0.7 94 | K.set_session(tf.Session(config=config)) 95 | 96 | 97 | ################## 98 | ### CNN layers ### 99 | ################## 100 | self.base_model = tf.keras.applications.InceptionV3( 101 | input_shape=(self.height, self.width, 3), 102 | include_top=False, 103 | weights='imagenet', 104 | pooling='max' 105 | ) 106 | 107 | # Freezing weights update 108 | self.base_model.trainable = False 109 | K.set_learning_phase(1) 110 | 111 | 112 | # base_model.summary() 113 | 114 | #################### 115 | ### Output layer ### 116 | #################### 117 | 118 | self.model = tf.keras.Sequential([ 119 | self.base_model, 120 | #keras.layers.Dense(1024, activation='relu'), 121 | keras.layers.Dense(self.n_classes, activation='softmax') 122 | ]) 123 | 124 | self.model.compile( 125 | optimizer=tf.keras.optimizers.Adam(lr=self.lr_initial), 126 | loss='categorical_crossentropy', 127 | metrics=['accuracy'] 128 | ) 129 | 130 | self.model.summary() 131 | 132 | # Input 133 | # self.model_output = self.model(self.model_X) 134 | 135 | # Compute Loss 136 | # self.model_loss = tf.losses.softmax_cross_entropy(self.model_y_one_hot, self.model_output) 137 | # self.model_loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.model_y_one_hot, logits=self.model_output) 138 | # self.model_loss = tf.reduce_mean(tf.keras.losses.categorical_crossentropy(self.model_y_one_hot, self.model_output)) 139 | 140 | # Optimizer with learning rate decay 141 | # self.model_optimizer = tf.train.AdamOptimizer(self.model_learning_rate).minimize(self.model_loss) 142 | # self.model_optimizer = tf.train.GradientDescentOptimizer(self.model_learning_rate).minimize(self.model_loss) 143 | # self.model_optimizer = tf.train.RMSPropOptimizer(self.model_learning_rate).minimize(self.model_loss) 144 | 145 | # Accuracy 146 | # prediction = tf.argmax(self.model_output, 1, name="net_output") 147 | # correct_prediction = tf.equal(prediction, self.model_y) 148 | # self.model_correct = tf.reduce_sum(tf.cast(correct_prediction, tf.float32)) 149 | 150 | print("================================================") 151 | 152 | return 153 | 154 | def train(self, n_folds=1, split_method='nataraj', use_subset=False): 155 | self.logger.info("** Training started!") 156 | 157 | self.data_handler.split_dataset(n_folds=n_folds, split_method=split_method, use_subset=use_subset) 158 | self.n_classes = self.data_handler.n_classes 159 | 160 | self.logger.info("** Fitting {} classes!".format(self.n_classes)) 161 | 162 | avg_acc = [] 163 | test_acc = 0 164 | for fold in range(n_folds): 165 | self.logger.info("===== FOLD {} =====".format(fold)) 166 | 167 | self.data_handler.compute_fold_split() 168 | 169 | self.patience = self.initial_patience 170 | self.build_graph( 171 | (None, self.height, self.width, 3), 172 | self.n_classes 173 | ) 174 | self._train(fold) 175 | 176 | # Restart training with best epoch 177 | self.model.load_weights(self.get_tmp_model_path() + str(self.best_epoch) + '_f' + str(fold)) 178 | for layer in self.model.layers: 179 | layer.trainable = True 180 | self.model.compile( 181 | optimizer=tf.keras.optimizers.Adam(lr=self.lr_initial), 182 | loss='categorical_crossentropy', 183 | metrics=['accuracy'] 184 | ) 185 | self.model.summary() 186 | self.patience *= 3 187 | self._train(fold, self.best_epoch) 188 | 189 | # Test with unseen data 190 | test_data = self.data_handler.get_test_data() 191 | test_acc = self._test( 192 | fold+1, 193 | self.get_tmp_model_path() + str(self.best_epoch) + '_f' + str(fold), 194 | test_data 195 | ) 196 | avg_acc.append(test_acc) 197 | print_str = "** Finished training! Average ACC: {}; STD DEV {};".format( 198 | np.mean(avg_acc), 199 | np.std(avg_acc) 200 | ) 201 | self.logger.warning(print_str) 202 | self.data_handler.save_to_log(print_str + '\n') 203 | 204 | def _train(self, fold, epoch_range_start=0): 205 | 206 | train_data = self.data_handler.get_train_data() 207 | training_set_size = len(train_data) 208 | n_batches = np.ceil(training_set_size/self.batch_size) 209 | best_acc = 0 210 | best_loss = 999999 211 | distance_from_improvement = 0 212 | 213 | # Run epochs 214 | for epoch in range(epoch_range_start, self.max_epochs): 215 | self.logger.info("Epoch {}".format(epoch+1)) 216 | 217 | # Mini-batch gradient descent 218 | np.random.shuffle(train_data) 219 | train_acc = 0 220 | train_loss = 0 221 | 222 | for idx in range(0, training_set_size, self.batch_size): 223 | 224 | batch_X, batch_y = self.data_handler.load_raw_images( 225 | train_data[idx:idx+self.batch_size], 226 | self.height, 227 | self.width, 228 | self.channels, 229 | True # Stack image channels (RGB) 230 | ) 231 | 232 | #self.logger.info("Data info: {} : {}".format(batch_X.shape, batch_y.shape)) 233 | 234 | ret = self.model.train_on_batch( 235 | batch_X, 236 | tf.keras.utils.to_categorical(batch_y, self.n_classes) 237 | ) 238 | 239 | # print(ret) 240 | # print(ret.shape) 241 | train_loss += ret[0] 242 | train_acc += ret[1] 243 | validation_acc, validation_loss = self._validate() 244 | 245 | self.logger.info( 246 | "*TRAINING* SET => ACC: {:.4f} ; " \ 247 | "LOSS: {:.4f}" 248 | .format( 249 | train_acc/n_batches, 250 | train_loss/n_batches 251 | ) 252 | ) 253 | self.logger.info( 254 | "*VALIDATE* SET => ACC: {:.4f} ; " \ 255 | "LOSS: {:.4f}" 256 | .format( 257 | validation_acc, 258 | validation_loss 259 | ) 260 | ) 261 | self.data_handler.save_to_log( 262 | "{}, {}, {}, {}, {}\n" 263 | .format( 264 | (epoch+1), 265 | train_acc/training_set_size, 266 | train_loss/training_set_size, 267 | validation_acc, 268 | validation_loss 269 | ) 270 | ) 271 | 272 | ############################### 273 | ### EARLY STOPPING ### 274 | ############################### 275 | if validation_acc > best_acc: 276 | best_loss = validation_loss 277 | best_acc = validation_acc 278 | self.best_epoch = (epoch+1) 279 | distance_from_improvement = 0 280 | # Save network parameters 281 | self.model.save_weights( 282 | self.get_tmp_model_path() + str(epoch+1) + '_f' + str(fold) 283 | ) 284 | else: 285 | distance_from_improvement += 1 286 | 287 | if distance_from_improvement > self.patience: 288 | 289 | print_str = "***** No improvement in last {} epochs! "\ 290 | "Stopping. Best epoch: {} => ACC: {}; LOSS: {};" \ 291 | .format( 292 | self.patience, 293 | self.best_epoch, 294 | best_acc, 295 | best_loss, 296 | ) 297 | self.logger.warning(print_str) 298 | self.data_handler.save_to_log(print_str + '\n') 299 | break 300 | 301 | return 302 | 303 | def _validate(self): 304 | 305 | validation_acc = 0 306 | validation_loss = 0 307 | validation_data = self.data_handler.get_validation_data() 308 | validation_set_size = len(validation_data) 309 | n_batches = np.ceil(validation_set_size/self.batch_size) 310 | 311 | for idx in range(0, validation_set_size, self.batch_size): 312 | 313 | validation_X, validation_y = self.data_handler.load_raw_images( 314 | validation_data[idx:idx+self.batch_size], 315 | self.height, 316 | self.width, 317 | self.channels, 318 | True # Stack image channels (RGB) 319 | ) 320 | 321 | ret = self.model.test_on_batch( 322 | validation_X, 323 | tf.keras.utils.to_categorical(validation_y, self.n_classes) 324 | ) 325 | 326 | validation_loss += ret[0] 327 | validation_acc += ret[1] 328 | 329 | return validation_acc/n_batches, validation_loss/n_batches 330 | 331 | def _test(self, fold, model_path, test_data): 332 | 333 | acc = 0 334 | self.logger.warning("*** Loading tensorflow Graph from {}.".format(model_path)) 335 | 336 | result_file = self.data_handler.create_file( 337 | name="test_results_{}.txt".format(fold), 338 | ) 339 | 340 | test_set_size = len(test_data) 341 | labels = [] 342 | predictions = [] 343 | 344 | self.model.load_weights(model_path) 345 | 346 | for idx in range(0, test_set_size, self.batch_size): 347 | test_X, test_y = self.data_handler.load_raw_images( 348 | test_data[idx:idx+self.batch_size], 349 | self.height, 350 | self.width, 351 | self.channels, 352 | True # Stack image channels (RGB) 353 | ) 354 | 355 | y_predict = self.model.predict_on_batch(test_X) 356 | 357 | for i in range(len(test_y)): 358 | labels.append(test_y[i]) 359 | predictions.append(np.argmax(y_predict[i])) 360 | result_file.write("{}, {}\n".format(test_y[i], np.argmax(y_predict[i]))) 361 | 362 | acc = accuracy_score(labels, predictions) 363 | print_str = "\t\t *TEST* SET => ACC: {:.4f}\n".format(acc) 364 | self.logger.info(print_str) 365 | result_file.write(print_str) 366 | 367 | self.logger.info("** Testing finished!") 368 | return acc 369 | 370 | def test(self, path): 371 | self.logger.info("[*] Running in test only mode.") 372 | 373 | self.data_handler.split_dataset() 374 | self.n_classes = self.data_handler.n_classes 375 | self.data_handler.compute_fold_split() 376 | 377 | self.logger.info("** Fitting {} classes!".format(self.n_classes)) 378 | 379 | 380 | self.build_graph( 381 | (None, self.height, self.width, 3), 382 | self.n_classes 383 | ) 384 | 385 | self._test('test_only', path, self.data_handler.get_all_data()) 386 | -------------------------------------------------------------------------------- /code/models/Nataraj2011.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | import joblib 4 | import json 5 | import time 6 | 7 | import sklearn.metrics as metrics 8 | from sklearn.metrics import f1_score, accuracy_score, recall_score, precision_score 9 | from sklearn.model_selection import StratifiedKFold 10 | from sklearn.neighbors import KNeighborsClassifier 11 | 12 | from .Basics import MachineLearningModel 13 | from .Data import MalImgDataset 14 | 15 | class KNN(MachineLearningModel): 16 | """ 17 | A class used to classify malware files using K-Nearest Neighbours. 18 | 19 | This class implements a classifier using KNN and GIST or LBP as descriptors, 20 | based upon Nataraj et. al. (2011) work. 21 | 22 | Attributes 23 | ---------- 24 | path : str 25 | Path to malware dataset 26 | n_classes : int 27 | Number of malware families to be classified 28 | descriptor : str 29 | Algorithm name to be used as descriptor (default "GIST") 30 | k : int 31 | Number of k-nearest neighbours (default 3) 32 | height : int 33 | Height of the malware image (default 64) 34 | width : int 35 | Width of the malware image (default 64) 36 | 37 | Methods 38 | ------- 39 | __init__(sound=None) 40 | Class initialization 41 | """ 42 | 43 | def __init__(self, path, ext='png', descriptor='GIST', k=3, height=64, width=64): 44 | """ 45 | Parameters 46 | ---------- 47 | path : str 48 | Path to malware dataset 49 | descriptor : str 50 | Algorithm name to be used as descriptor (default "GIST") 51 | k : int 52 | Number of k-nearest neighbours (default 3) 53 | height : int 54 | Height of the malware image (default 64) 55 | width : int 56 | Width of the malware image (default 64) 57 | """ 58 | 59 | self.k = k 60 | self.descriptor = descriptor 61 | self.height = height 62 | self.width = width 63 | 64 | if self.descriptor == 'GIST': 65 | model_filename = 'knn_gist_model_file' 66 | elif self.descriptor == 'LBP': 67 | model_filename = 'knn_lbp_model_file' 68 | else: 69 | raise Exception('Unknown descriptor for KNN model.') 70 | 71 | # Init parent class 72 | MachineLearningModel.__init__(self, path, model_filename, ext=ext) 73 | 74 | def train(self, 75 | n_folds=1, 76 | split_method='nataraj', 77 | use_subset=False, 78 | test_npz=None, 79 | augmenters=None): 80 | self.logger.info("** Training started!") 81 | 82 | # Set augmentation methods to be used 83 | self.augmenters = augmenters 84 | 85 | self.data_handler.split_dataset(n_folds=n_folds, split_method=split_method, use_subset=use_subset) 86 | 87 | avg_acc = [] 88 | avg_f1 = [] 89 | avg_time = [] 90 | test_acc = 0 91 | 92 | inj_avg_acc = [] 93 | inj_avg_f1 = [] 94 | inj_avg_time = [] 95 | 96 | for fold in range(n_folds): 97 | self.logger.info("===== FOLD {} =====".format(fold)) 98 | 99 | self.data_handler.compute_fold_split() 100 | 101 | start = time.time() 102 | 103 | clf = KNeighborsClassifier(self.k, weights='distance') 104 | 105 | train_data = self.data_handler.get_train_data(merge_validation=True) 106 | 107 | np.random.shuffle(train_data) 108 | 109 | self.logger.warning("Starting feature extraction.") 110 | if self.descriptor == 'GIST': 111 | train_X_features, train_y = self.data_handler.extract_GIST_features( 112 | train_data, 113 | self.height, 114 | self.width, 115 | augmenters=self.augmenters 116 | ) 117 | elif self.descriptor == 'LBP': 118 | train_X_features, train_y = self.data_handler.extract_LBP_features( 119 | train_data, 120 | self.height, 121 | self.width, 122 | ) 123 | 124 | self.logger.warning(f"Fitting classifier with {set(train_y)} and {train_X_features.shape} samples.") 125 | clf.fit(train_X_features, train_y) 126 | fold_model = self.save_model(clf, fold) 127 | 128 | end = time.time() 129 | 130 | train_time = int(end - start) 131 | 132 | test_set = self.data_handler.get_test_data() 133 | test_acc, test_f1, test_time = self._test(fold, 134 | fold_model, 135 | test_set) 136 | 137 | self.results[fold+1] = { 138 | "acc": test_acc, 139 | "f1": test_f1, 140 | "train_time": train_time, 141 | "test_time": test_time 142 | } 143 | total_time = train_time + test_time 144 | avg_acc.append(test_acc) 145 | avg_f1.append(test_f1) 146 | avg_time.append(total_time) 147 | 148 | for npz_path in test_npz: 149 | # Test with injected data 150 | test_acc, test_f1, test_time = self._test_injected(npz_path, 151 | fold, 152 | clf, 153 | binarize=None) 154 | self.results[f"{fold+1}_injected"] = { 155 | "path": npz_path, 156 | "acc": test_acc, 157 | "f1": test_f1, 158 | "test_time": test_time 159 | } 160 | inj_avg_acc.append(test_acc) 161 | inj_avg_f1.append(test_f1) 162 | inj_avg_time.append(test_time) 163 | 164 | print_str = "** Finished training in {}s! Average ACC: {}; STD DEV {};".format( 165 | np.mean(avg_time), 166 | np.mean(avg_acc), 167 | np.std(avg_acc) 168 | ) 169 | self.logger.warning(print_str) 170 | self.data_handler.save_to_log(print_str + '\n') 171 | self.data_handler.save_to_log(json.dumps(self.results)) 172 | 173 | return 174 | 175 | def _test(self, fold, model_path, test_data): 176 | self.logger.info("** Testing started!") 177 | 178 | result_file = self.data_handler.create_file( 179 | name="test_results_{}.txt".format(fold), 180 | ) 181 | 182 | test_set_size = len(test_data) 183 | labels = [] 184 | predictions = [] 185 | scores = [] 186 | 187 | _model = self.load_model(model_path) 188 | 189 | start_test_predict = time.time() 190 | 191 | # Testing 192 | if self.descriptor == 'GIST': 193 | X_test, y_test = self.data_handler.extract_GIST_features( 194 | test_data, 195 | self.height, 196 | self.width, 197 | ) 198 | elif self.descriptor == 'LBP': 199 | X_test, y_test = self.data_handler.extract_LBP_features( 200 | test_data, 201 | self.height, 202 | self.width, 203 | ) 204 | 205 | predictions = _model.predict(X_test) # output is labels and not indices 206 | 207 | end_test_predict = time.time() 208 | 209 | scores = _model.predict_proba(X_test) 210 | 211 | labels = y_test 212 | 213 | f1 = metrics.f1_score(y_test, predictions, average="weighted") 214 | acc = accuracy_score(y_test, predictions) 215 | difference = int(end_test_predict - start_test_predict) 216 | 217 | print_str = "\t\t *TEST* SET => Time: {}s; ACC: {:.4f}; F1: {:.4f}".format(difference, acc, f1) 218 | 219 | self.logger.info(print_str) 220 | result_file.write(print_str) 221 | 222 | self.logger.info(f" Saving npz: metrics_test_results_{fold}.npz") 223 | np.savez(f"{self.data_handler.tmp_output_path}/metrics_test_results_{fold}.npz", 224 | y_true=labels, 225 | y=predictions, 226 | p=scores, 227 | acc=acc, 228 | f1=f1) 229 | 230 | self.logger.info("** Testing finished!") 231 | 232 | return acc, f1, difference 233 | 234 | 235 | def _test_injected(self, npz, fold, clf, binarize=None): 236 | 237 | data = np.load(npz, mmap_mode='r', allow_pickle=True) 238 | 239 | total_samples = data['y'].shape[0] 240 | MBS=4096 241 | 242 | result_file_name = "{}_{}".format(npz.split('/')[-1].split('.')[0], fold) 243 | result_file = self.data_handler.create_file( 244 | name=f"test_results_{result_file_name}.txt", 245 | ) 246 | 247 | self.logger.warning(f"Testing against {total_samples} samples from {npz}.") 248 | 249 | labels = [] 250 | predictions = [] 251 | scores = [] 252 | 253 | # https://stackoverflow.com/questions/59216547/python-npzfile-objects-are-very-slow 254 | m_X = data['X'] 255 | m_y = data['y'] 256 | 257 | start_test_predict = time.time() 258 | 259 | for idx in range(0, total_samples, MBS): 260 | 261 | batchX = m_X[idx:idx+MBS] 262 | batchY = m_y[idx:idx+MBS] 263 | size = batchX.shape[0] 264 | 265 | batch_data = list(zip(batchX, batchY)) 266 | 267 | if self.descriptor == 'GIST': 268 | X, _ = self.data_handler.extract_GIST_features( 269 | batch_data, 270 | self.height, 271 | self.width, 272 | from_data=True 273 | ) 274 | elif self.descriptor == 'LBP': 275 | X, _ = self.data_handler.extract_LBP_features( 276 | batch_data, 277 | self.height, 278 | self.width, 279 | ) 280 | 281 | 282 | predicted_labels = clf.predict(X) # output is labels and not indices 283 | probs = clf.predict_proba(X) 284 | 285 | print(predicted_labels.shape, probs.shape) 286 | 287 | for _id in range(size): 288 | 289 | if binarize in [None, False]: 290 | y = batchY[_id] 291 | else: 292 | y = 1 if batchY[_id] == binarize else 0 293 | 294 | _y = predicted_labels[_id] 295 | score = probs[_id] 296 | 297 | labels.append(int(y)) 298 | predictions.append(_y) 299 | scores.append(score) 300 | 301 | result_file.write("{}, {}\n".format(y, 302 | _y)) 303 | 304 | end_test_predict = time.time() 305 | 306 | acc = metrics.accuracy_score(labels, predictions) 307 | f1 = metrics.f1_score(labels, predictions, average="weighted") 308 | # precision, recall, thresholds = metrics.precision_recall_curve(labels, scores) 309 | 310 | difference = int(end_test_predict - start_test_predict) 311 | 312 | print_str = "\t\t *TEST* SET (INJECTED) => Time: {}s; ACC: {:.4f}; F1: {:.4f}".format(difference, acc, f1) 313 | 314 | self.logger.info(print_str) 315 | result_file.write(print_str) 316 | 317 | self.logger.info(f" Saving npz: {result_file_name}.npz") 318 | np.savez(f"{self.data_handler.tmp_output_path}/metrics_{result_file_name}.npz", 319 | y_true=labels, 320 | y=predictions, 321 | p=scores, 322 | acc=acc, 323 | f1=f1) 324 | # precision=precision, 325 | # recall=recall, 326 | # thresholds=thresholds) 327 | 328 | self.logger.info("** Injection Testing finished!") 329 | 330 | return acc, f1, difference 331 | 332 | 333 | def test(self, _model, test_data): 334 | self.logger.info("** Testing started!") 335 | 336 | # Testing 337 | if self.descriptor == 'GIST': 338 | X_test, y_test = self.data_handler.extract_GIST_features( 339 | test_data, 340 | self.height, 341 | self.width, 342 | ) 343 | elif self.descriptor == 'LBP': 344 | X_test, y_test = self.data_handler.extract_LBP_features( 345 | test_data, 346 | self.height, 347 | self.width, 348 | ) 349 | 350 | y_predict = _model.predict(X_test) # output is labels and not indices 351 | acc = accuracy_score(y_test, y_predict) 352 | self.logger.info("\t\t *TEST* SET => ACC: {:.4f}".format(acc)) 353 | 354 | self.logger.info("** Testing finished!") 355 | 356 | 357 | def train_and_test(self, test_path): 358 | self.logger.info("** Training started!") 359 | 360 | self.data_handler.split_dataset() 361 | self.data_handler.compute_fold_split() 362 | train_data = self.data_handler.get_all_data() 363 | self.logger.info("Shape of training data: {}".format(len(train_data))) 364 | 365 | train_X_features, train_y = self.data_handler.extract_GIST_features( 366 | train_data, 367 | self.height, 368 | self.width, 369 | ) 370 | 371 | clf = KNeighborsClassifier(self.k, weights='distance') 372 | clf.fit(train_X_features, train_y) 373 | #self.save_model(clf, fold) 374 | 375 | self.logger.info("** Training finished!") 376 | 377 | ##################################################################### 378 | 379 | self.logger.info("** Testing started!") 380 | 381 | test_data_handler = MalImgDataset(test_path) 382 | test_data_handler.split_dataset() 383 | test_data_handler.compute_fold_split() 384 | test_data = test_data_handler.get_all_data() 385 | 386 | result_file = self.data_handler.create_file( 387 | name="test_results_test_only.txt", 388 | ) 389 | 390 | self.logger.info("Shape of testing data: {}".format(len(test_data))) 391 | 392 | X_test, y_test = self.data_handler.extract_GIST_features( 393 | test_data, 394 | self.height, 395 | self.width, 396 | ) 397 | 398 | 399 | y_predict = clf.predict(X_test) # output is labels and not indices 400 | 401 | for i in range(len(y_test)): 402 | result_file.write("{}, {}\n".format(y_test[i], y_predict[i])) 403 | 404 | acc = accuracy_score(y_test, y_predict) 405 | print_str = "\t\t *TEST* SET => ACC: {:.4f}\n".format(acc) 406 | self.logger.info(print_str) 407 | result_file.write(print_str) 408 | 409 | self.logger.info("** Testing finished!") 410 | 411 | def save_model(self, model, fold): 412 | path = self.get_tmp_model_path() + '_' + str(fold) 413 | joblib.dump(model, path) 414 | return path 415 | 416 | def load_model(self, path): 417 | return joblib.load(path) 418 | -------------------------------------------------------------------------------- /code/models/Raff2017.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import time 4 | import json 5 | import torch 6 | import torch.nn as nn 7 | import torch.nn.functional as F 8 | import torch.optim as optim 9 | import sklearn.metrics as metrics 10 | from sklearn.preprocessing import label_binarize 11 | import multiprocessing as mp 12 | from functools import partial 13 | 14 | from .Basics import MachineLearningModel 15 | 16 | # 1MB = 2**20 == 1048576 17 | # 2MB = 2**21 == 2097152 18 | 19 | class Net(nn.Module): 20 | # trained to minimize cross-entropy loss 21 | # criterion = nn.CrossEntropyLoss() 22 | def __init__(self, out_size=2, channels=128, window_size=512, embd_size=8): 23 | super(Net, self).__init__() 24 | self.embd = nn.Embedding(257, embd_size, padding_idx=0) 25 | 26 | self.window_size = window_size 27 | 28 | self.conv_1 = nn.Conv1d(embd_size, channels, window_size, stride=window_size, bias=True) 29 | self.conv_2 = nn.Conv1d(embd_size, channels, window_size, stride=window_size, bias=True) 30 | 31 | self.pooling = nn.AdaptiveMaxPool1d(1) 32 | 33 | self.fc_1 = nn.Linear(channels, channels) 34 | self.fc_2 = nn.Linear(channels, out_size) 35 | 36 | def forward(self, x): 37 | 38 | x = self.embd(x.long()) 39 | x = torch.transpose(x,-1,-2) 40 | 41 | cnn_value = self.conv_1(x) 42 | gating_weight = torch.sigmoid(self.conv_2(x)) 43 | 44 | x = cnn_value * gating_weight 45 | 46 | x = self.pooling(x) 47 | 48 | #Flatten 49 | x = x.view(x.size(0), -1) 50 | 51 | x = F.relu(self.fc_1(x)) 52 | x = self.fc_2(x) 53 | 54 | return x 55 | 56 | class Malconv(MachineLearningModel): 57 | """ 58 | This class is a new implementation of Maups idea. 59 | """ 60 | 61 | def __init__( 62 | self, 63 | path, 64 | ext='exe', 65 | max_len=2**21, 66 | max_epochs=10, 67 | patience=3, 68 | batch_size=512, 69 | binarize=None 70 | ): 71 | """ 72 | Parameters 73 | ---------- 74 | path : str 75 | Path to malware dataset 76 | max_len : int 77 | Length of the 1D malware data (default 2**21 [2MB]) 78 | max_epochs : int 79 | Number of max epochs to be run (default 250) 80 | patience : int 81 | Early stopping criteria. If improvement is not made for epochs (default 10) training stops 82 | batch_size : int 83 | Batch size (default 64) 84 | """ 85 | 86 | self.max_len = int(max_len) 87 | self.max_epochs = max_epochs 88 | self.batch_size = batch_size 89 | self.patience = patience 90 | self.model = None 91 | self.best_epoch = -1 92 | self.augmenter = None 93 | 94 | # Init parent class 95 | MachineLearningModel.__init__(self, 96 | path, 97 | 'model_raff2017_', 98 | ext=ext, 99 | batch_size=self.batch_size) 100 | 101 | torch.backends.cudnn.benchmark = True 102 | torch.backends.cudnn.enabled = True 103 | 104 | def train(self, 105 | n_folds=1, 106 | split_method='nataraj', 107 | use_subset=False, 108 | binarize=None, 109 | test_npz=None, 110 | augmenters=None): 111 | self.logger.info("** Training started!") 112 | 113 | # Set augmentation methods to be used 114 | self.augmenters = augmenters 115 | 116 | self.data_handler.split_dataset(n_folds=n_folds, 117 | split_method=split_method, 118 | use_subset=use_subset, 119 | binarize_dataset=binarize) 120 | self.n_classes = self.data_handler.n_classes 121 | 122 | self.logger.info("** Fitting {} classes!".format(self.n_classes)) 123 | 124 | avg_acc = [] 125 | avg_f1 = [] 126 | avg_time = [] 127 | 128 | inj_avg_acc = [] 129 | inj_avg_f1 = [] 130 | inj_avg_time = [] 131 | 132 | for fold in range(n_folds): 133 | self.logger.info("===== FOLD {} =====".format(fold)) 134 | 135 | self.data_handler.compute_fold_split() 136 | 137 | self.model = Net(out_size=self.data_handler.n_classes).cuda() 138 | self.optimizer = optim.SGD(self.model.parameters(), 139 | lr=1e-2, 140 | momentum=0.9, 141 | nesterov=True, 142 | weight_decay=1e-3) 143 | print(self.model) 144 | 145 | # Run training in fold 146 | train_time = self._train(fold) 147 | fold_model = self.get_tmp_model_path() + str(self.best_epoch) + '_f' + str(fold) + '.pt' 148 | self.model_paths.append(fold_model) 149 | 150 | # Test with unseen data 151 | test_data = self.data_handler.get_test_data() 152 | test_acc, test_f1, test_time = self._test(fold+1, 153 | fold_model, 154 | test_data) 155 | self.results[fold+1] = { 156 | "acc": test_acc, 157 | "f1": test_f1, 158 | "train_time": train_time, 159 | "test_time": test_time 160 | } 161 | total_time = train_time + test_time 162 | avg_acc.append(test_acc) 163 | avg_f1.append(test_f1) 164 | avg_time.append(total_time) 165 | 166 | for npz in test_npz: 167 | # Test with injected data 168 | test_acc, test_f1, test_time = self._test_injected(npz, 169 | fold+1, 170 | fold_model, 171 | binarize=binarize) 172 | self.results[f"{fold+1}_injected"] = { 173 | "path": npz, 174 | "acc": test_acc, 175 | "f1": test_f1, 176 | "test_time": test_time 177 | } 178 | inj_avg_acc.append(test_acc) 179 | inj_avg_f1.append(test_f1) 180 | inj_avg_time.append(test_time) 181 | print_str = "** Finished training in {}s! Average ACC: {}; STD DEV {};".format( 182 | np.mean(avg_time), 183 | np.mean(avg_acc), 184 | np.std(avg_acc) 185 | ) 186 | self.logger.warning(print_str) 187 | self.data_handler.save_to_log(print_str + '\n') 188 | self.data_handler.save_to_log(json.dumps(self.results)) 189 | 190 | def _train(self, fold, epoch_range_start=0): 191 | 192 | train_data = self.data_handler.get_train_data() 193 | training_set_size = len(train_data) 194 | n_batches = np.ceil(training_set_size/self.batch_size) 195 | 196 | # Used to get the epoch with best results and load its model for testing 197 | best_acc = 0 198 | best_loss = 999999 199 | distance_from_improvement = 0 200 | 201 | # Run epochs 202 | for epoch in range(epoch_range_start, self.max_epochs): 203 | self.logger.info( 204 | "Epoch {}: training on {} samples.".format( 205 | epoch+1, 206 | training_set_size 207 | ) 208 | ) 209 | 210 | # Mini-batch gradient descent 211 | np.random.shuffle(train_data) 212 | train_acc = 0 213 | train_loss = 0 214 | 215 | start = time.time() 216 | 217 | for idx in range(0, training_set_size, self.batch_size): 218 | 219 | batch_X, batch_y = self.data_handler.load_sequence( 220 | train_data[idx:idx+self.batch_size], 221 | length=self.max_len, 222 | augmenters=self.augmenters 223 | ) 224 | 225 | X = torch.from_numpy(batch_X).cuda() 226 | y = torch.from_numpy(batch_y).long().cuda() # cross_entropy expect long for target 227 | 228 | self.model.train() 229 | _y = self.model(X).cuda() 230 | 231 | # print(X) 232 | # print(_y) 233 | 234 | # self.logger.info( 235 | # "Data info --> train: {} : {} x {}".format( 236 | # X.shape, 237 | # y.shape, 238 | # _y.shape, 239 | # ) 240 | # ) 241 | 242 | # Run backward propagation 243 | self.optimizer.zero_grad() 244 | loss = F.cross_entropy(_y, y) 245 | loss.backward() 246 | self.optimizer.step() 247 | 248 | # print(torch.argmax(_y, dim=1)) 249 | 250 | _acc = ((torch.argmax(_y, dim=1) == y).sum().item() / X.shape[0]) 251 | 252 | train_loss += loss.item() 253 | train_acc += _acc 254 | 255 | end = time.time() 256 | 257 | time_diff = int(end - start) 258 | 259 | # Call validation method 260 | validation_acc, validation_loss = self._validate() 261 | 262 | ############################ 263 | ####### DEBUG ######## 264 | ############################ 265 | 266 | self.logger.info( 267 | "*TRAINING* SET => ACC: {:.4f} ; " \ 268 | "LOSS: {:.4f}" 269 | .format( 270 | train_acc/n_batches, 271 | train_loss/n_batches 272 | ) 273 | ) 274 | 275 | self.logger.info( 276 | "*VALIDATE* SET => ACC: {:.4f} ; " \ 277 | "LOSS: {:.4f}" 278 | .format( 279 | validation_acc, 280 | validation_loss 281 | ) 282 | ) 283 | 284 | self.logger.info( 285 | "Finished epoch in {}s.".format(time_diff) 286 | ) 287 | 288 | self.data_handler.save_to_log( 289 | "epoch: {}, train_acc: {}, train_loss: {}, valid_acc: {}, valid_los: {}, time: {}s\n" 290 | .format( 291 | (epoch+1), 292 | train_acc/n_batches, 293 | train_loss/n_batches, 294 | validation_acc, 295 | validation_loss, 296 | time_diff 297 | ) 298 | ) 299 | 300 | ############################### 301 | ### EARLY STOPPING ### 302 | ############################### 303 | 304 | # Save epoch with best validation loss for testing 305 | if validation_acc > best_acc: 306 | best_loss = validation_loss 307 | best_acc = validation_acc 308 | self.best_epoch = (epoch+1) 309 | distance_from_improvement = 0 310 | 311 | # Save network parameters 312 | torch.save( 313 | self.model, 314 | self.get_tmp_model_path() + str(epoch+1) + '_f' + str(fold) + '.pt' 315 | ) 316 | else: 317 | distance_from_improvement += 1 318 | 319 | if distance_from_improvement > self.patience: 320 | 321 | print_str = "***** No improvement in last {} epochs! "\ 322 | "Stopping. Best epoch: {} => ACC: {}; LOSS: {};" \ 323 | .format( 324 | self.patience, 325 | self.best_epoch, 326 | best_acc, 327 | best_loss, 328 | ) 329 | self.logger.warning(print_str) 330 | self.data_handler.save_to_log(print_str + '\n') 331 | break 332 | 333 | return time_diff 334 | 335 | def _validate(self): 336 | 337 | validation_acc = 0 338 | validation_loss = 0 339 | validation_data = self.data_handler.get_validation_data() 340 | validation_set_size = len(validation_data) 341 | n_batches = np.ceil(validation_set_size/self.batch_size) 342 | 343 | np.random.shuffle(validation_data) 344 | 345 | self.logger.info( 346 | "[*] Running validation on {} samples.".format( 347 | validation_set_size, 348 | ) 349 | ) 350 | 351 | for idx in range(0, validation_set_size, self.batch_size): 352 | 353 | validation_X, validation_y = self.data_handler.load_sequence( 354 | validation_data[idx:idx+self.batch_size], 355 | length=self.max_len 356 | ) 357 | 358 | X = torch.from_numpy(validation_X).float().cuda() 359 | y = torch.from_numpy(validation_y).long().cuda() # cross_entropy expect long for target 360 | 361 | self.model.eval() 362 | with torch.no_grad(): 363 | torch.cuda.empty_cache() 364 | _y = self.model(X).cuda() 365 | 366 | # self.logger.info( 367 | # "Data info --> validation: {} : {}".format( 368 | # _y.shape, 369 | # y.shape, 370 | # ) 371 | # ) 372 | 373 | loss = F.cross_entropy(_y, y) 374 | _acc = ((torch.argmax(_y, dim=1) == y).sum().item() / X.shape[0]) 375 | 376 | validation_loss += loss.item() 377 | validation_acc += _acc 378 | 379 | return validation_acc/n_batches, validation_loss/n_batches 380 | 381 | def _test(self, fold, model_path, test_data): 382 | 383 | self.logger.warning("*** Loading tensorflow Graph from {}.".format(model_path)) 384 | 385 | result_file = self.data_handler.create_file( 386 | name="test_results_{}.txt".format(fold), 387 | ) 388 | 389 | test_set_size = len(test_data) 390 | labels = [] 391 | predictions = [] 392 | scores = [] 393 | 394 | self.model = torch.load(model_path) 395 | 396 | start_test_predict = time.time() 397 | 398 | self.model.eval() 399 | 400 | with torch.no_grad(): 401 | torch.cuda.empty_cache() 402 | 403 | for idx in range(test_set_size): 404 | 405 | X, y = self.data_handler.load_sequence( 406 | [test_data[idx]], 407 | length=self.max_len 408 | ) 409 | 410 | X = torch.from_numpy(X).float().cuda() 411 | 412 | # Call softmax to transform output into probabilities 413 | # https://discuss.pytorch.org/t/vgg-output-layer-no-softmax/9273/7 414 | probs = F.softmax(self.model(X), dim=1).float() 415 | _y = torch.argmax(probs, axis=1).cpu().item() 416 | 417 | # Get score as 2D data 418 | scores.append(probs.detach().cpu().numpy()[0]) 419 | 420 | labels.append(y[0]) 421 | predictions.append(_y) 422 | 423 | result_file.write("{}, {}\n".format(y[0], 424 | _y)) 425 | 426 | end_test_predict = time.time() 427 | 428 | n_classes = np.unique(labels).shape[0] 429 | 430 | acc = metrics.accuracy_score(labels, predictions) 431 | f1 = metrics.f1_score(labels, predictions, average="weighted") 432 | if n_classes > 2: 433 | ytrue = label_binarize(labels, classes=[i for i in range(n_classes)]).ravel() 434 | probs = np.array(scores).ravel() 435 | probs = np.array(scores).ravel() 436 | else: 437 | ytrue = labels 438 | probs = np.array(scores)[:, 1] 439 | apc = metrics.average_precision_score(ytrue, probs) 440 | 441 | difference = int(end_test_predict - start_test_predict) 442 | 443 | print_str = "\t\t *TEST* SET => Time: {}s; ACC: {:.4f}; F1: {:.4f}; APC:{:.4f}".format(difference, acc, f1, apc) 444 | 445 | self.logger.info(print_str) 446 | result_file.write(print_str) 447 | 448 | self.logger.info(f" Saving npz: metrics_test_results_{fold}.npz") 449 | np.savez(f"{self.data_handler.tmp_output_path}/metrics_test_results_{fold}.npz", 450 | y_true=labels, 451 | y=predictions, 452 | p=scores, 453 | acc=acc, 454 | f1=f1) 455 | 456 | self.logger.info("** Testing finished!") 457 | 458 | return acc, f1, difference 459 | 460 | def _test_injected(self, npz, fold, model_path, binarize=None): 461 | 462 | 463 | data = np.load(npz, mmap_mode='r', allow_pickle=True) 464 | 465 | total_samples = data['y'].shape[0] 466 | MBS=128 467 | 468 | self.logger.warning("*** Loading torch model from {}. Testing against {} samples.".format(model_path, total_samples)) 469 | 470 | result_file_name = "{}_{}".format(npz.split('/')[-1].split('.')[0], fold) 471 | result_file = self.data_handler.create_file( 472 | name=f"test_results_{result_file_name}.txt", 473 | ) 474 | 475 | labels = [] 476 | predictions = [] 477 | scores = [] 478 | 479 | self.model = torch.load(model_path) 480 | 481 | start_test_predict = time.time() 482 | 483 | self.model.eval() 484 | 485 | with torch.no_grad(): 486 | torch.cuda.empty_cache() 487 | 488 | # https://stackoverflow.com/questions/59216547/python-npzfile-objects-are-very-slow 489 | m_X = data['X'] 490 | m_y = data['y'] 491 | 492 | for idx in range(0, total_samples, MBS): 493 | 494 | batchX = m_X[idx:idx+MBS] 495 | batchY = m_y[idx:idx+MBS] 496 | size = batchX.shape[0] 497 | 498 | batch_data = list(zip(batchX, batchY)) 499 | 500 | batch_X, _ = self.data_handler.load_sequence( 501 | batch_data, 502 | length=self.max_len, 503 | from_data=True 504 | ) 505 | 506 | print(f"loaded {batch_X.shape}") 507 | 508 | for _id in range(size): 509 | 510 | if binarize is None: 511 | y = batchY[_id] 512 | else: 513 | sample_id = batchY[_id] 514 | sample_class_name = self.data_handler.id_map[sample_id] 515 | y = 1 if sample_class_name == binarize else 0 516 | 517 | X = torch.from_numpy(batch_X[_id]).float().cuda().reshape(1, -1) 518 | # y = batchY[_id] 519 | 520 | # Call softmax to transform output into probabilities 521 | # https://discuss.pytorch.org/t/vgg-output-layer-no-softmax/9273/7 522 | probs = F.softmax(self.model(X), dim=1).float() 523 | _y = torch.argmax(probs, axis=1).cpu().item() 524 | 525 | # Get score as 2D data 526 | scores.append(probs.detach().cpu().numpy()[0]) 527 | labels.append(int(y)) 528 | predictions.append(_y) 529 | 530 | result_file.write("{}, {}\n".format(y, 531 | _y)) 532 | 533 | end_test_predict = time.time() 534 | 535 | n_classes = np.unique(labels).shape[0] 536 | 537 | acc = metrics.accuracy_score(labels, predictions) 538 | f1 = metrics.f1_score(labels, predictions, average="weighted") 539 | if n_classes > 2: 540 | ytrue = label_binarize(labels, classes=[i for i in range(n_classes)]).ravel() 541 | probs = np.array(scores).ravel() 542 | else: 543 | ytrue = np.array(labels) 544 | probs = np.array(scores)[:, 1] 545 | print(ytrue.shape, probs.shape) 546 | apc = metrics.average_precision_score(ytrue, probs) 547 | # precision, recall, thresholds = metrics.precision_recall_curve(labels, scores) 548 | 549 | difference = int(end_test_predict - start_test_predict) 550 | 551 | print_str = "\t\t *TEST* SET (INJECTED) => Time: {}s; ACC: {:.4f}; F1: {:.4f}; APC: {:.4f}".format(difference, acc, f1, apc) 552 | 553 | self.logger.info(print_str) 554 | result_file.write(print_str) 555 | 556 | self.logger.info(f" Saving npz: {result_file_name}.npz") 557 | np.savez(f"{self.data_handler.tmp_output_path}/metrics_{result_file_name}.npz", 558 | y_true=labels, 559 | y=predictions, 560 | p=scores, 561 | acc=acc, 562 | f1=f1) 563 | 564 | self.logger.info("** Injection Testing finished!") 565 | 566 | return acc, f1, difference 567 | 568 | def test(self, path): 569 | self.logger.info("[*] Running in test only mode.") 570 | 571 | self.data_handler.split_dataset() 572 | self.n_classes = self.data_handler.n_classes 573 | self.data_handler.compute_fold_split() 574 | 575 | self.logger.info("** Fitting {} classes!".format(self.n_classes)) 576 | 577 | self.model = self.create_model() 578 | 579 | self._test('test_only', path, self.data_handler.get_all_data()) 580 | -------------------------------------------------------------------------------- /code/models/Le2018.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import time 3 | import json 4 | import tensorflow as tf 5 | from tensorflow.keras import models 6 | from tensorflow.keras import layers 7 | from tensorflow.keras import regularizers 8 | from keras import backend as K 9 | import sklearn.metrics as metrics 10 | 11 | from .Basics import MachineLearningModel 12 | 13 | class CNN(MachineLearningModel): 14 | """ 15 | This class is based on Le2018 work. 16 | """ 17 | 18 | def __init__( 19 | self, 20 | path, 21 | ext='exe', 22 | max_len=1e4, 23 | use_lstm=True, 24 | use_lstm_bidirectional=True, 25 | max_epochs=250, 26 | patience=10, 27 | batch_size=64 28 | ): 29 | """ 30 | Parameters 31 | ---------- 32 | path : str 33 | Path to malware dataset 34 | max_len : int 35 | Length of the 1D malware data (default 1e4) 36 | use_lstm : int 37 | Flag to use cnn-lstm model if True or cnn if False (default True) 38 | max_epochs : int 39 | Number of max epochs to be run (default 250) 40 | patience : int 41 | Early stopping criteria. If improvement is not made for epochs (default 10) training stops 42 | batch_size : int 43 | Batch size (default 64) 44 | """ 45 | 46 | self.max_len = int(max_len) 47 | self.max_epochs = max_epochs 48 | self.batch_size = batch_size 49 | self.use_lstm = use_lstm 50 | self.bidirectional = use_lstm_bidirectional 51 | self.patience = patience 52 | self.model = None 53 | self.best_epoch = -1 54 | 55 | # Init parent class 56 | MachineLearningModel.__init__(self, 57 | path, 58 | 'model_original_le2018_', 59 | ext=ext, 60 | batch_size=self.batch_size) 61 | 62 | # Uncomment this block to train the model on GPU 63 | gpu_options = tf.compat.v1.GPUOptions(per_process_gpu_memory_fraction=0.7) 64 | config = tf.compat.v1.ConfigProto(gpu_options=gpu_options, allow_soft_placement=True, log_device_placement=True, device_count={'GPU': 1}) 65 | session = tf.compat.v1.Session(config=config) 66 | tf.compat.v1.keras.backend.set_session(session) 67 | 68 | def train(self, 69 | n_folds=1, 70 | split_method='nataraj', 71 | use_subset=False, 72 | test_npz=None, 73 | binarize=False, 74 | augmenters=None): 75 | self.logger.info("** Training started!") 76 | 77 | # Set augmentation methods to be used 78 | self.augmenters = augmenters 79 | 80 | self.data_handler.split_dataset(n_folds=n_folds, 81 | split_method=split_method, 82 | use_subset=use_subset) 83 | self.n_classes = self.data_handler.n_classes 84 | 85 | self.logger.info("** Fitting {} classes!".format(self.n_classes)) 86 | 87 | avg_acc = [] 88 | avg_f1 = [] 89 | avg_time = [] 90 | test_acc = 0 91 | 92 | 93 | inj_avg_acc = [] 94 | inj_avg_f1 = [] 95 | inj_avg_time = [] 96 | 97 | for fold in range(n_folds): 98 | self.logger.info("===== FOLD {} =====".format(fold)) 99 | 100 | self.data_handler.compute_fold_split() 101 | 102 | if self.use_lstm: 103 | self.model = self.create_cnn_lstm_model( 104 | n_class=self.data_handler.n_classes, 105 | bidirectional=self.bidirectional 106 | ) 107 | else: 108 | self.model = self.create_cnn_model( 109 | n_class=self.data_handler.n_classes 110 | ) 111 | 112 | print(self.model.summary()) 113 | 114 | # Run training in fold 115 | train_time = self._train(fold) 116 | fold_model = self.get_tmp_model_path() + str(self.best_epoch) + '_f' + str(fold) + '.h5' 117 | self.model_paths.append(fold_model) 118 | 119 | # Test with unseen data 120 | test_data = self.data_handler.get_test_data() 121 | test_acc, test_f1, test_time = self._test(fold+1, 122 | fold_model, 123 | test_data) 124 | self.results[fold+1] = { 125 | "acc": test_acc, 126 | "f1": test_f1, 127 | "train_time": train_time, 128 | "test_time": test_time 129 | } 130 | total_time = train_time + test_time 131 | avg_acc.append(test_acc) 132 | avg_f1.append(test_f1) 133 | avg_time.append(total_time) 134 | 135 | for npz in test_npz: 136 | # Test with injected data 137 | test_acc, test_f1, test_time = self._test_injected(npz, 138 | fold+1, 139 | fold_model, 140 | binarize=None) 141 | self.results[f"{fold+1}_injected"] = { 142 | "path": npz, 143 | "acc": test_acc, 144 | "f1": test_f1, 145 | "test_time": test_time 146 | } 147 | inj_avg_acc.append(test_acc) 148 | inj_avg_f1.append(test_f1) 149 | inj_avg_time.append(test_time) 150 | print_str = "** Finished training in {}s! Average ACC: {}; STD DEV {};".format( 151 | np.mean(avg_time), 152 | np.mean(avg_acc), 153 | np.std(avg_acc) 154 | ) 155 | self.logger.warning(print_str) 156 | self.data_handler.save_to_log(print_str + '\n') 157 | self.data_handler.save_to_log(json.dumps(self.results)) 158 | 159 | def _train(self, fold, epoch_range_start=0): 160 | 161 | train_data = self.data_handler.get_train_data() 162 | training_set_size = len(train_data) 163 | n_batches = np.ceil(training_set_size/self.batch_size) 164 | 165 | # Used to get the epoch with best results and load its model for testing 166 | best_acc = 0 167 | best_loss = 999999 168 | distance_from_improvement = 0 169 | 170 | total_time = 0 171 | 172 | # Run epochs 173 | for epoch in range(epoch_range_start, self.max_epochs): 174 | self.logger.info( 175 | "Epoch {}: training on {} samples.".format( 176 | epoch+1, 177 | training_set_size 178 | ) 179 | ) 180 | 181 | # Mini-batch gradient descent 182 | np.random.shuffle(train_data) 183 | train_acc = 0 184 | train_loss = 0 185 | 186 | start = time.time() 187 | 188 | for idx in range(0, training_set_size, self.batch_size): 189 | 190 | batch_X, batch_y = self.data_handler.load_raw_exe( 191 | train_data[idx:idx+self.batch_size], 192 | height=1, 193 | width=self.max_len, 194 | categorical_y=True, 195 | augmenters=self.augmenters 196 | ) 197 | 198 | self.logger.info( 199 | "Data info --> train: {} : {}".format( 200 | batch_X.shape, 201 | batch_y.shape, 202 | ) 203 | ) 204 | 205 | 206 | ret = self.model.train_on_batch( 207 | batch_X, 208 | batch_y, 209 | ) 210 | 211 | train_loss += ret[0] 212 | train_acc += ret[1] 213 | 214 | end = time.time() 215 | 216 | time_diff = int(end - start) 217 | total_time += time_diff 218 | 219 | # Call validation method 220 | validation_acc, validation_loss = self._validate() 221 | 222 | ############################ 223 | ####### DEBUG ######## 224 | ############################ 225 | 226 | self.logger.info( 227 | "*TRAINING* SET => ACC: {:.4f} ; " \ 228 | "LOSS: {:.4f}" 229 | .format( 230 | train_acc/n_batches, 231 | train_loss/n_batches 232 | ) 233 | ) 234 | 235 | self.logger.info( 236 | "*VALIDATE* SET => ACC: {:.4f} ; " \ 237 | "LOSS: {:.4f}" 238 | .format( 239 | validation_acc, 240 | validation_loss 241 | ) 242 | ) 243 | 244 | self.logger.info( 245 | "Finished epoch in {}s.".format(time_diff) 246 | ) 247 | 248 | self.data_handler.save_to_log( 249 | "epoch: {}, train_acc: {}, train_loss: {}, valid_acc: {}, valid_los: {}, time: {}s\n" 250 | .format( 251 | (epoch+1), 252 | train_acc/n_batches, 253 | train_loss/n_batches, 254 | validation_acc, 255 | validation_loss, 256 | time_diff 257 | ) 258 | ) 259 | 260 | ############################### 261 | ### EARLY STOPPING ### 262 | ############################### 263 | 264 | # Save epoch with best validation loss for testing 265 | if validation_acc > best_acc: 266 | best_loss = validation_loss 267 | best_acc = validation_acc 268 | self.best_epoch = (epoch+1) 269 | distance_from_improvement = 0 270 | 271 | # Save network parameters 272 | self.model.save_weights( 273 | self.get_tmp_model_path() + str(epoch+1) + '_f' + str(fold) + '.h5' 274 | ) 275 | else: 276 | distance_from_improvement += 1 277 | 278 | if distance_from_improvement > self.patience: 279 | 280 | print_str = "***** No improvement in last {} epochs! "\ 281 | "Stopping. Best epoch: {} => ACC: {}; LOSS: {};" \ 282 | .format( 283 | self.patience, 284 | self.best_epoch, 285 | best_acc, 286 | best_loss, 287 | ) 288 | self.logger.warning(print_str) 289 | self.data_handler.save_to_log(print_str + '\n') 290 | break 291 | 292 | return total_time 293 | 294 | def _validate(self): 295 | 296 | validation_acc = 0 297 | validation_loss = 0 298 | validation_data = self.data_handler.get_validation_data() 299 | validation_set_size = len(validation_data) 300 | n_batches = np.ceil(validation_set_size/self.batch_size) 301 | 302 | self.logger.info( 303 | "[*] Running validation on {} samples.".format( 304 | validation_set_size, 305 | ) 306 | ) 307 | 308 | for idx in range(0, validation_set_size, self.batch_size): 309 | 310 | validation_X, validation_y = self.data_handler.load_raw_exe( 311 | validation_data[idx:idx+self.batch_size], 312 | height=1, 313 | width=self.max_len, 314 | categorical_y=True 315 | ) 316 | 317 | self.logger.info( 318 | "Data info --> validation: {} : {}".format( 319 | validation_X.shape, 320 | validation_y.shape, 321 | ) 322 | ) 323 | 324 | ret = self.model.test_on_batch( 325 | validation_X, 326 | validation_y 327 | ) 328 | 329 | validation_loss += ret[0] 330 | validation_acc += ret[1] 331 | 332 | return validation_acc/n_batches, validation_loss/n_batches 333 | 334 | def _test(self, fold, model_path, test_data): 335 | 336 | self.logger.warning("*** Loading tensorflow Graph from {}.".format(model_path)) 337 | 338 | result_file = self.data_handler.create_file( 339 | name="test_results_{}.txt".format(fold), 340 | ) 341 | 342 | test_set_size = len(test_data) 343 | labels = [] 344 | predictions = [] 345 | scores = [] 346 | 347 | self.model.load_weights(model_path) 348 | 349 | start_test_predict = time.time() 350 | 351 | for idx in range(0, test_set_size, self.batch_size): 352 | 353 | samples = test_data[idx:idx+self.batch_size] 354 | 355 | test_X, test_y = self.data_handler.load_raw_exe( 356 | samples, 357 | height=1, 358 | width=self.max_len, 359 | categorical_y=False 360 | ) 361 | 362 | y_predict = self.model.predict(test_X) 363 | 364 | for i in range(len(test_y)): 365 | predicted_class = np.argmax(y_predict[i]) 366 | 367 | labels.append(test_y[i]) 368 | predictions.append(predicted_class) 369 | scores.append(y_predict[i]) 370 | 371 | result_file.write("{}, {}\n".format(test_y[i], 372 | predicted_class)) 373 | 374 | end_test_predict = time.time() 375 | 376 | acc = metrics.accuracy_score(labels, predictions) 377 | f1 = metrics.f1_score(labels, predictions, average="weighted") 378 | 379 | difference = int(end_test_predict - start_test_predict) 380 | 381 | print_str = "\t\t *TEST* SET => Time: {}s; ACC: {:.4f}; F1: {:.4f}".format(difference, acc, f1) 382 | 383 | self.logger.info(print_str) 384 | result_file.write(print_str) 385 | 386 | self.logger.info(f" Saving npz: metrics_test_results_{fold}.npz") 387 | np.savez(f"{self.data_handler.tmp_output_path}/metrics_test_results_{fold}.npz", 388 | y_true=labels, 389 | y=predictions, 390 | p=scores, 391 | acc=acc, 392 | f1=f1) 393 | 394 | self.logger.info("** Testing finished!") 395 | 396 | return acc, f1, difference 397 | 398 | def test(self, path): 399 | self.logger.info("[*] Running in test only mode.") 400 | 401 | self.data_handler.split_dataset() 402 | self.n_classes = self.data_handler.n_classes 403 | self.data_handler.compute_fold_split() 404 | 405 | self.logger.info("** Fitting {} classes!".format(self.n_classes)) 406 | 407 | if self.use_lstm: 408 | self.model = self.create_cnn_lstm_model( 409 | n_class=self.data_handler.n_classes, 410 | bidirectional=self.bidirectional 411 | ) 412 | else: 413 | self.model = self.create_cnn_model( 414 | n_class=self.data_handler.n_classes 415 | ) 416 | 417 | self._test('test_only', path, self.data_handler.get_all_data()) 418 | 419 | def test_injected(self, base_path, subdir, sections=5, bytes=5, bytes_start=1, bytes_increment=1): 420 | result_json = {} 421 | 422 | for _model in self.model_paths: 423 | self.logger.info("[@@] Evaluating {} _model".format(_model)) 424 | for _section in range(1, sections+1): 425 | for _byte in range(bytes_start, bytes+1, bytes_increment): 426 | dataset_path = "{}_{}_{}/{}/".format(base_path, _section, _byte, subdir) 427 | _split = "{}_{}".format(_section, _byte) 428 | 429 | from .Data import MalImgDataset 430 | _data_handler = MalImgDataset(dataset_path, 431 | extension=self.ext, 432 | batch_size=self.batch_size, 433 | output_mode=False) 434 | _data_handler.split_dataset() 435 | _data_handler.compute_fold_split() 436 | 437 | test_acc = self._test("injected_{}".format(_split), 438 | _model, 439 | _data_handler.get_all_data()) 440 | if _split not in result_json.keys(): 441 | result_json[_split] = [ test_acc ] 442 | else: 443 | result_json[_split].append(test_acc) 444 | result_file = self.data_handler.create_file(name="injected_results.txt") 445 | 446 | final_result = { 447 | "regular_tests" : self.results, 448 | "injection_tests" : result_json 449 | } 450 | result_file.write(json.dumps(final_result)) 451 | 452 | return final_result 453 | 454 | def _test_injected(self, npz, fold, model_path, binarize=None): 455 | 456 | data = np.load(npz, mmap_mode='r', allow_pickle=True) 457 | 458 | total_samples = data['y'].shape[0] 459 | MBS=4096 460 | 461 | self.logger.warning("*** Loading tensorflow Graph from {}. Testing against {} samples.".format(model_path, total_samples)) 462 | 463 | result_file_name = "{}_{}".format(npz.split('/')[-1].split('.')[0], fold) 464 | result_file = self.data_handler.create_file( 465 | name=f"test_results_{result_file_name}.txt", 466 | ) 467 | 468 | labels = [] 469 | predictions = [] 470 | scores = [] 471 | 472 | self.model.load_weights(model_path) 473 | 474 | # https://stackoverflow.com/questions/59216547/python-npzfile-objects-are-very-slow 475 | m_X = data['X'] 476 | m_y = data['y'] 477 | 478 | start_test_predict = time.time() 479 | 480 | for idx in range(0, total_samples, MBS): 481 | 482 | batchX = m_X[idx:idx+MBS] 483 | batchY = m_y[idx:idx+MBS] 484 | size = batchX.shape[0] 485 | 486 | batch_data = list(zip(batchX, batchY)) 487 | 488 | # Select a random negative as source for data injection 489 | # negative_sample = negative_paths[random.randint(0, negative_set_size-1)] 490 | 491 | X, _ = self.data_handler.load_raw_exe( 492 | batch_data, 493 | height=1, 494 | width=self.max_len, 495 | categorical_y=False, 496 | from_data=True 497 | ) 498 | 499 | probs = self.model.predict(X) 500 | 501 | for _id in range(size): 502 | 503 | # if binarize in [None, False]: 504 | y = batchY[_id] 505 | # else: 506 | # y = 1 if batchY[_id] == binarize else 0 507 | 508 | # X = self.data_handler.buffer_to_image(batchX[_id], 1, self.max_len) 509 | 510 | # # print(batchX[_id].shape, X.shape) 511 | 512 | # _y = self.model.predict(np.array([X])) 513 | # score = _y[0][1] # probability of being malware 514 | score = probs[_id] 515 | _y = np.argmax(score) 516 | 517 | scores.append(score) 518 | labels.append(int(y)) 519 | predictions.append(_y) 520 | 521 | result_file.write("{}, {}\n".format(y, 522 | _y)) 523 | 524 | end_test_predict = time.time() 525 | 526 | acc = metrics.accuracy_score(labels, predictions) 527 | f1 = metrics.f1_score(labels, predictions, average="weighted") 528 | # precision, recall, thresholds = metrics.precision_recall_curve(labels, scores) 529 | 530 | difference = int(end_test_predict - start_test_predict) 531 | 532 | print_str = "\t\t *TEST* SET (INJECTED) => Time: {}s; ACC: {:.4f}; F1: {:.4f}".format(difference, acc, f1) 533 | 534 | self.logger.info(print_str) 535 | result_file.write(print_str) 536 | 537 | 538 | self.logger.info(f" Saving npz: {result_file_name}.npz") 539 | np.savez(f"{self.data_handler.tmp_output_path}/metrics_{result_file_name}.npz", 540 | y_true=labels, 541 | y=predictions, 542 | p=scores, 543 | acc=acc, 544 | f1=f1) 545 | # precision=precision, 546 | # recall=recall, 547 | # thresholds=thresholds) 548 | 549 | self.logger.info("** Injection Testing finished!") 550 | 551 | return acc, f1, difference 552 | 553 | def test_online_injection(self): 554 | 555 | import random 556 | 557 | self.logger.warning("[@@@@@@@] Starting ONLINE INJECTION TEST.") 558 | 559 | fold = 1 560 | for _model in self.model_paths: 561 | 562 | self.logger.warning("*** Loading tensorflow Graph from {}.".format(_model)) 563 | self.model.load_weights(_model) 564 | 565 | for _class in self.data_handler.class_map.keys(): 566 | 567 | if _class == 'benign': 568 | continue 569 | 570 | _id = self.data_handler.class_map[_class] 571 | 572 | self.logger.warning("\t[&] Testing injection on {} samples.".format(_class)) 573 | 574 | result_file = self.data_handler.create_file( 575 | name="test_results_online_injection_{}_{}.txt".format(_class, fold), 576 | ) 577 | 578 | test_data = np.array(self.data_handler.get_test_data()) 579 | test_set_size = test_data.shape[0] 580 | 581 | labels = [] 582 | predictions = [] 583 | 584 | # Split paths into positive and negative samples (one against all) 585 | positive_paths = test_data[np.where(test_data[:, 1] == str(_id))][:,0] 586 | negative_paths = test_data[np.where(test_data[:, 1] != str(_id))][:,0] 587 | 588 | negative_set_size = negative_paths.shape[0] 589 | 590 | start_test_predict = time.time() 591 | 592 | for _positive in positive_paths: 593 | # Select a random negative as source for data injection 594 | negative_sample = negative_paths[random.randint(0, negative_set_size-1)] 595 | 596 | # self.logger.info("Injecting at {} from {}.".format(_positive, negative_sample)) 597 | 598 | # Inject section into the negative 599 | test_X = self.data_handler.inject_from_file(_positive, 600 | None, 601 | n_injected_sections=5, 602 | n_bytes=5, 603 | height=1, 604 | width=self.max_len) 605 | 606 | _X, _ = self.data_handler.load_raw_exe( 607 | [(_positive, _id)], 608 | height=1, 609 | width=self.max_len, 610 | categorical_y=False 611 | ) 612 | _y_original = self.model.predict(_X) 613 | 614 | # print(f"[ON] {_X.shape} | {test_X.shape}") 615 | 616 | # Perform prediction 617 | y_predict = self.model.predict(np.array([test_X])) 618 | 619 | 620 | predicted_class = np.argmax(y_predict[0]) 621 | 622 | labels.append(_id) 623 | predictions.append(predicted_class) 624 | 625 | result_file.write(f"{_positive} => orig: {_y_original} | inject: {y_predict}") 626 | result_file.write("[{}]: {}, {}\n".format(_class, _id, 627 | predicted_class)) 628 | 629 | end_test_predict = time.time() 630 | 631 | # Compute time 632 | difference = int(end_test_predict - start_test_predict) 633 | 634 | # Compute metrics 635 | acc = metrics.accuracy_score(labels, predictions) 636 | f1 = metrics.f1_score(labels, predictions, average="weighted") 637 | 638 | print_str = "\t\t *TEST* SET => Time: {}s; ACC: {:.4f}; F1: {:.4f}".format(difference, acc, f1) 639 | 640 | self.logger.info(print_str) 641 | result_file.write(print_str) 642 | 643 | self.logger.info("** Testing finished!") 644 | 645 | fold += 1 646 | 647 | 648 | def create_cnn_lstm_model(self, n_class, bidirectional=True): 649 | """ 650 | generate CNN with 1 or Bi directional LSTM on top 651 | Parameters: 652 | n_class: number of classes 653 | bidirectional: boolean value: to generate uni or bidirectional LSTM on top of CNN layers 654 | Return: 655 | the CNN -UniLSTM or CNN-BiLSTM model 656 | """ 657 | cnn_lstm_model = models.Sequential() 658 | 659 | cnn_lstm_model.add(layers.Conv1D(filters=30, kernel_size=7, strides=1, kernel_regularizer=regularizers.l2(0.01), activation='relu', input_shape=(self.max_len, 1))) 660 | cnn_lstm_model.add(layers.MaxPool1D(5)) 661 | cnn_lstm_model.add(layers.Conv1D(filters=50, kernel_size=7, strides=1, kernel_regularizer=regularizers.l2(0.01), activation='relu')) 662 | cnn_lstm_model.add(layers.MaxPool1D(5)) 663 | cnn_lstm_model.add(layers.Conv1D(filters=90, kernel_size=7, strides=1, kernel_regularizer=regularizers.l2(0.01), activation='relu')) 664 | cnn_lstm_model.add(layers.MaxPool1D(5)) 665 | 666 | if bidirectional: 667 | cnn_lstm_model.add(layers.Bidirectional(layers.LSTM(units=128, dropout=0.2, recurrent_dropout=0.2))) 668 | else: 669 | cnn_lstm_model.add(layers.LSTM(units=128, dropout=0.2, recurrent_dropout=0.2)) 670 | 671 | cnn_lstm_model.add(layers.Dense(n_class, activation='softmax')) 672 | 673 | cnn_lstm_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) 674 | 675 | return cnn_lstm_model 676 | 677 | def create_cnn_model(self, n_class): 678 | """ 679 | generate the CNN model 680 | Parameters: 681 | n_class: number of classes 682 | Return: 683 | the CNN model 684 | """ 685 | cnn_model_ = models.Sequential() 686 | 687 | cnn_model_.add(layers.Conv1D(filters=30, kernel_size=7, strides=1, kernel_regularizer=regularizers.l2(0.01), activation='relu', input_shape=(self.max_len, 1))) 688 | cnn_model_.add(layers.MaxPool1D(5)) 689 | cnn_model_.add(layers.Conv1D(filters=50, kernel_size=7, strides=1, kernel_regularizer=regularizers.l2(0.01), activation='relu')) 690 | cnn_model_.add(layers.MaxPool1D(5)) 691 | cnn_model_.add(layers.Conv1D(filters=90, kernel_size=7, strides=1, kernel_regularizer=regularizers.l2(0.01), activation='relu')) 692 | cnn_model_.add(layers.MaxPool1D(5)) 693 | 694 | cnn_model_.add(layers.Flatten()) 695 | cnn_model_.add(layers.Dropout(0.2)) 696 | cnn_model_.add(layers.Dense(256, activation='relu')) 697 | cnn_model_.add(layers.Dropout(0.3)) 698 | cnn_model_.add(layers.Dense(n_class, activation='softmax')) 699 | 700 | cnn_model_.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) 701 | 702 | return cnn_model_ 703 | -------------------------------------------------------------------------------- /dependencies/pyleargist-2.0.5/lear_gist/gist.c: -------------------------------------------------------------------------------- 1 | /* Lear's GIST implementation, version 1.0, (c) INRIA 2009, Licence: GPL */ 2 | /*--------------------------------------------------------------------------*/ 3 | 4 | #ifdef USE_GIST 5 | 6 | /*--------------------------------------------------------------------------*/ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include 15 | #include 16 | 17 | #ifdef STANDALONE_GIST 18 | 19 | #include "gist.h" 20 | 21 | #else 22 | 23 | #include 24 | #include 25 | 26 | #endif 27 | 28 | /*--------------------------------------------------------------------------*/ 29 | 30 | static pthread_mutex_t fftw_mutex = PTHREAD_MUTEX_INITIALIZER; 31 | 32 | static void fftw_lock(void) 33 | { 34 | pthread_mutex_lock(&fftw_mutex); 35 | } 36 | 37 | static void fftw_unlock(void) 38 | { 39 | pthread_mutex_unlock(&fftw_mutex); 40 | } 41 | 42 | /*--------------------------------------------------------------------------*/ 43 | 44 | static image_t *image_add_padding(image_t *src, int padding) 45 | { 46 | int i, j; 47 | 48 | image_t *img = image_new(src->width + 2*padding, src->height + 2*padding); 49 | 50 | memset(img->data, 0x00, img->stride*img->height*sizeof(float)); 51 | 52 | for(j = 0; j < src->height; j++) 53 | { 54 | for(i = 0; i < src->width; i++) { 55 | img->data[(j+padding)*img->stride+i+padding] = src->data[j*src->stride+i]; 56 | } 57 | } 58 | 59 | for(j = 0; j < padding; j++) 60 | { 61 | for(i = 0; i < src->width; i++) 62 | { 63 | img->data[j*img->stride+i+padding] = src->data[(padding-j-1)*src->stride+i]; 64 | img->data[(j+padding+src->height)*img->stride+i+padding] = src->data[(src->height-j-1)*src->stride+i]; 65 | } 66 | } 67 | 68 | for(j = 0; j < img->height; j++) 69 | { 70 | for(i = 0; i < padding; i++) 71 | { 72 | img->data[j*img->stride+i] = img->data[j*img->stride+padding+padding-i-1]; 73 | img->data[j*img->stride+i+padding+src->width] = img->data[j*img->stride+img->width-padding-i-1]; 74 | } 75 | } 76 | 77 | return img; 78 | } 79 | 80 | /*--------------------------------------------------------------------------*/ 81 | 82 | static color_image_t *color_image_add_padding(color_image_t *src, int padding) 83 | { 84 | int i, j; 85 | 86 | color_image_t *img = color_image_new(src->width + 2*padding, src->height + 2*padding); 87 | 88 | for(j = 0; j < src->height; j++) 89 | { 90 | for(i = 0; i < src->width; i++) 91 | { 92 | img->c1[(j+padding)*img->width+i+padding] = src->c1[j*src->width+i]; 93 | img->c2[(j+padding)*img->width+i+padding] = src->c2[j*src->width+i]; 94 | img->c3[(j+padding)*img->width+i+padding] = src->c3[j*src->width+i]; 95 | } 96 | } 97 | 98 | for(j = 0; j < padding; j++) 99 | { 100 | for(i = 0; i < src->width; i++) 101 | { 102 | img->c1[j*img->width+i+padding] = src->c1[(padding-j-1)*src->width+i]; 103 | img->c2[j*img->width+i+padding] = src->c2[(padding-j-1)*src->width+i]; 104 | img->c3[j*img->width+i+padding] = src->c3[(padding-j-1)*src->width+i]; 105 | 106 | img->c1[(j+padding+src->height)*img->width+i+padding] = src->c1[(src->height-j-1)*src->width+i]; 107 | img->c2[(j+padding+src->height)*img->width+i+padding] = src->c2[(src->height-j-1)*src->width+i]; 108 | img->c3[(j+padding+src->height)*img->width+i+padding] = src->c3[(src->height-j-1)*src->width+i]; 109 | } 110 | } 111 | 112 | for(j = 0; j < img->height; j++) 113 | { 114 | for(i = 0; i < padding; i++) 115 | { 116 | img->c1[j*img->width+i] = img->c1[j*img->width+padding+padding-i-1]; 117 | img->c2[j*img->width+i] = img->c2[j*img->width+padding+padding-i-1]; 118 | img->c3[j*img->width+i] = img->c3[j*img->width+padding+padding-i-1]; 119 | 120 | img->c1[j*img->width+i+padding+src->width] = img->c1[j*img->width+img->width-padding-i-1]; 121 | img->c2[j*img->width+i+padding+src->width] = img->c2[j*img->width+img->width-padding-i-1]; 122 | img->c3[j*img->width+i+padding+src->width] = img->c3[j*img->width+img->width-padding-i-1]; 123 | } 124 | } 125 | 126 | return img; 127 | } 128 | 129 | /*--------------------------------------------------------------------------*/ 130 | 131 | static void image_rem_padding(image_t *dest, image_t *src, int padding) 132 | { 133 | int i, j; 134 | 135 | for(j = 0; j < dest->height; j++) 136 | { 137 | for(i = 0; i < dest->width; i++) { 138 | dest->data[j*dest->stride+i] = src->data[(j+padding)*src->stride+i+padding]; 139 | } 140 | } 141 | } 142 | 143 | /*--------------------------------------------------------------------------*/ 144 | 145 | static void color_image_rem_padding(color_image_t *dest, color_image_t *src, int padding) 146 | { 147 | int i, j; 148 | 149 | for(j = 0; j < dest->height; j++) 150 | { 151 | for(i = 0; i < dest->width; i++) 152 | { 153 | dest->c1[j*dest->width+i] = src->c1[(j+padding)*src->width+i+padding]; 154 | dest->c2[j*dest->width+i] = src->c2[(j+padding)*src->width+i+padding]; 155 | dest->c3[j*dest->width+i] = src->c3[(j+padding)*src->width+i+padding]; 156 | } 157 | } 158 | } 159 | 160 | /*--------------------------------------------------------------------------*/ 161 | 162 | static void fftshift(float *data, int w, int h) 163 | { 164 | int i, j; 165 | 166 | float *buff = (float *) malloc(w*h*sizeof(float)); 167 | 168 | memcpy(buff, data, w*h*sizeof(float)); 169 | 170 | for(j = 0; j < (h+1)/2; j++) 171 | { 172 | for(i = 0; i < (w+1)/2; i++) { 173 | data[(j+h/2)*w + i+w/2] = buff[j*w + i]; 174 | } 175 | 176 | for(i = 0; i < w/2; i++) { 177 | data[(j+h/2)*w + i] = buff[j*w + i+(w+1)/2]; 178 | } 179 | } 180 | 181 | for(j = 0; j < h/2; j++) 182 | { 183 | for(i = 0; i < (w+1)/2; i++) { 184 | data[j*w + i+w/2] = buff[(j+(h+1)/2)*w + i]; 185 | } 186 | 187 | for(i = 0; i < w/2; i++) { 188 | data[j*w + i] = buff[(j+(h+1)/2)*w + i+(w+1)/2]; 189 | } 190 | } 191 | 192 | free(buff); 193 | } 194 | 195 | /*--------------------------------------------------------------------------*/ 196 | 197 | static image_list_t *create_gabor(int nscales, const int *or, int width, int height) 198 | { 199 | int i, j, fn; 200 | 201 | image_list_t *G = image_list_new(); 202 | 203 | int nfilters = 0; 204 | for(i=0;i M_PI) { 260 | tmp -= 2.0f*M_PI; 261 | } 262 | 263 | G0->data[j*G0->stride+i] = exp(-10.0f*param[fn][0]*(*fr_ptr/height/param[fn][1]-1)*(*fr_ptr/width/param[fn][1]-1)-2.0f*param[fn][2]*M_PI*tmp*tmp); 264 | fr_ptr++; 265 | } 266 | } 267 | 268 | image_list_append(G, G0); 269 | } 270 | 271 | for(i = 0; i < nscales * nfilters; i++) { 272 | free(param[i]); 273 | } 274 | free(param); 275 | 276 | free(fx); 277 | free(fy); 278 | free(fr); 279 | free(f); 280 | 281 | return G; 282 | } 283 | 284 | /*--------------------------------------------------------------------------*/ 285 | 286 | /*static*/ void prefilt(image_t *src, int fc) 287 | { 288 | fftw_lock(); 289 | 290 | int i, j; 291 | 292 | /* Log */ 293 | for(j = 0; j < src->height; j++) 294 | { 295 | for(i = 0; i < src->width; i++) { 296 | src->data[j*src->stride+i] = log(src->data[j*src->stride+i]+1.0f); 297 | } 298 | } 299 | 300 | image_t *img_pad = image_add_padding(src, 5); 301 | 302 | /* Get sizes */ 303 | int width = img_pad->width; 304 | int height = img_pad->height; 305 | int stride = img_pad->stride; 306 | 307 | /* Alloc memory */ 308 | float *fx = (float *) fftwf_malloc(width*height*sizeof(float)); 309 | float *fy = (float *) fftwf_malloc(width*height*sizeof(float)); 310 | float *gfc = (float *) fftwf_malloc(width*height*sizeof(float)); 311 | fftwf_complex *in1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 312 | fftwf_complex *in2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 313 | fftwf_complex *out = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 314 | 315 | /* Build whitening filter */ 316 | float s1 = fc/sqrt(log(2)); 317 | for(j = 0; j < height; j++) 318 | { 319 | for(i = 0; i < width; i++) 320 | { 321 | in1[j*width + i][0] = img_pad->data[j*stride+i]; 322 | in1[j*width + i][1] = 0.0f; 323 | 324 | fx[j*width + i] = (float) i - width/2.0f; 325 | fy[j*width + i] = (float) j - height/2.0f; 326 | 327 | gfc[j*width + i] = exp(-(fx[j*width + i]*fx[j*width + i] + fy[j*width + i]*fy[j*width + i]) / (s1*s1)); 328 | } 329 | } 330 | 331 | fftshift(gfc, width, height); 332 | 333 | /* FFT */ 334 | fftwf_plan fft1 = fftwf_plan_dft_2d(width, height, in1, out, FFTW_FORWARD, FFTW_ESTIMATE); 335 | fftw_unlock(); 336 | fftwf_execute(fft1); 337 | fftw_lock(); 338 | 339 | /* Apply whitening filter */ 340 | for(j = 0; j < height; j++) 341 | { 342 | for(i = 0; i < width; i++) 343 | { 344 | out[j*width+i][0] *= gfc[j*width + i]; 345 | out[j*width+i][1] *= gfc[j*width + i]; 346 | } 347 | } 348 | 349 | /* IFFT */ 350 | fftwf_plan ifft1 = fftwf_plan_dft_2d(width, height, out, in2, FFTW_BACKWARD, FFTW_ESTIMATE); 351 | fftw_unlock(); 352 | fftwf_execute(ifft1); 353 | fftw_lock(); 354 | 355 | /* Local contrast normalisation */ 356 | for(j = 0; j < height; j++) 357 | { 358 | for(i = 0; i < width; i++) 359 | { 360 | img_pad->data[j*stride + i] -= in2[j*width+i][0] / (width*height); 361 | 362 | in1[j*width + i][0] = img_pad->data[j*stride + i] * img_pad->data[j*stride + i]; 363 | in1[j*width + i][1] = 0.0f; 364 | } 365 | } 366 | 367 | /* FFT */ 368 | fftwf_plan fft2 = fftwf_plan_dft_2d(width, height, in1, out, FFTW_FORWARD, FFTW_ESTIMATE); 369 | fftw_unlock(); 370 | fftwf_execute(fft2); 371 | fftw_lock(); 372 | 373 | /* Apply contrast normalisation filter */ 374 | for(j = 0; j < height; j++) 375 | { 376 | for(i = 0; i < width; i++) 377 | { 378 | out[j*width+i][0] *= gfc[j*width + i]; 379 | out[j*width+i][1] *= gfc[j*width + i]; 380 | } 381 | } 382 | 383 | /* IFFT */ 384 | fftwf_plan ifft2 = fftwf_plan_dft_2d(width, height, out, in2, FFTW_BACKWARD, FFTW_ESTIMATE); 385 | fftw_unlock(); 386 | fftwf_execute(ifft2); 387 | fftw_lock(); 388 | 389 | /* Get result from contrast normalisation filter */ 390 | for(j = 0; j < height; j++) 391 | { 392 | for(i = 0; i < width; i++) { 393 | img_pad->data[j*stride+i] = img_pad->data[j*stride + i] / (0.2f+sqrt(sqrt(in2[j*width+i][0]*in2[j*width+i][0]+in2[j*width+i][1]*in2[j*width+i][1]) / (width*height))); 394 | } 395 | } 396 | 397 | image_rem_padding(src, img_pad, 5); 398 | 399 | /* Free */ 400 | fftwf_destroy_plan(fft1); 401 | fftwf_destroy_plan(fft2); 402 | fftwf_destroy_plan(ifft1); 403 | fftwf_destroy_plan(ifft2); 404 | 405 | image_delete(img_pad); 406 | 407 | fftwf_free(in1); 408 | fftwf_free(in2); 409 | fftwf_free(out); 410 | fftwf_free(fx); 411 | fftwf_free(fy); 412 | fftwf_free(gfc); 413 | 414 | fftw_unlock(); 415 | } 416 | 417 | /*--------------------------------------------------------------------------*/ 418 | 419 | static void color_prefilt(color_image_t *src, int fc) 420 | { 421 | fftw_lock(); 422 | 423 | int i, j; 424 | 425 | /* Log */ 426 | for(j = 0; j < src->height; j++) 427 | { 428 | for(i = 0; i < src->width; i++) 429 | { 430 | src->c1[j*src->width+i] = log(src->c1[j*src->width+i]+1.0f); 431 | src->c2[j*src->width+i] = log(src->c2[j*src->width+i]+1.0f); 432 | src->c3[j*src->width+i] = log(src->c3[j*src->width+i]+1.0f); 433 | } 434 | } 435 | 436 | color_image_t *img_pad = color_image_add_padding(src, 5); 437 | 438 | /* Get sizes */ 439 | int width = img_pad->width; 440 | int height = img_pad->height; 441 | 442 | /* Alloc memory */ 443 | float *fx = (float *) fftwf_malloc(width*height*sizeof(float)); 444 | float *fy = (float *) fftwf_malloc(width*height*sizeof(float)); 445 | float *gfc = (float *) fftwf_malloc(width*height*sizeof(float)); 446 | fftwf_complex *ina1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 447 | fftwf_complex *ina2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 448 | fftwf_complex *ina3 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 449 | fftwf_complex *inb1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 450 | fftwf_complex *inb2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 451 | fftwf_complex *inb3 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 452 | fftwf_complex *out1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 453 | fftwf_complex *out2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 454 | fftwf_complex *out3 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 455 | 456 | /* Build whitening filter */ 457 | float s1 = fc/sqrt(log(2)); 458 | for(j = 0; j < height; j++) 459 | { 460 | for(i = 0; i < width; i++) 461 | { 462 | ina1[j*width + i][0] = img_pad->c1[j*width+i]; 463 | ina2[j*width + i][0] = img_pad->c2[j*width+i]; 464 | ina3[j*width + i][0] = img_pad->c3[j*width+i]; 465 | ina1[j*width + i][1] = 0.0f; 466 | ina2[j*width + i][1] = 0.0f; 467 | ina3[j*width + i][1] = 0.0f; 468 | 469 | fx[j*width + i] = (float) i - width/2.0f; 470 | fy[j*width + i] = (float) j - height/2.0f; 471 | 472 | gfc[j*width + i] = exp(-(fx[j*width + i]*fx[j*width + i] + fy[j*width + i]*fy[j*width + i]) / (s1*s1)); 473 | } 474 | } 475 | 476 | fftshift(gfc, width, height); 477 | 478 | /* FFT */ 479 | fftwf_plan fft11 = fftwf_plan_dft_2d(width, height, ina1, out1, FFTW_FORWARD, FFTW_ESTIMATE); 480 | fftwf_plan fft12 = fftwf_plan_dft_2d(width, height, ina2, out2, FFTW_FORWARD, FFTW_ESTIMATE); 481 | fftwf_plan fft13 = fftwf_plan_dft_2d(width, height, ina3, out3, FFTW_FORWARD, FFTW_ESTIMATE); 482 | fftw_unlock(); 483 | fftwf_execute(fft11); 484 | fftwf_execute(fft12); 485 | fftwf_execute(fft13); 486 | fftw_lock(); 487 | 488 | /* Apply whitening filter */ 489 | for(j = 0; j < height; j++) 490 | { 491 | for(i = 0; i < width; i++) 492 | { 493 | out1[j*width+i][0] *= gfc[j*width + i]; 494 | out2[j*width+i][0] *= gfc[j*width + i]; 495 | out3[j*width+i][0] *= gfc[j*width + i]; 496 | 497 | out1[j*width+i][1] *= gfc[j*width + i]; 498 | out2[j*width+i][1] *= gfc[j*width + i]; 499 | out3[j*width+i][1] *= gfc[j*width + i]; 500 | } 501 | } 502 | 503 | /* IFFT */ 504 | fftwf_plan ifft11 = fftwf_plan_dft_2d(width, height, out1, inb1, FFTW_BACKWARD, FFTW_ESTIMATE); 505 | fftwf_plan ifft12 = fftwf_plan_dft_2d(width, height, out2, inb2, FFTW_BACKWARD, FFTW_ESTIMATE); 506 | fftwf_plan ifft13 = fftwf_plan_dft_2d(width, height, out3, inb3, FFTW_BACKWARD, FFTW_ESTIMATE); 507 | fftw_unlock(); 508 | fftwf_execute(ifft11); 509 | fftwf_execute(ifft12); 510 | fftwf_execute(ifft13); 511 | fftw_lock(); 512 | 513 | /* Local contrast normalisation */ 514 | for(j = 0; j < height; j++) 515 | { 516 | for(i = 0; i < width; i++) 517 | { 518 | img_pad->c1[j*width+i] -= inb1[j*width+i][0] / (width*height); 519 | img_pad->c2[j*width+i] -= inb2[j*width+i][0] / (width*height); 520 | img_pad->c3[j*width+i] -= inb3[j*width+i][0] / (width*height); 521 | 522 | float mean = (img_pad->c1[j*width+i] + img_pad->c2[j*width+i] + img_pad->c3[j*width+i])/3.0f; 523 | 524 | ina1[j*width+i][0] = mean*mean; 525 | ina1[j*width+i][1] = 0.0f; 526 | } 527 | } 528 | 529 | /* FFT */ 530 | fftwf_plan fft21 = fftwf_plan_dft_2d(width, height, ina1, out1, FFTW_FORWARD, FFTW_ESTIMATE); 531 | fftw_unlock(); 532 | fftwf_execute(fft21); 533 | fftw_lock(); 534 | 535 | /* Apply contrast normalisation filter */ 536 | for(j = 0; j < height; j++) 537 | { 538 | for(i = 0; i < width; i++) 539 | { 540 | out1[j*width+i][0] *= gfc[j*width + i]; 541 | out1[j*width+i][1] *= gfc[j*width + i]; 542 | } 543 | } 544 | 545 | /* IFFT */ 546 | fftwf_plan ifft2 = fftwf_plan_dft_2d(width, height, out1, inb1, FFTW_BACKWARD, FFTW_ESTIMATE); 547 | fftw_unlock(); 548 | fftwf_execute(ifft2); 549 | fftw_lock(); 550 | 551 | /* Get result from contrast normalisation filter */ 552 | for(j = 0; j < height; j++) 553 | { 554 | for(i = 0; i < width; i++) 555 | { 556 | float val = sqrt(sqrt(inb1[j*width+i][0]*inb1[j*width+i][0]+inb1[j*width+i][1]*inb1[j*width+i][1]) / (width*height)); 557 | 558 | img_pad->c1[j*width+i] /= (0.2f+val); 559 | img_pad->c2[j*width+i] /= (0.2f+val); 560 | img_pad->c3[j*width+i] /= (0.2f+val); 561 | } 562 | } 563 | 564 | color_image_rem_padding(src, img_pad, 5); 565 | 566 | /* Free */ 567 | fftwf_destroy_plan(fft11); 568 | fftwf_destroy_plan(fft12); 569 | fftwf_destroy_plan(fft13); 570 | fftwf_destroy_plan(ifft11); 571 | fftwf_destroy_plan(ifft12); 572 | fftwf_destroy_plan(ifft13); 573 | fftwf_destroy_plan(fft21); 574 | fftwf_destroy_plan(ifft2); 575 | 576 | color_image_delete(img_pad); 577 | 578 | fftwf_free(ina1); 579 | fftwf_free(ina2); 580 | fftwf_free(ina3); 581 | fftwf_free(inb1); 582 | fftwf_free(inb2); 583 | fftwf_free(inb3); 584 | fftwf_free(out1); 585 | fftwf_free(out2); 586 | fftwf_free(out3); 587 | fftwf_free(fx); 588 | fftwf_free(fy); 589 | fftwf_free(gfc); 590 | 591 | fftw_unlock(); 592 | } 593 | 594 | /*--------------------------------------------------------------------------*/ 595 | 596 | static void down_N(float *res, image_t *src, int N) 597 | { 598 | int i, j, k, l; 599 | 600 | int *nx = (int *) malloc((N+1)*sizeof(int)); 601 | int *ny = (int *) malloc((N+1)*sizeof(int)); 602 | 603 | for(i = 0; i < N+1; i++) 604 | { 605 | nx[i] = i*src->width/(N); 606 | ny[i] = i*src->height/(N); 607 | } 608 | 609 | for(l = 0; l < N; l++) 610 | { 611 | for(k = 0; k < N; k++) 612 | { 613 | float mean = 0.0f; 614 | 615 | for(j = ny[l]; j < ny[l+1]; j++) 616 | { 617 | for(i = nx[k]; i < nx[k+1]; i++) { 618 | mean += src->data[j*src->stride+i]; 619 | } 620 | } 621 | 622 | float denom = (float)(ny[l+1]-ny[l])*(nx[k+1]-nx[k]); 623 | 624 | res[k*N+l] = mean / denom; 625 | } 626 | } 627 | 628 | free(nx); 629 | free(ny); 630 | } 631 | 632 | /*--------------------------------------------------------------------------*/ 633 | 634 | static void color_down_N(float *res, color_image_t *src, int N, int c) 635 | { 636 | int i, j, k, l; 637 | 638 | int *nx = (int *) malloc((N+1)*sizeof(int)); 639 | int *ny = (int *) malloc((N+1)*sizeof(int)); 640 | 641 | for(i = 0; i < N+1; i++) 642 | { 643 | nx[i] = i*src->width/(N); 644 | ny[i] = i*src->height/(N); 645 | } 646 | 647 | for(l = 0; l < N; l++) 648 | { 649 | for(k = 0; k < N; k++) 650 | { 651 | float mean = 0.0f; 652 | 653 | float *ptr; 654 | switch(c) 655 | { 656 | case 0: 657 | ptr = src->c1; 658 | break; 659 | 660 | case 1: 661 | ptr = src->c2; 662 | break; 663 | 664 | case 2: 665 | ptr = src->c3; 666 | break; 667 | 668 | default: 669 | return; 670 | } 671 | 672 | for(j = ny[l]; j < ny[l+1]; j++) 673 | { 674 | for(i = nx[k]; i < nx[k+1]; i++) 675 | { 676 | mean += ptr[j*src->width+i]; 677 | } 678 | } 679 | 680 | float denom = (float)(ny[l+1]-ny[l])*(nx[k+1]-nx[k]); 681 | 682 | res[k*N+l] = mean / denom; 683 | assert(finite(res[k*N+l])); 684 | } 685 | } 686 | 687 | free(nx); 688 | free(ny); 689 | } 690 | 691 | /*--------------------------------------------------------------------------*/ 692 | 693 | /*static*/ float *gist_gabor(image_t *src, const int w, image_list_t *G) 694 | { 695 | fftw_lock(); 696 | 697 | int i, j, k; 698 | 699 | /* Get sizes */ 700 | int width = src->width; 701 | int height = src->height; 702 | int stride = src->stride; 703 | 704 | float *res = (float *) malloc(w*w*G->size*sizeof(float)); 705 | 706 | fftwf_complex *in1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 707 | fftwf_complex *in2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 708 | fftwf_complex *out1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 709 | fftwf_complex *out2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 710 | 711 | for(j = 0; j < height; j++) 712 | { 713 | for(i = 0; i < width; i++) 714 | { 715 | in1[j*width + i][0] = src->data[j*stride+i]; 716 | in1[j*width + i][1] = 0.0f; 717 | } 718 | } 719 | 720 | /* FFT */ 721 | fftwf_plan fft = fftwf_plan_dft_2d(width, height, in1, out1, FFTW_FORWARD, FFTW_ESTIMATE); 722 | fftwf_plan ifft = fftwf_plan_dft_2d(width, height, out2, in2, FFTW_BACKWARD, FFTW_ESTIMATE); 723 | 724 | fftw_unlock(); 725 | fftwf_execute(fft); 726 | 727 | for(k = 0; k < G->size; k++) 728 | { 729 | for(j = 0; j < height; j++) 730 | { 731 | for(i = 0; i < width; i++) 732 | { 733 | out2[j*width+i][0] = out1[j*width+i][0] * G->data[k]->data[j*stride+i]; 734 | out2[j*width+i][1] = out1[j*width+i][1] * G->data[k]->data[j*stride+i]; 735 | } 736 | } 737 | 738 | fftwf_execute(ifft); 739 | 740 | for(j = 0; j < height; j++) 741 | { 742 | for(i = 0; i < width; i++) { 743 | src->data[j*stride+i] = sqrt(in2[j*width+i][0]*in2[j*width+i][0]+in2[j*width+i][1]*in2[j*width+i][1])/(width*height); 744 | } 745 | } 746 | 747 | down_N(res+k*w*w, src, w); 748 | } 749 | 750 | fftw_lock(); 751 | 752 | fftwf_destroy_plan(fft); 753 | fftwf_destroy_plan(ifft); 754 | 755 | fftwf_free(in1); 756 | fftwf_free(in2); 757 | fftwf_free(out1); 758 | fftwf_free(out2); 759 | 760 | fftw_unlock(); 761 | 762 | return res; 763 | } 764 | 765 | /*--------------------------------------------------------------------------*/ 766 | 767 | static float *color_gist_gabor(color_image_t *src, const int w, image_list_t *G) 768 | { 769 | fftw_lock(); 770 | 771 | int i, j, k; 772 | 773 | /* Get sizes */ 774 | int width = src->width; 775 | int height = src->height; 776 | 777 | float *res = (float *) malloc(3*w*w*G->size*sizeof(float)); 778 | 779 | fftwf_complex *ina1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 780 | fftwf_complex *ina2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 781 | fftwf_complex *ina3 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 782 | fftwf_complex *inb1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 783 | fftwf_complex *inb2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 784 | fftwf_complex *inb3 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 785 | fftwf_complex *outa1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 786 | fftwf_complex *outa2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 787 | fftwf_complex *outa3 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 788 | fftwf_complex *outb1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 789 | fftwf_complex *outb2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 790 | fftwf_complex *outb3 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex)); 791 | 792 | for(j = 0; j < height; j++) 793 | { 794 | for(i = 0; i < width; i++) 795 | { 796 | ina1[j*width+i][0] = src->c1[j*width+i]; 797 | ina2[j*width+i][0] = src->c2[j*width+i]; 798 | ina3[j*width+i][0] = src->c3[j*width+i]; 799 | 800 | ina1[j*width+i][1] = 0.0f; 801 | ina2[j*width+i][1] = 0.0f; 802 | ina3[j*width+i][1] = 0.0f; 803 | } 804 | } 805 | 806 | /* FFT */ 807 | fftwf_plan fft1 = fftwf_plan_dft_2d(width, height, ina1, outa1, FFTW_FORWARD, FFTW_ESTIMATE); 808 | fftwf_plan fft2 = fftwf_plan_dft_2d(width, height, ina2, outa2, FFTW_FORWARD, FFTW_ESTIMATE); 809 | fftwf_plan fft3 = fftwf_plan_dft_2d(width, height, ina3, outa3, FFTW_FORWARD, FFTW_ESTIMATE); 810 | fftwf_plan ifft1 = fftwf_plan_dft_2d(width, height, outb1, inb1, FFTW_BACKWARD, FFTW_ESTIMATE); 811 | fftwf_plan ifft2 = fftwf_plan_dft_2d(width, height, outb2, inb2, FFTW_BACKWARD, FFTW_ESTIMATE); 812 | fftwf_plan ifft3 = fftwf_plan_dft_2d(width, height, outb3, inb3, FFTW_BACKWARD, FFTW_ESTIMATE); 813 | 814 | fftw_unlock(); 815 | fftwf_execute(fft1); 816 | fftwf_execute(fft2); 817 | fftwf_execute(fft3); 818 | 819 | for(k = 0; k < G->size; k++) 820 | { 821 | for(j = 0; j < height; j++) 822 | { 823 | for(i = 0; i < width; i++) 824 | { 825 | outb1[j*width+i][0] = outa1[j*width+i][0] * G->data[k]->data[j*G->data[k]->stride+i]; 826 | outb2[j*width+i][0] = outa2[j*width+i][0] * G->data[k]->data[j*G->data[k]->stride+i]; 827 | outb3[j*width+i][0] = outa3[j*width+i][0] * G->data[k]->data[j*G->data[k]->stride+i]; 828 | outb1[j*width+i][1] = outa1[j*width+i][1] * G->data[k]->data[j*G->data[k]->stride+i]; 829 | outb2[j*width+i][1] = outa2[j*width+i][1] * G->data[k]->data[j*G->data[k]->stride+i]; 830 | outb3[j*width+i][1] = outa3[j*width+i][1] * G->data[k]->data[j*G->data[k]->stride+i]; 831 | } 832 | } 833 | 834 | fftwf_execute(ifft1); 835 | fftwf_execute(ifft2); 836 | fftwf_execute(ifft3); 837 | 838 | for(j = 0; j < height; j++) 839 | { 840 | for(i = 0; i < width; i++) 841 | { 842 | src->c1[j*width+i] = sqrt(inb1[j*width+i][0]*inb1[j*width+i][0]+inb1[j*width+i][1]*inb1[j*width+i][1])/(width*height); 843 | src->c2[j*width+i] = sqrt(inb2[j*width+i][0]*inb2[j*width+i][0]+inb2[j*width+i][1]*inb2[j*width+i][1])/(width*height); 844 | src->c3[j*width+i] = sqrt(inb3[j*width+i][0]*inb3[j*width+i][0]+inb3[j*width+i][1]*inb3[j*width+i][1])/(width*height); 845 | } 846 | } 847 | 848 | color_down_N(res+0*G->size*w*w+k*w*w, src, w, 0); 849 | color_down_N(res+1*G->size*w*w+k*w*w, src, w, 1); 850 | color_down_N(res+2*G->size*w*w+k*w*w, src, w, 2); 851 | } 852 | 853 | fftw_lock(); 854 | 855 | fftwf_destroy_plan(fft1); 856 | fftwf_destroy_plan(fft2); 857 | fftwf_destroy_plan(fft3); 858 | fftwf_destroy_plan(ifft1); 859 | fftwf_destroy_plan(ifft2); 860 | fftwf_destroy_plan(ifft3); 861 | 862 | fftwf_free(ina1); 863 | fftwf_free(ina2); 864 | fftwf_free(ina3); 865 | fftwf_free(inb1); 866 | fftwf_free(inb2); 867 | fftwf_free(inb3); 868 | fftwf_free(outa1); 869 | fftwf_free(outa2); 870 | fftwf_free(outa3); 871 | fftwf_free(outb1); 872 | fftwf_free(outb2); 873 | fftwf_free(outb3); 874 | 875 | fftw_unlock(); 876 | 877 | return res; 878 | } 879 | 880 | /*--------------------------------------------------------------------------*/ 881 | 882 | float *bw_gist(image_t *src, int w, int a, int b, int c) 883 | { 884 | int orientationsPerScale[3]; 885 | 886 | orientationsPerScale[0] = a; 887 | orientationsPerScale[1] = b; 888 | orientationsPerScale[2] = c; 889 | 890 | return bw_gist_scaletab(src,w,3,orientationsPerScale); 891 | } 892 | 893 | float *bw_gist_scaletab(image_t *src, int w, int n_scale, const int *n_orientation) 894 | { 895 | int i; 896 | 897 | if(src->width < 8 || src->height < 8) 898 | { 899 | fprintf(stderr, "Error: bw_gist_scaletab() - Image not big enough !\n"); 900 | return NULL; 901 | } 902 | 903 | int numberBlocks = w; 904 | int tot_oris=0; 905 | for(i=0;iwidth, img->height); 909 | 910 | prefilt(img, 4); 911 | 912 | float *g = gist_gabor(img, numberBlocks, G); 913 | 914 | for(i = 0; i < tot_oris*w*w; i++) 915 | { 916 | if(!finite(g[i])) 917 | { 918 | fprintf(stderr, "Error: bw_gist_scaletab() - descriptor not valid (nan or inf)\n"); 919 | free(g); g=NULL; 920 | break; 921 | } 922 | } 923 | 924 | image_list_delete(G); 925 | image_delete(img); 926 | 927 | return g; 928 | } 929 | 930 | /*--------------------------------------------------------------------------*/ 931 | 932 | float *color_gist(color_image_t *src, int w, int a, int b, int c) { 933 | int orientationsPerScale[3]; 934 | 935 | orientationsPerScale[0] = a; 936 | orientationsPerScale[1] = b; 937 | orientationsPerScale[2] = c; 938 | 939 | return color_gist_scaletab(src,w,3,orientationsPerScale); 940 | 941 | } 942 | 943 | float *color_gist_scaletab(color_image_t *src, int w, int n_scale, const int *n_orientation) 944 | { 945 | int i; 946 | 947 | if(src->width < 8 || src->height < 8) 948 | { 949 | fprintf(stderr, "Error: color_gist_scaletab() - Image not big enough !\n"); 950 | return NULL; 951 | } 952 | 953 | int numberBlocks = w; 954 | int tot_oris=0; 955 | for(i=0;iwidth, img->height); 960 | 961 | color_prefilt(img, 4); 962 | 963 | float *g = color_gist_gabor(img, numberBlocks, G); 964 | 965 | for(i = 0; i < tot_oris*w*w*3; i++) 966 | { 967 | if(!finite(g[i])) 968 | { 969 | fprintf(stderr, "Error: color_gist_scaletab() - descriptor not valid (nan or inf)\n"); 970 | free(g); g=NULL; 971 | break; 972 | } 973 | } 974 | 975 | image_list_delete(G); 976 | color_image_delete(img); 977 | 978 | return g; 979 | } 980 | 981 | 982 | void free_desc(float *d){ 983 | free(d); 984 | } 985 | /*--------------------------------------------------------------------------*/ 986 | 987 | 988 | #ifndef STANDALONE_GIST 989 | 990 | /*--------------------------------------------------------------------------*/ 991 | 992 | local_desc_list_t *descriptor_bw_gist_cpu(image_t *src, int a, int b, int c, int w) 993 | { 994 | local_desc_list_t *desc_list = local_desc_list_new(); 995 | 996 | float *desc_raw = bw_gist(src, w, a, b, c); 997 | 998 | local_desc_t *desc = local_desc_new(); 999 | 1000 | desc->desc_size = (a+b+c)*w*w; 1001 | desc->desc = (float *) malloc(desc->desc_size*sizeof(float)); 1002 | memcpy(desc->desc, desc_raw, desc->desc_size*sizeof(float)); 1003 | local_desc_list_append(desc_list, desc); 1004 | 1005 | free(desc_raw); 1006 | 1007 | return desc_list; 1008 | } 1009 | 1010 | /*--------------------------------------------------------------------------*/ 1011 | 1012 | local_desc_list_t *descriptor_color_gist_cpu(color_image_t *src, int a, int b, int c, int w) 1013 | { 1014 | local_desc_list_t *desc_list = local_desc_list_new(); 1015 | 1016 | float *desc_raw = color_gist(src, w, a, b, c); 1017 | 1018 | local_desc_t *desc = local_desc_new(); 1019 | 1020 | desc->desc_size = 3*(a+b+c)*w*w; 1021 | desc->desc = (float *) malloc(desc->desc_size*sizeof(float)); 1022 | memcpy(desc->desc, desc_raw, desc->desc_size*sizeof(float)); 1023 | local_desc_list_append(desc_list, desc); 1024 | 1025 | free(desc_raw); 1026 | 1027 | return desc_list; 1028 | } 1029 | 1030 | #endif 1031 | 1032 | #endif 1033 | 1034 | /*--------------------------------------------------------------------------*/ 1035 | 1036 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------