Exemplo n.º 1
0
    def create(self, req, body):
        """
        Create or import keypair.

        Sending name will generate a key and return private_key
        and fingerprint.

        You can send a public_key to add an existing ssh key

        params: keypair object with:
            name (required) - string
            public_key (optional) - string
        """

        context = req.environ['nova.context']
        authorize(context)
        params = body['keypair']
        name = params['name']
        self._validate_keypair_name(name)

        if not 0 < len(name) < 256:
            msg = _('Keypair name must be between 1 and 255 characters long')
            raise webob.exc.HTTPBadRequest(explanation=msg)
        # NOTE(ja): generation is slow, so shortcut invalid name exception
        try:
            db.key_pair_get(context, context.user_id, name)
            msg = _("Key pair '%s' already exists.") % name
            raise webob.exc.HTTPConflict(explanation=msg)
        except exception.NotFound:
            pass

        keypair = {'user_id': context.user_id,
                   'name': name}

        if quota.allowed_key_pairs(context, 1) < 1:
            msg = _("Quota exceeded, too many key pairs.")
            raise webob.exc.HTTPRequestEntityTooLarge(
                      explanation=msg,
                      headers={'Retry-After': 0})
        # import if public_key is sent
        if 'public_key' in params:
            try:
                fingerprint = crypto.generate_fingerprint(params['public_key'])
            except exception.InvalidKeypair:
                msg = _("Keypair data is invalid")
                raise webob.exc.HTTPBadRequest(explanation=msg)

            keypair['public_key'] = params['public_key']
            keypair['fingerprint'] = fingerprint
        else:
            generated_key = self._gen_key()
            keypair['private_key'] = generated_key['private_key']
            keypair['public_key'] = generated_key['public_key']
            keypair['fingerprint'] = generated_key['fingerprint']

        db.key_pair_create(context, keypair)
        return {'keypair': keypair}
Exemplo n.º 2
0
 def test_launch_with_key(self):
     instance_uuid = utils.create_instance(self.context)
     blessed_instance = self.cobalt_api.bless_instance(self.context, instance_uuid)
     blessed_instance_uuid = blessed_instance["uuid"]
     db.key_pair_create(
         self.context, {"name": "foo", "public_key": "bar", "user_id": self.context.user_id, "fingerprint": ""}
     )
     inst = self.cobalt_api.launch_instance(self.context, blessed_instance_uuid, params={"key_name": "foo"})
     self.assertEqual(inst["key_name"], "foo")
     self.assertEqual(inst["key_data"], "bar")
Exemplo n.º 3
0
 def test_create(self):
     self.mox.StubOutWithMock(db, 'key_pair_create')
     db.key_pair_create(self.context,
                        {'name': 'foo-keypair',
                         'public_key': 'keydata'}).AndReturn(fake_keypair)
     self.mox.ReplayAll()
     keypair_obj = keypair.KeyPair(context=self.context)
     keypair_obj.name = 'foo-keypair'
     keypair_obj.public_key = 'keydata'
     keypair_obj.create()
     self.compare_obj(keypair_obj, fake_keypair)
Exemplo n.º 4
0
 def test_recreate_fails(self):
     self.mox.StubOutWithMock(db, 'key_pair_create')
     db.key_pair_create(self.context,
                        {'name': 'foo-keypair',
                         'public_key': 'keydata'}).AndReturn(fake_keypair)
     self.mox.ReplayAll()
     keypair_obj = keypair.KeyPair(context=self.context)
     keypair_obj.name = 'foo-keypair'
     keypair_obj.public_key = 'keydata'
     keypair_obj.create()
     self.assertRaises(exception.ObjectActionError, keypair_obj.create)
Exemplo n.º 5
0
 def test_create(self):
     self.mox.StubOutWithMock(db, 'key_pair_create')
     db.key_pair_create(self.context,
                        {'name': 'foo-keypair',
                         'public_key': 'keydata'}).AndReturn(fake_keypair)
     self.mox.ReplayAll()
     keypair_obj = keypair.KeyPair()
     keypair_obj.name = 'foo-keypair'
     keypair_obj.public_key = 'keydata'
     keypair_obj.create(self.context)
     self._compare(keypair_obj, fake_keypair)
