예제 #1
0
def writeRhnCert(options, cert):
    if os.path.exists(DEFAULT_RHN_CERT_LOCATION):
        fileutils.rotateFile(DEFAULT_RHN_CERT_LOCATION, depth=5)
    fo = open(DEFAULT_RHN_CERT_LOCATION, 'w+b')
    fo.write(cert)
    fo.close()
    options.rhn_cert = DEFAULT_RHN_CERT_LOCATION
def writeRhnCert(options, cert):
    if os.path.exists(DEFAULT_RHN_CERT_LOCATION):
        fileutils.rotateFile(DEFAULT_RHN_CERT_LOCATION, depth=5)
    fo = open(DEFAULT_RHN_CERT_LOCATION, 'w+b')
    fo.write(cert)
    fo.close()
    options.rhn_cert = DEFAULT_RHN_CERT_LOCATION
예제 #3
0
def writeRhsmManifest(options, manifest):
    if os.path.exists(DEFAULT_RHSM_MANIFEST_LOCATION):
        fileutils.rotateFile(DEFAULT_RHSM_MANIFEST_LOCATION, depth=5)
    fo = open(DEFAULT_RHSM_MANIFEST_LOCATION, 'w+b')
    fo.write(manifest)
    fo.close()
    options.manifest = DEFAULT_RHSM_MANIFEST_LOCATION
예제 #4
0
def writeRhsmManifest(options, manifest):
    if os.path.exists(DEFAULT_RHSM_MANIFEST_LOCATION):
        fileutils.rotateFile(DEFAULT_RHSM_MANIFEST_LOCATION, depth=5)
    fo = open(DEFAULT_RHSM_MANIFEST_LOCATION, 'w+b')
    fo.write(manifest)
    fo.close()
    # Delete from temporary location
    if options.manifest_refresh:
        os.unlink(options.manifest)
    options.manifest = DEFAULT_RHSM_MANIFEST_LOCATION
예제 #5
0
def writeRhsmManifest(options, manifest):
    if os.path.exists(DEFAULT_RHSM_MANIFEST_LOCATION):
        fileutils.rotateFile(DEFAULT_RHSM_MANIFEST_LOCATION, depth=5)
    fo = open(DEFAULT_RHSM_MANIFEST_LOCATION, 'w+b')
    fo.write(manifest)
    fo.close()
    # Delete from temporary location
    if options.manifest_refresh:
        os.unlink(options.manifest)
    options.manifest = DEFAULT_RHSM_MANIFEST_LOCATION
예제 #6
0
def copyFiles(options):
    """ copies SSL cert and GPG key to --pub-tree if not in there already
        existence check should have already been done.
    """

    pubDir = cleanupAbsPath(options.pub_tree or DEFAULT_APACHE_PUB_DIRECTORY)

    def copyFile(file0, file1):
        if not os.path.exists(os.path.dirname(file1)):
            sys.stderr.write("ERROR: directory does not exist:\n       %s\n"
                             % os.path.dirname(file1))
            sys.exit(errnoBadPath)
        if not os.path.exists(file0):
            sys.stderr.write("ERROR: file does not exist:\n       %s\n"
                             % file0)
            sys.exit(errnoCANotFound)
        sys.stderr.write("""\
  Coping file into public directory tree:
    %s to
    %s
""" % (file0, file1))
        shutil.copy(file0, file1)

    # CA SSL cert
    if not options.no_ssl and options.ssl_cert:
        writeYN = 1
        dest = os.path.join(pubDir, os.path.basename(options.ssl_cert))
        if os.path.dirname(options.ssl_cert) != pubDir:
            if os.path.isfile(dest) \
              and getFileChecksum('md5', options.ssl_cert) != getFileChecksum('md5', dest):
                rotateFile(dest, options.verbose)
            elif os.path.isfile(dest):
                writeYN = 0
            if writeYN:
                copyFile(options.ssl_cert, dest)

    # corp GPG keys
    if not options.no_gpg and options.gpg_key:
        for gpg_key in options.gpg_key.split(","):
            writeYN = 1
            dest = os.path.join(pubDir, os.path.basename(gpg_key))
            if os.path.dirname(gpg_key) != pubDir:
                if os.path.isfile(dest) \
                  and getFileChecksum('md5', gpg_key) != getFileChecksum('md5', dest):
                    rotateFile(dest, options.verbose)
                elif os.path.isfile(dest):
                    writeYN = 0
                if writeYN:
                    copyFile(gpg_key, dest)
예제 #7
0
def copyFiles(options):
    """ copies SSL cert and GPG key to --pub-tree if not in there already
        existence check should have already been done.
    """

    pubDir = cleanupAbsPath(options.pub_tree or DEFAULT_APACHE_PUB_DIRECTORY)

    def copyFile(file0, file1):
        if not os.path.exists(os.path.dirname(file1)):
            sys.stderr.write("ERROR: directory does not exist:\n       %s\n"
                             % os.path.dirname(file1))
            sys.exit(errnoBadPath)
        if not os.path.exists(file0):
            sys.stderr.write("ERROR: file does not exist:\n       %s\n"
                             % file0)
            sys.exit(errnoCANotFound)
        sys.stderr.write("""\
  Coping file into public directory tree:
    %s to
    %s
""" % (file0, file1))
        shutil.copy(file0, file1)

    # CA SSL cert
    if not options.no_ssl and options.ssl_cert:
        writeYN = 1
        dest = os.path.join(pubDir, os.path.basename(options.ssl_cert))
        if os.path.dirname(options.ssl_cert) != pubDir:
            if os.path.isfile(dest) \
              and getFileChecksum('md5', options.ssl_cert) != getFileChecksum('md5', dest):
                rotateFile(dest, options.verbose)
            elif os.path.isfile(dest):
                writeYN = 0
            if writeYN:
                copyFile(options.ssl_cert, dest)

    # corp GPG keys
    if not options.no_gpg and options.gpg_key:
        for gpg_key in options.gpg_key.split(","):
            writeYN = 1
            dest = os.path.join(pubDir, os.path.basename(gpg_key))
            if os.path.dirname(gpg_key) != pubDir:
                if os.path.isfile(dest) \
                  and getFileChecksum('md5', gpg_key) != getFileChecksum('md5', dest):
                    rotateFile(dest, options.verbose)
                elif os.path.isfile(dest):
                    writeYN = 0
                if writeYN:
                    copyFile(gpg_key, dest)
예제 #8
0
    def updateDir(self, newdir=None, verbosity=0):
        """ changes the CA configuration file's directory setting (if need be)
            in place. Touches nothing else.
        """

        if self.updateLegacy(newdir):
            return

        try:
            fo = open(self.filename, 'r')
        except:
            return

        olddir = ''
        if newdir is None:
            newdir = os.path.dirname(self.filename)

        newfile = ""
        hit_CA_defaultYN = 0

        line = fo.readline()
        while line:
            if string.strip(line) == '[ CA_default ]':
                # we don't care much until we hit this label
                hit_CA_defaultYN = 1
            if hit_CA_defaultYN:
                vector = string.split(line, '=')
                if len(vector) == 2:
                    key, value = vector
                    if string.strip(key) == 'dir':
                        value = string.strip(value)
                        olddir = value
                        line = '%s= %s\n' % (key, newdir)
                        hit_CA_defaultYN = 0
                        if newdir == olddir:
                            # nothing to do
                            return
            newfile = newfile + line
            line = fo.readline()

        try:
            rotated = rotateFile(filepath=self.filename, verbosity=verbosity)
            if verbosity >= 0 and rotated:
                print "Rotated: %s --> %s" % (os.path.basename(
                    self.filename), os.path.basename(rotated))
        except ValueError:
            pass
        fo = open(self.filename, 'w')
        fo.write(newfile)
        fo.close()
        os.chmod(self.filename, 0600)
예제 #9
0
    def updateDir(self, newdir=None, verbosity=0):
        """ changes the CA configuration file's directory setting (if need be)
            in place. Touches nothing else.
        """

        if self.updateLegacy(newdir):
            return

        try:
            fo = open(self.filename, 'r')
        except:
            return

        olddir = ''
        if newdir is None:
            newdir = os.path.dirname(self.filename)

        newfile = ""
        hit_CA_defaultYN = 0

        line = fo.readline()
        while line:
            if string.strip(line) == '[ CA_default ]':
                # we don't care much until we hit this label
                hit_CA_defaultYN = 1
            if hit_CA_defaultYN:
                vector = string.split(line, '=')
                if len(vector) == 2:
                    key, value = vector
                    if string.strip(key) == 'dir':
                        value = string.strip(value)
                        olddir = value
                        line = '%s= %s\n' % (key, newdir)
                        hit_CA_defaultYN = 0
                        if newdir == olddir:
                            # nothing to do
                            return
            newfile = newfile + line
            line = fo.readline()

        try:
            rotated = rotateFile(filepath=self.filename, verbosity=verbosity)
            if verbosity>=0 and rotated:
                print "Rotated: %s --> %s" % (os.path.basename(self.filename),
                                              os.path.basename(rotated))
        except ValueError:
            pass
        fo = open(self.filename, 'w')
        fo.write(newfile)
        fo.close()
        os.chmod(self.filename, 0600)
