Exemplo n.º 1
0
def get_searchList(search_text, page):
    headers = {'User-Agent': UserAgents.get_user_agent_phone()}
    url = '{0}/search?title={1}&page={2}'.format(server, search_text, page)
    html = requests.get(url, headers=headers).text

    soup = BeautifulSoup(html, 'html.parser')
    bookList = soup.find_all('a', class_='manga-item')
    results = []
    for book in bookList:
        temp = {}
        temp['url'] = '/info' + book['href']

        img = book.find('img')
        tag = soup.new_tag('div')
        tag['class'] = 'manga-right'

        for item in book.find_all('p'):
            item.name = 'div'
            tag.append(item)
        book.append(img)
        book.append(tag)
        # print(book)
        temp['html'] = ''.join(str(item) for item in book)
        results.append(temp)

    return results
Exemplo n.º 2
0
def put(*args):
    addr = args[0]
    flag_id = args[1]
    flag = args[2]
    vuln = args[3]

    flag_id = ''.join(random.choice(string.hexdigits)
                      for i in range(32)).upper()

    url = 'http://%s:1678%s/add_unit?uuid=%s&mind=%s' % (addr, int(vuln) - 1,
                                                         flag_id, flag)
    headers = {'User-Agent': UserAgents.get()}
    try:
        r = requests.post(url, headers=headers)
        if r.status_code == 502:
            close(DOWN, "Service is down", "Nginx 502")
        if r.status_code != 200:
            close(
                MUMBLE, "Submit error",
                "Invalid status code: %s %d %s" % (url, r.status_code, r.text))

    except Exception as e:
        close(DOWN, "HTTP Error", "HTTP error: %s" % e)

    close(OK, flag_id)
Exemplo n.º 3
0
def get(*args):
	addr = args[0]
	flag_id = args[1]
	flag = args[2]
	
	params = json.loads( flag_id )

	guid = params[ 'guid' ]
	COLOR_R = params[ 'COLOR_R' ]
	COLOR_G = params[ 'COLOR_G' ]
	COLOR_B = params[ 'COLOR_B' ]
	COLOR = ( COLOR_R, COLOR_G, COLOR_B, 0xff)
	L0 = params[ 'L0' ]
	L1 = params[ 'L1' ]
	ANGLE = params[ 'ANGLE' ]
	WIDTH = params[ 'WIDTH' ]
	HEIGHT = params[ 'HEIGHT' ]

	image = stars.generate_image( WIDTH, HEIGHT, COLOR, L0, L1, ANGLE, TENTACLES_NUM )

	url = 'http://%s/detectors/%s/check' % ( addr, guid )
	try:
		headers = { 'User-Agent' : UserAgents.get() }
		files = { 'image' : image }
		r = requests.post( url, files=files, headers=headers )
		if r.status_code == 502:
			close(DOWN, "Service is down", "Nginx 502")
		if r.status_code != 200:
			close( MUMBLE, "Invalid HTTP response", "Invalid status code: %s %d" % ( url, r.status_code ) )	
	except Exception as e:
		 close(DOWN, "HTTP Error", "HTTP error: %s" % e)

	if flag != r.text:
		close( CORRUPT, "Service corrupted", "Flag does not match: %s" % r.text )
	close( OK )
Exemplo n.º 4
0
def get_chapterImages(bookID, chapterID):
    results = {}
    images = []

    headers = {'User-Agent': UserAgents.get_user_agent_phone()}
    chapterUrl = server + '/m{0}'.format(chapterID)
    html = requests.get(chapterUrl, headers=headers, timeout=10).text

    urlNum = '1'
    spare = re.search(',\'[0-9].*?jpg', html).group().split('|')
    if spare is not None and len(spare) > 4 and spare[
            len(spare) - 3].isdigit() and int(spare[len(spare) - 3]) < 50:
        urlNum = spare[len(spare) - 3]
    else:
        urlNum = re.search('[0-9]\\.[0-9]\\.[0-9]/[0-9]*/', html).group()
        urlNum = urlNum.split('/')[1]

    imgsList = re.findall('[0-9]+?_[0-9]+', html)
    imgsList.sort(key=lambda x: int(str(x).split('_')[0]))

    for img in imgsList:
        img_url = imgServer + '{0}/{1}/{2}/'.format(urlNum, bookID,
                                                    chapterID) + img + '.jpg'
        images.append(img_url)

    results['imgs'] = images
    return results
