clamav-devel/libclamav/pdf.c
d056cc17
 /*
  *  Copyright (C) 2005 Nigel Horne <njh@bandsman.co.uk>
  *
  *  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
48b7b4a7
  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  *  MA 02110-1301, USA.
d056cc17
  */
48b7b4a7
 static	char	const	rcsid[] = "$Id: pdf.c,v 1.47 2006/04/09 19:59:27 kojm Exp $";
d056cc17
 
 #if HAVE_CONFIG_H
 #include "clamav-config.h"
 #endif
 
77a9730c
 #include "clamav.h"
8b6f8404
 #include "others.h"
77a9730c
 
240d3307
 #if HAVE_MMAP
 #if HAVE_SYS_MMAN_H
 #include <sys/mman.h>
 #else /* HAVE_SYS_MMAN_H */
 #undef HAVE_MMAP
 #endif
 #endif
 
8b6f8404
 #if HAVE_MMAP
240d3307
 #include <stdio.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <ctype.h>
 #include <string.h>
 #include <fcntl.h>
 #include <stdlib.h>
 #include <limits.h>
511a59c7
 #include <errno.h>
240d3307
 
 #ifdef HAVE_ZLIB_H
 #include <zlib.h>
 #endif
 
 #include "table.h"
 #include "mbox.h"
826bc6c1
 #include "blob.h"
654c0b96
 #include "pdf.h"
ff7d16a7
 #include "md5.h"
240d3307
 
4c32a40d
 static	int	flatedecode(const unsigned char *buf, size_t len, int fout, const cli_ctx *ctx);
da653b74
 static	int	ascii85decode(const char *buf, size_t len, unsigned char *output);
bce73fe9
 static	const	char	*pdf_nextlinestart(const char *ptr, size_t len);
ef8219b8
 static	const	char	*pdf_nextobject(const char *ptr, size_t len);
ceabee13
 static	const	char	*cli_pmemstr(const char *haystack, size_t hs, const char *needle, size_t ns);
da653b74
 
144df7c1
 /*
  * TODO: handle embedded URLs if (options&CL_SCAN_MAILURL)
  */
d056cc17
 int
2c313298
 cli_pdf(const char *dir, int desc, const cli_ctx *ctx)
