Example #1
0
def _existsUserGroup(log, user, group):
    try:
        osetuputil.getUid(user)
    except (KeyError, IndexError):
        log.warn(_("User {user} does not exist.".format(user=user)))
        return False

    try:
        osetuputil.getGid(group)
    except (KeyError, IndexError):
        log.warn(_("Group {group} does not exist.".format(group=group)))
        return False

    return True
Example #2
0
    def _misc(self):
        uid = osetuputil.getUid(
            self.environment[osetupcons.SystemEnv.USER_ENGINE])
        gid = osetuputil.getGid(
            self.environment[osetupcons.SystemEnv.GROUP_ENGINE])
        if os.path.exists(osetupcons.FileLocations.OVIRT_ENGINE_TMPDIR):
            # clean the directory only if it contains at least one file
            # not owned by engine
            rm_tmp_dir = False
            for root, dirs, files in os.walk(
                    top=osetupcons.FileLocations.OVIRT_ENGINE_TMPDIR,
                    followlinks=False,
            ):
                for name in dirs + files:
                    if os.stat(os.path.join(root, name)).st_uid != uid:
                        rm_tmp_dir = True
                        break
                if rm_tmp_dir:
                    break
            if rm_tmp_dir:
                self.logger.debug('Cleaning {tmpdir}'.format(
                    tmpdir=osetupcons.FileLocations.OVIRT_ENGINE_TMPDIR, ))
                shutil.rmtree(osetupcons.FileLocations.OVIRT_ENGINE_TMPDIR)

        for root, dirs, files in os.walk(
                top=osetupcons.FileLocations.OVIRT_ENGINE_DEPLOYMENTS_DIR,
                followlinks=False,
        ):
            os.chown(root, uid, gid)
            for name in dirs + files:
                os.chown(os.path.join(root, name), uid, gid)
Example #3
0
 def _misc(self):
     self.logger.info(_('Backing up PKI configuration and keys'))
     fd, self._bkpfile = tempfile.mkstemp(
         prefix=('engine-pki-%s' %
                 datetime.datetime.now().strftime('%Y%m%d%H%M%S')),
         suffix='.tar.gz',
         dir=self.environment[
             oenginecons.ConfigEnv.OVIRT_ENGINE_DB_BACKUP_DIR],
     )
     os.fchown(
         fd,
         osetuputil.getUid(
             self.environment[oengcommcons.SystemEnv.USER_ROOT]), -1)
     os.fchmod(fd, 0o600)
     with os.fdopen(fd, 'wb') as fileobj:
         # fileobj is not closed, when TarFile is closed
         # cannot use with tarfile.open() <python-2.7
         tar = None
         try:
             tar = tarfile.open(mode='w:gz', fileobj=fileobj)
             for n in (
                     oenginecons.FileLocations.
                     OVIRT_ENGINE_SERVICE_CONFIG_PKI,
                     oenginecons.FileLocations.OVIRT_ENGINE_PKIDIR,
             ):
                 if os.path.exists(n):
                     tar.add(n)
         finally:
             if tar is not None:
                 tar.close()
Example #4
0
 def _copyiso(self):
     self.logger.debug('Copying Iso Files')
     targetPath = os.path.join(
         self.environment[
             oenginecons.ConfigEnv.ISO_DOMAIN_NFS_MOUNT_POINT
         ],
         self.environment[
             oenginecons.ConfigEnv.ISO_DOMAIN_SD_UUID
         ],
         'images',
         oenginecons.Const.ISO_DOMAIN_IMAGE_UID
     )
     self.logger.debug('target path' + targetPath)
     # FIXME don't hardcode paths
     for filename in glob.glob('/home/liveuser/oVirtLiveFiles/iso/*.iso'):
         self.logger.debug(filename)
         shutil.move(filename, targetPath)
         os.chown(
             os.path.join(targetPath, os.path.basename(filename)),
             osetuputil.getUid(
                 oengcommcon.Defaults.DEFAULT_SYSTEM_USER_VDSM
             ),
             osetuputil.getGid(
                 oengcommcon.Defaults.DEFAULT_SYSTEM_GROUP_KVM
             )
         )
Example #5
0
    def _enrollCertificates(self, renew, uninstall_files):
        for entry in self._PKI_ENTRIES:
            self.logger.debug(
                "processing: '%s'[renew=%s]",
                entry['name'],
                renew,
            )

            pkcs12 = os.path.join(
                oenginecons.FileLocations.OVIRT_ENGINE_PKIKEYSDIR,
                '%s.p12' % entry['name'],
            )

            if not os.path.exists(pkcs12):
                enroll = True
                self.logger.debug(
                    "'%s' does not exist, enrolling",
                    pkcs12,
                )
            else:
                enroll = not renew

            if not enroll:
                enroll = self._ok_to_renew_cert(
                    pkcs12,
                    entry['name'],
                    entry['extract']
                )

                if enroll:
                    self.logger.info(
                        _('Renewing {name} certificate').format(
                            name=entry['name'],
                        )
                    )

            if enroll:
                self._enrollCertificate(
                    entry['name'],
                    uninstall_files,
                    keepKey=entry['keepKey'] and renew,
                )
                os.chown(
                    pkcs12,
                    osetuputil.getUid(self.environment[entry['user']]),
                    -1,
                )
                if entry['extract']:
                    self._expandPKCS12(
                        pkcs12,
                        entry['name'],
                        self.environment[entry['user']],
                        uninstall_files,
                    )
