Exemplo n.º 1
0
 def get_gost_remote_ip(config: t.Dict) -> str:
     if config.get("ChainNodes", []):
         first_chain_node = config["ChainNodes"][0]
         ip_or_address = (
             urlparse(first_chain_node).netloc.split("@")[-1].split(":")[0]
         )
         if not ip_or_address:
             return "127.0.0.1"
         elif is_ip(ip_or_address):
             return ip_or_address
         else:
             return dns_query(ip_or_address)
     elif config.get("ServeNodes", []):
         tcp_nodes = list(
             filter(lambda r: r.startswith("tcp"), config["ServeNodes"])
         )
         if tcp_nodes:
             parsed = urlparse(tcp_nodes[0])
             if parsed.path:
                 ip_or_address = parsed.path[1:].split(":")[0]
                 if is_ip(ip_or_address):
                     return ip_or_address
                 else:
                     return dns_query(ip_or_address)
     return "ANYWHERE"
Exemplo n.º 2
0
def ddns_runner():
    with db_session() as db:
        rules = get_all_ddns_rules(db)
    for rule in rules:
        remote_addr = ''
        if rule.config.get("remote_address"):
            remote_addr = rule.config.get("remote_address").strip(' ')
        if (
            rule.config.get("remote_address")
            and rule.config.get("remote_ip")
            and not is_ip(remote_addr)
        ):
            updated_ip = dns_query(remote_addr)
            if updated_ip and updated_ip != rule.config["remote_ip"]:
                print(
                    f"DNS changed for address {remote_addr}, "
                    + f"{rule.config['remote_ip']}->{updated_ip}"
                )
                if rule.method == MethodEnum.IPTABLES:
                    iptables_runner(
                        rule.port.id,
                        rule.port.server.id,
                        rule.port.num,
                        remote_address=updated_ip,
                        remote_port=rule.config["remote_port"],
                        forward_type=rule.config.get("type", "ALL"),
                        update_status=True,
                    )
                else:
                    rule_runner(rule_id=rule.id)
Exemplo n.º 3
0
 def get_app_command(self, db: Session, port: Port):
     command = port.forward_rule.config.get("command")
     if port.forward_rule.config.get("remote_address"):
         if not is_ip(port.forward_rule.config.get("remote_address")):
             remote_ip = dns_query(
                 port.forward_rule.config.get("remote_address"))
         else:
             remote_ip = port.forward_rule.config.get("remote_address")
         port.forward_rule.config['remote_ip'] = remote_ip
         db.add(port.forward_rule)
         db.commit()
     if command == "relay":
         args = (
             f"-f :{port.num} "
             f"-t {remote_ip}:{port.forward_rule.config.get('remote_port')}"
         )
     elif command in ("server", "wsserver"):
         args = f"-l :{port.num} -p {port.forward_rule.config.get('password')}"
     elif command in ("client", "wsclient"):
         args = (
             f"--socks5 0.0.0.0:{port.num} "
             f"-s {remote_ip}:{port.forward_rule.config.get('remote_port')} "
             f"-p {port.forward_rule.config.get('password')}")
     else:
         args = port.forward_rule.config.get("args")
     return f"/usr/local/bin/brook {command} {args}"
Exemplo n.º 4
0
def iptables_runner(
    port_id: int,
    server_id: int,
    local_port: int,
    remote_address: str,
    remote_port: int = None,
    forward_type: str = None,
    update_status: bool = False,
):
    try:
        if not is_ip(remote_address):
            remote_ip = dns_query(remote_address)
        else:
            remote_ip = remote_address
        with db_session() as db:
            port = get_port(db, server_id, port_id)
            if not forward_type:
                args = f" delete {local_port}"
            elif remote_port:
                port.forward_rule.config["remote_ip"] = remote_ip
                db.add(port.forward_rule)
                db.commit()
                args = (
                    f" -t={forward_type}"
                    f" {'-v=6' if is_ipv6(remote_ip) else '-v=4'}"
                    f" forward {local_port} {remote_ip} {remote_port}"
                )
            else:
                args = f" list {local_port}"
            server = get_server_with_ports_usage(db, server_id)

        extravars = {
            "host": server.ansible_name,
            "local_port": local_port,
            "iptables_args": args,
        }

        run(
            server=server,
            playbook="iptables.yml",
            extravars=extravars,
            status_handler=lambda s, **k: status_handler(
                port_id, s, update_status
            ),
            finished_callback=iptables_finished_handler(
                server.id, port_id, True
            )
            if update_status
            else lambda r: None,
        )
    except Exception:
        traceback.print_exc()
        with db_session() as db:
            port = get_port(db, server_id, port_id)
            port.forward_rule.status = "failed"
            port.forward_rule.config["error"] = traceback.format_exc()
            print(port.forward_rule.__dict__)
            db.add(port.forward_rule)
            db.commit()
Exemplo n.º 5
0
def dns_query(hostname: str) -> Optional[str]:
    hostname = hostname.strip()
    if not hostname:
        return None
    elif is_ip(hostname) or is_ipv6(hostname):
        return hostname

    if result := get_ipv4(hostname):
        return result
Exemplo n.º 6
0
    def get_app_command(self, db: Session, port: Port):
        if not is_ip(port.forward_rule.config.get('remote_address')):
            remote_ip = dns_query(
                port.forward_rule.config.get('remote_address'))
        else:
            remote_ip = port.forward_rule.config.get('remote_address')
        port.forward_rule.config['remote_ip'] = remote_ip
        db.add(port.forward_rule)
        db.commit()

        return (
            f"/usr/local/bin/tiny_port_mapper "
            f"--log-level 3 "
            f"--disable-color "
            f"-l0.0.0.0:{port.num} "
            f"-r{remote_ip}:{port.forward_rule.config.get('remote_port')} "
            f"{'-t ' if port.forward_rule.config.get('type') == 'ALL' or port.forward_rule.config.get('type') == 'TCP' else ''}"
            f"{'-u ' if port.forward_rule.config.get('type') == 'ALL' or port.forward_rule.config.get('type') == 'UDP' else ''}"
        )
Exemplo n.º 7
0
def check_ip(ip: str) -> str:
    if not (is_ip(ip) or is_ipv6(ip)):
        raise ValueError(f"Invalid ip: {ip}")
    return ip