crypto: validate PEM data before saving
This commit is contained in:
parent
9a9feea5ff
commit
2ee45f388c
|
@ -1,4 +1,7 @@
|
|||
"""passbook Crypto forms"""
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives.serialization import load_pem_private_key
|
||||
from cryptography.x509 import load_pem_x509_certificate
|
||||
from django import forms
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
|
@ -8,6 +11,32 @@ from passbook.crypto.models import CertificateKeyPair
|
|||
class CertificateKeyPairForm(forms.ModelForm):
|
||||
"""CertificateKeyPair Form"""
|
||||
|
||||
def clean_certificate_data(self):
|
||||
"""Verify that input is a valid PEM x509 Certificate"""
|
||||
certificate_data = self.cleaned_data["certificate_data"]
|
||||
try:
|
||||
load_pem_x509_certificate(
|
||||
certificate_data.encode("utf-8"), default_backend()
|
||||
)
|
||||
except ValueError:
|
||||
raise forms.ValidationError("Unable to load certificate.")
|
||||
|
||||
def clean_key_data(self):
|
||||
"""Verify that input is a valid PEM RSA Key"""
|
||||
key_data = self.cleaned_data["key_data"]
|
||||
# Since this field is optional, data can be empty.
|
||||
if key_data == "":
|
||||
return
|
||||
try:
|
||||
load_pem_private_key(
|
||||
str.encode("\n".join([x.strip() for x in key_data.split("\n")])),
|
||||
password=None,
|
||||
backend=default_backend(),
|
||||
)
|
||||
load_pem_x509_certificate(key_data.encode("utf-8"), default_backend())
|
||||
except ValueError:
|
||||
raise forms.ValidationError("Unable to load private key.")
|
||||
|
||||
class Meta:
|
||||
|
||||
model = CertificateKeyPair
|
||||
|
|
Reference in New Issue