예제 #1
0
    def test_load_dss(self):
        key = DSSKey.from_private_key_file(_support('test_dss.key'))
        self.assert_key_values(key, 'ssh-dss', 1024, PUB_DSS,
                               FINGER_DSS.split()[1], FINGER_SHA256_DSS)

        s = StringIO()
        key.write_private_key(s)
        self.assertEqual(DSS_PRIVATE_OUT, s.getvalue())
        s.seek(0)
        key2 = DSSKey.from_private_key(s)
        self.assertEqual(key, key2)
예제 #2
0
    def test_load_dss(self):
        key = DSSKey.from_private_key_file(_support("test_dss.key"))
        self.assertEqual("ssh-dss", key.get_name())
        self.assert_key_fingerprints(key, FINGER_DSS)
        self.assertEqual(PUB_DSS.split()[1], key.get_base64())
        self.assertEqual(1024, key.get_bits())

        s = StringIO()
        key.write_private_key(s)
        self.assertEqual(DSS_PRIVATE_OUT, s.getvalue())
        s.seek(0)
        key2 = DSSKey.from_private_key(s)
        self.assertEqual(key, key2)
예제 #3
0
    def test_4_load_dss(self):
        key = DSSKey.from_private_key_file(_support("test_dss.key"))
        self.assertEqual("ssh-dss", key.get_name())
        exp_dss = b(FINGER_DSS.split()[1].replace(":", ""))
        my_dss = hexlify(key.get_fingerprint())
        self.assertEqual(exp_dss, my_dss)
        self.assertEqual(PUB_DSS.split()[1], key.get_base64())
        self.assertEqual(1024, key.get_bits())

        s = StringIO()
        key.write_private_key(s)
        self.assertEqual(DSS_PRIVATE_OUT, s.getvalue())
        s.seek(0)
        key2 = DSSKey.from_private_key(s)
        self.assertEqual(key, key2)
예제 #4
0
    def test_4_load_dss(self):
        key = DSSKey.from_private_key_file('tests/test_dss.key')
        self.assertEquals('ssh-dss', key.get_name())
        exp_dss = FINGER_DSS.split()[1].replace(':', '')
        my_dss = hexlify(key.get_fingerprint())
        self.assertEquals(exp_dss, my_dss)
        self.assertEquals(PUB_DSS.split()[1], key.get_base64())
        self.assertEquals(1024, key.get_bits())

        s = StringIO()
        key.write_private_key(s)
        self.assertEquals(DSS_PRIVATE_OUT, s.getvalue())
        s.seek(0)
        key2 = DSSKey.from_private_key(s)
        self.assertEquals(key, key2)
예제 #5
0
    def test_4_load_dss(self):
        key = DSSKey.from_private_key_file('tests/test_dss.key')
        self.assertEquals('ssh-dss', key.get_name())
        exp_dss = FINGER_DSS.split()[1].replace(':', '')
        my_dss = hexlify(key.get_fingerprint())
        self.assertEquals(exp_dss, my_dss)
        self.assertEquals(PUB_DSS.split()[1], key.get_base64())
        self.assertEquals(1024, key.get_bits())

        s = StringIO.StringIO()
        key.write_private_key(s)
        self.assertEquals(DSS_PRIVATE_OUT, s.getvalue())
        s.seek(0)
        key2 = DSSKey.from_private_key(s)
        self.assertEquals(key, key2)
예제 #6
0
    def test_4_load_dss(self):
        key = DSSKey.from_private_key_file(_support("test_dss.key"))
        self.assertEqual("ssh-dss", key.get_name())
        exp_dss = b(FINGER_DSS.split()[1].replace(":", ""))
        my_dss = hexlify(key.get_fingerprint())
        self.assertEqual(exp_dss, my_dss)
        self.assertEqual(PUB_DSS.split()[1], key.get_base64())
        self.assertEqual(1024, key.get_bits())

        s = StringIO()
        key.write_private_key(s)
        self.assertEqual(DSS_PRIVATE_OUT, s.getvalue())
        s.seek(0)
        key2 = DSSKey.from_private_key(s)
        self.assertEqual(key, key2)