Exemplo n.º 5
0
def get(*args):
    addr = args[0]
    flag_id = args[1]
    flag = args[2]
    vuln = args[3]

    url = 'http://%s:1678%s/get?uuid=%s' % (addr, int(vuln) - 1, flag_id)
    headers = {'User-Agent': UserAgents.get()}
    try:
        r = requests.get(url, headers=headers)
        if r.status_code == 502:
            close(DOWN, "Service is down", "Nginx 502")
        if r.status_code != 200:
            close(
                MUMBLE, "Submit error",
                "Invalid status code: %s %d %s" % (url, r.status_code, r.text))

        j = json.loads(r.text)
        if 'mind' in j.keys():
            if j['mind'] != flag:
                close(CORRUPT, "Service corrupted",
                      "Invalid flag: %s" % j['mind'])
        else:
            close(CORRUPT, "Service corrupted",
                  "Invalid response: %s" % r.text)
    except Exception as e:
        close(DOWN, "HTTP Error", "HTTP error: %s" % e)

    close(OK)
Exemplo n.º 6
0
	def __init__(self, hostname, port=None):
		self.hostname = hostname
		self.port = '' if port is None else ':' + str(port)
		self.session = aiohttp.ClientSession(headers={
			'Referer': self.get_url(''), 
			'User-Agent': UserAgents.get()
		})
		self.signer = Signer()
Exemplo n.º 7
0
 def __init__(self, hostname, port=None, name='', user=None, password=None):
     self.hostname = hostname
     self.name = name
     self.port = '' if port is None else ':' + str(port)
     self.useragent = UserAgents.get()
     self.session = None
     if user is not None and password is not None:
         self.create_session(user, password)
Exemplo n.º 8
0
def put(*args):
	addr = args[0]
	flag_id = args[1]
	flag = args[2]

	COLOR_R = int( random.random() * 255 )
	COLOR_G = int( random.random() * 255 )
	COLOR_B = int( random.random() * 255 )
	L0 = random.uniform( 10.0, 30.0 )
	L1 = random.uniform( 10.0, 30.0 )
	ANGLE = random.uniform( 30.0, 90.0 )

	flag_defs = ""
	for i in range( len( flag ) ):
		s = flag[ i : ]
		byte = ord( s[:1] )
		flag_defs = flag_defs + ("-D F%d=%d " % ( i, byte ) )
	
	output_file = "/tmp/%s.bin" % flag_id
	defines = "-D COLOR_R=%s -D COLOR_G=%s -D COLOR_B=%s -D L0=%s -D L1=%s -D ANGLE=%s -D WIDTH=%s -D HEIGHT=%s -D TENTACLES_NUM=%s %s" % ( COLOR_R, COLOR_G, COLOR_B, L0, L1, ANGLE, WIDTH, HEIGHT, TENTACLES_NUM, flag_defs )
	driver = "Mali-400_r4p0-00rel1"
	core = "Mali-400"
	rev = "r0p0"
	cmd = "./malisc --fragment -d %s -c %s -r %s %s flag.frag -o %s > /dev/null 2> /dev/null" % ( driver, core, rev, defines, output_file )
	os.system( cmd )

	os.remove( output_file + ".prerotate" )

	shader_file_name = output_file + ".non-prerotate"
	shader_file = open( shader_file_name, 'rb' )
	shader_file.seek( 0, os.SEEK_END )
	shader_size = shader_file.tell()
	shader_file.seek( 0, os.SEEK_SET )

	detector = pack( 'i', shader_size ) + shader_file.read() + pack( 'ii', 8, 1 )
	
	flag_id = "" # reset flag id, we will build new, based on service response
	url = 'http://%s/detectors/add' % addr
	files = { 'detector': detector }
	headers = { 'User-Agent' : UserAgents.get() }
	try:
		r = requests.post(url, files=files, headers=headers )
		if r.status_code == 502:
			close(DOWN, "Service is down", "Nginx 502", shader_file_name)
		if r.status_code != 200:
			close( MUMBLE, "Submit error", "Invalid status code: %s %d" % ( url, r.status_code ), shader_file_name )	

		if not guid_regex.match( r.text ):
			close( CORRUPT, "Service corrupted", "Invalid guid received" )

		try:
			flag_id = json.dumps( { 'guid' : r.text[:-1], 'COLOR_R' : COLOR_R, 'COLOR_G' : COLOR_G, 'COLOR_B' : COLOR_B, 'L0' : L0, 'L1' : L1, 'ANGLE' : ANGLE, 'WIDTH' : WIDTH, 'HEIGHT' : HEIGHT } )
		except Exception as e:
			close(CORRUPT, "Service corrupted", "Service returns invalid guid: %s" % e, shader_file_name)			
	except Exception as e:
		 close(DOWN, "HTTP Error", "HTTP error: %s" % e, fileToRemove=shader_file_name)
	close(OK, flag_id, fileToRemove=shader_file_name)
Exemplo n.º 9
0
 def __init__(self, hostname, port=None, name=''):
     self.hostname = hostname
     self.name = name
     self.port = '' if port is None else ':' + str(port)
     cookie_jar = aiohttp.CookieJar(unsafe=True)
     self.session = aiohttp.ClientSession(cookie_jar=cookie_jar,
                                          headers={
                                              'Referer': self.get_url(''),
                                              'User-Agent':
                                              UserAgents.get(),
                                          })
Exemplo n.º 10
0
def getcodeinseturl(url, num_retries=2):
    myTime = time.strftime('%Y%m%d',
                           time.localtime(time.time() - 24 * 60 * 60))
    try:
        # print(myTime)
        dcap = dict(DesiredCapabilities.PHANTOMJS)
        dcap["phantomjs.page.settings.userAgent"] = UserAgents.getRandAgent()
        dcap["phantomjs.page.settings.resourceTimeout"] = "5000"
        dcap["phantomjs.page.settings.loadImages"] = False

        # print(url)
        # exit()
        driver = webdriver.PhantomJS(desired_capabilities=dcap,
                                     service_args=service_args)
        driver.implicitly_wait(5)
        driver.set_page_load_timeout(10)
        driver.set_script_timeout(10)
        driver.get(url)

        #print('dfasdfasdfadfasdfasdfasd')
        #exit()
        # print(driver.page_source)instwenzhang
        #print(u'============================打开搜狗微信公众号文章列表页面=============================')
        print(u"open public code page")

        bsObj = BeautifulSoup(driver.page_source, 'html.parser')
        _bool = isElementExist(bsObj, 'weui_media_title')

        if _bool == False:
            driver.quit()
            (url)
            return

        urlList = driver.find_elements_by_class_name('weui_media_title')
        tmpurllist = []
        for i in urlList:
            tmpurllist.append(i.get_attribute('hrefs'))

        #print(u'=============================返回微信公众号文章列表Link========================')
        print(u"return public code article list")
        return tmpurllist

    except Exception as e:
        print(e)
        #print(u'-----------------------------------文章异常处理')
        print(u"artilce note")
        tmpurllist = []
        if num_retries > 0:
            return getcodeinseturl(url, num_retries - 1)
Exemplo n.º 11
0
def upload_object(addr, tobject):
    url = 'http://%s:9007/object' % (addr)
    headers = {'User-Agent': UserAgents.get()}

    try:
        r = requests.put(url, headers=headers, json=tobject)

        if r.status_code != 200:
            close(MUMBLE, "Submit error",
                  "Invalid status code: %s %d" % (url, r.status_code))

        return r.content.decode("UTF-8")

    except Exception as e:
        close(DOWN, "HTTP Error", "HTTP error: %s" % e)
Exemplo n.º 12
0
def get_objects(addr, agentKey):
    url = 'http://%s:9007/objects?AgentKey=%s' % (addr, agentKey)
    headers = {'User-Agent': UserAgents.get()}
    try:
        r = requests.get(url, headers=headers)

        if r.status_code != 200:
            close(MUMBLE, "Submit error",
                  "Invalid status code: %s %d" % (url, r.status_code))

        str = r.content.decode("UTF-8")
        return json.loads(str)

    except Exception as e:
        close(DOWN, "HTTP Error", "HTTP error: %s" % e)
Exemplo n.º 13
0
def register_agent(addr):
    url = 'http://%s:9007/agent' % (addr)
    headers = {'User-Agent': UserAgents.get()}
    agent = {"AgentName": "TestName"}
    try:
        r = requests.post(url, headers=headers, json=agent)

        if r.status_code != 200:
            close(MUMBLE, "Submit error",
                  "Invalid status code: %s %d" % (url, r.status_code))

        str = r.content.decode("UTF-8")
        return json.loads(str)

    except Exception as e:
        close(DOWN, "HTTP Error", "HTTP error: %s" % e)
Exemplo n.º 14
0
def put(*args):
    addr = args[0]
    flag_id = args[1]
    flag = args[2]
    minidumpFilePath = "/tmp/" + flag_id + ".dmp"

    # crash the binary and generate minidump
    os.system('./%s %s %s' % (SERVICE_NAME, flag, minidumpFilePath))

    # zip minidump file
    inMemoryZip = BytesIO()
    zf = zipfile.ZipFile(inMemoryZip, mode='w')
    try:
        zf.write(minidumpFilePath, arcname='%s.dmp' % flag_id)
    except Exception as e:
        close(CHECKER_ERROR, "ZIP error", "Unknown error: %s" % e,
              minidumpFilePath)
    zf.close()
    inMemoryZip.seek(0)

    # submit report
    url = 'http://%s/submit' % addr
    files = {'dump_zip_file': inMemoryZip.read()}
    headers = {
        'User-Agent': UserAgents.get(),
        'Service-Name': SERVICE_NAME,
        'GUID': flag_id
    }
    try:
        r = requests.post(url, files=files, headers=headers)
        if r.status_code == 502:
            close(DOWN, "Service is down", "Nginx 502", minidumpFilePath)
        if r.status_code != 200:
            close(MUMBLE, "Submit error",
                  "Invalid status code: %s %d" % (url, r.status_code),
                  minidumpFilePath)
        try:
            r_json = r.json()
            if r_json['status'] != 'ok':
                close(MUMBLE, "Submit error", "Can not put flag",
                      minidumpFilePath)
        except Exception as e:
            close(CORRUPT, "Service corrupted",
                  "Service returns invalid json: %s" % e, minidumpFilePath)
    except Exception as e:
        close(DOWN, "HTTP Error", "HTTP error: %s" % e, minidumpFilePath)
    close(OK, minidumpFilePath=minidumpFilePath)
Exemplo n.º 15
0
    def request(self, method, relative_url, fun, **kwargs):
        data = None
        headers = {"User-Agent": UserAgents.get()}
        if "data" in kwargs:
            headers["Content-Type"] = 'application/octet-stream'
            data = kwargs["data"]
        elif "json" in kwargs:
            headers["Content-Type"] = 'application/json; charset=utf8'
            data = kwargs["json"]

        url = "http://%s/%s" % (self.addr, relative_url)
        request = Request(url, method=method, data=data, headers=headers)
        with urlopen(request) as response:
            if (response.status != 200):
                raise CheckerException("Recieved status %d on request %s" %
                                       (response.status, url))
            return fun(response.read())
Exemplo n.º 16
0
def download(url, num_retries=2, user_agent=''):
    try:
        dcap = dict(DesiredCapabilities.PHANTOMJS)
        # dcap["phantomjs.page.settings.userAgent"] = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53  (KHTML, like Gecko) Chrome/15.0.87")
        dcap["phantomjs.page.settings.userAgent"] = UserAgents.getRandAgent()
        dcap["phantomjs.page.settings.resourceTimeout"] = "5000"
        dcap["phantomjs.page.settings.loadImages"] = False

        driver = webdriver.PhantomJS(desired_capabilities=dcap,
                                     service_args=service_args)
        driver.implicitly_wait(5)
        driver.set_page_load_timeout(10)
        driver.set_script_timeout(10)
        driver.get(url)
        # print(driver.page_source)
        #print(u'=====================================打开搜狗搜索页面=====================================')

        bsObj = BeautifulSoup(driver.page_source, 'html.parser')

        #判断是否有此公众号和是否ip限制,如果找不到元素那么抛出异常
        wx_rb = isElementExist(bsObj, 'wx-rb')

        if wx_rb == False:
            driver.quit()
            download(url)
            return

        #返回页面HTML
        html = driver.page_source.encode('utf-8')
        #print(u"=====================================返回公众号搜索页面=====================================")
        return html
    except Exception as e:
        print(e)
        # 抛出的异常接住,再次调用
        # n = num_retries-1
        #print(u'-------------------------------------公众号异常处理')
        html = None
        if num_retries > 0:
            return download(url, num_retries - 1)
Exemplo n.º 17
0
def add_ship(addr, bin_file):
    pos_x = int(random.uniform(-2000000, 2000000))
    pos_z = int(random.uniform(-2000000, 2000000))
    rot_y = 0  #random.uniform( 0, 3.1415926 );

    url = 'http://%s:8080/add_ship?pos_x=%f&pos_z=%f&rot_y=%f' % (addr, pos_x,
                                                                  pos_z, rot_y)
    files = {'flag_shader': open(bin_file, 'rb').read()}
    headers = {'User-Agent': UserAgents.get()}
    try:
        r = requests.post(url, files=files, headers=headers)
        if r.status_code == 502:
            close(DOWN, "Service is down", "Nginx 502", bin_file)
        if r.status_code != 200:
            close(MUMBLE, "Submit error",
                  "Invalid status code: %s %d" % (url, r.status_code),
                  bin_file)

        if not guid_regex.match(r.text):
            close(CORRUPT, "Service corrupted", "Invalid guid received")
    except Exception as e:
        close(DOWN, "HTTP Error", "HTTP error: %s" % e, fileToRemove=bin_file)

    return json.dumps({'x': pos_x, 'z': pos_z, 'ry': rot_y})
Exemplo n.º 18
0
def DownloadSubAsBytesIO(domain, url, referer=None, cookies=None):
    """ Download a url, and return as file-like object (Bytes). Use the referer
        parameter if the site require such parameter in the header in order to
        download the file
    """

    # urlopen accepts only a url, so we need to join the domain and url
    # into a one string. Also, the type is needed, therefor the "http://"
    full_url = ""
    if url.startswith("http://"):
        full_url = url
    elif url.startswith("www."):
        full_url = "http://" + url
    else:
        full_url = "http://%s" % domain + url
    WriteDebug("Getting file: %s" % full_url)

    file_content = BytesIO()
    # Set the referer to be the domain because some site will avoid our request
    # if we don't do that
    request_headers = {
        "User-Agent": UserAgents.getAgent(),
        # Set the referer to be the domain if None passed
        "Referer": referer or domain,
    }
    if cookies:
        request_headers.update({"Cookie": cookies})

    file_request = Request(full_url, headers=request_headers)
    try:
        url_opened = urlopen(file_request)
        file_content.write(url_opened.read())
    except Exception as eX:
        WriteDebug("Failed getting file: %s->%s" % (full_url, eX))
        return None
    return file_content
Exemplo n.º 19
0
def get_bookInfo(bookID):
    results = {}
    headers = {'User-Agent': UserAgents.get_user_agent_phone()}
    html = requests.get('{0}/{1}'.format(server, bookID), headers=headers).text
    soup = BeautifulSoup(html, 'html.parser')

    results['title'] = soup.find('p', class_='detail-main-title').text
    results['author'] = soup.find(
        'p', class_='detail-main-subtitle').find('a').find('span').text
    results['content'] = soup.find(
        'p', class_='detail-main-content').text + soup.find(
            'p', class_='detail-main-content').text
    results['imgUrl'] = soup.find('img', class_='detail-bar-bg')['src']

    detailList = []
    for item in soup.find('div', class_='detail-list').find_all('a'):
        detail = {}
        detail['url'] = item['href']
        detail['name'] = item.text.strip()
        detailList.append(detail)
    results['list'] = detailList
    results['list'].reverse()

    return results
Exemplo n.º 20
0
def get(*args):
    addr = args[0]
    flag_id = args[1]
    flag = args[2]
    url = 'http://%s/%s/get' % (addr, flag_id)
    try:
        headers = {'User-Agent': UserAgents.get()}
        r = requests.get(url, headers=headers)
        if r.status_code == 502:
            close(DOWN, "Service is down", "Nginx 502")
        if r.status_code != 200:
            close(MUMBLE, "Invalid HTTP response",
                  "Invalid status code: %s %d" % (url, r.status_code))
    except Exception as e:
        close(DOWN, "HTTP Error", "HTTP error: %s" % e)

    try:
        if int(r.headers['Content-Length']) > 50000:  # tested
            close(CORRUPT, "Service corrupted", "Content is too big")
    except Exception as e:
        close(CORRUPT, "Service corrupted",
              "Something wrong with content length: %s" % e)

    # tested
    try:
        zf = zipfile.ZipFile(BytesIO(r.content))
    except Exception as e:
        close(CORRUPT, "Service corrupted", "Invalid zip file: %s" % e)

    if len(zf.namelist()) > 1:  # tested
        close(CORRUPT, "Service corrupted",
              "Invalid content, more than one file in zip")

    dmp_name = "%s.dmp" % flag_id
    dmp_path = "/tmp/%s" % dmp_name
    if not dmp_name in zf.namelist():  # tested
        close(CORRUPT, "Service corrupted",
              "Invalid content, there is no minidump file in zip")
    try:
        dmp = zf.read(dmp_name)
        open(dmp_path, 'wb').write(dmp)
    except Exception as e:
        close(CHECKER_ERROR, "Evil checker", "INTERNAL ERROR: %s" % e,
              dmp_path)

    # tested
    try:
        stackwalk = subprocess.check_output(
            './minidump_stackwalk -m %s symbols/ 2>/dev/null' % dmp_path,
            shell=True)
    except subprocess.CalledProcessError as e:
        close(CORRUPT, "Service corrupted", "Invalid minidump file: %s" % e,
              dmp_path)

    parser = StackWalkParser()
    parser.parse(stackwalk.decode())

    if len(parser.crash_thread_stack) < 17:  # not tested
        close(
            CORRUPT, "Service corrupted",
            "Invalid minidump file, callstack is too short %s" %
            parser.crash_thread_stack, dmp_path)
    if len(parser.crash_thread_stack) > 32:  # not tested
        close(CORRUPT, "Service corrupted",
              "Invalid minidump file, callstack is too long", dmp_path)
    if parser.crash_thread_stack[16][
            "signature"] != 'StartFlagProcessing()':  # tested
        close(
            CORRUPT, "Service corrupted",
            "Invalid minidump file, invalid callstack %s" %
            parser.crash_thread_stack, dmp_path)

    first_part_flag = ''
    for i in reversed(range(0, 16)):
        signature = parser.crash_thread_stack[i]["signature"]
        result = re.match(r"_(\w)\(\)", signature)
        if not result:  # tested
            close(
                CORRUPT, "Service corrupted",
                "Invalid minidump file, invalid signature in callstack %s" %
                signature, dmp_path)
        first_part_flag = first_part_flag + result.group(1)

    prefix = b'HERE IS THE REST OF YOUR FLAG'
    prefixPos = dmp.find(prefix)
    if prefixPos == -1:
        close(CORRUPT, "Service corrupted",
              "Invalid minidump file, cant find second part of the flag",
              dmp_path)
    flagPos = prefixPos + len(prefix) + 1
    try:  # tested
        second_part_flag = (dmp[flagPos:flagPos + 16]).decode()
    except Exception as e:
        close(CORRUPT, "Service corrupted",
              "Can not get second part of the flag: %s" % e, dmp_path)

    restored_flag = first_part_flag + second_part_flag
    if flag != restored_flag:  # tested
        close(CORRUPT, "Service corrupted",
              "Flag does not match: %s" % restored_flag, dmp_path)
    close(OK, minidumpFilePath=dmp_path)
