Using ssh-keygen to validate public key

This commit is contained in:
PCoder 2017-09-13 02:22:29 +05:30
parent 4ce914b178
commit 261615e701
2 changed files with 24 additions and 19 deletions

View file

@ -1,5 +1,8 @@
import datetime import datetime
import logging import logging
import subprocess
import tempfile
import os
from django import forms from django import forms
from django.contrib.auth import authenticate from django.contrib.auth import authenticate
@ -92,25 +95,22 @@ class UserHostingKeyForm(forms.ModelForm):
return self.data.get('public_key') return self.data.get('public_key')
KEY_ERROR_MESSAGE = _("Please input a proper SSH key") KEY_ERROR_MESSAGE = _("Please input a proper SSH key")
openssh_pubkey_str = self.data.get('public_key') openssh_pubkey_str = self.data.get('public_key')
with tempfile.NamedTemporaryFile(delete=True) as tmp_public_key_file:
tmp_public_key_file.writelines(openssh_pubkey_str)
tmp_public_key_file.flush()
try: try:
ssh_key = SSHKey(openssh_pubkey_str) out = subprocess.check_output(
ssh_key.parse() ['ssh-keygen', '-lf', tmp_public_key_file.name])
except InvalidKeyException as err: except subprocess.CalledProcessError as cpe:
logger.error( logger.debug(
"InvalidKeyException while parsing ssh key {0}".format(err)) "Not a correct ssh format {error} {out}".format(
raise forms.ValidationError(KEY_ERROR_MESSAGE) error=str(cpe), out=out))
except NotImplementedError as err:
logger.error(
"NotImplementedError while parsing ssh key {0}".format(err))
raise forms.ValidationError(KEY_ERROR_MESSAGE)
except UnicodeDecodeError as u:
logger.error(
"UnicodeDecodeError while parsing ssh key {0}".format(u))
raise forms.ValidationError(KEY_ERROR_MESSAGE)
except ValueError as v:
logger.error(
"ValueError while parsing ssh key {0}".format(v))
raise forms.ValidationError(KEY_ERROR_MESSAGE) raise forms.ValidationError(KEY_ERROR_MESSAGE)
try:
os.remove(tmp_public_key_file.name)
except OSError:
pass
return openssh_pubkey_str return openssh_pubkey_str
def clean_name(self): def clean_name(self):

View file

@ -1,4 +1,5 @@
import tempfile import tempfile
import os
import cdist import cdist
from cdist.integration import configure_hosts_simple from cdist.integration import configure_hosts_simple
@ -67,6 +68,10 @@ def save_ssh_key(self, hosts, keys):
except Exception as cdist_exception: except Exception as cdist_exception:
logger.error(cdist_exception) logger.error(cdist_exception)
return_value = False return_value = False
try:
os.remove(tmp_manifest.name)
except OSError:
pass
return return_value return return_value