libclamav/pe.c
e60810eb
 /*
8fc57a1f
  *  Copyright (C) 2004 - 2006 Tomasz Kojm <tkojm@clamav.net>
0bf8d34b
  *			      aCaB <acab@clamav.net>
3daea9cf
  *
e60810eb
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
  *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
  *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
30738099
  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  *  MA 02110-1301, USA.
e60810eb
  */
 
 #if HAVE_CONFIG_H
 #include "clamav-config.h"
 #endif
 
 #include <stdio.h>
 #include <string.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <sys/stat.h>
24481e0f
 #ifdef HAVE_UNISTD_H
e60810eb
 #include <unistd.h>
24481e0f
 #endif
e60810eb
 #include <time.h>
 
 #include "cltypes.h"
 #include "clamav.h"
 #include "others.h"
5ede41fa
 #include "pe.h"
 #include "petite.h"
3c5b57d4
 #include "fsg.h"
7c53d74b
 #include "spin.h"
dfad2d4d
 #include "upx.h"
 #include "yc.h"
dc4c26f6
 #include "wwunpack.h"
24481e0f
 #include "suecrypt.h"
25eaae24
 #include "unsp.h"
5ede41fa
 #include "scanners.h"
d6bc83e4
 #include "str.h"
1ec94c6b
 #include "execs.h"
344416f6
 #include "md5.h"
28992740
 #include "mew.h"
3b53a254
 #include "upack.h"
e60810eb
 
ac2888aa
 #ifndef	O_BINARY
 #define	O_BINARY	0
 #endif
 
4a30feab
 #define DCONF ctx->dconf->pe
 
e60810eb
 #define IMAGE_DOS_SIGNATURE	    0x5a4d	    /* MZ */
3d9cb459
 #define IMAGE_DOS_SIGNATURE_OLD	    0x4d5a          /* ZM */
e60810eb
 #define IMAGE_NT_SIGNATURE	    0x00004550
aa816b56
 #define PE32_SIGNATURE		    0x010b
 #define PE32P_SIGNATURE		    0x020b
e60810eb
 
f4520417
 #define optional_hdr64 pe_opt.opt64
 #define optional_hdr32 pe_opt.opt32
 
3d9cb459
 #define UPX_NRV2B "\x11\xdb\x11\xc9\x01\xdb\x75\x07\x8b\x1e\x83\xee\xfc\x11\xdb\x11\xc9\x11\xc9\x75\x20\x41\x01\xdb"
 #define UPX_NRV2D "\x83\xf0\xff\x74\x78\xd1\xf8\x89\xc5\xeb\x0b\x01\xdb\x75\x07\x8b\x1e\x83\xee\xfc\x11\xdb\x11\xc9"
 #define UPX_NRV2E "\xeb\x52\x31\xc9\x83\xe8\x03\x72\x11\xc1\xe0\x08\x8a\x06\x46\x83\xf0\xff\x74\x75\xd1\xf8\x89\xc5"
f2eb2372
 
70ea6092
 #define EC32(x) le32_to_host(x) /* Convert little endian to host */
 #define EC16(x) le16_to_host(x)
25eaae24
 /* lower and upper bondary alignment (size vs offset) */
 #define PEALIGN(o,a) (((a))?(((o)/(a))*(a)):(o))
 #define PESALIGN(o,a) (((a))?(((o)/(a)+((o)%(a)!=0))*(a)):(o))
c2484690
 
 extern short cli_leavetemps_flag;
 
8fc57a1f
 struct offset_list {
     uint32_t offset;
     struct offset_list *next;
 };
 
e6bea1aa
 static uint32_t cli_rawaddr(uint32_t rva, struct cli_exe_section *shp, uint16_t nos, unsigned int *err,	size_t fsize)
e3886d61
 {
 	int i, found = 0;
e6bea1aa
 	uint32_t ret;
e3886d61
 
e6bea1aa
     if (rva<0x1000) { /* Out of section EP - mapped to imagebase+rva */
         if (rva >= fsize) {
 	    *err=1;
 	    return 0;
 	}
         *err=0;
 	return rva;
     }
e3886d61
 
e6bea1aa
     for(i = nos-1; i >= 0; i--) {
         if(shp[i].rsz && shp[i].rva <= rva && shp[i].rsz > rva - shp[i].rva) {
e3886d61
 	    found = 1;
 	    break;
 	}
     }
 
     if(!found) {
a8b53539
 	*err = 1;
 	return 0;
e3886d61
     }
 
e6bea1aa
     ret = rva - shp[i].rva + shp[i].raw;
a8b53539
     *err = 0;
e6bea1aa
     return ret;
e3886d61
 }
 
f3e58a58
 static void xckriz(char **opcode, int *len, int checksize, int reg) {
e6bea1aa
     while(*len>6) {
         if (**opcode>='\x48' && **opcode<='\x4f' && **opcode!='\x4c') {
 	    if ((char)(**opcode-reg)=='\x48') break;
 	    (*len)--;
 	    (*opcode)++;
 	    continue;
 	}
 	if (**opcode>='\xb8' && **opcode<='\xbf' && **opcode!='\xbc') {
 	    if (checksize && cli_readint32(*opcode+1)==0x0fd2) break;
 	    (*len)-=5;
 	    (*opcode)+=5;
 	    continue;
 	}
 	if (**opcode=='\x81') {
 	    (*len)-=6;
 	    (*opcode)+=6;
 	    continue;
f3e58a58
 	}
e6bea1aa
 	break;
     }
f3e58a58
 }
 
 
a8b53539
 /*
e3886d61
 static int cli_ddump(int desc, int offset, int size, const char *file)
cea6b75d
 {
 	int pos, ndesc, bread, sum = 0;
 	char buff[FILEBUFF];
 
 
     cli_dbgmsg("in ddump()\n");
 
     if((pos = lseek(desc, 0, SEEK_CUR)) == -1) {
 	cli_dbgmsg("Invalid descriptor\n");
c2484690
 	return -1;
cea6b75d
     }
 
     if(lseek(desc, offset, SEEK_SET) == -1) {
 	cli_dbgmsg("lseek() failed\n");
 	lseek(desc, pos, SEEK_SET);
c2484690
 	return -1;
cea6b75d
     }
 
ac2888aa
     if((ndesc = open(file, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) {
cea6b75d
 	cli_dbgmsg("Can't create file %s\n", file);
 	lseek(desc, pos, SEEK_SET);
c2484690
 	return -1;
cea6b75d
     }
 
d7903e09
     while((bread = cli_readn(desc, buff, FILEBUFF)) > 0) {
cea6b75d
 	if(sum + bread >= size) {
 	    if(write(ndesc, buff, size - sum) == -1) {
 		cli_dbgmsg("Can't write to file\n");
 		lseek(desc, pos, SEEK_SET);
 		close(ndesc);
 		unlink(file);
c2484690
 		return -1;
cea6b75d
 	    }
 	    break;
 	} else {
 	    if(write(ndesc, buff, bread) == -1) {
 		cli_dbgmsg("Can't write to file\n");
 		lseek(desc, pos, SEEK_SET);
 		close(ndesc);
 		unlink(file);
c2484690
 		return -1;
cea6b75d
 	    }
 	}
 	sum += bread;
     }
 
     close(ndesc);
     lseek(desc, pos, SEEK_SET);
     return 0;
 }
a8b53539
 */
cea6b75d
 
e6bea1aa
 static unsigned int cli_md5sect(int fd, uint32_t offset, uint32_t size, unsigned char *digest)
344416f6
 {
 	size_t bread, sum = 0;
 	off_t pos;
 	char buff[FILEBUFF];
 	MD5_CTX md5ctx;
 
 
     if((pos = lseek(fd, 0, SEEK_CUR)) == -1) {
 	cli_dbgmsg("cli_md5sect: Invalid descriptor %d\n", fd);
e6bea1aa
 	return 0;
344416f6
     }
 
     if(lseek(fd, offset, SEEK_SET) == -1) {
 	cli_dbgmsg("cli_md5sect: lseek() failed\n");
 	lseek(fd, pos, SEEK_SET);
e6bea1aa
 	return 0;
344416f6
     }
 
     MD5_Init(&md5ctx);
 
     while((bread = cli_readn(fd, buff, FILEBUFF)) > 0) {
 	if(sum + bread >= size) {
 	    MD5_Update(&md5ctx, buff, size - sum);
 	    break;
 	} else {
 	    MD5_Update(&md5ctx, buff, bread);
 	    sum += bread;
 	}
     }
 
     MD5_Final(digest, &md5ctx);
     lseek(fd, pos, SEEK_SET);
e6bea1aa
     return 1;
344416f6
 }
 
605b8cf0
 int cli_scanpe(int desc, cli_ctx *ctx)
e60810eb
 {
 	uint16_t e_magic; /* DOS signature ("MZ") */
c2484690
 	uint16_t nsections;
e60810eb
 	uint32_t e_lfanew; /* address of new exe header */
e6bea1aa
 	uint32_t ep, vep; /* entry point (raw, virtual) */
8fc57a1f
 	uint8_t polipos = 0;
f91f55e0
 	time_t timestamp;
e60810eb
 	struct pe_image_file_hdr file_hdr;
e6bea1aa
 	union {
 	    struct pe_image_optional_hdr64 opt64;
 	    struct pe_image_optional_hdr32 opt32;
 	} pe_opt;
e3886d61
 	struct pe_image_section_hdr *section_hdr;
344416f6
 	struct cli_md5_node *md5_sect;
e60810eb
 	struct stat sb;
289ed7c4
 	char sname[9], buff[4096], *tempfile;
e6bea1aa
 	unsigned char *ubuff;
8fc57a1f
 	ssize_t bytes;
e6bea1aa
 	unsigned int i, found, upx_success = 0, min = 0, max = 0, err;
aa816b56
 	unsigned int ssize = 0, dsize = 0, dll = 0, pe_plus = 0;
a067388f
 	int (*upxfn)(char *, uint32_t, char *, uint32_t *, uint32_t, uint32_t, uint32_t) = NULL;
0d32af73
 	char *src = NULL, *dest = NULL;
3b53a254
 	int ndesc, ret = CL_CLEAN, upack = 0;
764dab55
 	size_t fsize;
e6bea1aa
 	uint32_t valign, falign;
 	struct cli_exe_section *exe_sections;
e60810eb
 
 
d7903e09
     if(cli_readn(desc, &e_magic, sizeof(e_magic)) != sizeof(e_magic)) {
cea6b75d
 	cli_dbgmsg("Can't read DOS signature\n");
1f576bce
 	return CL_CLEAN;
e60810eb
     }
 
3d9cb459
     if(EC16(e_magic) != IMAGE_DOS_SIGNATURE && EC16(e_magic) != IMAGE_DOS_SIGNATURE_OLD) {
e60810eb
 	cli_dbgmsg("Invalid DOS signature\n");
c2484690
 	return CL_CLEAN;
e60810eb
     }
 
     lseek(desc, 58, SEEK_CUR); /* skip to the end of the DOS header */
 
d7903e09
     if(cli_readn(desc, &e_lfanew, sizeof(e_lfanew)) != sizeof(e_lfanew)) {
cea6b75d
 	cli_dbgmsg("Can't read new header address\n");
1f576bce
 	/* truncated header? */
 	if(DETECT_BROKEN) {
605b8cf0
 	    if(ctx->virname)
 		*ctx->virname = "Broken.Executable";
1f576bce
 	    return CL_VIRUS;
 	}
 	return CL_CLEAN;
e60810eb
     }
 
c2484690
     e_lfanew = EC32(e_lfanew);
e60810eb
     cli_dbgmsg("e_lfanew == %d\n", e_lfanew);
     if(!e_lfanew) {
 	cli_dbgmsg("Not a PE file\n");
c2484690
 	return CL_CLEAN;
e60810eb
     }
0b2b8b9b
 
     if(lseek(desc, e_lfanew, SEEK_SET) < 0) {
 	/* probably not a PE file */
 	cli_dbgmsg("Can't lseek to e_lfanew\n");
 	return CL_CLEAN;
     }
e60810eb
 
d7903e09
     if(cli_readn(desc, &file_hdr, sizeof(struct pe_image_file_hdr)) != sizeof(struct pe_image_file_hdr)) {
0b2b8b9b
 	/* bad information in e_lfanew - probably not a PE file */
e60810eb
 	cli_dbgmsg("Can't read file header\n");
0b2b8b9b
 	return CL_CLEAN;
e60810eb
     }
 
c2484690
     if(EC32(file_hdr.Magic) != IMAGE_NT_SIGNATURE) {
cea6b75d
 	cli_dbgmsg("Invalid PE signature (probably NE file)\n");
c2484690
 	return CL_CLEAN;
e60810eb
     }
 
b76bf2c4
     if(EC16(file_hdr.Characteristics) & 0x2000) {
 	cli_dbgmsg("File type: DLL\n");
 	dll = 1;
     } else if(EC16(file_hdr.Characteristics) & 0x01) {
 	cli_dbgmsg("File type: Executable\n");
     }
 
c2484690
     switch(EC16(file_hdr.Machine)) {
95cf6990
 	case 0x0:
 	    cli_dbgmsg("Machine type: Unknown\n");
e60810eb
 	case 0x14c:
cea6b75d
 	    cli_dbgmsg("Machine type: 80386\n");
e60810eb
 	    break;
95cf6990
 	case 0x14d:
cea6b75d
 	    cli_dbgmsg("Machine type: 80486\n");
e60810eb
 	    break;
95cf6990
 	case 0x14e:
cea6b75d
 	    cli_dbgmsg("Machine type: 80586\n");
e60810eb
 	    break;
95cf6990
 	case 0x160:
 	    cli_dbgmsg("Machine type: R30000 (big-endian)\n");
 	    break;
e60810eb
 	case 0x162:
cea6b75d
 	    cli_dbgmsg("Machine type: R3000\n");
e60810eb
 	    break;
 	case 0x166:
cea6b75d
 	    cli_dbgmsg("Machine type: R4000\n");
e60810eb
 	    break;
 	case 0x168:
cea6b75d
 	    cli_dbgmsg("Machine type: R10000\n");
e60810eb
 	    break;
 	case 0x184:
cea6b75d
 	    cli_dbgmsg("Machine type: DEC Alpha AXP\n");
e60810eb
 	    break;
da034cc1
 	case 0x284:
 	    cli_dbgmsg("Machine type: DEC Alpha AXP 64bit\n");
 	    break;
e60810eb
 	case 0x1f0:
cea6b75d
 	    cli_dbgmsg("Machine type: PowerPC\n");
e60810eb
 	    break;
da034cc1
 	case 0x200:
 	    cli_dbgmsg("Machine type: IA64\n");
 	    break;
 	case 0x268:
 	    cli_dbgmsg("Machine type: M68k\n");
 	    break;
 	case 0x266:
 	    cli_dbgmsg("Machine type: MIPS16\n");
 	    break;
 	case 0x366:
 	    cli_dbgmsg("Machine type: MIPS+FPU\n");
 	    break;
 	case 0x466:
 	    cli_dbgmsg("Machine type: MIPS16+FPU\n");
 	    break;
 	case 0x1a2:
 	    cli_dbgmsg("Machine type: Hitachi SH3\n");
 	    break;
95cf6990
 	case 0x1a3:
 	    cli_dbgmsg("Machine type: Hitachi SH3-DSP\n");
 	    break;
 	case 0x1a4:
 	    cli_dbgmsg("Machine type: Hitachi SH3-E\n");
 	    break;
da034cc1
 	case 0x1a6:
 	    cli_dbgmsg("Machine type: Hitachi SH4\n");
 	    break;
95cf6990
 	case 0x1a8:
 	    cli_dbgmsg("Machine type: Hitachi SH5\n");
 	    break;
da034cc1
 	case 0x1c0:
 	    cli_dbgmsg("Machine type: ARM\n");
 	    break;
 	case 0x1c2:
 	    cli_dbgmsg("Machine type: THUMB\n");
 	    break;
95cf6990
 	case 0x1d3:
 	    cli_dbgmsg("Machine type: AM33\n");
 	    break;
 	case 0x520:
 	    cli_dbgmsg("Machine type: Infineon TriCore\n");
 	    break;
 	case 0xcef:
 	    cli_dbgmsg("Machine type: CEF\n");
 	    break;
 	case 0xebc:
 	    cli_dbgmsg("Machine type: EFI Byte Code\n");
 	    break;
 	case 0x9041:
 	    cli_dbgmsg("Machine type: M32R\n");
 	    break;
 	case 0xc0ee:
 	    cli_dbgmsg("Machine type: CEE\n");
 	    break;
 	case 0x8664:
 	    cli_dbgmsg("Machine type: AMD64\n");
 	    break;
e60810eb
 	default:
da034cc1
 	    cli_warnmsg("Unknown machine type in PE header (0x%x)\n", EC16(file_hdr.Machine));
e60810eb
     }
 
c2484690
     nsections = EC16(file_hdr.NumberOfSections);
e6bea1aa
     if(nsections < 1 || nsections > 96) {
f2284195
 	if(DETECT_BROKEN) {
605b8cf0
 	    if(ctx->virname)
 		*ctx->virname = "Broken.Executable";
f2284195
 	    return CL_VIRUS;
 	}
7135a8ff
 	if(nsections)
 	    cli_warnmsg("PE file contains %d sections\n", nsections);
 	else
 	    cli_warnmsg("PE file contains no sections\n");
f2284195
 	return CL_CLEAN;
     }
c2484690
     cli_dbgmsg("NumberOfSections: %d\n", nsections);
 
f91f55e0
     timestamp = (time_t) EC32(file_hdr.TimeDateStamp);
     cli_dbgmsg("TimeDateStamp: %s", ctime(&timestamp));
e60810eb
 
c211111e
     cli_dbgmsg("SizeOfOptionalHeader: %x\n", EC16(file_hdr.SizeOfOptionalHeader));
e60810eb
 
e6bea1aa
     if (EC16(file_hdr.SizeOfOptionalHeader) < sizeof(struct pe_image_optional_hdr32)) {
         cli_dbgmsg("SizeOfOptionalHeader too small\n");
 	if(DETECT_BROKEN) {
 	    if(ctx->virname)
 	        *ctx->virname = "Broken.Executable";
 	    return CL_VIRUS;
f8355d13
 	}
e6bea1aa
 	return CL_CLEAN;
e60810eb
     }
 
e6bea1aa
     if(cli_readn(desc, &optional_hdr32, sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr32)) {
         cli_dbgmsg("Can't read optional file header\n");
 	if(DETECT_BROKEN) {
 	    if(ctx->virname)
 	        *ctx->virname = "Broken.Executable";
 	    return CL_VIRUS;
 	}
 	return CL_CLEAN;
     }
aa816b56
 
e6bea1aa
     /* This will be a chicken and egg problem until we drop 9x */
     if(EC32(optional_hdr64.Magic)==PE32P_SIGNATURE) {
         if(EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr64)) {
 	    /* FIXME: need to play around a bit more with xp64 */
 	    cli_dbgmsg("Incorrect SizeOfOptionalHeader for PE32+\n");
aa816b56
 	    if(DETECT_BROKEN) {
e6bea1aa
 	        if(ctx->virname)
605b8cf0
 		    *ctx->virname = "Broken.Executable";
aa816b56
 		return CL_VIRUS;
 	    }
 	    return CL_CLEAN;
f8355d13
 	}
e6bea1aa
 	pe_plus = 1;
     } else {
         /*
 	    either it's got a PE32_SIGNATURE or
 	    we enable win9x compatibility in that we don't honor magic (see bb#119)
 	    either way it's a 32bit thingy
 	*/
         if(EC16(optional_hdr32.Magic) != PE32_SIGNATURE) {
aa816b56
 	    cli_warnmsg("Incorrect magic number in optional header\n");
 	    if(DETECT_BROKEN) {
e6bea1aa
 	        if(ctx->virname)
605b8cf0
 		    *ctx->virname = "Broken.Executable";
aa816b56
 		return CL_VIRUS;
 	    }
58a3b92a
 	    cli_dbgmsg("9x compatibility mode\n");
aa816b56
 	}
e6bea1aa
     }
 
     if(!pe_plus) { /* PE */
 	if (EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr32)) {
 	    /* Seek to the end of the long header */
 	    lseek(desc, (EC16(file_hdr.SizeOfOptionalHeader)-sizeof(struct pe_image_optional_hdr32)), SEEK_CUR);
 	}
 