예제 #10
0
def genPrivateCaKey(password, d, verbosity=0, forceYN=0):
    """ private CA key generation """

    gendir(d['--dir'])
    ca_key = os.path.join(d['--dir'], os.path.basename(d['--ca-key']))

    if not forceYN and os.path.exists(ca_key):
        sys.stderr.write("""\
ERROR: a CA private key already exists:
       %s
       If you wish to generate a new one, use the --force option.
""" % ca_key)
        sys.exit(errnoGeneralError)

    args = ("/usr/bin/openssl genrsa -passout pass:%s %s -out %s 2048" %
            ('%s', CRYPTO, repr(cleanupAbsPath(ca_key))))

    if verbosity >= 0:
        print "Generating private CA key: %s" % ca_key
        if verbosity > 1:
            print "Commandline:", args % "PASSWORD"
    try:
        rotated = rotateFile(filepath=ca_key, verbosity=verbosity)
        if verbosity >= 0 and rotated:
            print "Rotated: %s --> %s" \
                  % (d['--ca-key'], os.path.basename(rotated))
    except ValueError:
        pass

    cwd = chdir(_getWorkDir())
    try:
        ret, out_stream, err_stream = rhn_popen(args % repr(password))
    finally:
        chdir(cwd)

    out = out_stream.read()
    out_stream.close()
    err = err_stream.read()
    err_stream.close()
    if ret:
        raise GenPrivateCaKeyException("Certificate Authority private SSL "
                                       "key generation failed:\n%s\n%s" %
                                       (out, err))
    if verbosity > 2:
        if out:
            print "STDOUT:", out
        if err:
            print "STDERR:", err

    # permissions:
    os.chmod(ca_key, 0600)
예제 #11
0
def genPrivateCaKey(password, d, verbosity=0, forceYN=0):
    """ private CA key generation """

    gendir(d['--dir'])
    ca_key = os.path.join(d['--dir'], os.path.basename(d['--ca-key']))

    if not forceYN and os.path.exists(ca_key):
        sys.stderr.write("""\
ERROR: a CA private key already exists:
       %s
       If you wish to generate a new one, use the --force option.
""" % ca_key)
        sys.exit(errnoGeneralError)

    args = ("/usr/bin/openssl genrsa -passout pass:%s %s -out %s 2048"
            % ('%s', CRYPTO, repr(cleanupAbsPath(ca_key))))

    if verbosity >= 0:
        print("Generating private CA key: %s" % ca_key)
        if verbosity > 1:
            print("Commandline:", args % "PASSWORD")
    try:
        rotated = rotateFile(filepath=ca_key, verbosity=verbosity)
        if verbosity>=0 and rotated:
            print("Rotated: %s --> %s" \
                  % (d['--ca-key'], os.path.basename(rotated)))
    except ValueError:
        pass

    cwd = chdir(_getWorkDir())
    try:
        ret, out_stream, err_stream = rhn_popen(args % repr(password))
    finally:
        chdir(cwd)

    out = out_stream.read(); out_stream.close()
    err = err_stream.read(); err_stream.close()
    if ret:
        raise GenPrivateCaKeyException("Certificate Authority private SSL "
                                       "key generation failed:\n%s\n%s"
                                       % (out, err))
    if verbosity > 2:
        if out:
            print("STDOUT:", out)
        if err:
            print("STDERR:", err)

    # permissions:
    os.chmod(ca_key, int('0600',8))
예제 #12
0
def genServerKey(d, verbosity=0):
    """ private server key generation """

    serverKeyPairDir = os.path.join(d['--dir'],
                                    getMachineName(d['--set-hostname']))
    gendir(serverKeyPairDir)

    server_key = os.path.join(serverKeyPairDir,
                              os.path.basename(d['--server-key']))

    args = ("/usr/bin/openssl genrsa -out %s 2048" %
            (repr(cleanupAbsPath(server_key))))

    # generate the server key
    if verbosity >= 0:
        print "\nGenerating the web server's SSL private key: %s" % server_key
        if verbosity > 1:
            print "Commandline:", args

    try:
        rotated = rotateFile(filepath=server_key, verbosity=verbosity)
        if verbosity >= 0 and rotated:
            print "Rotated: %s --> %s" % (d['--server-key'],
                                          os.path.basename(rotated))
    except ValueError:
        pass

    cwd = chdir(_getWorkDir())
    try:
        ret, out_stream, err_stream = rhn_popen(args)
    finally:
        chdir(cwd)

    out = out_stream.read()
    out_stream.close()
    err = err_stream.read()
    err_stream.close()
    if ret:
        raise GenServerKeyException(
            "web server's SSL key generation failed:\n%s\n%s" % (out, err))
    if verbosity > 2:
        if out:
            print "STDOUT:", out
        if err:
            print "STDERR:", err

    # permissions:
    os.chmod(server_key, 0600)
예제 #13
0
def genServerKey(d, verbosity=0):
    """ private server key generation """

    serverKeyPairDir = os.path.join(d['--dir'],
                                    getMachineName(d['--set-hostname']))
    gendir(serverKeyPairDir)

    server_key = os.path.join(serverKeyPairDir,
                              os.path.basename(d['--server-key']))

    args = ("/usr/bin/openssl genrsa -out %s 2048"
            % (repr(cleanupAbsPath(server_key))))

    # generate the server key
    if verbosity >= 0:
        print("\nGenerating the web server's SSL private key: %s" % server_key)
        if verbosity > 1:
            print("Commandline:", args)

    try:
        rotated = rotateFile(filepath=server_key, verbosity=verbosity)
        if verbosity>=0 and rotated:
            print("Rotated: %s --> %s" % (d['--server-key'],
                                          os.path.basename(rotated)))
    except ValueError:
        pass

    cwd = chdir(_getWorkDir())
    try:
        ret, out_stream, err_stream = rhn_popen(args)
    finally:
        chdir(cwd)

    out = out_stream.read(); out_stream.close()
    err = err_stream.read(); err_stream.close()
    if ret:
        raise GenServerKeyException("web server's SSL key generation failed:\n%s\n%s"
                                % (out, err))
    if verbosity > 2:
        if out:
            print("STDOUT:", out)
        if err:
            print("STDERR:", err)

    # permissions:
    os.chmod(server_key, int('0600',8))
예제 #14
0
    def save(self, d, caYN=0, verbosity=0):
        """ d == commandline dictionary """

        mapping = {
                '--set-country'     : 'C',
                '--set-state'       : 'ST',
                '--set-city'        : 'L',
                '--set-org'         : 'O',
                '--set-org-unit'    : 'OU',
                '--set-common-name' : 'CN', # these two will never occur at the
                '--set-hostname'    : 'CN', # same time
                '--set-email'       : 'emailAddress',
                  }

        rdn = {}
        for k in d.keys():
            if mapping.has_key(k):
                rdn[mapping[k]] = string.strip(d[k])

        openssl_cnf = ''
        if caYN:
            openssl_cnf = CONF_TEMPLATE_CA % (
              os.path.dirname(self.filename)+'/',
              gen_req_distinguished_name(rdn),
              )
        else:
            openssl_cnf = CONF_TEMPLATE_SERVER \
              % (gen_req_distinguished_name(rdn), gen_req_alt_names(d, rdn['CN']))

        try:
            rotated = rotateFile(filepath=self.filename,verbosity=verbosity)
            if verbosity>=0 and rotated:
                print "Rotated: %s --> %s" % (os.path.basename(self.filename),
                                              os.path.basename(rotated))
        except ValueError:
            pass
        fo = open(self.filename, 'w')
        fo.write(openssl_cnf)
        fo.close()
        os.chmod(self.filename, 0600)
        return openssl_cnf
예제 #15
0
    def save(self, d, caYN=0, verbosity=0):
        """ d == commandline dictionary """

        mapping = {
            '--set-country': 'C',
            '--set-state': 'ST',
            '--set-city': 'L',
            '--set-org': 'O',
            '--set-org-unit': 'OU',
            '--set-common-name': 'CN',  # these two will never occur at the
            '--set-hostname': 'CN',  # same time
            '--set-email': 'emailAddress',
        }

        rdn = {}
        for k in d.keys():
            if mapping.has_key(k):
                rdn[mapping[k]] = string.strip(d[k])

        openssl_cnf = ''
        if caYN:
            openssl_cnf = CONF_TEMPLATE_CA % (
                os.path.dirname(self.filename) + '/',
                gen_req_distinguished_name(rdn),
            )
        else:
            openssl_cnf = CONF_TEMPLATE_SERVER \
              % (gen_req_distinguished_name(rdn), gen_req_alt_names(d, rdn['CN']))

        try:
            rotated = rotateFile(filepath=self.filename, verbosity=verbosity)
            if verbosity >= 0 and rotated:
                print "Rotated: %s --> %s" % (os.path.basename(
                    self.filename), os.path.basename(rotated))
        except ValueError:
            pass
        fo = open(self.filename, 'w')
        fo.write(openssl_cnf)
        fo.close()
        os.chmod(self.filename, 0600)
        return openssl_cnf
예제 #16
0
    def save(self, d, caYN=0, verbosity=0):
        """ d == commandline dictionary """

        mapping = {
            "--set-country": "C",
            "--set-state": "ST",
            "--set-city": "L",
            "--set-org": "O",
            "--set-org-unit": "OU",
            "--set-common-name": "CN",  # these two will never occur at the
            "--set-hostname": "CN",  # same time
            "--set-email": "emailAddress",
        }

        rdn = {}
        for k in d.keys():
            if mapping.has_key(k):
                rdn[mapping[k]] = string.strip(d[k])

        openssl_cnf = ""
        if caYN:
            openssl_cnf = CONF_TEMPLATE_CA % (os.path.dirname(self.filename) + "/", gen_req_distinguished_name(rdn))
        else:
            openssl_cnf = CONF_TEMPLATE_SERVER % gen_req_distinguished_name(rdn)

        try:
            rotated = rotateFile(filepath=self.filename, verbosity=verbosity)
            if verbosity >= 0 and rotated:
                print "Rotated: %s --> %s" % (os.path.basename(self.filename), os.path.basename(rotated))
        except ValueError:
            pass
        fo = open(self.filename, "w")
        fo.write(openssl_cnf)
        fo.close()
        os.chmod(self.filename, 0600)
        return openssl_cnf
