2020-04-07 17:45:16 +00:00
|
|
|
import base64
|
|
|
|
|
2020-04-03 17:27:49 +00:00
|
|
|
from django.contrib.auth import get_user_model
|
2020-04-07 17:45:16 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2020-04-03 17:27:49 +00:00
|
|
|
from rest_framework import serializers
|
|
|
|
|
|
|
|
from .models import *
|
2020-12-13 12:28:43 +00:00
|
|
|
from .services import *
|
2020-12-20 20:45:47 +00:00
|
|
|
from .selectors import *
|
|
|
|
|
2020-12-13 12:28:43 +00:00
|
|
|
|
|
|
|
class WireGuardVPNSerializer(serializers.ModelSerializer):
|
2020-12-13 16:59:35 +00:00
|
|
|
address = serializers.CharField(read_only=True)
|
2020-12-13 17:05:48 +00:00
|
|
|
vpn_server = serializers.CharField(read_only=True)
|
|
|
|
vpn_server_public_key = serializers.CharField(read_only=True)
|
2020-12-13 16:59:35 +00:00
|
|
|
network_mask = serializers.IntegerField()
|
|
|
|
|
2020-12-13 12:28:43 +00:00
|
|
|
class Meta:
|
|
|
|
model = WireGuardVPN
|
2020-12-13 17:05:48 +00:00
|
|
|
fields = [ 'wireguard_public_key', 'address', 'network_mask', 'vpn_server',
|
|
|
|
'vpn_server_public_key' ]
|
2020-12-13 12:28:43 +00:00
|
|
|
|
2020-12-13 16:59:35 +00:00
|
|
|
extra_kwargs = {
|
|
|
|
'network_mask': {'write_only': True }
|
|
|
|
}
|
2020-04-12 20:55:22 +00:00
|
|
|
|
|
|
|
|
2020-12-20 20:45:47 +00:00
|
|
|
def validate_network_mask(self, value):
|
|
|
|
msg = _(f"No pool for network size {value}")
|
|
|
|
sizes = allowed_vpn_network_reservation_size()
|
|
|
|
|
|
|
|
if not value in sizes:
|
|
|
|
raise serializers.ValidationError(msg)
|
|
|
|
|
2020-12-20 21:03:43 +00:00
|
|
|
return value
|
2020-12-20 20:45:47 +00:00
|
|
|
|
2020-12-20 18:37:12 +00:00
|
|
|
def validate_wireguard_public_key(self, value):
|
|
|
|
msg = _("Supplied key is not a valid wireguard public key")
|
2020-04-07 17:45:16 +00:00
|
|
|
|
2020-12-20 18:37:12 +00:00
|
|
|
"""
|
2020-12-25 09:08:34 +00:00
|
|
|
Verify wireguard key.
|
|
|
|
See https://lists.zx2c4.com/pipermail/wireguard/2020-December/006221.html
|
2020-12-20 18:37:12 +00:00
|
|
|
"""
|
2020-04-07 17:45:16 +00:00
|
|
|
|
2020-12-20 18:37:12 +00:00
|
|
|
try:
|
2020-12-25 09:08:34 +00:00
|
|
|
decoded_key = base64.standard_b64decode(value)
|
2020-12-20 18:37:12 +00:00
|
|
|
except Exception as e:
|
|
|
|
raise serializers.ValidationError(msg)
|
2020-04-07 17:45:16 +00:00
|
|
|
|
2020-12-25 09:08:34 +00:00
|
|
|
if not len(decoded_key) == 32:
|
2020-12-20 18:37:12 +00:00
|
|
|
raise serializers.ValidationError(msg)
|
2020-04-07 17:45:16 +00:00
|
|
|
|
2020-12-20 18:37:12 +00:00
|
|
|
return value
|
2020-12-20 20:45:47 +00:00
|
|
|
|
|
|
|
|
|
|
|
class WireGuardVPNSizesSerializer(serializers.Serializer):
|
|
|
|
size = serializers.IntegerField(min_value=0, max_value=128)
|