Best practice to run Linux service as a different user

后端 未结 8 1317
甜味超标
甜味超标 2020-12-04 04:46

Services default to starting as root at boot time on my RHEL box. If I recall correctly, the same is true for other Linux distros which use the init scripts in

相关标签:
8条回答
  • 2020-12-04 05:28

    After looking at all the suggestions here, I've discovered a few things which I hope will be useful to others in my position:

    1. hop is right to point me back at /etc/init.d/functions: the daemon function already allows you to set an alternate user:

      daemon --user=my_user my_cmd &>/dev/null &
      

      This is implemented by wrapping the process invocation with runuser - more on this later.

    2. Jonathan Leffler is right: there is setuid in Python:

      import os
      os.setuid(501) # UID of my_user is 501
      

      I still don't think you can setuid from inside a JVM, however.

    3. Neither su nor runuser gracefully handle the case where you ask to run a command as the user you already are. E.g.:

      [my_user@my_host]$ id
      uid=500(my_user) gid=500(my_user) groups=500(my_user)
      [my_user@my_host]$ su my_user -c "id"
      Password: # don't want to be prompted!
      uid=500(my_user) gid=500(my_user) groups=500(my_user)
      

    To workaround that behaviour of su and runuser, I've changed my init script to something like:

    if [[ "$USER" == "my_user" ]]
    then
        daemon my_cmd &>/dev/null &
    else
        daemon --user=my_user my_cmd &>/dev/null &
    fi
    

    Thanks all for your help!

    0 讨论(0)
  • 2020-12-04 05:39

    Some things to watch out for:

    • As you mentioned, su will prompt for a password if you are already the target user
    • Similarly, setuid(2) will fail if you are already the target user (on some OSs)
    • setuid(2) does not install privileges or resource controls defined in /etc/limits.conf (Linux) or /etc/user_attr (Solaris)
    • If you go the setgid(2)/setuid(2) route, don't forget to call initgroups(3) -- more on this here

    I generally use /sbin/su to switch to the appropriate user before starting daemons.

    0 讨论(0)
提交回复
热议问题