예제 #7
0
    def apply_config(self, user, timestamp, passphrase):

        """ Apply the configuration

        This will check the Affectedlog and generates proper authorized_keys
         file for each host affected.

        """

        retval = {
            "status": "success",
            "ssh_messages": []
        }

        # Add note about that.

        ActionLog(
            timestamp=timestamp,
            user=user,
            action="APPLY"
        ).save()

        # Do some initialisation

        affected_hosts = self.all()

        public_key = Configuration.objects.get(
            key="sshkey_public"
        )

        private_key_config = Configuration.objects.get(
            key="sshkey_private"
        )

        keytype = Configuration.objects.get(
            key="sshkey_type"
        )

        if not public_key or not private_key_config or not keytype:
            raise _("Invalid configuration. Did you run setup already?")

        if passphrase == "":
            passphrase = None

        private_key = None

        try:

            # Generate private key to use

            private_key_file = StringIO.StringIO(
                str(private_key_config.value)
            )

            if keytype.value == "dsa":

                # noinspection PyTypeChecker
                private_key = DSSKey.from_private_key(
                    private_key_file, passphrase
                )

            else:

                # noinspection PyTypeChecker
                private_key = RSAKey.from_private_key(
                    private_key_file, passphrase
                )

            private_key_file.close()

        except SSHException:

            retval['ssh_messages'].append(_(
                "Cannot open skd private key. Perhaps you specified the "
                "wrong passphrase?"
            ))

            retval['status'] = "error"

        hosts_applied = []

        if private_key:

            client = SSHClient()
            client.load_system_host_keys()
            client.set_missing_host_key_policy(AutoAddPolicy)

            for apply_line in affected_hosts:

                host = apply_line.host

                if host in hosts_applied:
                    continue

                workload = []

                # Find all users, that have access to this host.

                user_keys = UserKey.objects.filter(
                    **{
                        "user__useringroup__group__"
                        "usergroupinhostgroup__hostgroup__"
                        "hostingroup__host__id": host.id
                    }
                )

                if not user_keys:

                    # This seems to be an old entry. Obviously, no one
                    # has access to the host anymore. Skip it.

                    hosts_applied.append(host)
                    retval['ssh_messages'].append(
                        _(
                            "Removing seemingly orphaned host %(host)s "
                            "from workload" %
                            {
                                'host': host.name
                            }
                        )
                    )
                    continue

                if host.user == '*':
                    # This host is a wildcard host.

                    # Build up workload using the usernames of the
                    # assigned users and include optional username mappings

                    assigned_users = User.objects.filter(
                        **{
                            "useringroup__group__usergroupinhostgroup__"
                            "hostgroup__hostingroup__host__id": host.id
                        }
                    )

                    for assigned_user in assigned_users:

                        namemaps = UserMap.objects.filter(
                            user=assigned_user,
                            host=host
                        )

                        assigned_username = assigned_user.name

                        if namemaps:

                            assigned_username = namemaps[0].username

                        # Find all users, that also share this username,
                        # either inside their user data or via a username
                        # mapping.

                        # Namemaps

                        all_users = []

                        same_namemap = UserMap.objects.filter(
                            host=host,
                            username=assigned_username
                        )

                        for mapping in same_namemap:
                            all_users.append(mapping.user)

                        # User data

                        same_users = User.objects.filter(
                            **{
                                "name": assigned_username,
                                "useringroup__group__"
                                "usergroupinhostgroup__hostgroup__"
                                "hostingroup__host__id": host.id
                            }
                        )

                        for found_user in same_users:
                            all_users.append(found_user)

                        user_keys = UserKey.objects.filter(
                            user__in=all_users
                        )

                        workload.append(
                            {
                                'host': host,
                                'user': assigned_username,
                                'user_keys': user_keys
                            }
                        )

                else:

                    # No wildcard host, just us.

                    workload = [
                        {
                            'host': host,
                            'user': host.user,
                            'user_keys': user_keys
                        }
                    ]

                error_in_workload = False

                for step in workload:

                    # Build up authorized_keys-filecontent

                    authorized_keys = []

                    for key in user_keys:
                        authorized_keys.append("# %s (%s)" % (
                            key.user.fullname,
                            key.name
                        ))
                        authorized_keys.append(key.key)

                    # Add our own public key to the keys

                    authorized_keys.append("# Generated by skd")
                    authorized_keys.append(
                        public_key.value
                    )

                    # Connect to the server

                    is_connected = False

                    try:

                        client.connect(
                            hostname=str(step['host'].fqdn),
                            username=str(step['user']),
                            pkey=private_key
                        )

                        is_connected = True

                    except AuthenticationException:

                        retval['ssh_messages'].append(_(
                            "Cannot connect to host %(name)s as user "
                            "%(user)s. Perhaps the skd-key hasn't  been "
                            "added to it's authorized_keys-file" %
                            {
                                "name": step['host'].name,
                                "user": step['user']
                            }
                        ))

                        retval['status'] = "error"

                    except (SSHException, socket.error, socket.gaierror):

                        retval['ssh_messages'].append(_(
                            "System failure connecting to SSH host "
                            "%(host)s as user %(user)s: %(error)s" %
                            {
                                "error": sys.exc_info()[1],
                                "host": step['host'].name,
                                "user": step['user']
                            }
                        ))

                        retval['status'] = "error"

                    if is_connected:

                        try:

                            # Deploy the authorized_keys file onto the
                            # server.

                            def noAscii(k):
                                return ''.join(
                                    [x for x in k if ord(x) < 128]
                                )

                            command = 'echo -e "%s" > ~/' \
                                      '.ssh/authorized_keys' % \
                                      (
                                          noAscii(
                                              "\n".join(authorized_keys)
                                          )
                                      )

                            client.exec_command(command=command)

                            retval['ssh_messages'].append(_(
                                "Host %(host)s with user %(user)s "
                                "completed." %
                                {
                                    "host": step['host'].name,
                                    "user": step['user']
                                }
                            ))

                        except SSHException:

                            retval['ssh_messages'].append(_(
                                "Error deploying the authorized_keys-file "
                                "of host %(host)s / user %(user)s: "
                                "%(error)s" %
                                {
                                    "error": sys.exc_info()[1],
                                    "host": host.name,
                                    "user": host.user
                                }
                            ))

                            retval['status'] = "error"

                            error_in_workload = True

                        if not error_in_workload:

                            # All went well, delete host from apply-Log.

                            hosts_applied.append(host)

                        client.close()

            # Remove succesful hosts from applylog

            self.filter(host__in=hosts_applied).delete()

        return retval