Example #6
0
    def _enrollCertificates(self, renew, uninstall_files):
        for entry in self.environment[oenginecons.PKIEnv.ENTITIES]:
            self.logger.debug(
                "processing: '%s'[renew=%s]",
                entry['name'],
                renew,
            )

            pkcs12 = os.path.join(
                oenginecons.FileLocations.OVIRT_ENGINE_PKIKEYSDIR,
                '%s.p12' % entry['name'],
            )

            enroll = False

            if not os.path.exists(pkcs12):
                enroll = True
                self.logger.debug(
                    "'%s' does not exist, enrolling",
                    pkcs12,
                )
            elif renew:
                enroll = self._ok_to_renew_cert(
                    pkcs12,
                    entry['name'],
                    entry['extract']
                )

                if enroll:
                    self.logger.info(
                        _('Renewing {name} certificate').format(
                            name=entry['name'],
                        )
                    )

            if enroll:
                self._enrollCertificate(
                    entry['name'],
                    uninstall_files,
                    keepKey=entry['keepKey'] and renew,
                    shortLife=entry['shortLife'],
                )
                os.chown(
                    pkcs12,
                    osetuputil.getUid(self.environment[entry['user']]),
                    -1,
                )
                if entry['extract']:
                    self._expandPKCS12(
                        pkcs12,
                        entry['name'],
                        self.environment[entry['user']],
                        uninstall_files,
                    )
Example #7
0
    def _misc(self):
        """
        Load files (iso, vfd) from existing rpms to the NFS ISO domain
        TODO: use engine-iso-uploader when it will support local destinations
        """
        uninstall_files = []
        self.environment[
            osetupcons.CoreEnv.REGISTER_UNINSTALL_GROUPS].createGroup(
                group='iso_images',
                description='Uploaded ISO images',
                optional=True).addFiles(
                    group='iso_images',
                    fileList=uninstall_files,
                )

        targetDir = self.environment[
            oenginecons.ConfigEnv.ISO_DOMAIN_STORAGE_DIR]

        # Iterate the list and copy all the files.
        for filename in self.environment[
                osetupcons.ConfigEnv.ISO_PATHS_TO_UPLOAD]:
            if os.path.exists(filename):
                try:
                    targetFile = os.path.join(targetDir,
                                              os.path.basename(filename))
                    if os.path.exists(targetFile):
                        shutil.move(
                            targetFile, '%s.%s' %
                            (targetFile,
                             datetime.datetime.now().strftime('%Y%m%d%H%M%S')))
                    shutil.copyfile(filename, targetFile)
                    uninstall_files.append(targetFile)
                    os.chmod(targetFile, 0o644)
                    os.chown(
                        targetFile,
                        osetuputil.getUid(self.environment[
                            oengcommcons.SystemEnv.USER_VDSM]),
                        osetuputil.getGid(self.environment[
                            oengcommcons.SystemEnv.GROUP_KVM]))
                except (OSError, shutil.Error) as e:
                    self.logger.warning(
                        _("Cannot copy '{filename}' to iso domain "
                          "'{directory}', error: {error}").format(
                              filename=filename,
                              directory=targetDir,
                              error=e,
                          ))
Example #8
0
 def _closeupEngineAccess(self):
     # Doing this at closeup and not misc, because if using
     # remote_engine style manual_files, we prompt the user,
     # which might take a long time (until the user notices
     # and handles), and we'd rather not block the transaction
     # waiting. Downside is that if we fail during closeup
     # but before this event, it will not run, also on next
     # attempt.
     with open(
         odwhcons.FileLocations.
         OVIRT_ENGINE_ENGINE_SERVICE_CONFIG_DWH_DATABASE_EXAMPLE
     ) as f:
         self._remote_engine.copy_to_engine(
             file_name=(
                 odwhcons.FileLocations.
                 OVIRT_ENGINE_ENGINE_SERVICE_CONFIG_DWH_DATABASE
             ),
             content=f.read(),
             uid=osetuputil.getUid(
                 self.environment[osetupcons.SystemEnv.USER_ENGINE]
             ),
             gid=osetuputil.getGid(
                 self.environment[osetupcons.SystemEnv.GROUP_ENGINE]
             ),
             mode=0o600,
         )
     self._configured_now = True
     self.dialog.note(
         text=_(
             'Please restart the engine by running the following '
             'on {fqdn} :\n'
             '# service {service} restart\n'
             'This is required for the dashboard to work.'
         ).format(
             fqdn=self.environment[
                 oenginecons.ConfigEnv.ENGINE_FQDN
             ],
             service=oenginecons.Const.ENGINE_SERVICE_NAME,
         )
     )