예제 #17
0
def main():
    """ main routine
        1    general failure
        10   general sanity check failure (to include a remedial cert
             version check)
        11   expired!
        12   certificate version fails remedially
        13   certificate missing in manifest
        14   manifest signature incorrect
        15   cannot load mapping files
        16   manifest download failed
        17   manifest refresh failed
        30   local activation failure

        90   not registered to rhsm
        91   enabling sat repo failed

        127  general unknown failure (not really mapped yet)

        FIXME - need to redo how we process error codes - very manual
    """
    # pylint: disable=R0911

    options = processCommandline()

    if not cdn_activation:
        writeError(
            "Package spacewalk-backend-cdn has to be installed for using this tool."
        )
        sys.exit(1)

    # CDN Deactivation
    if options.deactivate:
        cdn_activation.Activation.deactivate()
        # Rotate the manifest to not have any currently used
        if os.path.exists(DEFAULT_RHSM_MANIFEST_LOCATION):
            fileutils.rotateFile(DEFAULT_RHSM_MANIFEST_LOCATION, depth=5)
            os.unlink(DEFAULT_RHSM_MANIFEST_LOCATION)
        return 0

    if options.rhn_cert:
        writeError(
            "Activation with RHN Classic Satellite Certificate is deprecated.\nPlease obtain a Manifest for this"
            " Satellite version via https://access.redhat.com/knowledge/tools/satcert, "
            "and re-run this activation tool with option --manifest=MANIFEST-FILE."
        )
        sys.exit(1)

    if not options.manifest:
        if os.path.exists(DEFAULT_RHSM_MANIFEST_LOCATION):
            options.manifest = DEFAULT_RHSM_MANIFEST_LOCATION
            if options.manifest_info:
                cdn_activation.Activation.manifest_info(
                    DEFAULT_RHSM_MANIFEST_LOCATION)
                return 0
            # Call regeneration API on Candlepin server
            if options.manifest_reconcile_request:
                log(0, "Requesting manifest regeneration...")
                ok = cdn_activation.Activation.refresh_manifest(
                    DEFAULT_RHSM_MANIFEST_LOCATION,
                    http_proxy=options.http_proxy,
                    http_proxy_username=options.http_proxy_username,
                    http_proxy_password=options.http_proxy_password)
                if not ok:
                    writeError("Manifest regeneration failed!")
                    return 17
                log(0, "Manifest regeneration requested.")
                return 0
            # Get new refreshed manifest from Candlepin server
            if options.manifest_download:
                log(0, "Downloading manifest...")
                path = cdn_activation.Activation.download_manifest(
                    DEFAULT_RHSM_MANIFEST_LOCATION,
                    http_proxy=options.http_proxy,
                    http_proxy_username=options.http_proxy_username,
                    http_proxy_password=options.http_proxy_password)
                if not path:
                    writeError("Manifest download failed!")
                    return 16
                if options.manifest_refresh:
                    options.manifest = path
                else:
                    log(0, "New manifest saved to: '%s'" % path)
                    return 0
        else:
            writeError(
                "No currently activated manifest was found. "
                "Run the activation tool with option --manifest=MANIFEST.")
            return 1
    # Handle RHSM manifest
    try:
        cdn_activate = cdn_activation.Activation(options.manifest)
    except CdnMappingsLoadError, e:
        writeError(e)
        return 15
예제 #18
0
def writeClientConfigOverrides(options):
    """ write our "overrides" configuration file
        This generated file is a configuration mapping file that is used
        to map settings in up2date and rhn_register when run through a
        seperate script.
    """

    up2dateConfMap = {
        # some are directly mapped, others are handled more delicately
        'http_proxy':           'httpProxy',
        'http_proxy_username':  '******',
        'http_proxy_password':  '******',
        'hostname':             'serverURL',
        'ssl_cert':             'sslCACert',
        'no_gpg':               'useGPG',
    }

    _bootstrapDir = cleanupAbsPath(os.path.join(options.pub_tree, 'bootstrap'))

    if not os.path.exists(_bootstrapDir):
        print "* creating '%s'" % _bootstrapDir
        os.makedirs(_bootstrapDir) # permissions should be fine

    d = {}
    if options.hostname:
        scheme = 'https'
        if options.no_ssl:
            scheme = 'http'
        d['serverURL'] = scheme + '://' + options.hostname + '/XMLRPC'
        d['noSSLServerURL'] = 'http://' + options.hostname + '/XMLRPC'
    
    # if proxy, enable it
    # if "", disable it
    if options.http_proxy:
        d['enableProxy'] = '1'
        d[up2dateConfMap['http_proxy']] = options.http_proxy
    else:
        d['enableProxy'] = '0'
        d[up2dateConfMap['http_proxy']] = ""

    # if proxy username, enable auth proxy
    # if "", disable it
    if options.http_proxy_username:
        d['enableProxyAuth'] = '1'
        d[up2dateConfMap['http_proxy_username']] = options.http_proxy_username
        d[up2dateConfMap['http_proxy_password']] = options.http_proxy_password
    else:
        d['enableProxyAuth'] = '0'
        d[up2dateConfMap['http_proxy_username']] = ""
        d[up2dateConfMap['http_proxy_password']] = ""

    # CA SSL certificate is a bit complicated. options.ssl_cert may be a file
    # or it may be an RPM or it may be "", which means "try to figure it out
    # by searching through the --pub-tree on your own.
    _isRpmYN = processCACertPath(options)
    if not options.ssl_cert:
        sys.stderr.write("WARNING: no SSL CA certificate or RPM found in %s\n" % options.pub_tree)
        if not options.no_ssl:
            sys.stderr.write("         Fix it by hand or turn off SSL in the clients (--no-ssl)\n")
    _certname = os.path.basename(options.ssl_cert) or CA_CRT_NAME
    _certdir = os.path.dirname(DEFAULT_CA_CERT_PATH)
    if _isRpmYN:
        hdr = rhn_rpm.get_package_header(options.ssl_cert)
        # Grab the first file out of the rpm
        d[up2dateConfMap['ssl_cert']] = hdr[rhn_rpm.RPMTAG_FILENAMES][0] # UGLY!
    else:
        d[up2dateConfMap['ssl_cert']] = os.path.join(_certdir, _certname)
    d[up2dateConfMap['no_gpg']] = int(operator.truth(not options.no_gpg))

    writeYN = 1
    _overrides = cleanupAbsPath(os.path.join(_bootstrapDir, options.overrides))
    if os.path.exists(_overrides):
        if readConfigFile(_overrides) != d:
            # only back it up if different
            backup = rotateFile(_overrides, depth=5, verbosity=options.verbose)
            if backup and options.verbose>=0:
                print """\
* WARNING: if there were hand edits to the rotated (backed up) file,
           some settings may need to be migrated."""
        else:
            # exactly the same... no need to write
            writeYN = 0
            print """\
* client configuration overrides (old and new are identical; not written):
  '%s'\n""" % _overrides

    if writeYN:
        fout = open(_overrides, 'wb')
        # header
        fout.write("""\
# RHN Client (rhn_register/up2date) config-overrides file v4.0
#
# To be used only in conjuction with client_config_update.py
#
# This file was autogenerated.
#
# The simple rules:
#     - a setting explicitely overwrites the setting in
#       /etc/syconfig/rhn/{rhn_register,up2date} on the client system.
#     - if a setting is removed, the client's state for that setting remains
#       unchanged.

""")
        keys = d.keys()
        keys.sort()
        for key in keys:
            if d[key] is not None:
                fout.write("%s=%s\n" % (key, d[key]))
        fout.close()
        print """\
* bootstrap overrides (written):
  '%s'\n""" % _overrides
        if options.verbose>=0:
            print "Values written:"
            for k, v in d.items():
                print k + ' '*(25-len(k)) + repr(v)
예제 #19
0
def generateBootstrapScript(options):
    "write, copy and place files into /var/www/html/pub/bootstrap/"

    orgCACert = os.path.basename(options.ssl_cert or '')

    # write to /var/www/html/pub/bootstrap/<options.overrides>
    writeClientConfigOverrides(options)

    isRpmYN = processCACertPath(options)
    pubname = os.path.basename(options.pub_tree)

    # generate script
    # In processCommandline() we have turned all boolean values to 0 or 1
    # this means that we can negate those booleans with 1 - their current
    # value (instead of doing not value which can yield True/False, which
    # would print as such)
    newScript = getHeader(PRODUCT_NAME, options.activation_keys,
                  options.gpg_key, options.overrides, options.hostname,
                  orgCACert, isRpmYN, 1 - options.no_ssl, 1 - options.no_gpg,
                  options.allow_config_actions, options.allow_remote_commands,
                  1 - options.no_up2date, pubname)

    writeYN = 1

    # concat all those script-bits
    newScript = newScript + getConfigFilesSh() + getUp2dateScriptsSh()

    
    newScript = newScript + getGPGKeyImportSh() + getCorpCACertSh() + \
                getRegistrationSh(PRODUCT_NAME) 

    #5/16/05 wregglej 159437 - moving stuff that messes with the allowed-action dir to after registration
    if options.allow_config_actions:
        newScript = newScript + getAllowConfigManagement()
    if options.allow_remote_commands:
        newScript = newScript + getAllowRemoteCommands()

    #5/16/05 wregglej 159437 - moved the stuff that up2dates the entire box to after allowed-actions permissions are set.
    newScript = newScript + getUp2dateTheBoxSh()

    _bootstrapDir = cleanupAbsPath(os.path.join(options.pub_tree, 'bootstrap'))
    _script = cleanupAbsPath(os.path.join(_bootstrapDir, options.script))

    if os.path.exists(_script):
        oldScript = open(_script, 'rb').read()
        if oldScript == newScript:
            writeYN = 0
        elif os.path.exists(_script):
            backup = rotateFile(_script, depth=5, verbosity=options.verbose)
            if backup and options.verbose>=0:
                print "* rotating %s --> %s" % (_script, backup)
        del oldScript

    if writeYN:
        fout = open(_script, 'wb')
        fout.write(newScript)
        fout.close()
        print """\
* bootstrap script (written):
    '%s'\n""" % _script
    else:
        print """\
* boostrap script (old and new scripts identical; not written):
    '%s'\n""" % _script
