1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
|
import logging
import sys
import traceback
import cookielib
import six
from urlparse import parse_qs
from saml2test import CheckError
from saml2test import FatalError
from saml2test import OperationError
from saml2test.check import ERROR
from saml2test.check import ExpectedError
from saml2test.interaction import Action
from saml2test.interaction import Interaction
from saml2test.interaction import InteractionNeeded
from saml2test.opfunc import Operation
from saml2test.status import INTERACTION
from saml2test.status import STATUSCODE
__author__ = "rolandh"
logger = logging.getLogger(__name__)
class Conversation(object):
"""
:ivar response: The received HTTP messages
:ivar protocol_response: List of the received protocol messages
"""
def __init__(
self,
client,
config,
interaction,
check_factory=None,
msg_factory=None,
features=None,
verbose=False,
expect_exception=None,
):
self.client = client
self.client_config = config
self.test_output = []
self.features = features
self.verbose = verbose
self.check_factory = check_factory
self.msg_factory = msg_factory
self.expect_exception = expect_exception
self.cjar = {"browser": cookielib.CookieJar(), "rp": cookielib.CookieJar(), "service": cookielib.CookieJar()}
self.protocol_response = []
self.last_response = None
self.last_content = None
self.response = None
self.interaction = Interaction(self.client, interaction)
self.exception = None
def check_severity(self, stat):
if stat["status"] >= 4:
logger.error("WHERE: %s", stat["id"])
logger.error("STATUS:%s", STATUSCODE[stat["status"]])
try:
logger.error("HTTP STATUS: %s", stat["http_status"])
except KeyError:
pass
try:
logger.error("INFO: %s", stat["message"])
except KeyError:
pass
raise CheckError
def do_check(self, test, **kwargs):
if isinstance(test, six.string_types):
chk = self.check_factory(test)(**kwargs)
else:
chk = test(**kwargs)
stat = chk(self, self.test_output)
self.check_severity(stat)
def err_check(self, test, err=None, bryt=True):
if err:
self.exception = err
chk = self.check_factory(test)()
chk(self, self.test_output)
if bryt:
e = FatalError("%s" % err)
e.trace = "".join(traceback.format_exception(*sys.exc_info()))
raise e
def test_sequence(self, sequence):
for test in sequence:
if isinstance(test, tuple):
test, kwargs = test
else:
kwargs = {}
self.do_check(test, **kwargs)
if test == ExpectedError:
return False
return True
def my_endpoints(self):
pass
def intermit(self):
_response = self.last_response
_last_action = None
_same_actions = 0
if _response.status_code >= 400:
done = True
else:
done = False
url = _response.url
content = _response.text
while not done:
rdseq = []
while _response.status_code in [302, 301, 303]:
url = _response.headers["location"]
if url in rdseq:
raise FatalError("Loop detected in redirects")
else:
rdseq.append(url)
if len(rdseq) > 8:
raise FatalError("Too long sequence of redirects: %s" % rdseq)
logger.info("HTTP %d Location: %s", _response.status_code, url)
# If back to me
for_me = False
for redirect_uri in self.my_endpoints():
if url.startswith(redirect_uri):
# Back at the RP
self.client.cookiejar = self.cjar["rp"]
for_me = True
try:
base, query = url.split("?")
except ValueError:
pass
else:
_response = parse_qs(query)
self.last_response = _response
self.last_content = _response
return _response
if for_me:
done = True
break
else:
try:
logger.info("GET %s", url)
_response = self.client.send(url, "GET")
except Exception as err:
raise FatalError("%s" % err)
content = _response.text
logger.info("<-- CONTENT: %s", content)
self.position = url
self.last_content = content
self.response = _response
if _response.status_code >= 400:
done = True
break
if done or url is None:
break
_base = url.split("?")[0]
try:
_spec = self.interaction.pick_interaction(_base, content)
except InteractionNeeded:
self.position = url
cnt = content.replace("\n", "").replace("\t", "").replace("\r", "")
logger.error("URL: %s", url)
logger.error("Page Content: %s", cnt)
raise
except KeyError:
self.position = url
cnt = content.replace("\n", "").replace("\t", "").replace("\r", "")
logger.error("URL: %s", url)
logger.error("Page Content: %s", cnt)
self.err_check("interaction-needed")
if _spec == _last_action:
_same_actions += 1
if _same_actions >= 3:
self.test_output.append(
{
"status": ERROR,
"message": "Interaction loop detection",
# "id": "exception",
# "name": "interaction needed",
"url": self.position,
}
)
raise OperationError()
else:
_last_action = _spec
if len(_spec) > 2:
logger.info(">> %s <<", _spec["page-type"])
if _spec["page-type"] == "login":
self.login_page = content
_op = Action(_spec["control"])
try:
_response = _op(self.client, self, url, _response, content, self.features)
if isinstance(_response, dict):
self.last_response = _response
self.last_content = _response
return _response
content = _response.text
self.position = url
self.last_content = content
self.response = _response
if _response.status_code >= 400:
txt = "Got status code '%s', error: %s"
logger.error(txt, _response.status_code, content)
self.test_output.append(
{
"status": ERROR,
"message": txt % (_response.status_code, content),
# "id": "exception",
# "name": "interaction needed",
"url": self.position,
}
)
raise OperationError()
except (FatalError, InteractionNeeded, OperationError):
raise
except Exception as err:
self.err_check("exception", err, False)
self.last_response = _response
try:
self.last_content = _response.text
except AttributeError:
self.last_content = None
def init(self, phase):
self.creq, self.cresp = phase
def setup_request(self):
self.request_spec = req = self.creq(conv=self)
if isinstance(req, Operation):
for intact in self.interaction.interactions:
try:
if req.__class__.__name__ == intact["matches"]["class"]:
req.args = intact["args"]
break
except KeyError:
pass
else:
try:
self.request_args = req.request_args
except KeyError:
pass
try:
self.args = req.kw_args
except KeyError:
pass
# The authorization dance is all done through the browser
if req.request == "AuthorizationRequest":
self.client.cookiejar = self.cjar["browser"]
# everything else by someone else, assuming the RP
else:
self.client.cookiejar = self.cjar["rp"]
self.req = req
def send(self):
pass
def handle_result(self):
pass
def do_query(self):
self.setup_request()
self.send()
if not self.handle_result():
self.intermit()
self.handle_result()
def do_sequence(self, oper):
try:
self.test_sequence(oper["tests"]["pre"])
except KeyError:
pass
for phase in oper["sequence"]:
self.init(phase)
try:
self.do_query()
except InteractionNeeded:
cnt = self.last_content.replace("\n", "").replace("\t", "").replace("\r", "")
self.test_output.append(
{
"status": INTERACTION,
"message": cnt,
"id": "exception",
"name": "interaction needed",
"url": self.position,
}
)
break
except (FatalError, OperationError):
raise
except Exception as err:
# self.err_check("exception", err)
raise
try:
self.test_sequence(oper["tests"]["post"])
except KeyError:
pass
|