Пример #1
0
    def __init__(self, client=None):

        self.wg_kernel = module_loaded('wireguard')
        self.wg = WireGuard() if self.wg_kernel else WireguardGo()
        self.ipdb = IPDB()
        self.routes = Routes()
        self.client = client
Пример #2
0
def main(args=None):
    """ This is executed when run from the command line """

    try:
        WireGuard()
    except:
        # Wireguard module load failed
        pass

    parser = argparse.ArgumentParser()

    # Required positional argument
    parser.add_argument("run", help="Required parameter to start agent")

    # Optional verbosity counter (eg. -v, -vv, -vvv, etc.)
    parser.add_argument("-v",
                        "--verbose",
                        action="count",
                        default=0,
                        help="Verbosity (-v, -vv, etc)")

    # Specify output of "--version"
    parser.add_argument(
        "--version",
        action="version",
        version="%(prog)s (version {version})".format(version=__version__))

    args = parser.parse_args()
    agent(args)
Пример #3
0
def get_stats(format, interface, extended=True):
    clients = WireGuard().info(interface)[0].WGDEVICE_A_PEERS.value

    combined = {"interface": interface}
    peers = []
    established_peers_count = 0
    for client in clients:
        public_key = client.WGPEER_A_PUBLIC_KEY["value"].decode("utf-8")

        # ignore dummy key
        if public_key == (43 * "0" + "="):
            continue

        established = False
        latest_handshake = client.WGPEER_A_LAST_HANDSHAKE_TIME["tv_sec"]
        if datetime.now() - datetime.fromtimestamp(latest_handshake) < TIMEOUT:
            established = True
            established_peers_count += 1
        if extended:
            peers.append({
                "public_key": public_key,
                "latest_handshake": latest_handshake,
                "is_established": established,
                "rx_bytes": int(client.WGPEER_A_RX_BYTES['value']),
                "tx_bytes": int(client.WGPEER_A_TX_BYTES['value']),
            })

    if extended:
        combined["peers"] = peers

    combined["established_peers_count"] = established_peers_count

    return combined
Пример #4
0
def _get_wg_mock(peer):
    info_mock = mock.Mock()
    info_mock.WGDEVICE_A_PEERS.value = [peer]
    wg_instance = WireGuard()
    wg_info_mock = wg_instance.__enter__.return_value
    wg_info_mock.set.return_value = {"WireGuard": "set"}
    wg_info_mock.info.return_value = [info_mock]
    return wg_info_mock
Пример #5
0
 def __init__(self, client, interval=60):
     super().__init__()
     self.client = client
     self.interval = interval
     self.wg = WireGuard() if module_loaded(
         "wireguard") else WireGuardRead()
     self.stop_peer_watcher = threading.Event()
     self.daemon = True
Пример #6
0
def add_default():
    # see https://www.wireguard.com/netns/#the-classic-solutions
    ip = IPRoute()
    wg = WireGuard()

    wg_set(fwmark=51820)
    add_route('0.0.0.0/0', table=51820)
    ip.rule('add', fwmark=51820, flags=2, table=51820)
    ip.rule('add', FRA_SUPPRESS_PREFIXLEN=0, table=254)
Пример #7
0
def _get_wg_mock(key_name, stale_time):
    pm = mock.Mock()
    pm.get_attr.side_effect = [{"tv_sec": stale_time}, key_name.encode()]
    peer_mock = mock.Mock()
    peer_mock.get_attr.side_effect = [[pm]]
    wg_instance = WireGuard()
    wg_info_mock = wg_instance.__enter__.return_value
    wg_info_mock.set.return_value = {"WireGuard": "set"}
    wg_info_mock.info.return_value = [peer_mock]
    return wg_info_mock
Пример #8
0
 def __init__(self, client, interval=1):
     logger.debug(f"[REROUTING] Initializing")
     super().__init__()
     self.interval = interval
     self.client = client
     self.wg = WireGuard() if module_loaded(
         "wireguard") else WireGuardRead()
     self.routes = Routes()
     self.stop_rerouting = threading.Event()
     self.daemon = True