예제 #20
0
def generateBootstrapScript(options):
    "write, copy and place files into /var/www/html/pub/bootstrap/"

    orgCACert = os.path.basename(options.ssl_cert or '')

    # write to /var/www/html/pub/bootstrap/<options.overrides>
    writeClientConfigOverrides(options)

    isRpmYN = processCACertPath(options)
    pubname = os.path.basename(options.pub_tree)

    # generate script
    # In processCommandline() we have turned all boolean values to 0 or 1
    # this means that we can negate those booleans with 1 - their current
    # value (instead of doing not value which can yield True/False, which
    # would print as such)
    newScript = getHeader(MY_PRODUCT_NAME, options.activation_keys,
                          options.gpg_key, options.overrides, options.hostname,
                          orgCACert, isRpmYN, 1 - options.no_ssl,
                          1 - options.no_gpg, options.allow_config_actions,
                          options.allow_remote_commands,
                          1 - options.no_up2date, pubname)

    writeYN = 1

    # concat all those script-bits
    newScript = newScript + getConfigFilesSh() + getUp2dateScriptsSh()


    newScript = newScript + getGPGKeyImportSh() + getCorpCACertSh() + \
                getRegistrationSh(MY_PRODUCT_NAME)

    #5/16/05 wregglej 159437 - moving stuff that messes with the allowed-action dir to after registration
    if options.allow_config_actions:
        newScript = newScript + getAllowConfigManagement()
    if options.allow_remote_commands:
        newScript = newScript + getAllowRemoteCommands()

    #5/16/05 wregglej 159437 - moved the stuff that up2dates the entire box to after allowed-actions permissions are set.
    newScript = newScript + getUp2dateTheBoxSh()

    _bootstrapDir = cleanupAbsPath(os.path.join(options.pub_tree, 'bootstrap'))
    _script = cleanupAbsPath(os.path.join(_bootstrapDir, options.script))

    if os.path.exists(_script):
        oldScript = open(_script, 'rb').read()
        if oldScript == newScript:
            writeYN = 0
        elif os.path.exists(_script):
            backup = rotateFile(_script, depth=5, verbosity=options.verbose)
            if backup and options.verbose >= 0:
                print "* rotating %s --> %s" % (_script, backup)
        del oldScript

    if writeYN:
        fout = open(_script, 'wb')
        fout.write(newScript)
        fout.close()
        print """\
* bootstrap script (written):
    '%s'\n""" % _script
    else:
        print """\
* boostrap script (old and new scripts identical; not written):
    '%s'\n""" % _script
예제 #21
0
def genServerCert(password, d, verbosity=0):
    """ server cert generation and signing """

    serverKeyPairDir = os.path.join(d['--dir'],
                                    getMachineName(d['--set-hostname']))

    genServerCert_dependencies(password, d)

    ca_key = os.path.join(d['--dir'], os.path.basename(d['--ca-key']))
    ca_cert = os.path.join(d['--dir'], os.path.basename(d['--ca-cert']))

    server_cert_req = os.path.join(serverKeyPairDir,
                                   os.path.basename(d['--server-cert-req']))
    server_cert = os.path.join(serverKeyPairDir,
                               os.path.basename(d['--server-cert']))
    ca_openssl_cnf = os.path.join(d['--dir'], CA_OPENSSL_CNF_NAME)

    index_txt = os.path.join(d['--dir'], 'index.txt')
    serial = os.path.join(d['--dir'], 'serial')

    try:
        os.unlink(index_txt)
    except:
        pass

    # figure out the serial file and truncate the index.txt file.
    ser = figureSerial(ca_cert, serial, index_txt)

    # need to insure the directory declared in the ca_openssl.cnf
    # file is current:
    configFile = ConfigFile(ca_openssl_cnf)
    configFile.updateDir()

    args = ("/usr/bin/openssl ca -extensions req_server_x509_extensions -passin pass:%s -outdir ./ -config %s "
            "-in %s -batch -cert %s -keyfile %s -startdate %s -days %s "
            "-md %s -out %s"
            % ('%s', repr(cleanupAbsPath(ca_openssl_cnf)),
               repr(cleanupAbsPath(server_cert_req)),
               repr(cleanupAbsPath(ca_cert)),
               repr(cleanupAbsPath(ca_key)), d['--startdate'],
               repr(d['--cert-expiration']), MD,
               repr(cleanupAbsPath(server_cert))))

    if verbosity >= 0:
        print("\nGenerating/signing web server's SSL certificate: %s" % d['--server-cert'])
        if verbosity > 1:
            print("Commandline:", args % 'PASSWORD')
    try:
        rotated = rotateFile(filepath=server_cert, verbosity=verbosity)
        if verbosity>=0 and rotated:
            print("Rotated: %s --> %s" % (d['--server-cert'],
                                          os.path.basename(rotated)))
    except ValueError:
        pass

    cwd = chdir(_getWorkDir())
    try:
        ret, out_stream, err_stream = rhn_popen(args % repr(password))
    finally:
        chdir(cwd)

    out = sstr(out_stream.read()); out_stream.close()
    err = sstr(err_stream.read()); err_stream.close()

    if ret:
        # signature for a mistyped CA password
        if err.find("unable to load CA private key") != -1 \
          and err.find("error:0906A065:PEM routines:PEM_do_header:bad decrypt:pem_lib.c") != -1 \
          and err.find("error:06065064:digital envelope routines:EVP_DecryptFinal:bad decrypt:evp_enc.c") != -1:
            raise GenServerCertException(
                    "web server's SSL certificate generation/signing "
                    "failed:\nDid you mistype your CA password?")
        else:
            raise GenServerCertException(
                    "web server's SSL certificate generation/signing "
                    "failed:\n%s\n%s" % (out, err))

    if verbosity > 2:
        if out:
            print("STDOUT:", out)
        if err:
            print("STDERR:", err)

    # permissions:
    os.chmod(server_cert, int('0644',8))

    # cleanup duplicate XX.pem file:
    pemFilename = os.path.basename(ser.upper()+'.pem')
    if pemFilename != server_cert and os.path.exists(pemFilename):
        os.unlink(pemFilename)

    # cleanup the old index.txt file
    try:
        os.unlink(index_txt + '.old')
    except:
        pass

    # cleanup the old serial file
    try:
        os.unlink(serial + '.old')
    except:
        pass
예제 #22
0
def genPublicCaCert(password, d, verbosity=0, forceYN=0):
    """ public CA certificate (client-side) generation """

    ca_key = os.path.join(d['--dir'], os.path.basename(d['--ca-key']))
    ca_cert_name = os.path.basename(d['--ca-cert'])
    ca_cert = os.path.join(d['--dir'], ca_cert_name)
    ca_openssl_cnf = os.path.join(d['--dir'], CA_OPENSSL_CNF_NAME)

    genPublicCaCert_dependencies(password, d, forceYN)

    configFile = ConfigFile(ca_openssl_cnf)
    if d.has_key('--set-hostname'):
        del d['--set-hostname']
    configFile.save(d, caYN=1, verbosity=verbosity)

    args = ("/usr/bin/openssl req -passin pass:%s -text -config %s "
            "-new -x509 -days %s -%s -key %s -out %s" %
            ('%s', repr(cleanupAbsPath(configFile.filename)),
             repr(d['--cert-expiration']), MD, repr(
                 cleanupAbsPath(ca_key)), repr(cleanupAbsPath(ca_cert))))

    if verbosity >= 0:
        print "\nGenerating public CA certificate: %s" % ca_cert
        print "Using distinguishing variables:"
        for k in ('--set-country', '--set-state', '--set-city', '--set-org',
                  '--set-org-unit', '--set-common-name', '--set-email'):
            print '    %s%s = "%s"' % (k, ' ' * (18 - len(k)), d[k])
        if verbosity > 1:
            print "Commandline:", args % "PASSWORD"

    try:
        rotated = rotateFile(filepath=ca_cert, verbosity=verbosity)
        if verbosity >= 0 and rotated:
            print "Rotated: %s --> %s" \
                  % (d['--ca-cert'], os.path.basename(rotated))
    except ValueError:
        pass

    cwd = chdir(_getWorkDir())
    try:
        ret, out_stream, err_stream = rhn_popen(args % repr(password))
    finally:
        chdir(cwd)

    out = out_stream.read()
    out_stream.close()
    err = err_stream.read()
    err_stream.close()
    if ret:
        raise GenPublicCaCertException(
            "Certificate Authority public "
            "SSL certificate generation failed:\n%s\n"
            "%s" % (out, err))
    if verbosity > 2:
        if out:
            print "STDOUT:", out
        if err:
            print "STDERR:", err

    latest_txt = os.path.join(d['--dir'], 'latest.txt')
    fo = open(latest_txt, 'wb')
    fo.write('%s\n' % ca_cert_name)
    fo.close()

    # permissions:
    os.chmod(ca_cert, 0644)
    os.chmod(latest_txt, 0644)
