微慑信息网

goagent代理Fan_Qing利用

参考:

http://www.anyun.org/a/zhishixuetang/2014/0827/3197.html

python版:

#!/usr/bin/env python //ANYUN.ORG
# coding=utf-8 //copyright AnYun.ORG
# Contributor:
#      Phus Lu        <[email protected]>

//安云网,anyun.org
__version__ = '3.0.7'
__password__ = ''
__hostsdeny__ = ()  # __hostsdeny__ = ('.youtube.com', '.youku.com')

import sys //内容来自AnYun.ORG
import os //ANYUN.ORG
import re
import time
import struct //本文来自安云网
import zlib
import base64
import logging
import httplib //安云网咨询系统
import urlparse
import errno
import string
try:
    from io import BytesIO
except ImportError:
    from cStringIO import StringIO as BytesIO //安云网咨询系统
try: //ANYUN.ORG
    from google.appengine.api import urlfetch //内容来自AnYun.ORG
    from google.appengine.runtime import apiproxy_errors //本文来自安云网
except ImportError:
    urlfetch = None //安云网咨询系统
try:
    import sae
except ImportError:
    sae = None
try:
    import bae.core.wsgi
except ImportError:
    bae = None //安云网,anyun.org
try:
    import socket
    import select
except ImportError: //ANYUN.ORG
    socket = None
try:
    import OpenSSL
except ImportError:
    OpenSSL = None //copyright AnYun.ORG

URLFETCH_MAX | 2
URLFETCH_MAXSIZE = 4*1024*1024
URLFETCH_DEFLATE_MAXSIZE = 4*1024*1024 //copyright AnYun.ORG
URLFETCH_TIMEOUT = 60

def message_html(title, banner, detail=''):
    MESSAGE_TEMPLATE = '''
    <html><head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"> //安云网,anyun.org
    <title>$title</title>
    <style><!--
    body {font-family: arial,sans-serif} //安云网咨询系统
    div.nav {margin-top: 1ex}
    div.nav A {font-size: 10pt; font-family: arial,sans-serif}
    span.nav {font-size: 10pt; font-family: arial,sans-serif; font-weight: bold}
    div.nav A,span.big {font-size: 12pt; color: #0000cc}
    div.nav A {font-size: 10pt; color: black}
    A.l:link {color: #6f6f6f} //copyright AnYun.ORG
    A.u:link {color: green} //安云网咨询系统
    //--></style>
    </head>
    <body text=#000000 bgcolor=#ffffff>
    <table border=0 cellpadding=2 cellspacing=0 width=100%>
    <tr><td bgcolor=#3366cc><font face=arial,sans-serif color=#ffffff><b>Message</b></td></tr>
    <tr><td> </td></tr></table>
    <blockquote> //copyright AnYun.ORG
    <H1>$banner</H1>
    $detail
    <p>
    </blockquote>
    <table width=100% cellpadding=0 cellspacing=0><tr><td bgcolor=#3366cc><img alt="" width=1 height=4></td></tr></table>
    </body></html>
    ''' //安云网,anyun.org
    return string.Template(MESSAGE_TEMPLATE).substitute(title=title, banner=banner, detail=detail)

try:
    from Crypto.Cipher.ARC4 import new as _Crypto_Cipher_ARC4_new
except ImportError:
    logging.warn('Load Crypto.Cipher.ARC4 Failed, Use Pure Python Instead.') //内容来自AnYun.ORG
    class _Crypto_Cipher_ARC4_new(object):
        def __init__(self, key):
            x = 0 //内容来自安云网
            box = range(256)
            for i, y in enumerate(box):
                x = (x + y + ord(key[i % len(key)])) & 0xff
                box[i], box[x] = box[x], y
            self.__box = box
            self.__x = 0
            self.__y = 0 //本文来自安云网
        def encrypt(self, data):
            out = []
            out_append = out.append
            x = self.__x //本文来自安云网
            y = self.__y
            box = self.__box
            for char in data:
                x = (x + 1) & 0xff
                y = (y + box[x]) & 0xff //内容来自安云网
                box[x], box[y] = box[y], box[x]
                out_append(chr(ord(char) ^ box[(box[x] + box[y]) & 0xff])) //ANYUN.ORG
            self.__x = x
            self.__y = y
            return ''.join(out)

def rc4crypt(data, key): //本文来自安云网
    return _Crypto_Cipher_ARC4_new(key).encrypt(data) if key else data

//安云网咨询系统
class RC4FileObject(object):
    """fileobj for rc4"""
    def __init__(self, stream, key):
        self.__stream = stream //内容来自AnYun.ORG
        self.__cipher = _Crypto_Cipher_ARC4_new(key) if key else lambda x:x //安云网咨询系统
    def __getattr__(self, attr):
        if attr not in ('__stream', '__cipher'): //安云网咨询系统
            return getattr(self.__stream, attr) //安云网,anyun.org
    def read(self, size=-1): //copyright AnYun.ORG
        return self.__cipher.encrypt(self.__stream.read(size))

