forms.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. from Crypto.Cipher import PKCS1_OAEP
  2. from Crypto.PublicKey import RSA
  3. from django import forms
  4. from taggit.forms import TagField
  5. from dcim.models import Device
  6. from extras.forms import (
  7. AddRemoveTagsForm, CustomFieldBulkEditForm, CustomFieldFilterForm, CustomFieldModelForm, CustomFieldModelCSVForm,
  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. class SecretCSVForm(CustomFieldModelCSVForm):
  100. device = CSVModelChoiceField(
  101. queryset=Device.objects.all(),
  102. to_field_name='name',
  103. help_text='Assigned device'
  104. )
  105. role = CSVModelChoiceField(
  106. queryset=SecretRole.objects.all(),
  107. to_field_name='name',
  108. help_text='Assigned role'
  109. )
  110. plaintext = forms.CharField(
  111. help_text='Plaintext secret data'
  112. )
  113. class Meta:
  114. model = Secret
  115. fields = Secret.csv_headers
  116. help_texts = {
  117. 'name': 'Name or username',
  118. }
  119. def save(self, *args, **kwargs):
  120. s = super().save(*args, **kwargs)
  121. s.plaintext = str(self.cleaned_data['plaintext'])
  122. return s
  123. class SecretBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEditForm):
  124. pk = forms.ModelMultipleChoiceField(
  125. queryset=Secret.objects.all(),
  126. widget=forms.MultipleHiddenInput()
  127. )
  128. role = DynamicModelChoiceField(
  129. queryset=SecretRole.objects.all(),
  130. required=False
  131. )
  132. name = forms.CharField(
  133. max_length=100,
  134. required=False
  135. )
  136. class Meta:
  137. nullable_fields = [
  138. 'name',
  139. ]
  140. class SecretFilterForm(BootstrapMixin, CustomFieldFilterForm):
  141. model = Secret
  142. q = forms.CharField(
  143. required=False,
  144. label='Search'
  145. )
  146. role = DynamicModelMultipleChoiceField(
  147. queryset=SecretRole.objects.all(),
  148. to_field_name='slug',
  149. required=False,
  150. widget=APISelectMultiple(
  151. value_field="slug",
  152. )
  153. )
  154. tag = TagFilterField(model)
  155. #
  156. # UserKeys
  157. #
  158. class UserKeyForm(BootstrapMixin, forms.ModelForm):
  159. class Meta:
  160. model = UserKey
  161. fields = ['public_key']
  162. help_texts = {
  163. 'public_key': "Enter your public RSA key. Keep the private one with you; you'll need it for decryption. "
  164. "Please note that passphrase-protected keys are not supported.",
  165. }
  166. labels = {
  167. 'public_key': ''
  168. }
  169. def clean_public_key(self):
  170. key = self.cleaned_data['public_key']
  171. # Validate the RSA key format.
  172. validate_rsa_key(key, is_secret=False)
  173. return key
  174. class ActivateUserKeyForm(forms.Form):
  175. _selected_action = forms.ModelMultipleChoiceField(
  176. queryset=UserKey.objects.all(),
  177. label='User Keys'
  178. )
  179. secret_key = forms.CharField(
  180. widget=forms.Textarea(
  181. attrs={
  182. 'class': 'vLargeTextField',
  183. }
  184. ),
  185. label='Your private key'
  186. )