From 6f67c9d043ebd104e07a59f0cd2e9eaca003a4c1 Mon Sep 17 00:00:00 2001 From: Chuck Short Date: Thu, 8 Mar 2012 15:09:38 -0500 Subject: EC2 KeyName validation. According to EC2 API Documentation, the keyname is acccetable as a alphanumeric characters, spaces, dashes, and underscores. As well as make sure that the keyname doesnt exceed 255 characters. Make sure that the key that is being created is valid. Fixes bug 947750. Change-Id: I083af7f2cbc417150fadb79b307083bb3ba229d6 Signed-off-by: Chuck Short --- nova/api/ec2/cloud.py | 11 +++++++++++ nova/tests/api/ec2/test_cloud.py | 18 +++++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/nova/api/ec2/cloud.py b/nova/api/ec2/cloud.py index 25d6c1c81..f4886551d 100644 --- a/nova/api/ec2/cloud.py +++ b/nova/api/ec2/cloud.py @@ -369,6 +369,17 @@ class CloudController(object): return {'keySet': result} def create_key_pair(self, context, key_name, **kwargs): + if not re.match('^[a-zA-Z0-9_\- ]+$', str(key_name)): + err = _("Value (%s) for KeyName is invalid." + " Content limited to Alphanumeric character, " + "spaces, dashes, and underscore.") % key_name + raise exception.EC2APIError(err) + + if len(str(key_name)) > 255: + err = _("Value (%s) for Keyname is invalid." + " Length exceeds maximum of 255.") % key_name + raise exception.EC2APIError(err) + LOG.audit(_("Create key pair %s"), key_name, context=context) data = _gen_key(context, context.user_id, key_name) return {'keyName': key_name, diff --git a/nova/tests/api/ec2/test_cloud.py b/nova/tests/api/ec2/test_cloud.py index 5a64f237e..9cf777e7a 100644 --- a/nova/tests/api/ec2/test_cloud.py +++ b/nova/tests/api/ec2/test_cloud.py @@ -20,8 +20,9 @@ import base64 import copy import functools -import tempfile import os +import string +import tempfile from nova.api.ec2 import cloud from nova.api.ec2 import ec2utils @@ -1363,6 +1364,21 @@ class CloudTestCase(test.TestCase): self.assertEqual(dummypub, keydata['public_key']) self.assertEqual(dummyfprint, keydata['fingerprint']) + def test_create_key_pair(self): + good_names = ('a', 'a' * 255, string.ascii_letters + ' -_') + bad_names = ('', 'a' * 256, '*', '/') + + for key_name in good_names: + result = self.cloud.create_key_pair(self.context, + key_name) + self.assertEqual(result['keyName'], key_name) + + for key_name in bad_names: + self.assertRaises(exception.EC2APIError, + self.cloud.create_key_pair, + self.context, + key_name) + def test_delete_key_pair(self): self._create_key('test') self.cloud.delete_key_pair(self.context, 'test') -- cgit