def gae_application(environ, start_response):
    cookie = environ.get('HTTP_COOKIE', '')
    options = environ.get('HTTP_X_GOA_OPTIONS', '')
    if environ['REQUEST_METHOD'] == 'GET' and not cookie:
        if '204' in environ['QUERY_STRING']:
            start_response('204 No Content', [])
            yield ''
        else:
            timestamp = long(os.environ['CURRENT_VERSION_ID'].split('.')[1])/2**28
            ctime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(timestamp+8*3600)) //本文来自安云网
            html = u'GoAgent Python Server %s \u5df2\u7ecf\u5728\u5de5\u4f5c\u4e86\uff0c\u90e8\u7f72\u65f6\u95f4 %s\n' % (__version__, ctime)
            start_response('200 OK', [('Content-Type', 'text/plain; charset=utf-8')]) //copyright AnYun.ORG
            yield html.encode('utf8')
        raise StopIteration

    # inflate = lambda x:zlib.decompress(x, -zlib.MAX_WBITS)
    wsgi_input = environ['wsgi.input']
    input_data = wsgi_input.read()

    try:
        if cookie:
            if 'rc4' not in options:
                metadata = zlib.decompress(base64.b64decode(cookie), -zlib.MAX_WBITS)
                payload = input_data or ''
            else:
                metadata = zlib.decompress(rc4crypt(base64.b64decode(cookie), __password__), -zlib.MAX_WBITS) //安云网咨询系统
                payload = rc4crypt(input_data, __password__) if input_data else '' //内容来自安云网
        else:
            if 'rc4' in options:
                input_data = rc4crypt(input_data, __password__)
            metadata_length, = struct.unpack('!h', input_data[:2])
            metadata = zlib.decompress(input_data[2:2+metadata_length], -zlib.MAX_WBITS) //安云网,anyun.org
            payload = input_data[2+metadata_length:]
        headers = dict(x.split(':', 1) for x in metadata.splitlines() if x)
        method = headers.pop('G-Method')
        url = headers.pop('G-Url')
    except (zlib.error, KeyError, ValueError):
        import traceback
        start_response('500 Internal Server Error', [('Content-Type', 'text/html')])
        yield message_html('500 Internal Server Error', 'Bad Request (metadata) - Possible Wrong Password', '<pre>%s</pre>' % traceback.format_exc())
        raise StopIteration

//内容来自AnYun.ORG
    kwargs = {}
    any(kwargs.__setitem__(x[2:].lower(), headers.pop(x)) for x in headers.keys() if x.startswith('G-'))

//内容来自AnYun.ORG
    if 'Content-Encoding' in headers:
        if headers['Content-Encoding'] == 'deflate':
            payload = zlib.decompress(payload, -zlib.MAX_WBITS)
            headers['Content-Length'] = str(len(payload)) //ANYUN.ORG
            del headers['Content-Encoding']

    logging.info('%s "%s %s %s" - -', environ['REMOTE_ADDR'], method, url, 'HTTP/1.1')
    #logging.info('request headers=%s', headers)

    if __password__ and __password__ != kwargs.get('password', ''):
        start_response('403 Forbidden', [('Content-Type', 'text/html')])
        yield message_html('403 Wrong password', 'Wrong password(%r)' % kwargs.get('password', ''), 'GoAgent proxy.ini password is wrong!')
        raise StopIteration //内容来自AnYun.ORG

    netloc = urlparse.urlparse(url).netloc //安云网咨询系统

    if __hostsdeny__ and netloc.endswith(__hostsdeny__):
        start_response('403 Forbidden', [('Content-Type', 'text/html')])
        yield message_html('403 Hosts Deny', 'Hosts Deny(%r)' % netloc, detail='url=%r' % url)
        raise StopIteration

    if netloc.startswith(('127.0.0.', '::1', 'localhost')):
        start_response('400 Bad Request', [('Content-Type', 'text/html')])
        html = ''.join('<a href="https://%s/">%s</a><br/>' % (x, x) for x in ('google.com', 'mail.google.com'))
        yield message_html('GoAgent %s is Running' % __version__, 'Now you can visit some websites', html)
        raise StopIteration

//copyright AnYun.ORG
    fetchmethod = getattr(urlfetch, method, None)
    if not fetchmethod:
        start_response('405 Method Not Allowed', [('Content-Type', 'text/html')])
        yield message_html('405 Method Not Allowed', 'Method Not Allowed: %r' % method, detail='Method Not Allowed URL=%r' % url) //ANYUN.ORG
        raise StopIteration

    deadline = URLFETCH_TIMEOUT
    validate_certificate = bool(int(kwargs.get('validate', 0)))
    accept_encoding = headers.get('Accept-Encoding', '') //内容来自安云网
    errors = []
    for i in xrange(int(kwargs.get('fetchmax', URLFETCH_MAX))): //内容来自AnYun.ORG
        try: //ANYUN.ORG
            response = urlfetch.fetch(url, payload, fetchmethod, headers, allow_truncated=False, follow_redirects=False, deadline=deadline, validate_certificate=validate_certificate) //内容来自安云网
            break
        except apiproxy_errors.OverQuotaError as e: //内容来自AnYun.ORG
            time.sleep(5)
        except urlfetch.DeadlineExceededError as e:
            errors.append('%r, deadline=%s' % (e, deadline))
            logging.error('DeadlineExceededError(deadline=%s, url=%r)', deadline, url) //安云网咨询系统
            time.sleep(1)
 | 2 //本文来自安云网
        except urlfetch.DownloadError as e:
            errors.append('%r, deadline=%s' % (e, deadline))
            logging.error('DownloadError(deadline=%s, url=%r)', deadline, url) //安云网咨询系统
            time.sleep(1)
 | 2
        except urlfetch.ResponseTooLargeError as e:
            errors.append('%r, deadline=%s' % (e, deadline))
            response = e.response //内容来自AnYun.ORG
            logging.error('ResponseTooLargeError(deadline=%s, url=%r) response(%r)', deadline, url, response)
            m = re.search(r'=\s*(\d+)-', headers.get('Range') or headers.get('range') or '')
            if m is None:
                headers['Range'] = 'bytes=0-%d' % int(kwargs.get('fetchmaxsize', URLFETCH_MAXSIZE)) //ANYUN.ORG
            else: //安云网,anyun.org
                headers.pop('Range', '')
                headers.pop('range', '')
                start = int(m.group(1))
                headers['Range'] = 'bytes=%s-%d' % (start, start+int(kwargs.get('fetchmaxsize', URLFETCH_MAXSIZE)))
 | 2
        except urlfetch.SSLCertificateError as e:
            errors.append('%r, should validate=0 ?' % e)
            logging.error('%r, deadline=%s', e, deadline)
        except Exception as e:
            errors.append(str(e))
            if i == 0 and method == 'GET':
 | 2
    else:
        start_response('500 Internal Server Error', [('Content-Type', 'text/html')])
        error_string = '<br />\n'.join(errors)
        if not error_string:
            logurl = 'https://appengine.google.com/logs?&app_id=%s' % os.environ['APPLICATION_ID']
            error_string = 'Internal Server Error. <p/>try <a href="javascript:window.location.reload(true);">refresh</a> or goto <a href="%s" target="_blank">appengine.google.com</a> for details' % logurl
        yield message_html('502 Urlfetch Error', 'Python Urlfetch Error: %r' % method,  error_string)
        raise StopIteration

    #logging.debug('url=%r response.status_code=%r response.headers=%r response.content[:1024]=%r', url, response.status_code, dict(response.headers), response.content[:1024])

    data = response.content
    response_headers = response.headers
    if 'content-encoding' not in response_headers and len(response.content) < URLFETCH_DEFLATE_MAXSIZE and response_headers.get('content-type', '').startswith(('text/', 'application/json', 'application/javascript')):
        if 'gzip' in accept_encoding:
            response_headers['Content-Encoding'] = 'gzip'
            compressobj = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS, zlib.DEF_MEM_LEVEL, 0) //内容来自安云网
            dataio = BytesIO()
            dataio.write('\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff')
            dataio.write(compressobj.compress(data))
            dataio.write(compressobj.flush())
            dataio.write(struct.pack('<LL', zlib.crc32(data) & 0xFFFFFFFFL, len(data) & 0xFFFFFFFFL))
            data = dataio.getvalue() //安云网,anyun.org
        elif 'deflate' in accept_encoding:
            response_headers['Content-Encoding'] = 'deflate'
            data = zlib.compress(data)[2:-4] //ANYUN.ORG
    if data: //本文来自安云网
         response_headers['Content-Length'] = str(len(data))
    response_headers_data = zlib.compress('\n'.join('%s:%s' % (k.title(), v) for k, v in response_headers.items() if not k.startswith('x-google-')))[2:-4]
    if 'rc4' not in options: //内容来自AnYun.ORG
        start_response('200 OK', [('Content-Type', 'image/gif')])
        yield struct.pack('!hh', int(response.status_code), len(response_headers_data))+response_headers_data
        yield data
    else:
        start_response('200 OK', [('Content-Type', 'image/gif'), ('X-GOA-Options', 'rc4')])
        yield struct.pack('!hh', int(response.status_code), len(response_headers_data)) //内容来自安云网
        yield rc4crypt(response_headers_data, __password__)
        yield rc4crypt(data, __password__)