Exemplo n.º 6
0
 def test_recreate_fails(self):
     self.mox.StubOutWithMock(db, 'key_pair_create')
     db.key_pair_create(self.context,
                        {'name': 'foo-keypair',
                         'public_key': 'keydata'}).AndReturn(fake_keypair)
     self.mox.ReplayAll()
     keypair_obj = keypair.KeyPair()
     keypair_obj.name = 'foo-keypair'
     keypair_obj.public_key = 'keydata'
     keypair_obj.create(self.context)
     self.assertRaises(exception.ObjectActionError, keypair_obj.create,
                       self.context)
Exemplo n.º 7
0
    def create(self, req, body):
        """
        Create or import keypair.

        Sending name will generate a key and return private_key
        and fingerprint.

        You can send a public_key to add an existing ssh key

        params: keypair object with:
            name (required) - string
            public_key (optional) - string
        """

        context = req.environ['nova.context']
        authorize(context)
        params = body['keypair']
        name = params['name']
        self._validate_keypair_name(name)

        if not 0 < len(name) < 256:
            msg = _('Keypair name must be between 1 and 255 characters long')
            raise webob.exc.HTTPBadRequest(explanation=msg)
        # NOTE(ja): generation is slow, so shortcut invalid name exception
        try:
            db.key_pair_get(context, context.user_id, name)
            msg = _("Key pair '%s' already exists.") % name
            raise webob.exc.HTTPConflict(explanation=msg)
        except exception.NotFound:
            pass

        keypair = {'user_id': context.user_id,
                   'name': name}

        # import if public_key is sent
        if 'public_key' in params:
            try:
                fingerprint = crypto.generate_fingerprint(params['public_key'])
            except exception.InvalidKeypair:
                msg = _("Keypair data is invalid")
                raise webob.exc.HTTPBadRequest(explanation=msg)

            keypair['public_key'] = params['public_key']
            keypair['fingerprint'] = fingerprint
        else:
            generated_key = self._gen_key()
            keypair['private_key'] = generated_key['private_key']
            keypair['public_key'] = generated_key['public_key']
            keypair['fingerprint'] = generated_key['fingerprint']

        db.key_pair_create(context, keypair)
        return {'keypair': keypair}
Exemplo n.º 8
0
 def test_launch_with_key(self):
     instance_uuid = utils.create_instance(self.context)
     blessed_instance = self.cobalt_api.bless_instance(self.context,
                                                            instance_uuid)
     blessed_instance_uuid = blessed_instance['uuid']
     db.key_pair_create(self.context, {'name': 'foo', 'public_key': 'bar',
                                       'user_id': self.context.user_id,
                                       'fingerprint': ''})
     inst = self.cobalt_api.launch_instance(self.context,
                                                 blessed_instance_uuid,
                                                 params={'key_name': 'foo'})
     self.assertEqual(inst['key_name'], 'foo')
     self.assertEqual(inst['key_data'], 'bar')
Exemplo n.º 9
0
    def create(self, req, body):
        """
        Create or import keypair.

        Sending name will generate a key and return private_key
        and fingerprint.

        You can send a public_key to add an existing ssh key

        params: keypair object with:
            name (required) - string
            public_key (optional) - string
        """

        context = req.environ["nova.context"]
        authorize(context)
        params = body["keypair"]
        name = params["name"]
        self._validate_keypair_name(name)

        if not 0 < len(name) < 256:
            msg = _("Keypair name must be between 1 and 255 characters long")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        # NOTE(ja): generation is slow, so shortcut invalid name exception
        try:
            db.key_pair_get(context, context.user_id, name)
            msg = _("Key pair '%s' already exists.") % name
            raise webob.exc.HTTPConflict(explanation=msg)
        except exception.NotFound:
            pass

        keypair = {"user_id": context.user_id, "name": name}

        # import if public_key is sent
        if "public_key" in params:
            try:
                fingerprint = crypto.generate_fingerprint(params["public_key"])
            except exception.InvalidKeypair:
                msg = _("Keypair data is invalid")
                raise webob.exc.HTTPBadRequest(explanation=msg)

            keypair["public_key"] = params["public_key"]
            keypair["fingerprint"] = fingerprint
        else:
            generated_key = self._gen_key()
            keypair["private_key"] = generated_key["private_key"]
            keypair["public_key"] = generated_key["public_key"]
            keypair["fingerprint"] = generated_key["fingerprint"]

        db.key_pair_create(context, keypair)
        return {"keypair": keypair}
