stop-abuse.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 = 'Removes all DNS records from domains given either by name or by email address of their owner. ' \
  8. 'Locks all implicated user accounts.'
  9. def add_arguments(self, parser):
  10. parser.add_argument('names', nargs='*',
  11. help='Domain(s) and User(s) to truncate and disable identified by name and email addresses')
  12. def handle(self, *args, **options):
  13. with PDNSChangeTracker():
  14. # domains to truncate: all domains given and all domains belonging to a user given
  15. domains = Domain.objects.filter(
  16. Q(name__in=options['names']) |
  17. Q(owner__email__in=options['names'])
  18. )
  19. domain_names = domains.distinct().values_list('name', flat=True)
  20. # users to lock: all associated with any of the domains and all given
  21. users = User.objects.filter(
  22. Q(domains__name__in=options['names']) |
  23. Q(email__in=options['names'])
  24. )
  25. user_emails = users.distinct().values_list('email', flat=True)
  26. # rrsets to delete: all belonging to (all domains given and all domains belonging to a user given)
  27. rrsets = RRset.objects.filter(
  28. Q(domain__name__in=options['names']) |
  29. Q(domain__owner__email__in=options['names'])
  30. )
  31. # Print summary
  32. print(f'Deleting {rrsets.distinct().count()} RRset(s) from {domains.distinct().count()} domain(s); '
  33. f'disabling {users.distinct().count()} associated user account(s).')
  34. # Print details
  35. for d in domain_names:
  36. print(f'Truncating domain {d}')
  37. for e in user_emails:
  38. print(f'Locking user {e}')
  39. # delete rrsets and create default NS records
  40. rrsets.delete()
  41. for d in domains:
  42. RRset.objects.create(domain=d, subname='', type='NS', ttl=3600, contents=settings.DEFAULT_NS)
  43. # lock users
  44. users.update(is_active=False)