In my last post where I was “explaining” why trivia had been quiet for a while following my belated upgrades, I said:
“Nothing essential seemed to break, either at Debian 12 or the final destination 13.6. The webserver (lighttpd) worked fine, it served trivia to the world with no apparent problems, I could log in to the wordpress administration panel and I successfully managed an upgrade to the latest version of wordpress. All good.”
Well, actually all was not good as I later discovered when I wanted to post something new.
For readers who may be unfamiliar with wordpress I should note here that WP stores the text of posts in a database (typically Mysql on linux) whilst posted images and other media are stored in an “uploads” directory in the wordpress directory structure. It was whilst attempting to upload an image to trivia that I hit a problem. Moreover a problem that really baffled me when I tried to find out why I couldn’t post. WP kept complaining that it could not move the uploaded image to the correct directory. Investigation of the WP “site health” check determined that, sure enough, the requisite uploads directory was not writeable by WP. Odd, I had changed nothing (said the man who had replaced the entire stack under the blog from the OS upwards, but you know what I mean I’m sure) so I ran a quick sanity check on my installation. WP likes a structure which is set mode 755 on directories and 644 on files with the whole structure owned by root except the uploads directory which must be owned by the user running the webserver, usually, as in my case, that is www-data. This means that directories (and most files) can only be read by the webserver whilst the uploads directory and its underlying structure can be both read and written to by the webserver. My sanity check revealed nothing out of the ordinary. All file and directory permissions were correct, both the webserver (lighttpd) and PHP were running as user www-data, and the required upload structure was owned by www-data.
I then spent a fruitless few days (in fact close to a week on and off) chasing my tail, turning on lighttpd and WP debugging at various levels, adding various PHP debugging tools to the site all to no avail.
Of course I searched all the available on-line fora for any and all advice about my problem. They all came back saying (effectively) “check the permissions”. Well, OK, thanks for that.
I eventually posted about my problem to my local LUG (Linux User Group) saying:
Hi Guys
I’m having ridiculous difficulty in tracking down a problem I have with
my wordpress installation.WordPress is at the latest level (7.1.5) php is at 8.4.27 (patched
since the php2shell problem) I’m running lighttpd 1.4.79 (ssl) on
Debian 13.7 and mysql is 11.8.6-MariaDBFor background I have been running wordpress for nearly 20 years on a
similar setup (but of course earlier versions of everything in that
stack) so I’m not entirely unaware of how to fix problems, But I’m
baffled as to what is happening now.Scenario – I upgraded debian (and thus all installed packages
including lighttpd, php, mysql (mariadb) etc in about July of this
year. After upgrade I checked my wordpress installation (my blog) and
all worked fine. I checked that I could still log in as admin but since
I had nothing to add to the blog at that time I didn’t try any editing.
In fact I hadn’t added anything to the blog since January (my bad, but
I’ve had nothing much to say).This week I tried to add a new post and hit a major problem. I could
not upload any media files. WordPress threw the error “The uploaded
file could not be moved to wp-content/uploads”. Now this is almost
always caused by a permissions problem (the web server needs write
access to the “wp-content/uploads” directory in the web’s document root.
So I checked the perms – all safe and sane as they have always been.
Wordpress likes directory mode 755 and files 644 with the “uploads”
directory owned by the web server. Everything else is owned by root.On checking the wordpress admin tools/site-info I noted that neither
the wp-content directory, nor its subdirectory “uploads” are writable
by the server. So I checked the web server and php ownership was
correct and sure enough both lightppd and php were running as www-data
(and the directories in question are owned by www-data) so why can’t it
write to them?I have turned on WP-DEBUG, installed a variety of php debugging plugins,
I have checked phpinfo() and come up baffled. Some of the php debugging
plugins are themselves a little brain dead in my view because they
try to write their logs to the web space (in either the docroot, the
wp-admin or wp-content directories – NO!!!, who in their right mind
would write sensitive log info to a space readable by the web? But the
fact that they failed to write these logs merely confirms the problem –
WP cannot write to directories I WANT it to write to.I have been tearing my hair out for the past four days and am getting
nowhere.Any ideas chaps? Have I missed something blindingly obvious?
Oh and in desperation I have also tried setting the directories in
question to mode 777 with no joy. (Now changed back of course).TIA
I received only one answer, and that was “Sorry, can’t help you Mick.”
In desperation I then started a new, completely clean, ground up build of a new server on a new VM so that everything, but everything would be in a state that I knew had been controlled and built properly (or as “properly” as I can get it) in preparation for a potential port of trivia to a new home. My hope here was that the earlier VM, which had been running for 7 or 8 years through many changes was in some bizarre way corrupted and a new build would solve my problems. Silly really, I would not have learned what was causing the problem on the original VM if the new VM worked, but at least I could park that problem whilst getting trivia up and running again.
It was at this stage that I went for a beer (or two) with an old mate. We used to work together back in my sysadmin days and he shares my background and experience. Like me, Al is now long retired but he keeps his hand in by running a website for the local engineering society. Al is also way more of a database expert than I will ever be, so I ran my problem past him. Al told me that he had used chatGPT recently when he was stuck on a coding problem and he said that he had been very pleasantly surprised at the quality of both the response to his question and the code it generated for him. What the hell, it must be worth a go I thought.
So, a few days ago I tried chatGPT for the very first time. Here I must say that I have always been deeply sceptical about both the very idea of LLMs and their use in solving real world problems. It turns out I was very, very wrong on both counts. I was completely stunned by the response I received. It was clear, cogent, coherent, grammatical and better yet, technically astute and practical. Though why I should be surprised at the latter points is daft since those very same LLMs are trained on the whole repository of publicly available information on every topic under the sun.
In my trial, I posted my original LUG question to chatGPT. I won’t give the entire transcript of the session here largely because it is quite long, but this is an extract of the main points of what it said originally, and in response to my later replies:
CGPT
First of all, don’t despair! I think there’s a good chance this is something relatively straightforward, but one of the less obvious differences introduced by the Debian upgrade.
There are a few things in your description that particularly interest me. In fact, **the fact that changing the permissions to 777 made absolutely no difference is the biggest clue of all.**
If this were simply a conventional Unix ownership/permissions problem, 777 should have made the directory writable (assuming the filesystem itself permits writing).
That suggests we should look beyond conventional file permissions.
Let me work through this systematically.
## **1. My prime suspects**
Given your combination of Debian 13, lighttpd, PHP 8.4 and MariaDB, I’d investigate these possibilities, in roughly this order.
### **A. PHP-FPM systemd security restrictions**
This is probably the first thing I’d investigate.
Debian packages increasingly use systemd security features to restrict what services can access. In particular, systemd can impose filesystem restrictions on PHP-FPM independently of the Unix permissions.
There followed some suggested tests which I ran and noted the results of.
CGPT then went on:
### **B. PHP open_basedir restrictions**
Another possibility is that PHP’s `open_basedir` restriction is preventing access to the upload directory.
Check your phpinfo() output for:
INI
“`
open_basedir
“`Also check the effective configuration from the command line:
Bash
“`
php -i | grep -i open_basedir
“`Be aware that the command-line PHP configuration and the PHP-FPM configuration can differ.
CGPT gave some more suggested tests then continued:
### **C. AppArmor**
Debian uses AppArmor, and although it isn’t necessarily enabled with restrictive profiles for every PHP installation, it’s worth checking.
AppArmor can deny filesystem access regardless of Unix ownership and mode bits.
Try:
Bash
“`
aa-status
“`Then:
Bash
“`
journalctl -k | grep -i apparmor
“`Look for messages indicating denied access involving PHP-FPM, lighttpd, or your WordPress directory.
A denial here would be particularly interesting.
CGPT then continued
## **2. Establish whether PHP itself can write to the directory**
This is probably the single most useful diagnostic test we can perform.
There is an important distinction between:
* The operating system allowing `www-data` to write to a directory.
* PHP, running as `www-data`, being allowed to write to that same directory.
Those aren’t necessarily equivalent because PHP-FPM may be subject to additional restrictions.
There were then some more suggested tests which I ran and again noted results.
CGPT then continued:
## **3. Check the filesystem itself**
There are a few other things worth eliminating.
### **Is the filesystem mounted read-only?**
Run:
Bash
“`
findmnt -T /path/to/wordpress/wp-content/uploads
“`Look at the mount options.
You want to establish that the filesystem is mounted `rw`, rather than `ro`.
### **Are there ACLs overriding the normal permissions?**
Run:
Bash
“`
getfacl /path/to/wordpress/wp-content
getfacl /path/to/wordpress/wp-content/uploads
“`ACLs can sometimes produce unexpected results, particularly after system migrations or filesystem restoration.
### **Is the directory marked immutable?**
Unlikely, but easy to check:
Bash
“`
lsattr -d /path/to/wordpress/wp-content
lsattr -d /path/to/wordpress/wp-content/uploads
“`Look for an `i` attribute.
### **Is the filesystem full?**
Don’t forget inodes:
Bash
“`
df -h
df -i
“`A filesystem can have plenty of free space but no available inodes.
Again I ran all those tests, some (but not all, I confess) of which I had already checked. Fortunately everything looked OK.
CGPT then went on:
## **4. Check PHP’s temporary upload directory**
This is another avenue worth investigating because WordPress media uploads involve two separate filesystem operations.
First, PHP receives the uploaded file and places it in a temporary directory.
Then WordPress moves it into `wp-content/uploads`.
Check these PHP settings:
INI
“`
upload_tmp_dir
upload_max_filesize
post_max_size
sys_temp_dir
“`If `upload_tmp_dir` is empty, PHP normally uses the system temporary directory.
Check that the temporary directory is accessible to the PHP process:
Some more tests were recommended so I ran those too.
CGPT went on:
## **5. One particularly useful diagnostic: watch the logs while uploading**
I’d actually do this before making any configuration changes.
Open two terminal sessions.
In the first:
Bash
“`
journalctl -f -u php8.4-fpm
“`In the second:
Bash
“`
journalctl -f -k
“`Now attempt an upload through WordPress.
Look for:
* Permission denied
* Read-only filesystem
* Operation not permitted
* open_basedir restriction
* AppArmor DENIED
* PHP-FPM filesystem errors
Also check your lighttpd error log, commonly:
Bash
“`
tail -f /var/log/lighttpd/error.log
“`The exact location depends on your configuration.
The important thing is to correlate the messages with the precise time you attempt the upload.
So I ran those tests too, even though I had previously thoroughly checked practically every log I could think of (and a few which only appeared when I added PHP debugging code to WP). Besides, I wasn’t using FPM.
CGPT then went on:
## **6. Something else I’d like to establish**
You mentioned that both lighttpd and PHP are running as `www-data`.
I’d like to clarify exactly how you’re running PHP.
Are you using:
1. **PHP-FPM**, with lighttpd passing PHP requests to a FastCGI socket?
2. **php-cgi**, spawned directly by lighttpd using `mod_fastcgi`?
3. Something else?
This matters because the systemd restrictions I mentioned earlier may apply to a different service depending on your configuration.
before concluding with the following:
## **My suggested order of attack**
I wouldn’t start changing permissions, reinstalling WordPress, or altering PHP configuration just yet.
I’d do these four things first:
1. Run `sudo -u www-data touch` against the uploads directory.
2. Run the PHP write test through your actual WordPress HTTPS site.
3. Check the PHP-FPM systemd restrictions (if you’re using FPM).
4. Look at the kernel/AppArmor logs immediately after attempting an upload.
**My suspicion is that something introduced by the Debian upgrade is restricting PHP’s filesystem access independently of the traditional Unix permissions.**
In particular, systemd service sandboxing is something that can easily escape notice when upgrading a server that has otherwise been running happily for years.
One final observation: MariaDB is almost certainly irrelevant here. WordPress is failing at the filesystem stage, before the database has anything meaningful to do with the uploaded file.
**Here’s what I’d particularly like you to report back:**
* Does the command-line `touch` work?
* What does the PHP `file_put_contents()` test return?
* Are you using PHP-FPM or php-cgi?
* What does `systemctl show php8.4-fpm` reveal, if you’re using FPM?
I think those results will get us much closer to the culprit. And please, don’t leave anything set to 777 in the meantime!
Much food for thought there. I had not previously realised the systemd might be at fault. Stupid really, of course it could.
So I said in response:
OK , I’ve run your suggested tests.
and CGPT replied:
Excellent. Let’s see what you’ve found.
Post the results, including any error messages verbatim if possible. Don’t worry about tidying them up.
I’ll work through them with you and we’ll narrow this down rather than randomly changing configuration settings.
I then said:
– the command line touch successfully creates a file.
– The PHP file put test returns “PHP user: root
Directory: /home/web/baldric.net/wp-content/uploads is_dir: bool(true)
is_writable: bool(false)
file_put_contents result: bool(false)
Last error: array(4) { [“type”]=> int(2) [“message”]=> string(124)
“file_put_contents(/home/web/baldric.net/wp-content/uploads/php-write-test.txt):
Failed to open stream: Read-only file system” [“file”]=> string(36)
“/home/web/baldric.net/write-test.php” [“line”]=> int(19) }
Effective UID: 33.
– I am not using FPM, rather php-cgi with fastcgi
CGPT then responds (and here I am giving a lot of the detail, including my responses to its suggested further tests, because it shows the logic applied by the LLM in reaching its conclusion):
Ah! That’s an extremely useful result. In fact, I think we’ve now found the general area of the problem.
The crucial piece of evidence is:
Failed to open stream: Read-only file system
That is not a Unix permissions error. It is the kernel telling PHP that the filesystem, as seen by the PHP process, is read-only.
The PHP user: root result is misleading, incidentally. As I mentioned earlier, get_current_user() reports the script file’s owner, not the executing process. Your effective UID of 33 confirms that PHP is running as www-data.
And the fact that PHP is running as CGI rather than PHP-FPM changes where I’d look.
1. My leading suspect: systemd’s ProtectHome setting
There’s one detail in your output that now looks particularly significant:
/home/web/baldric.net/wp-content/uploads
Your WordPress installation is under /home.
Systemd has a security feature called ProtectHome which can make /home read-only, or even inaccessible, to processes running inside a service’s security sandbox.
If lighttpd is running under a systemd service with:
ProtectHome=read-only
then its PHP-CGI child processes will inherit that restriction.
That would explain your symptoms almost perfectly:
The command-line touch works because it runs outside the lighttpd service’s restricted environment.
PHP can see the directory.
PHP runs as the correct user.
PHP cannot write, even with permissions set to 777.
The kernel reports Read-only file system.
And because you’re using PHP-CGI spawned by lighttpd, I’d investigate the lighttpd systemd service, rather than looking for a PHP-FPM service.
2. Please run these commands
First:
systemctl cat lighttpd
Then:
systemctl show lighttpd \
-p ProtectSystem \
-p ProtectHome \
-p ReadOnlyPaths \
-p ReadWritePaths \
-p InaccessiblePaths \
-p PrivateTmpI’m particularly interested in ProtectHome.
Also, let’s establish exactly how PHP-CGI is being started:
ps -ef | grep ‘[p]hp-cgi’
This will tell us whether PHP-CGI is a child of lighttpd or is being started by a separate service such as spawn-fcgi.
3. One further test (optional, but useful)
Find the PID of the PHP-CGI process from the previous command, then run:
cat /proc/PID/mountinfo | grep ‘/home’
Replace PID with the actual process ID.
This may reveal a mount covering /home or one of its subdirectories with read-only options.
You can also inspect the mount namespace:
readlink /proc/PID/ns/mnt
readlink /proc/1/ns/mntIf the namespace identifiers differ, PHP is running in a separate mount namespace.
My advice: don’t change anything yet.
I have a fairly strong suspicion that the July Debian upgrade introduced a systemd security restriction, possibly through a changed service unit or override.
Let’s see the output of systemctl cat lighttpd first. I suspect that may give us our answer rather quickly!
systemctl cat lighttpd
# /usr/lib/systemd/system/lighttpd.service
[Unit]
Description=Lighttpd Daemon
After=network-online.target
Documentation=man:lighttpd https://wiki.lighttpd.net# optional: systemd socket activation for lighttpd
#Requires=lighttpd-http-ipv4.socket lighttpd-http-ipv6.socket lighttpd-https-ipv4.socket lighttpd-https-ipv6.socket[Install]
WantedBy=multi-user.target[Service]
Type=simple
PIDFile=/run/lighttpd.pid
ExecStartPre=/usr/sbin/lighttpd -tt -f /etc/lighttpd/lighttpd.conf
ExecStart=/usr/sbin/lighttpd -D -f /etc/lighttpd/lighttpd.conf
ExecReload=/usr/sbin/lighttpd -tt -f /etc/lighttpd/lighttpd.conf
ExecReload=/bin/kill -USR1 $MAINPID
Restart=on-failure# increase num files soft limit; 1024 harkens back to select() limit
# (lighttpd.conf must still be configured with server.max-fds; default 4096)
LimitNOFILE=32768:524288#
# system capabilities hardening
## (comment all out if running lighttpd as root to manage system, e.g. via LuCI)
# Recommended configuration: have systemd start lighttpd as unprivileged user.
# Note: starting lighttpd as unprivileged user requires TLS certificates to be
# readable by the unprivileged user and will fail for existing configurations
# where that is not currently the case. For that scenario and for similar
# compatibility reasons, this is not yet enabled by default.
#User=lighttpd
#Group=lighttpd# Allow unprivileged lighttpd to bind,listen to ports < 1024 (i.e. 80 and 443). AmbientCapabilities=CAP_NET_BIND_SERVICE # Recommended configuration: strictly limit capabilities # Limit capabilities, including for children and privileged processes, e.g. root # CAP_NET_BIND_SERVICE allows bind() to ports < 1024 (i.e. 80 and 443). # CAP_SETGID, CAP_SETUID, and CAP_SYS_CHROOT are self explanatory. #CapabilityBoundingSet=CAP_NET_BIND_SERVICE CAP_SETGID CAP_SETUID CAP_SYS_CHROOT # If not starting lighttpd as root, minimal capability to bind to ports < 1024: #CapabilityBoundingSet=CAP_NET_BIND_SERVICE # Using systemd socket activation, even CAP_NET_BIND_SERVICE is not necessary # and could be removed from AmbientCapabilities and CapabilityBoundingSet. # Requires lighttpd.conf: server.systemd-socket-activation = "enable" # Requires installation, configuration, enabling of systemd lighttpd*.socket # Requires the 'Requires' in the [Unit] section at top of this file. # See /usr/share/doc/lighttpd/examples/lighttpd*.socket or lighttpd source tree # https://git.lighttpd.net/lighttpd/lighttpd1.4/src/branch/master/doc/systemd/ # Note: PrivateTmp=yes # could break backends if named socket from independent daemon is located # in /tmp; must relocate lighttpd.conf socket paths to e.g. /run/lighttpd # Note: ProtectHome=read-only # could break CGI scripts or WebDAV writing to home paths # Note: RestrictSUIDSGID=yes # could break CGI scripts or WebDAV setting suid/sgid permission bit on files KeyringMode=private LockPersonality=yes MemoryDenyWriteExecute=yes NoNewPrivileges=yes PrivateDevices=yes PrivateTmp=yes ProtectClock=yes ProtectControlGroups=yes ProtectHome=read-only ProtectHostname=yes ProtectKernelLogs=yes ProtectKernelModules=yes ProtectKernelTunables=yes ProtectProc=invisible ProtectSystem=full RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX RestrictNamespaces=yes RestrictRealtime=yes RestrictSUIDSGID=yes SystemCallArchitectures=native systemctl show lighttpd \ -p ProtectSystem \ -p ProtectHome \ -p ReadOnlyPaths \ -p ReadWritePaths \ -p InaccessiblePaths \ -p PrivateTmp ReadWritePaths= ReadOnlyPaths= InaccessiblePaths= PrivateTmp=yes ProtectHome=read-only ProtectSystem=full There it is! We've found it. I'm virtually certain this is your problem. Look at these two lines in your lighttpd service: ProtectHome=read-only ProtectSystem=full And remember where your WordPress installation lives: /home/web/baldric.net/ ProtectHome=read-only is preventing PHP-CGI from writing anywhere under /home. This is exactly consistent with every symptom you've described. PHP can read the WordPress directories. PHP runs under the correct UID (www-data). The directories have the correct ownership and permissions. Even permissions of 777 don't help. The kernel returns Read-only file system. Command-line writes work because they aren't running inside lighttpd's systemd security sandbox. It's also interesting that the Debian lighttpd service file actually contains this comment: # Note: ProtectHome=read-only # could break CGI scripts or WebDAV writing to home paths That's almost a smoking gun!
Smoking gun indeed. CGPT then suggested a fix, thus:
I would recommend overriding this one systemd setting rather than modifying the Debian-supplied service file.
Run:
sudo systemctl edit lighttpd
An editor will open. Add:
[Service]
ProtectHome=falseSave and exit.
Then:
sudo systemctl daemon-reload
sudo systemctl restart lighttpdNow repeat your PHP write test.
You should find:
is_writable: bool(true)
file_put_contents result: int(15)(The precise integer will depend on the length of your test string.)
Your WordPress media uploads should then work normally.
One security consideration
I wouldn’t remove ProtectSystem=full, NoNewPrivileges, PrivateTmp or the other systemd protections.
They provide useful security hardening, and there’s no reason to disable them to solve this problem.
We’re simply allowing lighttpd and its CGI children to write to the home directory, which is necessary given your particular filesystem layout.
An alternative, if you want to retain as much protection as possible, is to use:
[Service]
ProtectHome=tmpfs
ReadWritePaths=/home/web/baldric.net/wp-content/uploadsHowever, I would stick with ProtectHome=false initially to confirm the diagnosis. We can refine the restrictions afterwards if you wish.
I think we’ve cracked it!
And incidentally, this is a very good example of why permissions troubleshooting can be so frustrating: the permissions were perfectly correct all along. The restriction was imposed by systemd at the mount-namespace level, completely outside the normal Unix permissions mechanism.
Let me know whether the PHP write test succeeds after that change.
I then concluded the session by saying:
“Yes, thank you, I can now write to the wp-content/uploads directory. However, this incident has served to confirm my absolute hatred of systemd. It is an abomination.”
to which CGPT replied:
π I rather suspect you’ve just articulated the feelings of quite a few long-time Unix and Linux administrators!
There is a particularly irritating aspect to this episode: systemd silently changed the rules under which your perfectly functional web server was operating, without anything being wrong with the traditional Unix permissions model.
And the really maddening thing is that everything looked right:
Correct user.
Correct group.
Correct ownership.
Correct directory permissions.
Correct PHP configuration.
Correct lighttpd configuration.
Yet a security feature buried in a systemd service definition effectively overrode all of it.
I do have one recommendation, though: keep your override in /etc/systemd/system/lighttpd.service.d/override.conf rather than editing the vendor-supplied unit file. That way it should survive future package upgrades.
And perhaps add a comment explaining why it’s there:
[Service]
# WordPress installation resides under /home.
# CGI processes need write access to wp-content/uploads.
ProtectHome=falseOne final thought: given that you’ve been administering this sort of setup for nearly 20 years, you clearly know your way around Unix. Don’t let this episode convince you that you’ve forgotten how Linux permissions work!
You hadn’t. The goalposts had moved. π
So, CGPT actually solved my problem and it did so in a logical and practical way by taking me through all the possibilities which could explain my observed problem. Moreover, while doing so, it exhibited all the behaviours I would expect of an intelligent and sympathetic human teacher. The very fact that I found myself saying “Thank you” to a robot tells you a lot about my experience. And CGPT’s final response to my thank you is very like that you would expect from a human. I also like the fact that it sympathised with my view of systemd. That piece of maladjusted software sucks big time, and as I have said before, I really, really hate it. It was bad enough on my desktop, but when it starts f*****g with my server configurations without telling me it has gone way, way too far.
I came away from the experience both grateful and astonished but also rather worried. The experience made me acutely aware of how far LLMs have come whilst I have been ignoring them. I am now not at all surprised that people should be using them for a whole range of tasks – and the temptation for students to say to an LLM something like “Write me a 6000 word essay on the impact of the BREXIT vote on British politics” must be huge.
I may play further.
One point to note about all the above though is that I am probably unusual in that I run all my webs under /home. I suspect that most people will run them under the default /var/www/. If that were the case I might never have stumbled across this issue. But I don’t like running the defaults for a bunch of reasons, partly historic in that in the early days /var would have been a small separate partition on the server whilst /home would be a much larger structure.
YMMV.