├── .flake8 ├── .github └── workflows │ └── python-publish.yml ├── .gitignore ├── LICENSE.txt ├── Makefile ├── README.md ├── assets ├── device_add.png ├── device_edit.png ├── device_list.png └── login.png ├── netbox_otp_plugin ├── __init__.py ├── forms.py ├── management │ └── commands │ │ ├── addtotp.py │ │ └── resettotp.py ├── middleware.py ├── migrations │ └── __init__.py ├── models.py ├── navigation.py ├── tables.py ├── templates │ ├── otp_device.html │ └── otp_login.html ├── templatetags │ ├── __init__.py │ └── otp_login_helpers.py ├── tests │ ├── __init__.py │ ├── test_middleware.py │ └── test_views.py ├── urls.py └── views.py └── setup.py /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | extend-ignore = E501 3 | exclude = .git,__pycache__,build,dist,venv 4 | max-complexity = 10 5 | -------------------------------------------------------------------------------- /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will upload a Python Package using Twine when a release is created 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries 3 | 4 | # This workflow uses actions that are not certified by GitHub. 5 | # They are provided by a third-party and are governed by 6 | # separate terms of service, privacy policy, and support 7 | # documentation. 8 | 9 | name: Upload Python Package 10 | 11 | on: 12 | release: 13 | types: [published] 14 | workflow_dispatch: 15 | 16 | permissions: 17 | contents: read 18 | 19 | jobs: 20 | deploy: 21 | 22 | runs-on: ubuntu-latest 23 | 24 | steps: 25 | - uses: actions/checkout@v4 26 | - name: Set up Python 27 | uses: actions/setup-python@v3 28 | with: 29 | python-version: '3.x' 30 | - name: Install dependencies 31 | run: | 32 | python -m pip install --upgrade pip 33 | pip install build 34 | - name: Build package 35 | run: python -m build 36 | - name: Publish package 37 | uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 38 | with: 39 | user: __token__ 40 | password: ${{ secrets.PYPI_API_TOKEN }} 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.swp 3 | .vscode 4 | *.egg-info 5 | /build 6 | /dist -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | clean: 2 | rm -rf build 3 | rm -rf dist 4 | 5 | wheel: 6 | python3 -m build -w 7 | 8 | build: clean wheel 9 | 10 | upload: 11 | twine upload --skip-existing dist/* -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Netbox OTP Plugin 2 | 3 | Two-factor authentication for [NetBox](https://github.com/netbox-community/netbox). The plugin provides user OTP token verification and OTP device management is provided and bases on [django-otp](https://github.com/django-otp/django-otp) with Time-based One-time Password algorithm. 4 | 5 | ![alt text](assets/login.png "Login page") 6 | 7 | ## Compatibility 8 | 9 | | NetBox Version| Plugin Version| 10 | |---------------|---------------| 11 | | 4.2 | >= 1.3.2 | 12 | | 4.1 | >= 1.3.0 | 13 | | 4.0 | >= 1.1.0 | 14 | | 3.X | 1.0.7 | 15 | 16 | 17 | ## Installation 18 | 19 | The plugin is available as a [Python package](https://pypi.org/project/netbox-otp-plugin/) in pypi and can be installed with pip 20 | ``` 21 | source /opt/netbox/venv/bin/activate 22 | python -m pip install netbox-otp-plugin 23 | # or 24 | # python -m pip install netbox-otp-plugin== 25 | ``` 26 | 27 | Enable the plugin in /opt/netbox/netbox/netbox/configuration.py: 28 | ``` 29 | PLUGINS = ['netbox_otp_plugin'] 30 | ``` 31 | 32 | Run migration: 33 | ``` 34 | ./manage.py migrate netbox_otp_plugin 35 | ``` 36 | 37 | To ensure the plugin is automatically re-installed during future upgrades, create a file named `local_requirements.txt` (if not already existing) in the NetBox root directory (alongside `requirements.txt`) and append the `netbox-otp-plugin` package: 38 | 39 | ```no-highlight 40 | echo netbox-otp-plugin >> local_requirements.txt 41 | ``` 42 | 43 | ## Configuration 44 | 45 | An OTP device can be attached to a user on your NetBox site or using the command: 46 | ``` 47 | ./manage.py addtotp 48 | ``` 49 | Then you will see a QR code that you can add to an TOTP authenticator. 50 | 51 | To reset user OTP device use the site or the command: 52 | ``` 53 | ./manage.py resettotp 54 | ``` 55 | 56 | The plugin has additional options: 57 | * `otp_required` - if set to True then two-factor authentication will be always required even if a user doesn't have an OTP device yet. False value required to authenticate users only with an OTP device attached only. Default: `True`. 58 | * `issuer` - the issuer parameter for the otpauth URL (see more https://github.com/google/google-authenticator/wiki/Key-Uri-Format). Default: `'Netbox'`. 59 | 60 | ### Example 61 | 62 | ``` 63 | PLUGINS_CONFIG = { 64 | 'netbox_otp_plugin': { 65 | 'otp_required': False, 66 | 'issuer': 'MyOrgNetbox' 67 | } 68 | } 69 | ``` 70 | 71 | ## OTP Self-registration 72 | 73 | To allow users to register their devices themselves, you need to grant them the following permissions: 74 | 75 | | Objects | Actions | Constraints | 76 | |---------------------------|-----------|-------------------| 77 | | Otp_Totp > TOTP Device | view, add | {"user": "$user"} | 78 | | Users > User | view | {"pk": "$user"} | 79 | 80 | Note: `otp_required` the plugin options should be set to `False`. 81 | 82 | ## Screenshots 83 | 84 | ![alt text](assets/device_list.png "Device list") 85 | 86 | ![alt text](assets/device_add.png "Add a device") 87 | 88 | ![alt text](assets/device_edit.png "Edit a device") -------------------------------------------------------------------------------- /assets/device_add.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/k1nky/netbox-otp-plugin/fedd18c4cc2891ada496c0b68f2887d0cc8f045c/assets/device_add.png -------------------------------------------------------------------------------- /assets/device_edit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/k1nky/netbox-otp-plugin/fedd18c4cc2891ada496c0b68f2887d0cc8f045c/assets/device_edit.png -------------------------------------------------------------------------------- /assets/device_list.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/k1nky/netbox-otp-plugin/fedd18c4cc2891ada496c0b68f2887d0cc8f045c/assets/device_list.png -------------------------------------------------------------------------------- /assets/login.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/k1nky/netbox-otp-plugin/fedd18c4cc2891ada496c0b68f2887d0cc8f045c/assets/login.png -------------------------------------------------------------------------------- /netbox_otp_plugin/__init__.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | from django.core.exceptions import ImproperlyConfigured 3 | 4 | from netbox.plugins import PluginConfig 5 | import netbox.settings as netbox_settings 6 | 7 | if importlib.util.find_spec('django_otp') is None: 8 | raise ImproperlyConfigured( 9 | "netbox_otp_plugin is enabled but django_otp is not present. It can be " 10 | "installed by running 'pip install django_otp qrcode'." 11 | ) 12 | 13 | 14 | class OTPPluginConfig(PluginConfig): 15 | name = 'netbox_otp_plugin' 16 | verbose_name = 'OTP Login' 17 | description = 'OTP Login plugin' 18 | version = '1.3.2' 19 | author = 'Andrey Shalashov' 20 | author_email = 'avshalashov@yandex.ru' 21 | min_version = '4.0.0' 22 | max_version = '4.2.99' 23 | django_apps = [ 24 | 'django_otp', 25 | 'django_otp.plugins.otp_totp', 26 | 'qr_code' 27 | ] 28 | base_url = 'otp' 29 | required_settings = [] 30 | default_settings = { 31 | 'otp_required': True, 32 | 'issuer': 'Netbox' 33 | } 34 | middleware = [ 35 | 'django_otp.middleware.OTPMiddleware', 36 | 'netbox_otp_plugin.middleware.RedirectToOTPMiddleware' 37 | ] 38 | 39 | @classmethod 40 | def validate(cls, user_config, netbox_version): 41 | super().validate(user_config, netbox_version) 42 | # django_otp provides OTP_TOTP_ISSUER. Set it here to avoid 43 | # making any changes in the original settings.py 44 | setattr(netbox_settings, 'OTP_TOTP_ISSUER', user_config.get('issuer')) 45 | 46 | parsed_netbox_version = tuple(map(int, netbox_version.split('.'))) 47 | # the AUTH_EXEMPT_PATHS setting has been removed since NetBox v4.1.0 48 | if parsed_netbox_version < (4, 1, 0): 49 | # the plugin login URL must be exempt from authentication 50 | auth_exempt_paths = netbox_settings.AUTH_EXEMPT_PATHS + (f'/{netbox_settings.BASE_PATH}plugins/otp',) 51 | setattr(netbox_settings, 'AUTH_EXEMPT_PATHS', auth_exempt_paths) 52 | 53 | 54 | config = OTPPluginConfig 55 | -------------------------------------------------------------------------------- /netbox_otp_plugin/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | from django.contrib.auth.forms import AuthenticationForm 3 | from django.utils.translation import gettext_lazy as _ 4 | from django_otp.forms import OTPAuthenticationFormMixin 5 | from django_otp import user_has_device 6 | 7 | from netbox.forms import NetBoxModelForm 8 | from netbox.plugins import get_plugin_config 9 | from users.models import User 10 | from utilities.forms.fields import DynamicModelChoiceField 11 | 12 | from .models import Device 13 | 14 | 15 | class OTPAuthenticationForm(OTPAuthenticationFormMixin, AuthenticationForm): 16 | otp_device = forms.CharField( 17 | required=False, 18 | widget=forms.Select 19 | ) 20 | otp_token = forms.CharField( 21 | required=False, 22 | widget=forms.TextInput( 23 | attrs={ 24 | 'autocomplete': 'off', 25 | 'class': 'rounded' 26 | } 27 | ), 28 | label="OTP Token" 29 | ) 30 | otp_challenge = forms.CharField( 31 | required=False 32 | ) 33 | 34 | def clean(self): 35 | self.cleaned_data = super().clean() 36 | user = self.get_user() 37 | otp_required = get_plugin_config('netbox_otp_plugin', 'otp_required') 38 | if user_has_device(user) or otp_required: 39 | self.clean_otp(self.get_user()) 40 | 41 | return self.cleaned_data 42 | 43 | 44 | class OTPLoginForm(OTPAuthenticationForm): 45 | pass 46 | 47 | 48 | class DeviceForm(NetBoxModelForm): 49 | user = DynamicModelChoiceField( 50 | label=_('User'), 51 | queryset=User.objects.all(), 52 | required=True 53 | ) 54 | 55 | class Meta: 56 | model = Device 57 | fields = ( 58 | 'name', 59 | 'digits', 60 | 'user', 61 | ) 62 | -------------------------------------------------------------------------------- /netbox_otp_plugin/management/commands/addtotp.py: -------------------------------------------------------------------------------- 1 | from django.core.management.base import BaseCommand, CommandError 2 | 3 | from users.models import User 4 | 5 | try: 6 | from netbox_otp_plugin.models import Device as TOTPDevice 7 | import qrcode 8 | except ModuleNotFoundError: 9 | raise CommandError('django_otp or qrcode module does not exist') 10 | 11 | 12 | class Command(BaseCommand): 13 | 14 | help = 'Add a TOTP device for specified user' 15 | 16 | def add_arguments(self, parser): 17 | parser.add_argument('user', type=str) 18 | 19 | def handle(self, *args, **options): 20 | username = options['user'] 21 | try: 22 | user = User.objects.get(username=username) 23 | except User.DoesNotExist: 24 | raise CommandError(f"User {username} does not exist") 25 | device = TOTPDevice.objects.create(user=user, name=f'{username}-otp') 26 | qr = qrcode.QRCode() 27 | qr.add_data(device.config_url) 28 | qr.print_ascii() 29 | self.stdout.write(self.style.SUCCESS(f'Created: {str(device)} with key {device.base32_key}')) 30 | -------------------------------------------------------------------------------- /netbox_otp_plugin/management/commands/resettotp.py: -------------------------------------------------------------------------------- 1 | from django.core.management.base import BaseCommand, CommandError 2 | 3 | from users.models import User 4 | 5 | try: 6 | from netbox_otp_plugin.models import Device as TOTPDevice 7 | from django_otp import user_has_device 8 | except ModuleNotFoundError: 9 | raise CommandError('django_otp module does not exist') 10 | 11 | 12 | class Command(BaseCommand): 13 | 14 | help = 'Reset a TOTP device for specified user' 15 | 16 | def add_arguments(self, parser): 17 | parser.add_argument('user', type=str) 18 | 19 | def handle(self, *args, **options): 20 | username = options['user'] 21 | try: 22 | user = User.objects.get(username=username) 23 | except User.DoesNotExist: 24 | raise CommandError(f"User {username} does not exist") 25 | if user_has_device(user): 26 | device = TOTPDevice.objects.filter(user_id=user.id) 27 | device.delete() 28 | -------------------------------------------------------------------------------- /netbox_otp_plugin/middleware.py: -------------------------------------------------------------------------------- 1 | from django.http import HttpResponseRedirect 2 | from django.urls import reverse 3 | 4 | 5 | class RedirectToOTPMiddleware: 6 | def __init__(self, get_response): 7 | self.get_response = get_response 8 | 9 | def __call__(self, request): 10 | if request.path.startswith('/login'): 11 | return HttpResponseRedirect(reverse('plugins:netbox_otp_plugin:login')) 12 | 13 | return self.get_response(request) 14 | -------------------------------------------------------------------------------- /netbox_otp_plugin/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/k1nky/netbox-otp-plugin/fedd18c4cc2891ada496c0b68f2887d0cc8f045c/netbox_otp_plugin/migrations/__init__.py -------------------------------------------------------------------------------- /netbox_otp_plugin/models.py: -------------------------------------------------------------------------------- 1 | from base64 import b32encode 2 | from django_otp.plugins.otp_totp.models import TOTPDevice 3 | from django_otp.models import DeviceManager 4 | from utilities.querysets import RestrictedQuerySet 5 | from django.urls import reverse 6 | 7 | 8 | class DeviceQuerySet(RestrictedQuerySet, DeviceManager): 9 | pass 10 | 11 | 12 | class Device(TOTPDevice): 13 | 14 | class Meta: 15 | proxy = True 16 | objects = DeviceQuerySet.as_manager() 17 | 18 | def get_absolute_url(self): 19 | return reverse('plugins:netbox_otp_plugin:device', args=[self.pk]) 20 | 21 | @property 22 | def base32_key(self): 23 | return b32encode(self.bin_key).decode() 24 | -------------------------------------------------------------------------------- /netbox_otp_plugin/navigation.py: -------------------------------------------------------------------------------- 1 | from netbox.plugins import ( 2 | PluginMenu, PluginMenuButton, PluginMenuItem 3 | ) 4 | from netbox.choices import ButtonColorChoices 5 | 6 | devices_menu_item = PluginMenuItem( 7 | link='plugins:netbox_otp_plugin:device_list', 8 | link_text='Devices', 9 | buttons=( 10 | PluginMenuButton( 11 | link='plugins:netbox_otp_plugin:device_add', 12 | title='Add', 13 | icon_class='mdi mdi-plus-thick', 14 | color=ButtonColorChoices.DEFAULT, 15 | ), 16 | ) 17 | ) 18 | 19 | menu = PluginMenu( 20 | label='TOTP Plugin', 21 | groups=( 22 | ('Devices', (devices_menu_item,)), 23 | ), 24 | icon_class='mdi mdi-router' 25 | ) 26 | -------------------------------------------------------------------------------- /netbox_otp_plugin/tables.py: -------------------------------------------------------------------------------- 1 | import django_tables2 as tables 2 | from netbox.tables import NetBoxTable, columns 3 | from netbox_otp_plugin.models import Device 4 | 5 | 6 | class TOTPDeviceTable(NetBoxTable): 7 | user = tables.Column( 8 | verbose_name='User', 9 | linkify=True, 10 | ) 11 | name = tables.Column( 12 | verbose_name='Name', 13 | linkify=True 14 | ) 15 | 16 | actions = columns.ActionsColumn( 17 | actions=('edit', 'delete',) 18 | ) 19 | 20 | class Meta(NetBoxTable.Meta): 21 | model = Device 22 | fields = ( 23 | 'pk', 24 | 'id', 25 | 'name', 26 | 'user', 27 | 'digits', 28 | 'created_at', 29 | 'last_used_at', 30 | 'actions' 31 | ) 32 | default_columns = ( 33 | 'pk', 34 | 'name', 35 | 'user', 36 | 'actions', 37 | 'last_used_at', 38 | 'default_action' 39 | ) 40 | -------------------------------------------------------------------------------- /netbox_otp_plugin/templates/otp_device.html: -------------------------------------------------------------------------------- 1 | {% extends 'generic/object.html' %} 2 | {% load helpers %} 3 | {% load plugins %} 4 | {% load tz %} 5 | {% load i18n %} 6 | {% load mptt %} 7 | {% load qr_code %} 8 | 9 | {% block content %} 10 |
11 |
12 |
13 |
{% trans "Device" %}
14 | 15 | 16 | 17 | 20 | 21 | 22 | 23 | 26 | 27 | 28 | 29 | 32 | 33 |
{% trans "Name" %} 18 | {{ object.name }} 19 |
{% trans "User" %} 24 | {{ object.user|linkify|placeholder }} 25 |
{% trans "Key" %} 30 | {{ object.base32_key }}{% copy_content "otp_key" %} 31 |
34 |
35 | {% plugin_left_page object %} 36 |
37 |
38 |
39 |
40 | {% trans "QR Code" %} 41 |
42 |
43 | {% qr_from_text object.config_url size="T" %} 44 |
45 |
46 |
47 |
48 | {% endblock %} 49 | -------------------------------------------------------------------------------- /netbox_otp_plugin/templates/otp_login.html: -------------------------------------------------------------------------------- 1 | {# User login page. Extends base.html directly to override normal UI layout. #} 2 | {% extends 'base/base.html' %} 3 | {% load form_helpers %} 4 | {% load static %} 5 | {% load i18n %} 6 | {% load otp_login_helpers %} 7 | 8 | {% block layout %} 9 | 10 |
11 |
12 | 13 | {# NetBox logo #} 14 |
15 | {% if settings.VERSION|is_version_greater:'4.1.0' %} 16 | 17 | 18 | {% else %} 19 | {# for compatibility with NetBox 4.0 #} 20 | {% trans 21 | {% endif %} 22 |
23 | 24 | {# Login banner #} 25 | {% if config.BANNER_LOGIN %} 26 |
27 | {{ config.BANNER_LOGIN|safe }} 28 |
29 | {% endif %} 30 | 31 | {# Login form errors #} 32 | {% if form.non_field_errors %} 33 | 39 | {% endif %} 40 | 41 |
42 |
43 |

{% trans "Log In" %}

44 | 45 | {# Login form #} 46 |
47 | {% csrf_token %} 48 | 49 | {# Set post-login URL #} 50 | {% if 'next' in request.GET %} 51 | 52 | {% elif 'next' in request.POST %} 53 | 54 | {% endif %} 55 | 56 |
57 | 58 | {{ form.username }} 59 | {% for error in form.username.errors %} 60 |
{{ error }}
61 | {% endfor %} 62 |
63 | 64 |
65 | 66 | {{ form.password }} 67 | {% for error in form.password.errors %} 68 |
{{ error }}
69 | {% endfor %} 70 |
71 | 72 |
73 | 74 | {{ form.otp_token }} 75 | {% for error in form.otp_token.errors %} 76 |
{{ error }}
77 | {% endfor %} 78 |
79 | 80 | 85 |
86 |
87 | 88 | {# SSO login #} 89 | {% if auth_backends %} 90 |
{% trans "Or" context "Denotes an alternative option" %}
91 |
92 |
93 | {% for backend in auth_backends %} 94 | 100 | {% endfor %} 101 |
102 |
103 | {% endif %} 104 | 105 |
106 | 107 |
108 |
109 | 110 | {% endblock layout %} 111 | -------------------------------------------------------------------------------- /netbox_otp_plugin/templatetags/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/k1nky/netbox-otp-plugin/fedd18c4cc2891ada496c0b68f2887d0cc8f045c/netbox_otp_plugin/templatetags/__init__.py -------------------------------------------------------------------------------- /netbox_otp_plugin/templatetags/otp_login_helpers.py: -------------------------------------------------------------------------------- 1 | from django import template 2 | 3 | register = template.Library() 4 | 5 | 6 | @register.filter() 7 | def is_version_greater(value, target): 8 | """ Returns true if `value` is greater than or equal to `target`. 9 | """ 10 | version = lambda s: list(map(int, s.split('.'))) # noqa: E731 11 | return version(value) >= version(target) 12 | -------------------------------------------------------------------------------- /netbox_otp_plugin/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/k1nky/netbox-otp-plugin/fedd18c4cc2891ada496c0b68f2887d0cc8f045c/netbox_otp_plugin/tests/__init__.py -------------------------------------------------------------------------------- /netbox_otp_plugin/tests/test_middleware.py: -------------------------------------------------------------------------------- 1 | from utilities.testing.base import TestCase 2 | 3 | from django.urls import reverse 4 | from rest_framework import status 5 | 6 | 7 | class TestRedirectToOTPMiddleware(TestCase): 8 | 9 | def test_login(self): 10 | url = reverse('login') 11 | redirect_to = reverse('plugins:netbox_otp_plugin:login') 12 | response = self.client.get(url) 13 | self.assertEqual(response.status_code, status.HTTP_302_FOUND) 14 | self.assertEqual(response.url, redirect_to) 15 | 16 | def test_not_login(self): 17 | url = reverse('home') 18 | response = self.client.get(url) 19 | self.assertEqual(response.status_code, status.HTTP_200_OK) 20 | -------------------------------------------------------------------------------- /netbox_otp_plugin/tests/test_views.py: -------------------------------------------------------------------------------- 1 | from utilities.testing import ViewTestCases 2 | from netbox_otp_plugin.models import Device 3 | from users.models import User 4 | 5 | 6 | class DeviceTestCase(ViewTestCases.ListObjectsViewTestCase, 7 | ViewTestCases.GetObjectViewTestCase, 8 | ViewTestCases.DeleteObjectViewTestCase, 9 | ViewTestCases.CreateObjectViewTestCase): 10 | 11 | model = Device 12 | 13 | def _get_base_url(self): 14 | """ 15 | Return the base format for a URL for the test's model. Override this to test for a model which belongs 16 | to a different app (e.g. testing Interfaces within the virtualization app). 17 | """ 18 | return '{}:{}:{}_{{}}'.format('plugins', self.model._meta.app_label, self.model._meta.model_name) 19 | 20 | @classmethod 21 | def setUpTestData(cls): 22 | users = ( 23 | User(username='user_a'), 24 | User(username='user_b'), 25 | User(username='user_c') 26 | ) 27 | User.objects.bulk_create(users) 28 | devices = ( 29 | Device(name='device-1', user=users[0]), 30 | Device(name='device-2', user=users[1]) 31 | ) 32 | Device.objects.bulk_create(devices) 33 | 34 | cls.form_data = { 35 | 'name': 'device-3', 36 | 'user': users[0].pk, 37 | 'digits': 6, 38 | } 39 | 40 | def test_export_objects(self): 41 | pass 42 | -------------------------------------------------------------------------------- /netbox_otp_plugin/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | from . import views 4 | 5 | app_name = 'otp' 6 | urlpatterns = [ 7 | path('devices/', views.DeviceListView.as_view(), name='device_list'), 8 | path('devices/add/', views.DeviceEditView.as_view(), name='device_add'), 9 | path('devices//', views.DeviceView.as_view(), name='device'), 10 | path('devices/edit//', views.DeviceEditView.as_view(), name='device_edit'), 11 | path('devices/delete//', views.DeviceDeleteView.as_view(), name='device_delete'), 12 | path('', views.OTPLoginView.as_view(), name='login') 13 | ] 14 | -------------------------------------------------------------------------------- /netbox_otp_plugin/views.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from django.contrib.auth.views import LoginView 4 | from django.contrib.auth import login as auth_login 5 | from django.utils.http import url_has_allowed_host_and_scheme, urlencode 6 | from django.urls import reverse 7 | from django.conf import settings 8 | from social_core.backends.utils import load_backends 9 | from django.shortcuts import render 10 | from django.contrib.auth.models import update_last_login 11 | from django.contrib.auth.signals import user_logged_in 12 | from django.contrib import messages 13 | from django.http import HttpResponseRedirect 14 | 15 | from netbox.authentication import get_auth_backend_display, get_saml_idps 16 | from netbox.config import get_config 17 | from users.models import UserConfig 18 | from netbox.views import generic 19 | 20 | from . import tables 21 | from . import models 22 | from . import forms 23 | 24 | 25 | class OTPLoginView(LoginView): 26 | template_name = 'otp_login.html' 27 | authentication_form = forms.OTPLoginForm 28 | 29 | def gen_auth_data(self, name, url, params): 30 | display_name, icon_name = get_auth_backend_display(name) 31 | return { 32 | 'display_name': display_name, 33 | 'icon_name': icon_name, 34 | 'url': f'{url}?{urlencode(params)}', 35 | } 36 | 37 | def get_auth_backends(self, request): 38 | auth_backends = [] 39 | saml_idps = get_saml_idps() 40 | 41 | for name in load_backends(settings.AUTHENTICATION_BACKENDS).keys(): 42 | url = reverse('social:begin', args=[name]) 43 | params = {} 44 | if next := request.GET.get('next'): 45 | params['next'] = next 46 | if name.lower() == 'saml' and saml_idps: 47 | for idp in saml_idps: 48 | params['idp'] = idp 49 | data = self.gen_auth_data(name, url, params) 50 | data['display_name'] = f'{data["display_name"]} ({idp})' 51 | auth_backends.append(data) 52 | else: 53 | auth_backends.append(self.gen_auth_data(name, url, params)) 54 | 55 | return auth_backends 56 | 57 | def get(self, request): 58 | form = self.authentication_form(request) 59 | 60 | if request.user.is_authenticated: 61 | logger = logging.getLogger('netbox.auth.login') 62 | return self.redirect_to_next(request, logger) 63 | 64 | return render(request, self.template_name, { 65 | 'form': form, 66 | 'auth_backends': self.get_auth_backends(request), 67 | }) 68 | 69 | def post(self, request): 70 | logger = logging.getLogger('netbox.auth.login') 71 | form = self.authentication_form(request, data=request.POST) 72 | 73 | if form.is_valid(): 74 | logger.debug("Login form validation was successful") 75 | 76 | # If maintenance mode is enabled, assume the database is read-only, and disable updating the user's 77 | # last_login time upon authentication. 78 | if get_config().MAINTENANCE_MODE: 79 | logger.warning("Maintenance mode enabled: disabling update of most recent login time") 80 | user_logged_in.disconnect(update_last_login, dispatch_uid='update_last_login') 81 | 82 | # Authenticate user 83 | auth_login(request, form.get_user()) 84 | logger.info(f"User {request.user} successfully authenticated") 85 | messages.info(request, f"Logged in as {request.user}.") 86 | 87 | # Ensure the user has a UserConfig defined. (This should normally be handled by 88 | # create_userconfig() on user creation.) 89 | if not hasattr(request.user, 'config'): 90 | config = get_config() 91 | UserConfig(user=request.user, data=config.DEFAULT_USER_PREFERENCES).save() 92 | 93 | return self.redirect_to_next(request, logger) 94 | 95 | else: 96 | logger.debug(f"Login form validation failed for username: {form['username'].value()}") 97 | 98 | return render(request, self.template_name, { 99 | 'form': form, 100 | 'auth_backends': self.get_auth_backends(request), 101 | }) 102 | 103 | def redirect_to_next(self, request, logger): 104 | data = request.POST if request.method == "POST" else request.GET 105 | redirect_url = data.get('next', settings.LOGIN_REDIRECT_URL) 106 | 107 | if redirect_url and url_has_allowed_host_and_scheme(redirect_url, allowed_hosts=None): 108 | logger.debug(f"Redirecting user to {redirect_url}") 109 | else: 110 | if redirect_url: 111 | logger.warning(f"Ignoring unsafe 'next' URL passed to login form: {redirect_url}") 112 | redirect_url = reverse('home') 113 | 114 | return HttpResponseRedirect(redirect_url) 115 | 116 | 117 | class DeviceView(generic.ObjectView): 118 | queryset = models.Device.objects.all() 119 | template_name = 'otp_device.html' 120 | 121 | 122 | class DeviceEditView(generic.ObjectEditView): 123 | queryset = models.Device.objects.all() 124 | form = forms.DeviceForm 125 | 126 | 127 | class DeviceDeleteView(generic.ObjectDeleteView): 128 | queryset = models.Device.objects.all() 129 | 130 | 131 | class DeviceListView(generic.ObjectListView): 132 | queryset = models.Device.objects 133 | table = tables.TOTPDeviceTable 134 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_packages, setup 2 | 3 | setup( 4 | name='netbox_otp_plugin', 5 | version='1.3.2', 6 | description='OTP Login NetBox plugin', 7 | url='https://github.com/k1nky/netbox-otp-plugin', 8 | author='Andrey Shalashov', 9 | author_email='avshalashov@yandex.ru', 10 | long_description_content_type='text/markdown', 11 | license='Apache 2.0', 12 | keywords='netbox otp login plugin', 13 | install_requires=[ 14 | 'qrcode', 15 | 'django-otp', 16 | 'django-qr-code', 17 | ], 18 | packages=find_packages(exclude=["*tests.*", "*tests"]), 19 | package_data={ 20 | "netbox_otp_plugin": [ 21 | "templates/*", 22 | "management/commands/*" 23 | ] 24 | }, 25 | include_package_data=True, 26 | zip_safe=False, 27 | ) 28 | --------------------------------------------------------------------------------