stop-abuse.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from django.core.management import BaseCommand
  2. from django.db.models import Q
  3. from api import settings
  4. from desecapi.models import RRset, Domain, User
  5. from desecapi.pdns_change_tracker import PDNSChangeTracker
  6. class Command(BaseCommand):
  7. help = (
  8. "Removes all DNS records from domains given either by name or by email address of their owner. "
  9. "Locks all implicated user accounts."
  10. )
  11. def add_arguments(self, parser):
  12. parser.add_argument(
  13. "names",
  14. nargs="*",
  15. help="Domain(s) and User(s) to truncate and disable identified by name and email addresses",
  16. )
  17. def handle(self, *args, **options):
  18. with PDNSChangeTracker():
  19. # domains to truncate: all domains given and all domains belonging to a user given
  20. domains = Domain.objects.filter(
  21. Q(name__in=options["names"]) | Q(owner__email__in=options["names"])
  22. )
  23. domain_names = domains.distinct().values_list("name", flat=True)
  24. # users to lock: all associated with any of the domains and all given
  25. users = User.objects.filter(
  26. Q(domains__name__in=options["names"]) | Q(email__in=options["names"])
  27. )
  28. user_emails = users.distinct().values_list("email", flat=True)
  29. # rrsets to delete: all belonging to (all domains given and all domains belonging to a user given)
  30. rrsets = RRset.objects.filter(
  31. Q(domain__name__in=options["names"])
  32. | Q(domain__owner__email__in=options["names"])
  33. )
  34. # Print summary
  35. print(
  36. f"Deleting {rrsets.distinct().count()} RRset(s) from {domains.distinct().count()} domain(s); "
  37. f"disabling {users.distinct().count()} associated user account(s)."
  38. )
  39. # Print details
  40. for d in domain_names:
  41. print(f"Truncating domain {d}")
  42. for e in user_emails:
  43. print(f"Locking user {e}")
  44. # delete rrsets and create default NS records
  45. rrsets.delete()
  46. for d in domains:
  47. RRset.objects.create(
  48. domain=d,
  49. subname="",
  50. type="NS",
  51. ttl=3600,
  52. contents=settings.DEFAULT_NS,
  53. )
  54. # lock users
  55. users.update(is_active=False)