Exemplo n.º 10
0
    def create(self, req, body):
        """
        Create or import keypair.

        Sending name will generate a key and return private_key
        and fingerprint.

        You can send a public_key to add an existing ssh key

        params: keypair object with:
            name (required) - string
            public_key (optional) - string
        """

        context = req.environ['nova.context']
        authorize(context)
        params = body['keypair']
        name = params['name']

        if not 0 < len(name) < 256:
            msg = _('Keypair name must be between 1 and 255 characters long')
            raise webob.exc.HTTPBadRequest(explanation=msg)
        # NOTE(ja): generation is slow, so shortcut invalid name exception
        try:
            db.key_pair_get(context, context.user_id, name)
            raise exception.KeyPairExists(key_name=name)
        except exception.NotFound:
            pass

        keypair = {'user_id': context.user_id,
                   'name': name}

        # import if public_key is sent
        if 'public_key' in params:
            try:
                fingerprint = crypto.generate_fingerprint(params['public_key'])
            except exception.InvalidKeypair:
                msg = _("Keypair data is invalid")
                raise webob.exc.HTTPBadRequest(explanation=msg)

            keypair['public_key'] = params['public_key']
            keypair['fingerprint'] = fingerprint
        else:
            generated_key = self._gen_key()
            keypair['private_key'] = generated_key['private_key']
            keypair['public_key'] = generated_key['public_key']
            keypair['fingerprint'] = generated_key['fingerprint']

        db.key_pair_create(context, keypair)
        return {'keypair': keypair}
Exemplo n.º 11
0
 def create(self, context):
     if self.obj_attr_is_set('id'):
         raise exception.ObjectActionError(action='create',
                                           reason='already created')
     updates = self.obj_get_changes()
     db_keypair = db.key_pair_create(context, updates)
     self._from_db_object(context, self, db_keypair)
Exemplo n.º 12
0
 def create(self, context):
     if self.obj_attr_is_set("id"):
         raise exception.ObjectActionError(action="create", reason="already created")
     updates = self.obj_get_changes()
     updates.pop("id", None)
     db_keypair = db.key_pair_create(context, updates)
     self._from_db_object(context, self, db_keypair)
Exemplo n.º 13
0
 def create(self):
     if self.obj_attr_is_set('id'):
         raise exception.ObjectActionError(action='create',
                                           reason='already created')
     updates = self.obj_get_changes()
     db_keypair = db.key_pair_create(self._context, updates)
     self._from_db_object(self._context, self, db_keypair)
Exemplo n.º 14
0
    def create(self, req, body):
        """
        Create or import keypair.

        Sending name will generate a key and return private_key
        and fingerprint.

        You can send a public_key to add an existing ssh key

        params: keypair object with:
            name (required) - string
            public_key (optional) - string
        """

        context = req.environ['nova.context']
        params = body['keypair']
        name = params['name']

        # NOTE(ja): generation is slow, so shortcut invalid name exception
        try:
            db.key_pair_get(context, context.user_id, name)
            raise exception.KeyPairExists(key_name=name)
        except exception.NotFound:
            pass

        keypair = {'user_id': context.user_id,
                   'name': name}

        # import if public_key is sent
        if 'public_key' in params:
            tmpdir = tempfile.mkdtemp()
            fn = os.path.join(tmpdir, 'import.pub')
            with open(fn, 'w') as pub:
                pub.write(params['public_key'])
            fingerprint = crypto.generate_fingerprint(fn)
            shutil.rmtree(tmpdir)
            keypair['public_key'] = params['public_key']
            keypair['fingerprint'] = fingerprint
        else:
            generated_key = self._gen_key()
            keypair['private_key'] = generated_key['private_key']
            keypair['public_key'] = generated_key['public_key']
            keypair['fingerprint'] = generated_key['fingerprint']

        db.key_pair_create(context, keypair)
        return {'keypair': keypair}