Пример #9
0
def wireguard_handler(client: WireGuardClient) -> Dict:
    with WireGuard() as wg:

        wg_peer = {
            "public_key": client.public_key,
            "persistent_keepalive": 15,
            "allowed_ips": [client.lladdr],
            "remove": client.remove,
        }

        return wg.set(client.wg_interface, peer=wg_peer)
Пример #10
0
def switch_relay():
    wg = WireGuard()
    old_server_pubkey = wg.info(
        config.IFNAME
    )[0].WGDEVICE_A_PEERS['value'][0].WGPEER_A_PUBLIC_KEY['value'].decode()
    wg_set(remove=True, public_key=old_server_pubkey)

    server_ip, server_pubkey = pick_relay()
    wg_set(endpoint_addr=server_ip,
           public_key=server_pubkey,
           allowed_ips=config.ALLOWED_IPS)
Пример #11
0
    def create(self, **kwargs):
        # Create WireGuard Interface
        self.ifname = kwargs.get('ifname')
        self.ip = kwargs.get('ip')

        with IPDB() as ip:
            dev = ip.create(kind='wireguard', ifname=self.ifname)
            dev.add_ip(self.ip)
            dev.up()
            dev.commit()

        wg = WireGuard()
        wg.set(self.ifname,
               private_key=kwargs.get('privatekey'),
               listen_port=kwargs.get('listenport'))
Пример #12
0
    def pull_from_wireguard(self):
        with WireGuard() as wg:
            clients = wg.info(self.wg_interface)[0].WGDEVICE_A_PEERS.value

            for client in clients:
                latest_handshake = client.WGPEER_A_LAST_HANDSHAKE_TIME["tv_sec"]
                public_key = client.WGPEER_A_PUBLIC_KEY["value"].decode("utf-8")

                peer = self.find_by_public_key(public_key)
                if len(peer) < 1:
                    peer = WireGuardPeer(public_key)
                    self.all_peers.append(peer)
                else:
                    peer = peer[0]

                peer.latest_handshake = datetime.fromtimestamp(latest_handshake)
Пример #13
0
def find_stale_wireguard_clients(wg_interface: str) -> List:
    with WireGuard() as wg:

        clients = wg.info(wg_interface)[0].WGDEVICE_A_PEERS.value

        three_hours_ago = (datetime.now() - timedelta(hours=3)).timestamp()

        stale_clients = []
        for client in clients:
            latest_handshake = client.WGPEER_A_LAST_HANDSHAKE_TIME["tv_sec"]
            if latest_handshake < int(three_hours_ago):
                stale_clients.append(
                    client.WGPEER_A_PUBLIC_KEY["value"].decode("utf-8")
                )

        return stale_clients
Пример #14
0
def wg_peer(ifname, pubkey, **kwargs):
    """
    **kwargs 这里都是可以选项:
    {
        'remove': false,
        'preshared_key': 'Pz8/V2FudFRvVHJ5TXlBZXJvR3Jvc3NlQmljaGU/Pz8=',
        'endpoint_addr': '8.8.8.8',
        'endpoint_port': 9999,
        'persistent_keepalive': 25,
        'allowed_ips': ['::/0'],
    }
    """
    peer = {}
    peer['public_key'] = pubkey
    peer.update(**kwargs)
    with WireGuard() as wg:
        wg.set(ifname, peer=peer)
Пример #15
0
def wg_peer(ifname, pubkey, peer):
    """
    **kwargs 这里都是可以选项:
    {
        'remove': false,

        'public_key': 'l5NCG5NmhSB4rbFVGZACPiKEL01+tQnjD6dRHCjXtkQ=',
        'preshared_key': 'Pz8/V2FudFRvVHJ5TXlBZXJvR3Jvc3NlQmljaGU/Pz8=',
        'endpoint_addr': '8.8.8.8', # 这里只能是IP, 不能是域名.
        'endpoint_port': 9999,
        'persistent_keepalive': 25,
        'allowed_ips': ['::/0'],
    }
    """
    # 如果endpoint_addr 是 域名,解析成ip
    # ipv6 也许会有问题
    addr = peer.get("endpoint_addr")
    if addr is not None:
        try:
            ipaddress.ip_address(addr)
            ip = addr
        except ValueError:
            ip = socket.gethostbyname(addr)
        
        peer["endpoint_addr"] = ip
    

    # check allowed-ips 都是网络地址
    peer["allowed_ips"] = peer.get("allowed_ips").split(",")
    #if allowed_ips is not None:
    #    for network in allowed_ips:
    #        try:
    #            ipaddress.ip_network(network)
    #        except ValueError:
    #            #raise ValueError(f"allowed-ips: {network} 不是网络地址, 或网络地址不正确。")
        
    peer['public_key'] = pubkey
    with WireGuard() as wg:
        wg.set(ifname, peer=peer)