Exemplo n.º 21
0
def check(*args):
	addr = args[0]

	random.seed()
	X_GR = random.uniform( 2.0, 10.0 )
	Y_GR = random.uniform( 2.0, 10.0 )
	X_LS = random.uniform( -10.0, -2.0 )
	Y_LS = random.uniform( -10.0, -2.0 )

	A_X_GR = random.uniform( 2.0, 10.0 )
	A_Y_GR = random.uniform( 2.0, 10.0 )
	A_X_LS = random.uniform( -10.0, -2.0 )
	A_Y_LS = random.uniform( -10.0, -2.0 )

	B_X_GR = random.uniform( 2.0, 10.0 )
	B_Y_GR = random.uniform( 2.0, 10.0 )
	B_X_LS = random.uniform( -10.0, -2.0 )
	B_Y_LS = random.uniform( -10.0, -2.0 )

	VARIANT0 = random.randint( 0, 1 )
	VARIANT1 = random.randint( 0, 1 )
	VARIANT2 = random.randint( 0, 1 )

	R = random.randint( 48, 90 )
	G = random.randint( 48, 90 )
	B = random.randint( 48, 90 )
	A = random.randint( 48, 90 )

	WH = [ 8, 16, 32, 64, 128 ]
	W = WH[ random.randint( 0, 4 ) ]
	H = WH[ random.randint( 0, 4 ) ]

	m = hashlib.md5()
	m.update( ("%f" % time.time() ).encode() )
	output_file = "/tmp/%s" % m.hexdigest()
	defines = "-D X_GR=%f -D Y_GR=%f -D X_LS=%f -D Y_LS=%f " % ( X_GR, Y_GR, X_LS, Y_LS )
	defines = defines + "-D A_X_GR=%f -D A_Y_GR=%f -D A_X_LS=%f -D A_Y_LS=%f " % (A_X_GR, A_Y_GR, A_X_LS, A_Y_LS )
	defines = defines + "-D B_X_GR=%f -D B_Y_GR=%f -D B_X_LS=%f -D B_Y_LS=%f " % (B_X_GR, B_Y_GR, B_X_LS, B_Y_LS )
	defines = defines + "-D VARIANT0=%d -D VARIANT1=%d -D VARIANT2=%d " % ( VARIANT0, VARIANT1, VARIANT2 )
	defines = defines + "-D R=%d -D G=%d -D B=%d -D A=%d -D WIDTH=%d -D HEIGHT=%d " %( R, G, B, A, W, H )
	driver = "Mali-400_r4p0-00rel1"
	core = "Mali-400"
	rev = "r0p0"
	cmd = "./malisc --fragment -d %s -c %s -r %s %s check.frag -o %s > /dev/null 2> /dev/null" % ( driver, core, rev, defines, output_file )
	os.system( cmd )
	os.remove( output_file + ".prerotate" )

	shader_file_name = output_file + ".non-prerotate"
	shader_file = open( shader_file_name, 'rb' )
	shader_file.seek( 0, os.SEEK_END )
	shader_size = shader_file.tell()
	shader_file.seek( 0, os.SEEK_SET )

	detector = pack( 'i', shader_size ) + shader_file.read() + pack( 'ii', W, H )
	
	guid = ""
	url = 'http://%s/detectors/add' % addr
	files = { 'detector': detector }
	headers = { 'User-Agent' : UserAgents.get() }
	try:
		r = requests.post(url, files=files, headers=headers )
		if r.status_code == 502:
			close(DOWN, "Service is down", "Nginx 502", shader_file_name)
		if r.status_code != 200:
			close( MUMBLE, "Submit error", "Invalid status code: %s %d" % ( url, r.status_code ), shader_file_name )	

		if not guid_regex.match( r.text ):
			close( CORRUPT, "Service corrupted", "Invalid guid received" )

		guid = r.text[:-1]
	except Exception as e:
		 close(DOWN, "HTTP Error", "HTTP error: %s" % e, fileToRemove=shader_file_name)

	os.remove( shader_file_name )

	#
	WH = [ 64, 128, 256 ]
	W = WH[ random.randint( 0, 2 ) ]
	H = WH[ random.randint( 0, 2 ) ]
	image = stars.generate_image( W, H, ( 0xfe, 0xae, 0xda, 0xff), 10.0, 10.0, 50, random.randint( 2, 5 ) )

	url = 'http://%s/detectors/%s/check' % ( addr, guid )
	try:
		headers = { 'User-Agent' : UserAgents.get() }
		files = { 'image' : image }
		r = requests.post( url, files=files, headers=headers )
		if r.status_code == 502:
			close(DOWN, "Service is down", "Nginx 502")
		if r.status_code != 200:
			close( MUMBLE, "Invalid HTTP response", "Invalid status code: %s %d" % ( url, r.status_code ) )	
	except Exception as e:
		 close(DOWN, "HTTP Error", "HTTP error: %s" % e)

	if len( r.content ) < 4:
		close( CORRUPT, "Service corrupted" )

	for i in range( 0, len(r.content), 4 ):
		cr = r.content[ i + 0 ]
		cg = r.content[ i + 1 ]
		cb = r.content[ i + 2 ]
		ca = r.content[ i + 3 ]
		if( abs( cr - R ) > 2 or abs( cg - G ) > 2 or abs( cb - B ) > 2 or abs( ca - A ) > 2 ):
			close( CORRUPT, "Service corrupted" )

	close(OK)
