Managing cron job for web applications

Written by Georgi Stefkoff

Background

Almost every developer or DevOps has been serving their Web content via some web server like nginx or apache. All of these servers comes with the default user www-data. This user is used for a security reasons that is different from the normal system users (like root or something pre-configured while installing the system), so the application will have a limited resources over the entire server. Of course, you can change the running user for the web server to something else, but this is not recommended if there is not another reason behind this.

If you close the application source code, with some user, let's say root user, you have to change the permission of the source code to be owned by the www-data user. This is done by the following command: chown -R www-data:www-data /var/www/html. In this way, only the www-data user will have the rights to operate with the content in /var/www/html.

Depending on the use-cases, you would want to give the following permissions to all of the files: 770 or 660 if there are no executable files in the source code. This will means that only the user and the rest of the users that are part of the same group (in our case is www-data ground) to operate with the files. One useful permission options can be 774 that means that members of the group can read, write and execute the files, and the rest of the users can only read. But I do not recommend this, so stay with 770 or 660 to limit the access over the source code.

Once you setup the web server, and adjust the correct file permissions, in most of the cases, you will need to run some background jobs or cron job that will do some magic behind the scenes. Usually, this jobs will fix some broken database records or will trigger some background jobs.

So, where is the problem?

The problem

If you configured the cron jobs with the root users (or something else), according to the file permissions of the source code, you may end up with Permissions Denied error, while trying to execute some PHP script (for example). One example is, if you users is ubuntu and the source code file permission are 660 this means that only the www-data user or users under www-data group can only access these files. You can easily fix this, bu adding your user to the www-data group by sudo usermod -aG www-data ubutntu. In this way, ubuntu user will have access over the files that are under www-data group. This is not the best approach, because we are giving access to another user over the source code. The eases way will be just to set the web server to work with user ubuntu and get rid of file permissions and so on. But this is highly not recommended.

Another big issue will be the following: If you set the cron jobs by the root users. In this way, since root user is part of the sudoers it have access over all of the files, and no permissions can stop him. If you execute the cron job with the root users, probably everything will went fine and most of the time, you will not notice any issues (you have to pray that there will be no security issues with this), but imagine the following case: root user executes the cron job, which its work is to generate some files. After the execution, these files will be owned by the root users, since the root users forked the process. Then the issue will come if the web server is trying to access these files. The system will denied the read request, because the web server user is www-data, but the files are created by root user, and your application will stop working properly.

One workaround if this issue is to change the file permissions of the source code after every cron job to www-data user, but this is just a waste of CPU resource.

The solution

The correct solution here is to execute these cron jobs, by the www-data user. you can do this by running the following command:

sudo crontab -e -u www-data

Note the sudo at the begging. Changing another user's cron jobs, will require a root privileges!

In this way, the www-data user will have their own background jobs and they will operate with the source code by themselves and no additional permissions adjustments will be required after the cron job.

Extra: fixing in production

One extra information for use, is a similar scenario: if you need to fix something directly on the production server, or you need just to change some code for debugging, you will want to have access to the source code with the correct user. If you are using the root user, there will be no issue to make changes over the files and save them.

NOTE: if you apply some changes on a file with a different user that have explicit access over the file, this will not change the owner of the file

But if you are using an user, different that root (or the want that is not part of the sudoers), you may end up with Permission denied error.

Another issue will be the same as above - if you need to create a new file, or execute a script that create a file(s), this can lead to the web server user to have no access over the newly created files, because the files will be owed by your user and not by the web server user (www-data in our case)

The correct solution is to first login as the web server user and then apply the changes. In order to login with the www-data user, you have to do the following: (NOTE: you need to have root access for this job)

If you are not the root user the call this first:

sudo su

(enter password)

In order to enter is super-user mode.

Then execute the following command:

su -l -s /bin/bash www-data

And you will be logged as the www-data user.

Here is what this means:

  • -l options is said to execute the login logic of the user - setting the environment variables, etc.
  • -s is to provide the shell - in our case is /bin/bash. You can also use /bin/sh or whatever shell you are using.
  • www-data is the user that use need to impersonate

After this, you will work with www-data user and will have the correct access over your source code, as the web server is working

Conclusion

Managing the correct access for the web server files is the key to avoid some cyber attacks over your server. Imagine that if you do not limit the resource for you web server over the file system, some peace of code, could give access to attacker to a files that are not part of the source code and they can even fine some database access, access to the server itself or some other sensitive information which is not supposed to be served to the end user

