forms.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. from Crypto.Cipher import PKCS1_OAEP
  2. from Crypto.PublicKey import RSA
  3. from django import forms
  4. from dcim.models import Device
  5. from extras.forms import (
  6. AddRemoveTagsForm, CustomFieldBulkEditForm, CustomFieldFilterForm, CustomFieldModelForm, CustomFieldModelCSVForm,
  7. TagField,
  8. )
  9. from utilities.forms import (
  10. APISelectMultiple, BootstrapMixin, CSVModelChoiceField, CSVModelForm, DynamicModelChoiceField,
  11. DynamicModelMultipleChoiceField, SlugField, StaticSelect2Multiple, TagFilterField,
  12. )
  13. from .constants import *
  14. from .models import Secret, SecretRole, UserKey
  15. def validate_rsa_key(key, is_secret=True):
  16. """
  17. Validate the format and type of an RSA key.
  18. """
  19. if key.startswith('ssh-rsa '):
  20. raise forms.ValidationError("OpenSSH line format is not supported. Please ensure that your public is in PEM (base64) format.")
  21. try:
  22. key = RSA.importKey(key)
  23. except ValueError:
  24. raise forms.ValidationError("Invalid RSA key. Please ensure that your key is in PEM (base64) format.")
  25. except Exception as e:
  26. raise forms.ValidationError("Invalid key detected: {}".format(e))
  27. if is_secret and not key.has_private():
  28. raise forms.ValidationError("This looks like a public key. Please provide your private RSA key.")
  29. elif not is_secret and key.has_private():
  30. raise forms.ValidationError("This looks like a private key. Please provide your public RSA key.")
  31. try:
  32. PKCS1_OAEP.new(key)
  33. except Exception:
  34. raise forms.ValidationError("Error validating RSA key. Please ensure that your key supports PKCS#1 OAEP.")
  35. #
  36. # Secret roles
  37. #
  38. class SecretRoleForm(BootstrapMixin, forms.ModelForm):
  39. slug = SlugField()
  40. class Meta:
  41. model = SecretRole
  42. fields = [
  43. 'name', 'slug', 'description', 'users', 'groups',
  44. ]
  45. widgets = {
  46. 'users': StaticSelect2Multiple(),
  47. 'groups': StaticSelect2Multiple(),
  48. }
  49. class SecretRoleCSVForm(CSVModelForm):
  50. slug = SlugField()
  51. class Meta:
  52. model = SecretRole
  53. fields = SecretRole.csv_headers
  54. #
  55. # Secrets
  56. #
  57. class SecretForm(BootstrapMixin, CustomFieldModelForm):
  58. device = DynamicModelChoiceField(
  59. queryset=Device.objects.all()
  60. )
  61. plaintext = forms.CharField(
  62. max_length=SECRET_PLAINTEXT_MAX_LENGTH,
  63. required=False,
  64. label='Plaintext',
  65. widget=forms.PasswordInput(
  66. attrs={
  67. 'class': 'requires-session-key',
  68. }
  69. )
  70. )
  71. plaintext2 = forms.CharField(
  72. max_length=SECRET_PLAINTEXT_MAX_LENGTH,
  73. required=False,
  74. label='Plaintext (verify)',
  75. widget=forms.PasswordInput()
  76. )
  77. role = DynamicModelChoiceField(
  78. queryset=SecretRole.objects.all()
  79. )
  80. tags = TagField(
  81. required=False
  82. )
  83. class Meta:
  84. model = Secret
  85. fields = [
  86. 'device', 'role', 'name', 'plaintext', 'plaintext2', 'tags',
  87. ]
  88. def __init__(self, *args, **kwargs):
  89. super().__init__(*args, **kwargs)
  90. # A plaintext value is required when creating a new Secret
  91. if not self.instance.pk:
  92. self.fields['plaintext'].required = True
  93. def clean(self):
  94. # Verify that the provided plaintext values match
  95. if self.cleaned_data['plaintext'] != self.cleaned_data['plaintext2']:
  96. raise forms.ValidationError({
  97. 'plaintext2': "The two given plaintext values do not match. Please check your input."
  98. })
  99. # Validate uniqueness
  100. if Secret.objects.filter(
  101. device=self.cleaned_data['device'],
  102. role=self.cleaned_data['role'],
  103. name=self.cleaned_data['name']
  104. ).exclude(pk=self.instance.pk).exists():
  105. raise forms.ValidationError(
  106. "Each secret assigned to a device must have a unique combination of role and name"
  107. )
  108. class SecretCSVForm(CustomFieldModelCSVForm):
  109. device = CSVModelChoiceField(
  110. queryset=Device.objects.all(),
  111. to_field_name='name',
  112. help_text='Assigned device'
  113. )
  114. role = CSVModelChoiceField(
  115. queryset=SecretRole.objects.all(),
  116. to_field_name='name',
  117. help_text='Assigned role'
  118. )
  119. plaintext = forms.CharField(
  120. help_text='Plaintext secret data'
  121. )
  122. class Meta:
  123. model = Secret
  124. fields = Secret.csv_headers
  125. help_texts = {
  126. 'name': 'Name or username',
  127. }
  128. def save(self, *args, **kwargs):
  129. s = super().save(*args, **kwargs)
  130. s.plaintext = str(self.cleaned_data['plaintext'])
  131. return s
  132. class SecretBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  133. pk = forms.ModelMultipleChoiceField(
  134. queryset=Secret.objects.all(),
  135. widget=forms.MultipleHiddenInput()
  136. )
  137. role = DynamicModelChoiceField(
  138. queryset=SecretRole.objects.all(),
  139. required=False
  140. )
  141. name = forms.CharField(
  142. max_length=100,
  143. required=False
  144. )
  145. class Meta:
  146. nullable_fields = [
  147. 'name',
  148. ]
  149. class SecretFilterForm(BootstrapMixin, CustomFieldFilterForm):
  150. model = Secret
  151. q = forms.CharField(
  152. required=False,
  153. label='Search'
  154. )
  155. role = DynamicModelMultipleChoiceField(
  156. queryset=SecretRole.objects.all(),
  157. to_field_name='slug',
  158. required=False,
  159. widget=APISelectMultiple(
  160. value_field="slug",
  161. )
  162. )
  163. tag = TagFilterField(model)
  164. #
  165. # UserKeys
  166. #
  167. class UserKeyForm(BootstrapMixin, forms.ModelForm):
  168. class Meta:
  169. model = UserKey
  170. fields = ['public_key']
  171. help_texts = {
  172. 'public_key': "Enter your public RSA key. Keep the private one with you; you'll need it for decryption. "
  173. "Please note that passphrase-protected keys are not supported.",
  174. }
  175. labels = {
  176. 'public_key': ''
  177. }
  178. def clean_public_key(self):
  179. key = self.cleaned_data['public_key']
  180. # Validate the RSA key format.
  181. validate_rsa_key(key, is_secret=False)
  182. return key
  183. class ActivateUserKeyForm(forms.Form):
  184. _selected_action = forms.ModelMultipleChoiceField(
  185. queryset=UserKey.objects.all(),
  186. label='User Keys'
  187. )
  188. secret_key = forms.CharField(
  189. widget=forms.Textarea(
  190. attrs={
  191. 'class': 'vLargeTextField',
  192. }
  193. ),
  194. label='Your private key'
  195. )