Example #9
0
 def _misc(self):
     self.logger.info(
         _('Backing up PKI configuration and keys')
     )
     fd, self._bkpfile = tempfile.mkstemp(
         prefix=(
             'engine-pki-%s' %
             datetime.datetime.now().strftime('%Y%m%d%H%M%S')
         ),
         suffix='.tar.gz',
         dir=self.environment[
             oenginecons.ConfigEnv.OVIRT_ENGINE_DB_BACKUP_DIR
         ],
     )
     os.fchown(
         fd,
         osetuputil.getUid(
             self.environment[oengcommcons.SystemEnv.USER_ROOT]
         ),
         -1
     )
     os.fchmod(fd, 0o600)
     with os.fdopen(fd, 'wb') as fileobj:
         # fileobj is not closed, when TarFile is closed
         # cannot use with tarfile.open() <python-2.7
         tar = None
         try:
             tar = tarfile.open(
                 mode='w:gz',
                 fileobj=fileobj
             )
             for n in (
                 oenginecons.FileLocations.OVIRT_ENGINE_SERVICE_CONFIG_PKI,
                 oenginecons.FileLocations.OVIRT_ENGINE_PKIDIR,
             ):
                 if os.path.exists(n):
                     tar.add(n)
         finally:
             if tar is not None:
                 tar.close()
Example #10
0
 def _misc(self):
     rc, privkey, stderr = self.execute(
         (
             oenginecons.FileLocations.OVIRT_ENGINE_PKI_PKCS12_EXTRACT,
             '--name=engine',
             '--passin=%s' %
             self.environment[oenginecons.PKIEnv.STORE_PASS],
             '--key=-',
         ),
         logStreams=False,
     )
     self.environment[otopicons.CoreEnv.MAIN_TRANSACTION].append(
         filetransaction.FileTransaction(
             name=oenginecons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_SSH_KEY,
             content=privkey,
             mode=0o600,
             owner=self.environment[osetupcons.SystemEnv.USER_ENGINE],
             enforcePermissions=True,
             modifiedList=self.environment[
                 otopicons.CoreEnv.MODIFIED_FILES],
         ))
     if os.path.exists(
             oenginecons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_SSH_KEY):
         # Previous versions created it as root:root 0600.
         # We now want to use it also from the engine (for ansible).
         # The filetransaction above will not change ownership
         # if content is not changed. So do this here. We do not
         # do this in a transaction, should be ok.
         os.chown(
             oenginecons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_SSH_KEY,
             osetuputil.getUid(
                 self.environment[osetupcons.SystemEnv.USER_ENGINE], ),
             osetuputil.getGid(
                 self.environment[osetupcons.SystemEnv.GROUP_ENGINE], ),
         )
     self.environment[
         oenginecons.PKIEnv.ENGINE_SSH_PUBLIC_KEY] = self._getSSHPublicKey(
             self._getEnginePublicKey())
Example #11
0
    def _misc(self):
        uid = osetuputil.getUid(
            self.environment[osetupcons.SystemEnv.USER_ENGINE]
        )
        gid = osetuputil.getGid(
            self.environment[osetupcons.SystemEnv.GROUP_ENGINE]
        )
        if os.path.exists(osetupcons.FileLocations.OVIRT_ENGINE_TMPDIR):
            # clean the directory only if it contains at least one file
            # not owned by engine
            rm_tmp_dir = False
            for root, dirs, files in os.walk(
                top=osetupcons.FileLocations.OVIRT_ENGINE_TMPDIR,
                followlinks=False,
            ):
                for name in dirs + files:
                    if os.stat(os.path.join(root, name)).st_uid != uid:
                        rm_tmp_dir = True
                        break
                if rm_tmp_dir:
                    break
            if rm_tmp_dir:
                self.logger.debug(
                    'Cleaning {tmpdir}'.format(
                        tmpdir=osetupcons.FileLocations.OVIRT_ENGINE_TMPDIR,
                    )
                )
                shutil.rmtree(osetupcons.FileLocations.OVIRT_ENGINE_TMPDIR)

        for root, dirs, files in os.walk(
            top=osetupcons.FileLocations.OVIRT_ENGINE_DEPLOYMENTS_DIR,
            followlinks=False,
        ):
            os.chown(root, uid, gid)
            for name in dirs + files:
                os.chown(os.path.join(root, name), uid, gid)
Example #12
0
    def _artifacts(self):

        #
        # Remove embedded psql resources
        #
        for f in glob.glob(
            os.path.join(
                oreportscons.FileLocations.OVIRT_ENGINE_REPORTS_JASPER_WAR,
                'WEB-INF',
                'lib',
                'postgresql-*.jar',
            )
        ):
            os.unlink(f)

        #
        # Files contain password
        #
        for f in (
            'WEB-INF/js-jboss7-ds.xml',
            'META-INF/context.xml',
        ):
            f = os.path.join(
                oreportscons.FileLocations.OVIRT_ENGINE_REPORTS_JASPER_WAR,
                f
            )
            os.chown(
                f,
                osetuputil.getUid(
                    self.environment[osetupcons.SystemEnv.USER_ENGINE]
                ),
                osetuputil.getGid(
                    self.environment[osetupcons.SystemEnv.GROUP_ENGINE],
                ),
            )
            os.chmod(f, 0o600)
