Skip to content
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions base_requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,7 @@ svgwrite
# Tabular dataset library (for table-based exports)
# https://github.com/jazzband/tablib
tablib

# It changes comma separated widget to list based in admin panel
# https://github.com/gradam/django-better-admin-arrayfield
django_better_admin_arrayfield
10 changes: 10 additions & 0 deletions docs/release-notes/version-3.1.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# NetBox v3.1

## v3.1.10 (FUTURE)

### Enhancements

* [#8233](https://github.com/netbox-community/netbox/issues/8233) - Restrict API key usage by source IP

### Bug Fixes

---

## v3.1.9 (2022-03-07)

### Enhancements
Expand Down
19 changes: 19 additions & 0 deletions netbox/netbox/api/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ class TokenAuthentication(authentication.TokenAuthentication):
A custom authentication scheme which enforces Token expiration times.
"""
model = Token
__request = False

def authenticate(self, request):
self.request = request
return super().authenticate(request)

def authenticate_credentials(self, key):
model = self.get_model()
Expand All @@ -18,6 +23,20 @@ def authenticate_credentials(self, key):
except model.DoesNotExist:
raise exceptions.AuthenticationFailed("Invalid token")

# Verify source IP is allowed
request = self.request
if len(token.allowed_ips) > 0 and request:
### Replace 'HTTP_X_REAL_IP' with the settings variable choosen in #8867
if 'HTTP_X_REAL_IP' in request.META:
clientip = request.META['HTTP_X_REAL_IP'].split(",")[0].strip()
elif 'REMOTE_ADDR' in request.META:
clientip = request.META['REMOTE_ADDR']
else:
raise exceptions.AuthenticationFailed(f"The request headers (HTTP_X_REAL_IP, REMOTE_ADDR) are missing or do not contain a valid source IP.")

if not token.validate_client_ip(clientip):
raise exceptions.AuthenticationFailed(f"Source IP {clientip} is not allowed to use this token.")

# Enforce the Token's expiration time, if one has been set.
if token.is_expired:
raise exceptions.AuthenticationFailed("Token expired")
Expand Down
1 change: 1 addition & 0 deletions netbox/netbox/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,7 @@ def _setting(name, default=None):
'wireless',
'django_rq', # Must come after extras to allow overriding management commands
'drf_yasg',
'django_better_admin_arrayfield',
]

# Middleware
Expand Down
8 changes: 8 additions & 0 deletions netbox/templates/users/api_tokens.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@
<span>Never</span>
{% endif %}
</div>
<div class="col col-md-4">
<small class="text-muted">Allowed Source IPs</small><br />
{% if token.allowed_ips %}
{{ token.allowed_ips }}
{% else %}
<span>Any</span>
{% endif %}
</div>
<div class="col col-md-4">
<small class="text-muted">Create/Edit/Delete Operations</small><br />
{% if token.write_enabled %}
Expand Down
5 changes: 3 additions & 2 deletions netbox/users/admin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from users.models import ObjectPermission, Token
from . import filters, forms, inlines

from django_better_admin_arrayfield.admin.mixins import DynamicArrayMixin

#
# Users & groups
Expand Down Expand Up @@ -55,10 +56,10 @@ def get_inlines(self, request, obj):
#

@admin.register(Token)
class TokenAdmin(admin.ModelAdmin):
class TokenAdmin(admin.ModelAdmin, DynamicArrayMixin):
form = forms.TokenAdminForm
list_display = [
'key', 'user', 'created', 'expires', 'write_enabled', 'description'
'key', 'user', 'created', 'expires', 'write_enabled', 'description', 'allowed_ips'
]


Expand Down
2 changes: 1 addition & 1 deletion netbox/users/admin/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class TokenAdminForm(forms.ModelForm):

class Meta:
fields = [
'user', 'key', 'write_enabled', 'expires', 'description'
'user', 'key', 'write_enabled', 'expires', 'description', 'allowed_ips'
]
model = Token

Expand Down
2 changes: 1 addition & 1 deletion netbox/users/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class TokenSerializer(ValidatedModelSerializer):

class Meta:
model = Token
fields = ('id', 'url', 'display', 'user', 'created', 'expires', 'key', 'write_enabled', 'description')
fields = ('id', 'url', 'display', 'user', 'created', 'expires', 'key', 'write_enabled', 'description', 'allowed_ips')

def to_internal_value(self, data):
if 'key' not in data:
Expand Down
2 changes: 1 addition & 1 deletion netbox/users/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class TokenForm(BootstrapMixin, forms.ModelForm):
class Meta:
model = Token
fields = [
'key', 'write_enabled', 'expires', 'description',
'key', 'write_enabled', 'expires', 'description', 'allowed_ips',
]
widgets = {
'expires': DateTimePicker(),
Expand Down
20 changes: 20 additions & 0 deletions netbox/users/migrations/0002_token_allowed_ips.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by Django 3.2.12 on 2022-03-14 16:58

from django.db import migrations
import django_better_admin_arrayfield.models.fields
import ipam.fields


class Migration(migrations.Migration):

dependencies = [
('users', '0001_squashed_0011'),
]

operations = [
migrations.AddField(
model_name='token',
name='allowed_ips',
field=django_better_admin_arrayfield.models.fields.ArrayField(base_field=ipam.fields.IPNetworkField(), blank=True, null=True, size=None),
),
]
30 changes: 30 additions & 0 deletions netbox/users/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from django.contrib.auth.models import Group, User
from django.contrib.contenttypes.models import ContentType
from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import ValidationError
from django.core.validators import MinLengthValidator
from django.db import models
from django.db.models.signals import post_save
Expand All @@ -15,6 +16,10 @@
from utilities.utils import flatten_dict
from .constants import *

from ipam.fields import IPNetworkField
from django_better_admin_arrayfield.models.fields import ArrayField as betterArrayField
import ipaddress


__all__ = (
'ObjectPermission',
Expand Down Expand Up @@ -203,6 +208,12 @@ class Token(BigIDModel):
max_length=200,
blank=True
)
allowed_ips = betterArrayField(
base_field = IPNetworkField(),
blank = True,
null = True,
help_text = 'Allowed IPv4/IPv6 networks from where the token can be used. Leave blank for no restrictions. Ex: "10.1.1.0/24, 192.168.10.16/32, 2001:DB8:1::/64"',
)

class Meta:
pass
Expand All @@ -214,6 +225,7 @@ def __str__(self):
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()

return super().save(*args, **kwargs)

@staticmethod
Expand All @@ -227,6 +239,24 @@ def is_expired(self):
return False
return True

def validate_client_ip(self, raw_ip_address):
"""
Checks that an ip address falls within the allowed ips.
"""
if not self.allowed_ips:
return True

try:
ip_address = ipaddress.ip_address(raw_ip_address)
except ValueError:
raise ValidationError(f"{raw_ip_address} is an invalid IP address")

for ipnet in self.allowed_ips:
if ip_address in ipaddress.ip_network(ipnet):
return True

return False


#
# Permissions
Expand Down