36b3f1cc
 	if(DCONF & PE_CONF_UPACK)
 	    upack = (EC16(file_hdr.SizeOfOptionalHeader)==0x148);
 
e6bea1aa
 	vep = EC32(optional_hdr32.AddressOfEntryPoint);
aa816b56
 	cli_dbgmsg("File format: PE\n");
 
 	cli_dbgmsg("MajorLinkerVersion: %d\n", optional_hdr32.MajorLinkerVersion);
 	cli_dbgmsg("MinorLinkerVersion: %d\n", optional_hdr32.MinorLinkerVersion);
e6bea1aa
 	cli_dbgmsg("SizeOfCode: 0x%x\n", EC32(optional_hdr32.SizeOfCode));
 	cli_dbgmsg("SizeOfInitializedData: 0x%x\n", EC32(optional_hdr32.SizeOfInitializedData));
 	cli_dbgmsg("SizeOfUninitializedData: 0x%x\n", EC32(optional_hdr32.SizeOfUninitializedData));
 	cli_dbgmsg("AddressOfEntryPoint: 0x%x\n", vep);
aa816b56
 	cli_dbgmsg("BaseOfCode: 0x%x\n", EC32(optional_hdr32.BaseOfCode));
e6bea1aa
 	cli_dbgmsg("SectionAlignment: 0x%x\n", EC32(optional_hdr32.SectionAlignment));
 	cli_dbgmsg("FileAlignment: 0x%x\n", EC32(optional_hdr32.FileAlignment));
aa816b56
 	cli_dbgmsg("MajorSubsystemVersion: %d\n", EC16(optional_hdr32.MajorSubsystemVersion));
 	cli_dbgmsg("MinorSubsystemVersion: %d\n", EC16(optional_hdr32.MinorSubsystemVersion));
e6bea1aa
 	cli_dbgmsg("SizeOfImage: 0x%x\n", EC32(optional_hdr32.SizeOfImage));
 	cli_dbgmsg("SizeOfHeaders: 0x%x\n", EC32(optional_hdr32.SizeOfHeaders));
aa816b56
 	cli_dbgmsg("NumberOfRvaAndSizes: %d\n", EC32(optional_hdr32.NumberOfRvaAndSizes));
 
     } else { /* PE+ */
e6bea1aa
         /* read the remaining part of the header */
         if(cli_readn(desc, &optional_hdr32 + 1, sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) {
 	    cli_dbgmsg("Can't read optional file header\n");
aa816b56
 	    if(DETECT_BROKEN) {
e6bea1aa
 	        if(ctx->virname)
605b8cf0
 		    *ctx->virname = "Broken.Executable";
aa816b56
 		return CL_VIRUS;
 	    }
 	    return CL_CLEAN;
 	}
 
e6bea1aa
 	vep = EC32(optional_hdr64.AddressOfEntryPoint);
aa816b56
 	cli_dbgmsg("File format: PE32+\n");
 
 	cli_dbgmsg("MajorLinkerVersion: %d\n", optional_hdr64.MajorLinkerVersion);
 	cli_dbgmsg("MinorLinkerVersion: %d\n", optional_hdr64.MinorLinkerVersion);
e6bea1aa
 	cli_dbgmsg("SizeOfCode: 0x%x\n", EC32(optional_hdr64.SizeOfCode));
 	cli_dbgmsg("SizeOfInitializedData: 0x%x\n", EC32(optional_hdr64.SizeOfInitializedData));
 	cli_dbgmsg("SizeOfUninitializedData: 0x%x\n", EC32(optional_hdr64.SizeOfUninitializedData));
 	cli_dbgmsg("AddressOfEntryPoint: 0x%x\n", vep);
aa816b56
 	cli_dbgmsg("BaseOfCode: 0x%x\n", EC32(optional_hdr64.BaseOfCode));
e6bea1aa
 	cli_dbgmsg("SectionAlignment: 0x%x\n", EC32(optional_hdr64.SectionAlignment));
 	cli_dbgmsg("FileAlignment: 0x%x\n", EC32(optional_hdr64.FileAlignment));
aa816b56
 	cli_dbgmsg("MajorSubsystemVersion: %d\n", EC16(optional_hdr64.MajorSubsystemVersion));
 	cli_dbgmsg("MinorSubsystemVersion: %d\n", EC16(optional_hdr64.MinorSubsystemVersion));
e6bea1aa
 	cli_dbgmsg("SizeOfImage: 0x%x\n", EC32(optional_hdr64.SizeOfImage));
 	cli_dbgmsg("SizeOfHeaders: 0x%x\n", EC32(optional_hdr64.SizeOfHeaders));
aa816b56
 	cli_dbgmsg("NumberOfRvaAndSizes: %d\n", EC32(optional_hdr64.NumberOfRvaAndSizes));
e60810eb
     }
 
513f14df
     if (DETECT_BROKEN && (!(pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment)) || (pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment))%0x1000)) {
e6bea1aa
         cli_dbgmsg("Bad virtual alignemnt\n");
         if(ctx->virname)
 	    *ctx->virname = "Broken.Executable";
 	return CL_VIRUS;
513f14df
     }
 
     if (DETECT_BROKEN && (!(pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment)) || (pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment))%0x200)) {
e6bea1aa
         cli_dbgmsg("Bad file alignemnt\n");
 	if(ctx->virname)
 	    *ctx->virname = "Broken.Executable";
 	return CL_VIRUS;
513f14df
     }
 
aa816b56
     switch(pe_plus ? EC16(optional_hdr64.Subsystem) : EC16(optional_hdr32.Subsystem)) {
04268c03
 	case 0:
 	    cli_dbgmsg("Subsystem: Unknown\n");
 	    break;
e60810eb
 	case 1:
cea6b75d
 	    cli_dbgmsg("Subsystem: Native (a driver ?)\n");
e60810eb
 	    break;
 	case 2:
cea6b75d
 	    cli_dbgmsg("Subsystem: Win32 GUI\n");
e60810eb
 	    break;
 	case 3:
cea6b75d
 	    cli_dbgmsg("Subsystem: Win32 console\n");
e60810eb
 	    break;
 	case 5:
cea6b75d
 	    cli_dbgmsg("Subsystem: OS/2 console\n");
e60810eb
 	    break;
 	case 7:
cea6b75d
 	    cli_dbgmsg("Subsystem: POSIX console\n");
e60810eb
 	    break;
da034cc1
 	case 8:
 	    cli_dbgmsg("Subsystem: Native Win9x driver\n");
 	    break;
 	case 9:
 	    cli_dbgmsg("Subsystem: WinCE GUI\n");
 	    break;
 	case 10:
 	    cli_dbgmsg("Subsystem: EFI application\n");
 	    break;
 	case 11:
 	    cli_dbgmsg("Subsystem: EFI driver\n");
 	    break;
 	case 12:
 	    cli_dbgmsg("Subsystem: EFI runtime driver\n");
 	    break;
e60810eb
 	default:
aa816b56
 	    cli_warnmsg("Unknown subsystem in PE header (0x%x)\n", pe_plus ? EC16(optional_hdr64.Subsystem) : EC16(optional_hdr32.Subsystem));
e60810eb
     }
 
5ede41fa
     cli_dbgmsg("------------------------------------\n");
e60810eb
 
e263999b
     if(fstat(desc, &sb) == -1) {
 	cli_dbgmsg("fstat failed\n");
 	return CL_EIO;
     }
 
764dab55
     fsize = sb.st_size;
 
c2484690
     section_hdr = (struct pe_image_section_hdr *) cli_calloc(nsections, sizeof(struct pe_image_section_hdr));
e3886d61
 
     if(!section_hdr) {
 	cli_dbgmsg("Can't allocate memory for section headers\n");
 	return CL_EMEM;
     }
 
e6bea1aa
     exe_sections = (struct cli_exe_section *) cli_calloc(nsections, sizeof(struct cli_exe_section));
     
     if(!exe_sections) {
 	cli_dbgmsg("Can't allocate memory for section headers\n");
 	free(section_hdr);
 	return CL_EMEM;
     }
e60810eb
 
e6bea1aa
     valign = (pe_plus)?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment);
     falign = (pe_plus)?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment);
 
     if(cli_readn(desc, section_hdr, sizeof(struct pe_image_section_hdr)*nsections) != (int)(nsections*sizeof(struct pe_image_section_hdr))) {
         cli_dbgmsg("Can't read section header\n");
 	cli_dbgmsg("Possibly broken PE file\n");
 	free(section_hdr);
 	free(exe_sections);
 	if(DETECT_BROKEN) {
 	    if(ctx->virname)
 		*ctx->virname = "Broken.Executable";
 	    return CL_VIRUS;
 	}
 	return CL_CLEAN;
     }
     
     for(i = 0; falign!=0x200 && i<nsections; i++) {
 	/* file alignment fallback mode - blah */
58a3b92a
 	if (falign && section_hdr[i].SizeOfRawData && EC32(section_hdr[i].PointerToRawData)%falign && !(EC32(section_hdr[i].PointerToRawData)%0x200)) {
e6bea1aa
 	    cli_dbgmsg("Found misaligned section, using 0x200\n");
 	    falign = 0x200;
e60810eb
 	}
e6bea1aa
     }
e60810eb
 
e6bea1aa
     for(i = 0; i < nsections; i++) {
7f7736bb
 	strncpy(sname, (char *) section_hdr[i].Name, 8);
e60810eb
 	sname[8] = 0;
e6bea1aa
 	exe_sections[i].rva = PEALIGN(EC32(section_hdr[i].VirtualAddress), valign);
 	exe_sections[i].vsz = PESALIGN(EC32(section_hdr[i].VirtualSize), valign);
69ad9664
 	exe_sections[i].uvsz = EC32(section_hdr[i].VirtualSize);
e6bea1aa
 	exe_sections[i].raw = PEALIGN(EC32(section_hdr[i].PointerToRawData), falign);
 	exe_sections[i].rsz = PESALIGN(EC32(section_hdr[i].SizeOfRawData), falign);
cc4d42d9
 	exe_sections[i].ursz = EC32(section_hdr[i].SizeOfRawData);
e6bea1aa
 	if (exe_sections[i].rsz && fsize>exe_sections[i].raw && !CLI_ISCONTAINED(0, (uint32_t) fsize, exe_sections[i].raw, exe_sections[i].rsz))
 	    exe_sections[i].rsz = fsize - exe_sections[i].raw;
 	
8ce7d5f5
 	cli_dbgmsg("Section %d\n", i);
e60810eb
 	cli_dbgmsg("Section name: %s\n", sname);
e6bea1aa
 	cli_dbgmsg("Section data (from headers - in memory)\n");
 	cli_dbgmsg("VirtualSize: 0x%x 0x%x\n", EC32(section_hdr[i].VirtualSize), exe_sections[i].vsz);
 	cli_dbgmsg("VirtualAddress: 0x%x 0x%x\n", EC32(section_hdr[i].VirtualAddress), exe_sections[i].rva);
 	cli_dbgmsg("SizeOfRawData: 0x%x 0x%x\n", EC32(section_hdr[i].SizeOfRawData), exe_sections[i].rsz);
 	cli_dbgmsg("PointerToRawData: 0x%x 0x%x\n", EC32(section_hdr[i].PointerToRawData), exe_sections[i].raw);
e60810eb
 
c2484690
 	if(EC32(section_hdr[i].Characteristics) & 0x20) {
cea6b75d
 	    cli_dbgmsg("Section contains executable code\n");
 
e6bea1aa
 	    if(exe_sections[i].vsz < exe_sections[i].rsz) {
cea6b75d
 		cli_dbgmsg("Section contains free space\n");
 		/*
 		cli_dbgmsg("Dumping %d bytes\n", section_hdr.SizeOfRawData - section_hdr.VirtualSize);
f91f55e0
 		ddump(desc, section_hdr.PointerToRawData + section_hdr.VirtualSize, section_hdr.SizeOfRawData - section_hdr.VirtualSize, cli_gentemp(NULL));
cea6b75d
 		*/
 
 	    }
 	}
e60810eb
 
c2484690
 	if(EC32(section_hdr[i].Characteristics) & 0x20000000)
cea6b75d
 	    cli_dbgmsg("Section's memory is executable\n");
b76bf2c4
 
 	if(EC32(section_hdr[i].Characteristics) & 0x80000000)
 	    cli_dbgmsg("Section's memory is writeable\n");
 
5ede41fa
 	cli_dbgmsg("------------------------------------\n");
cea6b75d
 
e6bea1aa
 	if (DETECT_BROKEN && EC32(section_hdr[i].VirtualAddress)%valign) { /* Bad virtual alignment */
1c90f843
 	    cli_dbgmsg("VirtualAddress is misaligned\n");
 	    if(ctx->virname)
 	        *ctx->virname = "Broken.Executable";
 	    free(section_hdr);
e6bea1aa
 	    free(exe_sections);
1c90f843
 	    return CL_VIRUS;
 	}
344416f6
 
e6bea1aa
 	if (exe_sections[i].rsz) { /* Don't bother with virtual only sections */
 	    unsigned char md5_dig[16];
 	    if (exe_sections[i].raw >= fsize) { /* really broken */
 	        cli_dbgmsg("Broken PE file - Section %d starts beyond the end of file (Offset@ %d, Total filesize %d)\n", i, exe_sections[i].raw, fsize);
 		free(section_hdr);
 		free(exe_sections);
 		if(DETECT_BROKEN) {
 		    if(ctx->virname)
 		        *ctx->virname = "Broken.Executable";
 		    return CL_VIRUS;
 		}
 		return CL_CLEAN; /* no ninjas to see here! move along! */
 	    }
 	    
 	    /* check MD5 section sigs */
4a30feab
 	    if(DCONF & PE_CONF_MD5SECT)
 		md5_sect = ctx->engine->md5_sect;
 	    else
 		md5_sect = NULL;
 
e6bea1aa
 	    while(md5_sect && md5_sect->size < exe_sections[i].rsz)
 	        md5_sect = md5_sect->next;
 
 	    if(md5_sect && md5_sect->size == exe_sections[i].rsz) {
 	        if(!cli_md5sect(desc, exe_sections[i].raw, exe_sections[i].rsz, md5_dig)) {
 		    cli_errmsg("PE: Can't calculate MD5 for section %d\n", i);
 		} else {
 		    while(md5_sect && md5_sect->size == exe_sections[i].rsz) {
 		        if(!memcmp(md5_dig, md5_sect->md5, 16)) {
 			    if(ctx->virname)
 			        *ctx->virname = md5_sect->virname;
 			    free(section_hdr);
 			    free(exe_sections);
 			    return CL_VIRUS;
344416f6
 			}
e6bea1aa
 			md5_sect = md5_sect->next;
344416f6
 		    }
 		}
 	    }
f8355d13
 	}
 
5ede41fa
 	if(!i) {
e6bea1aa
 	    if (DETECT_BROKEN && EC32(section_hdr[i].VirtualAddress)!=valign) { /* Bad first section RVA */
1c90f843
 	        cli_dbgmsg("First section is in the wrong place\n");
 	        if(ctx->virname)
f4520417
 		    *ctx->virname = "Broken.Executable";
1c90f843
 		free(section_hdr);
e6bea1aa
 		free(exe_sections);
1c90f843
 		return CL_VIRUS;
 	    }
e6bea1aa
 	    min = exe_sections[i].rva;
 	    max = exe_sections[i].rva + exe_sections[i].rsz;
5ede41fa
 	} else {
e6bea1aa
 	    if (DETECT_BROKEN && EC32(section_hdr[i].VirtualAddress)-EC32(section_hdr[i-1].VirtualAddress)!= exe_sections[i-1].vsz) { /* No holes, no overlapping, no virtual disorder */
1c90f843
 	        cli_dbgmsg("Virtually misplaced section (wrong order, overlapping, non contiguous)\n");
 	        if(ctx->virname)
f4520417
 		    *ctx->virname = "Broken.Executable";
1c90f843
 		free(section_hdr);
e6bea1aa
 		free(exe_sections);
1c90f843
 		return CL_VIRUS;
 	    }
e6bea1aa
 	    if(exe_sections[i].rva < min)
 	        min = exe_sections[i].rva;
cea6b75d
 
e6bea1aa
 	    if(exe_sections[i].rva + exe_sections[i].rsz > max)
 	        max = exe_sections[i].rva + exe_sections[i].rsz;
cea6b75d
 	}
e60810eb
 
4a30feab
 	if(SCAN_ALGO && (DCONF & PE_CONF_POLIPOS) && !strlen(sname)) {
e6bea1aa
 	    if(exe_sections[i].vsz > 40000 && exe_sections[i].vsz < 70000) {
8fc57a1f
 		if(EC32(section_hdr[i].Characteristics) == 0xe0000060) {
 		    polipos = i;
 		}
 	    }
 	}
 
e60810eb
     }
 