Example #13
0
    def _prepare_new_domain(self, path):
        uninstall_files = []
        self.environment[
            osetupcons.CoreEnv.REGISTER_UNINSTALL_GROUPS
        ].createGroup(
            group='iso_domain',
            description='ISO domain layout',
            optional=True
        ).addFiles(
            group='iso_domain',
            fileList=uninstall_files,
        )
        if os.path.exists(path):
            self.logger.debug(
                'Enforcing ownership and access bits on {path}'.format(
                    path=path,
                )
            )
            os.chown(
                path,
                osetuputil.getUid(
                    self.environment[osetupcons.SystemEnv.USER_VDSM]
                ),
                osetuputil.getGid(
                    self.environment[osetupcons.SystemEnv.GROUP_KVM]
                )
            )
            os.chmod(path, 0o755)

        self.logger.debug('Generating a new uuid for ISO domain')
        sdUUID = str(uuid.uuid4())
        description = self.environment[
            osetupcons.ConfigEnv.ISO_DOMAIN_NAME
        ]
        self.logger.debug(
            'Creating ISO domain for {path}. uuid: {uuid}'.format(
                path=path,
                uuid=sdUUID
            )
        )
        #Create images directory tree
        basePath = os.path.join(path, sdUUID)
        self.environment[otopicons.CoreEnv.MAIN_TRANSACTION].append(
            filetransaction.FileTransaction(
                name=os.path.join(
                    basePath,
                    'images',
                    osetupcons.Const.ISO_DOMAIN_IMAGE_UID,
                    '.keep',
                ),
                content=[],
                mode=0o644,
                dmode=0o755,
                owner=self.environment[osetupcons.SystemEnv.USER_VDSM],
                group=self.environment[osetupcons.SystemEnv.GROUP_KVM],
                downer=self.environment[
                    osetupcons.SystemEnv.USER_VDSM
                ],
                dgroup=self.environment[osetupcons.SystemEnv.GROUP_KVM],
                modifiedList=uninstall_files,
            )
        )
        #Create dom_md directory tree
        domMdDir = os.path.join(basePath, 'dom_md')
        for name in ('ids', 'inbox', 'outbox'):
            filename = os.path.join(domMdDir, name)
            self.environment[otopicons.CoreEnv.MAIN_TRANSACTION].append(
                filetransaction.FileTransaction(
                    name=filename,
                    content=[],
                    mode=0o660,
                    dmode=0o755,
                    owner=self.environment[osetupcons.SystemEnv.USER_VDSM],
                    group=self.environment[osetupcons.SystemEnv.GROUP_KVM],
                    downer=self.environment[
                        osetupcons.SystemEnv.USER_VDSM
                    ],
                    dgroup=self.environment[osetupcons.SystemEnv.GROUP_KVM],
                    modifiedList=uninstall_files,
                )
            )
        self.environment[otopicons.CoreEnv.MAIN_TRANSACTION].append(
            filetransaction.FileTransaction(
                name=os.path.join(domMdDir, 'leases'),
                content=b'\x00' * 512,
                binary=True,
                mode=0o660,
                dmode=0o755,
                owner=self.environment[osetupcons.SystemEnv.USER_VDSM],
                group=self.environment[osetupcons.SystemEnv.GROUP_KVM],
                downer=self.environment[
                    osetupcons.SystemEnv.USER_VDSM
                ],
                dgroup=self.environment[osetupcons.SystemEnv.GROUP_KVM],
                modifiedList=uninstall_files,
            )
        )
        metadata = os.path.join(domMdDir, 'metadata')
        self.environment[otopicons.CoreEnv.MAIN_TRANSACTION].append(
            filetransaction.FileTransaction(
                name=metadata,
                mode=0o644,
                dmode=0o755,
                owner=self.environment[osetupcons.SystemEnv.USER_VDSM],
                group=self.environment[osetupcons.SystemEnv.GROUP_KVM],
                downer=self.environment[osetupcons.SystemEnv.USER_VDSM],
                dgroup=self.environment[osetupcons.SystemEnv.GROUP_KVM],
                content=self._generate_md_content(sdUUID, description),
                modifiedList=uninstall_files,
            )
        )

        return sdUUID
