Esempio n. 1
0
    def _create(self,
                domain: str,
                create_keys: List[str] = None,
                dkim_selector: str = "",
                redirect_to: str = "",
                jwt_allow_subdomain_signing: str = "false",
                **kwargs: Any) -> None:
        try:
            domobj = Domain.objects.get(name__iexact=domain)
        except Domain.DoesNotExist:
            pass
        else:
            sys.stderr.write("Error: Domain %s already exists\n" % domain)
            sys.exit(1)

        domobj = Domain.objects.create(
            name=domain,
            dkimselector=dkim_selector,
            redirect_to=redirect_to,
            jwt_subdomains=jwt_allow_subdomain_signing)
        if create_keys is None:
            create_keys = []

        if "jwt" in create_keys:
            domobj.jwtkey = generate_rsa_key(2048).private_key
        if "dkim" in create_keys:
            domobj.dkimkey = generate_rsa_key(2048).private_key
        domobj.save()

        sys.stderr.write("Domain %s created\n" % domain)
Esempio n. 2
0
    def response_change(self, request: HttpRequest,
                        obj: Domain) -> HttpResponse:
        opts = self.model._meta
        pk_value = obj._get_pk_val()
        preserved_filters = self.get_preserved_filters(request)

        msg_dict = {
            'name':
            force_text(opts.verbose_name),
            'obj':
            format_html('<a href="{}">{}</a>',
                        urllib.parse.quote(request.path), obj),
        }
        for key in request.POST.keys():
            if key.startswith("_genkey-"):
                if hasattr(obj, key[len("_genkey-"):]):
                    setattr(obj, key[len("_genkey-"):],
                            generate_rsa_key(2048).private_key)
                    obj.save()
                    msg = format_html(
                        _('The {name} "{obj}" was changed successfully. You may edit it again below.'
                          ), **msg_dict)
                    self.message_user(request, msg, messages.SUCCESS)
                    redirect_url = request.path
                    redirect_url = add_preserved_filters(
                        {
                            'preserved_filters': preserved_filters,
                            'opts': opts
                        }, redirect_url)
                    return HttpResponseRedirect(redirect_url)

        return super().response_change(request, obj)
Esempio n. 3
0
    def _pubkey(self,
                domain: str,
                output: str,
                key: str = "jwt",
                create_key: bool = False,
                format: str = "pem",
                **kwargs: Any) -> None:
        attr = None
        if key == "dkim":
            attr = "dkimkey"
            try:
                domobj = Domain.objects.get(name=domain)
            except Domain.DoesNotExist:
                sys.stderr.write("Error: Domain %s does not exist\n" % domain)
                sys.exit(1)
        else:
            attr = "jwtkey"
            try:
                domobj = Domain.objects.find_parent_domain(domain)
            except Domain.DoesNotExist:
                sys.stderr.write(
                    "Error: Domain does not exist and no parent domain exists with signing rights "
                    "for %s\n" % domain)
                sys.exit(1)

        if not attr:
            sys.stderr.write("Unknown key type: %s\n" % key)
            sys.exit(1)

        if getattr(domobj, attr, "") == "":
            if create_key:
                privkey = generate_rsa_key()
                setattr(domobj, attr, privkey.private_key)
                domobj.save()
            else:
                sys.stderr.write(
                    "Error: Domain %s has no private key of type %s and --create-key is not set\n"
                    % (domain, key))
                sys.exit(1)
        else:
            privkey = import_rsa_key(getattr(domobj, attr))

        public_key = privkey.public_key
        with stdout_or_file(output) as f:
            if format == "pem":
                print(public_key, file=cast(IO[str], f))
            elif format == "dkimdns":
                outstr = "\"v=DKIM1\\; k=rsa\\; p=\" {split_key}".format(
                    split_key="\n".join([
                        '"%s"' % line for line in cast(
                            Match[str],
                            re.search("--\n(.*?)\n--", public_key,
                                      re.DOTALL)).group(1).split("\n")
                    ])
                )  # the cast tells mypy that re.search will not return None here
                print(outstr, file=cast(IO[str], f))

        if output != "-":
            sys.stderr.write("Public key exported to %s\n" % output)
Esempio n. 4
0
    def response_add(self, request: HttpRequest, obj: Domain, post_url_continue: str=None) -> \
            HttpResponse:
        opts = self.opts
        preserved_filters = self.get_preserved_filters(request)

        msg_dict = {
            'name':
            force_text(opts.verbose_name),
            'obj':
            format_html('<a href="{}">{}</a>',
                        urllib.parse.quote(request.path), obj),
        }
        obj_url = reverse(
            'admin:%s_%s_change' % (self.opts.app_label, self.opts.model_name),
            args=(urllib.parse.quote(str(obj.pk)), ),
            current_app=self.admin_site.name,
        )

        for key in request.POST.keys():
            if key.startswith("_genkey-"):
                if hasattr(obj, key[len("_genkey-"):]):
                    setattr(obj, key[len("_genkey-"):],
                            generate_rsa_key(2048).private_key)
                    obj.save()
                    msg = format_html(
                        _('The {name} "{obj}" was changed successfully. You may edit it again below.'
                          ), **msg_dict)
                    self.message_user(request, msg, messages.SUCCESS)
                    if post_url_continue is None:
                        post_url_continue = obj_url
                    post_url_continue = add_preserved_filters(
                        {
                            'preserved_filters': preserved_filters,
                            'opts': opts
                        }, post_url_continue)
                    return HttpResponseRedirect(post_url_continue)
        return super().response_add(request, obj, post_url_continue)
Esempio n. 5
0
    def _edit(self,
              domain: str,
              create_keys: List[str] = None,
              remove_keys: List[str] = None,
              dkim_selector: str = "",
              redirect_to: str = "",
              overwrite: bool = False,
              jwt_allow_subdomain_signing: bool = False,
              **kwargs: Any) -> None:
        try:
            domobj = Domain.objects.get(name__iexact=domain)
        except Domain.DoesNotExist:
            sys.stderr.write("Error: Domain %s does not exist\n" % domain)
            sys.exit(1)

        if create_keys is None:
            create_keys = []

        if remove_keys is None:
            remove_keys = []

        if create_keys and remove_keys:
            sys.stderr.write(
                "As it is impossible to discern your intentions, please don't use --create-key and "
                "--remove-key in the same command, instead split it in two commands in the right order.\n"
            )
            sys.exit(1)

        if "jwt" in create_keys:
            if (domobj.jwtkey and overwrite) or not domobj.jwtkey:
                if domobj.jwtkey and overwrite:
                    sys.stderr.write("Overwriting JWT key for domain %s" %
                                     domain)
                elif not domobj.jwtkey:
                    sys.stderr.write("Generating JWT key for domain %s" %
                                     domain)
                domobj.jwtkey = generate_rsa_key(2048).private_key
            else:
                sys.stderr.write(
                    "JWT key for domain %s already exists and --overwrite not specified\n"
                    % domain)
        if "dkim" in create_keys:
            if (domobj.dkimkey and overwrite) or not domobj.dkimkey:
                if domobj.dkimkey and overwrite:
                    sys.stderr.write("Overwriting DKIM key for domain %s\n" %
                                     domain)
                elif not domobj.dkimkey:
                    sys.stderr.write("Generating DKIM key for domain %s\n" %
                                     domain)
                domobj.dkimkey = generate_rsa_key(2048).private_key
            else:
                sys.stderr.write(
                    "DKIM key for domain %s already exists and --overwrite not specified\n"
                    % domain)

        if "jwt" in remove_keys:
            domobj.jwtkey = None
        if "dkim" in remove_keys:
            domobj.dkimkey = None

        if dkim_selector:
            domobj.dkimselector = dkim_selector

        if redirect_to:
            domobj.redirect_to = redirect_to

        if jwt_allow_subdomain_signing:
            domobj.jwt_subdomains = jwt_allow_subdomain_signing == "true"

        domobj.save()
        sys.stderr.write("Domain %s edited\n" % domain)