1

(maybe this question is suited for SO, but I don't think it's linked to my code).

I'm using SQLite3 as a database engine for my Web app.

I freshly deployed it on the production server, and it's not working as expected.

I'm using PDO (a PHP DB interface) to access this DB, but whenever I try to write something in it, I get the error:

SQLSTATE[HY000]: General error: 8 attempt to write a readonly database

The production server is a Centos 8 running Httpd (so Apache). I've set the rights to 777 for the whole folder (this is just a test, don't blame me), but still getting the error.

I've read many things about this error, but none of them worked for me.

Funny thing, when running:

php -r 'var_dump(
  $db=new PDO("sqlite:/var/www/myProjetFolder/db/myProjetDb.sqlite"),
  $q=$db->query("SELECT * FROM sqlite_master"),
  $q->fetchAll()); '

At the root of the Web server, I get the content of my database, so I guess the rights are good.

As a precision, my project is stored in /var/www/myProjectFolder/.

I did not create any vHost for the moment, I simply edited httpd.conf and changed the DocumentRoot.

Why is this happening?

LeRouteur
  • 388
  • 2
  • 16

1 Answers1

4

By default SELinux doesn't allow the web server to write any files (uploads, your SQLite database, etc). You need to tell it which files and directories should be writable by the web server.

To make a single file writable:

semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/myProjetFolder/db/myProjetDb.sqlite"

To make a whole directory writable:

semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/uploads(/.*)?"

Then reset the file contexts on the affected file or directory.

restorecon -rv /var/www/uploads
restorecon -v /var/www/myProjetFolder/db/myProjetDb.sqlite
Michael Hampton
  • 244,070
  • 43
  • 506
  • 972
  • Thank you for this developed answer. But is there any advantage to complicate the construction of the Web server like this? The Web server itself is strongly secured, so I don't really understand the benefits of this. – LeRouteur Nov 03 '20 at 08:48
  • 1
    @LeRouteur SELinux is mandatory access control, a different layer of security. There are plenty of advantages to having defense in depth. You can look up more detailed information on all of these concepts on the Internet, but the one thing SELinux is very good at is stopping zero-day attacks. (If you don't turn it off or allow unnecessary things, of course.) – Michael Hampton Nov 03 '20 at 20:18
  • Perfect, thank you for the explanation, I'll have a look at it! :) – LeRouteur Nov 04 '20 at 07:44