e6bea1aa
     if(!(ep = cli_rawaddr(vep, exe_sections, nsections, &err, fsize)) && err) {
 	cli_dbgmsg("EntryPoint out of file\n");
e3886d61
 	free(section_hdr);
e6bea1aa
 	free(exe_sections);
f8355d13
 	if(DETECT_BROKEN) {
605b8cf0
 	    if(ctx->virname)
 		*ctx->virname = "Broken.Executable";
f8355d13
 	    return CL_VIRUS;
 	}
f2eb2372
 	return CL_CLEAN;
e60810eb
     }
 
f2eb2372
     cli_dbgmsg("EntryPoint offset: 0x%x (%d)\n", ep, ep);
 
f164272a
     if(pe_plus) { /* Do not continue for PE32+ files */
 	free(section_hdr);
e6bea1aa
 	free(exe_sections);
f164272a
 	return CL_CLEAN;
     }
 
d6bc83e4
     /* Attempt to detect some popular polymorphic viruses */
 
     /* W32.Parite.B */
4a30feab
     if(SCAN_ALGO && (DCONF & PE_CONF_PARITE) && !dll && ep == exe_sections[nsections - 1].raw) {
3d4cb247
 	lseek(desc, ep, SEEK_SET);
d7903e09
 	if(cli_readn(desc, buff, 4096) == 4096) {
f58ad3be
 		const char *pt = cli_memstr(buff, 4040, "\x47\x65\x74\x50\x72\x6f\x63\x41\x64\x64\x72\x65\x73\x73\x00", 15);
d6bc83e4
 	    if(pt) {
 		    uint32_t dw1, dw2;
 
 		pt += 15;
 		if(((dw1 = cli_readint32(pt)) ^ (dw2 = cli_readint32(pt + 4))) == 0x505a4f && ((dw1 = cli_readint32(pt + 8)) ^ (dw2 = cli_readint32(pt + 12))) == 0xffffb && ((dw1 = cli_readint32(pt + 16)) ^ (dw2 = cli_readint32(pt + 20))) == 0xb8) {
605b8cf0
 		    *ctx->virname = "W32.Parite.B";
98454000
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
d6bc83e4
 		    return CL_VIRUS;
 		}
 	    }
 	}
     }
 
f3e58a58
     /* Kriz */
4a30feab
     if(SCAN_ALGO && (DCONF & PE_CONF_KRIZ) && CLI_ISCONTAINED(exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz, ep, 0x0fd2)) {
f3e58a58
 	cli_dbgmsg("in kriz\n");
 	lseek(desc, ep, SEEK_SET);
d7903e09
 	if(cli_readn(desc, buff, 200) == 200) {
ba9f25bb
 	    while (1) {
 		char *krizpos=buff+3;
 		char *krizmov, *krizxor;
 		int krizleft = 200-3;
 		int krizrega,krizregb;
 
 		if (buff[1]!='\x9c' || buff[2]!='\x60') break; /* EP+1 */
 		xckriz(&krizpos, &krizleft, 0, 8);
 		if (krizleft < 6 || *krizpos!='\xe8' || krizpos[2] || krizpos[3] || krizpos[4]) break; /* call DELTA */
 		krizleft-=5+(unsigned char)krizpos[1];
 		if (krizleft < 2) break;
 		krizpos+=5+(unsigned char)krizpos[1];
 		if (*krizpos<'\x58' || *krizpos>'\x5f' || *krizpos=='\x5c') break; /* pop DELTA */
 		krizrega=*krizpos-'\x58';
 		cli_dbgmsg("kriz: pop delta using %d\n", krizrega);
 		krizpos+=1;
 		krizleft-=1;
 		xckriz(&krizpos, &krizleft, 1, 8);
 		if (krizleft <6 || *krizpos<'\xb8' || *krizpos>'\xbf' || *krizpos=='\xbc' || cli_readint32(krizpos+1)!=0x0fd2) break;
 		krizregb=*krizpos-'\xb8';
 		if (krizrega==krizregb) break;
 		cli_dbgmsg("kriz: using %d for size\n", krizregb);
 		krizpos+=5;
 		krizleft-=5;
 		krizmov = krizpos;
 		xckriz(&krizpos, &krizleft, 0, 8);
 		krizxor=krizpos;
 		if (krizleft && *krizpos=='\x3e') {
 		    /* strip ds: */
 		    krizpos++;
 		    krizleft--;
 		}
 		if (krizleft<8 || *krizpos!='\x80' || (char)(krizpos[1]-krizrega)!='\xb0') {
 		    cli_dbgmsg("kriz: bogus opcode or register\n");
 		    break;
 		}
 		krizpos+=7;
 		krizleft-=7;
 		xckriz(&krizpos, &krizleft, 0, krizrega);
 		if (! krizleft || (char)(*krizpos-krizrega)!='\x48') break; /* dec delta */
 		krizpos++;
 		krizleft--;
 		cli_dbgmsg("kriz: dec delta found\n");
 		xckriz(&krizpos, &krizleft, 0, krizregb);
 		if (krizleft <4 || (char)(*krizpos-krizregb)!='\x48' || krizpos[1]!='\x75') break; /* dec size + jne loop */
 		if (krizpos+3+(int)krizpos[2]<krizmov || krizpos+3+(int)krizpos[2]>krizxor) {
 		    cli_dbgmsg("kriz: jmp back out of range (%d>%d>%d)\n", krizmov-(krizpos+3), (int)krizpos[2], krizxor-(krizpos+3));
 		    break;
f3e58a58
 		}
ba9f25bb
 		*ctx->virname = "Win32.Kriz";
 		free(section_hdr);
 		free(exe_sections);
 		return CL_VIRUS;
 	    }
f3e58a58
 	}
     }
 
b76bf2c4
     /* W32.Magistr.A/B */
4a30feab
     if(SCAN_ALGO && (DCONF & PE_CONF_MAGISTR) && !dll && (EC32(section_hdr[nsections - 1].Characteristics) & 0x80000000)) {
cc4d42d9
 	    uint32_t rsize, vsize, dam = 0;
b76bf2c4
 
69ad9664
 	vsize = exe_sections[nsections - 1].uvsz;
cc4d42d9
 	rsize = exe_sections[nsections - 1].rsz;
 	if(rsize < exe_sections[nsections - 1].ursz) {
 	    rsize = exe_sections[nsections - 1].ursz;
 	    dam = 1;
 	}
b76bf2c4
 
cc4d42d9
 	if(vsize >= 0x612c && rsize >= 0x612c && ((vsize & 0xff) == 0xec)) {
b76bf2c4
 		int bw = rsize < 0x7000 ? rsize : 0x7000;
 
ba9f25bb
 	    lseek(desc, exe_sections[nsections - 1].raw + rsize - bw, SEEK_SET);
d7903e09
 	    if(cli_readn(desc, buff, 4096) == 4096) {
b76bf2c4
 		if(cli_memstr(buff, 4091, "\xe8\x2c\x61\x00\x00", 5)) {
cc4d42d9
 		    *ctx->virname = dam ? "W32.Magistr.A.dam" : "W32.Magistr.A";
b76bf2c4
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
b76bf2c4
 		    return CL_VIRUS;
 		} 
 	    }
 
 	} else if(rsize >= 0x7000 && vsize >= 0x7000 && ((vsize & 0xff) == 0xed)) {
 		int bw = rsize < 0x8000 ? rsize : 0x8000;
 
ba9f25bb
 	    lseek(desc, exe_sections[nsections - 1].raw + rsize - bw, SEEK_SET);
d7903e09
 	    if(cli_readn(desc, buff, 4096) == 4096) {
b76bf2c4
 		if(cli_memstr(buff, 4091, "\xe8\x04\x72\x00\x00", 5)) {
cc4d42d9
 		    *ctx->virname = dam ? "W32.Magistr.B.dam" : "W32.Magistr.B";
b76bf2c4
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
b76bf2c4
 		    return CL_VIRUS;
 		} 
 	    }
 	}
     }
 
8fc57a1f
     /* W32.Polipos.A */
f164272a
    if(polipos && !dll && nsections > 2 && nsections < 13 && e_lfanew <= 0x800 && (EC16(optional_hdr32.Subsystem) == 2 || EC16(optional_hdr32.Subsystem) == 3) && EC16(file_hdr.Machine) == 0x14c && optional_hdr32.SizeOfStackReserve >= 0x80000) {
e6bea1aa
 		uint32_t remaining = exe_sections[0].rsz;
8fc57a1f
 		uint32_t chunk = sizeof(buff);
7f7736bb
 		uint32_t val, shift, raddr, total = 0;
8fc57a1f
 		const char *jpt;
 		struct offset_list *offlist = NULL, *offnode;
 
 
 	cli_dbgmsg("Detected W32.Polipos.A characteristics\n");
 
 	if(remaining < chunk)
 	    chunk = remaining;
 
e6bea1aa
 	lseek(desc, exe_sections[0].raw, SEEK_SET);
8fc57a1f
 	while((bytes = cli_readn(desc, buff, chunk)) > 0) {
 	    shift = 0;
e6bea1aa
 	    while((uint32_t)bytes - 5 > shift) {
8fc57a1f
 		jpt = buff + shift;
 		if(*jpt!='\xe9' && *jpt!='\xe8') {
 		    shift++;
 		    continue;
 		}
 		val = cli_readint32(jpt + 1);
e6bea1aa
 		val += 5 + exe_sections[0].rva + total + shift;
 		raddr = cli_rawaddr(val, exe_sections, nsections, &err, fsize);
8fc57a1f
 
e6bea1aa
 		if(!err && (raddr >= exe_sections[polipos].raw && raddr < exe_sections[polipos].raw + exe_sections[polipos].rsz) && (!offlist || (raddr != offlist->offset))) {
8fc57a1f
 		    offnode = (struct offset_list *) cli_malloc(sizeof(struct offset_list));
 		    if(!offnode) {
 			free(section_hdr);
e6bea1aa
 			free(exe_sections);
8fc57a1f
 			while(offlist) {
 			    offnode = offlist;
 			    offlist = offlist->next;
 			    free(offnode);
 			}
 			return CL_EMEM;
 		    }
 		    offnode->offset = raddr;
 		    offnode->next = offlist;
 		    offlist = offnode;
 		}
 
 		shift++;
 	    }
 
 	    if(remaining < chunk) {
 		chunk = remaining;
 	    } else {
 		remaining -= bytes;
 		if(remaining < chunk) {
 		    chunk = remaining;
 		}
 	    }
 
 	    if(!remaining)
 		break;
 
 	    total += bytes;
 	}
 
 	offnode = offlist;
 	while(offnode) {
 	    cli_dbgmsg("Polipos: Checking offset 0x%x (%u)", offnode->offset, offnode->offset);
 	    lseek(desc, offnode->offset, SEEK_SET);
 	    if(cli_readn(desc, buff, 9) == 9) {
 		ubuff = (unsigned char *) buff;
 		if(ubuff[0] == 0x55 && ubuff[1] == 0x8b && ubuff[2] == 0xec &&
 		   ((ubuff[3] == 0x83 && ubuff[4] == 0xec && ubuff[6] == 0x60) ||  ubuff[3] == 0x60 ||
 		     (ubuff[3] == 0x81 && ubuff[4] == 0xec && ubuff[7] == 0x00 && ubuff[8] == 0x00))) {
 		    ret = CL_VIRUS;
 		    *ctx->virname = "W32.Polipos.A";
 		    break;
 		}
 	    }
 
 	    offnode = offnode->next;
 	}
 
 	while(offlist) {
 	    offnode = offlist;
 	    offlist = offlist->next;
 	    free(offnode);
 	}
 
 	if(ret == CL_VIRUS) {
 	    free(section_hdr);
e6bea1aa
 	    free(exe_sections);
8fc57a1f
 	    return CL_VIRUS;
 	}
     }
 
24481e0f
     /* SUE */
     
