1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 08:56:07 +00:00

fix(accounts): an SSH key is a whole key, and added once

The profile took an SSH key whose blob only named its type
("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5") or was cut short, and offered it
for a VM, where it lets no one in. A key is now parsed whole with
cryptography (which paramiko already brings), security keys
(sk-ssh-ed25519) included.

The same key with another comment was added a second time, and
deleting one left the other to be installed. Keys are now compared by
their type and key, without the comment.
This commit is contained in:
catborise 2026-11-12 16:33:09 +03:00
parent 2ab1bac0c7
commit f18be7c33e
4 changed files with 47 additions and 35 deletions

View file

@ -71,8 +71,9 @@ class UserSSHKeyForm(ModelForm):
return self.cleaned_data["keyname"]
def clean_keypublic(self):
# the same key with another comment is the same key
for key in self.publickeys:
if self.cleaned_data["keypublic"] == key.keypublic:
if self.cleaned_data["keypublic"].split()[:2] == key.keypublic.split()[:2]:
raise ValidationError(_("Public key already exist"))
if not validate_ssh_key(self.cleaned_data["keypublic"]):

View file

@ -1,9 +1,13 @@
"""A user's SSH keys go with the user (validate_ssh_key: test_utils)."""
"""A user's SSH keys go with the user, and a key is added once
(validate_ssh_key: test_utils)."""
from django.contrib.auth import get_user_model
from django.test import TestCase
from accounts.forms import UserSSHKeyForm
from accounts.models import UserSSHKey
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
class SshKeyTestCase(TestCase):
@ -20,3 +24,10 @@ class SshKeyTestCase(TestCase):
user.delete()
self.assertFalse(UserSSHKey.objects.filter(id=key.id).exists())
def test_the_same_key_with_another_comment_is_refused(self):
user = get_user_model().objects.create_user(username="dup_key_user", password="password")
key = Ed25519PrivateKey.generate().public_key().public_bytes(Encoding.OpenSSH, PublicFormat.OpenSSH).decode()
UserSSHKey.objects.create(user=user, keyname="laptop", keypublic=f"{key} laptop")
form = UserSSHKeyForm({"keyname": "desktop", "keypublic": f"{key} other comment"}, user=user)
self.assertEqual(form.errors["keypublic"], ["Public key already exist"])

View file

@ -11,6 +11,8 @@ from django.core import mail
from django.test import RequestFactory, TestCase, override_settings
from django.urls import reverse
from django_otp.plugins.otp_totp.models import TOTPDevice
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
from lxml import html
from accounts.utils import (OTP_LINK, OTP_LINK_MAX_AGE, get_existing_totp_device, get_user_totp_device, otp_qr_svg,
@ -25,20 +27,30 @@ class AccountsUtilsTestCase(TestCase):
)
def test_validate_ssh_key_valid(self):
blob = (
struct.pack(">I", 7)
+ b"ssh-rsa"
+ struct.pack(">I", 3)
+ b"\x01\x00\x01"
+ struct.pack(">I", 8)
+ b"\x00" * 8
)
b64 = base64.b64encode(blob).decode()
valid_key = f"ssh-rsa {b64} user@example.com"
self.assertTrue(validate_ssh_key(valid_key))
key = Ed25519PrivateKey.generate().public_key().public_bytes(Encoding.OpenSSH, PublicFormat.OpenSSH).decode()
self.assertTrue(validate_ssh_key(f"{key} user@example.com"))
# ssh-keygen -C "John Doe laptop": the comment holds spaces
self.assertTrue(validate_ssh_key(f"ssh-rsa {b64} John Doe laptop"))
self.assertTrue(validate_ssh_key(f"ssh-rsa {b64}"))
self.assertTrue(validate_ssh_key(f"{key} John Doe laptop"))
self.assertTrue(validate_ssh_key(key))
# a security key (ssh-keygen -t ed25519-sk): its type, key and application
blob = b"".join(struct.pack(">I", len(part)) + part
for part in (b"sk-ssh-ed25519@openssh.com", b"\x01" * 32, b"ssh:"))
self.assertTrue(validate_ssh_key(f"sk-ssh-ed25519@openssh.com {base64.b64encode(blob).decode()} yubikey"))
def test_validate_ssh_key_truncated(self):
# the type alone, or a key cut short: nothing a VM could let in
key = Ed25519PrivateKey.generate().public_key().public_bytes(Encoding.OpenSSH, PublicFormat.OpenSSH).decode()
for truncated in ("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5", key[:-8]):
with self.subTest(truncated):
self.assertFalse(validate_ssh_key(truncated))
def test_validate_ssh_key_one_line(self):
# authorized_keys holds a key per line: a key split over two, or two keys, is not one key
key = Ed25519PrivateKey.generate().public_key().public_bytes(Encoding.OpenSSH, PublicFormat.OpenSSH).decode()
for text in (key.replace(" ", "\r\n", 1), f"{key} a\n{key} b"):
with self.subTest(text):
self.assertFalse(validate_ssh_key(text))
self.assertTrue(validate_ssh_key(f"{key} laptop\r\n"))
def test_validate_ssh_key_invalid_parts(self):
self.assertFalse(validate_ssh_key("only_two parts"))

View file

@ -1,9 +1,8 @@
import base64
import binascii
import struct
from decimal import Decimal
import segno
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.primitives.serialization import load_ssh_public_key
from django.contrib.auth import get_user_model
from django.core.mail import send_mail
from django.core.signing import TimestampSigner
@ -38,25 +37,14 @@ def get_user_totp_device(user):
def validate_ssh_key(key):
# An OpenSSH public key is a type, a key and an optional comment, which may hold spaces
array = key.strip().encode().split(maxsplit=2)
if len(array) < 2:
"""An OpenSSH public key: its type, a whole key of that type (security
keys too) and an optional comment, which may hold spaces: one line, as
authorized_keys holds it."""
if "\n" in key.strip() or "\r" in key.strip():
return False
typeofkey = array[0]
string = array[1]
# must have only valid rsa-ssh key characters ie binascii characters
try:
data = base64.decodebytes(string)
except binascii.Error:
return False
# unpack the contents of data, from data[:4] , property of ssh key .
try:
str_len = struct.unpack(">I", data[:4])[0]
except struct.error:
return False
# data[4:str_len] must have string which matches with the typeofkey, another ssh key property.
if data[4 : 4 + str_len] != typeofkey:
load_ssh_public_key(" ".join(key.split(maxsplit=2)[:2]).encode())
except (ValueError, UnsupportedAlgorithm):
return False
return True