def isHandshakeSuccessful(self, timeout=1.0): """ Wait to receive "handshake successful" event until the end of the timeout. @param timeout: time to wait response in second (default=1s) @type timeout: float @return: an event matching with the template or None otherwise @rtype: templatemessage """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) tpl_rsp = TestTemplatesLib.TemplateMessage() if self.cfg['agent-support']: layer_agent = TestTemplatesLib.TemplateLayer('AGENT') layer_agent.addKey(name='name', data=self.cfg['agent']['name']) layer_agent.addKey(name='type', data=self.cfg['agent']['type']) tpl_rsp.addLayer(layer_agent) tpl_rsp.addLayer(AdapterIP.ip(more=AdapterIP.received())) tpl_rsp.addLayer(AdapterTCP.tcp(more=AdapterTCP.received())) if self.cfg['ssl-support']: tpl_rsp.addLayer(AdapterSSL.ssl(more=AdapterSSL.received())) tpl_rsp.addLayer(AdapterHTTP.response()) tpl_rsp.addLayer(templates.ws(more=templates.handshake_ok())) return self.received(expected=tpl_rsp, timeout=timeout)
def hasReceivedHttpResponse(self, httpCode="200", httpPhrase="OK", headers=None, timeout=1.0): """ Wait to receive "http response" until the end of the timeout. @param httpCode: http code (default=200) @type httpCode: string @param httpPhrase: http phrase (default=OK) @type httpPhrase: string @param timeout: time to wait in seconds (default=1s) @type timeout: float @return: http response @rtype: template """ TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout) tpl = TestTemplatesLib.TemplateMessage() if self.cfg['agent-support']: layer_agent= TestTemplatesLib.TemplateLayer('AGENT') layer_agent.addKey(name='name', data=self.cfg['agent']['name'] ) layer_agent.addKey(name='type', data=self.cfg['agent']['type'] ) tpl.addLayer( layer_agent ) tpl.addLayer( AdapterIP.ip( more=AdapterIP.received() ) ) tpl.addLayer( AdapterTCP.tcp(more=AdapterTCP.received()) ) if self.ADP_HTTP.tcp().cfg['ssl-support']: tpl.addLayer( AdapterSSL.ssl(more=AdapterSSL.received()) ) tpl.addLayer( AdapterHTTP.response( version="HTTP/1.1", code=httpCode, phrase=httpPhrase, headers=headers ) ) return self.hasReceivedResponse(expected=tpl, timeout=timeout)
def __init__(self, parent, bindIp='', bindPort=0, destinationIp='127.0.0.1', proxyIp='', proxyPort=3128, proxyHost='', proxyEnabled=False, destinationPort=80, destinationHost='', name=None, debug=False, sslSupport=False, sslVersion=AdapterSSL.SSLv23, agentSupport=False, agent=None, shared=False, logEventSent=True, logEventReceived=True): """ Adapter for the websocket protocol according to the rfc 6455 Ssl and proxy support @param parent: parent testcase @type parent: testcase @param bindIp: source ip (default='') @type bindIp: string @param bindPort: source port (default=0) @type bindPort: integer @param destinationIp: destination ip @type destinationIp: string @param destinationPort: destination port (default: port 80) @type destinationPort: integer @param destinationHost: destination host (dns resolution) @type destinationHost: string @param proxyIp: proxy ip @type proxyIp: string @param proxyPort: proxy port @type proxyPort: integer @param proxyHost: proxy host (automatic dns resolution) @type proxyHost: string @param proxyEnabled: True to support proxy (default=False) @type proxyEnabled: boolean @param sslSupport: activate SSL channel (default=False) @type sslSupport: boolean @param sslVersion: SutAdapters.SSL.SSLv2 | SutAdapters.SSL.SSLv23 (default) | SutAdapters.SSL.SSLv3 | SutAdapters.SSL.TLSv1 | SutAdapters.SSL.TLSv11 | SutAdapters.SSL.TLSv12 @type sslVersion: strconstant @param name: adapter name used with from origin/to destination (default=None) @type name: string/none @param debug: active debug mode (default=False) @type debug: boolean @param agentSupport: agent support to use a remote socket (default=False) @type agentSupport: boolean @param agent: agent to use when this mode is activated @type agent: string/None @param shared: shared adapter (default=False) @type shared: boolean """ # init adapter TestAdapterLib.Adapter.__init__(self, name=__NAME__, parent=parent, debug=debug, realname=name, agentSupport=agentSupport, agent=agent, caller=TestAdapterLib.caller(), agentType=AGENT_TYPE_EXPECTED) self.logEventSent = logEventSent self.logEventReceived = logEventReceived self.wsKey = None self.wsHanshakeSuccess = False self.wsMaxPayloadSize = codec.WEBSOCKET_MAX_BASIC_DATA1024 self.buf = '' self.cfg = {} self.cfg['dest-ip'] = destinationIp self.cfg['dest-port'] = destinationPort self.cfg['ssl-support'] = sslSupport # agent support self.cfg['agent-support'] = agentSupport if agentSupport: self.cfg['agent'] = agent self.cfg['agent-name'] = agent['name'] self.__checkConfig() self.ADP_HTTP = AdapterHTTP.Client(parent=parent, bindIp=bindIp, bindPort=bindPort, name=name, destinationIp=destinationIp, destinationPort=destinationPort, destinationHost=destinationHost, proxyIp=proxyIp, proxyPort=proxyPort, proxyHost=proxyHost, proxyEnabled=proxyEnabled, socketTimeout=300.0, socketFamily=4, websocketMode=True, saveContent=False, httpVersion='HTTP/1.1', httpAgent='ExtensiveTesting', httpConnection='close', httpChunckedData=False, sslSupport=sslSupport, sslVersion=sslVersion, checkCert='No', debug=debug, logEventSent=False, logEventReceived=False, truncateBody=False, agentSupport=agentSupport, agent=agent, shared=shared, strictMode=False) self.ADP_HTTP.handleIncomingResponse = self.handleIncomingHttpResponse self.ADP_HTTP.onWebsocketIncomingData = self.onWebsocketIncomingData self.wsCodec = codec.Codec(parent=self)
def __init__(self, parent, name=None, bindIp='', bindPort=0, destinationIp='127.0.0.1', destinationPort=80, debug=False, logEventSent=True, logEventReceived=True, xmlns0='http://schemas.xmlsoap.org/soap/envelope/', xmlns1='', xmlns2='', xmlns3='', xmlns4='', xmlns5='', xmlns6='', xmlns7='', xmlns8='', httpAgent='ExtensiveTesting', httpVersion='HTTP/1.1', httpConnection='close', agentSupport=False, agent=None, shared=False, httpAuthentication=False, proxyIp='', proxyPort=3128, proxyHost='', proxyEnabled=False, proxyType=AdapterTCP.PROXY_HTTP, verbose=True, sslSupport=False, sslVersion=AdapterSSL.SSLv23, checkCert=AdapterSSL.CHECK_CERT_NO, caCerts=None, checkHost=False, hostCn=None, certfile=None, keyfile=None ): """ This class enables to send and receive SOAP data @param bindIp: bind ip (default='') @type bindIp: string @param bindPort: bind port (default=0) @type bindPort: integer @param destinationIp: destination ip (default=127.0.0.1) @type destinationIp: string @param destinationPort: destination port (default=80) @type destinationPort: integer @param xmlns0: xml namespace @type xmlns0: string @param xmlns1: xml namespace @type xmlns1: string @param xmlns2: xml namespace @type xmlns2: string @param xmlns3: xml namespace @type xmlns3: string @param xmlns4: xml namespace @type xmlns4: string @param xmlns5: xml namespace @type xmlns5: string @param xmlns6: xml namespace @type xmlns6: string @param xmlns7: xml namespace @type xmlns7: string @param xmlns8: xml namespace @type xmlns8: string @param supportAuthentication: support digest authentication (default=False) @type supportAuthentication: boolean @param httpAgent: http agent (default value=ExtensiveTesting) @type httpAgent: string @param httpConnection: SutAdapters.HTTP.CONN_CLOSE (default) | SutAdapters.HTTP.CONN_KEEPALIVE | None @type httpConnection: strconstant @param httpVersion: SutAdapters.HTTP.VERSION_10 | SutAdapters.HTTP.VERSION_11 (default) @type httpVersion: strconstant @param sslSupport: ssl support (default=False) @type sslSupport: boolean @param sslVersion: SutAdapters.SSL.SSLv2 | SutAdapters.SSL.SSLv23 (default) | SutAdapters.SSL.SSLv3 | SutAdapters.SSL.TLSv1 | SutAdapters.SSL.TLSv11 | SutAdapters.SSL.TLSv12 @type sslVersion: strconstant @param checkCert: SutAdapters.SSL.CHECK_CERT_NO (default) | SutAdapters.SSL.CHECK_CERT_OPTIONAL | SutAdapters.SSL.CHECK_CERT_REQUIRED @type checkCert: strconstant @param caCerts: path to the certificate authority (default=None) @type caCerts: string/none @param checkHost: validate the common name field (default=False) @type checkHost: boolean @param hostCn: common name to check (default=None) @type hostCn: string/none @param parent: parent testcase @type parent: testcase @param name: adapter name used with from origin/to destination (default=None) @type name: string/none @param debug: active debug mode (default=False) @type debug: boolean @param agentSupport: agent support to use a remote socket (default=False) @type agentSupport: boolean @param agent: agent to use when this mode is activated @type agent: string/None @param shared: shared adapter (default=False) @type shared: boolean @param proxyType: SutAdapters.TCP.PROXY_HTTP (default) | SutAdapters.TCP.PROXY_SOCKS4 | SutAdapters.TCP.PROXY_SOCKS5 @type proxyType: strconstant @param proxyIp: proxy ip @type proxyIp: string @param proxyPort: proxy port @type proxyPort: integer @param proxyHost: proxy host (automatic dns resolution) @type proxyHost: string @param proxyEnabled: True to support proxy (default=False) @type proxyEnabled: boolean @param certfile: path to the cert file (default=None) @type certfile: string/none @param keyfile: path to the key file (default=None) @type keyfile: string/none """ # init adapter TestAdapterLib.Adapter.__init__(self, name = __NAME__, parent = parent, debug=debug, shared=shared, realname=name, agentSupport=agentSupport, agent=agent, showEvts=verbose, showSentEvts=verbose, showRecvEvts=verbose, caller=TestAdapterLib.caller(), agentType=AGENT_TYPE_EXPECTED) self.logEventSent = logEventSent self.logEventReceived = logEventReceived self.ADP_HTTP = AdapterHTTP.Client( parent=parent, bindIp=bindIp, bindPort=bindPort, destinationIp=destinationIp, destinationPort=destinationPort, proxyIp=proxyIp, proxyPort=proxyPort, proxyHost=proxyHost, proxyEnabled=proxyEnabled, proxyType=proxyType, destinationHost='', socketTimeout=300.0, socketFamily=4, saveContent=False, httpVersion=httpVersion, httpAgent=httpAgent, httpConnection=httpConnection, httpChunckedData=False, sslSupport=sslSupport, sslVersion=sslVersion, checkCert=checkCert, debug=debug, caCerts=caCerts, checkHost=checkHost, hostCn=hostCn, logEventSent=False, logEventReceived=False, agentSupport=agentSupport, agent=agent, shared=shared, name=name, verbose=verbose, keyfile=keyfile, certfile=certfile ) self.ADP_HTTP.handleIncomingResponse = self.handleIncomingResponse self.codecX2D = Xml2Dict.Xml2Dict(coding='utf8') self.codecD2X = Dict2Xml.Dict2Xml(coding = 'utf8') self.cfg = {} self.cfg['xmlns0'] = xmlns0 self.cfg['xmlns1'] = xmlns1 self.cfg['xmlns2'] = xmlns2 self.cfg['xmlns3'] = xmlns3 self.cfg['xmlns4'] = xmlns4 self.cfg['xmlns5'] = xmlns5 self.cfg['xmlns6'] = xmlns6 self.cfg['xmlns7'] = xmlns7 self.cfg['xmlns8'] = xmlns8 self.cfg['http-agent'] = httpAgent self.cfg['agent-support'] = agentSupport self.cfg['http_support_authentication'] = httpAuthentication self.cfg['http_digest_timeout'] = 10.0 if agentSupport: self.cfg['agent'] = agent self.cfg['agent-name'] = agent['name'] # digest library self.rfc2617 = LibraryAuth.Digest(parent=parent, debug=debug) self.__checkConfig()
def sendSoap(self, uri, host, soap, httpHeaders = {}, method='POST', login='', password='', httpVersion="HTTP/1.1"): """ Send SOAP data with a HTTP request, http headers can be added @param uri: uri @type uri: string @param host: host @type host: string @param soap: soap @type soap: string @param httpHeaders: http headers to add @type httpHeaders: dict @param method: http method (default=POST) @type method: string @param login: login used on digest authentication (default='') @type login: string @param password: password used on digest authentication (default='') @type password: string """ try: # encode template try: new_xml = self.__removeNamespace(soapXml=soap) except Exception as e: raise Exception("Cannot remove namespace: %s" % str(e)) try: layerSoap = self.decodeSoap(data=eval(new_xml), firstCall=True ) layerSoap.addRaw(soap) except Exception as e: raise Exception("Cannot encode SOAP request: %s" % str(e)) # Send request try: hdrs = { "Host": host , "User-Agent": self.cfg['http-agent'] , "Content-Length": str(len(soap)), "Content-Type": "text/xml; charset=utf-8" } hdrs.update(httpHeaders) req_tpl = AdapterHTTP.request(method=method, uri=uri, version=httpVersion, headers=hdrs, body=soap) lower = self.ADP_HTTP.sendRequest(tpl=req_tpl) except Exception as e: raise Exception("http failed: %s" % str(e)) lower.addLayer( layerSoap ) lower.addRaw( lower.get('HTTP').getRaw() ) # Log event if self.logEventSent: lower.addRaw(raw=lower.getRaw()) self.logSentEvent( shortEvt = 'SOAP request', tplEvt = lower ) # support authentification if self.cfg['http_support_authentication'] : rsp = self.hasReceivedHttpResponse(httpCode="401", httpPhrase=None, headers={ 'www-authenticate': TestOperatorsLib.Any()}, timeout=self.cfg['http_digest_timeout']) if rsp is not None: # extract authentication self.debug('authentication to do, extract www-authen header') http_hdrs = rsp.get('HTTP', 'headers') www_hdr = http_hdrs.get('www-authenticate') # respond to the challenge challenge = self.rfc2617.decode(challenge=www_hdr) rsp, cnonce, nc = self.rfc2617.compute( username=login, password=password, realm=challenge['realm'], nonce=challenge['nonce'], method=method, uri=uri , qop=challenge['qop'], algo=challenge['algorithm'], body=None ) challengeRsp = self.rfc2617.encode( username=login, realm=challenge['realm'], nonce=challenge['nonce'], uri=uri, response=rsp, cnonce=cnonce, nc=nc, qop=challenge['qop'], algo=challenge['algorithm']) hdrs.update( {'authorization': challengeRsp} ) try: req_tpl = AdapterHTTP.request(method=method, uri=uri, version=httpVersion, headers=hdrs, body=soap) lower = self.ADP_HTTP.sendRequest(tpl=req_tpl) except Exception as e: raise Exception("http digest failed: %s" % str(e)) lower.addLayer( layerSoap ) lower.addRaw( lower.get('HTTP').getRaw() ) # Log event if self.logEventSent: lower.addRaw(raw=lower.getRaw()) self.logSentEvent( shortEvt = 'SOAP request', tplEvt = lower ) except Exception as e: self.error( 'unable to send soap: %s' % str(e) )
def hasReceivedRestResponse(self, httpCode="200", httpPhrase="OK", httpVersion='HTTP/1.1', timeout=1.0, httpHeaders={}, httpBody=None): """ Wait to receive "rest response" until the end of the timeout. @param httpCode: http code (default=200) @type httpCode: string @param httpPhrase: http phrase (default=OK) @type httpPhrase: string @param httpVersion: http version (default=HTTP/1.1) @type httpVersion: string @param httpHeaders: expected http headers @type httpHeaders: dict @param httpBody: expected body (default=None) @type httpBody: string/none @param timeout: time to wait in seconds (default=1s) @type timeout: float @return: http response @rtype: template """ TestAdapter.check_timeout(caller=TestAdapter.caller(), timeout=timeout) tpl = TestTemplates.TemplateMessage() if self.cfg['agent-support']: layer_agent = TestTemplates.TemplateLayer('AGENT') layer_agent.addKey(name='name', data=self.cfg['agent']['name']) layer_agent.addKey(name='type', data=self.cfg['agent']['type']) tpl.addLayer(layer_agent) tpl.addLayer(AdapterIP.ip(more=AdapterIP.received())) tpl.addLayer(AdapterTCP.tcp(more=AdapterTCP.received())) if self.ADP_HTTP.tcp().cfg['ssl-support']: tpl.addLayer(AdapterSSL.ssl(more=AdapterSSL.received())) headers = { 'content-type': TestOperators.Contains(needle='application/json', AND=True, OR=False) } headers.update(httpHeaders) tpl.addLayer( AdapterHTTP.response(version=httpVersion, code=httpCode, phrase=httpPhrase, headers=headers, body=httpBody)) tpl.addLayer(templates.response()) return self.hasReceivedResponse(expected=tpl, timeout=timeout)
def sendRest(self, uri, host, json='', method='POST', httpHeaders={}, body=None, timeout=1.0): """ Send REST data, http headers can be added @param uri: uri @type uri: string @param host: host @type host: string @param method: POST | GET | PUT | DELETE (default=POST) @type method: string @param json: json @type json: string @param httpHeaders: http headers to add @type httpHeaders: dict @param timeout: time max to wait to receive event in second (default=1s) @type timeout: float """ # connect ? if not self.ADP_HTTP.tcp().connected: if not self.ADP_HTTP.connection(timeout=timeout): return try: # encode template try: if len(json): str_json = self.LIB_JSON.encode(json_obj=json) if isinstance(json, list): layerRest = self.decodeList(data=json, firstCall=True) elif isinstance(json, dict): layerRest = self.decodeDict(data=json, firstCall=True) else: raise Exception('unsupported json type: %s' % type(json)) layerRest.addRaw(str_json) else: if body is not None: str_json = body else: str_json = '' except Exception as e: raise Exception("Cannot encode REST request: %s" % str(e)) # Send request try: hdrs = { "Host": host, "User-Agent": self.cfg['http-agent'], "Content-Length": str(len(str_json)) } if len(json): hdrs.update( {"Content-Type": "application/json; charset=utf-8"}) hdrs.update(httpHeaders) req_tpl = AdapterHTTP.request(method=method, uri=uri, version="HTTP/1.1", headers=hdrs, body=str_json) lower = self.ADP_HTTP.sendRequest(tpl=req_tpl) except Exception as e: raise Exception("http failed: %s" % str(e)) if len(json): lower.addLayer(layerRest) # Log event if self.logEventSent: lower.addRaw(raw=lower.getLayer("HTTP").getRaw()) self.logSentEvent(shortEvt='REST request', tplEvt=lower) except Exception as e: self.error('unable to send rest: %s' % str(e))
def __init__(self, parent, name=None, bindIp='', bindPort=0, destinationIp='127.0.0.1', destinationPort=80, debug=False, logEventSent=True, logEventReceived=True, httpAgent='ExtensiveTesting', httpVersion='HTTP/1.1', httpConnection='close', sslSupport=False, sslVersion=AdapterSSL.SSLv23, checkCert=AdapterSSL.CHECK_CERT_NO, caCerts=None, checkHost=False, hostCn=None, agentSupport=False, agent=None, shared=False, proxyIp='', proxyPort=3128, proxyHost='', proxyEnabled=False, proxyType=AdapterTCP.PROXY_HTTP, certfile=None, keyfile=None): """ This class enables to send and receive REST data @param bindIp: bind ip (default='') @type bindIp: string @param bindPort: bind port (default=0) @type bindPort: integer @param destinationIp: destination ip (default=127.0.0.1) @type destinationIp: string @param destinationPort: destination port (default=80) @type destinationPort: integer @param httpAgent: http agent (default value=ExtensiveTesting) @type httpAgent: string @param httpConnection: SutAdapters.HTTP.CONN_CLOSE (default) | SutAdapters.HTTP.CONN_KEEPALIVE | None @type httpConnection: strconstant @param httpVersion: SutAdapters.HTTP.VERSION_10 | SutAdapters.HTTP.VERSION_11 (default) @type httpVersion: strconstant @param sslSupport: ssl support (default=False) @type sslSupport: boolean @param checkCert: SutAdapters.SSL.CHECK_CERT_NO (default) | SutAdapters.SSL.CHECK_CERT_OPTIONAL | SutAdapters.SSL.CHECK_CERT_REQUIRED @type checkCert: strconstant @param caCerts: path to the certificate authority (default=None) @type caCerts: string/none @param checkHost: validate the common name field (default=False) @type checkHost: boolean @param hostCn: common name to check (default=None) @type hostCn: string/none @param parent: parent testcase @type parent: testcase @param name: adapter name used with from origin/to destination (default=None) @type name: string/none @param debug: active debug mode (default=False) @type debug: boolean @param agentSupport: agent support to use a remote socket (default=False) @type agentSupport: boolean @param agent: agent to use when this mode is activated, socket type expected @type agent: string/None @param shared: shared adapter (default=False) @type shared: boolean @param proxyType: SutAdapters.TCP.PROXY_HTTP (default) | SutAdapters.TCP.PROXY_SOCKS4 | SutAdapters.TCP.PROXY_SOCKS5 @type proxyType: strconstant @param proxyIp: proxy ip @type proxyIp: string @param proxyPort: proxy port @type proxyPort: integer @param proxyHost: proxy host (automatic dns resolution) @type proxyHost: string @param proxyEnabled: True to support proxy (default=False) @type proxyEnabled: boolean @param certfile: path to the cert file (default=None) @type certfile: string/none @param keyfile: path to the key file (default=None) @type keyfile: string/none """ # init adapter TestAdapter.Adapter.__init__(self, name=__NAME__, parent=parent, debug=debug, shared=shared, realname=name, agentSupport=agentSupport, agent=agent, caller=TestAdapter.caller(), agentType=AGENT_TYPE_EXPECTED) self.logEventSent = logEventSent self.logEventReceived = logEventReceived self.ADP_HTTP = AdapterHTTP.Client(parent=parent, bindIp=bindIp, bindPort=bindPort, destinationIp=destinationIp, destinationPort=destinationPort, proxyIp=proxyIp, proxyPort=proxyPort, proxyHost=proxyHost, proxyEnabled=proxyEnabled, proxyType=proxyType, destinationHost='', socketTimeout=300.0, socketFamily=4, saveContent=False, httpVersion=httpVersion, httpAgent=httpAgent, httpConnection=httpConnection, httpChunckedData=False, sslSupport=sslSupport, sslVersion=sslVersion, checkCert=checkCert, caCerts=caCerts, checkHost=checkHost, hostCn=hostCn, debug=debug, logEventSent=False, logEventReceived=False, agentSupport=agentSupport, agent=agent, shared=shared, name=name, keyfile=keyfile, certfile=certfile) self.ADP_HTTP.handleIncomingResponse = self.handleIncomingResponse self.LIB_JSON = DataExchange.JSON(parent=parent, name=name, debug=debug, ignoreErrors=True) self.cfg = {} self.cfg['http-agent'] = httpAgent self.cfg['agent-support'] = agentSupport if agentSupport: self.cfg['agent'] = agent self.cfg['agent-name'] = agent['name'] self.__checkConfig()