File: drop_privs_server.py

package info (click to toggle)
pyro5 5.16-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,124 kB
  • sloc: python: 14,328; makefile: 161; sh: 66; javascript: 62
file content (43 lines) | stat: -rw-r--r-- 1,333 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import os
import pwd
import Pyro5.api


class RestrictedService:
    @Pyro5.api.expose
    def who_is_server(self):
        return os.getuid(), os.getgid(), pwd.getpwuid(os.getuid()).pw_name

    @Pyro5.api.expose
    def write_file(self):
        # this should fail ("permission denied") because of the dropped privileges
        with open("dummy-test-file.bin", "w"):
            pass


class RestrictedDaemon(Pyro5.api.Daemon):
    def __init__(self):
        super().__init__()
        print("Server started as:")
        print(" uid/gid", os.getuid(), os.getgid())
        print(" euid/egid", os.geteuid(), os.getegid())
        self.drop_privileges("nobody")

    def drop_privileges(self, user):
        nobody = pwd.getpwnam(user)
        try:
            os.setgid(nobody.pw_uid)
            os.setuid(nobody.pw_gid)
        except OSError:
            print("Failed to drop privileges. You'll have to start this program as root to be able to do this.")
            raise
        print("Privileges dropped. Server now running as", user)
        print(" uid/gid", os.getuid(), os.getgid())
        print(" euid/egid", os.geteuid(), os.getegid())


if __name__ == "__main__":
    rdaemon = RestrictedDaemon()
    Pyro5.api.serve({
        RestrictedService: "restricted"
    }, host="localhost", daemon=rdaemon, use_ns=False)