Skip to content

phar: NULL dereference in Phar::webPhar() when SCRIPT_NAME is absent from SAPI environment #21797

@iliaal

Description

@iliaal

Description

Phar::webPhar() calls sapi_getenv("SCRIPT_NAME", ...) and passes the result directly to strstr() without checking for NULL. When the SAPI environment does not provide SCRIPT_NAME (e.g. a misconfigured FastCGI upstream), sapi_getenv returns NULL and the strstr call segfaults.

Affected code

ext/phar/phar_object.c, PHP_METHOD(Phar, webPhar):

testit = sapi_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1);
if (!(pt = strstr(testit, basename))) {   // NULL dereference if testit == NULL
    efree(testit);
    goto finish;
}

Trigger conditions

FastCGI deployment (nginx, Caddy, LiteSpeed) where SCRIPT_NAME is not forwarded in the FastCGI params block. This is an atypical but possible misconfiguration. Not reachable via php-cgi invoked directly, since CGI SAPI derives request_uri from SCRIPT_NAME and returns early before this code is reached.

Expected behavior

webPhar() should handle a missing SCRIPT_NAME gracefully (treat it as non-matching and fall through to the finish label).

Fix

Add a NULL guard immediately after the sapi_getenv call:

testit = sapi_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1);
if (!testit) {
    goto finish;
}
if (!(pt = strstr(testit, basename))) {
    efree(testit);
    goto finish;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions