Python socket via proxy

SocksLib

Sockslib is a library designed to make the usage of socks proxies as easy as possible. This library can connect to proxies, authenticate, and then have the use of a normal python socket.

Features

  • Socks5 support
  • Socks4 support
  • IPv4 Support
  • IPv6 Support (Socks5)
  • Domain Support
  • User/Pass authentication (Socks5)
  • Easily customizable authentication (Socks5)
  • UDP Support (Socks5)
  • Full socket api

Documentation

Index

  1. Intro
    1. Creating a socket
    2. Setting the proxy
    3. Set the default proxy
    4. URLLib proxied
    5. IPv6
    1. TCP
    2. UDP
    3. Using Other Authentication Methods
    4. Implementing Your Own Authentication Methods
    1. No Authentication
    2. Identity Authentication

    Intro

    Creating a new socket

    Default proxies can be useful for situations when other libraries use sockets to communicate and you want to force that library to use a proxy instead of a direct connection

       To connect to a proxy server via ipv6, you must explicitly specify the protocol by passing the ip_protocol parameter to the SocksSocket constructor, OR by using the 3rd option of set_default_proxy. Here is an example of connecting to a remote IPv6 proxy:

    Examples

    SOCKS5

    Socks5 TCP

    This is an example usage that connects to a Socks5 proxy at 127.0.0.1:9050 and then requests the page http://myexternalip.com/raw

    Socks5 UDP

    This is an example usage that connects to a Socks5 proxy at 127.0.0.1:9050 and then sends a UDP packet.

    Due to the nature of UDP in the SOCKS5 protocol, it is reccomended to use the context manager, as the remote proxy server will not drop the UDP associate request until the socket is closed.

    Using other authentication methods

    To use more authentication methods like User/Pass auth, you pass an array of authentication methods to the third parameter of set_proxy (Don’t neglect to set the second parameter to the proxy type!)

    Implementing your own authentication methods

    To implement your own socks5 authentication method, you must make a class that implements sockslib.AuthenticationMethod it requires that you implement a getId() function, an authenticate(socket) function, and a forP function. Note: the authenticate function must return a boolean, True if authentication succeeded and False if it failed.

        This is an example usage that connects to a Socks4 proxy at 127.0.0.1:9050 and then requests the page http://myexternalip.com/raw

    Источник

    frxstrem / http_proxy_connect.py

    This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

    »’
    Establish a socket connection through an HTTP proxy.
    Author: Fredrik Østrem
    License:
    Copyright 2013 Fredrik Østrem
    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
    documentation files (the «Software»), to deal in the Software without restriction, including without
    limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
    Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
    The above copyright notice and this permission notice shall be included in all copies or substantial portions
    of the Software.
    THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
    TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
    CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
    »’
    import socket
    from base64 import b64encode
    def http_proxy_connect ( address , proxy = None , auth = None , headers = <>):
    «»»
    Establish a socket connection through an HTTP proxy.
    Arguments:
    address (required) = The address of the target
    proxy (def: None) = The address of the proxy server
    auth (def: None) = A tuple of the username and password used for authentication
    headers (def: <>) = A set of headers that will be sent to the proxy
    Returns:
    A 3-tuple of the format:
    (socket, status_code, headers)
    Where `socket’ is the socket object, `status_code` is the HTTP status code that the server
    returned and `headers` is a dict of headers that the server returned.
    «»»
    def valid_address ( addr ):
    «»» Verify that an IP/port tuple is valid «»»
    return isinstance ( addr , ( list , tuple )) and len ( addr ) == 2 and isinstance ( addr [ 0 ], str ) and isinstance ( addr [ 1 ], ( int , long ))
    if not valid_address ( address ):
    raise ValueError ( ‘Invalid target address’ )
    if proxy == None :
    s = socket . socket ()
    s . connect ( address )
    return s , 0 , <>
    if not valid_address ( proxy ):
    raise ValueError ( ‘Invalid proxy address’ )
    headers =
    ‘host’ : address [ 0 ]
    >
    if auth != None :
    if isinstance ( auth , str ):
    headers [ ‘proxy-authorization’ ] = auth
    elif auth and isinstance ( auth , ( tuple , list )) and len ( auth ) == 2 :
    headers [ ‘proxy-authorization’ ] = ‘Basic ‘ + b64encode ( ‘%s:%s’ % auth )
    else :
    raise ValueError ( ‘Invalid authentication specification’ )
    s = socket . socket ()
    s . connect ( proxy )
    fp = s . makefile ( ‘r+’ )
    fp . write ( ‘CONNECT %s:%d HTTP/1.0 \r \n ‘ % address )
    fp . write ( ‘ \r \n ‘ . join ( ‘%s: %s’ % ( k , v ) for ( k , v ) in headers . items ()) + ‘ \r \n \r \n ‘ )
    fp . flush ()
    statusline = fp . readline (). rstrip ( ‘ \r \n ‘ )
    if statusline . count ( ‘ ‘ ) < 2 :
    fp . close ()
    s . close ()
    raise IOError ( ‘Bad response’ )
    version , status , statusmsg = statusline . split ( ‘ ‘ , 2 )
    if not version in ( ‘HTTP/1.0’ , ‘HTTP/1.1’ ):
    fp . close ()
    s . close ()
    raise IOError ( ‘Unsupported HTTP version’ )
    try :
    status = int ( status )
    except ValueError :
    fp . close ()
    s . close ()
    raise IOError ( ‘Bad response’ )
    response_headers = <>
    while True :
    tl = »
    l = fp . readline (). rstrip ( ‘ \r \n ‘ )
    if l == » :
    break
    if not ‘:’ in l :
    continue
    k , v = l . split ( ‘:’ , 1 )
    response_headers [ k . strip (). lower ()] = v . strip ()
    fp . close ()
    return ( s , status , response_headers )

    Источник

    A python proxy in less than 100 lines of code

    It’s a intermediary server intended to act in name of a client, and sometimes to do something useful with the data before it reaches the original target. Let’s see a picture:

    My idea was to produce a proxy using only the default python library, and to guide me during development I set the following:

    • Each new client connection to our proxy must generate a new connection to the original target.
    • Each data packet that reaches our proxy must be forwarded to the original target.
    • Each data packet received from the target must be sent back to the correct client
    • The proxy must accept multiple clients
    • Must be fast
    • Must have a low resource usage

    The result:

    The explanation

    class Forward()

    The Forward class is the one responsible for establishing a connection between the proxy and the remote server(original target).

    class TheServer().main_loop()

    The input_list stores all the avaiable sockets that will be managed by select.select, the first one to be appended is the server socket itself, each new connection to this socket will trigger the on_accept() method.

    If the current socket inputready (returned by select) is not a new connection, it will be considered as incoming data(maybe from server, maybe from client), if the data lenght is 0 it’s a close request, otherwise the packet should be forwarded to the correct endpoint.

    class TheServer().on_accept()

    This method creates a new connection with the original target (proxy -> remote server), and accepts the current client connection (client->proxy). Both sockets are stored in input_list, to be then handled by main_loop. A «channel» dictionary is used to associate the endpoints(clientserver).

    class TheServer().recv()

    This method is used to process and forward the data to the original destination ( client server ).

    class TheServer().on_close()

    Disables and removes the socket connection between the proxy and the original server and the one between the client and the proxy itself.

    Источник

    Читайте также:  Java locale and date
Оцените статью