4a30feab
     if((DCONF & PE_CONF_SUE) && nsections > 2 && vep == exe_sections[nsections - 1].rva && exe_sections[nsections - 1].rsz > 0x350 && exe_sections[nsections - 1].rsz < 0x292+0x350+1000) {
24481e0f
   
       
       char *sue=buff+0x74;
       uint32_t key;
       
       if(lseek(desc, ep-4, SEEK_SET) == -1) {
e6bea1aa
 	cli_dbgmsg("SUE: lseek() failed\n");
24481e0f
 	free(section_hdr);
e6bea1aa
 	free(exe_sections);
24481e0f
 	return CL_EIO;
       }
e6bea1aa
       if((unsigned int) cli_readn(desc, buff, exe_sections[nsections - 1].rsz+4) == exe_sections[nsections - 1].rsz+4) {
24481e0f
 	found=0;
e6bea1aa
 	while(CLI_ISCONTAINED(buff+4, exe_sections[nsections - 1].rsz, sue, 4*3)) {
24481e0f
 	  if((cli_readint32(sue)^cli_readint32(sue+4))==0x5c41090e && (cli_readint32(sue)^cli_readint32(sue+8))==0x021e0145) {
 	    found=1;
 	    key=(cli_readint32(sue)^0x6e72656b);
 	    break;
 	  }
 	  sue++;
 	}
 	cli_dbgmsg("SUE: key(%x) found @%x\n", key, sue-buff);
e6bea1aa
 	if (found && CLI_ISCONTAINED(buff, exe_sections[nsections - 1].rsz, sue-0x74, 0xbe) &&
 	    (sue=sudecrypt(desc, fsize, exe_sections, nsections-1, sue, key, cli_readint32(buff), e_lfanew))) {
24481e0f
 	  if(!(tempfile = cli_gentemp(NULL))) {
 	    free(sue);
 	    free(section_hdr);
e6bea1aa
 	    free(exe_sections);
24481e0f
 	    return CL_EMEM;
 	  }
e6bea1aa
 
ac2888aa
 	  if((ndesc = open(tempfile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) {
24481e0f
 	    cli_dbgmsg("sue: Can't create file %s\n", tempfile);
 	    free(tempfile);
 	    free(sue);
 	    free(section_hdr);
e6bea1aa
 	    free(exe_sections);
24481e0f
 	    return CL_EIO;
 	  }
 	  
e6bea1aa
 	  if((unsigned int) cli_writen(ndesc, sue, ep) != ep) {
24481e0f
 	    cli_dbgmsg("sue: Can't write %d bytes\n", ep);
 	    close(ndesc);
 	    free(tempfile);
 	    free(sue);
 	    free(section_hdr);
e6bea1aa
 	    free(exe_sections);
24481e0f
 	    return CL_EIO;
 	  }
 
 	  free(sue);
 	  if (cli_leavetemps_flag)
 	    cli_dbgmsg("SUE: Decrypted executable saved in %s\n", tempfile);
 	  else
 	    cli_dbgmsg("SUE: Executable decrypted\n");
 	  fsync(ndesc);
 	  lseek(ndesc, 0, SEEK_SET);
 
 	  if(cli_magic_scandesc(ndesc, ctx) == CL_VIRUS) {
 	    free(section_hdr);
e6bea1aa
 	    free(exe_sections);
24481e0f
 	    close(ndesc);
 	    if(!cli_leavetemps_flag)
 	      unlink(tempfile);
 	    free(tempfile);
 	    return CL_VIRUS;
 	  }
 	  close(ndesc);
 	  if(!cli_leavetemps_flag)
 	    unlink(tempfile);
 	  free(tempfile);
 	}
       }
 
     }
 
28992740
     /* UPX, FSG, MEW support */
c2484690
 
     /* try to find the first section with physical size == 0 */
     found = 0;
36b3f1cc
     if(DCONF & (PE_CONF_UPX | PE_CONF_FSG | PE_CONF_MEW)) {
4a30feab
 	for(i = 0; i < (unsigned int) nsections - 1; i++) {
 	    if(!section_hdr[i].SizeOfRawData && section_hdr[i].VirtualSize && section_hdr[i + 1].SizeOfRawData && section_hdr[i + 1].VirtualSize) {
 		found = 1;
28992740
 		cli_dbgmsg("UPX/FSG/MEW: empty section found - assuming compression\n");
4a30feab
 		break;
 	    }
c2484690
 	}
     }
 
28992740
     /* MEW support */
36b3f1cc
     if (found && (DCONF & PE_CONF_MEW)) {
28992740
 	uint32_t fileoffset;
 	/* Check EP for MEW */
 	if(lseek(desc, ep, SEEK_SET) == -1) {
 	    cli_dbgmsg("MEW: lseek() failed\n");
 	    free(section_hdr);
1c39d9da
 	    free(exe_sections);
28992740
 	    return CL_EIO;
 	}
 
         if((bytes = read(desc, buff, 25)) != 25 && bytes < 16) {
 	    cli_dbgmsg("MEW: Can't read at least 16 bytes at 0x%x (%d) %d\n", ep, ep, bytes);
 	    cli_dbgmsg("MEW: Broken or not compressed file\n");
             free(section_hdr);
1c39d9da
 	    free(exe_sections);
28992740
 	    return CL_CLEAN;
 	}
 
 	fileoffset = (vep + cli_readint32(buff + 1) + 5);
 	do {
 	    if (found && (buff[0] == '\xe9') && (fileoffset == 0x154 || fileoffset == 0x158))
 	    {
 		uint32_t offdiff, uselzma;
 
 		cli_dbgmsg ("MEW characteristics found: %08X + %08X + 5 = %08X\n", 
 			cli_readint32(buff + 1), vep, cli_readint32(buff + 1) + vep + 5);
 
 		if(lseek(desc, fileoffset, SEEK_SET) == -1) {
 		    cli_dbgmsg("MEW: lseek() failed\n");
 		    free(section_hdr);
1c39d9da
 		    free(exe_sections);
28992740
 		    return CL_EIO;
 		}
 
 		if((bytes = read(desc, buff, 0xb0)) != 0xb0) {
 		    cli_dbgmsg("MEW: Can't read 0xb0 bytes at 0x%x (%d) %d\n", fileoffset, fileoffset, bytes);
 		    break;
 		}
 
 		if (fileoffset == 0x154) 
 		    cli_dbgmsg("MEW: Win9x compatibility was set!\n");
 		else
 		    cli_dbgmsg("MEW: Win9x compatibility was NOT set!\n");
 
 		/* is it always 0x1C and 0x21C or not */
1c39d9da
 		if((offdiff = cli_readint32(buff+1) - EC32(optional_hdr32.ImageBase)) <= exe_sections[i + 1].rva || offdiff >= exe_sections[i + 1].rva + exe_sections[i + 1].raw - 4)
28992740
 		{
 		    cli_dbgmsg("MEW: ESI is not in proper section\n");
 		    break;
 		}
1c39d9da
 		offdiff -= exe_sections[i + 1].rva;
28992740
 
1c39d9da
 		if(lseek(desc, exe_sections[i + 1].raw, SEEK_SET) == -1) {
28992740
 		    cli_dbgmsg("MEW: lseek() failed\n"); /* ACAB: lseek won't fail here but checking doesn't hurt even */
 		    free(section_hdr);
1c39d9da
 		    free(exe_sections);
28992740
 		    return CL_EIO;
 		}
1c39d9da
 		ssize = exe_sections[i + 1].vsz;
 		dsize = exe_sections[i].vsz;
28992740
 
 		cli_dbgmsg("MEW: ssize %08x dsize %08x offdiff: %08x\n", ssize, dsize, offdiff);
1c39d9da
 		if(ctx->limits && ctx->limits->maxfilesize && (ssize + dsize > ctx->limits->maxfilesize || exe_sections[i + 1].rsz > ctx->limits->maxfilesize)) {
28992740
 		    cli_dbgmsg("MEW: Sizes exceeded (ssize: %u, dsize: %u, max: %lu)\n", ssize, dsize , ctx->limits->maxfilesize);
 		    free(section_hdr);
1c39d9da
 		    free(exe_sections);
28992740
 		    if(BLOCKMAX) {
 			*ctx->virname = "PE.MEW.ExceededFileSize";
 			return CL_VIRUS;
 		    } else {
 			return CL_CLEAN;
 		    }
 		}
 
 		/* allocate needed buffer */
 		if (!(src = cli_calloc (ssize + dsize, sizeof(char)))) {
 		    free(section_hdr);
1c39d9da
 		    free(exe_sections);
28992740
 		    return CL_EMEM;
 		}
 
1c39d9da
 		if (exe_sections[i + 1].rsz < offdiff + 12 || exe_sections[i + 1].rsz > ssize)
28992740
 		{
1c39d9da
 		    cli_dbgmsg("MEW: Size mismatch: %08x\n", exe_sections[i + 1].rsz);
28992740
 		    free(src);
 		    break;
 		}
 
1c39d9da
 		if((bytes = read(desc, src + dsize, exe_sections[i + 1].rsz)) != exe_sections[i + 1].rsz) {
 		    cli_dbgmsg("MEW: Can't read %d bytes [readed: %d]\n", exe_sections[i + 1].rsz, bytes);
28992740
 		    free(section_hdr);
1c39d9da
 		    free(exe_sections);
28992740
 		    free(src);
 		    return CL_EIO;
 		}
 		cli_dbgmsg("MEW: %d (%08x) bytes read\n", bytes, bytes);
 		/* count offset to lzma proc, if lzma used, 0xe8 -> call */
 		if (buff[0x7b] == '\xe8')
 		{
1c39d9da
 		    if (!CLI_ISCONTAINED(exe_sections[1].rva, exe_sections[1].vsz, cli_readint32(buff + 0x7c) + fileoffset + 0x80, 4))
28992740
 		    {
 			cli_dbgmsg("MEW: lzma proc out of bounds!\n");
 			free(src);
 			break; /* to next unpacker in chain */
 		    }
1c39d9da
 		    uselzma = cli_readint32(buff + 0x7c) - (exe_sections[0].rva - fileoffset - 0x80);
28992740
 		} else
 		    uselzma = 0;
 
 		if(!(tempfile = cli_gentemp(NULL))) {
 		    free(section_hdr);
1c39d9da
 		    free(exe_sections);
28992740
 		    free(src);
 		    return CL_EMEM;
 		}
 		if((ndesc = open(tempfile, O_RDWR|O_CREAT|O_TRUNC, S_IRWXU)) < 0) {
 		    cli_dbgmsg("MEW: Can't create file %s\n", tempfile);
 		    free(tempfile);
 		    free(section_hdr);
1c39d9da
 		    free(exe_sections);
28992740
 		    free(src);
 		    return CL_EIO;
 		}
 		dest = src;
1c39d9da
 		switch(unmew11(i, src, offdiff, ssize, dsize, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, uselzma, NULL, NULL, ndesc)) {
28992740
 		    case 1: /* Everything OK */
 			cli_dbgmsg("MEW: Unpacked and rebuilt executable saved in %s\n", tempfile);
 			free(src);
 			fsync(ndesc);
 			lseek(ndesc, 0, SEEK_SET);
 
 			cli_dbgmsg("***** Scanning rebuilt PE file *****\n");
 			if(cli_magic_scandesc(ndesc, ctx) == CL_VIRUS) {
 			    free(section_hdr);
1c39d9da
 			    free(exe_sections);
28992740
 			    close(ndesc);
 			    if(!cli_leavetemps_flag)
 				unlink(tempfile);
 			    free(tempfile);
 			    return CL_VIRUS;
 			}
 			close(ndesc);
 			if(!cli_leavetemps_flag)
 			    unlink(tempfile);
 			free(tempfile);
 			free(section_hdr);
1c39d9da
 			free(exe_sections);
28992740
 			return CL_CLEAN;
 		    default: /* Everything gone wrong */
 			cli_dbgmsg("MEW: Unpacking failed\n");
 			close(ndesc);
 			unlink(tempfile); /* It's empty anyway */
 			free(tempfile);
 			free(src);
 			break;
 		}
 	    }
 	} while (0);
     }
 
3b53a254
     if(found || upack) {
 	/* Check EP for UPX vs. FSG vs. Upack */
3c5b57d4
 	if(lseek(desc, ep, SEEK_SET) == -1) {
 	    cli_dbgmsg("UPX/FSG: lseek() failed\n");
9c3920b9
 	    free(section_hdr);
e6bea1aa
 	    free(exe_sections);
3c5b57d4
 	    return CL_EIO;
5115a5eb
 	}
 
d7903e09
         if(cli_readn(desc, buff, 168) != 168) {
6bd80fe3
 	    cli_dbgmsg("UPX/FSG: Can't read 168 bytes at 0x%x (%d)\n", ep, ep);
b5666f50
 	    cli_dbgmsg("UPX/FSG: Broken or not UPX/FSG compressed file\n");
3c5b57d4
             free(section_hdr);
e6bea1aa
 	    free(exe_sections);
b5666f50
 	    return CL_CLEAN;
fbbf7cd2
 	}
 
3b53a254
 	/* Upack 0.39 produces 2 types of executables
 	 * 3 sections:           | 2 sections (one empty, I don't chech found if !upack, since it's in OR above):
 	 *   mov esi, value      |   pusha
 	 *   lodsd               |   call $+0x9
 	 *   push eax            |
 	 *
 	 * Upack 1.1/1.2 Beta produces [based on 2 samples (sUx) provided by aCaB]:
 	 * 2 sections
 	 *   mov esi, value
 	 *   loads
 	 *   mov edi, eax
 	 *
 	 * Upack unknown [sample 0297729]
 	 * 3 sections
 	 *   mov esi, value
 	 *   push [esi]
 	 *   jmp
 	 * 
 	 */
 	/* upack 0.39-3s + sample 0151477*/
  	if((upack && buff[0] == '\xbe' && cli_readint32(buff + 1) - EC32(optional_hdr32.ImageBase) > min && /* mov esi */
 				buff[5] == '\xad' && buff[6] == '\x50' && /* lodsd; push eax */
 				EC16(file_hdr.NumberOfSections) == 3) || /* 3 sections */
 			/* based on 0297729 sample from aCaB */
 			(upack && buff[0] == '\xbe' && cli_readint32(buff + 1) - EC32(optional_hdr32.ImageBase) > min && /* mov esi */
 			 buff[5] == '\xff' && buff[6] == '\x36' && /* push [esi] */
 			 EC16(file_hdr.NumberOfSections) == 3) ||
 			/* upack 0.39-2s */
 			(!upack && buff[0] == '\x60' && buff[1] == '\xe8' && cli_readint32(buff+2) == 0x9 && /* pusha; call+9 */
 			 EC16(file_hdr.NumberOfSections) == 2) || /* 2 sections */
 			/* upack 1.1/1.2, based on 2 samples */
 			(!upack && buff[0] == '\xbe' && cli_readint32(buff+1) - EC32(optional_hdr32.ImageBase) < min &&  /* mov esi */
 			 cli_readint32(buff + 1) - EC32(optional_hdr32.ImageBase) > 0 && 
 			 buff[5] == '\xad' && buff[6] == '\x8b' && buff[7] == '\xf8' && /* loads;  mov edi, eax */
 			 EC16(file_hdr.NumberOfSections) == 2)) { /* 2 sections */
 		uint32_t vma, off;
 		int a,b,c, file;
 
 		cli_dbgmsg("Upack characteristics found.\n");
 		a = EC32(section_hdr[0].VirtualSize);
 		b = EC32(section_hdr[1].VirtualSize);
 		if (upack) {
 			cli_dbgmsg("upack var set\n");
 			c = EC32(section_hdr[2].VirtualSize);
 			ssize = EC32(section_hdr[0].SizeOfRawData) + EC32(section_hdr[0].PointerToRawData);
 			off = EC32(section_hdr[0].VirtualAddress);
 			vma = EC32(optional_hdr32.ImageBase) + EC32(section_hdr[0].VirtualAddress);
 		} else {
 			cli_dbgmsg("upack var NOT set\n");
 			c = EC32(section_hdr[1].VirtualAddress);
 			ssize = EC32(section_hdr[1].PointerToRawData);
 			off = 0;
 			vma = EC32(section_hdr[1].VirtualAddress) - EC32(section_hdr[1].PointerToRawData);
 		}
 
 		dsize = a+b+c;
 		if (ctx->limits && ctx->limits->maxfilesize && (dsize > ctx->limits->maxfilesize || ssize > ctx->limits->maxfilesize || EC32(section_hdr[1].SizeOfRawData) > ctx->limits->maxfilesize))
 		{
 		    cli_dbgmsg("Upack: Sizes exceeded (a: %u, b: %u, c: %ux, max: %lu)\n", a, b, c, ctx->limits->maxfilesize);
 		    free(section_hdr);
 		    if(BLOCKMAX) {
 			*ctx->virname = "PE.Upack.ExceededFileSize";
 			return CL_VIRUS;
 		    } else {
 			return CL_CLEAN;
 		    }
 		}
 		/* these are unsigned so if vaddr - off < 0, it should be ok */
 		if (EC32(section_hdr[1].VirtualAddress) - off > dsize || EC32(section_hdr[1].VirtualAddress) - off > dsize - EC32(section_hdr[1].SizeOfRawData) || (upack && (EC32(section_hdr[2].VirtualAddress) - EC32(section_hdr[0].VirtualAddress) > dsize || EC32(section_hdr[2].VirtualAddress) - EC32(section_hdr[0].VirtualAddress) > dsize - ssize)) || ssize > dsize)
 		{
 		    cli_dbgmsg("Upack: probably malformed pe-header, skipping to next unpacker\n");
 		    goto skip_upack_and_go_to_next_unpacker; /* I didn't want to add additional do while + break, can it be this way ? */
 		}
 			
 		if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
 		    free(section_hdr);
 		    return CL_EMEM;
 		}
 		src = NULL;
 		cli_dbgmsg("Upack: min: %08x %08x max: %08x\n", dest, a+b+c, dest+a+b+c);
 	
 		lseek(desc, 0, SEEK_SET);
 		if(read(desc, dest, ssize) != ssize) { /* 2vGiM: i think this can be overflowed - should you check for ssize < dsize ?
 		                                        * yup, I think you're right, added above
 							*/
 		    cli_dbgmsg("Upack: Can't read raw data of section 0\n");
 		    free(section_hdr);
 		    free(dest);
 		    return CL_EIO;
 		}
 
 		if (upack)
 			memmove(dest + EC32(section_hdr[2].VirtualAddress) - EC32(section_hdr[0].VirtualAddress), dest, ssize);
 
 		lseek(desc, EC32(section_hdr[1].PointerToRawData), SEEK_SET);
 
 		if(read(desc, dest+EC32(section_hdr[1].VirtualAddress) - off, EC32(section_hdr[1].SizeOfRawData)) != EC32(section_hdr[1].SizeOfRawData)) {
 		    cli_dbgmsg("Upack: Can't read raw data of section 1\n");
 		    free(section_hdr);
 		    free(dest);
 		    return CL_EIO;
 		}
 
 		if(!(tempfile = cli_gentemp(NULL)))
 		    return CL_EMEM;
 
 		if((file = open(tempfile, O_RDWR|O_CREAT|O_TRUNC, S_IRWXU)) < 0) {
 		    cli_dbgmsg("Upack: Can't create file %s\n", tempfile);
 		    free(tempfile);
 		    free(section_hdr);
 		    free(dest);
 		    return CL_EIO;
 		}
 
 		switch (unupack(upack, dest, dsize, buff, vma, ep, EC32(optional_hdr32.ImageBase), EC32(section_hdr[0].VirtualAddress), file))
 		{
 			case 1: /* Everything OK */
 				cli_dbgmsg("Upack: Unpacked and rebuilt executable saved in %s\n", tempfile);
 				free(dest);
 				fsync(file);
 				lseek(file, 0, SEEK_SET);
 
 				cli_dbgmsg("***** Scanning rebuilt PE file *****\n");
 				if(cli_magic_scandesc(file, ctx) == CL_VIRUS) {
 					free(section_hdr);
 					close(file);
 					if(!cli_leavetemps_flag)
 						unlink(tempfile);
 					free(tempfile);
 					return CL_VIRUS;
 				}
 
 				close(file);
 				if(!cli_leavetemps_flag)
 					unlink(tempfile);
 				free(tempfile);
 				free(section_hdr);
 				return CL_CLEAN;
 
 			default: /* Everything gone wrong */
 				cli_dbgmsg("Upack: Unpacking failed\n");
 				close(file);
 				unlink(tempfile); /* It's empty anyway */
 				free(tempfile);
 				free(dest);
 				break;
 		}
 	}
 skip_upack_and_go_to_next_unpacker:
 
4a30feab
 	if((DCONF & PE_CONF_FSG) && buff[0] == '\x87' && buff[1] == '\x25') {
f2eb2372
 
3daea9cf
 	    /* FSG v2.0 support - thanks to aCaB ! */
f2eb2372
 
e6bea1aa
 	    ssize = exe_sections[i + 1].rsz;
 	    dsize = exe_sections[i].vsz;
f2eb2372
 
3c5b57d4
 	    while(found) {
 		    uint32_t newesi, newedi, newebx, newedx;
5115a5eb
 
605b8cf0
 		if(ctx->limits && ctx->limits->maxfilesize && (ssize > ctx->limits->maxfilesize || dsize > ctx->limits->maxfilesize)) {
7135a8ff
 		    cli_dbgmsg("FSG: Sizes exceeded (ssize: %u, dsize: %u, max: %lu)\n", ssize, dsize , ctx->limits->maxfilesize);
3c5b57d4
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
125845b5
 		    if(BLOCKMAX) {
605b8cf0
 			*ctx->virname = "PE.FSG.ExceededFileSize";
125845b5
 			return CL_VIRUS;
 		    } else {
 			return CL_CLEAN;
 		    }
3c5b57d4
 		}
5115a5eb
 
3c5b57d4
 		if(ssize <= 0x19 || dsize <= ssize) {
 		    cli_dbgmsg("FSG: Size mismatch (ssize: %d, dsize: %d)\n", ssize, dsize);
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
3c5b57d4
 		    return CL_CLEAN;
 		}
 
e6bea1aa
 		newedx = cli_readint32(buff + 2) - EC32(optional_hdr32.ImageBase);
 		if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) {
3c5b57d4
 		    cli_dbgmsg("FSG: xchg out of bounds (%x), giving up\n", newedx);
 		    break;
 		}
 
 		if((src = (char *) cli_malloc(ssize)) == NULL) {
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
3c5b57d4
 		    return CL_EMEM;
 		}
 
e6bea1aa
 		lseek(desc, exe_sections[i + 1].raw, SEEK_SET);
d7903e09
 		if((unsigned int) cli_readn(desc, src, ssize) != ssize) {
e6bea1aa
 		    cli_dbgmsg("Can't read raw data of section %d\n", i + 1);
3c5b57d4
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
3c5b57d4
 		    free(src);
 		    return CL_EIO;
 		}
 
e6bea1aa
 		dest = src + newedx - exe_sections[i + 1].rva;
 		if(newedx < exe_sections[i + 1].rva || !CLI_ISCONTAINED(src, ssize, dest, 4)) {
3c5b57d4
 		    cli_dbgmsg("FSG: New ESP out of bounds\n");
 		    free(src);
 		    break;
 		}
 
e6bea1aa
 		newedx = cli_readint32(dest) - EC32(optional_hdr32.ImageBase);
 		if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) {
3c5b57d4
 		    cli_dbgmsg("FSG: New ESP (%x) is wrong\n", newedx);
 		    free(src);
 		    break;
 		}
  
e6bea1aa
 		dest = src + newedx - exe_sections[i + 1].rva;
 		if(!CLI_ISCONTAINED(src, ssize, dest, 32)) {
3c5b57d4
 		    cli_dbgmsg("FSG: New stack out of bounds\n");
 		    free(src);
 		    break;
 		}
 
aa816b56
 		newedi = cli_readint32(dest) - EC32(optional_hdr32.ImageBase);
 		newesi = cli_readint32(dest + 4) - EC32(optional_hdr32.ImageBase);
 		newebx = cli_readint32(dest + 16) - EC32(optional_hdr32.ImageBase);
3c5b57d4
 		newedx = cli_readint32(dest + 20);
 
e6bea1aa
 		if(newedi != exe_sections[i].rva) {
 		    cli_dbgmsg("FSG: Bad destination buffer (edi is %x should be %x)\n", newedi, exe_sections[i].rva);
3c5b57d4
 		    free(src);
 		    break;
 		}
 
e6bea1aa
 		if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) {
3c5b57d4
 		    cli_dbgmsg("FSG: Source buffer out of section bounds\n");
 		    free(src);
 		    break;
 		}
 
e6bea1aa
 		if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newebx, 16)) {
3c5b57d4
 		    cli_dbgmsg("FSG: Array of functions out of bounds\n");
 		    free(src);
 		    break;
 		}
 