Example #14
0
    def _misc(self):
        """
        Load files (iso, vfd) from existing rpms to the NFS ISO domain
        TODO: use engine-iso-uploader when it will support local destinations
        """
        uninstall_files = []
        self.environment[
            osetupcons.CoreEnv.REGISTER_UNINSTALL_GROUPS
        ].createGroup(
            group='iso_images',
            description='Uploaded ISO images',
            optional=True
        ).addFiles(
            group='iso_images',
            fileList=uninstall_files,
        )

        targetDir = self.environment[
            oenginecons.ConfigEnv.ISO_DOMAIN_STORAGE_DIR
        ]

        # Iterate the list and copy all the files.
        for filename in self.environment[
            osetupcons.ConfigEnv.ISO_PATHS_TO_UPLOAD
        ]:
            if os.path.exists(filename):
                try:
                    targetFile = os.path.join(
                        targetDir,
                        os.path.basename(filename)
                    )
                    if os.path.exists(targetFile):
                        shutil.move(
                            targetFile,
                            '%s.%s' % (
                                targetFile,
                                datetime.datetime.now().strftime(
                                    '%Y%m%d%H%M%S'
                                )
                            )
                        )
                    shutil.copyfile(filename, targetFile)
                    uninstall_files.append(targetFile)
                    os.chmod(targetFile, 0o644)
                    os.chown(
                        targetFile,
                        osetuputil.getUid(
                            self.environment[oengcommcons.SystemEnv.USER_VDSM]
                        ),
                        osetuputil.getGid(
                            self.environment[oengcommcons.SystemEnv.GROUP_KVM]
                        )
                    )
                except (OSError, shutil.Error) as e:
                    self.logger.warning(
                        _(
                            "Cannot copy '{filename}' to iso domain "
                            "'{directory}', error: {error}"
                        ).format(
                            filename=filename,
                            directory=targetDir,
                            error=e,
                        )
                    )
Example #15
0
 def __init__(self, user):
     self._user = osetuputil.getUid(user)
Example #16
0
    def _prepare_new_domain(self, path):
        uninstall_files = []
        self.environment[
            osetupcons.CoreEnv.REGISTER_UNINSTALL_GROUPS].createGroup(
                group='iso_domain',
                description='ISO domain layout',
                optional=True).addFiles(
                    group='iso_domain',
                    fileList=uninstall_files,
                )
        if os.path.exists(path):
            self.logger.debug(
                'Enforcing ownership and access bits on {path}'.format(
                    path=path, ))
            os.chown(
                path,
                osetuputil.getUid(
                    self.environment[oengcommcons.SystemEnv.USER_VDSM]),
                osetuputil.getGid(
                    self.environment[oengcommcons.SystemEnv.GROUP_KVM]))
            os.chmod(path, 0o755)

        self.logger.debug('Generating a new uuid for ISO domain')
        sdUUID = str(uuid.uuid4())
        description = self.environment[oenginecons.ConfigEnv.ISO_DOMAIN_NAME]
        self.logger.debug(
            'Creating ISO domain for {path}. uuid: {uuid}'.format(path=path,
                                                                  uuid=sdUUID))
        # Create images directory tree
        basePath = os.path.join(path, sdUUID)
        self.environment[otopicons.CoreEnv.MAIN_TRANSACTION].append(
            filetransaction.FileTransaction(
                name=os.path.join(
                    basePath,
                    'images',
                    oenginecons.Const.ISO_DOMAIN_IMAGE_UID,
                    '.keep',
                ),
                content=[],
                mode=0o644,
                dmode=0o755,
                owner=self.environment[oengcommcons.SystemEnv.USER_VDSM],
                group=self.environment[oengcommcons.SystemEnv.GROUP_KVM],
                downer=self.environment[oengcommcons.SystemEnv.USER_VDSM],
                dgroup=self.environment[oengcommcons.SystemEnv.GROUP_KVM],
                modifiedList=uninstall_files,
            ))
        # Create dom_md directory tree
        domMdDir = os.path.join(basePath, 'dom_md')
        for name in ('ids', 'inbox', 'outbox'):
            filename = os.path.join(domMdDir, name)
            self.environment[otopicons.CoreEnv.MAIN_TRANSACTION].append(
                filetransaction.FileTransaction(
                    name=filename,
                    content=[],
                    mode=0o660,
                    dmode=0o755,
                    owner=self.environment[oengcommcons.SystemEnv.USER_VDSM],
                    group=self.environment[oengcommcons.SystemEnv.GROUP_KVM],
                    downer=self.environment[oengcommcons.SystemEnv.USER_VDSM],
                    dgroup=self.environment[oengcommcons.SystemEnv.GROUP_KVM],
                    modifiedList=uninstall_files,
                ))
        self.environment[otopicons.CoreEnv.MAIN_TRANSACTION].append(
            filetransaction.FileTransaction(
                name=os.path.join(domMdDir, 'leases'),
                content=b'\x00' * 512,
                binary=True,
                mode=0o660,
                dmode=0o755,
                owner=self.environment[oengcommcons.SystemEnv.USER_VDSM],
                group=self.environment[oengcommcons.SystemEnv.GROUP_KVM],
                downer=self.environment[oengcommcons.SystemEnv.USER_VDSM],
                dgroup=self.environment[oengcommcons.SystemEnv.GROUP_KVM],
                modifiedList=uninstall_files,
            ))
        metadata = os.path.join(domMdDir, 'metadata')
        self.environment[otopicons.CoreEnv.MAIN_TRANSACTION].append(
            filetransaction.FileTransaction(
                name=metadata,
                mode=0o644,
                dmode=0o755,
                owner=self.environment[oengcommcons.SystemEnv.USER_VDSM],
                group=self.environment[oengcommcons.SystemEnv.GROUP_KVM],
                downer=self.environment[oengcommcons.SystemEnv.USER_VDSM],
                dgroup=self.environment[oengcommcons.SystemEnv.GROUP_KVM],
                content=self._generate_md_content(sdUUID, description),
                modifiedList=uninstall_files,
            ))

        return sdUUID