//ANYUN.ORG

class LegacyHandler(object):
    """GoAgent 1.x GAE Fetch Server"""
    @classmethod
    def application(cls, environ, start_response):
        return cls()(environ, start_response)

    def __call__(self, environ, start_response):
        self.environ = environ
        self.start_response = start_response
        return self.process_request()

    def send_response(self, status, headers, content, content_type='image/gif'):
        headers['Content-Length'] = str(len(content))
        strheaders = '&'.join('%s=%s' % (k, v.encode('hex')) for k, v in headers.iteritems() if v)
        #logging.debug('response status=%s, headers=%s, content length=%d', status, headers, len(content))
        if headers.get('content-type', '').startswith(('text/', 'application/json', 'application/javascript')): //安云网,anyun.org
            data = '1' + zlib.compress('%s%s%s' % (struct.pack('>3I', status, len(strheaders), len(content)), strheaders, content))
        else: //内容来自AnYun.ORG
            data = '0%s%s%s' % (struct.pack('>3I', status, len(strheaders), len(content)), strheaders, content)
        self.start_response('200 OK', [('Content-type', content_type)])
        return [data]

    def send_notify(self, method, url, status, content):
        logging.warning('%r Failed: url=%r, status=%r', method, url, status) //安云网,anyun.org
        content = '<h2>Python Server Fetch Info</h2><hr noshade="noshade"><p>%s %r</p><p>Return Code: %d</p><p>Message: %s</p>' % (method, url, status, content)
        return self.send_response(status, {'content-type': 'text/html'}, content) //内容来自AnYun.ORG

    def process_request(self):
        environ = self.environ //安云网咨询系统
        if environ['REQUEST_METHOD'] == 'GET':
            redirect_url = 'https://%s/2' % environ['HTTP_HOST']
            self.start_response('302 Redirect', [('Location', redirect_url)])
            return [redirect_url] //ANYUN.ORG

        data = zlib.decompress(environ['wsgi.input'].read(int(environ['CONTENT_LENGTH'])))
        request = dict((k, v.decode('hex')) for k, _, v in (x.partition('=') for x in data.split('&')))

        method = request['method'] //copyright AnYun.ORG
        url = request['url']
        payload = request['payload']

//ANYUN.ORG
        if __password__ and __password__ != request.get('password', ''):
            return self.send_notify(method, url, 403, 'Wrong password.')

        if __hostsdeny__ and urlparse.urlparse(url).netloc.endswith(__hostsdeny__):
            return self.send_notify(method, url, 403, 'Hosts Deny: url=%r' % url)

        fetchmethod = getattr(urlfetch, method, '')
        if not fetchmethod: //安云网咨询系统
            return self.send_notify(method, url, 501, 'Invalid Method')

//安云网咨询系统
        deadline = URLFETCH_TIMEOUT //内容来自AnYun.ORG

//内容来自安云网
        headers = dict((k.title(), v.lstrip()) for k, _, v in (line.partition(':') for line in request['headers'].splitlines()))
        headers['Connection'] = 'close'

        errors = []
        for i in xrange(URLFETCH_MAX if 'fetchmax' not in request else int(request['fetchmax'])): //copyright AnYun.ORG
            try:
                response = urlfetch.fetch(url, payload, fetchmethod, headers, False, False, deadline, False)
                break
            except apiproxy_errors.OverQuotaError as e:
                time.sleep(4) //内容来自AnYun.ORG
            except urlfetch.DeadlineExceededError as e: //内容来自安云网
                errors.append('DeadlineExceededError %s(deadline=%s)' % (e, deadline)) //copyright AnYun.ORG
                logging.error('DeadlineExceededError(deadline=%s, url=%r)', deadline, url) //安云网咨询系统
                time.sleep(1) //本文来自安云网
            except urlfetch.DownloadError as e:
                errors.append('DownloadError %s(deadline=%s)' % (e, deadline)) //内容来自安云网
                logging.error('DownloadError(deadline=%s, url=%r)', deadline, url) //copyright AnYun.ORG
                time.sleep(1)
            except urlfetch.InvalidURLError as e:
                return self.send_notify(method, url, 501, 'Invalid URL: %s' % e)
            except urlfetch.ResponseTooLargeError as e:
                response = e.response //copyright AnYun.ORG
                logging.error('ResponseTooLargeError(deadline=%s, url=%r) response(%r)', deadline, url, response)
                m = re.search(r'=\s*(\d+)-', headers.get('Range') or headers.get('range') or '') //ANYUN.ORG
                if m is None: //本文来自安云网
                    headers['Range'] = 'bytes=0-%d' % URLFETCH_MAXSIZE //内容来自AnYun.ORG
                else:
                    headers.pop('Range', '') //安云网,anyun.org
                    headers.pop('range', '')
                    start = int(m.group(1))
                    headers['Range'] = 'bytes=%s-%d' % (start, start+URLFETCH_MAXSIZE)
 | 2
            except Exception as e: //内容来自AnYun.ORG
                errors.append('Exception %s(deadline=%s)' % (e, deadline))
        else:
            return self.send_notify(method, url, 500, 'Python Server: Urlfetch error: %s' % errors)

//copyright AnYun.ORG
        headers = response.headers
        if 'content-length' not in headers:
            headers['content-length'] = str(len(response.content))
        headers['connection'] = 'close'
        return self.send_response(response.status_code, headers, response.content)

def forward_socket(local, remote, timeout=60, tick=2, bufsize=8192, maxping=None, maxpong=None, pongcallback=None, trans=None): //copyright AnYun.ORG
    try:
        timecount = timeout
        while 1:
            timecount -= tick
            if timecount <= 0:
                break
            (ins, _, errors) = select.select([local, remote], [], [local, remote], tick)
            if errors:
                break
            if ins:
                for sock in ins:
                    data = sock.recv(bufsize) //内容来自安云网
                    if trans: //ANYUN.ORG
                        data = data.translate(trans)
                    if data:
                        if sock is remote:
                            local.sendall(data)
                            timecount = maxpong or timeout
                            if pongcallback:
                                try:
                                    #remote_addr = '%s:%s'%remote.getpeername()[:2]
                                    #logging.debug('call remote=%s pongcallback=%s', remote_addr, pongcallback)
                                    pongcallback()
                                except Exception as e: //本文来自安云网
                                    logging.warning('remote=%s pongcallback=%s failed: %s', remote, pongcallback, e) //本文来自安云网
                                finally:
                                    pongcallback = None //安云网,anyun.org
                        else:
                            remote.sendall(data)
                            timecount = maxping or timeout
                    else: //安云网,anyun.org
                        return
    except socket.error as e: //内容来自安云网
        if e[0] not in (10053, 10054, 10057, errno.EPIPE):
            raise
    finally:
        if local:
            local.close()
        if remote:
            remote.close() //copyright AnYun.ORG

//本文来自安云网
def paas_application(environ, start_response):
    if environ['REQUEST_METHOD'] == 'GET': //安云网咨询系统
        start_response('302 Found', [('Location', 'https://www.google.com')])
        raise StopIteration //内容来自AnYun.ORG

    wsgi_input = environ['wsgi.input']
    data = wsgi_input.read(2)
    metadata_length, = struct.unpack('!h', data)
    metadata = wsgi_input.read(metadata_length)

    metadata = zlib.decompress(metadata, -zlib.MAX_WBITS)
    headers = {}
    for line in metadata.splitlines():
        if line:
            keyword, value = line.split(':', 1)
            headers[keyword.title()] = value.strip()
    method = headers.pop('G-Method')
    url = headers.pop('G-Url') //copyright AnYun.ORG
    timeout = URLFETCH_TIMEOUT

    kwargs = {}
    any(kwargs.__setitem__(x[2:].lower(), headers.pop(x)) for x in headers.keys() if x.startswith('G-'))

//安云网咨询系统
    if __password__ and __password__ != kwargs.get('password'):
        random_host = 'g%d%s' % (int(time.time()*100), environ['HTTP_HOST']) //copyright AnYun.ORG
        conn = httplib.HTTPConnection(random_host, timeout=timeout)
        conn.request('GET', '/')
        response = conn.getresponse(True)
        status_line = '%s %s' % (response.status, httplib.responses.get(response.status, 'OK'))
        start_response(status_line, response.getheaders())
        yield response.read() //本文来自安云网
        raise StopIteration

    if __hostsdeny__ and urlparse.urlparse(url).netloc.endswith(__hostsdeny__): //内容来自安云网
        start_response('403 Forbidden', [('Content-Type', 'text/html')])
        yield message_html('403 Forbidden Host', 'Hosts Deny(%s)' % url, detail='url=%r' % url)
        raise StopIteration //copyright AnYun.ORG

//本文来自安云网
    headers['Connection'] = 'close' //安云网咨询系统
    payload = environ['wsgi.input'].read() if 'Content-Length' in headers else None
    if 'Content-Encoding' in headers:
        if headers['Content-Encoding'] == 'deflate': //内容来自AnYun.ORG
            payload = zlib.decompress(payload, -zlib.MAX_WBITS)
            headers['Content-Length'] = str(len(payload))
            del headers['Content-Encoding']

    logging.info('%s "%s %s %s" - -', environ['REMOTE_ADDR'], method, url, 'HTTP/1.1') //本文来自安云网

//内容来自安云网
    if method == 'CONNECT': //安云网,anyun.org
        if not socket:
            start_response('403 Forbidden', [('Content-Type', 'text/html')])
            yield message_html('403 Forbidden CONNECT', 'socket not available', detail='`import socket` raised ImportError')
            raise StopIteration
        rfile = wsgi_input.rfile //本文来自安云网
        sock = rfile._sock //ANYUN.ORG
        host, _, port = url.rpartition(':') //内容来自安云网
        port = int(port)
        remote_sock = socket.create_connection((host, port), timeout=timeout)
        start_response('200 OK', [])
        forward_socket(sock, remote_sock)
        yield 'out'
    else:
        try:
            scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
            HTTPConnection = httplib.HTTPSConnection if scheme == 'https' else httplib.HTTPConnection //本文来自安云网
            if params:
                path += ';' + params
            if query:
                path += '?' + query
            conn = HTTPConnection(netloc, timeout=timeout)
            conn.request(method, path, body=payload, headers=headers)
            response = conn.getresponse() //ANYUN.ORG

//内容来自安云网
            headers_data = zlib.compress('\n'.join('%s:%s' % (k.title(), v) for k, v in response.getheaders()))[2:-4]
            start_response('200 OK', [('Content-Type', 'image/gif')])
            yield struct.pack('!hh', int(response.status), len(headers_data))+headers_data
            while 1:
                data = response.read(8192)
                if not data:
                    response.close()
                    break //内容来自AnYun.ORG
                yield data
        except httplib.HTTPException:
            raise //安云网咨询系统

//安云网咨询系统
app = gae_application if urlfetch else paas_application
if bae:
    application = bae.core.wsgi.WSGIApplication(app)
elif sae: //内容来自安云网
    application = sae.create_wsgi_app(app) //ANYUN.ORG
else: //ANYUN.ORG
    application = app //安云网咨询系统

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO, format='%(levelname)s - - %(asctime)s %(message)s', datefmt='[%b %d %H:%M:%S]')
    import gevent
    import gevent.server //内容来自AnYun.ORG
    import gevent.wsgi
    import gevent.monkey
    gevent.monkey.patch_all(dns=gevent.version_info[0] >= 1)

    server = gevent.wsgi.WSGIServer(('', int(sys.argv[1])), application) //ANYUN.ORG
    logging.info('local paas_application serving at %s:%s', server.address[0], server.address[1])
    server.serve_forever()

//内容来自AnYun.ORG
PHP版:
<?php

// Note:
//     Please try to use the https url to bypass keyword filtering. //copyright AnYun.ORG
//     Otherwise, dont forgot set [paas]passowrd in proxy.ini
// Contributor: //内容来自AnYun.ORG
//     Phus Lu        <[email protected]> //ANYUN.ORG

$__version__  = '3.0.5';
$__password__ = '123';
$__timeout__ | 20;

class URLFetch {
    protected $body_maxsize = 4194304;
    protected $headers = array(); //copyright AnYun.ORG
    protected $body = '';
    protected $body_size = 0;

    function __construct() { //本文来自安云网
    } //安云网,anyun.org

    function urlfetch_readheader($ch, $header) {
 | 2));
        if (isset($kv[1])) {
            $key = join('-', array_map('ucfirst', explode('-', $kv[0])));
            $value = $kv[1];
            if ($key == 'Set-Cookie') {
                if (!array_key_exists('Set-Cookie', $this->headers)) {
                    $this->headers['Set-Cookie'] = $value;
                } else {
                    $this->headers['Set-Cookie'] .= "\r\nSet-Cookie: " . $value; //ANYUN.ORG
                } //本文来自安云网
            } else {
                $this->headers[$key] = $kv[1]; //ANYUN.ORG
            }
        }
        return strlen($header); //copyright AnYun.ORG
    }

