forms.py 6.2 KB

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