Example #17
0
    def _enrollCertificates(self, renew, uninstall_files):
        for entry in (
            {
                'name': 'engine',
                'extract': False,
                'user': osetupcons.SystemEnv.USER_ENGINE,
                'keepKey': True,
            },
            {
                'name': 'jboss',
                'extract': False,
                'user': osetupcons.SystemEnv.USER_ENGINE,
                'keepKey': False,
            },
            {
                'name': 'websocket-proxy',
                'extract': True,
                'user': osetupcons.SystemEnv.USER_ENGINE,
                'keepKey': False,
            },
            {
                'name': 'apache',
                'extract': True,
                'user': oengcommcons.SystemEnv.USER_ROOT,
                'keepKey': False,
            },
            {
                'name': 'reports',
                'extract': True,
                'user': oengcommcons.SystemEnv.USER_ROOT,
                'keepKey': False,
            },
        ):
            self.logger.debug(
                "processing: '%s'[renew=%s]",
                entry['name'],
                renew,
            )

            pkcs12 = os.path.join(
                oenginecons.FileLocations.OVIRT_ENGINE_PKIKEYSDIR,
                '%s.p12' % entry['name'],
            )

            if not os.path.exists(pkcs12):
                enroll = True
                self.logger.debug(
                    "'%s' does not exist, enrolling",
                    pkcs12,
                )
            else:
                enroll = not renew

            if not enroll:
                x509 = self._extractPKCS12Certificate(pkcs12)
                if self._expired(x509):
                    if not entry['extract']:
                        enroll = True
                    else:
                        if x509.verify(
                            X509.load_cert(
                                oenginecons.FileLocations.
                                OVIRT_ENGINE_PKI_ENGINE_CA_CERT
                            ).get_pubkey()
                        ):
                            self.logger.debug(
                                'certificate is an internal certificate'
                            )

                            # sanity check, make sure user did not manually
                            # change cert
                            x509x = X509.load_cert(
                                os.path.join(
                                    (
                                        oenginecons.FileLocations.
                                        OVIRT_ENGINE_PKICERTSDIR
                                    ),
                                    '%s.cer' % entry['name'],
                                )
                            )

                            if x509x.as_pem() == x509.as_pem():
                                self.logger.debug('certificate is sane')
                                enroll = True

                if enroll:
                    self.logger.info(
                        _('Renewing {name} certificate').format(
                            name=entry['name'],
                        )
                    )

            if enroll:
                self._enrollCertificate(
                    entry['name'],
                    uninstall_files,
                    keepKey=entry['keepKey'] and renew,
                )
                os.chown(
                    pkcs12,
                    osetuputil.getUid(self.environment[entry['user']]),
                    -1,
                )
                if entry['extract']:
                    self._expandPKCS12(
                        pkcs12,
                        entry['name'],
                        self.environment[entry['user']],
                        uninstall_files,
                    )
Example #18
0
 def __init__(self, user):
     self._user = osetuputil.getUid(user)
