Skip to content

ext/phar: improve .phar madic directory preservation logic in phar::addEmptyDir()#22011

Open
LamentXU123 wants to merge 1 commit into
php:masterfrom
LamentXU123:sec-refactor
Open

ext/phar: improve .phar madic directory preservation logic in phar::addEmptyDir()#22011
LamentXU123 wants to merge 1 commit into
php:masterfrom
LamentXU123:sec-refactor

Conversation

@LamentXU123
Copy link
Copy Markdown
Contributor

@LamentXU123 LamentXU123 commented May 11, 2026

Now, the .phar directory is a magic dir for phar files, and in phar::addEmptyDir(), users couldn't create a dir naming .phar

The implementation is:

	if (zend_string_starts_with_literal(dir_name, ".phar")) {
		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot create a directory in magic \".phar\" directory");
		RETURN_THROWS();

This has two bugs.

Firstly, people can use /.phar to create the .phar dir. The leading / will be ignored. (no need to concern about ../ though, it will be ignored.)

<?php
  $phar = new Phar(__DIR__ . '/test.phar', 0, 'test.phar');
  $phar->addEmptyDir('/.phar');
  var_dump(is_dir('phar://' . __DIR__ . '/test.phar/.phar'));

Will return true, while if the dir is .phar it will raise an error.

Secondly, it only matches the prefix. That said, /.pharxxx will not be allowed to create, which is not a magic dir.

<?php
  $phar = new Phar(__DIR__ . '/test.phar', 0, 'test.phar');
  $phar->addEmptyDir('.pharx');

This will raise an error.

PHP Fatal error:  Uncaught BadMethodCallException: Cannot create a directory in magic ".phar" directory in C:\Users\admin\Desktop\bench.php:3

This PR fix both by 1. adding a trailing check of the path to make .pharx valid 2. adding a check to /.phar

cc @Girgias Thanks!

Comment thread ext/phar/phar_object.c
) {
size_t prefix_len = (ZSTR_VAL(dir_name)[0] == '/') + sizeof(".phar") - 1;
char next_char = ZSTR_VAL(dir_name)[prefix_len];
if (next_char == '/' || next_char == '\\' || next_char == '\0') {
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure about the \0 logic here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant