Beispiel #1
0
    def fetch_pending(self, deleted):
        if (not deleted):
            objs = OpenVPNTenant.get_tenant_objects().filter(
                Q(enacted__lt=F('updated')) | Q(enacted=None),
                Q(lazy_blocked=False))
        else:
            objs = OpenVPNTenant.get_deleted_tenant_objects()

        return objs
    def fetch_pending(self, deleted):
        if (not deleted):
            objs = OpenVPNTenant.get_tenant_objects().filter(
                Q(enacted__lt=F('updated')) |
                Q(enacted=None), Q(lazy_blocked=False))
        else:
            objs = OpenVPNTenant.get_deleted_tenant_objects()

        return objs
Beispiel #3
0
    def sync_fields(self, o, fields):
        pki_dir = OpenVPNService.get_pki_dir(o)

        if (not os.path.isdir(pki_dir)):
            OpenVPNService.execute_easyrsa_command(pki_dir, "init-pki")
            OpenVPNService.execute_easyrsa_command(
                pki_dir, "--req-cn=XOS build-ca nopass")

        # Very hacky way to handle VPNs that need to share CAs
        if (o.use_ca_from_id):
            tenant = OpenVPNTenant.get_tenant_objects().filter(
                pk=o.use_ca_from_id)[0]
            other_pki_dir = OpenVPNService.get_pki_dir(tenant)
            shutil.copy2(other_pki_dir + "/ca.crt", pki_dir)
            shutil.copy2(other_pki_dir + "/private/ca.key",
                         pki_dir + "/private")

        # If the server has to be built then we need to build it
        if (not os.path.isfile(pki_dir + "/issued/server.crt")):
            OpenVPNService.execute_easyrsa_command(
                pki_dir, "build-server-full server nopass")
            OpenVPNService.execute_easyrsa_command(pki_dir, "gen-dh")

        # Get the most recent list of revoked clients
        OpenVPNService.execute_easyrsa_command(pki_dir, "gen-crl")

        # Super runs the playbook
        super(SyncOpenVPNTenant, self).sync_fields(o, fields)
Beispiel #4
0
    def get_script_text(self, obj):
        """Gets the text of the client script for the requesting user.

        Parameters:
            obj (services.openvpn.models.OpenVPNTenant): The OpenVPNTenant to connect to.

        Returns:
            str: The client script as a str.
        """
        env = jinja2.Environment(loader=jinja2.FileSystemLoader(
            "/opt/xos/services/openvpn/templates"))
        template = env.get_template("connect.vpn.j2")
        client_name = self.context['request'].user.email + "-" + str(obj.id)
        remote_ids = list(obj.failover_server_ids)
        remote_ids.insert(0, obj.id)
        remotes = OpenVPNTenant.get_tenant_objects().filter(pk__in=remote_ids)
        pki_dir = OpenVPNService.get_pki_dir(obj)
        fields = {
            "client_name": client_name,
            "remotes": remotes,
            "is_persistent": obj.is_persistent,
            "ca_crt": obj.get_ca_crt(pki_dir),
            "client_crt": obj.get_client_cert(client_name, pki_dir),
            "client_key": obj.get_client_key(client_name, pki_dir)
        }
        return template.render(fields)
Beispiel #5
0
    def get_script_text(self, obj):
        """Gets the text of the client script for the requesting user.

        Parameters:
            obj (services.openvpn.models.OpenVPNTenant): The OpenVPNTenant to connect to.

        Returns:
            str: The client script as a str.
        """
        env = jinja2.Environment(
            loader=jinja2.FileSystemLoader("/opt/xos/services/openvpn/templates"))
        template = env.get_template("connect.vpn.j2")
        client_name = self.context['request'].user.email + "-" + str(obj.id)
        remote_ids = list(obj.failover_server_ids)
        remote_ids.insert(0, obj.id)
        remotes = OpenVPNTenant.get_tenant_objects().filter(pk__in=remote_ids)
        pki_dir = OpenVPNService.get_pki_dir(obj)
        fields = {"client_name": client_name,
                  "remotes": remotes,
                  "is_persistent": obj.is_persistent,
                  "ca_crt": obj.get_ca_crt(pki_dir),
                  "client_crt": obj.get_client_cert(client_name, pki_dir),
                  "client_key": obj.get_client_key(client_name, pki_dir)
                  }
        return template.render(fields)
    def sync_fields(self, o, fields):
        pki_dir = OpenVPNService.get_pki_dir(o)

        if (not os.path.isdir(pki_dir)):
            OpenVPNService.execute_easyrsa_command(pki_dir, "init-pki")
            OpenVPNService.execute_easyrsa_command(
                pki_dir, "--req-cn=XOS build-ca nopass")

        # Very hacky way to handle VPNs that need to share CAs
        if (o.use_ca_from_id):
            tenant = OpenVPNTenant.get_tenant_objects().filter(
                pk=o.use_ca_from_id)[0]
            other_pki_dir = OpenVPNService.get_pki_dir(tenant)
            shutil.copy2(other_pki_dir + "/ca.crt", pki_dir)
            shutil.copy2(other_pki_dir + "/private/ca.key",
                         pki_dir + "/private")

        # If the server has to be built then we need to build it
        if (not os.path.isfile(pki_dir + "/issued/server.crt")):
            OpenVPNService.execute_easyrsa_command(
                pki_dir, "build-server-full server nopass")
            OpenVPNService.execute_easyrsa_command(pki_dir, "gen-dh")

        # Get the most recent list of revoked clients
        OpenVPNService.execute_easyrsa_command(pki_dir, "gen-crl")

        # Super runs the playbook
        super(SyncOpenVPNTenant, self).sync_fields(o, fields)
Beispiel #7
0
 def get_queryset(self):
     # Get every privilege for this user
     tenants_privs = TenantPrivilege.objects.all().filter(
         user=self.request.user)
     vpn_tenants = []
     for priv in tenants_privs:
         vpn_tenants.append(OpenVPNTenant.get_tenant_objects().filter(
             pk=priv.tenant.pk)[0])
     return vpn_tenants
Beispiel #8
0
 def get_queryset(self):
     # Get every privilege for this user
     tenants_privs = TenantPrivilege.objects.all().filter(
         user=self.request.user)
     vpn_tenants = []
     for priv in tenants_privs:
         vpn_tenants.append(
             OpenVPNTenant.get_tenant_objects().filter(pk=priv.tenant.pk)[0])
     return vpn_tenants
Beispiel #9
0
    def __init__(self, *args, **kwargs):
        super(OpenVPNTenantForm, self).__init__(*args, **kwargs)
        self.fields['kind'].widget.attrs['readonly'] = True
        self.fields['failover_servers'].widget.attrs['rows'] = 300
        self.fields['provider_service'].queryset = (
            OpenVPNService.get_service_objects().all())

        self.fields['kind'].initial = OPENVPN_KIND

        if self.instance:
            self.fields['creator'].initial = self.instance.creator
            self.fields['vpn_subnet'].initial = self.instance.vpn_subnet
            self.fields[
                'server_network'].initial = self.instance.server_network
            self.fields['clients_can_see_each_other'].initial = (
                self.instance.clients_can_see_each_other)
            self.fields['is_persistent'].initial = self.instance.is_persistent
            self.initial['protocol'] = self.instance.protocol
            self.fields['failover_servers'].queryset = (
                OpenVPNTenant.get_tenant_objects().exclude(
                    pk=self.instance.pk))
            self.initial[
                'failover_servers'] = OpenVPNTenant.get_tenant_objects(
                ).filter(pk__in=self.instance.failover_server_ids)
            self.fields['use_ca_from'].queryset = (
                OpenVPNTenant.get_tenant_objects().exclude(
                    pk=self.instance.pk))
            if (self.instance.use_ca_from_id):
                self.initial['use_ca_from'] = (
                    OpenVPNTenant.get_tenant_objects().filter(
                        pk=self.instance.use_ca_from_id)[0])

        if (not self.instance) or (not self.instance.pk):
            self.fields['creator'].initial = get_request().user
            self.fields['vpn_subnet'].initial = "255.255.255.0"
            self.fields['server_network'].initial = "10.66.77.0"
            self.fields['clients_can_see_each_other'].initial = True
            self.fields['is_persistent'].initial = True
            self.fields['failover_servers'].queryset = (
                OpenVPNTenant.get_tenant_objects())
            if OpenVPNService.get_service_objects().exists():
                self.fields["provider_service"].initial = (
                    OpenVPNService.get_service_objects().all()[0])