Example #19
0
    def _misc(self):
        # TODO
        # this implementaiton is not transactional
        # too many issues with legacy ca implementation
        # need to work this out to allow transactional
        # for now just delete files if we fail
        uninstall_files = []
        self.environment[otopicons.CoreEnv.MAIN_TRANSACTION].append(
            self.CATransaction(
                parent=self,
                uninstall_files=uninstall_files,
            )
        )

        # LEGACY NOTE
        # This is needed for avoiding error in create_ca when supporting
        # max cn length of 64.
        # please DON'T increase this size, any value over 55 will fail the
        # setup. the truncated host-fqdn is concatenated with a random string
        # to create a unique CN value.
        self.environment[
            osetupcons.CoreEnv.REGISTER_UNINSTALL_GROUPS
        ].createGroup(
            group='ca_pki',
            description='PKI keys',
            optional=True,
        ).addFiles(
            group='ca_pki',
            fileList=uninstall_files,
        )
        MAX_HOST_FQDN_LEN = 55

        self.logger.info(_('Creating CA'))

        localtransaction = transaction.Transaction()
        with localtransaction:
            for name in (
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_CA_TEMPLATE,
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_CERT_TEMPLATE,
            ):
                localtransaction.append(
                    filetransaction.FileTransaction(
                        name=name[:-len('.in')],
                        content=outil.processTemplate(
                            name,
                            {
                                '@AIA@': 'http://%s:%s%s' % (
                                    self.environment[
                                        osetupcons.ConfigEnv.FQDN
                                    ],
                                    self.environment[
                                        osetupcons.ConfigEnv.PUBLIC_HTTP_PORT
                                    ],
                                    osetupcons.Const.ENGINE_PKI_CA_URI,
                                )
                            }
                        ),
                        modifiedList=uninstall_files,
                    ),
                )

        self.execute(
            args=(
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_CA_CREATE,
                '--subject=/C=%s/O=%s/CN=%s.%s' % (
                    self._subjectComponentEscape(
                        self.environment[osetupcons.PKIEnv.COUNTRY],
                    ),
                    self._subjectComponentEscape(
                        self.environment[osetupcons.PKIEnv.ORG],
                    ),
                    self._subjectComponentEscape(
                        self.environment[
                            osetupcons.ConfigEnv.FQDN
                        ][:MAX_HOST_FQDN_LEN],
                    ),
                    random.randint(10000, 99999),
                ),
                '--keystore-password=%s' % (
                    self.environment[osetupcons.PKIEnv.STORE_PASS],
                ),
            ),
            envAppend={
                'JAVA_HOME': self.environment[
                    osetupcons.ConfigEnv.JAVA_HOME
                ],
            },
        )

        for name in ('engine', 'apache', 'jboss'):
            self.execute(
                (
                    osetupcons.FileLocations.OVIRT_ENGINE_PKI_CA_ENROLL,
                    '--name=%s' % name,
                    '--password=%s' % (
                        self.environment[osetupcons.PKIEnv.STORE_PASS],
                    ),
                    '--subject=/C=%s/O=%s/CN=%s' % (
                        self._subjectComponentEscape(
                            self.environment[osetupcons.PKIEnv.COUNTRY],
                        ),
                        self._subjectComponentEscape(
                            self.environment[osetupcons.PKIEnv.ORG],
                        ),
                        self._subjectComponentEscape(
                            self.environment[osetupcons.ConfigEnv.FQDN],
                        ),
                    ),
                ),
            )

        uninstall_files.extend(
            (
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_CERT,
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_STORE,
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_CA_CERT,
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_CA_KEY,
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_CERT,
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_STORE,
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_TRUST_STORE,
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_JBOSS_STORE,
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_CA_CERT_CONF,
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_CERT_CONF,
            )
        )

        self.execute(
            args=(
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_PKCS12_EXTRACT,
                '--name=apache',
                '--passin=%s' % (
                    self.environment[osetupcons.PKIEnv.STORE_PASS],
                ),
                '--key=%s' % (
                    osetupcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_KEY,
                ),
            ),
            logStreams=False,
        )
        uninstall_files.append(
            osetupcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_KEY
        )

        if not os.path.exists(
            osetupcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_CA_CERT
        ):
            os.symlink(
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_CA_CERT,
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_CA_CERT
            )
            uninstall_files.append(
                osetupcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_CA_CERT
            )

        for f in (
            osetupcons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_STORE,
            osetupcons.FileLocations.OVIRT_ENGINE_PKI_JBOSS_STORE,
        ):
            os.chown(
                f,
                osetuputil.getUid(
                    self.environment[osetupcons.SystemEnv.USER_ENGINE]
                ),
                -1,
            )
