4

There are many different variants of this question on SO, but I've found none that actually explain what specific permissions should be granted to allow apache to write to an SQLite DB safely/with minimal risk. I've asked this question because there's plenty of information on the general concept of allowing write access for the apache user, but no specifics on how to grant that access to the apache user with minimal required permissions.

Given my web app's structure with the sqlite db outside the web root:

/var/
├── databases/
│   └── myapp/
│       └── db.sqlite3 (PERMISSIONS)
│
├── www/html/ (web root)
│   ├── index.php
│   └── includes/ 
│       ├── include1.php
│       └── ...

When I call a PHP script that tries to perform a write operation on the DB, I get the following error in apache2's error.log:

PHP Fatal error:  Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /var/www/html/includes/include1.php:xx\nStack trace:\n#0 /var/www/html/includes/include1.php(xx): PDOStatement->execute()\n#1 {main}\n  thrown in /var/www/html/includes/include1.php on line xx, referer: ...

I know from various SO questions and from the PDO manual that the solution to this problem is to grant write access for the database's directory to the www-data user, but I'm relatively new to permissions and how to safely grant them. Can someone specify what permissions level should be granted to the www-data user, and how to accomplish this?

Community
  • 1
  • 1
Marcatectura
  • 1,721
  • 5
  • 30
  • 49
  • 3
    The crucial information here is that the db's _directory_ needs write access because sqlite3 needs to create new files in the dir (such as the "wal" or rollback files). It took me hours to figure that out (most answers only tell you to make sure the DB file itself is writeable) – Thomas Tempelmann Dec 06 '19 at 09:59

1 Answers1

5

This really depends on apache server configuration (maybe you are not allowed to exit virtual host directory), but this could do the trick

chown -R www-data:www-data /var/databases/myapp/
chmod -R u+w /var/databases/myapp/
dsmatilla
  • 107
  • 3
  • Thank you, this did work - are there any security issues with this approach? – Marcatectura Feb 17 '17 at 22:01
  • Apache is not supposed to have write permission outside virtual host directory. Be care when writing your PHP, any security breach here could lead to someone writing in your DB directory. – dsmatilla Feb 17 '17 at 22:10