d056cc17
 {
240d3307
 	struct stat statb;
6c9dc98d
 	off_t size;	/* total number of bytes in the file */
bce73fe9
 	long bytesleft, trailerlength;
6c9dc98d
 	char *buf;	/* start of memory mapped area */
bce73fe9
 	const char *p, *q, *trailerstart;
6c9dc98d
 	const char *xrefstart;	/* cross reference table */
70502709
 	/*size_t xreflength;*/
550ee789
 	int rc = CL_CLEAN;
ff7d16a7
 	struct table *md5table;
240d3307
 
798308de
 	cli_dbgmsg("in cli_pdf()\n");
 
240d3307
 	if(fstat(desc, &statb) < 0)
 		return CL_EOPEN;
 
 	size = (size_t)statb.st_size;
 
 	if(size == 0)
 		return CL_CLEAN;
 
139823ca
 	if(size <= 7)	/* doesn't even include the file header */
 		return CL_EFORMAT;
 
240d3307
 	p = buf = mmap(NULL, size, PROT_READ, MAP_SHARED, desc, 0);
 	if(buf == MAP_FAILED)
 		return CL_EMEM;
 
6c9dc98d
 	cli_dbgmsg("cli_pdf: scanning %lu bytes\n", size);
0a097146
 
139823ca
 	/* Lines are terminated by \r, \n or both */
 
 	/* File Header */
 	if(memcmp(p, "%PDF-1.", 7) != 0) {
 		munmap(buf, size);
 		return CL_EFORMAT;
 	}
 
ef8219b8
 #if	0
 	q = pdf_nextlinestart(&p[6], size - 6);
bce73fe9
 	if(q == NULL) {
 		munmap(buf, size);
 		return CL_EFORMAT;
139823ca
 	}
6c9dc98d
 	bytesleft = size - (long)(q - p);
bce73fe9
 	p = q;
ef8219b8
 #else
 	p = &p[6];
 	bytesleft = size - 6;
 #endif
139823ca
 
 	/* Find the file trailer */
6c9dc98d
 	for(q = &p[bytesleft - 6]; q > p; --q)
139823ca
 		if(memcmp(q, "%%EOF", 5) == 0)
 			break;
 
 	if(q == p) {
 		munmap(buf, size);
 		return CL_EFORMAT;
 	}
 
b533a221
 	for(trailerstart = &q[-7]; trailerstart > p; --trailerstart)
bce73fe9
 		if(memcmp(trailerstart, "trailer", 7) == 0)
139823ca
 			break;
 
 	/*
bce73fe9
 	 * q points to the end of the trailer section
139823ca
 	 */
bce73fe9
 	trailerlength = (long)(q - trailerstart);
 	if(cli_pmemstr(trailerstart, trailerlength, "Encrypt", 7)) {
501e5d12
 		/*
 		 * This tends to mean that the file is, in effect, read-only
 		 */
 		munmap(buf, size);
6c9dc98d
 		cli_warnmsg("Encrypted PDF files not yet supported\n");
501e5d12
 		return CL_EFORMAT;
 	}
 
ef8219b8
 	/*
 	 * not true, since edits may put data after the trailer
bce73fe9
 	bytesleft -= trailerlength;
ef8219b8
 	 */
bce73fe9
 
76fb2ef1
 	/*
 	 * FIXME: Handle more than one xref section in the xref table
 	 */
6c9dc98d
 	for(xrefstart = trailerstart; xrefstart > p; --xrefstart)
 		if(memcmp(xrefstart, "xref", 4) == 0)
76fb2ef1
 			/*
 			 * Make sure it's the start of the line, not a startxref
 			 * token
 			 */
 			if((xrefstart[-1] == '\n') || (xrefstart[-1] == '\r'))
 				break;
6c9dc98d
 
 	if(xrefstart == p) {
 		munmap(buf, size);
 		return CL_EFORMAT;
 	}
 
ff7d16a7
 	md5table = tableCreate();
ef8219b8
 	/*
 	 * not true, since edits may put data after the trailer
70502709
 	xreflength = (size_t)(trailerstart - xrefstart);
6c9dc98d
 	bytesleft -= xreflength;
ef8219b8
 	 */
6c9dc98d
 
 	/*
ef8219b8
 	 * The body section consists of a sequence of indirect objects
6c9dc98d
 	 */
ef8219b8
 	while((p < xrefstart) && ((q = pdf_nextobject(p, bytesleft)) != NULL)) {
bce73fe9
 		int is_ascii85decode, is_flatedecode, fout, len;
d8ab9ddc
 		/*int object_number, generation_number;*/
6c9dc98d
 		const char *objstart, *objend, *streamstart, *streamend;
ff7d16a7
 		char *md5digest;
bce73fe9
 		size_t length, objlen, streamlen;
240d3307
 		char fullname[NAME_MAX + 1];
144df7c1
   
ef8219b8
 		if(q == xrefstart)
 			break;
 		if(memcmp(q, "xref", 4) == 0)
 			break;
616fd006
 
 		/*object_number = atoi(q);*/
 		bytesleft -= (q - p);
 		p = q;
 
 		if(memcmp(q, "endobj", 6) == 0)
 			continue;
ef8219b8
 		if(!isdigit(*q)) {
a5ade23c
 			cli_warnmsg("cli_pdf: Object number missing\n");
ef8219b8
 			rc = CL_EFORMAT;
 			break;
 		}
 		q = pdf_nextobject(p, bytesleft);
 		if((q == NULL) || !isdigit(*q)) {
a5ade23c
 			cli_warnmsg("cli_pdf: Generation number missing\n");
ef8219b8
 			rc = CL_EFORMAT;
 			break;
 		}
a5f514a4
 		/*generation_number = atoi(q);*/
ef8219b8
 		bytesleft -= (q - p);
 		p = q;
 
 		q = pdf_nextobject(p, bytesleft);
 		if((q == NULL) || (memcmp(q, "obj", 3) != 0)) {
 			cli_warnmsg("Indirect object missing \"obj\"\n");
 			rc = CL_EFORMAT;
 			break;
 		}
 
 		bytesleft -= (q - p) + 3;
 		objstart = p = &q[3];
6c9dc98d
 		objend = cli_pmemstr(p, bytesleft, "endobj", 6);
 		if(objend == NULL) {
ef8219b8
 			cli_dbgmsg("No matching endobj\n");
240d3307
 			break;
 		}
6c9dc98d
 		bytesleft -= (objend - p) + 6;
 		p = &objend[6];
 		objlen = (size_t)(objend - objstart);
240d3307
 
6c9dc98d
 		/* Is this object a stream? */
bce73fe9
 		streamstart = cli_pmemstr(objstart, objlen, "stream", 6);
 		if(streamstart == NULL)
 			continue;
240d3307
 
139823ca
 		length = is_ascii85decode = is_flatedecode = 0;
bce73fe9
 		/*
 		 * TODO: handle F and FFilter?
 		 */
9be10a55
 		q = objstart;
 		while(q < streamstart) {
ef8219b8
 			if(*q == '/') {	/* name object */
6c9dc98d
 				if(strncmp(++q, "Length ", 7) == 0) {
 					q += 7;
 					length = atoi(q);
 					while(isdigit(*q))
 						q++;
 					q--;
 				} else if(strncmp(q, "FlateDecode", 11) == 0) {
da653b74
 					is_flatedecode = 1;
6c9dc98d
 					q += 12;
 				} else if(strncmp(q, "ASCII85Decode", 12) == 0) {
da653b74
 					is_ascii85decode = 1;
6c9dc98d
 					q += 13;
240d3307
 				}
 			}
ef8219b8
 			q = pdf_nextobject(q, (size_t)(streamstart - q));
9be10a55
 			if(q == NULL)
 				break;
 		}
ce42a31a
 
6c9dc98d
 		/* objend points to the end of the object (start of "endobj") */
 		streamstart += 6;	/* go past the word "stream" */
 		len = (int)(objend - streamstart);
 		q = pdf_nextlinestart(streamstart, len);
 		if(q == NULL)
bce73fe9
 			break;
6c9dc98d
 		len -= (int)(q - streamstart);
 		streamstart = q;
 		streamend = cli_pmemstr(streamstart, len, "endstream\n", 10);
 		if(streamend == NULL) {
 			streamend = cli_pmemstr(streamstart, len, "endstream\r", 10);
 			if(streamend == NULL) {
0a097146
 				cli_dbgmsg("No endstream");
 				break;
 			}
240d3307
 		}
44399452
 		streamlen = (int)(streamend - streamstart) + 1;
 
 		if(streamlen == 0) {
 			cli_dbgmsg("Empty stream");
 			continue;
 		}
 
6c9dc98d
 		/*while(strchr("\r\n", *--streamend))
 			;*/
240d3307
 		snprintf(fullname, sizeof(fullname), "%s/pdfXXXXXX", dir);
 #if	defined(C_LINUX) || defined(C_BSD) || defined(HAVE_MKSTEMP) || defined(C_SOLARIS) || defined(C_CYGWIN)
 		fout = mkstemp(fullname);
 #else
 		(void)mktemp(fullname);
 		fout = open(fullname, O_WRONLY|O_CREAT|O_EXCL|O_TRUNC|O_BINARY, 0600);
 #endif
 
 		if(fout < 0) {
 			cli_errmsg("cli_pdf: can't create temporary file %s: %s\n", fullname, strerror(errno));
bbc4f890
 			rc = CL_ETMPFILE;
 			break;
240d3307
 		}
 
6c9dc98d
 		cli_dbgmsg("length %d, streamlen %d\n", length, streamlen);
bce73fe9
 
 #if	0
 		/* FIXME: this isn't right... */
 		if(length)
 			/*streamlen = (is_flatedecode) ? length : MIN(length, streamlen);*/
 			streamlen = MIN(length, streamlen);
 #endif
 
da653b74
 		if(is_ascii85decode) {
7158ca7e
 			unsigned char *tmpbuf = cli_malloc(streamlen * 5);
bce73fe9
 			int ret;
550ee789
 
1160fc1d
 			if(tmpbuf == NULL) {
b8705ec8
 				close(fout);
52a88dee
 				unlink(fullname);
 				rc = CL_EMEM;
1160fc1d
 				continue;
 			}
 
bce73fe9
 			ret = ascii85decode(streamstart, streamlen, tmpbuf);
bbc4f890
 
bce73fe9
 			if(ret == -1) {
da653b74
 				free(tmpbuf);
b8705ec8
 				close(fout);
52a88dee
 				unlink(fullname);
 				rc = CL_EFORMAT;
240d3307
 				continue;
 			}
44399452
 			if(ret) {
 				streamlen = (size_t)ret;
 				/* free unused trailing bytes */
 				tmpbuf = cli_realloc(tmpbuf, streamlen);
 				/*
 				 * Note that it will probably be both
 				 * ascii85encoded and flateencoded
 				 */
 				if(is_flatedecode) {
4c32a40d
 					const int zstat = flatedecode((unsigned char *)tmpbuf, streamlen, fout, ctx);
44399452
 
 					if(zstat != Z_OK)
 						rc = CL_EZIP;
ef8219b8
 				} else
 					cli_writen(fout, (char *)streamstart, streamlen);
550ee789
 			}
da653b74
 			free(tmpbuf);
 		} else if(is_flatedecode) {
4c32a40d
 			const int zstat = flatedecode((unsigned char *)streamstart, streamlen, fout, ctx);
240d3307
 
da653b74
 			if(zstat != Z_OK)
1160fc1d
 				rc = CL_EZIP;
240d3307
 		} else
80386ef0
 			cli_writen(fout, (char *)streamstart, streamlen);
240d3307
 
 		close(fout);
ff7d16a7
 		md5digest = cli_md5file(fullname);
 		if(tableFind(md5table, md5digest) >= 0) {
 			cli_dbgmsg("cli_pdf: not scanning duplicate embedded file '%s'\n", fullname);
 			unlink(fullname);
 		} else
 			tableInsert(md5table, md5digest, 1);
 		free(md5digest);
240d3307
 		cli_dbgmsg("cli_pdf: extracted to %s\n", fullname);
 	}
 
 	munmap(buf, size);
0a097146
 
ff7d16a7
 	tableDestroy(md5table);
 
bbc4f890
 	cli_dbgmsg("cli_pdf: returning %d\n", rc);
550ee789
 	return rc;
d056cc17
 }
