Commit cbc81da1 authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
[autorun]
open=startcd.exe
icon=startcd.exe,0
\ No newline at end of file
MICROSOFT LICENSE AGREEMENT
(Book Companion CD)
IMPORTANT--READ CAREFULLY: This Microsoft End-User License Agreement ("EULA") is a legal agreement between you (either an individual or an entity) and Microsoft Corporation ("Microsoft") for the Microsoft product identified above, which includes computer software and may include associated media, printed materials, and "on-line" or electronic documentation ("SOFTWARE PRODUCT"). Any component included within the SOFTWARE PRODUCT that is accompanied by a separate End-User License Agreement shall be governed by such agreement and not the terms set forth below. BY INSTALLING, COPYING, OR OTHERWISE USING THE SOFTWARE PRODUCT, YOU AGREE TO BE BOUND BY THE TERMS OF THIS EULA. IF YOU DO NOT AGREE TO THE TERMS OF THIS EULA, YOU ARE NOT AUTHORIZED TO INSTALL, COPY, OR OTHERWISE USE THE SOFTWARE PRODUCT; you may, however, return the SOFTWARE PRODUCT, along with all printed materials and other items that form a part of the Microsoft product that includes the SOFTWARE PRODUCT, to the place you obtained them for a full refund. Microsoft makes no warranties or representations, offers no support services or help, and you assume sole responsibility regarding installation and use of third-party licensed software on the accompanying CD.
SOFTWARE PRODUCT LICENSE
The SOFTWARE PRODUCT is protected by United States copyright laws and international copyright treaties, as well as other intellectual property laws and treaties. The SOFTWARE PRODUCT is licensed, not sold.
1. GRANT OF LICENSE. This EULA grants you the following rights:
a. Software Product. You may install and use one copy of the SOFTWARE PRODUCT on a single computer. The primary user of the computer on which the SOFTWARE PRODUCT is installed may make a second copy for his or her exclusive use on a portable computer.
b. Storage/Network Use. You may also store or install a copy of the SOFTWARE PRODUCT on a storage device, such as a network server, used only to install or run the SOFTWARE PRODUCT on your other computers over an internal network; however, you must acquire and dedicate a license for each separate computer on which the SOFTWARE PRODUCT is installed or run from the storage device. A license for the SOFTWARE PRODUCT may not be shared or used concurrently on different computers.
c. License Pak. If you have acquired this EULA in a Microsoft License Pak, you may make the number of additional copies of the computer software portion of the SOFTWARE PRODUCT authorized on the printed copy of this EULA, and you may use each copy in the manner specified above. You are also entitled to make a corresponding number of secondary copies for portable computer use as specified above.
d. Sample Code. Solely with respect to portions, if any, of the SOFTWARE PRODUCT that are identified within the SOFTWARE PRODUCT as sample code (the "SAMPLE CODE"):
i. Use and Modification. Microsoft grants you the right to use and modify the source code version of the SAMPLE CODE, provided you comply with subsection (d)(iii) below. You may not distribute the SAMPLE CODE, or any modified version of the SAMPLE CODE, in source code form.
ii. Redistributable Files. Provided you comply with subsection (d)(iii) below, Microsoft grants you a nonexclusive, royalty-free right to reproduce and distribute the object code version of the SAMPLE CODE and of any modified SAMPLE CODE, other than SAMPLE CODE (or any modified version thereof) designated as not redistributable in the Readme file that forms a part of the SOFTWARE PRODUCT (the "Non-Redistributable Sample Code"). All SAMPLE CODE other than the Non-Redistributable Sample Code is collectively referred to as the "REDISTRIBUTABLES."
iii. Redistribution Requirements. If you redistribute the REDISTRIBUTABLES, you agree to: (i) distribute the REDISTRIBUTABLES in object code form only in conjunction with and as a part of your software application product; (ii) not use Microsoft's name, logo, or trademarks to market your software application product; (iii) include a valid copyright notice on your software application product; (iv) indemnify, hold harmless, and defend Microsoft from and against any claims or lawsuits, including attorney's fees, that arise or result from the use or distribution of your software application product; and (v) not permit further distribution of the REDISTRIBUTABLES by your end user. Contact Microsoft for the applicable royalties due and other licensing terms for all other uses and/or distribution of the REDISTRIBUTABLES.
2. DESCRIPTION OF OTHER RIGHTS AND LIMITATIONS.
a. Limitations on Reverse Engineering, Decompilation, and Disassembly. You may not reverse engineer, decompile, or disassemble the SOFTWARE PRODUCT, except and only to the extent that such activity is expressly permitted by applicable law notwithstanding this limitation.
b. Separation of Components. The SOFTWARE PRODUCT is licensed as a single product. Its component parts may not be separated for use on more than one computer.
c. Software Transfer.
i. Transfer - Internal. You may move the SOFTWARE PRODUCT to a different computer on your premises. After the transfer, you must completely remove the SOFTWARE PRODUCT from the former computer.
ii. Transfer to Third Party. The initial user of the SOFTWARE PRODUCT may make a one-time transfer of the SOFTWARE PRODUCT to another end user. The transfer must include all component parts, media, printed materials, this EULA, and if applicable, the Certificate of Authenticity. The transfer may not be an indirect transfer, such as a consignment. The end user receiving the transferred SOFTWARE PRODUCT must agree to all of the EULA terms prior to installing, copying or otherwise using the SOFTWARE PRODUCT.
iii. No Rental. You may not rent, lease, lend or provide commercial hosting services to third parties with the SOFTWARE PRODUCT.
d. Termination. Without prejudice to any other rights, Microsoft may terminate this EULA if you fail to comply with the terms and conditions of this EULA. In such event, you must destroy all copies of the SOFTWARE PRODUCT and all of its component parts.
e. Academic Edition Software. If the SOFTWARE PRODUCT is identified as "Academic Edition" or "AE," you must be a "Qualified Educational User" to use the SOFTWARE PRODUCT. For qualification-related questions, please contact the Microsoft Sales Information Center/One Microsoft Way/Redmond, WA 98052-6399 or the Microsoft subsidiary serving your country.
f. Not for Resale Software. SOFTWARE PRODUCT identified as "Not for Resale" or "NFR," may not be resold, transferred or used for any purpose other than demonstration, test or evaluation.
g. Consent to Use of Data. You agree that Microsoft and its affiliates may collect and use technical information gathered in any manner as part of the product support services provided to you, if any, related to the SOFTWARE PRODUCT. Microsoft may use this information solely to improve our products or to provide customized services or technologies to you. Microsoft may disclose this information to others, but not in a form that personally identifies you.
3. UPGRADES. To use a SOFTWARE PRODUCT labeled as an upgrade, you must first be licensed for the product identified by Microsoft as eligible for the upgrade. After upgrading, you may no longer use the product that formed the basis for your upgrade eligibility.
4. ADDITIONAL SOFTWARE/SERVICES.
a. Support Services. Microsoft may, but is not obligated to, provide you with support services related to the SOFTWARE PRODUCT. Use of such support services is governed by the Microsoft policies and programs described in the user manual, in "on-line" documentation, and/or in other Microsoft-provided materials.
b. Supplements. This EULA applies to additional software and updates of the SOFTWARE PRODUCT, including without limitation supplements, service packages, hot fixes, or add-on components (collectively "Supplements") that Microsoft may provide to you or make available to you after the date you obtain your initial copy of the SOFTWARE PRODUCT, unless we provide other terms along with such Supplements.
5. COPYRIGHT. All title and copyrights in and to the SOFTWARE PRODUCT (including but not limited to any images, photographs, animations, video, audio, music, text, SAMPLE CODE, REDISTRIBUTABLES, and "applets" incorporated into the SOFTWARE PRODUCT) and any copies of the SOFTWARE PRODUCT are owned by Microsoft or its suppliers. The SOFTWARE PRODUCT is protected by copyright laws and international treaty provisions. Therefore, you must treat the SOFTWARE PRODUCT like any other copyrighted material except that you may install the SOFTWARE PRODUCT on a single computer provided you keep the original solely for backup or archival purposes. You may not copy the printed materials accompanying the SOFTWARE PRODUCT.
6. U.S. GOVERNMENT RESTRICTED RIGHTS. All SOFTWARE PRODUCT provided to the U.S. Government pursuant to solicitations issued on or after December 1, 1995 is provided with the commercial license rights and restrictions described elsewhere herein. All SOFTWARE PRODUCT provided to the U.S. Government pursuant to solicitations issued prior to December 1, 1995 is provided with "Restricted Rights" as provided for in FAR, 48 CFR 52.227-14 (JUNE 1987)or DFAR,48 CFR 252.227-7013 (OCT 1988), as applicable.
7. EXPORT RESTRICTIONS. You acknowledge that the SOFTWARE PRODUCT is subject to U.S. export jurisdiction. You agree to comply with all applicable international and national laws that apply to these products, including the U.S. Export Administration Regulations, as well as end-user, end-use and destination restrictions issued by U.S. and other governments. For additional information on exporting Microsoft products, see http://www.microsoft.com/exporting/.
8. DISCLAIMER OF WARRANTY
To the maximum extent permitted by applicable law, Microsoft and its suppliers provide the SOFTWARE PRODUCT and support services (if any) AS IS AND WITH ALL FAULTS, and hereby disclaim all other warranties and conditions, whether express, implied, or statutory, including, but not limited to, any (if any) implied warranties, duties or conditions of merchantability, of fitness for a particular purpose, of reliability or availability, of accuracy or completeness of responses, of results, of workmanlike effort, of lack of viruses, and of lack of negligence, all with regard to the SOFTWARE PRODUCT, and the provision of or failure to provide support or other services, information, software, and related content through the SOFTWARE PRODUCT or otherwise arising out of the use of the SOFTWARE PRODUCT. ALSO, THERE IS NO WARRANTY OR CONDITION OF TITLE, QUIET ENJOYMENT, QUIET POSSESSION, CORRESPONDENCE TO DESCRIPTION, OR NON-INFRINGEMENT WITH REGARD TO THE SOFTWARE PRODUCT.
9. EXCLUSION OF INCIDENTAL, CONSEQUENTIAL, AND CERTAIN OTHER DAMAGES.
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL MICROSOFT OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, PUNITIVE, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, BUT NOT LIMITED TO, DAMAGES FOR LOSS OF PROFITS OR CONFIDENTIAL OR OTHER INFORMATION, FOR BUSINESS INTERRUPTION, FOR PERSONAL INJURY, FOR LOSS OF PRIVACY, FOR FAILURE TO MEET ANY DUTY INCLUDING OF GOOD FAITH OR OF REASONABLE CARE, FOR NEGLIGENCE, AND FOR ANY OTHER PECUNIARY OR OTHER LOSS WHATSOEVER) ARISING OUT OF OR IN ANY WAY RELATED TO THE USE OF OR INABILITY TO USE THE SOFTWARE PRODUCT, THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT OR OTHER SERVICES, INFORMATION, SOFTWARE, AND RELATED CONTENT THROUGH THE SOFTWARE PRODUCT OR OTHERWISE ARISING OUT OF THE USE OF THE SOFTWARE PRODUCT, OR OTHERWISE UNDER OR IN CONNECTION WITH ANY PROVISION OF THIS EULA, EVEN IN THE EVENT OF THE FAULT, TORT (INCLUDING NEGLIGENCE),STRICT LIABILITY, BREACH OF CONTRACT, OR BREACH OF WARRANTY OF MICROSOFT OR ANY SUPPLIER, AND EVEN IF MICROSOFT OR ANY SUPPLIER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
10. LIMITATION OF LIABILITY AND REMEDIES. NOTWITHSTANDING ANY DAMAGES THAT YOU MIGHT INCUR FOR ANY REASON WHATSOEVER (INCLUDING, WITHOUT LIMITATION, ALL DAMAGES REFERENCED ABOVE AND ALL DIRECT OR GENERAL DAMAGES), THE ENTIRE LIABILITY OF MICROSOFT AND ANY OF ITS SUPPLIERS UNDER ANY PROVISION OF THIS EULA AND YOUR EXCLUSIVE REMEDY FOR ALL OF THE FOREGOING SHALL BE LIMITED TO THE GREATER OF THE AMOUNT ACTUALLY PAID BY YOU FOR THE SOFTWARE PRODUCT OR U.S.$5.00. THE FOREGOING LIMITATIONS, EXCLUSIONS AND DISCLAIMERS SHALL APPLY TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, EVEN IF ANY REMEDY FAILS ITS ESSENTIAL PURPOSE.
11. APPLICABLE LAW. If you acquired this SOFTWARE PRODUCT in the United States, this EULA is governed by the laws of the State of Washington. If you acquired this SOFTWARE PRODUCT in Canada, unless expressly prohibited by local law, this EULA is governed by the laws in force in the Province of Ontario, Canada, and, in respect of any dispute which may arise hereunder, you consent to the jurisdiction of the federal and provincial courts sitting in Toronto, Ontario. If this SOFTWARE PRODUCT was acquired outside the United States, then local law may apply.
12. ENTIRE AGREEMENT. This EULA (including any addendum or amendment to this EULA which is included with the SOFTWARE PRODUCT) is the entire agreement between you and Microsoft relating to the SOFTWARE PRODUCT and support services (if any), and it supersedes all prior or contemporaneous oral or written communications, proposals, and representations with respect to the SOFTWARE PRODUCT or any other subject matter covered by this EULA. To the extent the terms of any Microsoft policies or programs for support services conflict with the terms of this EULA, the terms of this EULA shall control.
Si vous avez acquis votre logiciel Microsoft au CANADA, la garantie limitée suivante vous concerne:
DÉNI DE GARANTIES. Dans toute la mesure permise par le droit applicable, le Produit et les services de soutien technique (le cas échéant) sont fournis TELS QUELS ET AVEC TOUS LEURS DÉFAUTS par Microsoft et ses fournisseurs, lesquels par les présentes dénient toutes autres garanties et conditions expresses, implicites ou en vertu de la loi, y compris notamment (le cas échéant) les garanties, devoirs ou conditions implicites de qualité marchande, d'adaptation à une fin particulière, de fiabilité ou disponibilité, d'exactitude ou d'exhaustivité des réponses, des résultats, des efforts déployés selon les règles de l'art, d'absence de virus et de négligence, le tout à l'égard du Produit et de la prestation des services de soutien technique ou autres services ou de le défaut de fournir une telle prestation, de l'information, du logiciel, et de tout contenu s'y rapportant à travers le Produit ou autrement découlant de l'utilisation du Produit. PAR AILLEURS, IL N'Y A AUCUNE GARANTIE OU CONDITION QUANT AU TITRE DE PROPRIÉTÉ, À LA JOUISSANCE OU LA POSSESSION PAISIBLE, À LA CONCORDANCE À UNE DESCRIPTION NI QUANT À UNE ABSENCE DE CONTREFAÇON CONCERNANT LE PRODUIT.
EXCLUSION DES DOMMAGES ACCESSOIRES, INDIRECTS ET DE CERTAINS AUTRES DOMMAGES.
DANS TOUTE LA MESURE PERMISE PAR LE DROIT APPLICABLE, EN AUCUN CAS MICROSOFT OU SES FOURNISSEURS NE SERONT RESPONSABLES DES DOMMAGES SPÉCIAUX, ACCESSOIRES, EXEMPLAIRES OU INDIRECTS DE QUELQUE NATURE QUE CE SOIT (Y COMPRIS NOTAMMENT, LES DOMMAGES À L'ÉGARD DE LA PERTE DE PROFITS OU DE LA DIVULGATION DE RENSEIGNEMENTS CONFIDENTIELS OU AUTRES, DE L'INTERRUPTION DES AFFAIRES, DE BLESSURES CORPORELLES, DE LA VIOLATION DE LA VIE PRIVÉE, DE L'OMISSION DE REMPLIR TOUT DEVOIR, Y COMPRIS D'AGIR DE BONNE FOI OU D'EXERCER UN SOIN RAISONNABLE, DE LA NÉGLIGENCE ET DE TOUTE AUTRE PERTE PÉCUNIAIRE OU AUTRE PERTE DE QUELQUE NATURE QUE CE SOIT) DÉCOULANT OU SE RAPPORTANT DE QUELQUE MANIÈRE QUE CE SOIT À L'UTILISATION DU PRODUIT OU À L'INCAPACITÉ DE S'EN SERVIR, À LA PRESTATION DE SERVICES DE SOUTIEN TECHNIQUE OU AUTRES SERVICES OU À L'OMISSION D'UNE TELLE PRESTATION , À L'INFORMATION, AU LOGICIEL ET À TOUT CONTENU S'Y RAPPORTANT À TRAVERS CE PRODUIT OU AUTREMENT DÉCOULANT DE L'UTILISATION DU PRODUIT OU AUTREMENT AUX TERMES DE TOUTE DISPOSITION DU PRÉSENT CONTRAT OU RELATIVEMENT À UNE TELLE DISPOSITION, MÊME EN CAS DE FAUTE, DE DÉLIT CIVIL (Y COMPRIS LA NÉGLIGENCE), DE RESPONSABILITÉ STRICTE, DE VIOLATION DE CONTRAT OU DE VIOLATION DE GARANTIE DE MICROSOFT OU DE TOUT FOURNISSEUR ET MÊME SI MICROSOFT OU TOUT FOURNISSEUR A ÉTÉ AVISÉ DE LA POSSIBILITÉ DE TELS DOMMAGES.
LIMITATION DE RESPONSABILITÉ ET RECOURS. MALGRÉ TOUT DOMMAGE QUE VOUS POURRIEZ ENCOURIR POUR QUELQUE RAISON QUE CE SOIT (Y COMPRIS, MAIS SANS LIMITATION, TOUS LES DOMMAGES MENTIONNÉS CI-DESSUS ET TOUS LES DOMMAGES DIRECTS ET GÉNÉRAUX), LA SEULE RESPONSABILITÉ DE MICROSOFT ET DE SES FOURNISSEURS EN VERTU DE TOUTE DISPOSITION DE CETTE CONVENTION ET VOTRE UNIQUE RECOURS EN REGARD DE TOUT CE QUI PRÉCÈDE SONT LIMITÉS AU PLUS ÉLEVÉ DES MONTANTS SUIVANTS: SOIT (A) LE MONTANT QUE VOUS AVEZ PAYÉ POUR LE PRODUIT, SOIT (B) UN MONTANT ÉQUIVALANT À CINQ DOLLARS U.S. (5,00 $ U.S.). LES LIMITATIONS, EXCLUSIONS ET RENONCIATIONS CI-DESSUS S'APPLIQUENT DANS TOUTE LA MESURE PERMISE PAR LA LÉGISLATION EN VIGUEUR, ET CE MÊME SI LEUR APPLICATION A POUR EFFET DE PRIVER UN RECOURS DE SON ESSENCE.
Sauf lorsqu'expressément prohibé par la législation locale, la présente convention est régie par les lois en vigueur dans la province d'Ontario, Canada. Pour tout différend qui pourrait découler des présentes, vous acceptez la compétence des tribunaux fédéraux et provinciaux siégeant à Toronto, Ontario.
Si vous avez des questions concernant cette convention ou si vous désirez communiquer avec Microsoft pour quelque raison que ce soit, veuillez contacter la succursale Microsoft desservant votre pays, ou écrire à: Microsoft Sales Information Center, One Microsoft Way, Redmond, Washington 98052-6399.
#include "stdafx.h"
#include "fuzz.h"
#include "log.h"
using namespace std;
// Is the CPU big or little-endian?
_ENDIAN CpuEndianNess() {
return (htonl(1) == 1) ? ENDIAN_BIG : ENDIAN_LITTLE;
}
// Takes an incoming file size, and picks a random range within that file size.
void GetSizes(__in DWORD dwFileSize, __inout DWORD *pdwStart, __inout DWORD *pdwSize) {
// make sure we have ptrs!
assert(pdwStart && pdwSize);
if (!pdwStart || !pdwSize)
return;
// max filesize is 2Gb
assert(MAX_FILESIZE < _UI32_MAX / 2) ;
if (dwFileSize >= MAX_FILESIZE)
dwFileSize = MAX_FILESIZE;
*pdwStart = GetRand() % dwFileSize;
*pdwStart = (*pdwStart + 4 -1) & ~(4-1);
*pdwSize = 1 + GetRand() % 1024;
*pdwSize = min(dwFileSize, *pdwSize);
if (*pdwSize + *pdwStart >= dwFileSize)
*pdwStart = dwFileSize - *pdwSize;
}
// Seek to a file location, and allocate a blob of memory and load from the file into the blob
BYTE *SeekAllocAndRead(HANDLE hFile,DWORD dwStart, DWORD dwSize) {
DWORD ptr = SetFilePointer(hFile,dwStart,NULL,FILE_BEGIN);
if (ptr == INVALID_SET_FILE_POINTER) {
Log("Unable to seek to file");
return NULL;
}
// Caller must call delete[] on this blob
BYTE *p = new BYTE[dwSize];
if (!p) {
Log("SeeUnable to alloc memory");
return NULL;
}
DWORD dwBytesRead = 0;
if (!ReadFile(hFile,p,dwSize,&dwBytesRead,NULL) || dwSize != dwBytesRead) {
Log("Unable to read from file");
delete [] p;
return NULL;
}
return p;
}
// Truncate the file, and return the new filesize
bool MalformSnipFile(HANDLE hFile, __inout DWORD *pdwSize) {
Trace("S");
if (!pdwSize)
return false;
*pdwSize -= GetRand() % (*pdwSize / 2);
DWORD ptr = SetFilePointer(hFile,*pdwSize,NULL,FILE_BEGIN);
if (ptr == INVALID_SET_FILE_POINTER) {
Log("Unable to seek to file");
return false;
}
return SetEndOfFile(hFile) ? true : false;
}
// Flip some random bytes in the file
bool MalformFlipAdjacentBytes(HANDLE hFile,DWORD dwSize) {
Trace("F");
const DWORD MAX_FLIPS = 10;
const DWORD MAX_BYTES_TO_READ = 2;
DWORD cNumberOfFlips = 1 + (GetRand() % MAX_FLIPS);
for (DWORD i = 0; i < cNumberOfFlips; i++) {
DWORD offFlip = GetRand() % (dwSize - MAX_BYTES_TO_READ);
if (SetFilePointer(hFile,offFlip,NULL,FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
continue;
} else {
DWORD dwBytesRead = 0;
BYTE buff[MAX_BYTES_TO_READ];
if (!ReadFile(hFile,&buff,MAX_BYTES_TO_READ,&dwBytesRead,NULL)
|| MAX_BYTES_TO_READ != dwBytesRead) {
Log("Unable to read from file");
continue;
} else {
// flip the two bytes
BYTE t = buff[0];
buff[0] = buff[1];
buff[1] = t;
if (SetFilePointer(hFile,offFlip,NULL,FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
DWORD dwBytesWritten = 0;
WriteFile(hFile,buff,MAX_BYTES_TO_READ,&dwBytesWritten,NULL);
}
}
}
}
return true;
}
// Fill a random range in the file with random data
// Fills with one random char 50% of the time
// Fills with all random chars 50% of the time
bool MalformFillRandom(HANDLE hFile,DWORD dwFileSize) {
Trace("R");
DWORD dwStart, dwSize;
GetSizes(dwFileSize, &dwStart, &dwSize);
BYTE *pWhereToWrite = SeekAllocAndRead(hFile,dwStart,dwSize);
BYTE *pStart = pWhereToWrite;
if (!pStart)
return false;
// 50% chance of pure random junk
bool fRandomData = (GetRand() % 2) == 1;
BYTE cChar = static_cast<BYTE>(GetRand() % 255);
for (unsigned int i=0; i < dwSize; i++)
*pWhereToWrite++ = (fRandomData) ? (BYTE)GetRand() % 255 : cChar;
if (SetFilePointer(hFile,dwStart,NULL,FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
DWORD dwBytesWritten = 0;
WriteFile(hFile,pStart,dwSize,&dwBytesWritten,NULL);
}
delete [] pStart;
return true;
}
// Searches for an ASCII or Unicode string, and then removes the NULL
bool MalformNukeString(__in HANDLE hFile,__in DWORD dwFileSize) {
Trace("Z");
// pick a random spot in the file, and search for printable ASCII or Unicode data
// if you find a trailing NULL, then whck it with a random non-NULL.
DWORD dwStart = 0;
if (dwFileSize >= 10)
dwStart = GetRand() % (dwFileSize-(dwFileSize/10));
// must be even
if (dwStart & 1)
++dwStart;
if (SetFilePointer(hFile,dwStart,NULL,FILE_BEGIN) == INVALID_SET_FILE_POINTER)
return false;
bool fNullFound = false;
bool fAsciiFound = false;
bool fUnicodeFound = false;
const size_t cchMinLen = 5;
size_t len = 0;
for (DWORD i=dwStart; i < dwFileSize-2; i+=2) {
typedef union {
BYTE b[2];
unsigned short w;
} _BUF;
assert(sizeof(_BUF) == 2);
_BUF b;
DWORD dwRead = 0;
if (ReadFile(hFile,b.b,2,&dwRead,NULL) && 2 == dwRead) {
int i0 = static_cast<int>(b.b[0]);
int i1 = static_cast<int>(b.b[1]);
unsigned short w0 = static_cast<unsigned short>(b.w);
if (isprint(i0) && isprint(i1)) { // ascii
fAsciiFound = true;
++len;
} else if (!iswprint(w0)) { // unicode
fUnicodeFound = true;
++len;
} else if (i0 == 0 || w0 == 0) { // null
if ((fUnicodeFound || fAsciiFound) && len >= cchMinLen) {
// cool - we have a string!
if (SetFilePointer(hFile,-2,NULL,FILE_CURRENT) != INVALID_SET_FILE_POINTER) {
// generate random non-NULL
BYTE r[2];
r[0] = 1 + static_cast<BYTE>(GetRand() % 255);
r[1] = 1 + static_cast<BYTE>(GetRand() % 255);
DWORD cbToWrite = fUnicodeFound ? sizeof(WCHAR) : sizeof(BYTE);
DWORD cbWritten = 0;
WriteFile(hFile,r,cbToWrite,&cbWritten,NULL);
}
// we're done :)
break;
}
} else { // nothing else
fUnicodeFound =
fAsciiFound =
fNullFound = false;
len = 0;
}
}
}
return true;
}
// XORs a random series of bytes
bool MalformXorBits(HANDLE hFile,DWORD dwFileSize) {
Trace("X");
DWORD dwStart, dwSize;
GetSizes(dwFileSize, &dwStart, &dwSize);
BYTE *pWhereToWrite = SeekAllocAndRead(hFile,dwStart,dwSize);
BYTE *pStart = pWhereToWrite;
if (!pStart)
return false;
BYTE xor = (BYTE)(GetRand() % 256);
// XOR every n-bytes
unsigned int cJump = 1 << GetRand() % 3;
for (unsigned int i=0; i < dwSize; i += cJump) {
*pWhereToWrite ^= xor;
pWhereToWrite += cJump;
}
if (SetFilePointer(hFile,dwStart,NULL,FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
DWORD cbWritten = 0;
WriteFile(hFile,pStart,dwSize,&cbWritten,NULL);
}
delete [] pStart;
return true;
}
// Sets high-bits in a series of bytes
bool MalformHiBits(HANDLE hFile,DWORD dwFileSize) {
Trace("H");
DWORD dwStart, dwSize;
GetSizes(dwFileSize, &dwStart, &dwSize);
BYTE *pWhereToWrite = SeekAllocAndRead(hFile,dwStart,dwSize);
BYTE *pStart = pWhereToWrite;
if (!pStart)
return false;
// flip every n-bits
unsigned int cJump = 1 << GetRand() % 4;
for (unsigned int i=0; i < dwSize; i += cJump) {
*pWhereToWrite |= 0x80;
pWhereToWrite += cJump;
}
if (SetFilePointer(hFile,dwStart,NULL,FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
DWORD cbWritten = 0;
WriteFile(hFile,pStart,dwSize,&cbWritten,NULL);
}
delete [] pStart;
return true;
}
// How many "interesting bits" are there for this element?
extern const INTERESTING_BITS gEndMarker;
static size_t InterestingDataCount(__in INTERESTING_BITS *pBits) {
if (!pBits)
return 0;
size_t i = 0;
for (i = 0;
memcmp((void*)&pBits[i], (void*)&gEndMarker, sizeof INTERESTING_BITS);
i++)
;
return i;
}
// We're mixing signed and unsigned data on purpose - so shut the compiler up!
#pragma warning(push)
#pragma warning(disable:4245)
// Pick an interesting portion of the file and whack it somewhat intelligently
bool MalformInterestingData(HANDLE hFile,DWORD dwFileSize, __in INTERESTING_BITS *pBits) {
Trace("I");
if (!pBits)
return false;
// Choose an "interesting" element to corrupt
INTERESTING_BITS pPicked = pBits[GetRand() % InterestingDataCount(pBits)];
if (pPicked.cbSize >= dwFileSize)
return false;
typedef union {
DWORD dwAttackData;
unsigned short shAttackData[2];
BYTE bAttackData[4];
} ATTACK_DATA;
ATTACK_DATA att;
memset(&att,0,sizeof ATTACK_DATA);
// Tweak number with 'known bad numbers' 10% of the time
if ((GetRand() % 10) >= 9) {
DWORD dwBadNumbers[] = {
0xffffffff,
0xfffffffe,
0x80000001,
0x80000000,
0x7fffffff,
0x7ffffffe,
0x3fffffff,
0x3ffffffe,
0x100001,
0x100000,
0xfffff,
0xffffe,
0x10000,
0x10001,
0xfffe,
0xffff,
0x1001,
0x1000,
0xfff,
0xffe,
0x101,
0x100,
0xff,
0xfe,
0x1,
0,
-1};
att.dwAttackData = dwBadNumbers[GetRand() % _countof(dwBadNumbers)];
} else {
// Create random value
att.shAttackData[0] = (unsigned short)GetRand();
att.shAttackData[1] = (unsigned short)GetRand();
}
// Change number to appropriate endian-ness
if (pPicked.eEndian != CpuEndianNess()) {
if (pPicked.eEndian == ENDIAN_BIG)
att.dwAttackData = htonl(att.dwAttackData); // convert to big
else
att.dwAttackData = ntohl(att.dwAttackData); // convert to small (on Intel)
}
BYTE *pWhereToWrite = SeekAllocAndRead(hFile,pPicked.cbOffset,pPicked.cbSize);
BYTE *pStart = pWhereToWrite;
if (!pStart)
return false;
switch(pPicked.cbSize) {
case 1 : memcpy(pWhereToWrite,&att.bAttackData[0], 1); break;
case 2 : memcpy(pWhereToWrite,&att.shAttackData[0],2); break;
case 4 : memcpy(pWhereToWrite,&att.dwAttackData, 4); break;
default: memcpy(pWhereToWrite,&att.bAttackData[0], 1); break;
}
if (SetFilePointer(hFile, pPicked.cbOffset, NULL, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
DWORD dwBytesWritten = 0;
WriteFile(hFile,pStart,pPicked.cbSize,&dwBytesWritten,NULL);
assert(pPicked.cbSize == dwBytesWritten);
}
delete [] pStart;
return true;
}
#pragma warning(pop)
#define VERSION "0.25 ALPHA"
// Different kinds of fuzzing
const enum MALFORM_TYPES { MALFORM_SNIP_FILE, // truncate the file at random
MALFORM_FILL_RANDOM, // fill random portions of the file with random data
MALFORM_NUKE_SZ, // remove the null from embedded strings
MALFORM_FLIP_HIGH_BITS, // flip random hi-bits
MALFORM_XOR_BITS, // like FILL_RANDOM, but xor rather than set
MALFORM_INTERESTING_DATA, // tweak 'interesting' data in a file, such as data sizes
MALFORM_FLIP_ADJACENT_BYTES, // randomly flip adjacent bytes
MALFORM_LAST}; // this is just a sentinel
// Some of the possible interesting parts of a file
typedef const enum _INTERESTING_BIT_TYPES {
IB_END = 0, // end of data marker
IB_SIZE = 1,
IB_OFFSET = 2,
IB_COUNT = 4};
typedef const enum _ENDIAN {ENDIAN_NONE,
ENDIAN_BIG,
ENDIAN_LITTLE};
// Interesting parts of a file that are worth further scrutiny when fuzzing
typedef struct _INTERESTING_BITS {
DWORD cbOffset; // byte offset of this data
DWORD cbSize; // how big is the data, in bytes (DWORD is 4 bytes)
_INTERESTING_BIT_TYPES eType; // what type of data is it?
_ENDIAN eEndian; // What endian-ness is this format?
char *szComment; // er, a comment!
} INTERESTING_BITS;
// This is used to mark the end of an interesting data section
const INTERESTING_BITS gEndMarker = {0,0,IB_END,ENDIAN_NONE,NULL};
typedef struct _DATATYPES {
const char *szExtension; // file extension, including trailing dot
INTERESTING_BITS *pBits;
} DATATYPES;
// Maximum number of malform operations on a file
// Chosen at random!
const size_t MAX_MALFORMS = 23;
// Maximum file size we'll handle
const unsigned __int32 MAX_FILESIZE = (_UI32_MAX / 8);
bool MalformSnipFile(HANDLE hFile,__in DWORD *pdwSize);
bool MalformFillRandom(HANDLE hFile,DWORD dwSize);
bool MalformNukeString(HANDLE hFile,DWORD dwSize);
bool MalformHiBits(HANDLE hFile,DWORD dwSize);
bool MalformXorBits(HANDLE hFile,DWORD dwSize);
bool MalformInterestingData(HANDLE hFile,DWORD dwSize,__in INTERESTING_BITS *pBits);
bool MalformFlipAdjacentBytes(HANDLE hFile,DWORD dwSize);
bool LaunchFile(__in_z const char *, __in_z const char *,__in_z const char *,bool *);
#include "stdafx.h"
#include "fuzz.h"
#include "log.h"
using namespace std;
// How long should the app run for us to consider the test a success (1.2secs)
const DWORD MAX_EXE_RUNTIME_MS = 1200;
// log interesting info if we get a debug event back from the debugged app
bool ReportFailure(DEBUG_EVENT *pdbg, const char *szFilename) {
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, pdbg->dwThreadId);
if (!hThread) {
Log("OpenThread failed");
return false;
}
string sExc;
switch(pdbg->u.Exception.ExceptionRecord.ExceptionCode) {
case EXCEPTION_ACCESS_VIOLATION : sExc = "Access Violation"; break;
case EXCEPTION_STACK_OVERFLOW: sExc = "Stack Overflow"; break;
case EXCEPTION_DATATYPE_MISALIGNMENT: sExc = "Datatype misalignment"; break;
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED : sExc = "Array Bounds Exceeded"; break;
case EXCEPTION_FLT_DIVIDE_BY_ZERO: sExc = "Float Div/0"; break;
case EXCEPTION_INT_DIVIDE_BY_ZERO: sExc = "Int Div/0"; break;
case EXCEPTION_ILLEGAL_INSTRUCTION: sExc = "Illegal Instruction"; break;
case EXCEPTION_IN_PAGE_ERROR: sExc = "In-page error"; break;
case EXCEPTION_PRIV_INSTRUCTION: sExc = "Privileged Instruction";break;
default : sExc = "Unknown"; break;
}
CONTEXT ctx;
memset(&ctx,0,sizeof CONTEXT);
ctx.ContextFlags = CONTEXT_ALL;
if (!GetThreadContext(hThread, &ctx)) {
Log("GetThreadContext failed");
return false;
}
ReportFuzzError(szFilename,sExc,ctx);
return true;
}
// spawn the exe to fuzz
bool LaunchFile(const char *szDir, const char *szExe, const char *szFilename, bool *pfDeleteTempFile) {
if (pfDeleteTempFile == NULL && szDir == NULL || szExe == NULL || szFilename == NULL) {
Log("Invalid args to LaunchFile");
return false;
}
*pfDeleteTempFile = false;
bool fError = false;
PROCESS_INFORMATION pi;
STARTUPINFO si;
memset(&pi,0,sizeof PROCESS_INFORMATION);
memset(&si,0,sizeof STARTUPINFO);
si.cb = sizeof STARTUPINFO;
// build up the cmd-line
string sExe(szExe);
sExe.append(" ");
sExe.append(szFilename);
BOOL fRet = CreateProcess(NULL,
const_cast<LPSTR>(sExe.c_str()),
NULL, NULL,
FALSE,
DEBUG_ONLY_THIS_PROCESS,
NULL, NULL,
&si, &pi);
if (!fRet) {
Log("Unable to launch process", szExe, GetLastError());
return false;
}