예제 #23
0
def genPublicCaCert(password, d, verbosity=0, forceYN=0):
    """ public CA certificate (client-side) generation """

    ca_key = os.path.join(d['--dir'], os.path.basename(d['--ca-key']))
    ca_cert_name = os.path.basename(d['--ca-cert'])
    ca_cert = os.path.join(d['--dir'], ca_cert_name)
    ca_openssl_cnf = os.path.join(d['--dir'], CA_OPENSSL_CNF_NAME)

    genPublicCaCert_dependencies(password, d, forceYN)

    configFile = ConfigFile(ca_openssl_cnf)
    if '--set-hostname' in d:
        del d['--set-hostname']
    configFile.save(d, caYN=1, verbosity=verbosity)

    args = ("/usr/bin/openssl req -passin pass:%s -text -config %s "
            "-new -x509 -days %s -%s -key %s -out %s"
            % ('%s', repr(cleanupAbsPath(configFile.filename)),
               repr(d['--cert-expiration']),
               MD, repr(cleanupAbsPath(ca_key)),
               repr(cleanupAbsPath(ca_cert))))

    if verbosity >= 0:
        print("\nGenerating public CA certificate: %s" % ca_cert)
        print("Using distinguishing variables:")
        for k in ('--set-country', '--set-state', '--set-city', '--set-org',
                  '--set-org-unit', '--set-common-name', '--set-email'):
            print('    %s%s = "%s"' % (k, ' '*(18-len(k)), d[k]))
        if verbosity > 1:
            print("Commandline:", args % "PASSWORD")

    try:
        rotated = rotateFile(filepath=ca_cert, verbosity=verbosity)
        if verbosity>=0 and rotated:
            print("Rotated: %s --> %s" \
                  % (d['--ca-cert'], os.path.basename(rotated)))
    except ValueError:
        pass

    cwd = chdir(_getWorkDir())
    try:
        ret, out_stream, err_stream = rhn_popen(args % repr(password))
    finally:
        chdir(cwd)

    out = out_stream.read(); out_stream.close()
    err = err_stream.read(); err_stream.close()
    if ret:
        raise GenPublicCaCertException("Certificate Authority public "
                                   "SSL certificate generation failed:\n%s\n"
                                   "%s" % (out, err))
    if verbosity > 2:
        if out:
            print("STDOUT:", out)
        if err:
            print("STDERR:", err)

    latest_txt = os.path.join(d['--dir'], 'latest.txt')
    fo = open(latest_txt, 'wb')
    fo.write(bstr('%s\n' % ca_cert_name))
    fo.close()

    # permissions:
    os.chmod(ca_cert, int('0644',8))
    os.chmod(latest_txt, int('0644',8))
예제 #24
0
    def updateLegacy(self, newdir=None, verbosity=1):
        """ in slightly older formatted ca_openssl.cnf files, there
            was no dir setting seperate from the database and serial
            settings. This function fixes that setup.

            Most of the time this function short-circuits early.
        """

        try:
            fo = open(self.filename, 'r')
        except:
            return

        if newdir is None:
            newdir = os.path.dirname(self.filename)

        newfile = ""
        in_CA_defaultYN = 0
        dirSetYN = 0

        line = fo.readline()
        while line:
            cleanLine = string.strip(line)

            # is this a label?
            isLabelYN = 0
            if cleanLine \
              and (cleanLine[0], cleanLine[-1]) == ('[',']'):
                isLabelYN = 1

            if cleanLine == '[ CA_default ]':
                # we don't care much until we hit this label
                in_CA_defaultYN = 1
            elif isLabelYN:
                in_CA_defaultYN = 0  # hit another label

            if in_CA_defaultYN:
                vector = string.split(line, '=')
                if len(vector) == 2:
                    key = string.strip(vector[0])
                    if key == 'dir':
                        # we should be OK - short-circuit
                        return
                    if key in ('database', 'serial'):
                        # we never hit a "dir" key
                        if not dirSetYN:
                            newfile = newfile + """\
dir                     = %s
database                = $dir/index.txt
serial                  = $dir/serial
""" % newdir
                            dirSetYN = 1
                        line = fo.readline()
                        continue

            newfile = newfile + line
            line = fo.readline()

        try:
            rotated = rotateFile(filepath=self.filename, verbosity=verbosity)
            if verbosity >= 0 and rotated:
                print "Rotated: %s --> %s" % (os.path.basename(
                    self.filename), os.path.basename(rotated))
        except ValueError:
            pass
        fo = open(self.filename, 'w')
        fo.write(newfile)
        fo.close()
        os.chmod(self.filename, 0600)

        return dirSetYN
예제 #25
0
def genServerCertReq(d, verbosity=0):
    """ private server cert request generation """

    serverKeyPairDir = os.path.join(d['--dir'],
                                    getMachineName(d['--set-hostname']))
    server_key = os.path.join(serverKeyPairDir,
                              os.path.basename(d['--server-key']))
    server_cert_req = os.path.join(serverKeyPairDir,
                                   os.path.basename(d['--server-cert-req']))
    server_openssl_cnf = os.path.join(serverKeyPairDir,
                                      SERVER_OPENSSL_CNF_NAME)

    genServerCertReq_dependencies(d)

    # XXX: hmm.. should private_key, etc. be set for this before the write?
    #      either that you pull the key/certs from the files all together?
    configFile = ConfigFile(server_openssl_cnf)
    if d.has_key('--set-common-name'):
        del d['--set-common-name']
    configFile.save(d, caYN=0, verbosity=verbosity)

    ## generate the server cert request
    args = ("/usr/bin/openssl req -%s -text -config %s -new -key %s -out %s " %
            (MD, repr(cleanupAbsPath(
                configFile.filename)), repr(cleanupAbsPath(server_key)),
             repr(cleanupAbsPath(server_cert_req))))

    if verbosity >= 0:
        print "\nGenerating web server's SSL certificate request: %s" % server_cert_req
        print "Using distinguished names:"
        for k in ('--set-country', '--set-state', '--set-city', '--set-org',
                  '--set-org-unit', '--set-hostname', '--set-email'):
            print '    %s%s = "%s"' % (k, ' ' * (18 - len(k)), d[k])
        if verbosity > 1:
            print "Commandline:", args

    try:
        rotated = rotateFile(filepath=server_cert_req, verbosity=verbosity)
        if verbosity >= 0 and rotated:
            print "Rotated: %s --> %s" % (d['--server-cert-req'],
                                          os.path.basename(rotated))
    except ValueError:
        pass

    cwd = chdir(_getWorkDir())
    try:
        ret, out_stream, err_stream = rhn_popen(args)
    finally:
        chdir(cwd)

    out = out_stream.read()
    out_stream.close()
    err = err_stream.read()
    err_stream.close()
    if ret:
        raise GenServerCertReqException(
            "web server's SSL certificate request generation "
            "failed:\n%s\n%s" % (out, err))
    if verbosity > 2:
        if out:
            print "STDOUT:", out
        if err:
            print "STDERR:", err

    # permissions:
    os.chmod(server_cert_req, 0600)
예제 #26
0
def writeClientConfigOverrides(options):
    """ write our "overrides" configuration file
        This generated file is a configuration mapping file that is used
        to map settings in up2date and rhn_register when run through a
        seperate script.
    """

    up2dateConfMap = {
        # some are directly mapped, others are handled more delicately
        'http_proxy':           'httpProxy',
        'http_proxy_username':  '******',
        'http_proxy_password':  '******',
        'hostname':             'serverURL',
        'ssl_cert':             'sslCACert',
        'no_gpg':               'useGPG',
    }

    _bootstrapDir = cleanupAbsPath(os.path.join(options.pub_tree, 'bootstrap'))

    if not os.path.exists(_bootstrapDir):
        print("* creating '%s'" % _bootstrapDir)
        os.makedirs(_bootstrapDir) # permissions should be fine

    d = {}
    if options.hostname:
        scheme = 'https'
        if options.no_ssl:
            scheme = 'http'
        d['serverURL'] = scheme + '://' + options.hostname + '/XMLRPC'
        d['noSSLServerURL'] = 'http://' + options.hostname + '/XMLRPC'

    # if proxy, enable it
    # if "", disable it
    if options.http_proxy:
        d['enableProxy'] = '1'
        d[up2dateConfMap['http_proxy']] = options.http_proxy
    else:
        d['enableProxy'] = '0'
        d[up2dateConfMap['http_proxy']] = ""

    # if proxy username, enable auth proxy
    # if "", disable it
    if options.http_proxy_username:
        d['enableProxyAuth'] = '1'
        d[up2dateConfMap['http_proxy_username']] = options.http_proxy_username
        d[up2dateConfMap['http_proxy_password']] = options.http_proxy_password
    else:
        d['enableProxyAuth'] = '0'
        d[up2dateConfMap['http_proxy_username']] = ""
        d[up2dateConfMap['http_proxy_password']] = ""

    # CA SSL certificate is a bit complicated. options.ssl_cert may be a file
    # or it may be an RPM or it may be "", which means "try to figure it out
    # by searching through the --pub-tree on your own.
    _isRpmYN = processCACertPath(options)
    if not options.ssl_cert:
        sys.stderr.write("WARNING: no SSL CA certificate or RPM found in %s\n" % options.pub_tree)
        if not options.no_ssl:
            sys.stderr.write("         Fix it by hand or turn off SSL in the clients (--no-ssl)\n")
    _certname = os.path.basename(options.ssl_cert) or CA_CRT_NAME
    _certdir = os.path.dirname(DEFAULT_CA_CERT_PATH)
    if _isRpmYN:
        hdr = rhn_rpm.get_package_header(options.ssl_cert)
        # Grab the first file out of the rpm
        d[up2dateConfMap['ssl_cert']] = hdr[rhn_rpm.rpm.RPMTAG_FILENAMES][0] # UGLY!
    else:
        d[up2dateConfMap['ssl_cert']] = os.path.join(_certdir, _certname)
    d[up2dateConfMap['no_gpg']] = int(operator.truth(not options.no_gpg))

    writeYN = 1
    _overrides = cleanupAbsPath(os.path.join(_bootstrapDir, options.overrides))
    if os.path.exists(_overrides):
        if readConfigFile(_overrides) != d:
            # only back it up if different
            backup = rotateFile(_overrides, depth=5, verbosity=options.verbose)
            if backup and options.verbose>=0:
                print("""\
* WARNING: if there were hand edits to the rotated (backed up) file,
           some settings may need to be migrated.""")
        else:
            # exactly the same... no need to write
            writeYN = 0
            print("""\
* client configuration overrides (old and new are identical; not written):
  '%s'\n""" % _overrides)

    if writeYN:
        fout = open(_overrides, 'w')
        # header
        fout.write("""\
# RHN Client (rhn_register/up2date) config-overrides file v4.0
#
# To be used only in conjuction with client_config_update.py
#
# This file was autogenerated.
#
# The simple rules:
#     - a setting explicitely overwrites the setting in
#       /etc/syconfig/rhn/{rhn_register,up2date} on the client system.
#     - if a setting is removed, the client's state for that setting remains
#       unchanged.

""")
        keys = list(d.keys())
        keys.sort()
        for key in keys:
            if d[key] is not None:
                fout.write("%s=%s\n" % (key, d[key]))
        fout.close()
        print("""\
* bootstrap overrides (written):
  '%s'\n""" % _overrides)
        if options.verbose>=0:
            print("Values written:")
            for k, v in list(d.items()):
                print(k + ' '*(25-len(k)) + repr(v))