e6bea1aa
 		newedx=cli_readint32(newebx + 12 - exe_sections[i + 1].rva + src) - EC32(optional_hdr32.ImageBase);
f50d51f7
 		cli_dbgmsg("FSG: found old EP @%x\n",newedx);
3c5b57d4
 
 		if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
3c5b57d4
 		    free(src);
 		    return CL_EMEM;
 		}
 
bf37ec7f
 		if(!(tempfile = cli_gentemp(NULL))) {
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
bf37ec7f
 		    free(src);
fb1ce239
 		    free(dest);
764dab55
 		    return CL_EMEM;
bf37ec7f
 		}
764dab55
 
ac2888aa
 		if((ndesc = open(tempfile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) {
f50d51f7
 		    cli_dbgmsg("FSG: Can't create file %s\n", tempfile);
 		    free(tempfile);
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
3c5b57d4
 		    free(src);
 		    free(dest);
f50d51f7
 		    return CL_EIO;
 		}
 		
e6bea1aa
 		switch (unfsg_200(newesi - exe_sections[i + 1].rva + src, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, newedi, EC32(optional_hdr32.ImageBase), newedx, ndesc)) {
f50d51f7
 		    case 1: /* Everything OK */
 			cli_dbgmsg("FSG: Unpacked and rebuilt executable saved in %s\n", tempfile);
 			free(src);
 			free(dest);
 			fsync(ndesc);
 			lseek(ndesc, 0, SEEK_SET);
 
 			cli_dbgmsg("***** Scanning rebuilt PE file *****\n");
605b8cf0
 			if(cli_magic_scandesc(ndesc, ctx) == CL_VIRUS) {
f50d51f7
 			    free(section_hdr);
e6bea1aa
 			    free(exe_sections);
f50d51f7
 			    close(ndesc);
 			    if(!cli_leavetemps_flag)
 				unlink(tempfile);
 			    free(tempfile);
 			    return CL_VIRUS;
 			}
 
 			close(ndesc);
 			if(!cli_leavetemps_flag)
 			    unlink(tempfile);
 			free(tempfile);
 			free(section_hdr);
e6bea1aa
 			free(exe_sections);
f50d51f7
 			return CL_CLEAN;
 
 		    case 0: /* We've got an unpacked buffer, no exe though */
e6bea1aa
 			cli_dbgmsg("FSG: Successfully decompressed\n");
f50d51f7
 			close(ndesc);
 			unlink(tempfile);
 			free(tempfile);
 			found = 0;
 			upx_success = 1;
 			break; /* Go and scan the buffer! */
 
 		    default: /* Everything gone wrong */
 			cli_dbgmsg("FSG: Unpacking failed\n");
 			close(ndesc);
7f7736bb
 			unlink(tempfile); /* It's empty anyway */
f50d51f7
 			free(tempfile);
 			free(src);
 			free(dest);
 			break;
3c5b57d4
 		}
 
04a81177
 		break; /* were done with 2 */
5115a5eb
 	    }
 	}
 
4a30feab
  	if(found && (DCONF & PE_CONF_FSG) && buff[0] == '\xbe' && cli_readint32(buff + 1) - EC32(optional_hdr32.ImageBase) < min) {
3daea9cf
 
 	    /* FSG support - v. 1.33 (thx trog for the many samples) */
 
e6bea1aa
 	    ssize = exe_sections[i + 1].rsz;
 	    dsize = exe_sections[i].vsz;
3daea9cf
 
 	    while(found) {
e6bea1aa
 	            int sectcnt = 0;
3daea9cf
 		    char *support;
e6bea1aa
 		    uint32_t newesi, newedi, newebx, oldep, gp, t;
 		    struct cli_exe_section *sections;
3daea9cf
 
 
605b8cf0
 		if(ctx->limits && ctx->limits->maxfilesize && (ssize > ctx->limits->maxfilesize || dsize > ctx->limits->maxfilesize)) {
7135a8ff
 		    cli_dbgmsg("FSG: Sizes exceeded (ssize: %u, dsize: %u, max: %lu)\n", ssize, dsize, ctx->limits->maxfilesize);
3daea9cf
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
125845b5
 		    if(BLOCKMAX) {
605b8cf0
 			*ctx->virname = "PE.FSG.ExceededFileSize";
125845b5
 			return CL_VIRUS;
 		    } else {
 			return CL_CLEAN;
 		    }
3daea9cf
 		}
 
 		if(ssize <= 0x19 || dsize <= ssize) {
 		    cli_dbgmsg("FSG: Size mismatch (ssize: %d, dsize: %d)\n", ssize, dsize);
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
3daea9cf
 		    return CL_CLEAN;
 		}
 
e6bea1aa
 		if(!(gp = cli_rawaddr(cli_readint32(buff + 1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize)) && err ) {
 		    cli_dbgmsg("FSG: Support data out of padding area\n");
3daea9cf
 		    break;
 		}
 
6bd80fe3
 		lseek(desc, gp, SEEK_SET);
e6bea1aa
 		gp = exe_sections[i + 1].raw - gp;
6bd80fe3
 
605b8cf0
 		if(ctx->limits && ctx->limits->maxfilesize && (unsigned int) gp > ctx->limits->maxfilesize) {
 		    cli_dbgmsg("FSG: Buffer size exceeded (size: %d, max: %lu)\n", gp, ctx->limits->maxfilesize);
3daea9cf
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
125845b5
 		    if(BLOCKMAX) {
605b8cf0
 			*ctx->virname = "PE.FSG.ExceededFileSize";
125845b5
 			return CL_VIRUS;
 		    } else {
 			return CL_CLEAN;
 		    }
3daea9cf
 		}
 
 		if((support = (char *) cli_malloc(gp)) == NULL) {
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
3daea9cf
 		    return CL_EMEM;
 		}
 
e6bea1aa
 		if((int)cli_readn(desc, support, gp) != (int)gp) {
3daea9cf
 		    cli_dbgmsg("Can't read %d bytes from padding area\n", gp); 
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
3daea9cf
 		    free(support);
 		    return CL_EIO;
 		}
 
e6bea1aa
 		/* newebx = cli_readint32(support) - EC32(optional_hdr32.ImageBase);  Unused */
aa816b56
 		newedi = cli_readint32(support + 4) - EC32(optional_hdr32.ImageBase); /* 1st dest */
 		newesi = cli_readint32(support + 8) - EC32(optional_hdr32.ImageBase); /* Source */
3daea9cf
 
e6bea1aa
 		if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) {
3daea9cf
 		    cli_dbgmsg("FSG: Source buffer out of section bounds\n");
 		    free(support);
 		    break;
 		}
 
e6bea1aa
 		if(newedi != exe_sections[i].rva) {
 		    cli_dbgmsg("FSG: Bad destination (is %x should be %x)\n", newedi, exe_sections[i].rva);
3daea9cf
 		    free(support);
 		    break;
 		}
 
 		/* Counting original sections */
 		for(t = 12; t < gp - 4; t += 4) {
 			uint32_t rva = cli_readint32(support+t);
 
 		    if(!rva)
 			break;
 
aa816b56
 		    rva -= EC32(optional_hdr32.ImageBase)+1;
3daea9cf
 		    sectcnt++;
 
 		    if(rva % 0x1000)
 			/* FIXME: really need to bother? */
 			cli_dbgmsg("FSG: Original section %d is misaligned\n", sectcnt);
 
e6bea1aa
 		    if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) {
3daea9cf
 			cli_dbgmsg("FSG: Original section %d is out of bounds\n", sectcnt);
 			break;
 		    }
 		}
 
d8f0a45c
 		if(t >= gp - 4 || cli_readint32(support + t)) {
3daea9cf
 		    free(support);
 		    break;
 		}
 
e6bea1aa
 		if((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) {
3daea9cf
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
3daea9cf
 		    free(support);
 		    return CL_EMEM;
 		}
 
 		sections[0].rva = newedi;
e6bea1aa
 		for(t = 1; t <= (uint32_t)sectcnt; t++)
 		    sections[t].rva = cli_readint32(support + 8 + t * 4) - 1 - EC32(optional_hdr32.ImageBase);
3daea9cf
 
 		free(support);
 
 		if((src = (char *) cli_malloc(ssize)) == NULL) {
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
3daea9cf
 		    free(sections);
 		    return CL_EMEM;
 		}
 
e6bea1aa
 		lseek(desc, exe_sections[i + 1].raw, SEEK_SET);
d7903e09
 		if((unsigned int) cli_readn(desc, src, ssize) != ssize) {
3daea9cf
 		    cli_dbgmsg("Can't read raw data of section %d\n", i);
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
3daea9cf
 		    free(sections);
 		    free(src);
 		    return CL_EIO;
 		}
 
 		if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
3daea9cf
 		    free(src);
 		    free(sections);
 		    return CL_EMEM;
 		}
 
e6bea1aa
 		oldep = vep + 161 + 6 + cli_readint32(buff+163);
3daea9cf
 		cli_dbgmsg("FSG: found old EP @%x\n", oldep);
 
bf37ec7f
 		if(!(tempfile = cli_gentemp(NULL))) {
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
bf37ec7f
 		    free(src);
 		    free(dest);
 		    free(sections);
764dab55
 		    return CL_EMEM;
bf37ec7f
 		}
764dab55
 
ac2888aa
 		if((ndesc = open(tempfile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) {
3daea9cf
 		    cli_dbgmsg("FSG: Can't create file %s\n", tempfile);
 		    free(tempfile);
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
3daea9cf
 		    free(src);
 		    free(dest);
 		    free(sections);
 		    return CL_EIO;
 		}
 
e6bea1aa
 		switch(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)) {
3daea9cf
 		    case 1: /* Everything OK */
 			cli_dbgmsg("FSG: Unpacked and rebuilt executable saved in %s\n", tempfile);
 			free(src);
 			free(dest);
 			free(sections);
 			fsync(ndesc);
 			lseek(ndesc, 0, SEEK_SET);
 
7c00689d
 			cli_dbgmsg("***** Scanning rebuilt PE file *****\n");
605b8cf0
 			if(cli_magic_scandesc(ndesc, ctx) == CL_VIRUS) {
3daea9cf
 			    free(section_hdr);
e6bea1aa
 			    free(exe_sections);
3daea9cf
 			    close(ndesc);
 			    if(!cli_leavetemps_flag)
 				unlink(tempfile);
 			    free(tempfile);
 			    return CL_VIRUS;
 			}
 
 			close(ndesc);
 			if(!cli_leavetemps_flag)
 			    unlink(tempfile);
 			free(tempfile);
 			free(section_hdr);
e6bea1aa
 			free(exe_sections);
3daea9cf
 			return CL_CLEAN;
 
 		    case 0: /* We've got an unpacked buffer, no exe though */
e6bea1aa
 			cli_dbgmsg("FSG: Successfully decompressed\n");
3daea9cf
 			close(ndesc);
 			unlink(tempfile);
 			free(tempfile);
 			free(sections);
 			found = 0;
 			upx_success = 1;
 			break; /* Go and scan the buffer! */
 
 		    default: /* Everything gone wrong */
 			cli_dbgmsg("FSG: Unpacking failed\n");
 			close(ndesc);
7f7736bb
 			unlink(tempfile); /* It's empty anyway */
3daea9cf
 			free(tempfile);
 			free(src);
 			free(dest);
 			free(sections);
 			break;
 		}
 
 		break; /* were done with 1.33 */
 	    }
 	}
 
6bd80fe3
 	/* FIXME: easy 2 hack */