Beispiel #10
0
    def __init__(self, *args, **kwargs):
        super(OpenVPNTenantForm, self).__init__(*args, **kwargs)
        self.fields['kind'].widget.attrs['readonly'] = True
        self.fields['failover_servers'].widget.attrs['rows'] = 300
        self.fields[
            'provider_service'].queryset = (
                OpenVPNService.get_service_objects().all())

        self.fields['kind'].initial = OPENVPN_KIND

        if self.instance:
            self.fields['creator'].initial = self.instance.creator
            self.fields['vpn_subnet'].initial = self.instance.vpn_subnet
            self.fields[
                'server_network'].initial = self.instance.server_network
            self.fields[
                'clients_can_see_each_other'].initial = (
                    self.instance.clients_can_see_each_other)
            self.fields['is_persistent'].initial = self.instance.is_persistent
            self.initial['protocol'] = self.instance.protocol
            self.fields['failover_servers'].queryset = (
                OpenVPNTenant.get_tenant_objects().exclude(pk=self.instance.pk))
            self.initial['failover_servers'] = OpenVPNTenant.get_tenant_objects().filter(
                pk__in=self.instance.failover_server_ids)
            self.fields['use_ca_from'].queryset = (
                OpenVPNTenant.get_tenant_objects().exclude(pk=self.instance.pk))
            if (self.instance.use_ca_from_id):
                self.initial['use_ca_from'] = (
                    OpenVPNTenant.get_tenant_objects().filter(pk=self.instance.use_ca_from_id)[0])

        if (not self.instance) or (not self.instance.pk):
            self.fields['creator'].initial = get_request().user
            self.fields['vpn_subnet'].initial = "255.255.255.0"
            self.fields['server_network'].initial = "10.66.77.0"
            self.fields['clients_can_see_each_other'].initial = True
            self.fields['is_persistent'].initial = True
            self.fields['failover_servers'].queryset = (
                OpenVPNTenant.get_tenant_objects())
            if OpenVPNService.get_service_objects().exists():
                self.fields["provider_service"].initial = (
                    OpenVPNService.get_service_objects().all()[0])
 def sync_record(self, record):
     if (not record.tenant.id):
         raise DeferredException("Privilege waiting on VPN Tenant ID")
     certificate = self.get_certificate_name(record)
     tenant = OpenVPNTenant.get_tenant_objects().filter(pk=record.tenant.id)[0]
     if (not tenant):
         raise DeferredException("Privilege waiting on VPN Tenant")
     # Only add a certificate if ones does not yet exist
     pki_dir = OpenVPNService.get_pki_dir(tenant)
     if (not os.path.isfile(pki_dir + "/issued/" + certificate + ".crt")):
         OpenVPNService.execute_easyrsa_command(
             pki_dir, "build-client-full " + certificate + " nopass")
         tenant.save()
     record.save()
 def sync_record(self, record):
     if (not record.tenant.id):
         raise DeferredException("Privilege waiting on VPN Tenant ID")
     certificate = self.get_certificate_name(record)
     tenant = OpenVPNTenant.get_tenant_objects().filter(
         pk=record.tenant.id)[0]
     if (not tenant):
         raise DeferredException("Privilege waiting on VPN Tenant")
     # Only add a certificate if ones does not yet exist
     pki_dir = OpenVPNService.get_pki_dir(tenant)
     if (not os.path.isfile(pki_dir + "/issued/" + certificate + ".crt")):
         OpenVPNService.execute_easyrsa_command(
             pki_dir, "build-client-full " + certificate + " nopass")
         tenant.save()
     record.save()
    def delete_record(self, record):
        if (not record.tenant.id):
            return
        certificate = self.get_certificate_name(record)
        tenant = OpenVPNTenant.get_tenant_objects().filter(pk=record.tenant.id)[0]
        if (not tenant):
            return
        # If the client has already been reovked don't do it again
        pki_dir = OpenVPNService.get_pki_dir(tenant)
        if (os.path.isfile(pki_dir + "/issued/" + certificate + ".crt")):
            OpenVPNService.execute_easyrsa_command(
                pki_dir, "revoke " + certificate)
            # Revoking a client cert does not delete any of the files
            # to make sure that we can add this user again we need to
            # delete all of the files created by easyrsa
            os.remove(pki_dir + "/issued/" + certificate + ".crt")
            os.remove(pki_dir + "/private/" + certificate + ".key")
            os.remove(pki_dir + "/reqs/" + certificate + ".req")
            tenant.save()

        record.delete()
    def delete_record(self, record):
        if (not record.tenant.id):
            return
        certificate = self.get_certificate_name(record)
        tenant = OpenVPNTenant.get_tenant_objects().filter(
            pk=record.tenant.id)[0]
        if (not tenant):
            return
        # If the client has already been reovked don't do it again
        pki_dir = OpenVPNService.get_pki_dir(tenant)
        if (os.path.isfile(pki_dir + "/issued/" + certificate + ".crt")):
            OpenVPNService.execute_easyrsa_command(pki_dir,
                                                   "revoke " + certificate)
            # Revoking a client cert does not delete any of the files
            # to make sure that we can add this user again we need to
            # delete all of the files created by easyrsa
            os.remove(pki_dir + "/issued/" + certificate + ".crt")
            os.remove(pki_dir + "/private/" + certificate + ".key")
            os.remove(pki_dir + "/reqs/" + certificate + ".req")
            tenant.save()

        record.delete()
