re6st-conf 6.08 KB
#!/usr/bin/python
import argparse, atexit, errno, os, subprocess, sqlite3, sys, time
from OpenSSL import crypto
from re6st import registry, utils

def create(path, text=None, mode=0666):
    fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, mode)
    try:
        os.write(fd, text)
    finally:
        os.close(fd)

def loadCert(pem):
    return crypto.load_certificate(crypto.FILETYPE_PEM, pem)

def main():
    parser = argparse.ArgumentParser(
        description="Setup script for re6stnet.",
        formatter_class=utils.HelpFormatter)
    _ = parser.add_argument
    _('--registry', required=True, metavar='URL',
        help="HTTP URL of the server delivering certificates.")
    _('--is-needed', action='store_true',
        help="Exit immediately after asking the registry CA. Status code is"
             " non-zero if we're already part of the network, which means"
             " re6st is already running or we're behind a re6st router.")
    _('--ca-only', action='store_true',
        help='Only fetch CA from registry and exit.')
    _('-d', '--dir',
        help="Directory where the key and certificate will be stored.")
    _('-r', '--req', nargs=2, action='append', metavar=('KEY', 'VALUE'),
        help="The registry only sets the Common Name of your certificate,"
             " which actually encodes your allocated prefix in the network."
             " You can repeat this option to add any field you want to its"
             " subject.")
    _('--email',
        help="Email address where your token is sent. Use -r option if you"
             " want to show an email in your certificate.")
    _('--token', help="The token you received.")
    _('--anonymous', action='store_true',
        help="Request an anonymous certificate. No email is required but the"
             " registry may deliver a longer prefix.")
    config = parser.parse_args()
    if config.dir:
        os.chdir(config.dir)
    conf_path = 're6stnet.conf'
    ca_path = 'ca.crt'
    cert_path = 'cert.crt'
    key_path = 'cert.key'
    dh_path = 'dh2048.pem'

    # Establish connection with server
    s = registry.RegistryClient(config.registry)

    # Get CA
    ca = s.getCa()
    network = utils.networkFromCa(loadCert(ca))
    if config.is_needed:
        route, err = subprocess.Popen(('ip', '-6', '-o', 'route', 'get',
                                       utils.ipFromBin(network)),
                                      stdout=subprocess.PIPE).communicate()
        sys.exit(err or route and
            utils.binFromIp(route.split()[8]).startswith(network))

    create(ca_path, ca)
    if config.ca_only:
        sys.exit()

    # Generating dh file
    if not os.access(dh_path, os.F_OK):
        r = subprocess.call(('openssl', 'dhparam', '-out', dh_path, '2048'))
        if r:
            sys.exit(r)

    req = crypto.X509Req()
    try:
        with open(cert_path) as f:
            cert = loadCert(f.read())
        components = dict(cert.get_subject().get_components())
        components.pop('CN', None)
    except IOError, e:
        if e.errno != errno.ENOENT:
            raise
        components = {}
    if config.req:
        components.update(config.req)
    subj = req.get_subject()
    for k, v in components.iteritems():
        if k == 'CN':
            sys.exit("CN field is reserved.")
        if v:
            setattr(subj, k, v)

    cert_fd = token_advice = None
    try:
        token = config.token
        if config.anonymous:
            if not (token is config.email is None):
                parser.error("--anonymous conflicts with --email/--token")
            token = ''
        elif not token:
            if not config.email:
                config.email = raw_input('Please enter your email address: ')
            s.requestToken(config.email)
            token_advice = "Use --token to retry without asking a new token\n"
            while not token:
                token = raw_input('Please enter your token: ')

        try:
            with open(key_path) as f:
                pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, f.read())
            key = None
            print "Reusing existing key."
        except IOError, e:
            if e.errno != errno.ENOENT:
                raise
            print "Generating 2048-bit key ..."
            pkey = crypto.PKey()
            pkey.generate_key(crypto.TYPE_RSA, 2048)
            key = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)
            create(key_path, key, 0600)

        req.set_pubkey(pkey)
        req.sign(pkey, 'sha1')
        req = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)

        # First make sure we can open certificate file for writing,
        # to avoid using our token for nothing.
        cert_fd = os.open(cert_path, os.O_CREAT | os.O_WRONLY, 0666)
        print "Requesting certificate ..."
        cert = s.requestCertificate(token, req)
        if not cert:
            token_advice = None
            sys.exit("Error: invalid or expired token")
    except:
        if cert_fd is not None and not os.lseek(cert_fd, 0, os.SEEK_END):
            os.remove(cert_path)
        if token_advice:
            atexit.register(sys.stdout.write, token_advice)
        raise
    os.write(cert_fd, cert)
    os.ftruncate(cert_fd, len(cert))
    os.close(cert_fd)

    cert = loadCert(cert)
    not_after = utils.notAfter(cert)
    print("Setup complete. Certificate is valid until %s UTC"
          " and will be automatically renewed after %s UTC" % (
        time.asctime(time.gmtime(not_after)),
        time.asctime(time.gmtime(not_after - registry.RENEW_PERIOD))))

    if not os.path.lexists(conf_path):
        create(conf_path, """\
registry %s
ca %s
cert %s
key %s
dh %s
# for udp only:
#pp 1194 udp
# increase re6stnet verbosity:
#verbose 3
# enable OpenVPN logging:
#ovpnlog
# increase OpenVPN verbosity:
#O--verb
#O3
""" % (config.registry, ca_path, cert_path, key_path, dh_path))
        print "Sample configuration file created."

    cn = utils.subnetFromCert(cert)
    subnet = network + utils.binFromSubnet(cn)
    print "Your subnet: %s/%u (CN=%s)" \
        % (utils.ipFromBin(subnet), len(subnet), cn)

if __name__ == "__main__":
    main()