da653b74
 
 /* flate inflation - returns zlib status, e.g. Z_OK */
 static int
4c32a40d
 flatedecode(const unsigned char *buf, size_t len, int fout, const cli_ctx *ctx)
da653b74
 {
 	int zstat;
4c32a40d
 	off_t nbytes;
da653b74
 	z_stream stream;
 	unsigned char output[BUFSIZ];
 
 	cli_dbgmsg("cli_pdf: flatedecode %lu bytes\n", len);
 
 	stream.zalloc = (alloc_func)Z_NULL;
 	stream.zfree = (free_func)Z_NULL;
 	stream.opaque = (void *)NULL;
 	stream.next_in = (unsigned char *)buf;
 	stream.avail_in = len;
501e5d12
 	stream.next_out = output;
 	stream.avail_out = sizeof(output);
da653b74
 
 	zstat = inflateInit(&stream);
 	if(zstat != Z_OK) {
 		cli_warnmsg("cli_pdf: inflateInit failed");
 		return zstat;
 	}
9f2bc4ca
 
4c32a40d
 	nbytes = 0;
9f2bc4ca
 
da653b74
 	for(;;) {
 		zstat = inflate(&stream, Z_NO_FLUSH);
 		switch(zstat) {
 			case Z_OK:
1160fc1d
 				if(stream.avail_out == 0) {
9f2bc4ca
 
4c32a40d
 					nbytes += cli_writen(fout, output, sizeof(output));
9f2bc4ca
 
4c32a40d
 					if(ctx->limits &&
 					   ctx->limits->maxfilesize &&
 					   (nbytes > (off_t) ctx->limits->maxfilesize)) {
 						cli_dbgmsg("cli_pdf: flatedecode size exceeded (%lu)\n", nbytes);
 						inflateEnd(&stream);
 #ifdef	notdef
 						*ctx->virname = "PDF.ExceededFileSize";
 #endif
 						return Z_DATA_ERROR;
 					}
1160fc1d
 					stream.next_out = output;
501e5d12
 					stream.avail_out = sizeof(output);
1160fc1d
 				}
da653b74
 				continue;
 			case Z_STREAM_END:
 				break;
 			default:
fb53f48e
 				if(stream.msg)
 					cli_warnmsg("Error \"%s\" inflating PDF attachment\n", stream.msg);
 				else
 					cli_warnmsg("Error %d inflating PDF attachment\n", zstat);
da653b74
 				inflateEnd(&stream);
 				return zstat;
 		}
 		break;
 	}
 
9f2bc4ca
 	if(stream.avail_out != sizeof(output))
 		(void)cli_writen(fout, output, sizeof(output) - stream.avail_out);
 
4c32a40d
 	cli_dbgmsg("cli_pdf: flatedecode in=%lu out=%lu ratio %ld (max %d)\n",
 		stream.total_in, stream.total_out,
 		stream.total_out / stream.total_in,
 		ctx->limits ? ctx->limits->maxratio : 0);
 
 	if(ctx->limits &&
 	   ctx->limits->maxratio &&
 	   ((stream.total_out / stream.total_in) > ctx->limits->maxratio)) {
 		cli_dbgmsg("cli_pdf: flatedecode Max ratio reached\n");
 		inflateEnd(&stream);
 #ifdef	notdef
 		*ctx->virname = "Oversized.PDF";
 #endif
 		return Z_DATA_ERROR;
 	}
2c313298
 
da653b74
 	return inflateEnd(&stream);
 }
 
 /* ascii85 inflation, returns number of bytes in output, -1 for error */
 static int
 ascii85decode(const char *buf, size_t len, unsigned char *output)
 {
 	const char *ptr = buf;
 	uint32_t sum = 0;
 	int quintet = 0;
 	int ret = 0;
 
 	cli_dbgmsg("cli_pdf: ascii85decode %lu bytes\n", len);
 
bce73fe9
 	while(len > 0) {
 		int byte = (len--) ? (int)*ptr++ : EOF;
da653b74
 
 		if((byte == '~') && (*ptr == '>'))
 			byte = EOF;
 
 		if(byte >= '!' && byte <= 'u') {
6c9dc98d
 			sum = sum * 85 + ((uint32_t)byte - '!');
da653b74
 			if(++quintet == 5) {
e8130f50
 				*output++ = (unsigned char)(sum >> 24);
 				*output++ = (unsigned char)((sum >> 16) & 0xFF);
 				*output++ = (unsigned char)((sum >> 8) & 0xFF);
 				*output++ = (unsigned char)(sum & 0xFF);
da653b74
 				ret += 4;
 				quintet = 0;
 				sum = 0;
 			}
 		} else if(byte == 'z') {
 			if(quintet) {
1160fc1d
 				cli_warnmsg("ascii85decode: unexpected 'z'\n");
da653b74
 				return -1;
 			}
 			*output++ = '\0';
 			*output++ = '\0';
 			*output++ = '\0';
 			*output++ = '\0';
 			ret += 4;
 		} else if(byte == EOF) {
 			if(quintet) {
 				int i;
 
 				if(quintet == 1) {
 					cli_warnmsg("ascii85Decode: only 1 byte in last quintet\n");
 					return -1;
 				}
6c9dc98d
 				sum *= 85 * (5 - quintet);
da653b74
 				if(quintet > 1)
 					sum += (0xFFFFFF >> ((quintet - 2) * 8));
 				ret += quintet;
 				for(i = 0; i < quintet - 1; i++)
e8130f50
 					*output++ = (unsigned char)((sum >> (24 - 8 * i)) & 0xFF);
da653b74
 				quintet = 0;
 			}
6c9dc98d
 			len = 0;
da653b74
 			break;
 		} else if(!isspace(byte)) {
6c9dc98d
 			cli_warnmsg("ascii85Decode: invalid character 0x%x, len %lu\n", byte & 0xFF, len);
da653b74
 			return -1;
 		}
 	}
 	return ret;
 }
