Beispiel #1
0
 def copy_to(self, target_: asn1.SkrIPMask):
     if isinstance(self.mask, ipaddress.IPv4Address):
         target_.setComponentByName(
             'ipv4-mask', ipaddress.v4_int_to_packed(int(self.mask)))
     else:
         target_.setComponentByName(
             'ipv6-mask', ipaddress.v6_int_to_packed(int(self.mask)))
Beispiel #2
0
 def copy_to(self, target_):
     if isinstance(self.address, ipaddress.IPv4Address):
         target_.setComponentByName(
             'ipv4', ipaddress.v4_int_to_packed(int(self.address)))
     else:
         target_.setComponentByName(
             'ipv6', ipaddress.v6_int_to_packed(int(self.address)))
Beispiel #3
0
def makeResponseForAAAA(parsedData, IP, ttl=60):
    ttl = int(ttl)
    typeOf = parsedData.qType
    IPData = v6_int_to_packed(IP._ip)
    data = requestMaker(parsedData.domain, parsedData.qType, 1, 1)
    data = writeString(data, parsedData.domain)
    fmt = struct.Struct("!H H I H")
    qT = (typeOf, IN, ttl, 16)
    data += fmt.pack(*qT)
    data += IPData
    return data
Beispiel #4
0
 def __make_address__(key):
     """Make version and address."""
     address = ipaddress.ip_address(self.__args__[key])
     version = address.version
     if version == 4:  # IPv4 address
         verbit = '0100'
         packed = ipaddress.v4_int_to_packed(int(address))
     elif version == 6:  # IPv6 address
         verbit = '0110'
         packed = ipaddress.v6_int_to_packed(int(address))
     else:
         raise pcapkit.utilities.exceptions.VersionError(
             'unknown IP version')
     return (verbit, packed)
Beispiel #5
0
def socks5EncodeBindHost(bindHost):
    atyp = b'\x03'
    hostData = None
    try:
        ipAddr = ipaddress.ip_address(bindHost)
        if ipAddr.version == 4:
            atyp = b'\x01'
            hostData = struct.pack('!L', int(ipAddr))
        else:
            atyp = b'\x04'
            hostData = struct.pack('!16s', ipaddress.v6_int_to_packed(int(ipAddr)))
    except Exception:
        hostData = struct.pack(f'!B{len(bindHost)}s', len(bindHost), bindHost)
    return atyp, hostData
Beispiel #6
0
def socks5EncodeBindHost(bindHost): # 根据IP地址种类的不同,编码不同的报文
    atyp = b'\x03'
    hostData = None
    try:
        ipAddr = ipaddress.ip_address(bindHost)
        if ipAddr.version == 4:
            atyp = b'\x01'
            hostData = struct.pack('!L', int(ipAddr))   #ipv4,pack()函数用于将int型转为字符串
        else:
            atyp = b'\x04'
            hostData = struct.pack('!16s', ipaddress.v6_int_to_packed(int(ipAddr))) # ipv6
    except Exception:
        hostData = struct.pack(f'!B{len(bindHost)}s', len(bindHost), bindHost)
    return atyp, hostData
Beispiel #7
0
def ip6_str_to_bytes(ip6_str):
    """Convert ip address 127.0.0.1 to byte representation."""
    return v6_int_to_packed(int(IPv6Address(ip6_str)))