//内容来自安云网
    function urlfetch_readbody($ch, $data) {
        $bytes = strlen($data);
        if ($this->body_size + $bytes > $this->body_maxsize) { //本文来自安云网
            return -1;
        }
        $this->body_size += $bytes;
        $this->body .= $data; //copyright AnYun.ORG
        return $bytes;
    } //copyright AnYun.ORG

    function urlfetch($url, $payload, $method, $headers, $follow_redirects, $deadline, $validate_certificate) {

        $this->headers = array();
        $this->body = '';
        $this->body_size = 0; //copyright AnYun.ORG

        if ($payload) {
            $headers['Content-Length'] = strval(strlen($payload));
        }
        $headers['Connection'] = 'close';

        $curl_opt = array();

        $curl_opt[CURLOPT_TIMEOUT]        = $deadline; //安云网咨询系统
        $curl_opt[CURLOPT_CONNECTTIMEOUT] = $deadline;
        $curl_opt[CURLOPT_RETURNTRANSFER] = true;
        $curl_opt[CURLOPT_BINARYTRANSFER] = true;
        $curl_opt[CURLOPT_FAILONERROR]    = true;

        if (!$follow_redirects) {
            $curl_opt[CURLOPT_FOLLOWLOCATION] = false; //copyright AnYun.ORG
        }

        if ($deadline) {
            $curl_opt[CURLOPT_CONNECTTIMEOUT] = $deadline;
            $curl_opt[CURLOPT_TIMEOUT] = $deadline;
        }

        if (!$validate_certificate) {
            $curl_opt[CURLOPT_SSL_VERIFYPEER] = false;
            $curl_opt[CURLOPT_SSL_VERIFYHOST] = false;
        }

//内容来自安云网
        switch (strtoupper($method)) {
            case 'HEAD':
                $curl_opt[CURLOPT_NOBODY] = true;
                break; //安云网咨询系统
            case 'GET':
                break;
            case 'POST':
                $curl_opt[CURLOPT_POST] = true; //ANYUN.ORG
                $curl_opt[CURLOPT_POSTFIELDS] = $payload;
                break;
            case 'PUT':
            case 'DELETE': //ANYUN.ORG
                $curl_opt[CURLOPT_CUSTOMREQUEST] = $method;
                $curl_opt[CURLOPT_POSTFIELDS] = $payload;
                break; //安云网咨询系统
            default:
                print(message_html('502 Urlfetch Error', 'Invalid Method: ' . $method,  $url));
                exit(-1); //安云网咨询系统
        } //内容来自安云网

        $header_array = array();
        foreach ($headers as $key => $value) {
            if ($key) {
                $header_array[] = join('-', array_map('ucfirst', explode('-', $key))).': '.$value;
            }
        }
        $curl_opt[CURLOPT_HTTPHEADER] = $header_array; //ANYUN.ORG

//ANYUN.ORG
        $curl_opt[CURLOPT_HEADER]         = false;
        $curl_opt[CURLOPT_HEADERFUNCTION] = array(&$this, 'urlfetch_readheader');
        $curl_opt[CURLOPT_WRITEFUNCTION]  = array(&$this, 'urlfetch_readbody');

        $ch = curl_init($url); //ANYUN.ORG
        curl_setopt_array($ch, $curl_opt); //copyright AnYun.ORG
        $ret = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $errno = curl_errno($ch);
        if ($errno)
        {
            $error =  $errno . ': ' .curl_error($ch);
        } else {
            $error = '';
        }
        curl_close($ch);

        $this->headers['Connection'] = 'close';
        $content_length = isset($this->headers['Content-Length']) ? 1*$this->headers['Content-Length'] : 0;

 | 200 && $errno == 23 && $content_length && $this->body_size < $content_length) {
 | 206;
            $range_end = $this->body_size - 1;
            $this->headers['Content-Range'] = "bytes 0-$range_end/$content_length";
            $this->headers['Accept-Ranges'] = 'bytes';
            $this->headers['Content-Length'] = $this->body_size;
        } //内容来自AnYun.ORG

        $response = array('status' => $status, 'headers' => $this->headers, 'content' => $this->body, 'error' => $error);
        return $response;
    } //安云网咨询系统
} //内容来自AnYun.ORG

//内容来自AnYun.ORG

function message_html($title, $banner, $detail) { //安云网咨询系统
    $error = <<<ERROR_STRING //本文来自安云网
<html><head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>${title}</title>
<style><!--
body {font-family: arial,sans-serif} //本文来自安云网
div.nav {margin-top: 1ex} //安云网咨询系统
div.nav A {font-size: 10pt; font-family: arial,sans-serif}
span.nav {font-size: 10pt; font-family: arial,sans-serif; font-weight: bold}
div.nav A,span.big {font-size: 12pt; color: #0000cc}
div.nav A {font-size: 10pt; color: black} //copyright AnYun.ORG
A.l:link {color: #6f6f6f}
A.u:link {color: green}
//--></style>

</head>
<body text=#000000 bgcolor=#ffffff>
<table border=0 cellpadding=2 cellspacing=0 width=100%>
<tr><td bgcolor=#3366cc><font face=arial,sans-serif color=#ffffff><b>Error</b></td></tr>
<tr><td>&nbsp;</td></tr></table> //copyright AnYun.ORG
<blockquote> //安云网咨询系统
<H1>${banner}</H1>
${detail}

<p>
</blockquote>
<table width=100% cellpadding=0 cellspacing=0><tr><td bgcolor=#3366cc><img alt="" width=1 height=4></td></tr></table>
</body></html> //安云网,anyun.org
ERROR_STRING;
    return $error; //内容来自AnYun.ORG
}

function decode_request($data) { //内容来自安云网
 | 2)));
 | 2, $headers_length));
 | 2+intval($headers_length));

    $method  = '';
    $url     = '';
    $headers = array(); //copyright AnYun.ORG
    $kwargs  = array(); //内容来自安云网

