-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtest_api.py
2261 lines (1803 loc) · 80.8 KB
/
test_api.py
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
API server tests.
"""
import io
import os
import json
import uuid
import yaml
import time
import base64
import hashlib
import random
import datetime
import dateutil.parser
import unittest.mock
import ooogame.database.api as app
DEFAULT_TICKET_STATUS = "OPEN"
TICKET_CREATE_MSG = "ticket created successfully"
TEST_TEAM_ID = 1
TEST_TICKET_ID = 1
MAX_TEST_TEAM=10
def test_create_ticket():
test_subject = f"SUBJECT {TEST_TEAM_ID} {random.randint(0, 0xFFFFFFFF)}"
test_description = f"DESCRIPTION {TEST_TEAM_ID} {random.randint(0, 0xFFFFFFFF)}"
client = init_for_ticket_testing(test_subject, test_description)
response = client.post(f"/api/v1/ticket/{TEST_TEAM_ID}",data=dict(subject=test_subject, description=test_description))
assert response.status_code == 200, f"status code ==> {response.status_code}"
assert response.json["message"] == TICKET_CREATE_MSG, f"not equal {response.json['message']} != {TICKET_CREATE_MSG}"
response = client.get("/api/v1/tickets")
print(f"response={response.status_code}, json={response.json} ")
assert response.status_code == 200, f"status code ==> {response.status_code}"
assert "tickets" in response.json, f"tickets not in response.json ==> {response.json}"
tickets = response.json["tickets"]
assert len(tickets) > 0, "No Tickets returned from query"
t = tickets[0]
eval_ticket(t, TEST_TEAM_ID, test_subject, test_description, DEFAULT_TICKET_STATUS)
def test_list_team_tickets():
client = init_for_ticket_testing()
tickets_opened_by_test_team = 0
number_tickets_to_create = 100
# find all prior tickets created by test team, to set starting count
response = client.get("/api/v1/tickets")
tickets = response.json["tickets"]
for t in tickets:
if t["team_id"] == TEST_TEAM_ID:
tickets_opened_by_test_team += 1
pre_created_tickets = len(tickets)
for cnt in range(0, number_tickets_to_create-pre_created_tickets):
random_team_id = random.randint(1, MAX_TEST_TEAM) if tickets_opened_by_test_team > 0 else TEST_TEAM_ID
if random_team_id == TEST_TEAM_ID:
tickets_opened_by_test_team += 1
test_subject = f"SUBJECT {random_team_id} {random.randint(0, 0xFFFFFFFF)}"
test_description = f"DESCRIPTION {random_team_id} {random.randint(0, 0xFFFFFFFF)}"
response = client.post(f"/api/v1/ticket/{random_team_id}",data=dict(subject=test_subject,
description=test_description))
assert response.status_code == 200, f"status code ==> {response.status_code}"
assert response.json["message"] == TICKET_CREATE_MSG, f"not equal {response.json['message']} != {TICKET_CREATE_MSG}"
# Did all the tickets get created?
response = client.get("/api/v1/tickets")
assert response.status_code == 200, f"status code ==> {response.status_code}"
tickets = response.json["tickets"]
assert len(tickets) == number_tickets_to_create, f"Tickets returned not equal, {len(tickets)} != {number_tickets_to_create}"
assert tickets_opened_by_test_team > 0, "Failed to create any tickets for test team"
print(f"Created {number_tickets_to_create} TICKETS ")
# Does it filter by team and only return the teams ?
response = client.get(f"/api/v1/tickets/{TEST_TEAM_ID}")
assert response.status_code == 200, f"status code ==> {response.status_code}"
assert "tickets" in response.json
tickets = response.json["tickets"]
assert len(tickets) == tickets_opened_by_test_team, \
f"Tickets returned not equal, {len(tickets)} != {tickets_opened_by_test_team}"
for t in tickets:
eval_ticket(t, TEST_TEAM_ID, f"SUBJECT {TEST_TEAM_ID}", f"DESCRIPTION {TEST_TEAM_ID}", "OPEN")
def test_add_ticket_fail():
client = init_for_ticket_testing()
response = client.post(f"/api/v1/ticket/{TEST_TEAM_ID}", data=dict(description="desc w/o subject"))
assert response.status_code == 500
response = client.post(f"/api/v1/ticket/{TEST_TEAM_ID}", data=dict(subject="subject w/o desc"))
assert response.status_code == 500
def test_ticket_team_check():
client = init_for_ticket_testing()
response = client.get(f"/api/v1/ticket/1/message/{TEST_TEAM_ID}/team")
assert response.status_code == 200
assert response.json["message"] == "permitted"
response = client.get(f"/api/v1/ticket/1/message/5/team")
assert response.status_code == 200
assert response.json["message"] == "unauthorized attempt to add a message"
def test_add_status_fail():
client = init_for_ticket_testing()
# RI test, ticket does not exist
response = client.post(f"/api/v1/ticket/status/1999393", data=dict(status="OPEN"))
assert response.status_code == 500, f"status code ==> {response.status_code}"
# RI test, status does not exist
response = client.post(f"/api/v1/ticket/status/{TEST_TEAM_ID}", data=dict(status="IMNOTREAL"))
assert response.status_code == 500, f"status code ==> {response.status_code}"
def test_add_ticket_status():
client = init_for_ticket_testing()
ticket_status_add_msg = "status updated for ticket"
client.post(f"/api/v1/ticket/{TEST_TEAM_ID}", data=dict(subject="subject herez", description="desc"))
def verify_ticket_status(client, test_status):
response = client.post(f"/api/v1/ticket/status/{TEST_TICKET_ID}", data=dict(status=test_status))
assert response.status_code == 200, f"status code ==> {response.status_code}"
assert response.json["message"].startswith(ticket_status_add_msg), \
f"message={response.json['message']} does NOT start with {ticket_status_add_msg}"
response = client.get("/api/v1/tickets")
tickets = response.json["tickets"]
for t in tickets:
if t["id"] == TEST_TICKET_ID:
assert t["status"] == test_status
return
verify_ticket_status(client, test_status="CLOSED")
verify_ticket_status(client, test_status="OPEN")
verify_ticket_status(client, test_status="CLOSED")
verify_ticket_status(client, test_status="CLOSED")
verify_ticket_status(client, test_status="OPEN")
def test_add_admin_message():
client = init_for_ticket_testing()
test_message_text = f"MESSAGE_TEXT ADMIN {random.randint(0, 0xFFFFFFFF)}"
ticket_msg_add_msg = f"Message for ticket #{TEST_TICKET_ID} added successfully"
response = client.post(f"/api/v1/ticket/{TEST_TICKET_ID}/message", data=dict(message_text=test_message_text))
verify_message(response, ticket_msg_add_msg)
response = client.get("/api/v1/tickets")
ticket = response.json['tickets'][0]
for msg in ticket['messages']:
if not msg['is_team_message']:
assert msg['message_text'] == test_message_text
break
def test_add_team_message():
client = init_for_ticket_testing()
test_message_text = f"MESSAGE_TEXT TEAM {TEST_TEAM_ID} {random.randint(0, 0xFFFFFFFF)}"
ticket_msg_add_msg = f"Message for ticket #{TEST_TICKET_ID} added successfully"
response = client.post(f"/api/v1/ticket/{TEST_TICKET_ID}/message", data=dict(message_text=test_message_text,
is_team_message=True))
verify_message(response, ticket_msg_add_msg)
response = client.get("/api/v1/tickets")
ticket = response.json['tickets'][0]
for msg in ticket['messages']:
if msg['is_team_message']:
assert msg['message_text'] == test_message_text
break
# ---------------~~~~~~~~~~~<[ utililty functions for ticket testing ]>~~~~~~~~~~~~~~~~~------------------
def verify_message(response, test_message):
assert response.status_code == 200, f"status code ==> {response.status_code}"
assert response.json["message"].startswith(test_message), \
f"message={response.json['message']} does NOT start with {test_message}"
def init_for_ticket_testing(subject=f"SUBJECT {TEST_TEAM_ID}", description=f"DESCRIPTION {TEST_TEAM_ID}"):
app.db.create_all()
app.init_test_data()
client = app.app.test_client()
response = client.get(f"/api/v1/tickets")
if len(response.json["tickets"]) == 0:
client.post(f"/api/v1/ticket/{TEST_TEAM_ID}", data=dict(subject=subject, description=description))
return client
def eval_ticket(t, test_team_id, test_subject, test_desc, test_status):
assert t["team_id"] == test_team_id, f"not equal {t['team_id']} != {test_team_id}"
assert t["subject"].startswith(test_subject), f"t['subject']={t['subject']} does not start with {test_subject}"
assert t["description"].startswith(test_desc), f"t['description']={t['description']} does not start with {test_desc}"
assert t["status"] == test_status, f"not equal {t['status']} != {test_status}"
# ---------------~~~~~~~~~~~<[ END UTILITY FUNCTION AREA 51 ]>~~~~~~~~~~~~~~~~~------------------
def test_teams():
app.db.create_all()
app.init_test_data()
client = app.app.test_client()
response = client.get("/api/v1/teams")
assert response.status_code == 200
assert "teams" in response.json
assert isinstance(response.json["teams"], list)
assert "id" in response.json["teams"][0]
assert "name" in response.json["teams"][0]
assert "team_network" in response.json["teams"][0]
assert len(app.db.session.query(app.Deleted).all()) == 0
team_id = response.json["teams"][0]["id"]
team = app.db.session.query(app.Team).get(team_id)
app.db.session.delete(team)
app.db.session.commit()
response = client.get("/api/v1/teams")
assert response.status_code == 200
assert team_id != response.json["teams"][0]["id"]
assert len(app.db.session.query(app.Deleted).all()) == 1
deleted = app.db.session.query(app.Deleted).all()[0]
assert str(team_id).encode() in deleted.content
def test_team_info():
app.db.create_all()
app.init_test_data()
client = app.app.test_client()
response = client.get("/api/v1/team/1")
assert response.status_code == 200
assert "id" in response.json
assert "name" in response.json
assert "team_network" in response.json
def _get_normal_service(client):
response = client.get("/api/v1/services")
assert response.status_code == 200
services = response.json['services']
to_return = None
for s in services:
if s['type'] == "NORMAL":
to_return = s
break
assert to_return != None
return to_return
def _get_different_normal_service(client, service):
response = client.get("/api/v1/services")
assert response.status_code == 200
services = response.json['services']
to_return = None
for s in services:
if s['id'] == service['id']:
continue
if s['type'] == "NORMAL":
to_return = s
break
assert to_return != None
return to_return
def test_flag_creation_and_submission():
app.db.create_all()
app.init_test_data()
client = app.app.test_client()
service = _get_normal_service(client)
service_id = service['id']
# Check without the game running, it should not create a flag
response = client.post(f"/api/v1/flag/generate/{service_id}/1")
assert response.status_code != 200
# Start the game!
response = client.post("/api/v1/game/start")
assert response.status_code == 200
response = client.post(f"/api/v1/flag/generate/{service_id}/1")
assert "id" in response.json
assert "flag" in response.json
flag_tick_id = response.json['tick_id']
flag_id = response.json['id']
assert len(response.json["flag"]) > 5
the_flag = response.json["flag"]
# Test that if we generate a flag for the same tick, we will get the same flag
new_response = client.post(f"/api/v1/flag/generate/{service_id}/1")
assert flag_tick_id == new_response.json['tick_id']
assert flag_id == new_response.json['id']
# Test if we can get this flag from the "latest" endpoint
response = client.get(f"/api/v1/flag/latest/{service_id}/1")
assert response.status_code == 200
assert response.json['flag'] == the_flag
# Test if flags for ticks returns this
response = client.get(f"/api/v1/flags/{flag_tick_id}")
assert len(response.json) == 1
assert response.json[0]['flag'] == the_flag
# service is not active, so flags don't count
response = client.post("/api/v1/flag/submit/2",
data=dict(
flag=the_flag
))
assert response.status_code == 200
assert response.json['result'] == 'SERVICE_INACTIVE'
response = client.post(f"/api/v1/service/{service_id}/is_active/1")
assert response.status_code == 200
# service is now active, so the flag should count
response = client.post("/api/v1/flag/submit/2",
data=dict(
flag=the_flag
))
assert response.status_code == 200
assert response.json['result'] == 'CORRECT'
# check that the event made it
response = client.get("/api/v1/events")
assert len(response.json['events']) == 1, response.json
event = response.json['events'][0]
assert 'id' in event
assert 'FLAG_STOLEN' == event['event_type']
assert 'reason' in event
assert flag_tick_id == event['tick_id']
assert 2 == event['exploit_team_id']
assert 1 == event['victim_team_id']
assert service_id == event['service_id']
assert flag_id == event['flag_id']
response = client.post("/api/v1/flag/submit/2",
data=dict(
flag=the_flag
))
assert response.json['result'] == 'ALREADY_SUBMITTED'
fake_flag = "OOOwillthisonedo"
response = client.post("/api/v1/flag/submit/2",
data=dict(
flag=fake_flag
))
assert response.json['result'] == 'INCORRECT'
# Test team1 submitting own flag
response = client.post("/api/v1/flag/submit/1",
data=dict(
flag=the_flag
))
assert response.json['result'] == 'OWN_FLAG'
# Test team2 submitting a super old flag
response = client.post("/api/v1/tick/next")
new_tick = response.json['tick']
response = client.post(f"/api/v1/flag/generate/{service_id}/1")
the_flag = response.json["flag"]
for i in range(app.NUM_TICKS_FLAG_VALID_FOR + 1):
response = client.post("/api/v1/tick/next")
new_tick = response.json['tick']
response = client.post("/api/v1/flag/submit/2",
data=dict(
flag=the_flag
))
assert response.json['result'] == 'TOO_OLD', response.json
# Test team2 submitting an almost old flag
response = client.post("/api/v1/tick/next")
new_tick = response.json['tick']
response = client.post(f"/api/v1/flag/generate/{service_id}/1")
the_flag = response.json["flag"]
flag_id = response.json["id"]
for i in range(app.NUM_TICKS_FLAG_VALID_FOR):
response = client.post("/api/v1/tick/next")
new_tick = response.json['tick']
response = client.post("/api/v1/flag/submit/2",
data=dict(
flag=the_flag
))
assert response.json['result'] == 'CORRECT', response.json
# test deleting a flag
response = client.post(f"/api/v1/flag/generate/{service_id}/1")
flag_id = response.json["id"]
the_flag = app.db.session.query(app.Flag).get(flag_id)
app.db.session.delete(the_flag)
app.db.session.commit()
assert len(app.db.session.query(app.Deleted).all()) != 1
deleted = app.db.session.query(app.Deleted).all()[-1]
assert str(flag_id).encode() in deleted.content
def test_game_state():
app.db.drop_all()
app.db.create_all()
app.init_test_data()
client = app.app.test_client()
response = client.get("/api/v1/game/state")
assert response.status_code == 200
assert response.json['state'] == 'INIT'
assert 'tick' in response.json
assert 'current_tick_created_on' in response.json
# Test changing game state
for state in ["RUNNING", "PAUSED", "STOPPED", "INIT"]:
response = client.post("/api/v1/game/state",
data=dict(
state=state
))
assert response.status_code == 200
response = client.get("/api/v1/game/state")
assert response.json['state'] == state
# test invalid staring the game
response = client.post("/api/v1/game/state",
data=dict(
state="RUNNING"
))
assert response.status_code == 200
response = client.post("/api/v1/game/start")
assert response.status_code != 200
# test staring the game
response = client.post("/api/v1/game/state",
data=dict(
state="INIT"
))
assert response.status_code == 200
response = client.post("/api/v1/game/start")
first_tick = response.json['tick']
# ensure that game is now running and the tick is returned
response = client.get("/api/v1/game/state")
assert response.json['state'] == "RUNNING"
assert response.json['tick'] == first_tick
assert response.json['current_tick_created_on'] != None
# now tick that tock!
response = client.post("/api/v1/tick/next")
assert response.json['tick'] != first_tick
new_tick = response.json['tick']
response = client.get("/api/v1/game/state")
assert response.json['tick'] == new_tick
def _test_service_one(service):
yml_service_data = yaml.safe_load(open(os.path.join(os.path.dirname(os.path.realpath(app.__file__)), 'service_info.yml'), 'r'))[
'services']
assert len(yml_service_data) > 0, f"service_info.yml has no services\n\tyml_service_data={yml_service_data}"
srv1 = yml_service_data[0]
assert srv1['type'].lower() == "normal", "1st service in yaml should be 'normal' for tests to work correctly."
assert 'limit_memory' in srv1 and 'request_memory' in srv1, "1st service in yaml should explicitly set memory limits for tests to work correctly"
assert service['flag_location'] == srv1['flag_location']
assert service['description'] == srv1['description']
assert service['central_server'] == srv1['central_server']
assert service['isolation'] == srv1['isolation']
assert service['port'] == srv1['port']
assert service['container_port'] == srv1['container_port']
assert 'description' in service
assert 'max_bytes' in service, service
assert 'patchable_file_from_service_dir' in service
assert 'patchable_file_from_docker' in service
assert service['interaction_docker']
assert service['local_interaction_docker']
assert service['service_docker']
assert service['release_pcaps'] == False
assert service['is_visible'] == False
assert service['is_active'] == False
assert service['service_indicator'] == "GOOD"
assert 'local_interaction_scripts' in service
assert len(service['exploit_scripts']) == len(srv1['exploit_scripts']), \
f"{len(service['exploit_scripts'])} NOT= {len(srv1['exploit_scripts'])}"
assert len(service['sla_scripts']) == len(srv1['sla_scripts'])
assert srv1['sla_scripts'][0] in service['sla_scripts']
assert srv1['limit_memory'] == service['limit_memory']
assert srv1['request_memory'] == service['request_memory']
def _test_koh_service(service):
assert service['score_location'] == '/home/reverse/conf/score.dat'
assert service['port'] == 7777
assert 'description' in service
assert service['type'] == "KING_OF_THE_HILL"
assert service['repo_url'] == "[email protected]:o-o-overflow/finals-chall-reverse.git"
def test_service_list():
app.db.create_all()
app.init_test_data()
client = app.app.test_client()
response = client.get("/api/v1/services")
assert response.status_code == 200
services = response.json['services']
def test_service():
app.db.create_all()
app.init_test_data()
client = app.app.test_client()
service = _get_normal_service(client)
response = client.get(f"/api/v1/service/{service['id']}")
_test_service_one(response.json)
def test_toggle_service_functions():
app.db.create_all()
app.init_test_data()
client = app.app.test_client()
service = _get_normal_service(client)
service_id = service['id']
for prop in ["release_pcaps", "is_visible", "is_active"]:
response = client.post(f"/api/v1/service/{service_id}/{prop}/1")
assert response.status_code == 200
response = client.get(f"/api/v1/service/{service_id}")
assert response.json[prop] == True
response = client.post(f"/api/v1/service/{service_id}/{prop}/0")
assert response.status_code == 200
response = client.get(f"/api/v1/service/{service_id}")
assert response.json[prop] == False
def test_tick_length():
app.db.create_all()
app.init_test_data()
client = app.app.test_client()
response = client.get("/api/v1/game/state")
assert response.json['tick_time_seconds'] == app.TickTime._DEFAULT_TICK_TIME
assert response.json['is_game_state_public'] == app.IsGameStatePublic._DEFAULT_VALUE
assert 'estimated_tick_time_remaining' in response.json
assert response.json['estimated_tick_time_remaining'] >= 0
prev_time = response.json['estimated_tick_time_remaining']
response = client.get("/api/v1/game/state")
assert prev_time > response.json['estimated_tick_time_remaining']
response = client.post("/api/v1/tick/time",
data=dict(
tick_time_seconds=10,
))
assert response.status_code == 200
response = client.get("/api/v1/game/state")
assert response.json['tick_time_seconds'] == 10
response = client.post("/api/v1/tick/time",
data=dict(
tick_time_seconds=500,
))
assert response.status_code == 200
response = client.get("/api/v1/game/state")
assert response.json['tick_time_seconds'] == 500
def test_is_game_state_public():
app.db.create_all()
app.init_test_data()
client = app.app.test_client()
response = client.get("/api/v1/game/state")
assert response.json['is_game_state_public'] == app.IsGameStatePublic._DEFAULT_VALUE
response = client.post("/api/v1/game/is_game_state_public/1")
assert response.status_code == 200
response = client.get("/api/v1/game/state")
assert response.json['is_game_state_public'] == True
response = client.post("/api/v1/game/is_game_state_public/0")
assert response.status_code == 200
response = client.get("/api/v1/game/state")
assert response.json['is_game_state_public'] == False
def test_game_state_delay():
app.db.create_all()
app.init_test_data()
client = app.app.test_client()
response = client.get("/api/v1/game/state")
assert response.json['game_state_delay'] == app.GameStateDelay._DEFAULT_VALUE
response = client.post("/api/v1/game/game_state_delay/10")
assert response.status_code == 200
response = client.get("/api/v1/game/state")
assert response.json['game_state_delay'] == 10
response = client.post("/api/v1/game/game_state_delay/0")
assert response.status_code == 200
response = client.get("/api/v1/game/state")
assert response.json['game_state_delay'] == 0
def test_ip_to_team():
app.db.create_all()
app.init_test_data()
client = app.app.test_client()
response = client.get("/api/v1/team-from-ip/10.1.0.20")
assert response.status_code == 200
assert response.json['team_id'] == 1
response = client.get("/api/v1/team-from-ip/192.168.10.12")
assert response.json['team_id'] == None
def test_events():
app.db.drop_all()
app.db.create_all()
app.init_test_data()
client = app.app.test_client()
# Start the game
response = client.post("/api/v1/game/start")
# check that the endpoints exist
for endpoint in ["/api/v1/events", "/api/v1/events/1"]:
response = client.get(endpoint)
assert response.status_code == 200
assert 'events' in response.json
# Create a new event
response = client.post("/api/v1/event",
data=dict(
event_type="EXPLOIT_SCRIPT",
reason="Testing the application.",
team_id=2,
service_id=1,
ip="127.0.0.1",
port=31337,
service_interaction_docker="testing-interaction",
the_script="/exploit.sh",
docker_registry="",
result="SUCCESS",
))
assert response.status_code == 200, response
# check that it's in all events
response = client.get("/api/v1/events")
assert len(response.json['events']) == 1, response.json
event = response.json['events'][0]
assert event['event_type'] == 'EXPLOIT_SCRIPT'
assert event['team_id'] == 2
assert event['service_id'] == 1
assert event['ip'] == '127.0.0.1'
assert event['port'] == 31337
assert event['service_interaction_docker'] == 'testing-interaction'
assert event['the_script'] == '/exploit.sh'
assert 'docker_registry' in event
assert event['result'] == "SUCCESS"
# Try SLA Script
response = client.post("/api/v1/event",
data=dict(
event_type="SLA_SCRIPT",
reason="Testing the application.",
team_id=2,
service_id=1,
ip="127.0.0.1",
port=31337,
service_interaction_docker="testing-interaction",
the_script="/exploit.sh",
docker_registry="",
result="SUCCESS",
))
assert response.status_code == 200, response
# check that it's in all events
response = client.get("/api/v1/events")
assert len(response.json['events']) == 2
event = response.json['events'][1]
assert event['event_type'] == 'SLA_SCRIPT'
assert event['team_id'] == 2
assert event['service_id'] == 1
assert 'tick_id' in event
assert event['ip'] == '127.0.0.1'
assert event['port'] == 31337
assert event['service_interaction_docker'] == 'testing-interaction'
assert event['the_script'] == '/exploit.sh'
assert 'docker_registry' in event
assert event['result'] == "SUCCESS"
# Test set flag event
# Need to get a flag
response = client.post("/api/v1/flag/generate/2/1")
assert response.status_code == 200
flag_id = response.json['id']
the_flag = response.json['flag']
# Test if we can get this flag from the "latest" endpoint
response = client.get("/api/v1/flag/latest/2/1")
assert response.status_code == 200
assert response.json['flag'] == the_flag
response = client.post("/api/v1/event",
data=dict(
event_type="SET_FLAG",
reason="Testing the application.",
team_id=1,
service_id=2,
flag_id=flag_id,
result="SUCCESS",
))
assert response.status_code == 200
# check that it's in all events
response = client.get("/api/v1/events")
assert len(response.json['events']) == 3
event = response.json['events'][2]
assert event['event_type'] == 'SET_FLAG'
assert event['team_id'] == 1
assert event['service_id'] == 2
assert event['flag_id'] == flag_id
assert event['result'] == "SUCCESS"
# Test KoH Events
response = client.post("/api/v1/event",
data=dict(
event_type="KOH_SCORE_FETCH",
reason="Successly extracted score.",
team_id=1,
service_id=3,
score=10,
data="foobar",
result="SUCCESS",
))
assert response.status_code == 200
# check that it's in all events
response = client.get("/api/v1/events")
assert len(response.json['events']) == 4
event = response.json['events'][3]
assert event['event_type'] == 'KOH_SCORE_FETCH'
assert event['team_id'] == 1
assert event['service_id'] == 3
assert event['score'] == 10
assert event['data'] == "foobar"
assert event['result'] == "SUCCESS"
# Failed score fetching event
response = client.post("/api/v1/event",
data=dict(
event_type="KOH_SCORE_FETCH",
reason="Failed to extract score.",
team_id=2,
service_id=3,
result="FAIL",
))
assert response.status_code == 200
# check that it's in all events
response = client.get("/api/v1/events")
assert len(response.json['events']) == 5
event = response.json['events'][4]
assert event['event_type'] == 'KOH_SCORE_FETCH'
assert event['team_id'] == 2
assert event['service_id'] == 3
assert event['result'] == "FAIL"
# posting a koh ranking event, which is a bit complicated
# first, get all teams to generate a fake ranking
response = client.get("/api/v1/teams")
teams = response.json['teams']
max_score = len(teams) + 1
ranking = []
rank = 1
score = max_score
for t in teams:
this_team_score = dict(rank=rank,
score=score,
data="some metadata {}".format(rank),
team_id=t['id']
)
ranking.append(this_team_score)
score -= 1
rank += 1
response = client.post("/api/v1/event",
data=dict(
event_type="KOH_RANKING",
reason="Ranking of teams for service 3 tick 2.",
tick_id=2,
ranking=json.dumps(ranking),
service_id=3,
))
assert response.status_code == 200
# check that it's in all events
response = client.get("/api/v1/events")
assert len(response.json['events']) == 6
event = response.json['events'][5]
assert event['event_type'] == 'KOH_RANKING'
assert event['service_id'] == 3
assert event['tick_id'] == 2
assert len(event['ranking']) == len(ranking)
# Test the pcap created event
response = client.post("/api/v1/event",
data=dict(
event_type="PCAP_CREATED",
reason="Test of pcap creation event.",
service_id=1,
team_id=2,
pcap_name="team_2_service_1_1000.pcap",
))
assert response.status_code == 200
# check that it's in all events
response = client.get("/api/v1/events")
assert len(response.json['events']) == 7
event = response.json['events'][6]
assert event['event_type'] == 'PCAP_CREATED'
assert event['service_id'] == 1
assert event['team_id'] == 2
# Test the pcap released event
response = client.post("/api/v1/event",
data=dict(
event_type="PCAP_RELEASED",
reason="Test of pcap released event.",
service_id=1,
team_id=2,
pcap_name="team_2_service_1_1000.released.pcap",
))
assert response.status_code == 200
# check that it's in all events
response = client.get("/api/v1/events")
assert len(response.json['events']) == 8
event = response.json['events'][7]
assert event['event_type'] == 'PCAP_RELEASED'
assert event['service_id'] == 1
assert event['team_id'] == 2
def test_defense():
app.db.drop_all()
app.db.create_all()
app.init_test_data()
client = app.app.test_client()
service = _get_normal_service(client)
service_id = service['id']
# Start the game
response = client.post("/api/v1/game/start")
new_tick = response.json['tick']
# first get the number of teams
response = client.get("/api/v1/teams")
teams = response.json['teams']
response = client.get("/api/v1/services")
services = response.json['services']
num_normal_services = len([s for s in services if s['type'] == "NORMAL" and s['is_active']])
response = client.get("/api/v1/score/{}".format(new_tick))
assert response.status_code == 200
assert response.json['tick_id'] == new_tick
assert len(teams) == len(response.json['teams'])
# there's been no flags submitted yet, so all the team's attack scores should be 0, defense should be num(services where type == normal), and koh should be 0
for t in teams:
assert str(t['id']) in response.json['teams']
team_score = response.json['teams'][str(t['id'])]
assert team_score['ATTACK'] == 0
assert team_score['DEFENSE'] == 0
assert team_score['KING_OF_THE_HILL'] == 0
# Activate service 1
response = client.post(f"/api/v1/service/{service_id}/is_active/1")
assert response.status_code == 200
response = client.get("/api/v1/services")
services = response.json['services']
num_normal_services = len([s for s in services if s['type'] == "NORMAL" and s['is_active']])
response = client.post(f"/api/v1/flag/generate/{service_id}/2")
assert "id" in response.json
assert "flag" in response.json
flag_tick_id = response.json['tick_id']
flag_id = response.json['id']
the_flag = response.json['flag']
response = client.post("/api/v1/flag/submit/1",
data=dict(
flag=the_flag
))
assert response.status_code == 200
assert response.json['result'] == 'CORRECT'
# Team 1 should have an attack score of 1
response = client.get("/api/v1/score/{}".format(new_tick))
for t in teams:
assert str(t['id']) in response.json['teams']
team_score = response.json['teams'][str(t['id'])]
if t['id'] == 1:
assert team_score['ATTACK'] == 1
else:
assert team_score['ATTACK'] == 0
if t['id'] == 2:
assert team_score['DEFENSE'] == 0
else: