laracoft's avatar

Cron some tasks as `root`

Is there a Laravel way setup cron to run most tasks as www-data and some tasks as root?

The docs show only https://laravel.com/docs/12.x/scheduling#running-the-scheduler which implies only 1 user can be specified. It feels dangerous to set it as root.

0 likes
5 replies
Glukinho's avatar

Setup a dedicated queue worker running from root (user=root, group=root in supervisord config) and handling queue named "as-root":

php artisan queue:work --queue=as-root

Dispatch jobs to as-root queue from where you need (from some scheduled tasks as you wrote) and they will be executed with root privileges:

SomeJob::dispatch()->onQueue('as-root');

Out of curiosity, why you need such a setup?

laracoft's avatar

Thanks,

  1. How would code for scheduling a root Task look like? It sounds cumbersome if I have to create a Job for every root Task
  2. I need to run as root when modifying certain files, e.g. nginx etc
Glukinho's avatar

If you don't want dedicated job class, you can dispatch a closure:

dispatch(function() {
	// ...actions need to be done as root...
})->onQueue('as-root');

Or you can schedule a job without having Command class:

// routes/console.php

Schedule::job(new SomeJob, 'as-root')->hourly();
Snapey's avatar

how is root authenticated without creating some huge security hole?

JussiMannisto's avatar

That is a really bad idea from a security standpoint.

Giving write access to any Nginx file from the application layer sounds very risky too. A slightly better approach would be to create a group that both nginx and www-data belong to, change the group ownership of the relevant files/directories to that group, and add group write permissions. That's still risky since an RCE anywhere in the program would makes those files writable for the attacker.

It's hard to say what the correct and safe approach would be without knowing the problem that you're trying to solve. Can you elaborate on that?

You could also allow www-data to run a specific script as nginx via the sudoers file:

www-data ALL=(nginx) NOPASSWD: /opt/my/script.sh

You could then invoke that script from Laravel. But like I said, I'd need to know the actual problem.

Please or to participate in this conversation.