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

Last change on this file since 2045 was 2045, checked in by ezyang, 11 years ago
Add scripts-1024.key to credential store.
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'),
[2045]53    ('root', 0o600, 'etc/pki/tls/private/scripts-1024.key'),
[2044]54    ('root', 0o600, 'etc/pki/tls/private/scripts.key'),
55    ('root', 0o600, 'etc/whoisd-password'),
56    ('root', 0o600, 'etc/daemon.keytab'),
[1999]57
[2044]58    ('root', 0o644, 'etc/ssh/ssh_host_dsa_key.pub'),
59    ('root', 0o644, 'etc/ssh/ssh_host_key.pub'),
60    ('root', 0o644, 'etc/ssh/ssh_host_rsa_key.pub'),
[1999]61
[2044]62    ('sql', 0o600, 'etc/sql-mit-edu.cfg.php'),
63    ('signup', 0o600, 'etc/signup-ldap-pw'),
[1999]64    ]
65
66MACHINE_PROD_CREDS = [
67    # XXX NEED TO CHECK THAT THESE ARE SENSIBLE
[2044]68    ('root', 0o600, 'etc/krb5.keytab'),
69    ('fedora-ds', 0o600, 'etc/dirsrv/keytab')
[1999]70    ]
71
[2044]72def mkdir_p(path): # it's like mkdir -p
[1999]73    try:
74        os.makedirs(path)
[2044]75    except OSError as e:
76        if e.errno == errno.EEXIST:
[1999]77            pass
78        else: raise
79
[2044]80# XXX This code is kind of dangerous, because we are directly using the
81# kernel modules to manipulate possibly untrusted disk images.  This
82# means that if an attacker can corrupt the disk, and exploit a problem
83# in the kernel vfs driver, he can escalate a guest root exploit
84# to a host root exploit.  Ultimately we should use libguestfs
85# which makes this attack harder to pull off, but at the time of writing
86# squeeze didn't package libguestfs.
87#
88# We try to minimize attack surface by explicitly specifying the
89# expected filesystem type.
[1999]90class WithMount(object):
91    """Context for running code with an extra mountpoint."""
92    guest = None
[2044]93    types = None # comma separated, like the mount argument -t
[1999]94    mount = None
95    dev = None
[2044]96    def __init__(self, guest, types):
[1999]97        self.guest = guest
[2044]98        self.types = types
[1999]99    def __enter__(self):
100        self.dev = "/dev/%s/%s-root" % (HOST, self.guest)
101
102        mapper_name = shell.eval("kpartx", "-l", self.dev).split()[0]
103        shell.call("kpartx", "-a", self.dev)
104        mapper = "/dev/mapper/%s" % mapper_name
105
106        # this is why bracketing functions and hanging lambdas are a good idea
107        try:
108            self.mount = tempfile.mkdtemp("-%s" % self.guest, 'vm-', '/mnt') # no trailing slash
109            try:
[2044]110                shell.call("mount", "--types", self.types, mapper, self.mount)
[1999]111            except:
112                os.rmdir(self.mount)
113                raise
114        except:
115            shell.call("kpartx", "-d", self.dev)
116            raise
117
118        return self.mount
[2044]119    def __exit__(self, _type, _value, _traceback):
[1999]120        shell.call("umount", self.mount)
121        os.rmdir(self.mount)
122        shell.call("kpartx", "-d", self.dev)
123
124def main():
[2044]125    usage = """usage: %prog [push|pull|pull-common] GUEST"""
[1999]126
127    parser = optparse.OptionParser(usage)
[2044]128    # ext3 will probably supported for a while yet and a pretty
129    # reasonable thing to always try
130    parser.add_option('-t', '--types', dest="types", default="ext4,ext3",
131            help="filesystem type(s)")
132    parser.add_option('--creds-dir', dest="creds_dir", default="/root/creds",
133            help="directory to store/fetch credentials in")
134    options, args = parser.parse_args()
[1999]135
[2044]136    if not os.path.isdir(options.creds_dir):
137        raise Exception("/root/creds does not exist") # XXX STRING
138    # XXX check owned by root and appropriately chmodded
[1999]139
140    os.umask(0o077) # overly restrictive
141
142    if len(args) != 2:
[2044]143        parser.print_help()
[1999]144        raise Exception("Wrong number of arguments")
145
146    command = args[0]
147    guest   = args[1]
148
[2044]149    with WithMount(guest, options.types) as tmp_mount:
150        uid_lookup = lookup("%s/etc/passwd" % tmp_mount)
151        gid_lookup = lookup("%s/etc/group" % tmp_mount)
[1999]152        def push_files(files, type):
[2044]153            for (usergroup, perms, f) in files:
[1999]154                dest = "%s/%s" % (tmp_mount, f)
[2044]155                mkdir_p(os.path.dirname(dest)) # useful for .ssh
[1999]156                # assuming OK to overwrite
[2044]157                # XXX we could compare the files before doing anything...
158                shutil.copyfile("%s/%s/%s" % (options.creds_dir, type, f), dest)
159                try:
160                    os.chown(dest, uid_lookup[usergroup], gid_lookup[usergroup])
161                    os.chmod(dest, perms)
162                except:
163                    # never ever leave un-chowned files lying around
164                    os.unlink(dest)
165                    raise
[1999]166        def pull_files(files, type):
167            for (_, _, f) in files:
[2044]168                dest = "%s/%s/%s" % (options.creds_dir, type, f)
[1999]169                mkdir_p(os.path.dirname(dest))
170                # error if doesn't exist
171                shutil.copyfile("%s/%s" % (tmp_mount, f), dest)
172
173        if command == "push":
174            push_files(COMMON_CREDS, 'common')
175            push_files(COMMON_PROD_CREDS,  'common')
176            push_files(MACHINE_PROD_CREDS, 'machine/%s' % guest)
177        elif command == "pull":
178            pull_files(MACHINE_PROD_CREDS, 'machine/%s' % guest)
179        elif command == "pull-common":
180            pull_files(COMMON_CREDS, 'common')
181            pull_files(COMMON_PROD_CREDS,  'common')
182
183if __name__ == "__main__":
184    main()
Note: See TracBrowser for help on using the repository browser.