bce73fe9
 
 /*
  * Find the start of the next line
  */
 static const char *
 pdf_nextlinestart(const char *ptr, size_t len)
 {
 	while(strchr("\r\n", *ptr) == NULL) {
 		if(--len == 0L)
 			return NULL;
 		ptr++;
 	}
 	while(strchr("\r\n", *ptr) != NULL) {
 		if(--len == 0L)
 			return NULL;
 		ptr++;
 	}
 	return ptr;
 }
9be10a55
 
ef8219b8
 /*
  * Return the start of the next PDF object.
  * This assumes that we're not in a stream.
  */
 static const char *
 pdf_nextobject(const char *ptr, size_t len)
 {
 	const char *p;
 	int inobject = 1;
 
 	while(len) {
 		switch(*ptr) {
 			case '\n':
 			case '\r':
 			case '%':	/* comment */
 				p = pdf_nextlinestart(ptr, len);
 				if(p == NULL)
 					return NULL;
 				len -= (size_t)(p - ptr);
 				ptr = p;
 				inobject = 0;
 				break;
 
9be10a55
 			case ' ':
 			case '\t':
ef8219b8
 			case '\v':
 			case '\f':
 				inobject = 0;
9be10a55
 				ptr++;
 				len--;
 				break;
 			default:
ef8219b8
 				if(!inobject)
 					/* TODO: parse and return object type */
9be10a55
 					return ptr;
 				ptr++;
 				len--;
 		}
 	}
 	return NULL;
 }
ceabee13
 
 /*
  * like cli_memstr - but returns the location of the match
  * FIXME: need a case insensitive version
  */
 static const char *
 cli_pmemstr(const char *haystack, size_t hs, const char *needle, size_t ns)
 {
 	const char *pt, *hay;
 	size_t n;
 
 	if(haystack == needle)
 		return haystack;
 
 	if(hs < ns)
 		return NULL;
 
 	if(memcmp(haystack, needle, ns) == 0)
 		return haystack;
 
 	pt = hay = haystack;
 	n = hs;
 
 	while((pt = memchr(hay, needle[0], n)) != NULL) {
 		n -= (int) pt - (int) hay;
 		if(n < ns)
 			break;
 
 		if(memcmp(pt, needle, ns) == 0)
 			return pt;
 
 		if(hay == pt) {
 			n--;
 			hay++;
 		} else
 			hay = pt;
 	}
 
 	return NULL;
 }
8b6f8404
 #else	/*!HAVE_MMAP*/
 int
 cli_pdf(const char *dir, int desc)
 {
 	cli_warnmsg("File not decoded - PDF decoding needs mmap() (for now)\n");
 	return CL_CLEAN;
 }
 #endif