Beispiel #15
0
 def queryset(self, request):
     return OpenVPNTenant.get_tenant_objects_by_user(request.user)
Beispiel #16
0
class OpenVPNTenantForm(forms.ModelForm):
    """The form used to create and edit a OpenVPNTenant.

    Attributes:
        creator (forms.ModelChoiceField): The XOS user that created this
            tenant.
        server_network (forms.GenericIPAddressField): The IP address of the VPN network.
        vpn_subnet (forms.GenericIPAddressField): The subnet used by the VPN network.
        is_persistent (forms.BooleanField): Determines if this Tenant keeps
            this connection alive through failures.
        clients_can_see_each_other (forms.BooleanField): Determines if the clients on the VPN can
            communicate with each other.
        failover_servers (forms.ModelMultipleChoiceField): The other OpenVPNTenants to use as failover
            servers.
        protocol (forms.ChoiceField): The protocol to use.
        use_ca_from (forms.ModelChoiceField): Another OpenVPNTenant to use the CA of, this is a very
            hacky way to let VPNs have the same clients.
    """
    creator = forms.ModelChoiceField(queryset=User.objects.all())
    server_network = forms.GenericIPAddressField(protocol="IPv4",
                                                 required=True)
    vpn_subnet = forms.GenericIPAddressField(protocol="IPv4", required=True)
    is_persistent = forms.BooleanField(required=False)
    clients_can_see_each_other = forms.BooleanField(required=False)
    failover_servers = forms.ModelMultipleChoiceField(
        required=False, queryset=OpenVPNTenant.get_tenant_objects())
    protocol = forms.ChoiceField(required=True,
                                 choices=[("tcp", "tcp"), ("udp", "udp")])
    use_ca_from = forms.ModelChoiceField(
        queryset=OpenVPNTenant.get_tenant_objects(), required=False)

    def __init__(self, *args, **kwargs):
        super(OpenVPNTenantForm, self).__init__(*args, **kwargs)
        self.fields['kind'].widget.attrs['readonly'] = True
        self.fields['failover_servers'].widget.attrs['rows'] = 300
        self.fields['provider_service'].queryset = (
            OpenVPNService.get_service_objects().all())

        self.fields['kind'].initial = OPENVPN_KIND

        if self.instance:
            self.fields['creator'].initial = self.instance.creator
            self.fields['vpn_subnet'].initial = self.instance.vpn_subnet
            self.fields[
                'server_network'].initial = self.instance.server_network
            self.fields['clients_can_see_each_other'].initial = (
                self.instance.clients_can_see_each_other)
            self.fields['is_persistent'].initial = self.instance.is_persistent
            self.initial['protocol'] = self.instance.protocol
            self.fields['failover_servers'].queryset = (
                OpenVPNTenant.get_tenant_objects().exclude(
                    pk=self.instance.pk))
            self.initial[
                'failover_servers'] = OpenVPNTenant.get_tenant_objects(
                ).filter(pk__in=self.instance.failover_server_ids)
            self.fields['use_ca_from'].queryset = (
                OpenVPNTenant.get_tenant_objects().exclude(
                    pk=self.instance.pk))
            if (self.instance.use_ca_from_id):
                self.initial['use_ca_from'] = (
                    OpenVPNTenant.get_tenant_objects().filter(
                        pk=self.instance.use_ca_from_id)[0])

        if (not self.instance) or (not self.instance.pk):
            self.fields['creator'].initial = get_request().user
            self.fields['vpn_subnet'].initial = "255.255.255.0"
            self.fields['server_network'].initial = "10.66.77.0"
            self.fields['clients_can_see_each_other'].initial = True
            self.fields['is_persistent'].initial = True
            self.fields['failover_servers'].queryset = (
                OpenVPNTenant.get_tenant_objects())
            if OpenVPNService.get_service_objects().exists():
                self.fields["provider_service"].initial = (
                    OpenVPNService.get_service_objects().all()[0])

    def save(self, commit=True):
        self.instance.creator = self.cleaned_data.get("creator")
        self.instance.is_persistent = self.cleaned_data.get('is_persistent')
        self.instance.vpn_subnet = self.cleaned_data.get("vpn_subnet")
        self.instance.server_network = self.cleaned_data.get('server_network')
        self.instance.clients_can_see_each_other = self.cleaned_data.get(
            'clients_can_see_each_other')

        self.instance.failover_server_ids = [
            tenant.id for tenant in self.cleaned_data.get('failover_servers')
        ]

        # Do not aquire a new port number if the protocol hasn't changed
        if ((not self.instance.protocol) or
            (self.instance.protocol != self.cleaned_data.get("protocol"))):
            self.instance.protocol = self.cleaned_data.get("protocol")
            self.instance.port_number = (
                self.instance.provider_service.get_next_available_port(
                    self.instance.protocol))

        if (self.cleaned_data.get('use_ca_from')):
            self.instance.use_ca_from_id = self.cleaned_data.get(
                'use_ca_from').id
        else:
            self.instance.use_ca_from_id = None

        return super(OpenVPNTenantForm, self).save(commit=commit)

    class Meta:
        model = OpenVPNTenant
Beispiel #17
0
 def queryset(self, request):
     return OpenVPNTenant.get_tenant_objects_by_user(request.user)