Example #20
0
    def _misc(self):
        self._enabled = True

        # TODO
        # this implementaiton is not transactional
        # too many issues with legacy ca implementation
        # need to work this out to allow transactional
        # for now just delete files if we fail
        uninstall_files = []
        self._setupUninstall(uninstall_files)
        self.environment[otopicons.CoreEnv.MAIN_TRANSACTION].append(
            self.CATransaction(
                parent=self,
                uninstall_files=uninstall_files,
            ))

        # LEGACY NOTE
        # This is needed for avoiding error in create_ca when supporting
        # max cn length of 64.
        # please DON'T increase this size, any value over 55 will fail the
        # setup. the truncated host-fqdn is concatenated with a random string
        # to create a unique CN value.
        MAX_HOST_FQDN_LEN = 55

        self.logger.info(_('Creating CA'))

        localtransaction = transaction.Transaction()
        with localtransaction:
            for name in (
                    oenginecons.FileLocations.OVIRT_ENGINE_PKI_CA_TEMPLATE,
                    oenginecons.FileLocations.OVIRT_ENGINE_PKI_CERT_TEMPLATE,
            ):
                localtransaction.append(
                    filetransaction.FileTransaction(
                        name=name[:-len('.in')],
                        content=outil.processTemplate(
                            name, {
                                '@AIA@':
                                'http://%s:%s%s' % (
                                    self.environment[
                                        osetupcons.ConfigEnv.FQDN],
                                    self.environment[oengcommcons.ConfigEnv.
                                                     PUBLIC_HTTP_PORT],
                                    oenginecons.Const.ENGINE_PKI_CA_URI,
                                )
                            }),
                        modifiedList=uninstall_files,
                    ), )

        self.execute(
            args=(
                oenginecons.FileLocations.OVIRT_ENGINE_PKI_CA_CREATE,
                '--subject=/C=%s/O=%s/CN=%s.%s' % (
                    self._subjectComponentEscape(
                        self.environment[oenginecons.PKIEnv.COUNTRY], ),
                    self._subjectComponentEscape(
                        self.environment[oenginecons.PKIEnv.ORG], ),
                    self._subjectComponentEscape(
                        self.environment[osetupcons.ConfigEnv.FQDN]
                        [:MAX_HOST_FQDN_LEN], ),
                    random.randint(10000, 99999),
                ),
                '--keystore-password=%s' %
                (self.environment[oenginecons.PKIEnv.STORE_PASS], ),
            ),
            envAppend={
                'JAVA_HOME':
                self.environment[oengcommcons.ConfigEnv.JAVA_HOME],
            },
        )

        for name in ('engine', 'apache', 'jboss', 'websocket-proxy',
                     'reports'):
            self.execute((
                oenginecons.FileLocations.OVIRT_ENGINE_PKI_CA_ENROLL,
                '--name=%s' % name,
                '--password=%s' %
                (self.environment[oenginecons.PKIEnv.STORE_PASS], ),
                '--subject=/C=%s/O=%s/CN=%s' % (
                    self._subjectComponentEscape(
                        self.environment[oenginecons.PKIEnv.COUNTRY], ),
                    self._subjectComponentEscape(
                        self.environment[oenginecons.PKIEnv.ORG], ),
                    self._subjectComponentEscape(
                        self.environment[osetupcons.ConfigEnv.FQDN], ),
                ),
            ), )

        uninstall_files.extend((
            oengcommcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_CERT,
            oenginecons.FileLocations.OVIRT_ENGINE_PKI_APACHE_STORE,
            oenginecons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_CA_CERT,
            oenginecons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_CA_KEY,
            oenginecons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_CERT,
            oenginecons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_STORE,
            oenginecons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_TRUST_STORE,
            oenginecons.FileLocations.OVIRT_ENGINE_PKI_JBOSS_STORE,
            oenginecons.FileLocations.OVIRT_ENGINE_PKI_JBOSS_CERT,
            oenginecons.FileLocations.OVIRT_ENGINE_PKI_CA_CERT_CONF,
            oenginecons.FileLocations.OVIRT_ENGINE_PKI_CERT_CONF,
            (oenginecons.FileLocations.
             OVIRT_ENGINE_PKI_LOCAL_WEBSOCKET_PROXY_CERT),
            (oenginecons.FileLocations.
             OVIRT_ENGINE_PKI_LOCAL_WEBSOCKET_PROXY_STORE),
        ))

        self.execute(
            args=(
                oenginecons.FileLocations.OVIRT_ENGINE_PKI_PKCS12_EXTRACT,
                '--name=websocket-proxy',
                '--passin=%s' %
                (self.environment[oenginecons.PKIEnv.STORE_PASS], ),
                '--key=%s' % (oenginecons.FileLocations.
                              OVIRT_ENGINE_PKI_LOCAL_WEBSOCKET_PROXY_KEY, ),
            ),
            logStreams=False,
        )
        uninstall_files.append(oenginecons.FileLocations.
                               OVIRT_ENGINE_PKI_LOCAL_WEBSOCKET_PROXY_KEY)

        self.execute(
            args=(
                oenginecons.FileLocations.OVIRT_ENGINE_PKI_PKCS12_EXTRACT,
                '--name=reports',
                '--passin=%s' %
                (self.environment[oenginecons.PKIEnv.STORE_PASS], ),
                '--key=%s' %
                (oenginecons.FileLocations.OVIRT_ENGINE_PKI_REPORTS_KEY, ),
            ),
            logStreams=False,
        )
        uninstall_files.append(
            oenginecons.FileLocations.OVIRT_ENGINE_PKI_REPORTS_KEY)

        self.execute(
            args=(
                oenginecons.FileLocations.OVIRT_ENGINE_PKI_PKCS12_EXTRACT,
                '--name=apache',
                '--passin=%s' %
                (self.environment[oenginecons.PKIEnv.STORE_PASS], ),
                '--key=%s' %
                (oengcommcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_KEY, ),
            ),
            logStreams=False,
        )
        uninstall_files.append(
            oengcommcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_KEY)

        if not os.path.exists(
                oengcommcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_CA_CERT):
            os.symlink(
                oenginecons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_CA_CERT,
                oengcommcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_CA_CERT)
            uninstall_files.append(
                oengcommcons.FileLocations.OVIRT_ENGINE_PKI_APACHE_CA_CERT)

        for f in (
                oenginecons.FileLocations.OVIRT_ENGINE_PKI_ENGINE_STORE,
                oenginecons.FileLocations.OVIRT_ENGINE_PKI_JBOSS_STORE,
                oenginecons.FileLocations.
                OVIRT_ENGINE_PKI_LOCAL_WEBSOCKET_PROXY_KEY,
                oenginecons.FileLocations.
                OVIRT_ENGINE_PKI_LOCAL_WEBSOCKET_PROXY_STORE,
        ):
            os.chown(
                f,
                osetuputil.getUid(
                    self.environment[osetupcons.SystemEnv.USER_ENGINE]),
                -1,
            )