Exemplo n.º 22
0
def PerformRequest(domain, url, data="", type=HttpRequestTypes.GET, more_headers="", retry=False, is_redirection=False):
    """ 
        Performs http requests. We are using fake user-agents. Use the data arg
        in case you send a "POST" request. Also, you can specify more headers 
        by supplying a dict in the more_headers arg

        Url should start with "/". If not, the function adds it.
    """
    import UserAgents

    response = ""
    if not url.startswith("/"):
        url = "/" + url
    try:
        httpcon = httplib.HTTPConnection(domain, timeout=10)

        headers = {}
        # Each packet we send will have this params (good for hiding)
        if not retry:
            headers = {
                "Connection": r"keep-alive",
                "User-Agent": UserAgents.getAgent(),
                "X-Requested-With": r"XMLHttpRequest",
                "Content-Type": r"application/x-www-form-urlencoded",
                "Accept-Charset": r"utf-8;q=0.7,*;q=0.3",
                "Accept-Language": r"en-US,en;q=0.8",
                "Cache-Control": r"max-age=0",
            }
        else:
            # The Fake User Agent
            headers = {"User-Agent": UserAgents.getAgent()}

        # In case of specifiyng more headers, we add them
        if len(more_headers):
            headers.update(more_headers)

        WriteDebug("Sending request for: %s" % (domain + url))
        got_respone = None
        response = None
        # Try 3 times.
        for error_count in range(1, 4):
            try:
                # Before each request, we need to try and connect, because
                # we're probably not connected (that's way the exception that
                # we're catching was raised).
                httpcon.connect()
                httpcon.request(type, url, str(data), headers)
                got_response = httpcon.getresponse()
                response = got_response.read()
                # If we got the response, break the loop.
                break
            except Exception as error:
                WriteDebug("Failed sending the request for the %d time: %s" % (error_count, error))
                # Sleep some time before we request it again.
                sleep(2)
                # Close it (we're calling connect() again inside the try).
                httpcon.close()

        # In order to avoid decoding problems, we just convert the bytes to
        # str. The problem is that when we do that, the str preserve the
        # preceding 'b' of the bytes type, so we remove it, and the single
        # quotes and the start and the end of the string
        try:
            response = response.decode("utf-8", errors="replace")
        except:
            response = str(response)[2:-1]
        response = response.replace("\r", "").replace("\n", "")
        # When we get and empty response, it might be a sign that we got a
        # redirection and therefor we check the current url against the
        # requested one. Also, if is_redirection is true, it means that we
        # already got redirection, and therefor we stop the procedure
        if not response and not is_redirection:
            new_url = got_response.msg.dict["location"]
            if url not in new_url:
                WriteDebug("Got Redirection: %s->%s" % (url, new_url))
                # Because the location gives us the full address including the
                # protocol and the domain, we remove them in order to get the
                # relative url
                new_url = new_url.replace("http://", "").replace(domain, "")
                return PerformRequest(domain, new_url, is_redirection=True)
    except Exception as eX:
        WriteDebug("Failed Getting: %s->%s [%s]" % (domain, url, eX))

    return response
Exemplo n.º 23
0
def draw(addr, pos_json):
    params = json.loads(pos_json)

    pos_x = params['x'] + 0.4
    pos_y = 1.6
    pos_z = params['z'] - 0.3
    aimpos_x = pos_x
    aimpos_y = pos_y
    aimpos_z = params['z']

    url = 'http://%s:8080/draw?pos_x=%f&pos_y=%f&pos_z=%f&aimpos_x=%f&aimpos_y=%f&aimpos_z=%f' % (
        addr, pos_x, pos_y, pos_z, aimpos_x, aimpos_y, aimpos_z)
    #print( url )
    try:
        headers = {'User-Agent': UserAgents.get()}
        r = requests.get(url, headers=headers)
        if r.status_code == 502:
            close(DOWN, "Service is down", "Nginx 502")
        if r.status_code != 200:
            close(MUMBLE, "Invalid HTTP response",
                  "Invalid status code: %s %d" % (url, r.status_code))
    except Exception as e:
        close(DOWN, "HTTP Error", "HTTP error: %s" % e)

    try:
        stream = io.BytesIO(r.content)
        img = Image.open(stream)

        if img.size[0] != 128 or img.size[0] != 128:
            close(CORRUPT, "Service corrupted",
                  "Invalid image size %ux%u" % (img.size[0], img.size[1]))

        left = -1
        right = -1
        pixels = img.load()
        RED = (255, 0, 0, 255)

        for y in range(1, 127):
            for x in range(1, 127):
                if pixels[x, y] != RED and pixels[x + 1,
                                                  y] == RED and left == -1:
                    #print( "left", x, y, pixels[ x, y ], pixels[ x + 1, y ] )
                    left = x
                if pixels[x, y] == RED and pixels[x + 1,
                                                  y] != RED and right == -1:
                    #print( "right", x, y, pixels[ x, y ], pixels[ x + 1, y ] )
                    right = x

        top = -1
        bottom = -1
        for x in range(1, 127):
            for y in range(1, 127):
                if pixels[x, y] != RED and pixels[x,
                                                  y + 1] == RED and top == -1:
                    #print( "top", x, y, pixels[ x, y ], pixels[ x, y + 1 ] )
                    top = y
                if pixels[x, y] == RED and pixels[x, y +
                                                  1] != RED and bottom == -1:
                    #print( "bottom", x, y, pixels[ x, y ], pixels[ x, y + 1 ] )
                    bottom = y

        width = right - left
        height = bottom - top
        stepX = width / 6
        stepY = height / 4

        startX = left + stepX * 1.5
        startY = top + stepY * 1.5

        x = startX
        y = startY
        payload = []
        for iy in range(0, 2):
            for ix in range(0, 4):
                p = pixels[int(x), int(y)]
                payload.append(p)
                x += stepX
            y += stepY
            x = startX

        return payload

    except Exception as e:
        close(CORRUPT, "Service corrupted", "Invalid response: %s" % e)