fopen clears file instead writing - php

I'm trying to write into a text file via PHP. My problem is that PHP always just clears the file instead of writing in it.
$fp = fopen('status.txt', 'w+');
fwrite($fp, "test");
fclose($fp);
I guess this depends on some permission issues. But I can't figure out what to change. At the moment the permission of the PHP file is:
-rwxrwx--- 1 www-data www-data 1980 Feb 18 11:25 test8.php
the permission of textfile is:
-rwxrwx--- 1 www-data www-data 0 Feb 18 11:25 status.txt
I'm using apache2 on my Raspberry Pi. The PHP script and the text file are stored in Apache main directory /var/www/

Related

Permissions problems with proc_open

I'm having permissions problems when running the following PHP script as root:
#!/usr/bin/php
<?php
$ph = proc_open('whoami', [['pipe','r'],['pipe','w'],['file','/tmp/foo.bar', 'w']], $fds);
if ($ph) {
echo 'command output: ' . stream_get_contents($fds[1]);
proc_close($ph);
} else {
echo 'proc_open failed' . PHP_EOL;
}
The script itself runs fine if /tmp/foo.bar doesn't exist, or is owned by root. But if ownership is changed to another user, proc_open will fail regardless of permissions on the file.
SELinux is disabled, and we are not using ACLs. I'm using PHP 7.4.33 (I know it's old and unsupported, but it's a requirement for FreePBX) on Alma Linux 9.1.
Output:
$ ./test.php
command output: root
$ ls -lah /tmp/
total 12K
drwxrwxrwt. 18 root root 4.0K Dec 14 16:57 .
dr-xr-xr-x. 18 root root 4.0K Dec 14 16:48 ..
-rw-r--r-- 1 root root 0 Dec 14 16:57 foo.bar
$ chown admin /tmp/foo.bar
$ ./test.php
proc_open failed
$ chmod 777 /tmp/foo.bar
$ ./test.php
proc_open failed
$ ls -lah /tmp/
total 12K
drwxrwxrwt. 18 root root 4.0K Dec 14 16:57 .
dr-xr-xr-x. 18 root root 4.0K Dec 14 16:48 ..
-rwxrwxrwx 1 admin root 0 Dec 14 16:57 foo.bar
$ tail -2 /var/log/php.log
[14-Dec-2022 16:57:17 America/Toronto] PHP Warning: proc_open(/tmp/foo.bar): failed to open stream: Permission denied in /test.php on line 3
[14-Dec-2022 16:57:28 America/Toronto] PHP Warning: proc_open(/tmp/foo.bar): failed to open stream: Permission denied in /test.php on line 3
Even disregarding the fact that I'm root, group permissions should allow me full access to the file. So what's going on?
This is due to the permissions on the /tmp directory. When PHP tries to open the file for writing, it gets the EACCES error. From the documentation of open(2):
EACCES
Where O_CREAT is specified, the protected_fifos or protected_regular sysctl is enabled, the file already exists and is a FIFO or regular file, the owner of the file is neither the current user nor the owner of the containing directory, and the containing directory is both world- or group-writable and sticky. For details, see the descriptions of /proc/sys/fs/protected_fifos and /proc/sys/fs/protected_regular in proc(5).
/tmp has the sticky bit set so that anyone can create files there, but users can only delete their own files. Although root can bypass this deletion restriction, it can't bypass the above check in open().
Ok I tried this in a different directory than /tmp, as suggested in comments, and it worked as expected. Using that to hone my search terms I was able pretty quickly to find this U&L answer. Beginning with kernel 4.19 the fs.protected_regular kernel parameter was made available. This parameter:
Disallows open of FIFOs or regular files not owned by the user in world writable sticky directories, unless the owner is the same as that of the directory or the file is opened without the O_CREAT flag. The purpose is to make data spoofing attacks harder.
Apparently it's enabled by default. So because /tmp is world-writable and sticky, I can't touch files that aren't mine – even if I'm root. For the record, if I have to disable this feature:
sysctl fs.protected_regular=0
echo 'fs.protected_regular=0' > /etc/sysctl.d/90-writabletemp.conf
But I'll be better off trying to work around it in the code somehow.

How to run a python script using PHP and create a file?

I am trying a POC running a python script in a back-end implemented in PHP. The web server is Apache in a Docker container.
This is the PHP code:
$command = escapeshellcmd('/usr/local/test/script.py');
$output = shell_exec($command);
echo $output;
When I execute the python script using the back-end we are getting a permission denied error for creating the file.
My python script:
#!/usr/bin/env python
file = open("/tmp/testfile.txt","w+")
file.write("Hello World")
file.close()
This is the error I'm getting:
IOError: [Errno 13] Permission denied: 'testfile.txt'
For the directory im working with the permissions are as follows,
drwxrwsr-x 2 1001 www-data 4096 May 8 05:35 .
drwxrwxr-x 3 1001 1001 4096 May 3 08:49 ..
Any thoughts on this? How do I overcome this problem?
To start is is incredibly bad practice to have relative paths in any scripting environment. Start by rewriting your code to use a full path such as /usr/local/test/script.py and /tmp/testfile.txt. My guess is your script is attempting to write to a different spot than you think it is.
When you know exactly where the files are being written go to the directory and run ls -la and check the permissions on the directory. You want it to be writeable by the same user or group as the web server runs.
Looking at the permissions you have shown you don't have the user able to write to the directory, just everyone and the group. You need to add user write permissions - chmod u+w /tmp will do the job.
I believe the problem is that you are trying to write to an existing file in the /tmp/ directory. Typically /tmp/ will have the sticky permission bit set. That means that only the owner of a file has permission to write or delete it. Group write permissions on files do not matter if the sticky bit is set on the parent directory.
So if this is the contents of your /tmp
$ ls -al /tmp
drwxrwxrwt 5 root root 760 Apr 30 12:00 .
drwxr-xr-x 21 root root 4096 Apr 30 12:00 ..
-rw-rw---- 2 1001 www-data 80 May 8 12:00 testfile.txt
We might assume that users in the group www-data should be able to write to testfile.txt. But that is not the case, since . (the /tmp/ directory itself) has the sticky bit set (the t in the permissions section indicates this).
The reason why the sticky bit is set here is that everyone should be able to write files there, but not have to worry that other users might modify our temporary files.
To avoid permission errors, you can use the standard library tempfile module. This code will create a unique filename such as testfile.JCDxK2.txt, so it doesn't matter if testfile.txt already exists.
#!/usr/bin/env python
import tempfile
with tempfile.NamedTemporaryFile(
mode='w',
prefix='testfile.',
suffix='.txt',
delete=False,
) as file:
file.write("Hello World")