예제 #27
0
def genServerCertReq(d, verbosity=0):
    """ private server cert request generation """

    serverKeyPairDir = os.path.join(d['--dir'],
                                    getMachineName(d['--set-hostname']))
    server_key = os.path.join(serverKeyPairDir,
                              os.path.basename(d['--server-key']))
    server_cert_req = os.path.join(serverKeyPairDir,
                                   os.path.basename(d['--server-cert-req']))
    server_openssl_cnf = os.path.join(serverKeyPairDir,
                                      SERVER_OPENSSL_CNF_NAME)

    genServerCertReq_dependencies(d)

    # XXX: hmm.. should private_key, etc. be set for this before the write?
    #      either that you pull the key/certs from the files all together?
    configFile = ConfigFile(server_openssl_cnf)
    if '--set-common-name' in d:
        del d['--set-common-name']
    configFile.save(d, caYN=0, verbosity=verbosity)

    ## generate the server cert request
    args = ("/usr/bin/openssl req -%s -text -config %s -new -key %s -out %s "
            % (MD, repr(cleanupAbsPath(configFile.filename)),
               repr(cleanupAbsPath(server_key)),
               repr(cleanupAbsPath(server_cert_req))))

    if verbosity >= 0:
        print("\nGenerating web server's SSL certificate request: %s" % server_cert_req)
        print("Using distinguished names:")
        for k in ('--set-country', '--set-state', '--set-city', '--set-org',
                  '--set-org-unit', '--set-hostname', '--set-email'):
            print('    %s%s = "%s"' % (k, ' '*(18-len(k)), d[k]))
        if verbosity > 1:
            print("Commandline:", args)

    try:
        rotated = rotateFile(filepath=server_cert_req, verbosity=verbosity)
        if verbosity>=0 and rotated:
            print("Rotated: %s --> %s" % (d['--server-cert-req'],
                                          os.path.basename(rotated)))
    except ValueError:
        pass

    cwd = chdir(_getWorkDir())
    try:
        ret, out_stream, err_stream = rhn_popen(args)
    finally:
        chdir(cwd)

    out = out_stream.read(); out_stream.close()
    err = err_stream.read(); err_stream.close()
    if ret:
        raise GenServerCertReqException(
                "web server's SSL certificate request generation "
                "failed:\n%s\n%s" % (out, err))
    if verbosity > 2:
        if out:
            print("STDOUT:", out)
        if err:
            print("STDERR:", err)

    # permissions:
    os.chmod(server_cert_req, int('0600',8))
예제 #28
0
def legacyTreeFixup(d):
    """ move old server.* files to and "unknown" machinename directory
        Most of this is Red Hat Satellite 2.* and 3.* changes. Near the end
        we get to 3.6 changes.
    """

    topdir = cleanupAbsPath(d['--dir'])

    oldTree = '/etc/sysconfig/rhn/ssl'
    if topdir != oldTree and os.path.exists(oldTree):
        sys.stderr.write("""\
WARNING: %s
         still exists even though
         %s
         is the currently configured build tree. You may wish to either
         (a) move %s to
             %s, or
         (b) point directly at the old tree by via the --dir option.
""" % (oldTree, topdir, oldTree, topdir))
        sys.stderr.write("Pausing for 5 secs")
        for i in range(5):
            sys.stderr.write(".")
            time.sleep(1)
        sys.stderr.write("\n")

    unknown = os.path.join(topdir, 'unknown')
    server_rpm_name = os.path.basename(d.get('--server-rpm', ''))
    serverKeyPairDir = None
    if d.has_key('--set-hostname'):
        serverKeyPairDir = os.path.join(d['--dir'],
                                        getMachineName(d['--set-hostname']))

    while os.path.exists(unknown):
        # to avoid clashing with a possible "unknown" machinename
        unknown = unknown + '_'

    old_server_splat = os.path.join(topdir, 'server.')

    moveMessage = ""
    for ext in ('key', 'csr', 'crt'):
        if os.path.exists(old_server_splat + ext):
            gendir(unknown)
            files = glob.glob(old_server_splat + ext + '*')
            moved = []
            for f in files:
                # move the files to the "unknown" directory
                new_server_splat = os.path.join(unknown, os.path.basename(f))
                if not os.path.exists(new_server_splat):
                    shutil.copy2(f, new_server_splat)
                    os.unlink(f)
                    moved.append(f)

            #if files and verbosity:
            if moved:
                s = 'server.' + ext + '*'
                moveMessage = moveMessage + (
                    '  <BUILD_DIR>/%s --> <BUILD_DIR>/%s/%s\n' %
                    (s, os.path.basename(unknown), s))

    # move legacy server SSL RPMs. But if server_rpm_name is the same name
    # as the target RPM name, then we move the RPMs into the appropriate
    # machine name directory.
    for name in [LEGACY_SERVER_RPM_NAME1, LEGACY_SERVER_RPM_NAME2]:
        old_server_rpms = glob.glob(os.path.join(topdir, name + '-*-*.*.rpm'))
        movedYN = 0
        for old_rpm in old_server_rpms:
            targetDir = unknown
            old_hdr = get_package_header(old_rpm)
            if old_hdr and old_hdr[
                    'name'] == server_rpm_name and serverKeyPairDir:
                targetDir = serverKeyPairDir
            gendir(targetDir)
            # move the files to the targetDir directory
            new_rpm = os.path.join(targetDir, os.path.basename(old_rpm))
            if not os.path.exists(new_rpm):
                shutil.copy2(old_rpm, new_rpm)
                os.unlink(old_rpm)
                movedYN = 1
        if movedYN:
            s = name + '-*-*.{noarch,src}.rpm'
            moveMessage = moveMessage + """\
  <BUILD_DIR>/%s
      --> <BUILD_DIR>/%s/%s\n""" % (s, os.path.basename(targetDir), s)

    # I move the first 100 .pem files I find
    # if there is more than that... oh well
    movedYN = 0
    for i in range(100):
        serial = fixSerial(hex(i))
        oldPemPath = os.path.join(topdir, serial + '.pem')
        newPemPath = os.path.join(unknown, serial + '.pem')
        if os.path.exists(oldPemPath) and not os.path.exists(newPemPath):
            gendir(unknown)
            shutil.copy2(oldPemPath, newPemPath)
            os.unlink(oldPemPath)
            movedYN = 1
    if movedYN:
        moveMessage = moveMessage + (
            '  <BUILD_DIR>/HEX*.pem --> <BUILD_DIR>/%s/HEX*.pem\n' %
            os.path.basename(unknown))

    if moveMessage:
        sys.stdout.write('\nLegacy tree structured file(s) moved:\n%s' %
                         moveMessage)

    # move rhn-org-httpd-ssl-MACHINENAME-VERSION.*.rpm files to the
    # MACHINENAME directory! (an RHN 3.6.0 change)
    rootFilename = pathJoin(topdir, 'rhn-org-httpd-ssl-key-pair-')
    filenames = glob.glob(rootFilename + '*')
    for filename in filenames:
        # note: assuming version-rel is of that form.
        machinename = filename[len(rootFilename):]
        machinename = string.join(string.split(machinename, '-')[:-2], '-')
        serverKeySetDir = pathJoin(topdir, machinename)
        gendir(serverKeySetDir)
        fileto = pathJoin(serverKeySetDir, filename)
        if os.path.exists(fileto):
            rotateFile(filepath=fileto, verbosity=0)
        shutil.copy2(filename, fileto)
        os.unlink(filename)
        print """\
Moved (legacy tree cleanup):
    %s
    ...moved to...
    %s""" % (filename, fileto)
예제 #29
0
def main():
    """ main routine
        1    general failure
        10   general sanity check failure (to include a remedial cert
             version check)
        11   expired!
        12   certificate version fails remedially
        13   certificate missing in manifest
        14   manifest signature incorrect
        15   cannot load mapping files
        16   manifest download failed
        17   manifest refresh failed
        30   local activation failure

        90   not registered to rhsm
        91   enabling sat repo failed

        127  general unknown failure (not really mapped yet)

        FIXME - need to redo how we process error codes - very manual
    """
    # pylint: disable=R0911

    options = processCommandline()

    if not cdn_activation:
        writeError("Package spacewalk-backend-cdn has to be installed for using this tool.")
        sys.exit(1)

    # CDN Deactivation
    if options.deactivate:
        cdn_activation.Activation.deactivate()
        # Rotate the manifest to not have any currently used
        if os.path.exists(DEFAULT_RHSM_MANIFEST_LOCATION):
            fileutils.rotateFile(DEFAULT_RHSM_MANIFEST_LOCATION, depth=5)
            os.unlink(DEFAULT_RHSM_MANIFEST_LOCATION)
        return 0

    if options.rhn_cert:
        writeError("Activation with RHN Classic Satellite Certificate is deprecated.\nPlease obtain a Manifest for this"
                   " Satellite version via https://access.redhat.com/knowledge/tools/satcert, "
                   "and re-run this activation tool with option --manifest=MANIFEST-FILE.")
        sys.exit(1)

    if not options.manifest:
        if os.path.exists(DEFAULT_RHSM_MANIFEST_LOCATION):
            options.manifest = DEFAULT_RHSM_MANIFEST_LOCATION
            if options.manifest_info:
                cdn_activation.Activation.manifest_info(DEFAULT_RHSM_MANIFEST_LOCATION)
                return 0
            # Call regeneration API on Candlepin server
            if options.manifest_reconcile_request:
                log(0, "Requesting manifest regeneration...")
                ok = cdn_activation.Activation.refresh_manifest(
                    DEFAULT_RHSM_MANIFEST_LOCATION,
                    http_proxy=options.http_proxy,
                    http_proxy_username=options.http_proxy_username,
                    http_proxy_password=options.http_proxy_password)
                if not ok:
                    writeError("Manifest regeneration failed!")
                    return 17
                log(0, "Manifest regeneration requested.")
                return 0
            # Get new refreshed manifest from Candlepin server
            if options.manifest_download:
                log(0, "Downloading manifest...")
                path = cdn_activation.Activation.download_manifest(
                    DEFAULT_RHSM_MANIFEST_LOCATION,
                    http_proxy=options.http_proxy,
                    http_proxy_username=options.http_proxy_username,
                    http_proxy_password=options.http_proxy_password)
                if not path:
                    writeError("Manifest download failed!")
                    return 16
                if options.manifest_refresh:
                    options.manifest = path
                else:
                    log(0, "New manifest saved to: '%s'" % path)
                    return 0
        else:
            writeError("No currently activated manifest was found. "
                       "Run the activation tool with option --manifest=MANIFEST.")
            return 1
    # Handle RHSM manifest
    try:
        cdn_activate = cdn_activation.Activation(options.manifest)
    except CdnMappingsLoadError, e:
        writeError(e)
        return 15
