@@ -66,11 +66,18 @@ def get_subj_alt_name(peer_cert):
6666
6767def validate_certificate (value ):
6868 try :
69- crypto .load_certificate (crypto .FILETYPE_PEM , value )
69+ return crypto .load_certificate (crypto .FILETYPE_PEM , value )
7070 except crypto .Error as e :
7171 raise ValidationError ('Could not load certificate: {}' .format (e ))
7272
7373
74+ def validate_private_key (value ):
75+ try :
76+ return crypto .load_privatekey (crypto .FILETYPE_PEM , value )
77+ except crypto .Error as e :
78+ raise ValidationError ('Could not load private key: {}' .format (e ))
79+
80+
7481class Certificate (AuditedModel ):
7582 """
7683 Public and private key pair used to secure application traffic at the router.
@@ -79,7 +86,7 @@ class Certificate(AuditedModel):
7986 name = models .CharField (max_length = 253 , unique = True , validators = [validate_label ])
8087 # there is no upper limit on the size of an x.509 certificate
8188 certificate = models .TextField (validators = [validate_certificate ])
82- key = models .TextField ()
89+ key = models .TextField (validators = [ validate_private_key ] )
8390 # X.509 certificates allow any string of information as the common name.
8491 common_name = models .TextField (editable = False , unique = False , null = True )
8592 # A list of DNS records if certificate has SubjectAltName
@@ -106,14 +113,14 @@ def domains(self):
106113 def __str__ (self ):
107114 return self .name
108115
109- def _get_certificate (self ):
116+ def save (self , * args , ** kwargs ):
110117 try :
111- return crypto .load_certificate (crypto .FILETYPE_PEM , self .certificate )
112- except crypto .Error as e :
118+ certificate = validate_certificate (self .certificate )
119+ # NOTE(bacongobbler): we want to load the key here to ensure that it is valid before
120+ # saving it to the database.
121+ validate_private_key (self .key )
122+ except ValidationError as e :
113123 raise SuspiciousOperation (e )
114-
115- def save (self , * args , ** kwargs ):
116- certificate = self ._get_certificate ()
117124 if not self .common_name :
118125 self .common_name = certificate .get_subject ().CN
119126
0 commit comments