def req(self):
        from base64 import encodestring as es
        
        url = "/%s%s/%s.%s" % (self.uri, self.model, self.method, self.fmt)
        self.last_req = {'url' : url, 'args' : self.args}
        
        if self.action == "GET" and len(self.args) > 0:
            url = "%s?%s" % (url, urllib.urlencode(self.args))
            self.args = None
        
        if self.args is not None:
            self.args = urllib.urlencode(self.args)
        
        if self.port == "http":
            ws = httplib.HTTPConnection(self.host, timeout=120)
        elif self.port == "https":
            ws = httplib.HTTPSConnection(self.host, timeout=120)
        else:
            raise Exception("Protocol '%s' unknown or unsupported." % (port))
        
        auth = es('%s:%s' % (self.user, self.pasw)).replace('\n', '')
        
        headers = {"Authorization" : "Basic %s" % auth}
        
	try:
            ws.request(self.action, url, self.args, headers)
	except:
	    raise Exception("Unable to establish a connection (Action: %s, URL: %s, Args: %s, Headers: %s, URI: %s, Model: %s, Method: %s)" % (self.action, url, self.args, headers, self.uri, self.model, self.method))
        
        resp = ws.getresponse()
        
        data = resp.read()
        ws.close()
        
        return BlestaResponse(data, resp.status)
Example #2
0
    def get(self):
        logger.debug('Handle %s request to %s', self.request.method,
                     self.request.uri)

        def handle_response(response):
            if (response.error and not
                    isinstance(response.error, tornado.httpclient.HTTPError)):
                self.set_status(500)
                self.write('Internal server error:\n' + str(response.error))
            else:
                self.set_status(response.code, response.reason)
                self._headers = tornado.httputil.HTTPHeaders() # clear tornado default header

                for header, v in response.headers.get_all():
                    if header not in ('Content-Length', 'Transfer-Encoding', 'Content-Encoding', 'Connection'):
                        self.add_header(header, v) # some header appear multiple times, eg 'Set-Cookie'

                if response.body:
                    self.set_header('Content-Length', len(response.body))
                    self.write(response.body)
                    #print 11
            self.finish()

        body = self.request.body

        if not body:
            body = ""
        try:
            if 'Proxy-Connection' in self.request.headers:
                del self.request.headers['Proxy-Connection']


            fetch_request(
                self.request.uri, handle_response,
                method=self.request.method, body=body,
                headers=self.request.headers, follow_redirects=False,
                allow_nonstandard_methods=True)
            request_dict={}
            request_dict['uri']=self.request.uri
            request_dict['method']=self.request.method
            request_dict['headers']=dict(self.request.headers)
            request_dict['body']=body
            request_dict['postdata'] = request_dict['body']
            url=urlparse(request_dict['uri'])
            request_dict['host']= url.netloc
            request_dict['url']= request_dict['uri'].split(url.netloc)[-1]
            request_dict['hash']= self.get_hash(request_dict['host'], request_dict['postdata'])
            #print "="*10, "Got one:", request_dict
            b64req =  es(json.dumps(request_dict))
            self.insert_redis(b64req, request_dict['host'], request_dict['host'])

        except tornado.httpclient.HTTPError as e:
            if hasattr(e, 'response') and e.response:
                handle_response(e.response)
            else:
                self.set_status(500)
                self.write('Internal server error:\n' + str(e))
                self.finish()
Example #3
0
def updaterequest(reqhash, taskid, sqlmapapi, sqlidata):
    oldrequest = json.loads(ds(r.hget("request", reqhash)))
    oldrequest["taskid"] = taskid
    oldrequest["sqlmapapi"] = sqlmapapi
    oldrequest["dbms"] = sqlidata[0]['value'][0]['dbms']
    oldrequest["os"] = sqlidata[0]['value'][0]['os']
    oldrequest["parameter"] = sqlidata[0]['value'][0]['parameter']
    oldrequest["sqlititle"] = sqlidata[0]['value'][0]['data']['1']['title']
    b64req = es(json.dumps(oldrequest))
    r.hset("request", reqhash, b64req)
Example #4
0
    def open(self, req):
        import urllib2

        # print 'DEBUG: Abriendo', url

        if isinstance(req, str):
            req = urllib2.Request(req)

        intento = 0
        handle = None
        while handle is None:
            intento += 1
            try:
                handle = urllib2.urlopen(req)
            except urllib2.URLError, e:
                if intento > self.maxintentos:
                    raise DownloadError, ("Máximo número de intentos excedido", None)

                if not hasattr(e, "code"):
                    raise DownloadError, ("No se pudo conectar al servidor", e)

                if e.code == 401:
                    if intento > 1:
                        self.usuario = self.clave = None
                        print " - Intento #%d" % intento

                    if not (self.interactivo or (self.usuario and self.clave)):
                        raise DownloadError, ("No se puede autentificar en la web", None)

                    if not self.usuario:
                        self.usuario = raw_input("Usuario: ")
                    if not self.clave:
                        import getpass

                        self.clave = getpass.getpass("Clave para %s: " % self.usuario)

                    from base64 import encodestring as es

                    req.add_header("Authorization", "Basic " + es("%s:%s" % (self.usuario, self.clave)).strip())
                else:
                    raise DownloadError, ("No se pudo descargar la url", e)
Example #5
0
    def req(self):
        from base64 import encodestring as es

        url = "/%s%s/%s.%s" % (self.uri, self.model, self.method, self.fmt)
        self.last_req = {'url': url, 'args': self.args}

        if self.action == "GET" and len(self.args) > 0:
            url = "%s?%s" % (url, urllib.urlencode(self.args))
            self.args = None

        if self.args is not None:
            self.args = urllib.urlencode(self.args)

        if self.port == "http":
            ws = httplib.HTTPConnection(self.host, timeout=120)
        elif self.port == "https":
            ws = httplib.HTTPSConnection(self.host, timeout=120)
        else:
            raise Exception("Protocol '%s' unknown or unsupported." % (port))

        auth = es('%s:%s' % (self.user, self.pasw)).replace('\n', '')

        headers = {"Authorization": "Basic %s" % auth}

        try:
            ws.request(self.action, url, self.args, headers)
        except:
            raise Exception(
                "Unable to establish a connection (Action: %s, URL: %s, Args: %s, Headers: %s, URI: %s, Model: %s, Method: %s)"
                % (self.action, url, self.args, headers, self.uri, self.model,
                   self.method))

        resp = ws.getresponse()

        data = resp.read()
        ws.close()

        return BlestaResponse(data, resp.status)