source: branches/fc15-dev/host/credit-card/host.py @ 2044

Last change on this file since 2044 was 2044, checked in by ezyang, 12 years ago
Make credit-card safer and more robust.
File size: 6.3 KB
RevLine 
[1999]1import os
2import optparse
3import socket
4import tempfile
5import shutil
6import errno
[2044]7import csv
[1999]8
9import shell
10
11HOST = socket.gethostname()
12
13# XXX test server and wizard server
14
[2044]15# UIDs (sketchy):
16#   signup 102
17#   fedora-ds 103 (sketchy, not true for b-b)
18#   logview 501 (really sketchy, since it's in the dynamic range)
[1999]19
[2044]20# Works for passwd and group, but be careful! They're different things!
21def lookup(filename):
22    # Super-safe to assume and volume IDs (expensive to check)
23    r = {
24        'root': 0,
25        'sql': 537704221,
26    }
27    with open(filename, 'rb') as f:
28        reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
29        for row in reader:
30            r[row[0]] = int(row[2])
31    return r
32
33# Format here assumes that we always chmod $USER:$USER ...
34# but note the latter refers to group...
[1999]35COMMON_CREDS = [
[2044]36    ('root', 0o600, 'root/.bashrc'),
37    ('root', 0o600, 'root/.screenrc'),
38    ('root', 0o600, 'root/.ssh/authorized_keys'),
39    ('root', 0o600, 'root/.ssh/authorized_keys2'),
40    ('root', 0o600, 'root/.vimrc'),
41    ('root', 0o600, 'root/.k5login'),
[1999]42    # punted /root/.ssh/known_hosts
43
[2044]44    # XXX user must be created in Kickstart
45    ('logview', 0o600, 'home/logview/.k5login'),
[1999]46    ]
47
48COMMON_PROD_CREDS = [ # important: no leading slashes!
[2044]49    ('root', 0o600, 'root/.ldapvirc'),
50    ('root', 0o600, 'etc/ssh/ssh_host_dsa_key'),
51    ('root', 0o600, 'etc/ssh/ssh_host_key'),
52    ('root', 0o600, 'etc/ssh/ssh_host_rsa_key'),
53    ('root', 0o600, 'etc/pki/tls/private/scripts.key'),
54    ('root', 0o600, 'etc/whoisd-password'),
55    ('root', 0o600, 'etc/daemon.keytab'),
[1999]56
[2044]57    ('root', 0o644, 'etc/ssh/ssh_host_dsa_key.pub'),
58    ('root', 0o644, 'etc/ssh/ssh_host_key.pub'),
59    ('root', 0o644, 'etc/ssh/ssh_host_rsa_key.pub'),
[1999]60
[2044]61    ('sql', 0o600, 'etc/sql-mit-edu.cfg.php'),
62    ('signup', 0o600, 'etc/signup-ldap-pw'),
[1999]63    ]
64
65MACHINE_PROD_CREDS = [
66    # XXX NEED TO CHECK THAT THESE ARE SENSIBLE
[2044]67    ('root', 0o600, 'etc/krb5.keytab'),
68    ('fedora-ds', 0o600, 'etc/dirsrv/keytab')
[1999]69    ]
70
[2044]71def mkdir_p(path): # it's like mkdir -p
[1999]72    try:
73        os.makedirs(path)
[2044]74    except OSError as e:
75        if e.errno == errno.EEXIST:
[1999]76            pass
77        else: raise
78
[2044]79# XXX This code is kind of dangerous, because we are directly using the
80# kernel modules to manipulate possibly untrusted disk images.  This
81# means that if an attacker can corrupt the disk, and exploit a problem
82# in the kernel vfs driver, he can escalate a guest root exploit
83# to a host root exploit.  Ultimately we should use libguestfs
84# which makes this attack harder to pull off, but at the time of writing
85# squeeze didn't package libguestfs.
86#
87# We try to minimize attack surface by explicitly specifying the
88# expected filesystem type.
[1999]89class WithMount(object):
90    """Context for running code with an extra mountpoint."""
91    guest = None
[2044]92    types = None # comma separated, like the mount argument -t
[1999]93    mount = None
94    dev = None
[2044]95    def __init__(self, guest, types):
[1999]96        self.guest = guest
[2044]97        self.types = types
[1999]98    def __enter__(self):
99        self.dev = "/dev/%s/%s-root" % (HOST, self.guest)
100
101        mapper_name = shell.eval("kpartx", "-l", self.dev).split()[0]
102        shell.call("kpartx", "-a", self.dev)
103        mapper = "/dev/mapper/%s" % mapper_name
104
105        # this is why bracketing functions and hanging lambdas are a good idea
106        try:
107            self.mount = tempfile.mkdtemp("-%s" % self.guest, 'vm-', '/mnt') # no trailing slash
108            try:
[2044]109                shell.call("mount", "--types", self.types, mapper, self.mount)
[1999]110            except:
111                os.rmdir(self.mount)
112                raise
113        except:
114            shell.call("kpartx", "-d", self.dev)
115            raise
116
117        return self.mount
[2044]118    def __exit__(self, _type, _value, _traceback):
[1999]119        shell.call("umount", self.mount)
120        os.rmdir(self.mount)
121        shell.call("kpartx", "-d", self.dev)
122
123def main():
[2044]124    usage = """usage: %prog [push|pull|pull-common] GUEST"""
[1999]125
126    parser = optparse.OptionParser(usage)
[2044]127    # ext3 will probably supported for a while yet and a pretty
128    # reasonable thing to always try
129    parser.add_option('-t', '--types', dest="types", default="ext4,ext3",
130            help="filesystem type(s)")
131    parser.add_option('--creds-dir', dest="creds_dir", default="/root/creds",
132            help="directory to store/fetch credentials in")
133    options, args = parser.parse_args()
[1999]134
[2044]135    if not os.path.isdir(options.creds_dir):
136        raise Exception("/root/creds does not exist") # XXX STRING
137    # XXX check owned by root and appropriately chmodded
[1999]138
139    os.umask(0o077) # overly restrictive
140
141    if len(args) != 2:
[2044]142        parser.print_help()
[1999]143        raise Exception("Wrong number of arguments")
144
145    command = args[0]
146    guest   = args[1]
147
[2044]148    with WithMount(guest, options.types) as tmp_mount:
149        uid_lookup = lookup("%s/etc/passwd" % tmp_mount)
150        gid_lookup = lookup("%s/etc/group" % tmp_mount)
[1999]151        def push_files(files, type):
[2044]152            for (usergroup, perms, f) in files:
[1999]153                dest = "%s/%s" % (tmp_mount, f)
[2044]154                mkdir_p(os.path.dirname(dest)) # useful for .ssh
[1999]155                # assuming OK to overwrite
[2044]156                # XXX we could compare the files before doing anything...
157                shutil.copyfile("%s/%s/%s" % (options.creds_dir, type, f), dest)
158                try:
159                    os.chown(dest, uid_lookup[usergroup], gid_lookup[usergroup])
160                    os.chmod(dest, perms)
161                except:
162                    # never ever leave un-chowned files lying around
163                    os.unlink(dest)
164                    raise
[1999]165        def pull_files(files, type):
166            for (_, _, f) in files:
[2044]167                dest = "%s/%s/%s" % (options.creds_dir, type, f)
[1999]168                mkdir_p(os.path.dirname(dest))
169                # error if doesn't exist
170                shutil.copyfile("%s/%s" % (tmp_mount, f), dest)
171
172        if command == "push":
173            push_files(COMMON_CREDS, 'common')
174            push_files(COMMON_PROD_CREDS,  'common')
175            push_files(MACHINE_PROD_CREDS, 'machine/%s' % guest)
176        elif command == "pull":
177            pull_files(MACHINE_PROD_CREDS, 'machine/%s' % guest)
178        elif command == "pull-common":
179            pull_files(COMMON_CREDS, 'common')
180            pull_files(COMMON_PROD_CREDS,  'common')
181
182if __name__ == "__main__":
183    main()
Note: See TracBrowser for help on using the repository browser.