Example #1
0
    def generatekey(self):
        public_key = StringIO()
        private_key = StringIO()
        public_key_value = None
        private_key_value = None
        try:
            if self.keytype == 'rsa':
                key = RSAKey.generate(self.rsabits)
            elif self.keytype == 'ecdsa':
                key = ECDSAKey.generate(bits=self.ecdsabits)
            elif self.keytype == 'dss':
                key = DSSKey.generate(bits=self.dssbits)
            else:
                return None, "sshkey暂时不支持其它类型 %s" % self.keytype
            key.write_private_key(private_key)
            public_key.write("%s %s %s" %
                             (key.get_name(), key.get_base64(), self.basename))
            public_key_value = public_key.getvalue()
            private_key_value = private_key.getvalue()
            cache.set("user_%s_private_key" % self.username, private_key_value)
            cache.set("user_%s_public_key" % self.username, public_key_value)

        except Exception as e:
            logger.error(e.args)
            return None, e.args
        finally:
            public_key.close()
            private_key.close()
        return {
            "publickey": public_key_value,
            "privatekey": private_key_value
        }, None
Example #2
0
    def from_line(cls, line, lineno=None):
        """
        Parses the given line of text to find the names for the host,
        the type of key, and the key data. The line is expected to be in the
        format used by the OpenSSH known_hosts file.

        Lines are expected to not have leading or trailing whitespace.
        We don't bother to check for comments or empty lines.  All of
        that should be taken care of before sending the line to us.

        :param str line: a line from an OpenSSH known_hosts file
        """
        log = get_logger("paramiko.hostkeys")
        fields = line.split(" ")
        if len(fields) < 3:
            # Bad number of fields
            msg = "Not enough fields found in known_hosts in line {} ({!r})"
            log.info(msg.format(lineno, line))
            return None
        fields = fields[:3]

        names, keytype, key = fields
        names = names.split(",")

        # Decide what kind of key we're looking at and create an object
        # to hold it accordingly.
        try:
            key = b(key)
            if keytype == "ssh-rsa":
                key = RSAKey(data=decodebytes(key))
            elif keytype == "ssh-dss":
                key = DSSKey(data=decodebytes(key))
            elif keytype in ECDSAKey.supported_key_format_identifiers():
                key = ECDSAKey(data=decodebytes(key), validate_point=False)
            elif keytype == "ssh-ed25519":
                key = Ed25519Key(data=decodebytes(key))
            elif keytype == "ssh-xmss":
                key = XMSS(data=decodebytes(key))
            else:
                log.info("Unable to handle key of type {}".format(keytype))
                return None

        except binascii.Error as e:
            raise InvalidHostKey(line, e)

        return cls(names, key)
Example #3
0
def _parse_ecdsa_key(msg):
    # See comment for _parse_rsa_key
    key_msg = Message()
    curve = msg.get_text()
    key_msg.add_string('ecdsa-sha2-{}'.format(curve))
    key_msg.add_string(curve)
    key_msg.add_string(msg.get_binary())
    key_msg.rewind()
    return ECDSAKey(msg=key_msg)
Example #4
0
    def _get_key_name_pattern(self, identity: Identity) -> Pattern[str]:
        """Make the regex pattern from the format string.  Put two different
        random keys, compare two outputs, and then replace the difference
        with wildcard.

        """
        cls = type(self)
        sample_keys = cls._sample_keys
        if sample_keys is None:
            sample_keys = (RSAKey.generate(bits=512),
                           RSAKey.generate(bits=512),
                           ECDSAKey.generate(bits=256),
                           ECDSAKey.generate(bits=256))
            cls._sample_keys = sample_keys
        sample_names = [self._get_key_name(identity, k) for k in sample_keys]
        if len(frozenset(sample_names)) < 2:
            return re.compile('^' + re.escape(sample_names[0]) + '$')
        prefix = os.path.commonprefix(sample_names)
        postfix = os.path.commonprefix([n[::-1] for n in sample_names])[::-1]
        return re.compile('^{}.+?{}$'.format(re.escape(prefix),
                                             re.escape(postfix)))