예제 #30
0
    def updateLegacy(self, newdir=None, verbosity=1):
        """ in slightly older formatted ca_openssl.cnf files, there
            was no dir setting seperate from the database and serial
            settings. This function fixes that setup.

            Most of the time this function short-circuits early.
        """

        try:
            fo = open(self.filename, 'r')
        except:
            return

        if newdir is None:
            newdir = os.path.dirname(self.filename)

        newfile = ""
        in_CA_defaultYN = 0
        dirSetYN = 0

        line = fo.readline()
        while line:
            cleanLine = string.strip(line)

            # is this a label?
            isLabelYN = 0
            if cleanLine \
              and (cleanLine[0], cleanLine[-1]) == ('[',']'):
                isLabelYN = 1

            if cleanLine == '[ CA_default ]':
                # we don't care much until we hit this label
                in_CA_defaultYN = 1
            elif isLabelYN:
                in_CA_defaultYN = 0 # hit another label

            if in_CA_defaultYN:
                vector = string.split(line, '=')
                if len(vector) == 2:
                    key = string.strip(vector[0])
                    if key == 'dir':
                        # we should be OK - short-circuit
                        return
                    if key in ('database', 'serial'):
                        # we never hit a "dir" key
                        if not dirSetYN:
                            newfile = newfile + """\
dir                     = %s
database                = $dir/index.txt
serial                  = $dir/serial
""" % newdir
                            dirSetYN = 1
                        line = fo.readline()
                        continue

            newfile = newfile + line
            line = fo.readline()

        try:
            rotated = rotateFile(filepath=self.filename, verbosity=verbosity)
            if verbosity>=0 and rotated:
                print "Rotated: %s --> %s" % (os.path.basename(self.filename),
                                              os.path.basename(rotated))
        except ValueError:
            pass
        fo = open(self.filename, 'w')
        fo.write(newfile)
        fo.close()
        os.chmod(self.filename, 0600)

        return dirSetYN
예제 #31
0
def generateBootstrapScript(options):
    "write, copy and place files into <DEFAULT_APACHE_PUB_DIRECTORY>/bootstrap/"

    orgCACert = os.path.basename(options.ssl_cert or '')

    # write to <DEFAULT_APACHE_PUB_DIRECTORY>/bootstrap/<options.overrides>
    writeClientConfigOverrides(options)

    isRpmYN = processCACertPath(options)
    pubname = os.path.basename(options.pub_tree)

    newScript = []

    # generate script
    # In processCommandline() we have turned all boolean values to 0 or 1
    # this means that we can negate those booleans with 1 - their current
    # value (instead of doing not value which can yield True/False, which
    # would print as such)
    newScript.append(
                    getHeader(
                            MY_PRODUCT_NAME,
                            options,
                            orgCACert,
                            isRpmYN,
                            pubname,
                            DEFAULT_APACHE_PUB_DIRECTORY
                            )
                    )

    writeYN = 1

    # concat all those script-bits
    newScript.append(getConfigFilesSh())

    # don't call this twice
    # getUp2dateScriptsSh()

    newScript.append(getGPGKeyImportSh())
    newScript.append(getCorpCACertSh())

    # SLES: install packages required for registration on systems that do not have them installed
    newScript.append(getRegistrationStackSh(options.salt))

    if not options.salt:
        newScript.append(getUp2dateScriptsSh())

    if (options.salt):
        newScript.append(removeTLSCertificate())
        newScript.append(getRegistrationSaltSh(MY_PRODUCT_NAME))
    else:
        newScript.append(getRegistrationSh(MY_PRODUCT_NAME))

    #5/16/05 wregglej 159437 - moving stuff that messes with the allowed-action dir to after registration
    if not options.salt:
        newScript.append(getAllowConfigManagement())
        newScript.append(getAllowRemoteCommands())

        #5/16/05 wregglej 159437 - moved the stuff that up2dates the entire box to after allowed-actions permissions are set.
        newScript.append(getUp2dateTheBoxSh(MY_PRODUCT_NAME, options.salt))

    _bootstrapDir = cleanupAbsPath(os.path.join(options.pub_tree, 'bootstrap'))
    _script = cleanupAbsPath(os.path.join(_bootstrapDir, options.script))

    newScript = ''.join(newScript)

    if os.path.exists(_script):
        oldScript = open(_script, 'r').read()
        if oldScript == newScript:
            writeYN = 0
        elif os.path.exists(_script):
            backup = rotateFile(_script, depth=5, verbosity=options.verbose)
            if backup and options.verbose>=0:
                print("* rotating %s --> %s" % (_script, backup))
        del oldScript

    if writeYN:
        fout = open(_script, 'w')
        fout.write(newScript)
        fout.close()
        print("""\
* bootstrap script (written):
    '%s'\n""" % _script)
    else:
        print("""\
* boostrap script (old and new scripts identical; not written):
    '%s'\n""" % _script)
예제 #32
0
def legacyTreeFixup(d):
    """ move old server.* files to and "unknown" machinename directory
        Most of this is Red Hat Satellite 2.* and 3.* changes. Near the end
        we get to 3.6 changes.
    """

    topdir = cleanupAbsPath(d['--dir'])

    oldTree = '/etc/sysconfig/rhn/ssl'
    if topdir != oldTree and os.path.exists(oldTree):
        sys.stderr.write("""\
WARNING: %s
         still exists even though
         %s
         is the currently configured build tree. You may wish to either
         (a) move %s to
             %s, or
         (b) point directly at the old tree by via the --dir option.
""" % (oldTree, topdir, oldTree, topdir))
        sys.stderr.write("Pausing for 5 secs")
        for i in range(5):
            sys.stderr.write("."); time.sleep(1)
        sys.stderr.write("\n")

    unknown = os.path.join(topdir, 'unknown')
    server_rpm_name = os.path.basename(d.get('--server-rpm', ''))
    serverKeyPairDir = None
    if '--set-hostname' in d:
        serverKeyPairDir = os.path.join(d['--dir'],
                                        getMachineName(d['--set-hostname']))

    while os.path.exists(unknown):
        # to avoid clashing with a possible "unknown" machinename
        unknown = unknown + '_'

    old_server_splat = os.path.join(topdir, 'server.')

    moveMessage = ""
    for ext in ('key', 'csr', 'crt'):
        if os.path.exists(old_server_splat+ext):
            gendir(unknown)
            files = glob.glob(old_server_splat+ext+'*')
            moved = []
            for f in files:
                # move the files to the "unknown" directory
                new_server_splat = os.path.join(unknown, os.path.basename(f))
                if not os.path.exists(new_server_splat):
                    shutil.copy2(f, new_server_splat)
                    os.unlink(f)
                    moved.append(f)

            #if files and verbosity:
            if moved:
                s = 'server.' + ext + '*'
                moveMessage = moveMessage + (
                  '  <BUILD_DIR>/%s --> <BUILD_DIR>/%s/%s\n'
                  % (s, os.path.basename(unknown), s))

    # move legacy server SSL RPMs. But if server_rpm_name is the same name
    # as the target RPM name, then we move the RPMs into the appropriate
    # machine name directory.
    for name in [LEGACY_SERVER_RPM_NAME1, LEGACY_SERVER_RPM_NAME2]:
        old_server_rpms = glob.glob(os.path.join(topdir, name+'-*-*.*.rpm'))
        movedYN = 0
        for old_rpm in old_server_rpms:
            targetDir = unknown
            old_hdr = get_package_header(old_rpm)
            if old_hdr and old_hdr['name'] == server_rpm_name and serverKeyPairDir:
                targetDir = serverKeyPairDir
            gendir(targetDir)
            # move the files to the targetDir directory
            new_rpm = os.path.join(targetDir, os.path.basename(old_rpm))
            if not os.path.exists(new_rpm):
                shutil.copy2(old_rpm, new_rpm)
                os.unlink(old_rpm)
                movedYN = 1
        if movedYN:
            s = name+'-*-*.{noarch,src}.rpm'
            moveMessage = moveMessage + """\
  <BUILD_DIR>/%s
      --> <BUILD_DIR>/%s/%s\n""" % (s, os.path.basename(targetDir), s)

    # I move the first 100 .pem files I find
    # if there is more than that... oh well
    movedYN = 0
    for i in range(100):
        serial = fixSerial(hex(i))
        oldPemPath = os.path.join(topdir, serial+'.pem')
        newPemPath = os.path.join(unknown, serial+'.pem')
        if os.path.exists(oldPemPath) and not os.path.exists(newPemPath):
            gendir(unknown)
            shutil.copy2(oldPemPath, newPemPath)
            os.unlink(oldPemPath)
            movedYN = 1
    if movedYN:
        moveMessage = moveMessage + (
          '  <BUILD_DIR>/HEX*.pem --> <BUILD_DIR>/%s/HEX*.pem\n'
          % os.path.basename(unknown))

    if moveMessage:
        sys.stdout.write('\nLegacy tree structured file(s) moved:\n%s'
                         % moveMessage)

    # move rhn-org-httpd-ssl-MACHINENAME-VERSION.*.rpm files to the
    # MACHINENAME directory! (an RHN 3.6.0 change)
    rootFilename = pathJoin(topdir, 'rhn-org-httpd-ssl-key-pair-')
    filenames = glob.glob(rootFilename+'*')
    for filename in filenames:
        # note: assuming version-rel is of that form.
        machinename = filename[len(rootFilename):]
        machinename = '-'.join(machinename.split('-')[:-2])
        serverKeySetDir = pathJoin(topdir, machinename)
        gendir(serverKeySetDir)
        fileto = pathJoin(serverKeySetDir, filename)
        if os.path.exists(fileto):
            rotateFile(filepath=fileto, verbosity=0)
        shutil.copy2(filename, fileto)
        os.unlink(filename)
        print("""\
Moved (legacy tree cleanup):
    %s
    ...moved to...
    %s""" % (filename, fileto))