Exemplo n.º 15
0
    def create(self, req, body):
        """
        Create or import keypair.

        Sending name will generate a key and return private_key
        and fingerprint.

        You can send a public_key to add an existing ssh key

        params: keypair object with:
            name (required) - string
            public_key (optional) - string
        """

        context = req.environ['nova.context']
        params = body['keypair']
        name = params['name']

        # NOTE(ja): generation is slow, so shortcut invalid name exception
        try:
            db.key_pair_get(context, context.user_id, name)
            raise exception.KeyPairExists(key_name=name)
        except exception.NotFound:
            pass

        keypair = {'user_id': context.user_id,
                   'name': name}

        # import if public_key is sent
        if 'public_key' in params:
            tmpdir = tempfile.mkdtemp()
            fn = os.path.join(tmpdir, 'import.pub')
            with open(fn, 'w') as pub:
                pub.write(params['public_key'])
            fingerprint = crypto.generate_fingerprint(fn)
            shutil.rmtree(tmpdir)
            keypair['public_key'] = params['public_key']
            keypair['fingerprint'] = fingerprint
        else:
            generated_key = self._gen_key()
            keypair['private_key'] = generated_key['private_key']
            keypair['public_key'] = generated_key['public_key']
            keypair['fingerprint'] = generated_key['fingerprint']

        db.key_pair_create(context, keypair)
        return {'keypair': keypair}
Exemplo n.º 16
0
    def _gen_key(self, context, user_id, key_name):
        """Generate a key

        This is a module level method because it is slow and we need to defer
        it into a process pool."""
        # NOTE(vish): generating key pair is slow so check for legal
        #             creation before creating key_pair
        try:
            db.key_pair_get(context, user_id, key_name)
            raise exception.KeyPairExists(key_name=key_name)
        except exception.NotFound:
            pass
        private_key, public_key, fingerprint = crypto.generate_key_pair()
        key = {}
        key['user_id'] = user_id
        key['name'] = key_name
        key['public_key'] = public_key
        key['fingerprint'] = fingerprint
        db.key_pair_create(context, key)
        return {'private_key': private_key, 'fingerprint': fingerprint}
Exemplo n.º 17
0
 def import_public_key(self, context, key_name, public_key,
                      fingerprint=None):
     LOG.audit(_("Import key %s"), key_name, context=context)
     key = {}
     key['user_id'] = context.user_id
     key['name'] = key_name
     key['public_key'] = public_key
     if fingerprint is None:
         tmpdir = tempfile.mkdtemp()
         pubfile = os.path.join(tmpdir, 'temp.pub')
         fh = open(pubfile, 'w')
         fh.write(public_key)
         fh.close()
         (out, err) = utils.execute('ssh-keygen', '-q', '-l', '-f',
                                    '%s' % (pubfile))
         fingerprint = out.split(' ')[1]
         shutil.rmtree(tmpdir)
     key['fingerprint'] = fingerprint
     db.key_pair_create(context, key)
     return True
Exemplo n.º 18
0
    def _gen_key(self, context, user_id, key_name):
        """Generate a key

        This is a module level method because it is slow and we need to defer
        it into a process pool."""
        # NOTE(vish): generating key pair is slow so check for legal
        #             creation before creating key_pair
        try:
            db.key_pair_get(context, user_id, key_name)
            raise exception.KeyPairExists(key_name=key_name)
        except exception.NotFound:
            pass
        private_key, public_key, fingerprint = crypto.generate_key_pair()
        key = {}
        key['user_id'] = user_id
        key['name'] = key_name
        key['public_key'] = public_key
        key['fingerprint'] = fingerprint
        db.key_pair_create(context, key)
        return {'private_key': private_key, 'fingerprint': fingerprint}
Exemplo n.º 19
0
 def create(self, context):
     updates = {}
     for key in self.obj_what_changed():
         updates[key] = self[key]
     db_keypair = db.key_pair_create(context, updates)
     self._from_db_object(context, self, db_keypair)
Exemplo n.º 20
0
 def create(self, context):
     updates = {}
     for key in self.obj_what_changed():
         updates[key] = self[key]
     db_keypair = db.key_pair_create(context, updates)
     self._from_db_object(context, self, db_keypair)
Exemplo n.º 21
0
 def create(self, context):
     updates = self.obj_get_changes()
     db_keypair = db.key_pair_create(context, updates)
     self._from_db_object(context, self, db_keypair)