PHP No permissions to create file/folder

I got an issue with my centos server, It, from 3 days ago won't allow me to edit files (write into .txt) create files or create directories with mkdir..
I checked the file ownage, runned whoami and checked the php file had the right permissions but it doesn't want to work.
Might someone suggest me troubleshootings? Also I tried switching from nginx to httpd and repeat the permission checks but still nothing.
running ls -l on the php script it outputs the following:
-rwxrwxr--. 1 nginx nginx 63 Dec 21 14:31 cartella.php
and after : chown apache:apache -R /usr/share/nginx/html/cartella.php
-rwxrwxr--. 1 apache apache 63 Dec 21 14:31 cartella.php
also permissions I tried setting them to 644/755/777 but neither one worked.
Php code that worked till a few days ago:
exec(" > test.txt"); //to empty the file and set the right permissions
$myfile = fopen("test.txt", "a") or die("Unable to open file!");
fwrite($myfile, $text);
fclose($myfile);

perform shell_exec over browser - raspberry pi

I want to run a PHP script from chromium-browser which will print a file. The file is located in /tmp folder on the Raspberry Pi. The file is copied from the server using SAMBA. The script has shell_exec command which attempts to do something with the file. The script works from the command line but not through the browser (chromium). I run the latest Stretch version of Raspbian.
I suspect it is something to do with permissions but I do not know where the problem is located. I have previous image Jessie with similar setup and functionality and it works. I compared all the permissions on both systems and they are exactly the same but I must be missing something.
Here is the PHP script:
<?php
header("Access-Control-Allow-Origin: *");
shell_exec("sudo lpr -P printerName /tmp/sample.pdf");
shell_exec("rm /tmp/sample.pdf");
?>
Here are related permissions:
drwxrwxrwt 15 root root 4096 Nov 23 16:17 tmp
drwxr-xr-x 12 root root 4096 Nov 3 13:58 var
-rwxrw-rw- 1 nobody nogroup 320855 Nov 23 15:31 sample.pdf

how to permission uploaded file correctly

I have an upload script that uploads a zip file to a directory on my website, it then unzips the file and creates a directory for each file uploaded.
drwxrwxrwx 7 Fabulous admin 238 12 Jan 18:20 .
drwxrwxrwx 39 Fabulous admin 1326 12 Jan 12:28 ..
-rwxr--r--# 1 Fabulous admin 15364 12 Jan 18:21 .DS_Store
drwxr-xr-x 4 nobody admin 136 12 Jan 18:20 2012_06
drwxr-xr-x 4 nobody admin 136 12 Jan 18:20 2012_07
-rwxr--r-- 1 Fabulous admin 2904 31 Oct 16:11 index.php
I have another php script that runs which copies the files in the directories 2012_06 and 2012_07 which where created by the upload script. Every thing is working fine via the browser. However I am trying to automate the process via the command line using the unix command line to call the scripts.
The problem is the script runs if I change ownership of the directories to Fabulous by using the following commands
cd upload
sudo chown -R Fabulous:admin .
However when I do this then my upload script index.php no longer has permission access to upload files to the upload directory unless I change ownership back to nobody.
Error Message
Warning:
rename(/htdocs/data_vis/upload/2012_06/Audit_Log.csv,htdocs/data_vis/data_out/2012_06_Audit_Log.csv): Permission denied in
/htdocs/data_vis/rename_files_in_sdir_with_sdir_name_prefix.php on line 27
Any suggestions/advice or fixes on what I should be doing or the correct way to resolve this via permissioning or any other method are welcome. Thanks in advance.
Either add them both to a group or have the file owned by nobody and group owned by Fabulous you dont need it to be admin, root can access everything anyway
the easiest way is make sure the group stays the same is using sticky bits
if /path/to/dir is owned by the correct group
chmod g+s /path/to/dir
will make it so all new folders under /path/to/dir eg /path/to/dir/1 are owned by the same group as /path/to/dir instead of the users default group
https://superuser.com/questions/102253/how-to-make-files-created-in-a-directory-owned-by-directory-group
Then both your web application should be ok and your cron script without modifing the code
I used the following to change ownership of the files in the directory so the other scripts can use the files.
<?php
// File name and username to use
$file_name= "foo.php";
$path = "/home/sites/php.net/public_html/sandbox/" . $file_name ;
$user_name = "fred";
// Set the user
chown($path, $user_name);
// Check the result
$stat = stat($path);
print_r(posix_getpwuid($stat['uid']));
?>

Categories