예제 #33
0
def genServerCert(password, d, verbosity=0):
    """ server cert generation and signing """

    serverKeyPairDir = os.path.join(d['--dir'],
                                    getMachineName(d['--set-hostname']))

    genServerCert_dependencies(password, d)

    ca_key = os.path.join(d['--dir'], os.path.basename(d['--ca-key']))
    ca_cert = os.path.join(d['--dir'], os.path.basename(d['--ca-cert']))

    server_cert_req = os.path.join(serverKeyPairDir,
                                   os.path.basename(d['--server-cert-req']))
    server_cert = os.path.join(serverKeyPairDir,
                               os.path.basename(d['--server-cert']))
    ca_openssl_cnf = os.path.join(d['--dir'], CA_OPENSSL_CNF_NAME)

    index_txt = os.path.join(d['--dir'], 'index.txt')
    serial = os.path.join(d['--dir'], 'serial')

    try:
        os.unlink(index_txt)
    except:
        pass

    # figure out the serial file and truncate the index.txt file.
    ser = figureSerial(ca_cert, serial, index_txt)

    # need to insure the directory declared in the ca_openssl.cnf
    # file is current:
    configFile = ConfigFile(ca_openssl_cnf)
    configFile.updateDir()

    args = (
        "/usr/bin/openssl ca -extensions req_server_x509_extensions -passin pass:%s -outdir ./ -config %s "
        "-in %s -batch -cert %s -keyfile %s -startdate %s -days %s "
        "-md %s -out %s" %
        ('%s', repr(cleanupAbsPath(ca_openssl_cnf)),
         repr(cleanupAbsPath(server_cert_req)), repr(cleanupAbsPath(ca_cert)),
         repr(cleanupAbsPath(ca_key)), d['--startdate'],
         repr(d['--cert-expiration']), MD, repr(cleanupAbsPath(server_cert))))

    if verbosity >= 0:
        print "\nGenerating/signing web server's SSL certificate: %s" % d[
            '--server-cert']
        if verbosity > 1:
            print "Commandline:", args % 'PASSWORD'
    try:
        rotated = rotateFile(filepath=server_cert, verbosity=verbosity)
        if verbosity >= 0 and rotated:
            print "Rotated: %s --> %s" % (d['--server-cert'],
                                          os.path.basename(rotated))
    except ValueError:
        pass

    cwd = chdir(_getWorkDir())
    try:
        ret, out_stream, err_stream = rhn_popen(args % repr(password))
    finally:
        chdir(cwd)

    out = out_stream.read()
    out_stream.close()
    err = err_stream.read()
    err_stream.close()

    if ret:
        # signature for a mistyped CA password
        if string.find(err, "unable to load CA private key") != -1 \
          and string.find(err, "error:0906A065:PEM routines:PEM_do_header:bad decrypt:pem_lib.c") != -1 \
          and string.find(err, "error:06065064:digital envelope routines:EVP_DecryptFinal:bad decrypt:evp_enc.c") != -1:
            raise GenServerCertException(
                "web server's SSL certificate generation/signing "
                "failed:\nDid you mistype your CA password?")
        else:
            raise GenServerCertException(
                "web server's SSL certificate generation/signing "
                "failed:\n%s\n%s" % (out, err))

    if verbosity > 2:
        if out:
            print "STDOUT:", out
        if err:
            print "STDERR:", err

    # permissions:
    os.chmod(server_cert, 0644)

    # cleanup duplicate XX.pem file:
    pemFilename = os.path.basename(string.upper(ser) + '.pem')
    if pemFilename != server_cert and os.path.exists(pemFilename):
        os.unlink(pemFilename)

    # cleanup the old index.txt file
    try:
        os.unlink(index_txt + '.old')
    except:
        pass

    # cleanup the old serial file
    try:
        os.unlink(serial + '.old')
    except:
        pass
def main():
    """ main routine
        1    general failure
        10   general sanity check failure (to include a remedial cert
             version check)
        11   expired!
        12   certificate version fails remedially
        13   certificate missing in manifest
        14   manifest signature incorrect
        15   cannot load mapping files
        16   manifest download failed
        17   manifest refresh failed
        18   manifest entitlements parse failed
        30   local activation failure

        90   not registered to rhsm
        91   enabling sat repo failed

        127  general unknown failure (not really mapped yet)

        FIXME - need to redo how we process error codes - very manual
    """
    # pylint: disable=R0911

    options = processCommandline()

    if not cdn_activation:
        writeError(
            "Package spacewalk-backend-cdn has to be installed for using this tool."
        )
        sys.exit(1)

    # CDN Deactivation
    if options.deactivate:
        cdn_activation.Activation.deactivate()
        # Rotate the manifest to not have any currently used
        if os.path.exists(DEFAULT_RHSM_MANIFEST_LOCATION):
            fileutils.rotateFile(DEFAULT_RHSM_MANIFEST_LOCATION, depth=5)
            os.unlink(DEFAULT_RHSM_MANIFEST_LOCATION)
        return 0

    if options.rhn_cert:
        writeError(
            "Activation with RHN Classic Satellite Certificate is deprecated.\nPlease obtain a Manifest for this"
            " Satellite version via https://access.redhat.com/knowledge/tools/satcert, "
            "and re-run this activation tool with option --manifest=MANIFEST-FILE."
        )
        sys.exit(1)

    if not options.manifest:
        if os.path.exists(DEFAULT_RHSM_MANIFEST_LOCATION):
            options.manifest = DEFAULT_RHSM_MANIFEST_LOCATION
            if options.manifest_info:
                cdn_activation.Activation.manifest_info(
                    DEFAULT_RHSM_MANIFEST_LOCATION)
                return 0
            # Call regeneration API on Candlepin server
            if options.manifest_reconcile_request:
                log(0, "Requesting manifest regeneration...")
                ok = cdn_activation.Activation.refresh_manifest(
                    DEFAULT_RHSM_MANIFEST_LOCATION,
                    http_proxy=options.http_proxy,
                    http_proxy_username=options.http_proxy_username,
                    http_proxy_password=options.http_proxy_password)
                if not ok:
                    writeError("Manifest regeneration failed!")
                    return 17
                log(0, "Manifest regeneration requested.")
                return 0
            # Get new refreshed manifest from Candlepin server
            if options.manifest_download:
                log(0, "Downloading manifest...")
                path = cdn_activation.Activation.download_manifest(
                    DEFAULT_RHSM_MANIFEST_LOCATION,
                    http_proxy=options.http_proxy,
                    http_proxy_username=options.http_proxy_username,
                    http_proxy_password=options.http_proxy_password)
                if not path:
                    writeError("Manifest download failed!")
                    return 16
                if options.manifest_refresh:
                    options.manifest = path
                else:
                    log(0, "New manifest saved to: '%s'" % path)
                    return 0
        else:
            writeError(
                "No currently activated manifest was found. "
                "Run the activation tool with option --manifest=MANIFEST.")
            return 1
    # Handle RHSM manifest
    try:
        cdn_activate = cdn_activation.Activation(options.manifest)
    except CdnMappingsLoadError as e:
        writeError(e)
        return 15
    except MissingSatelliteCertificateError as e:
        writeError(e)
        return 13
    except IncorrectEntitlementsFileFormatError as e:
        writeError(e)
        return 18

    # general sanity/GPG check
    try:
        validateSatCert(cdn_activate.manifest.get_satellite_certificate())
    except RHNCertGeneralSanityException as e:
        writeError(e)
        return 10

    # expiration check
    if not options.ignore_expiration:
        date = expiredYN(cdn_activate.manifest.get_satellite_certificate())
        if date:
            just_date = date.split(' ')[0]
            writeError('Satellite Certificate appears to have expired: %s' %
                       just_date)
            return 11

    if options.sanity_only:
        return 0

    if not options.disconnected:
        rhsm_uuid = getRHSMUuid()
        if not rhsm_uuid:
            writeError(
                "System not registered to RHSM? No identity found. Please register system to RHSM"
                " or run activation with --disconnected option.")
            return 90
        try:
            enableSatelliteRepo(
                cdn_activate.manifest.get_satellite_certificate())
        except EnableSatelliteRepositoryException:
            e = sys.exc_info()[1]
            writeError(e)
            return 91

    try:
        cdn_activate.activate()
    except ManifestValidationError:
        e = sys.exc_info()[1]
        writeError(e)
        return 14

    storeRhsmManifest(options)

    return 0