Beispiel #8
0
async def handle(client_reader, client_writer):
    client_host, client_port, *_ = client_writer.get_extra_info('peername')
    logger.info(f'Request from local: {client_host} {client_port}')
    first_byte = await aio_read(
        client_reader,
        READ_MODE.EXACT,
        read_len=1,
        log_hint=f'first byte from {client_host} {client_port}')
    log_hint = f'{client_host} {client_port}'
    remote_host = None
    remote_port = None
    try:
        if first_byte == b'\x05':
            proxy_protocal = 'SOCKS5'
            nmethods = await aio_read(client_reader,
                                      READ_MODE.EXACT,
                                      read_len=1,
                                      log_hint=f'nmethods')
            await aio_read(client_reader,
                           READ_MODE.EXACT,
                           read_len=nmethods[0],
                           log_hint='methods')
            resp_data = struct.pack("!BB", SOCKS_VER, 0)
            await aio_write(client_writer,
                            b'\x05\x00',
                            log_hint='reply no auth')
            await aio_read(client_reader,
                           READ_MODE.EXACT,
                           exact_data=b'\x05\x01\x00',
                           read_len=1,
                           log_hint='version command reservation')
            atyp = await aio_read(client_reader,
                                  READ_MODE.EXACT,
                                  read_len=1,
                                  log_hint=f'atyp')
            if atyp == b'\x01':  # IPv4
                temp_addr = await aio_read(client_reader,
                                           READ_MODE.EXACT,
                                           read_len=4,
                                           log_hint='ipv4')
                remote_host = str(ipaddress.ip_address(temp_addr))
            elif atyp == b'\x03':  # domain
                domain_len = await aio_read(client_reader,
                                            READ_MODE.EXACT,
                                            read_len=1,
                                            log_hint='domain len')
                remote_host = await aio_read(client_reader,
                                             READ_MODE.EXACT,
                                             read_len=domain_len[0],
                                             log_hint='domain')
                remote_host = remote_host.decode('utf8')
            elif atyp == b'\x04':  # IPv6
                temp_addr = await aio_read(client_reader,
                                           READ_MODE.EXACT,
                                           read_len=16,
                                           log_hint='ipv6')
                remote_host = str(ipaddress.ip_address(temp_addr))
            else:
                raise program_err(f'invalid atyp')
            remote_port = await aio_read(client_reader,
                                         READ_MODE.EXACT,
                                         read_len=2,
                                         log_hint='port')
            remote_port = int.from_bytes(remote_port, 'big')
        else:
            req = await aio_read(client_reader,
                                 READ_MODE.LINE,
                                 log_hint='http request')
            req = bytes.decode(first_byte + req)
            method, uri, protocal, *_ = req.split()
            if method.lower() == 'connect':
                proxy_protocal = 'HTTPS'
                log_hint = f'{log_hint} {proxy_protocal}'
                remote_host, remote_port, *_ = uri.split(':')
                await aio_read(client_reader,
                               READ_MODE.UNTIL,
                               until_str=b'\r\n\r\n',
                               log_hint='message left')
            else:
                raise program_err(f'cannot server the request {req.split()}')

        logger.info(f'{log_hint} connect to {remote_host} {remote_port}')

        remote_reader, remote_writer = await asyncio.open_connection(
            args.remote_server_ip, args.remote_server_port)
        await aio_write(
            remote_writer,
            f'{remote_host} {remote_port} {args.username} {args.password}\r\n'.
            encode(),
            log_hint=
            f'{log_hint} connect to remote server, {remote_host} {remote_port}'
        )
        reply_bindaddr = await aio_read(
            remote_reader,
            READ_MODE.LINE,
            log_hint='remote server reply the bind addr')
        reply_bindaddr = bytes.decode(reply_bindaddr)
        addr = reply_bindaddr[:-2].split()
        bind_host, bind_port = addr[0], addr[1]
        logger.info(f'{log_hint} bind at {bind_host} {bind_port}')

        if proxy_protocal == 'SOCKS5':
            bind_domain = bind_host
            bind_host = ipaddress.ip_address(bind_host)
            atyp = b'\x03'
            host_data = None
            try:
                if bind_host.version == 4:
                    atyp = b'\x01'
                    host_data = struct.pack('!L', int(bind_host))
                    reply_data = struct.pack(
                        f'!ssss', b'\x05', b'\x00', b'\x00',
                        atyp) + host_data + struct.pack('!H', int(bind_port))
                else:
                    atyp = b'\x04'
                    host_data = struct.pack(
                        '!16s', ipaddress.v6_int_to_packed(int(bind_host)))
                    reply_data = struct.pack(
                        f'!ssss', b'\x05', b'\x00', b'\x00',
                        atyp) + host_data + struct.pack('!H', int(bind_port))
            except Exception as exc:
                logExc(exc)
                host_data = struct.pack(f'!B{len(bind_domain)}s',
                                        len(bind_domain), bind_domain.encode())
                reply_data = struct.pack(f'!ssss{len(host_data)}sH', b'\x05',
                                         b'\x00', b'\x00', atyp, host_data,
                                         int(bind_port))

            await aio_write(client_writer,
                            reply_data,
                            log_hint='reply the bind addr')
        else:
            await aio_write(client_writer,
                            f'{protocal} 200 OK\r\n\r\n'.encode(),
                            log_hint='response to HTTPS')

        try:
            await asyncio.gather(
                handle_local(client_reader, remote_writer, client_writer),
                handle_remote(client_writer, remote_reader, remote_writer))
        except Exception as exc:
            logExc(exc)
            client_writer.close()
            remote_writer.close()
    except program_err as exc:
        logger.info(f'{log_hint} {exc}')
        await client_writer.close()
        await remote_writer.close()
    except OSError:
        logger.info(f'{log_hint} connect fail')
        await client_writer.close()
    except Exception as exc:
        logger.error(f'{traceback.format_exc()}')
        exit(1)
Beispiel #9
0
def get_property_ip6(var):
    """Create a get/set-property for an IP6 address as string-representation."""
    return property(
        lambda obj: str(IPv6Address(obj.__getattribute__(var))),
        lambda obj, val: obj.__setattr__(
            var, v6_int_to_packed(int(IPv6Address(val)))))
Beispiel #10
0
 def update_event(self, inp=-1):
     self.set_output_val(0, ipaddress.v6_int_to_packed(self.input(0)))