4a30feab
  	if(found && (DCONF & PE_CONF_FSG) && buff[0] == '\xbb' && cli_readint32(buff + 1) - EC32(optional_hdr32.ImageBase) < min && buff[5] == '\xbf' && buff[10] == '\xbe' && vep >= exe_sections[i + 1].rva && vep - exe_sections[i + 1].rva > exe_sections[i + 1].rva - 0xe0 ) {
6bd80fe3
 
 	    /* FSG support - v. 1.31 */
 
e6bea1aa
 	    ssize = exe_sections[i + 1].rsz;
 	    dsize = exe_sections[i].vsz;
6bd80fe3
 
 	    while(found) {
e6bea1aa
 		    int sectcnt = 0;
 		    uint32_t t;
 		    uint32_t gp = cli_rawaddr(cli_readint32(buff+1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize);
6bd80fe3
 		    char *support;
aa816b56
 		    uint32_t newesi = cli_readint32(buff+11) - EC32(optional_hdr32.ImageBase);
 		    uint32_t newedi = cli_readint32(buff+6) - EC32(optional_hdr32.ImageBase);
e6bea1aa
 		    uint32_t oldep = vep - exe_sections[i + 1].rva;
 		    struct cli_exe_section *sections;
6bd80fe3
 
e6bea1aa
 		if(err) {
 		    cli_dbgmsg("FSG: Support data out of padding area\n");
 		    break;
6bd80fe3
 		}
 
e6bea1aa
 		if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].raw) {
6bd80fe3
 		    cli_dbgmsg("FSG: Source buffer out of section bounds\n");
 		    break;
 		}
 
e6bea1aa
 		if(newedi != exe_sections[i].rva) {
 		    cli_dbgmsg("FSG: Bad destination (is %x should be %x)\n", newedi, exe_sections[i].rva);
6bd80fe3
 		    break;
 		}
 
605b8cf0
 		if(ctx->limits && ctx->limits->maxfilesize && (ssize > ctx->limits->maxfilesize || dsize > ctx->limits->maxfilesize)) {
7135a8ff
 		    cli_dbgmsg("FSG: Sizes exceeded (ssize: %u, dsize: %u, max: %lu)\n", ssize, dsize, ctx->limits->maxfilesize);
6bd80fe3
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
125845b5
 		    if(BLOCKMAX) {
605b8cf0
 			*ctx->virname = "PE.FSG.ExceededFileSize";
125845b5
 			return CL_VIRUS;
 		    } else {
 			return CL_CLEAN;
 		    }
6bd80fe3
 		}
 
 		if(ssize <= 0x19 || dsize <= ssize) {
 		    cli_dbgmsg("FSG: Size mismatch (ssize: %d, dsize: %d)\n", ssize, dsize);
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
6bd80fe3
 		    return CL_CLEAN;
 		}
 
 		lseek(desc, gp, SEEK_SET);
e6bea1aa
 		gp = exe_sections[i + 1].raw - gp;
6bd80fe3
 
e6bea1aa
 		if(ctx->limits && ctx->limits->maxfilesize && gp > ctx->limits->maxfilesize) {
605b8cf0
 		    cli_dbgmsg("FSG: Buffer size exceeded (size: %d, max: %lu)\n", gp, ctx->limits->maxfilesize);
6bd80fe3
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
125845b5
 		    if(BLOCKMAX) {
605b8cf0
 			*ctx->virname = "PE.FSG.ExceededFileSize";
125845b5
 			return CL_VIRUS;
 		    } else {
 			return CL_CLEAN;
 		    }
6bd80fe3
 		}
 
 		if((support = (char *) cli_malloc(gp)) == NULL) {
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
6bd80fe3
 		    return CL_EMEM;
 		}
 
e6bea1aa
 		if(cli_readn(desc, support, gp) != (int)gp) {
6bd80fe3
 		    cli_dbgmsg("Can't read %d bytes from padding area\n", gp); 
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
6bd80fe3
 		    free(support);
 		    return CL_EIO;
 		}
 
 		/* Counting original sections */
 		for(t = 0; t < gp - 2; t += 2) {
e6bea1aa
 		  uint32_t rva = support[t]|(support[t+1]<<8);
6bd80fe3
 		  
 		  if (rva == 2 || rva == 1)
 		    break;
 
aa816b56
 		  rva = ((rva-2)<<12) - EC32(optional_hdr32.ImageBase);
6bd80fe3
 		  sectcnt++;
 
e6bea1aa
 		  if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) {
6bd80fe3
 		    cli_dbgmsg("FSG: Original section %d is out of bounds\n", sectcnt);
 		    break;
 		  }
 		}
 
d6bc83e4
 		if(t >= gp-10 || cli_readint32(support + t + 6) != 2) {
6bd80fe3
 		    free(support);
 		    break;
 		}
 
e6bea1aa
 		if((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) {
6bd80fe3
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
6bd80fe3
 		    free(support);
 		    return CL_EMEM;
 		}
 
 		sections[0].rva = newedi;
e6bea1aa
 		for(t = 0; t <= (uint32_t)sectcnt - 1; t++) {
 		  sections[t+1].rva = (((support[t*2]|(support[t*2+1]<<8))-2)<<12)-EC32(optional_hdr32.ImageBase);
6bd80fe3
 		}
 
 		free(support);
 
 		if((src = (char *) cli_malloc(ssize)) == NULL) {
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
6bd80fe3
 		    free(sections);
 		    return CL_EMEM;
 		}
 
e6bea1aa
 		lseek(desc, exe_sections[i + 1].raw, SEEK_SET);
d7903e09
 		if((unsigned int) cli_readn(desc, src, ssize) != ssize) {
e6bea1aa
 		    cli_dbgmsg("FSG: Can't read raw data of section %d\n", i);
6bd80fe3
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
6bd80fe3
 		    free(sections);
 		    free(src);
 		    return CL_EIO;
 		}
 
 		if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
6bd80fe3
 		    free(src);
 		    free(sections);
 		    return CL_EMEM;
 		}
 
 		/* Better not increasing buff size any further, let's go the hard way */
920406d9
 		gp = 0xda + 6*(buff[16]=='\xe8');
e6bea1aa
 		oldep = vep + gp + 6 + cli_readint32(src+gp+2+oldep);
6bd80fe3
 		cli_dbgmsg("FSG: found old EP @%x\n", oldep);
 
bf37ec7f
 		if(!(tempfile = cli_gentemp(NULL))) {
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
bf37ec7f
 		    free(src);
 		    free(dest);
 		    free(sections);
764dab55
 		    return CL_EMEM;
bf37ec7f
 		}
764dab55
 
ac2888aa
 		if((ndesc = open(tempfile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) {
6bd80fe3
 		    cli_dbgmsg("FSG: Can't create file %s\n", tempfile);
 		    free(tempfile);
 		    free(section_hdr);
e6bea1aa
 		    free(exe_sections);
6bd80fe3
 		    free(src);
 		    free(dest);
 		    free(sections);
 		    return CL_EIO;
 		}
 
aa816b56
 		switch(unfsg_133(src + newesi - EC32(section_hdr[i + 1].VirtualAddress), dest, ssize + EC32(section_hdr[i + 1].VirtualAddress) - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)) {
6bd80fe3
 		    case 1: /* Everything OK */
 			cli_dbgmsg("FSG: Unpacked and rebuilt executable saved in %s\n", tempfile);
 			free(src);
 			free(dest);
 			free(sections);
 			fsync(ndesc);
 			lseek(ndesc, 0, SEEK_SET);
 
7c00689d
 			cli_dbgmsg("***** Scanning rebuilt PE file *****\n");
605b8cf0
 			if(cli_magic_scandesc(ndesc, ctx) == CL_VIRUS) {
6bd80fe3
 			    free(section_hdr);
e6bea1aa
 			    free(exe_sections);
6bd80fe3
 			    close(ndesc);
 			    if(!cli_leavetemps_flag)
 				unlink(tempfile);
 			    free(tempfile);
 			    return CL_VIRUS;
 			}
 
 			close(ndesc);
 			if(!cli_leavetemps_flag)
 			    unlink(tempfile);
 			free(tempfile);
 			free(section_hdr);
e6bea1aa
 			free(exe_sections);
6bd80fe3
 			return CL_CLEAN;
 
 		    case 0: /* We've got an unpacked buffer, no exe though */
 			cli_dbgmsg("FSG: FSG: Successfully decompressed\n");
 			close(ndesc);
 			unlink(tempfile);
 			free(tempfile);
 			free(sections);
 			found = 0;
 			upx_success = 1;
 			break; /* Go and scan the buffer! */
 
 		    default: /* Everything gone wrong */
 			cli_dbgmsg("FSG: Unpacking failed\n");
 			close(ndesc);
7f7736bb
 			unlink(tempfile); /* It's empty anyway */
6bd80fe3
 			free(tempfile);
 			free(src);
 			free(dest);
 			free(sections);
 			break;
 		}
 
 		break; /* were done with 1.31 */
 	    }
 	}
 
 