Пример #16
0
 def setup(self):
     require_user('root')
     self.ipnets = []
     self.wg = WireGuard()
     self.log_id = uifname()
     self.ndb = NDB(log='../ndb-%s-%s.log' % (os.getpid(), self.log_id),
                    rtnl_debug=True)
     self.netif = uifname()
     self.wg0if = uifname()
     self.wg1if = uifname()
     self.ifnames = [self.netif, self.wg0if, self.wg1if]
     self.ipnets.append(allocate_network())
     self.ipnets.append(allocate_network())
     self.ipranges = [[str(x) for x in net] for net in self.ipnets]
     # create the "network" interface
     (self.ndb.interfaces.create(ifname=self.netif, kind='dummy').set(
         'state', 'up').add_ip('%s/24' % (self.ipranges[0][1])).commit())
     # create one peer
     (self.ndb.interfaces.create(ifname=self.wg0if, kind='wireguard').set(
         'state', 'up').add_ip('%s/24' % (self.ipranges[1][1])).commit())
     # create another peer
     (self.ndb.interfaces.create(ifname=self.wg1if, kind='wireguard').set(
         'state', 'up').add_ip('%s/24' % (self.ipranges[1][2])).commit())
Пример #17
0
def wg_set(**kwargs):
    wg = WireGuard()

    interface_kwargs = ['private_key', 'fwmark', 'listen_port']
    peer_kwargs = [
        'public_key', 'remove', 'preshared_key', 'endpoint_addr',
        'endpoint_port', 'persistent_keepalive', 'allowed_ips'
    ]
    interface = {}
    peer = {}
    for arg, value in kwargs.items():
        if arg in interface_kwargs:
            interface[arg] = value
        elif arg in peer_kwargs:
            peer[arg] = value

    if 'endpoint_addr' in peer and 'endpoint_port' not in peer:
        peer['endpoint_port'] = 51820

    if peer:
        wg.set(config.IFNAME, **interface, peer=peer)
    else:
        wg.set(config.IFNAME, **interface)
Пример #18
0
    def addpeer(self, **kwargs):
        # Create WireGuard object
        wg = WireGuard()

        # build peer dict
        peer = {}
        for key in kwargs.keys():
            if key == 'publickey':
                peer = {**peer, **{'public_key': kwargs.get('publickey')}}
            if key == 'endpointaddr':
                peer = {
                    **peer,
                    **{
                        'endpoint_addr': kwargs.get('endpointaddr')
                    }
                }
            if key == 'endpointport':
                peer = {
                    **peer,
                    **{
                        'endpoint_port': kwargs.get('endpointport')
                    }
                }
            if key == 'keepalive':
                peer = {
                    **peer,
                    **{
                        'persistent_keepalive': kwargs.get('keepalive')
                    }
                }
            if key == 'allowedips':
                peer = {**peer, **{'allowed_ips': kwargs.get('allowedips')}}

        print(f"peer: {peer}")

        # add peer
        wg.set(self.ifname, peer=peer)
Пример #19
0
def wg_delete_peer(ifname, pubkey):
    peer = {}
    peer["public_key"] = pubkey
    peer["remove"] = True
    with WireGuard() as wg:
        wg.set(ifname, peer=peer)
Пример #20
0
def wg_fwmark(ifname, fwmark):
    with WireGuard() as wg:
        wg.set(ifname, fwmark=fwmark)
Пример #21
0
def wg_set(ifname, private_key, listen_port=None, fwmark=0):
    with WireGuard() as wg:
        wg.set(ifname,
               private_key=private_key,
               listen_port=listen_port,
               fwmark=fwmark)
Пример #22
0
 def __init__(self, interval=10):
     self.interval = interval
     self.wg = WireGuard() if module_loaded(
         "wireguard") else WireGuardRead()