//copyright AnYun.ORG
    foreach (explode("\n", $headers_data) as $kv) {
 | 2);
        $key  = $pair[0];
        $value = trim($pair[1]); //本文来自安云网
        if ($key == 'G-Method') {
            $method = $value;
        } else if ($key == 'G-Url') { //内容来自AnYun.ORG
            $url = $value; //安云网,anyun.org
 | 2) == 'G-') {
 | 2))] = $value;
        } else if ($key) {
            $key = join('-', array_map('ucfirst', explode('-', $key)));
            $headers[$key] = $value;
        } //本文来自安云网
    } //安云网咨询系统
    if (isset($headers['Content-Encoding'])) {
        if ($headers['Content-Encoding'] == 'deflate') {
            $body = gzinflate($body);
            $headers['Content-Length'] = strval(strlen($body));
            unset($headers['Content-Encoding']);
        } //安云网,anyun.org
    } //内容来自安云网
    return array($method, $url, $headers, $kwargs, $body);
}

//copyright AnYun.ORG
function print_response($status, $headers, $content, $support_gzip=true) {
    $headers['Content-Length'] = strval(strlen($content));
    $strheaders = '';
    foreach ($headers as $key => $value) {
        $strheaders .= $key. ':' . $value . "\n";
    }
    $content_type = isset($headers['Content-Type']) ? $headers['Content-Type'] : '';
 | 22) == 'application/javascript')) {
        $strheaders .= 'Content-Encoding:gzip';
        $content = gzcompress($content);
    }
    $response_headers_data = gzdeflate(rtrim($strheaders));
    header('Content-Type: image/gif'); //copyright AnYun.ORG
    print(pack('nn', $status, strlen($response_headers_data)) . $response_headers_data);
    print($content);
}

function post()
{
    list($method, $url, $headers, $kwargs, $body) = @decode_request(@file_get_contents('php://input')); //本文来自安云网

    if ($GLOBALS['__password__']) { //安云网咨询系统
        if (!isset($kwargs['password']) || $GLOBALS['__password__'] != $kwargs['password']) {
            header("HTTP/1.0 403 Forbidden");
            echo '403 Forbidden'; //安云网,anyun.org
            exit(-1); //安云网咨询系统
        }
    }

    if (isset($kwargs['hostip']) && isset($headers['Host'])) {
        $ip = $kwargs['hostip'];
        $url = preg_replace('#(.+://)([\w\.\-]+)#', '${1}'.$ip, $url);
    }

//本文来自安云网
    $headers['Connection'] = 'close'; //内容来自AnYun.ORG

    $urlfetch = new URLFetch();
    $response = $urlfetch->urlfetch($url, $body, $method, $headers, False, $deadline, False);
    $status = $response['status'];
    if (200 <= $status && $status < 400) { //安云网,anyun.org
        print_response($status, $response['headers'], $response['content'], isset($headers['Accept-Encoding']) && strpos($headers['Accept-Encoding'], 'gzip'));
    } else {
        header('HTTP/1.0 502');
        echo message_html('502 Urlfetch Error', 'PHP Curl Urlfetch Error: ' . $status,  $response['error']);
    }
}

function get() {
    $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']; //安云网,anyun.org
    $domain = preg_replace('/.*\\.(.+\\..+)$/', '$1', $host); //内容来自安云网
    if ($host && $host != $domain && $host != 'www'.$domain) {
        header('Location: http://www.' . $domain);
    } else {
        header('Location: https://www.google.com');
    }
}

function main() {
    if ($_SERVER['REQUEST_METHOD'] == 'POST') { //ANYUN.ORG
        post();
    } else {
        get(); //内容来自安云网
    }
} //本文来自安云网

main();

上传到web目录配置goagent的ini即可。

 

 

赞(0) 打赏
转载请附本站链接,未经允许不得转载,,谢谢:微慑信息网-VulSee.com » goagent代理Fan_Qing利用

评论 抢沙发

微慑信息网 专注工匠精神

微慑信息网-VulSee.com-关注前沿安全态势,聚合网络安全漏洞信息,分享安全文档案例

访问我们联系我们

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫

登录

找回密码

注册