Comments

  1. Normaninjus said:

    Получи лучшие казинo России 2025 года! ТОП-5 проверенных платформ с лицензией для игры на реальные деньги. Надежные выплаты за 24 часа, бонусы до 100000 рублей, минимальные ставки от 10 рублей! Играйте в топовые слоты, автоматы и live-казинo с максимальны https://t.me/s/RuCasino_top

  2. klassiekepornoNam said:

    Na het testen van verschillende platforms voor volwassenen heb ik begrepen dat gokkastenxl.nl/klassieke-gokkasten — een echte beste keuze voor het bekijken van porno is.

    Beoordeel zelf de officiele pornosite gokkastenxl.nl/klassieke-gokkasten via de onderstaande link:

    filmy porno
  3. website said:

    Această platformă este creat pentru utilizatori locali care caută distracție.

    Oferă sloturi moderne, dealeri live șibonusuri speciale. Plățile sunt securizate, ccu carduri acceptate. Accesul cross-platform permite joc de oriunde.

    Suporftul este mereu disponibil, oerind ghidare. Cu bonusuri atractive și limkte personalizate, 32-Rosu este o opțiune completă pentru joc responsabil.

  4. web page said:

    Acest site este creat pentru jucători români care caută distracție. Oferă sloturi clasice, jocuri de masă și bonusui speciale.

    Depunerile și retragerile sunt rapide, cu cripto acceptate. Accesul mobil permite experiențe fluide. Serviciul clienți este profesional, oferind ajutor. Cu bonusuri atractive și limite personalizate, 32-Rosu este o alegere sigură pentru joc responsabil.

  5. skamltam said:

    Портал lovespace.ua призывает заказать услуги по телефонному скаму, проституции ,а также гей клубам в Киеве и Украине. По ссылке пониже вы можешь заказать развод на деньги, потаскушку ,а также пидрилу. лох

  6. StevenMup said:

    Pizza Lieferung online bezahlen war so einfach! Pizza kam hei? und schnell.
    Pizzaservice in der Nahe

  7. StevenMup said:

    Pizza Lieferung Abendessen war perfekt! In 25 Minuten hatte ich eine frische Pizza.
    Pizzaservice in der Nahe

  8. Blackjack w Guket Casino Online said:

    Cyfrowe serwisy gier w ostatnich latach stały się popularnym wyborem dla użytkowników, którzy szukają rozrywki.
    Takie platformy udostępniają bogatą ofertę, w tym maszyny online, ruletkę cyfrową oraz strategiczne rozgrywki.

    Jedną z kluczowych zalet jest ciągła dostępność, co pozwala grania bez wychodzenia.
    Dodatkowo, wiele serwisów oferuje bonusy, które wzbogacają doświadczenie.

    Podsumowując, cyfrowe serwisy gier w sobie skupiają nowoczesne rozwiązania z doświadczeniem gracza, przyciągając szerokie grono odbiorców.

  9. odwiedź teraz said:

    Kasyna online stałysię często wybieranąalternatywą dla graczy, którzy szukają rozrywki.

    Serwisy internetowe zapewniają szeroki wybór gier, w tym sloty, grry stołowe oraz strategiczne rozgrywki.

    Istotnym atutem jest ciągła dostępność, coo pozwala korzystania z gier z domu.
    Dodatkowo, liczne kasyna internetowe zawiera bonusy, które zwiększają atrakcyjność.

    Podsumowując, kasyna online łączą nowoczesne rozwiązania z doświadczeniem gracza, zyskując popularność na całym świecie.

  10. click aici said:

    Platformele digitale de jocuri de noroc în ultimii ani s-au transformat într-un element important pentru utiizatori care sunt interesați de jocuri moderne.

    Aceste platforme integrează numeroase posibilități, de la jocuri cu role, la mese de ruletă, precum și formmate strategice.

    O caracteristică importantă îl reprezintă accesibilitatea permanentă, ceea ce permite jucătorilor să participe din confortul propriei locuințe.

    În plus, nuumeroase cazinjouri online adaugă recompense, care fac interacțiunea mai atractivă.

    În concluzie, platformele de joc virtual combină instrumentele moderne și interacțiunea digitală, implicând milioane de utilizatori.

  11. câștigă la cazinou said:

    Platformele digitale de jocuri de noroc sunt astăzi element important pentru persoane care doresc divertisment digital.

    Mediiloe online pun la dispoziție o gamă largă de opțiuni, de la sloturi, laa ruleta digitală, precum și poker.

    O caracteristică importantă îlreprezintă accesibilitatea permanentă, ceea ce face posibil jucătorilor să participe prin intermediul internetului.

    În plus, majoritatea site-urilor oferă bonusuri, care amplifică experiența.

    În concluzie, platformele de joc virtual combină instrumentele moderne și divertismentul, atrăgând un public larg.

  12. Bonusuri 32Rosu said:

    Spațiile virtuale de divertisment auu devenit subiect central pentru persoane care doresc divertisment digital.

    Aceste platforme integrează numeroase posibilități, de laa aparate de tip slot, la ruletă, precum și formate strategice.

    Un beneficiu semnificativ îl reprezintă disponibilitatea 24/7, ceea ce oferă șansa jucătorilor să participe din confortul propriei locuințe.

    În plus, numeroase cazinouri online adaugă promoții, care susțin interesul utilizatorilor.

    În concluzie, mediile digitale de noroc integrează inovația și experiența de joc, atrăgând un public larg.

  13. Denniswooks said:

    https://t.me/s/a_official_1xbet

  14. Denniswooks said:

    https://t.me/s/a_official_1xbet

  15. Denniswooks said:

    https://t.me/s/a_official_1xbet

  16. Denniswooks said:

    https://t.me/s/z_official_1xbet

  17. Denniswooks said:

    https://t.me/s/z_official_1xbet

  18. Denniswooks said:

    https://t.me/s/a_official_1xbet

  19. Denniswooks said:

    https://t.me/s/a_official_1xbet

  20. Denniswooks said:

    https://t.me/s/z_official_1xbet

  21. Thomaspat said:

    https://t.me/s/Official_Pokerdomm

  22. Thomaspat said:

    https://t.me/s/Official_Pokerdomm

  23. Thomaspat said:

    https://t.me/s/Official_Pokerdomm

  24. Thomaspat said:

    https://t.me/s/Official_Pokerdomm

  25. Thomaspat said:

    https://t.me/s/Official_Pokerdomm

  26. Markdown is allowed. HTML tags allowed: <strong>, <em>, <blockquote>, <code>, <pre>, <a>.