Example #5
0
def post_init_hook(cr, pool):
    if socket.getfqdn().endswith('odoo-community.org'):  # pragma: no cover
        # we need a different default listeing address on runbot
        pool['ir.config_parameter'].set_param(cr, SUPERUSER_ID,
                                              'document_sftp.bind',
                                              '%s:0' % socket.getfqdn())
    hostkey = pool['ir.config_parameter'].get_param(cr, SUPERUSER_ID,
                                                    'document_sftp.hostkey')
    parameters = etree.parse(
        tools.file_open('document_sftp/data/ir_config_parameter.xml'))
    default_value = None
    for node in parameters.xpath(
            "//record[@id='param_hostkey']//field[@name='value']"):
        default_value = node.text
    if not hostkey or hostkey == default_value:
        _logger.info('Generating host key for database %s', cr.dbname)
        key = StringIO.StringIO()
        ECDSAKey.generate().write_private_key(key)
        pool['ir.config_parameter'].set_param(cr, SUPERUSER_ID,
                                              'document_sftp.hostkey',
                                              key.getvalue())
        key.close()
Example #6
0
    def _get_key_name_pattern(self,
                              identity: Identity) -> Pattern[str]:
        """Make the regex pattern from the format string.  Put two different
        random keys, compare two outputs, and then replace the difference
        with wildcard.

        """
        cls = type(self)
        sample_keys = cls._sample_keys
        if sample_keys is None:
            sample_keys = (RSAKey.generate(bits=512),
                           RSAKey.generate(bits=512),
                           ECDSAKey.generate(bits=256),
                           ECDSAKey.generate(bits=256))
            cls._sample_keys = sample_keys
        sample_names = [self._get_key_name(identity, k) for k in sample_keys]
        if len(frozenset(sample_names)) < 2:
            return re.compile('^' + re.escape(sample_names[0]) + '$')
        prefix = os.path.commonprefix(sample_names)
        postfix = os.path.commonprefix([n[::-1] for n in sample_names])[::-1]
        return re.compile(
            '^{}.+?{}$'.format(re.escape(prefix), re.escape(postfix))
        )
Example #7
0
    def from_line(cls, line, lineno=None):
        """
        Parses the given line of text to find the names for the host,
        the type of key, and the key data. The line is expected to be in the
        format used by the OpenSSH known_hosts file.

        Lines are expected to not have leading or trailing whitespace.
        We don't bother to check for comments or empty lines.  All of
        that should be taken care of before sending the line to us.

        :param str line: a line from an OpenSSH known_hosts file
        """
        log = get_logger("paramiko.hostkeys")
        fields = line.split(" ")
        if len(fields) < 3:
            # Bad number of fields
            msg = "Not enough fields found in known_hosts in line {} ({!r})"
            log.info(msg.format(lineno, line))
            return None
        fields = fields[:3]

        names, keytype, key = fields
        names = names.split(",")

        # Decide what kind of key we're looking at and create an object
        # to hold it accordingly.
        try:
            key = b(key)
            if keytype == "ssh-rsa":
                key = RSAKey(data=decodebytes(key))
            elif keytype == "ssh-dss":
                key = DSSKey(data=decodebytes(key))
            elif keytype in ECDSAKey.supported_key_format_identifiers():
                key = ECDSAKey(data=decodebytes(key), validate_point=False)
            elif keytype == "ssh-ed25519":
                key = Ed25519Key(data=decodebytes(key))
            else:
                log.info("Unable to handle key of type {}".format(keytype))
                return None

        except binascii.Error as e:
            raise InvalidHostKey(line, e)

        return cls(names, key)
Example #8
0
    def from_line(cls, line, lineno=None):
        """
        Parses the given line of text to find the names for the host,
        the type of key, and the key data. The line is expected to be in the
        format used by the openssh known_hosts file.

        Lines are expected to not have leading or trailing whitespace.
        We don't bother to check for comments or empty lines.  All of
        that should be taken care of before sending the line to us.

        @param line: a line from an OpenSSH known_hosts file
        @type line: str
        """
        log = get_logger('paramiko.hostkeys')
        fields = line.split(' ')
        if len(fields) < 3:
            # Bad number of fields
            log.info("Not enough fields found in known_hosts in line %s (%r)" %
                     (lineno, line))
            return None
        fields = fields[:3]

        names, keytype, key = fields
        names = names.split(',')

        # Decide what kind of key we're looking at and create an object
        # to hold it accordingly.
        try:
            key = b(key)
            if keytype == 'ssh-rsa':
                key = RSAKey(data=decodebytes(key))
            elif keytype == 'ssh-dss':
                key = DSSKey(data=decodebytes(key))
            elif keytype == 'ecdsa-sha2-nistp256':
                key = ECDSAKey(data=decodebytes(key))
            else:
                log.info("Unable to handle key of type %s" % (keytype, ))
                return None

        except binascii.Error:
            raise InvalidHostKey(line, sys.exc_info()[1])

        return cls(names, key)