#!/usr/bin/python
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------------- #
#    Isida-NG Jabber Bot (fork of iSida)                                      #
#    Isida-NG Copyright (C) 2026 Luciferus <luciferus@ubunix.pro>             #
#    Project home: https://git.ubunix.pro/Luciferus/Isida-NG                  #
#                                                                             #
#    DNSrecon int plugin                                                      #
#                                                                             #
#    This program is free software: you can redistribute it and/or modify     #
#    it under the terms of the GNU General Public License as published by     #
#    the Free Software Foundation, either version 3 of the License, or        #
#    (at your option) any later version.                                      #
#                                                                             #
#    This program is distributed in the hope that it will be useful,          #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of           #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
#    GNU General Public License for more details.                             #
#                                                                             #
#    You should have received a copy of the GNU General Public License        #
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.    #
#                                                                             #
# --------------------------------------------------------------------------- #

import dns.resolver
import dns.exception
import re

# --------------------------------------------------------------------------- #
# ПРОТОКОЛЫ                                                                   #

PROTOCOLS = {
    'xmpp': ['_xmpp-client._tcp.%s', '_xmpp-server._tcp.%s', '_xmpps-client._tcp.%s', '_xmpps-server._tcp.%s'],
    'sip': ['_sip._tcp.%s', '_sips._tcp.%s', '_sip._udp.%s'],
    'call': ['_turn._tcp.%s', '_turns._tcp.%s', '_stun._tcp.%s', '_stuns._tcp.%s', '_turn._udp.%s', '_stun._udp.%s'],
    'mail': ['_imap._tcp.%s', '_imaps._tcp.%s', '_pop._tcp.%s', '_pops._tcp.%s', '_pop3s._tcp.%s',
             '_smtp._tcp.%s', '_smtps._tcp.%s', '_submission._tcp.%s', '_caldavs._tcp.%s',
             '_carddavs._tcp.%s', '_autodiscover._tcp.%s'],
}

ALL_TARGETS = []
for p in PROTOCOLS.values():
    ALL_TARGETS.extend(p)

# --------------------------------------------------------------------------- #
# ПАРСИНГ ФИЛЬТРОВ                                                            #

def parse_filters(filter_str):
    """Парсит строку фильтра с поддержкой запятых"""
    if filter_str.lower() == 'all':
        return ALL_TARGETS

    targets = []
    for part in filter_str.lower().split(','):
        part = part.strip()
        if part in PROTOCOLS:
            targets.extend(PROTOCOLS[part])
        else:
            # Если фильтр не найден — возвращаем None
            return None, part
    return targets, None

# --------------------------------------------------------------------------- #
# КОМАНДА                                                                     #

def dnsrecon_cmd(type, jid, nick, text):
    text = text.strip()

    if not text:
        send_msg(type, jid, nick, 'Usage: dnsrecon <filter> <domain>\nFilters: xmpp, sip, call, mail, all (supports comma: xmpp,call)\nExample: dnsrecon xmpp,call domain.tld')
        return

    parts = text.split()
    if len(parts) < 2:
        send_msg(type, jid, nick, 'Usage: dnsrecon <filter> <domain>\nExample: dnsrecon xmpp,call domain.tld')
        return

    filter_str = parts[0].lower()
    domain = parts[1].strip().lower()

    # Парсим фильтры
    targets, unknown = parse_filters(filter_str)
    if unknown:
        send_msg(type, jid, nick, 'Unknown filter: %s\nAvailable: xmpp, sip, call, mail, all (comma-separated)' % unknown)
        return

    # Настройка резолвера
    resolver = dns.resolver.Resolver()
    resolver.nameservers = ['8.8.8.8', '1.1.1.1']
    resolver.timeout = 30
    resolver.lifetime = 30

    found = []

    for template in targets:
        target = template % domain
        try:
            answers = resolver.resolve(target, 'SRV')
            for ans in answers:
                found.append({
                    'srv': target,
                    'priority': ans.priority,
                    'weight': ans.weight,
                    'port': ans.port,
                    'host': str(ans.target).rstrip('.'),
                })
        except:
            pass

    if not found:
        send_msg(type, jid, nick, 'No SRV records found for %s (filter: %s)' % (domain, filter_str))
        return

    # Легенда
    legend = 'SRV-запись | Приоритет | Вес | Порт | Домен'

    # Формируем ответ
    msg = 'Found SRV records for %s (filter: %s):\n' % (domain, filter_str)
    msg += legend + '\n'
    msg += '-' * len(legend) + '\n'

    for r in found:
        msg += '%s | %s | %s | %s | %s\n' % (
            r['srv'],
            r['priority'],
            r['weight'],
            r['port'],
            r['host']
        )

    send_msg(type, jid, nick, msg.strip())

# --------------------------------------------------------------------------- #
# РЕГИСТРАЦИЯ                                                                 #

global execute

execute = [
    (6, 'dnsrecon', dnsrecon_cmd, 2, 'DNS SRV reconnaissance.\ndnsrecon <filter> <domain>\nFilters: xmpp, sip, call, mail, all (supports comma)\nExample: dnsrecon xmpp,call domain.tld'),
]
