From b185724000dafcfbbb7b5eb52acf20f52228269d Mon Sep 17 00:00:00 2001 From: Inex Code Date: Tue, 23 Nov 2021 20:32:51 +0200 Subject: [PATCH] Move SSH key validation to utils --- selfprivacy_api/resources/services/ssh.py | 24 +++++++++-------------- selfprivacy_api/utils.py | 9 +++++++++ 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/selfprivacy_api/resources/services/ssh.py b/selfprivacy_api/resources/services/ssh.py index d924660..8cc96d9 100644 --- a/selfprivacy_api/resources/services/ssh.py +++ b/selfprivacy_api/resources/services/ssh.py @@ -3,7 +3,7 @@ from flask_restful import Resource, reqparse from selfprivacy_api.resources.services import api -from selfprivacy_api.utils import WriteUserData, ReadUserData +from selfprivacy_api.utils import WriteUserData, ReadUserData, validate_ssh_public_key class EnableSSH(Resource): @@ -154,13 +154,10 @@ class WriteSSHKey(Resource): public_key = args["public_key"] - # Validate SSH public key - # It may be ssh-ed25519 or ssh-rsa - if not public_key.startswith("ssh-ed25519"): - if not public_key.startswith("ssh-rsa"): - return { - "error": "Invalid key type. Only ssh-ed25519 and ssh-rsa are supported.", - }, 400 + if not validate_ssh_public_key(public_key): + return { + "error": "Invalid key type. Only ssh-ed25519 and ssh-rsa are supported.", + }, 400 with WriteUserData() as data: if "ssh" not in data: @@ -272,13 +269,10 @@ class SSHKeys(Resource): "error": "Use /ssh/key/send to add root keys", }, 400 - # Validate SSH public key - # It may be ssh-ed25519 or ssh-rsa - if not args["public_key"].startswith("ssh-ed25519"): - if not args["public_key"].startswith("ssh-rsa"): - return { - "error": "Invalid key type. Only ssh-ed25519 and ssh-rsa are supported.", - }, 400 + if not validate_ssh_public_key(args["public_key"]): + return { + "error": "Invalid key type. Only ssh-ed25519 and ssh-rsa are supported.", + }, 400 with WriteUserData() as data: if username == data["username"]: diff --git a/selfprivacy_api/utils.py b/selfprivacy_api/utils.py index 8a8006c..a2953b1 100644 --- a/selfprivacy_api/utils.py +++ b/selfprivacy_api/utils.py @@ -49,3 +49,12 @@ class ReadUserData(object): def __exit__(self, *args): portalocker.unlock(self.userdata_file) self.userdata_file.close() + + +def validate_ssh_public_key(key): + """Validate SSH public key. It may be ssh-ed25519 or ssh-rsa.""" + if not key.startswith("ssh-ed25519"): + if not key.startswith("ssh-rsa"): + return False + return True + \ No newline at end of file