4a30feab
 	if(found && (DCONF & PE_CONF_UPX)) {
fbbf7cd2
 
3c5b57d4
 	    /* UPX support */
fbbf7cd2
 
7f7736bb
 	    strncpy(sname, (char *) section_hdr[i].Name, 8);
3c5b57d4
 	    sname[8] = 0;
 	    cli_dbgmsg("UPX: Section %d name: %s\n", i, sname);
7f7736bb
 	    strncpy(sname, (char *) section_hdr[i + 1].Name, 8);
3c5b57d4
 	    sname[8] = 0;
 	    cli_dbgmsg("UPX: Section %d name: %s\n", i + 1, sname);
 
7f7736bb
 	    if(strncmp((char *) section_hdr[i].Name, "UPX0", 4) || strncmp((char *) section_hdr[i + 1].Name, "UPX1", 4))
3c5b57d4
 		cli_dbgmsg("UPX: Possibly hacked UPX section headers\n");
 
 	    /* we assume (i + 1) is UPX1 */
e6bea1aa
 	    ssize = exe_sections[i + 1].rsz;
 	    dsize = exe_sections[i].vsz + exe_sections[i + 1].vsz;
3c5b57d4
 
605b8cf0
 	    if(ctx->limits && ctx->limits->maxfilesize && (ssize > ctx->limits->maxfilesize || dsize > ctx->limits->maxfilesize)) {
7135a8ff
 		cli_dbgmsg("UPX: Sizes exceeded (ssize: %u, dsize: %u, max: %lu)\n", ssize, dsize , ctx->limits->maxfilesize);
3c5b57d4
 		free(section_hdr);
e6bea1aa
 		free(exe_sections);
125845b5
 		if(BLOCKMAX) {
605b8cf0
 		    *ctx->virname = "PE.UPX.ExceededFileSize";
125845b5
 		    return CL_VIRUS;
 		} else {
 		    return CL_CLEAN;
 		}
f2eb2372
 	    }
fbbf7cd2
 
3c5b57d4
 	    if(ssize <= 0x19 || dsize <= ssize) { /* FIXME: What are reasonable values? */
 		cli_dbgmsg("UPX: Size mismatch (ssize: %d, dsize: %d)\n", ssize, dsize);
 		free(section_hdr);
e6bea1aa
 		free(exe_sections);
3c5b57d4
 		return CL_CLEAN;
 	    }
f2eb2372
 
3c5b57d4
 	    /* FIXME: use file operations in case of big files */
 	    if((src = (char *) cli_malloc(ssize)) == NULL) {
 		free(section_hdr);
e6bea1aa
 		free(exe_sections);
3c5b57d4
 		return CL_EMEM;
f2eb2372
 	    }
 
7135a8ff
 	    if(dsize > CLI_MAX_ALLOCATION) {
 		cli_errmsg("UPX: Too big value of dsize\n");
 		free(section_hdr);
e6bea1aa
 		free(exe_sections);
7135a8ff
 		free(src);
 		return CL_EMEM;
 	    }
 
e6bea1aa
 	    if((dest = (char *) cli_calloc(dsize + 8192, sizeof(char))) == NULL) {
3c5b57d4
 		free(section_hdr);
e6bea1aa
 		free(exe_sections);
3c5b57d4
 		free(src);
 		return CL_EMEM;
f2eb2372
 	    }
 
e6bea1aa
 	    lseek(desc, exe_sections[i + 1].raw, SEEK_SET);
d7903e09
 	    if((unsigned int) cli_readn(desc, src, ssize) != ssize) {
e6bea1aa
 		cli_dbgmsg("UPX: Can't read raw data of section %d\n", i+1);
3c5b57d4
 		free(section_hdr);
e6bea1aa
 		free(exe_sections);
3c5b57d4
 		free(src);
 		free(dest);
 		return CL_EIO;
 	    }
 
 	    /* try to detect UPX code */
 
 	    if(lseek(desc, ep, SEEK_SET) == -1) {
e6bea1aa
 		cli_dbgmsg("UPX: lseek() failed\n");
3c5b57d4
 		free(section_hdr);
e6bea1aa
 		free(exe_sections);
3c5b57d4
 		free(src);
 		free(dest);
 		return CL_EIO;
 	    }
 
d7903e09
 	    if(cli_readn(desc, buff, 126) != 126) { /* i.e. 0x69 + 13 + 8 */
3c5b57d4
 		cli_dbgmsg("UPX: Can't read 126 bytes at 0x%x (%d)\n", ep, ep);
e6bea1aa
 		cli_dbgmsg("UPX: Broken or not UPX compressed file\n");
3c5b57d4
 		free(section_hdr);
e6bea1aa
 		free(exe_sections);
3c5b57d4
 		free(src);
 		free(dest);
b5666f50
 		return CL_CLEAN;
f2eb2372
 	    } else {
3c5b57d4
 		if(cli_memstr(UPX_NRV2B, 24, buff + 0x69, 13) || cli_memstr(UPX_NRV2B, 24, buff + 0x69 + 8, 13)) {
 		    cli_dbgmsg("UPX: Looks like a NRV2B decompression routine\n");
 		    upxfn = upx_inflate2b;
 		} else if(cli_memstr(UPX_NRV2D, 24, buff + 0x69, 13) || cli_memstr(UPX_NRV2D, 24, buff + 0x69 + 8, 13)) {
 		    cli_dbgmsg("UPX: Looks like a NRV2D decompression routine\n");
 		    upxfn = upx_inflate2d;
 		} else if(cli_memstr(UPX_NRV2E, 24, buff + 0x69, 13) || cli_memstr(UPX_NRV2E, 24, buff + 0x69 + 8, 13)) {
 		    cli_dbgmsg("UPX: Looks like a NRV2E decompression routine\n");
 		    upxfn = upx_inflate2e;
 		}
 	    }
 
 	    if(upxfn) {
e6bea1aa
 		    int skew = cli_readint32(buff + 2) - EC32(optional_hdr32.ImageBase) - exe_sections[i + 1].rva;
3c5b57d4
 
d6bc83e4
 		if(buff[1] != '\xbe' || skew <= 0 || skew > 0xfff) { /* FIXME: legit skews?? */
3c5b57d4
 		    skew = 0; 
e6bea1aa
 		    if(upxfn(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >= 0)
3c5b57d4
 			upx_success = 1;
 
 		} else {
 		    cli_dbgmsg("UPX: UPX1 seems skewed by %d bytes\n", skew);
e6bea1aa
                     if(upxfn(src + skew, ssize - skew, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep-skew) >= 0 || upxfn(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >= 0)
3c5b57d4
 			upx_success = 1;
 		}
 
 		if(upx_success)
 		    cli_dbgmsg("UPX: Successfully decompressed\n");
 		else
e6bea1aa
 		    cli_dbgmsg("UPX: Preferred decompressor failed\n");
3c5b57d4
 	    }
 
 	    if(!upx_success && upxfn != upx_inflate2b) {
e6bea1aa
 		if(upx_inflate2b(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2b(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) {
7c00689d
 
3c5b57d4
 		    cli_dbgmsg("UPX: NRV2B decompressor failed\n");
 		} else {
 		    upx_success = 1;
 		    cli_dbgmsg("UPX: Successfully decompressed with NRV2B\n");
 		}
 	    }
 
 	    if(!upx_success && upxfn != upx_inflate2d) {
e6bea1aa
 		if(upx_inflate2d(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2d(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) {
7c00689d
 
3c5b57d4
 		    cli_dbgmsg("UPX: NRV2D decompressor failed\n");
 		} else {
 		    upx_success = 1;
 		    cli_dbgmsg("UPX: Successfully decompressed with NRV2D\n");
 		}
 	    }
 
 	    if(!upx_success && upxfn != upx_inflate2e) {
e6bea1aa
 		if(upx_inflate2e(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2e(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) {
3c5b57d4
 		    cli_dbgmsg("UPX: NRV2E decompressor failed\n");
 		} else {
 		    upx_success = 1;
 		    cli_dbgmsg("UPX: Successfully decompressed with NRV2E\n");
 		}
 	    }
 
 	    if(!upx_success) {
 		cli_dbgmsg("UPX: All decompressors failed\n");
 		free(src);
 		free(dest);
c2484690
 	    }
 	}
f2eb2372
 
3c5b57d4
 	if(upx_success) {
7c00689d
 	    free(src);
 	    free(section_hdr);
e6bea1aa
 	    free(exe_sections);
f2eb2372
 
dc4c26f6
 	    if(!(tempfile = cli_gentemp(NULL))) {
 	        free(dest);
764dab55
 		return CL_EMEM;
dc4c26f6
 	    }
764dab55
 
ac2888aa
 	    if((ndesc = open(tempfile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) {
7c00689d
 		cli_dbgmsg("UPX/FSG: Can't create file %s\n", tempfile);
 		free(tempfile);
 		free(dest);
 		return CL_EIO;
 	    }
f2eb2372
 
a8b53539
 	    if((unsigned int) write(ndesc, dest, dsize) != dsize) {
7c00689d
 		cli_dbgmsg("UPX/FSG: Can't write %d bytes\n", dsize);
 		free(tempfile);
 		free(dest);
f2eb2372
 		close(ndesc);
7c00689d
 		return CL_EIO;
 	    }
 
 	    free(dest);
 	    fsync(ndesc);
 	    lseek(ndesc, 0, SEEK_SET);
 
 	    if(cli_leavetemps_flag)
3c5b57d4
 		cli_dbgmsg("UPX/FSG: Decompressed data saved in %s\n", tempfile);
7c00689d
 
3b46821b
 	    cli_dbgmsg("***** Scanning decompressed file *****\n");
605b8cf0
 	    if((ret = cli_magic_scandesc(ndesc, ctx)) == CL_VIRUS) {
7c00689d
 		close(ndesc);
 		if(!cli_leavetemps_flag)
 		    unlink(tempfile);
f2eb2372
 		free(tempfile);
7c00689d
 		return CL_VIRUS;
f2eb2372
 	    }
 
7c00689d
 	    close(ndesc);
 	    if(!cli_leavetemps_flag)
 		unlink(tempfile);
 	    free(tempfile);
65ab8d96
 	    return ret;
3c5b57d4
 	}
f2eb2372
     }
e3886d61
 
5ede41fa
     /* Petite */
 
     found = 2;
 
     lseek(desc, ep, SEEK_SET);
0bf8d34b
     memset(buff, 0, sizeof(buff));
     if(cli_readn(desc, buff, 200) == -1) {
 	cli_dbgmsg("cli_readn() failed\n");
f8355d13
 	free(section_hdr);
e6bea1aa
 	free(exe_sections);
5ede41fa
 	return CL_EIO;
f8355d13
     }
5ede41fa
 
aa816b56
     if(buff[0] != '\xb8' || (uint32_t) cli_readint32(buff + 1) != EC32(section_hdr[nsections - 1].VirtualAddress) + EC32(optional_hdr32.ImageBase)) {
 	if(nsections < 2 || buff[0] != '\xb8' || (uint32_t) cli_readint32(buff + 1) != EC32(section_hdr[nsections - 2].VirtualAddress) + EC32(optional_hdr32.ImageBase))
5ede41fa
 	    found = 0;
 	else
 	    found = 1;
     }
 
4a30feab
     if((DCONF & PE_CONF_PETITE) && found) {
5ede41fa
 	cli_dbgmsg("Petite: v2.%d compression detected\n", found);
 
 	if(cli_readint32(buff + 0x80) == 0x163c988d) {
 	    cli_dbgmsg("Petite: level zero compression is not supported yet\n");
 	} else {
 	    dsize = max - min;
 
605b8cf0
 	    if(ctx->limits && ctx->limits->maxfilesize && dsize > ctx->limits->maxfilesize) {
7135a8ff
 		cli_dbgmsg("Petite: Size exceeded (dsize: %u, max: %lu)\n", dsize, ctx->limits->maxfilesize);
5ede41fa
 		free(section_hdr);
e6bea1aa
 		free(exe_sections);
125845b5
 		if(BLOCKMAX) {
605b8cf0
 		    *ctx->virname = "PE.Petite.ExceededFileSize";
125845b5
 		    return CL_VIRUS;
 		} else {
 		    return CL_CLEAN;
 		}
5ede41fa
 	    }
 
 	    if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
 		cli_dbgmsg("Petite: Can't allocate %d bytes\n", dsize);
 		free(section_hdr);
e6bea1aa
 		free(exe_sections);
5ede41fa
 		return CL_EMEM;
 	    }
 
 	    for(i = 0 ; i < nsections; i++) {
65ab8d96
 		if(section_hdr[i].SizeOfRawData) {
e6bea1aa
 		  uint32_t offset = cli_rawaddr(EC32(section_hdr[i].VirtualAddress), exe_sections, nsections, &err, fsize);
65ab8d96
 
d7903e09
 		    if(err || lseek(desc, offset, SEEK_SET) == -1 || (unsigned int) cli_readn(desc, dest + EC32(section_hdr[i].VirtualAddress) - min, EC32(section_hdr[i].SizeOfRawData)) != EC32(section_hdr[i].SizeOfRawData)) {
65ab8d96
 			free(section_hdr);
e6bea1aa
 			free(exe_sections);
65ab8d96
 			free(dest);
 			return CL_EIO;
 		    }
 		}
5ede41fa
 	    }
 
dc4c26f6
 	    if(!(tempfile = cli_gentemp(NULL))) {
 	      free(dest);
 	      free(section_hdr);
e6bea1aa
 	      free(exe_sections);
dc4c26f6
 	      return CL_EMEM;
 	    }
764dab55
 
ac2888aa
 	    if((ndesc = open(tempfile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) {
5ede41fa
 		cli_dbgmsg("Petite: Can't create file %s\n", tempfile);
 		free(tempfile);
 		free(section_hdr);
e6bea1aa
 		free(exe_sections);
5ede41fa
 		free(dest);
 		return CL_EIO;
 	    }
 
65ab8d96
 	    /* aCaB: Fixed to allow petite v2.1 unpacking (last section is a ghost) */
e6bea1aa
 	    if (!petite_inflate2x_1to9(dest, min, max - min, section_hdr,
aa816b56
 		    nsections - (found == 1 ? 1 : 0), EC32(optional_hdr32.ImageBase),
e6bea1aa
 		    vep, ndesc, found, EC32(optional_hdr32.DataDirectory[2].VirtualAddress),
aa816b56
 		    EC32(optional_hdr32.DataDirectory[2].Size))) {
e6bea1aa
 	        cli_dbgmsg("Petite: Unpacked and rebuilt executable saved in %s\n", tempfile);
 		cli_dbgmsg("***** Scanning rebuilt PE file *****\n");
 		free(dest);
 		fsync(ndesc);
 		lseek(ndesc, 0, SEEK_SET);
 		if(cli_magic_scandesc(ndesc, ctx) == CL_VIRUS) {
 		    free(section_hdr);
 		    free(exe_sections);
 		    close(ndesc);
 		    if(!cli_leavetemps_flag) {
 		        unlink(tempfile);
 		    }
5ede41fa
 		    free(tempfile);
e6bea1aa
 		    return CL_VIRUS;
5ede41fa
 		}
 
e6bea1aa
 	    } else {
 	        cli_dbgmsg("Petite: Unpacking failed\n");
 		free(dest);
 	    }
5ede41fa
 	    close(ndesc);
 	    if(!cli_leavetemps_flag) {
e6bea1aa
 	        unlink(tempfile);
5ede41fa
 	    }
e6bea1aa
 	    free(tempfile);
5ede41fa
 	}
     }
 
7c53d74b
     /* PESpin 1.1 */
 
4a30feab
     if((DCONF & PE_CONF_PESPIN) && nsections > 1 &&
e6bea1aa
        vep >= EC32(section_hdr[nsections - 1].VirtualAddress) &&
        vep < EC32(section_hdr[nsections - 1].VirtualAddress) + EC32(section_hdr[nsections - 1].SizeOfRawData) - 0x3217 - 4 &&
7c53d74b
        memcmp(buff+4, "\xe8\x00\x00\x00\x00\x8b\x1c\x24\x83\xc3", 10) == 0)  {
 
25eaae24
 	    char *spinned;
 
ce4d0aa2
 	if(ctx->limits && ctx->limits->maxfilesize && fsize > ctx->limits->maxfilesize) {
 	    cli_dbgmsg("PEspin: Size exceeded (fsize: %u, max: %lu)\n", fsize, ctx->limits->maxfilesize);
             free(section_hdr);
e6bea1aa
 	    free(exe_sections);
ce4d0aa2
 	    if(BLOCKMAX) {
 		*ctx->virname = "PE.Pespin.ExceededFileSize";
 		return CL_VIRUS;
 	    } else {
 		return CL_CLEAN;
 	    }
 	}
7c53d74b
 
764dab55
 	if((spinned = (char *) cli_malloc(fsize)) == NULL) {
7c53d74b
 	    free(section_hdr);
e6bea1aa
 	    free(exe_sections);
7c53d74b
 	    return CL_EMEM;
 	}
 
 	lseek(desc, 0, SEEK_SET);
d7903e09
 	if((size_t) cli_readn(desc, spinned, fsize) != fsize) {
764dab55
 	    cli_dbgmsg("PESpin: Can't read %d bytes\n", fsize);
7c53d74b
 	    free(spinned);
 	    free(section_hdr);
e6bea1aa
 	    free(exe_sections);
7c53d74b
 	    return CL_EIO;
 	}
 
dc4c26f6
 	if(!(tempfile = cli_gentemp(NULL))) {
 	  free(spinned);
 	  free(section_hdr);
e6bea1aa
 	  free(exe_sections);
dc4c26f6
 	  return CL_EMEM;
 	}
764dab55
 
ac2888aa
 	if((ndesc = open(tempfile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) {
7c53d74b
 	    cli_dbgmsg("PESpin: Can't create file %s\n", tempfile);
 	    free(tempfile);
 	    free(spinned);
 	    free(section_hdr);
e6bea1aa
 	    free(exe_sections);
7c53d74b
 	    return CL_EIO;
 	}
 
e6bea1aa
 	switch(unspin(spinned, fsize, section_hdr, nsections - 1, vep, ndesc, ctx)) {
ce4d0aa2
 	case 0:
7c53d74b
 	    free(spinned);
ce4d0aa2
 	    if(cli_leavetemps_flag)
 		cli_dbgmsg("PESpin: Unpacked and rebuilt executable saved in %s\n", tempfile);
 	    else
 		cli_dbgmsg("PESpin: Unpacked and rebuilt executable\n");
7c53d74b
 	    fsync(ndesc);
 	    lseek(ndesc, 0, SEEK_SET);
605b8cf0
 	    if(cli_magic_scandesc(ndesc, ctx) == CL_VIRUS) {
7c53d74b
 		close(ndesc);
ce4d0aa2
 		if(!cli_leavetemps_flag)
7c53d74b
 		    unlink(tempfile);
ce4d0aa2
 	        free(tempfile);
 		free(section_hdr);
e6bea1aa
 		free(exe_sections);
7c53d74b
 		return CL_VIRUS;
 	    }
ce4d0aa2
 	    close(ndesc);
    	    if(!cli_leavetemps_flag)
 		unlink(tempfile);
 	    break;
 	case 1:
7c53d74b
 	    free(spinned);
ce4d0aa2
 	    close(ndesc);
 	    unlink(tempfile);
7c53d74b
 	    cli_dbgmsg("PESpin: Rebuilding failed\n");
ce4d0aa2
 	    break;
 	case 2:
 	    free(spinned);
 	    close(ndesc);
7c53d74b
 	    unlink(tempfile);
ce4d0aa2
 	    cli_dbgmsg("PESpin: Size exceeded\n");
 	    if(BLOCKMAX) {
 		free(tempfile);
 		free(section_hdr);
e6bea1aa
 		free(exe_sections);
ce4d0aa2
 		*ctx->virname = "PE.Pespin.ExceededFileSize";
 		return CL_VIRUS;
 	    }
7c53d74b
 	}
ce4d0aa2
 	free(tempfile);
 	
7c53d74b
     }
 
dfad2d4d
 
     /* yC 1.3 */
 
4a30feab
     if((DCONF & PE_CONF_YC) && nsections > 1 &&
dfad2d4d
        EC32(optional_hdr32.AddressOfEntryPoint) == EC32(section_hdr[nsections - 1].VirtualAddress) + 0x60 &&
        memcmp(buff, "\x55\x8B\xEC\x53\x56\x57\x60\xE8\x00\x00\x00\x00\x5D\x81\xED\x6C\x28\x40\x00\xB9\x5D\x34\x40\x00\x81\xE9\xC6\x28\x40\x00\x8B\xD5\x81\xC2\xC6\x28\x40\x00\x8D\x3A\x8B\xF7\x33\xC0\xEB\x04\x90\xEB\x01\xC2\xAC", 51) == 0)  {
 
 	    char *spinned;
 
764dab55
 	if ( fsize >= EC32(section_hdr[nsections - 1].PointerToRawData) + 0xC6 + 0xb97 ) { /* size check on yC sect */
 	  if((spinned = (char *) cli_malloc(fsize)) == NULL) {
dfad2d4d
 	    free(section_hdr);
e6bea1aa
 	    free(exe_sections);
dfad2d4d
 	    return CL_EMEM;
 	  }
 
 	  lseek(desc, 0, SEEK_SET);
d7903e09
 	  if((size_t) cli_readn(desc, spinned, fsize) != fsize) {
764dab55
 	    cli_dbgmsg("yC: Can't read %d bytes\n", fsize);
dfad2d4d
 	    free(spinned);
 	    free(section_hdr);
e6bea1aa
 	    free(exe_sections);
dfad2d4d
 	    return CL_EIO;
 	  }
764dab55
 
dc4c26f6
 	  if(!(tempfile = cli_gentemp(NULL))) {
 	    free(spinned);
 	    free(section_hdr);
e6bea1aa
 	    free(exe_sections);
dc4c26f6
 	    return CL_EMEM;
 	  }
764dab55
 
ac2888aa
 	  if((ndesc = open(tempfile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) {
dfad2d4d
 	    cli_dbgmsg("yC: Can't create file %s\n", tempfile);
 	    free(tempfile);
 	    free(spinned);
 	    free(section_hdr);
e6bea1aa
 	    free(exe_sections);
dfad2d4d
 	    return CL_EIO;
 	  }
764dab55
 
 	  if(!yc_decrypt(spinned, fsize, section_hdr, nsections-1, e_lfanew, ndesc)) {
dfad2d4d
 	    free(spinned);
 	    cli_dbgmsg("yC: Unpacked and rebuilt executable saved in %s\n", tempfile);
 	    fsync(ndesc);
 	    lseek(ndesc, 0, SEEK_SET);
 	    
605b8cf0
 	    if(cli_magic_scandesc(ndesc, ctx) == CL_VIRUS) {
dfad2d4d
 	      free(section_hdr);
e6bea1aa
 	      free(exe_sections);
dfad2d4d
 	      close(ndesc);
 	      if(!cli_leavetemps_flag) {
 		unlink(tempfile);
 		free(tempfile);
 	      } else {
 		free(tempfile);
 	      }
 	      return CL_VIRUS;
 	    }
 	    
 	  } else {
 	    free(spinned);
 	    cli_dbgmsg("yC: Rebuilding failed\n");
 	  }
 	  
 	  close(ndesc);
 	  if(!cli_leavetemps_flag) {
 	    unlink(tempfile);
 	    free(tempfile);
 	  } else {
 	    free(tempfile);
 	  }
 
 	}
     }
 
46db9ea5
 
dc4c26f6
     /* WWPack */
 
4a30feab
     if((DCONF & PE_CONF_WWPACK) && nsections > 1 &&
e6bea1aa
        exe_sections[nsections-1].raw>0x2b1 &&
        vep == exe_sections[nsections - 1].rva &&
        exe_sections[nsections - 1].rva + exe_sections[nsections - 1].rsz == max &&
dc4c26f6
        memcmp(buff, "\x53\x55\x8b\xe8\x33\xdb\xeb", 7) == 0 &&
        memcmp(buff+0x68, "\xe8\x00\x00\x00\x00\x58\x2d\x6d\x00\x00\x00\x50\x60\x33\xc9\x50\x58\x50\x50", 19) == 0)  {
e6bea1aa
       uint32_t headsize=exe_sections[nsections - 1].raw;
dc4c26f6
       char *dest, *wwp;
 
e6bea1aa
       for(i = 0 ; i < (unsigned int)nsections-1; i++)
 	if (!err && exe_sections[i].raw<headsize) headsize=exe_sections[i].raw;
dc4c26f6
       
e6bea1aa
       dsize = max-min+headsize-exe_sections[nsections - 1].rsz;
dc4c26f6
 
       if(ctx->limits && ctx->limits->maxfilesize && dsize > ctx->limits->maxfilesize) {
 	cli_dbgmsg("WWPack: Size exceeded (dsize: %u, max: %lu)\n", dsize, ctx->limits->maxfilesize);
 	free(section_hdr);
e6bea1aa
 	free(exe_sections);
dc4c26f6
 	if(BLOCKMAX) {
 	  *ctx->virname = "PE.WWPack.ExceededFileSize";
 	  return CL_VIRUS;
 	} else {
 	  return CL_CLEAN;
 	}
       }
 
       if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
 	cli_dbgmsg("WWPack: Can't allocate %d bytes\n", dsize);
 	free(section_hdr);
e6bea1aa
 	free(exe_sections);
dc4c26f6
 	return CL_EMEM;
       }
       memset(dest, 0, dsize);
 
       lseek(desc, 0, SEEK_SET);
d7903e09
       if((size_t) cli_readn(desc, dest, headsize) != headsize) {
dc4c26f6
 	cli_dbgmsg("WWPack: Can't read %d bytes from headers\n", headsize);
 	free(dest);
 	free(section_hdr);
e6bea1aa
 	free(exe_sections);
dc4c26f6
 	return CL_EIO;
       }
 
46db9ea5
       for(i = 0 ; i < (unsigned int)nsections-1; i++) {
e6bea1aa
 	if(exe_sections[i].rsz) {
 	  uint32_t offset = exe_sections[i].raw;
dc4c26f6
 	  
e6bea1aa
 	  if(err || lseek(desc, offset, SEEK_SET) == -1 || (unsigned int) cli_readn(desc, dest + headsize + exe_sections[i].rva - min, exe_sections[i].rsz) != exe_sections[i].rsz) {
dc4c26f6
 	    free(dest);
 	    free(section_hdr);
e6bea1aa
 	    free(exe_sections);
dc4c26f6
 	    return CL_EIO;
 	  }
 	}
       }
 
e6bea1aa
       if((wwp = (char *) cli_calloc(exe_sections[nsections - 1].rsz, sizeof(char))) == NULL) {
 	cli_dbgmsg("WWPack: Can't allocate %d bytes\n", exe_sections[nsections - 1].rsz);
dc4c26f6
 	free(dest);
 	free(section_hdr);
e6bea1aa
 	free(exe_sections);
dc4c26f6
 	return CL_EMEM;
       }
 
e6bea1aa
       lseek(desc, exe_sections[nsections - 1].raw, SEEK_SET);
       if((size_t) cli_readn(desc, wwp, exe_sections[nsections - 1].rsz) != exe_sections[nsections - 1].rsz) {
 	cli_dbgmsg("WWPack: Can't read %d bytes from wwpack sect\n", exe_sections[nsections - 1].rsz);
dc4c26f6
 	free(dest);
 	free(wwp);
 	free(section_hdr);
e6bea1aa
 	free(exe_sections);
dc4c26f6
 	return CL_EIO;
       }
 
e6bea1aa
       if (!wwunpack(dest, dsize, headsize, min, exe_sections[nsections-1].rva, e_lfanew, wwp, exe_sections[nsections - 1].rsz, nsections-1)) {
dc4c26f6
 	
 	free(wwp);
 
bf37ec7f
 	if(!(tempfile = cli_gentemp(NULL))) {
 	  free(dest);
 	  free(section_hdr);
e6bea1aa
 	  free(exe_sections);
dc4c26f6
 	  return CL_EMEM;
bf37ec7f
 	}
dc4c26f6
 
ac2888aa
 	if((ndesc = open(tempfile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) {
dc4c26f6
 	  cli_dbgmsg("WWPack: Can't create file %s\n", tempfile);
 	  free(tempfile);
 	  free(dest);
 	  free(section_hdr);
e6bea1aa
 	  free(exe_sections);
dc4c26f6
 	  return CL_EIO;
 	}
 
 	if((unsigned int) write(ndesc, dest, dsize) != dsize) {
24481e0f
 	  cli_dbgmsg("WWPack: Can't write %d bytes\n", dsize);
dc4c26f6
 	  close(ndesc);
 	  free(tempfile);
 	  free(dest);
 	  free(section_hdr);
e6bea1aa
 	  free(exe_sections);
dc4c26f6
 	  return CL_EIO;
 	}
 
 	free(dest);
24481e0f
 	if (cli_leavetemps_flag)
 	  cli_dbgmsg("WWPack: Unpacked and rebuilt executable saved in %s\n", tempfile);
 	else
 	  cli_dbgmsg("WWPack: Unpacked and rebuilt executable\n");
 
dc4c26f6
 	fsync(ndesc);
 	lseek(ndesc, 0, SEEK_SET);
 
 	if(cli_magic_scandesc(ndesc, ctx) == CL_VIRUS) {
 	  free(section_hdr);
e6bea1aa
 	  free(exe_sections);
dc4c26f6
 	  close(ndesc);
 	  if(!cli_leavetemps_flag)
 	    unlink(tempfile);
 	  free(tempfile);
 	  return CL_VIRUS;
 	}
 
 	close(ndesc);
 	if(!cli_leavetemps_flag)
 	  unlink(tempfile);
 	free(tempfile);
       } else {
 	free(wwp);
 	free(dest);
 	cli_dbgmsg("WWPpack: Decompression failed\n");
       }
     }
 
25eaae24
     /* NsPack */
 
4a30feab
     while (DCONF & PE_CONF_NSPACK) {
e6bea1aa
       uint32_t eprva = vep;
       uint32_t start_of_stuff, ssize, dsize, rep = ep;
25eaae24
       unsigned int nowinldr;
e6bea1aa
       char nbuff[24];
       char *src=buff, *dest;
25eaae24
       FILE *asd;
 
       if (*buff=='\xe9') { /* bitched headers */
e6bea1aa
 	eprva = cli_readint32(buff+1)+vep+5;
 	if (!(rep = cli_rawaddr(eprva, exe_sections, nsections, &err, fsize)) && err) break;
 	if (lseek(desc, rep, SEEK_SET)==-1) break;
 	if (cli_readn(desc, nbuff, 24)!=24) break;
 	src = nbuff;
25eaae24
       }
 
e6bea1aa
       if (memcmp(src, "\x9c\x60\xe8\x00\x00\x00\x00\x5d\xb8\x07\x00\x00\x00", 13)) break;
25eaae24
 
e6bea1aa
       nowinldr = 0x54-cli_readint32(src+17);
25eaae24
       cli_dbgmsg("NsPack: Found *start_of_stuff @delta-%x\n", nowinldr);
 
e6bea1aa
       if (lseek(desc, rep-nowinldr, SEEK_SET)==-1) break;
       if (cli_readn(desc, nbuff, 4)!=4) break;
       start_of_stuff=rep+cli_readint32(nbuff);
25eaae24
       if (lseek(desc, start_of_stuff, SEEK_SET)==-1) break;
e6bea1aa
       if (cli_readn(desc, nbuff, 20)!=20) break;
       src = nbuff;
       if (!cli_readint32(nbuff)) {
25eaae24
 	start_of_stuff+=4; /* FIXME: more to do */
 	src+=4;
       }
 
       ssize = cli_readint32(src+5)|0xff;
       dsize = cli_readint32(src+9);
 
       if(ctx->limits && ctx->limits->maxfilesize && (ssize > ctx->limits->maxfilesize || dsize > ctx->limits->maxfilesize)) {
 	cli_dbgmsg("NsPack: Size exceeded\n");
 	free(section_hdr);
e6bea1aa
 	free(exe_sections);
25eaae24
 	if(BLOCKMAX) {
 	  *ctx->virname = "PE.NsPack.ExceededFileSize";
 	  return CL_VIRUS;
 	} else {
 	  return CL_CLEAN;
 	}
       }
 
e6bea1aa
       if ( !ssize || !dsize || dsize != exe_sections[0].vsz) break;
25eaae24
       if (lseek(desc, start_of_stuff, SEEK_SET)==-1) break;
       if (!(dest=cli_malloc(dsize))) break;
       /* memset(dest, 0xfc, dsize); */
 
       if (!(src=cli_malloc(ssize))) {
 	free(dest);
 	break;
       }
       /* memset(src, 0x00, ssize); */
       cli_readn(desc, src, ssize);
 
       eprva+=0x27a;
e6bea1aa
       if (!(rep = cli_rawaddr(eprva, exe_sections, nsections, &err, fsize)) && err) break;
       if (lseek(desc, rep, SEEK_SET)==-1) break;
       if (cli_readn(desc, nbuff, 5)!=5) break;
       eprva=eprva+5+cli_readint32(nbuff+1);
25eaae24
       cli_dbgmsg("NsPack: OEP = %08x\n", eprva);
 
       if(!(tempfile = cli_gentemp(NULL))) {
 	free(src);
 	free(dest);
 	free(section_hdr);
e6bea1aa
 	free(exe_sections);
25eaae24
 	return CL_EMEM;
       }
 
       if((ndesc = open(tempfile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) {
 	cli_dbgmsg("NsPack: Can't create file %s\n", tempfile);
 	free(tempfile);
 	free(src);
 	free(dest);
 	free(section_hdr);
e6bea1aa
 	free(exe_sections);
25eaae24
 	return CL_EIO;
       }
 
e6bea1aa
       if (!unspack(src, dest, ctx, exe_sections[0].rva, EC32(optional_hdr32.ImageBase), eprva, ndesc)) {
25eaae24
 	free(src);
 	free(dest);
 	if (cli_leavetemps_flag)
 	  cli_dbgmsg("NsPack: Unpacked and rebuilt executable saved in %s\n", tempfile);
 	else
 	  cli_dbgmsg("NsPack: Unpacked and rebuilt executable\n");
 	fsync(ndesc);
 	lseek(ndesc, 0, SEEK_SET);
 
 	if(cli_magic_scandesc(ndesc, ctx) == CL_VIRUS) {
 	  free(section_hdr);
e6bea1aa
 	  free(exe_sections);
25eaae24
 	  close(ndesc);
 	  if(!cli_leavetemps_flag) unlink(tempfile);
 	  free(tempfile);
 	  return CL_VIRUS;
 	}
       } else {
 	free(src);
 	free(dest);
 	cli_dbgmsg("NsPack: Unpacking failed\n");
       }
       close(ndesc);
       if(!cli_leavetemps_flag) unlink(tempfile);
       free(tempfile);
       break;
     }
dc4c26f6
 
e60810eb
     /* to be continued ... */
 
e3886d61
     free(section_hdr);
e6bea1aa
     free(exe_sections);
f2eb2372
     return CL_CLEAN;
e60810eb
 }
e263999b
 
1ec94c6b
 int cli_peheader(int desc, struct cli_exe_info *peinfo)
e263999b
 {
 	uint16_t e_magic; /* DOS signature ("MZ") */
 	uint32_t e_lfanew; /* address of new exe header */
e6bea1aa
 	/* Obsolete - see below
 	  uint32_t min = 0, max = 0;
 	*/
e263999b
 	struct pe_image_file_hdr file_hdr;
e6bea1aa
 	union {
 	    struct pe_image_optional_hdr64 opt64;
 	    struct pe_image_optional_hdr32 opt32;
 	} pe_opt;
e263999b
 	struct pe_image_section_hdr *section_hdr;
 	struct stat sb;
 	int i;
aa816b56
 	unsigned int err, pe_plus = 0;
e6bea1aa
 	uint32_t valign, falign;
 	size_t fsize;
e263999b
 
     cli_dbgmsg("in cli_peheader\n");
 
e6bea1aa
     if(fstat(desc, &sb) == -1) {
 	cli_dbgmsg("fstat failed\n");
 	return -1;
     }
 
     fsize = sb.st_size;
 
d7903e09
     if(cli_readn(desc, &e_magic, sizeof(e_magic)) != sizeof(e_magic)) {
e263999b
 	cli_dbgmsg("Can't read DOS signature\n");
 	return -1;
     }
 
     if(EC16(e_magic) != IMAGE_DOS_SIGNATURE && EC16(e_magic) != IMAGE_DOS_SIGNATURE_OLD) {
 	cli_dbgmsg("Invalid DOS signature\n");
 	return -1;
     }
 
     lseek(desc, 58, SEEK_CUR); /* skip to the end of the DOS header */
 
d7903e09
     if(cli_readn(desc, &e_lfanew, sizeof(e_lfanew)) != sizeof(e_lfanew)) {
e263999b
 	cli_dbgmsg("Can't read new header address\n");
 	/* truncated header? */
 	return -1;
     }
 
     e_lfanew = EC32(e_lfanew);
     if(!e_lfanew) {
 	cli_dbgmsg("Not a PE file\n");
 	return -1;
     }
 
     if(lseek(desc, e_lfanew, SEEK_SET) < 0) {
 	/* probably not a PE file */
 	cli_dbgmsg("Can't lseek to e_lfanew\n");
 	return -1;
     }
 
d7903e09
     if(cli_readn(desc, &file_hdr, sizeof(struct pe_image_file_hdr)) != sizeof(struct pe_image_file_hdr)) {
e263999b
 	/* bad information in e_lfanew - probably not a PE file */
 	cli_dbgmsg("Can't read file header\n");
 	return -1;
     }
 
     if(EC32(file_hdr.Magic) != IMAGE_NT_SIGNATURE) {
 	cli_dbgmsg("Invalid PE signature (probably NE file)\n");
 	return -1;
     }
 
aa816b56
     peinfo->nsections = EC16(file_hdr.NumberOfSections);
 
e6bea1aa
     if (EC16(file_hdr.SizeOfOptionalHeader) < sizeof(struct pe_image_optional_hdr32)) {
         cli_dbgmsg("SizeOfOptionalHeader too small\n");
 	return -1;
     }
 
     if(cli_readn(desc, &optional_hdr32, sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr32)) {
         cli_dbgmsg("Can't read optional file header\n");
 	return -1;
     }
 
     if(EC32(optional_hdr64.Magic)==PE32P_SIGNATURE) {
         if(EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr64)) {
 	    cli_dbgmsg("Incorrect SizeOfOptionalHeader for PE32+\n");
aa816b56
 	    return -1;
 	}
e6bea1aa
 	pe_plus = 1;
e263999b
     }
 
aa816b56
     if(!pe_plus) { /* PE */
e8c965b2
 	cli_dbgmsg("File format: PE\n");
e6bea1aa
 	if (EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr32)) {
 	    /* Seek to the end of the long header */
 	    lseek(desc, (EC16(file_hdr.SizeOfOptionalHeader)-sizeof(struct pe_image_optional_hdr32)), SEEK_CUR);
 	}
aa816b56
 
e6bea1aa
     } else { /* PE+ */
         if(cli_readn(desc, &optional_hdr32 + 1, sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) {
 	    cli_dbgmsg("Can't read optional file header\n");
aa816b56
 	    return -1;
 	}
e6bea1aa
 
 	cli_dbgmsg("File format: PE32+\n");
e263999b
     }
 
e6bea1aa
     valign = (pe_plus)?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment);
     falign = (pe_plus)?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment);
 
1ec94c6b
     peinfo->section = (struct cli_exe_section *) cli_calloc(peinfo->nsections, sizeof(struct cli_exe_section));
e263999b
 
856d9c84
     if(!peinfo->section) {
e263999b
 	cli_dbgmsg("Can't allocate memory for section headers\n");
 	return -1;
     }
 
856d9c84
     section_hdr = (struct pe_image_section_hdr *) cli_calloc(peinfo->nsections, sizeof(struct pe_image_section_hdr));
e263999b
 
     if(!section_hdr) {
 	cli_dbgmsg("Can't allocate memory for section headers\n");
856d9c84
 	free(peinfo->section);
54c0fba0
 	peinfo->section = NULL;
e263999b
 	return -1;
     }
 
856d9c84
     for(i = 0; i < peinfo->nsections; i++) {
e263999b
 
d7903e09
 	if(cli_readn(desc, &section_hdr[i], sizeof(struct pe_image_section_hdr)) != sizeof(struct pe_image_section_hdr)) {
e263999b
 	    cli_dbgmsg("Can't read section header\n");
 	    cli_dbgmsg("Possibly broken PE file\n");
 	    free(section_hdr);
856d9c84
 	    free(peinfo->section);
54c0fba0
 	    peinfo->section = NULL;
e263999b
 	    return -1;
 	}
 
e6bea1aa
 	peinfo->section[i].rva = PEALIGN(EC32(section_hdr[i].VirtualAddress), valign);
 	peinfo->section[i].vsz = PESALIGN(EC32(section_hdr[i].VirtualSize), valign);
 	peinfo->section[i].raw = PEALIGN(EC32(section_hdr[i].PointerToRawData), falign);
 	peinfo->section[i].rsz = PESALIGN(EC32(section_hdr[i].SizeOfRawData), falign);
 	if (peinfo->section[i].rsz && !CLI_ISCONTAINED(0, (uint32_t) fsize, peinfo->section[i].raw, peinfo->section[i].rsz))
 	    peinfo->section[i].rsz = (fsize - peinfo->section[i].raw)*(fsize>peinfo->section[i].raw);
e263999b
 
e6bea1aa
 	/* cli_rawaddr now handles the whole process space
 	 * TO BE REMOVED
6eb8dbe9
 	if(!i) {
e6bea1aa
 	    min = peinfo->section[i].rva;
 	    max = peinfo->section[i].rva + peinfo->section[i].rsz;
6eb8dbe9
 	} else {
 	    if(EC32(section_hdr[i].VirtualAddress) < min)
 		min = EC32(section_hdr[i].VirtualAddress);
 
 	    if(EC32(section_hdr[i].VirtualAddress) + EC32(section_hdr[i].SizeOfRawData) > max)
 		max = EC32(section_hdr[i].VirtualAddress) + EC32(section_hdr[i].SizeOfRawData);
 	}
e6bea1aa
 	*/
6eb8dbe9
     }
a8b53539
 
aa816b56
     if(pe_plus)
 	peinfo->ep = EC32(optional_hdr64.AddressOfEntryPoint);
     else
 	peinfo->ep = EC32(optional_hdr32.AddressOfEntryPoint);
 
e6bea1aa
     if(!(peinfo->ep = cli_rawaddr(peinfo->ep, peinfo->section, peinfo->nsections, &err, fsize)) && err) {
 #ifdef ACAB_REGRESSION
 	peinfo->ep = 0x7fffffff;
 #else
 	cli_dbgmsg("Broken PE file\n");
e263999b
 	free(section_hdr);
856d9c84
 	free(peinfo->section);
54c0fba0
 	peinfo->section = NULL;
e263999b
 	return -1;
e6bea1aa
 #endif /* ACAB_REGRESSION */
e263999b
     }
 
     free(section_hdr);
     return 0;
 }