-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfb_tester.py
More file actions
984 lines (825 loc) · 42.7 KB
/
Copy pathfb_tester.py
File metadata and controls
984 lines (825 loc) · 42.7 KB
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
#!/usr/bin/env python3
"""
Firebase Configuration Security Testing Tool
Tests Firebase configurations for potential security misconfigurations
Usage examples:
# Parse JSON config with quoted keys
python3 firebase_test.py --firebase-config '{"apiKey":"AIza...","authDomain":"proj.firebaseapp.com"}'
# Parse JavaScript config with unquoted keys
python3 firebase_test.py --firebase-config '{apiKey:"AIza...",authDomain:"proj.firebaseapp.com"}'
# Parse multiline config
python3 firebase_test.py --firebase-config '{
apiKey: "AIza...",
authDomain: "proj.firebaseapp.com"
}'
# Individual parameters
python3 firebase_test.py --api-key "AIza..." --database-url "https://proj.firebaseio.com"
# Debug mode (prints curl commands for each test)
python3 firebase_test.py --firebase-config '...' --debug
# Custom email/password for registration test
python3 firebase_test.py --firebase-config '...' --email "test@example.com" --password "Pa$w0rd"
"""
import argparse
import json
import random
import string
import sys
import requests
from urllib.parse import quote
import base64
import re
from typing import Dict, Optional, Any
class FirebaseConfigTester:
def __init__(self, config: Dict[str, str], debug: bool = False):
self.debug = debug
self.config = self._parse_config(config)
self.config = self._derive_missing_fields(self.config)
self.id_token = None
self.random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
def _derive_missing_fields(self, config: Dict[str, str]) -> Dict[str, str]:
"""Derive missing fields from available configuration fields"""
derived_config = config.copy()
# Try to derive projectId from authDomain
if 'projectId' not in derived_config and 'authDomain' in derived_config:
auth_domain = derived_config['authDomain']
if '.firebaseapp.com' in auth_domain:
project_id = auth_domain.replace('.firebaseapp.com', '')
derived_config['projectId'] = project_id
if self.debug:
print(f"DEBUG: Derived projectId '{project_id}' from authDomain '{auth_domain}'")
# Try to derive databaseURL from projectId or authDomain
if 'databaseURL' not in derived_config:
project_id = derived_config.get('projectId')
if project_id:
derived_config['databaseURL'] = f"https://{project_id}-default-rtdb.firebaseio.com"
if self.debug:
print(f"DEBUG: Derived databaseURL from projectId: {derived_config['databaseURL']}")
elif 'authDomain' in derived_config:
auth_domain = derived_config['authDomain']
if '.firebaseapp.com' in auth_domain:
project_id = auth_domain.replace('.firebaseapp.com', '')
derived_config['databaseURL'] = f"https://{project_id}-default-rtdb.firebaseio.com"
if self.debug:
print(f"DEBUG: Derived databaseURL from authDomain: {derived_config['databaseURL']}")
# Try to derive storageBucket from projectId or authDomain
if 'storageBucket' not in derived_config:
project_id = derived_config.get('projectId')
if project_id:
derived_config['storageBucket'] = f"{project_id}.appspot.com"
if self.debug:
print(f"DEBUG: Derived storageBucket from projectId: {derived_config['storageBucket']}")
elif 'authDomain' in derived_config:
auth_domain = derived_config['authDomain']
if '.firebaseapp.com' in auth_domain:
project_id = auth_domain.replace('.firebaseapp.com', '')
derived_config['storageBucket'] = f"{project_id}.appspot.com"
if self.debug:
print(f"DEBUG: Derived storageBucket from authDomain: {derived_config['storageBucket']}")
return derived_config
def _parse_config(self, config: Dict[str, str]) -> Dict[str, str]:
"""Parse and clean the Firebase configuration"""
# Handle unicode escape sequences
config_str = json.dumps(config)
config_str = config_str.encode().decode('unicode_escape')
# Clean up the config (remove quotes, spaces, etc.)
cleaned_config = {}
for key, value in json.loads(config_str).items():
if value:
cleaned_config[key] = str(value).strip()
return cleaned_config
def _print_debug(self, message: str, curl_command: str = None):
"""Print debug information if debug mode is enabled"""
if self.debug:
print(f"DEBUG: {message}")
if curl_command:
print(f"CURL: {curl_command}")
def check_registration(self, email: str, password: str) -> bool:
"""Check if registration is possible with provided apiKey"""
if 'apiKey' not in self.config:
print("No apiKey provided, skipping registration check")
return False
url = f"https://identitytoolkit.googleapis.com/v1/accounts:signUp?key={self.config['apiKey']}"
headers = {'Content-Type': 'application/json'}
# Test 1: Email/password registration (prioritized)
data = {
"email": email,
"password": password,
"returnSecureToken": True
}
curl_cmd = f"curl '{url}' -H 'Content-Type: application/json' --data '{json.dumps(data)}'"
self._print_debug(f"Checking email/password registration at {url}", curl_cmd)
try:
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
print(f"✓ Email/password registration successful with apiKey (status: {response.status_code})")
result = response.json()
self.id_token = result.get('idToken')
return True
elif response.status_code == 400:
print(f"✗ Email/password registration not allowed (status: {response.status_code})")
else:
print(f"✗ Email/password registration check failed (status: {response.status_code})")
except Exception as e:
print(f"✗ Email/password registration check error: {e}")
# Test 2: Anonymous registration (fallback)
print("Trying anonymous registration as fallback...")
anonymous_data = {}
curl_cmd_anon = f"curl '{url}' -H 'Content-Type: application/json' --data '{{}}'"
self._print_debug(f"Checking anonymous registration at {url}", curl_cmd_anon)
try:
response = requests.post(url, headers=headers, json=anonymous_data)
if response.status_code == 200:
print(f"✓ Anonymous registration successful with apiKey (status: {response.status_code})")
result = response.json()
self.id_token = result.get('idToken')
return True
elif response.status_code == 400:
print(f"✗ Anonymous registration not allowed (status: {response.status_code})")
return False
else:
print(f"✗ Anonymous registration check failed (status: {response.status_code})")
return False
except Exception as e:
print(f"✗ Anonymous registration check error: {e}")
return False
def check_storage_bucket(self):
"""Check if storageBucket is accessible"""
if 'storageBucket' not in self.config:
print("No storageBucket provided, skipping check")
return
storage_bucket = self.config['storageBucket']
# Check via firebasestorage.googleapis.com
print(f"\nChecking storage bucket: {storage_bucket}")
# Test anonymous, authenticated legacy (Bearer), and modern (Firebase)
headers_list = [{}]
if self.id_token:
headers_list.append({"Authorization": f"Bearer {self.id_token}"})
headers_list.append({"Authorization": f"Firebase {self.id_token}"})
for i, headers in enumerate(headers_list):
if not headers:
auth_type = "anonymous"
elif "Bearer" in headers.get("Authorization", ""):
auth_type = "authenticated (Bearer)"
else:
auth_type = "authenticated (Firebase)"
# Firebase Storage API
url = f"https://firebasestorage.googleapis.com/v0/b/{storage_bucket}/o"
curl_cmd = f"curl '{url}'"
if headers:
curl_cmd += f" -H 'Authorization: {headers['Authorization']}'"
self._print_debug(f"Checking {url} ({auth_type})", curl_cmd)
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
print(f"✓ Storage bucket accessible ({auth_type}) (status: {response.status_code})")
print(f" URL: {url}")
# Save storage listing to file
try:
listing_data = response.json()
filename = f"storage-listing-{auth_type.replace(' ', '-').replace('(', '').replace(')', '')}.json"
with open(filename, 'w') as f:
json.dump(listing_data, f, indent=2)
print(f" Listing saved to {filename}")
except Exception as e:
print(f" Could not save listing: {e}")
elif response.status_code == 404:
print(f"✗ Storage bucket not found ({auth_type}) (status: {response.status_code})")
else:
print(f"✗ Storage bucket check failed ({auth_type}) (status: {response.status_code})")
except Exception as e:
print(f"✗ Storage bucket check error ({auth_type}): {e}")
# Google Cloud Storage API
url = f"https://storage.googleapis.com/{storage_bucket}/"
curl_cmd = f"curl '{url}'"
if headers:
curl_cmd += f" -H 'Authorization: {headers['Authorization']}'"
self._print_debug(f"Checking {url} ({auth_type})", curl_cmd)
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
print(f"✓ Google Cloud Storage accessible ({auth_type}) (status: {response.status_code})")
print(f" URL: {url}")
else:
print(f"✗ Google Cloud Storage check failed ({auth_type}) (status: {response.status_code})")
except Exception as e:
print(f"✗ Google Cloud Storage check error ({auth_type}): {e}")
def check_storage_upload(self):
"""Check if uploading to storageBucket is possible"""
if 'storageBucket' not in self.config:
print("No storageBucket provided, skipping upload check")
return
storage_bucket = self.config['storageBucket']
filename = f"poc_{self.random_string}.json"
upload_data = {"poc": self.random_string}
print(f"\nChecking storage upload capability")
# Test anonymous, authenticated legacy (Bearer), and modern (Firebase)
headers_list = [{"Content-Type": "application/json"}]
if self.id_token:
headers_list.append({
"Authorization": f"Bearer {self.id_token}",
"Content-Type": "application/json"
})
headers_list.append({
"Authorization": f"Firebase {self.id_token}",
"Content-Type": "application/json"
})
for i, headers in enumerate(headers_list):
if "Authorization" not in headers:
auth_type = "anonymous"
elif "Bearer" in headers.get("Authorization", ""):
auth_type = "authenticated (Bearer)"
else:
auth_type = "authenticated (Firebase)"
# Upload file
url = f"https://firebasestorage.googleapis.com/v0/b/{storage_bucket}/o?name={filename}"
curl_cmd = f"curl -X POST '{url}' -H 'Content-Type: application/json'"
if "Authorization" in headers:
curl_cmd += f" -H 'Authorization: {headers['Authorization']}'"
curl_cmd += f" -d '{json.dumps(upload_data)}'"
self._print_debug(f"Attempting upload ({auth_type})", curl_cmd)
try:
response = requests.post(url, headers=headers, json=upload_data)
if response.status_code == 200:
print(f"✓ Upload successful ({auth_type}) (status: {response.status_code})")
# Verify upload
verify_url = f"https://firebasestorage.googleapis.com/v0/b/{storage_bucket}/o/{filename}?alt=media"
verify_response = requests.get(verify_url)
if verify_response.status_code == 200:
print(f"✓ Upload verified ({auth_type}) (status: {verify_response.status_code})")
print(f" URL: {verify_url}")
else:
print(f"✗ Upload verification failed ({auth_type}) (status: {verify_response.status_code})")
else:
print(f"✗ Upload failed ({auth_type}) (status: {response.status_code})")
except Exception as e:
print(f"✗ Upload check error ({auth_type}): {e}")
def check_database_accessibility(self):
"""Check general database accessibility for common endpoints"""
if 'databaseURL' not in self.config:
print("No databaseURL provided, skipping accessibility checks")
return
database_url = self.config['databaseURL']
print(f"\nChecking database general accessibility")
# Common Firebase database endpoints to check
endpoints = [
"/.json",
"/Users.json",
"/users.json",
"/Logs.json",
"/logs.json",
"/Messages.json",
"/messages.json",
"/Posts.json",
"/posts.json",
"/Comments.json",
"/comments.json",
"/Profiles.json",
"/profiles.json",
"/Settings.json",
"/settings.json",
"/Config.json",
"/config.json"
]
# Test anonymous, authenticated legacy (Bearer), and modern (Firebase)
headers_list = [{}]
if self.id_token:
headers_list.append({"Authorization": f"Bearer {self.id_token}"})
headers_list.append({"Authorization": f"Firebase {self.id_token}"})
for i, headers in enumerate(headers_list):
if not headers:
auth_type = "anonymous"
elif "Bearer" in headers.get("Authorization", ""):
auth_type = "authenticated (Bearer)"
else:
auth_type = "authenticated (Firebase)"
accessible_endpoints = []
for endpoint in endpoints:
url = f"{database_url}{endpoint}"
curl_cmd = f"curl '{url}'"
if headers:
curl_cmd += f" -H 'Authorization: {headers['Authorization']}'"
try:
response = requests.get(url, headers=headers, timeout=5)
if response.status_code == 200:
accessible_endpoints.append(endpoint)
print(f"✓ Database endpoint accessible ({auth_type}): {endpoint} (status: {response.status_code})")
# Save data if it contains content
try:
data = response.json()
if data: # Only save if there's actual data
filename = f"database-{endpoint.replace('/', '').replace('.json', '')}-{auth_type.replace(' ', '-').replace('(', '').replace(')', '')}.json"
with open(filename, 'w') as f:
json.dump(data, f, indent=2)
print(f" Data saved to {filename}")
except Exception as e:
print(f" Could not parse/save data: {e}")
elif response.status_code == 401:
print(f"✗ Database endpoint requires auth ({auth_type}): {endpoint} (status: {response.status_code})")
elif response.status_code == 404:
# Don't print for 404s as this is expected for non-existent paths
pass
else:
print(f"- Database endpoint ({auth_type}): {endpoint} (status: {response.status_code})")
except requests.exceptions.Timeout:
print(f"- Database endpoint timeout ({auth_type}): {endpoint}")
except Exception as e:
# Silently skip connection errors for non-existent endpoints
pass
if accessible_endpoints:
print(f"\nSummary ({auth_type}): Found {len(accessible_endpoints)} accessible endpoints")
else:
print(f"\nSummary ({auth_type}): No accessible endpoints found")
def check_database_url(self):
"""Check if databaseURL is accessible and writable"""
if 'databaseURL' not in self.config:
print("No databaseURL provided, skipping database checks")
return
database_url = self.config['databaseURL']
poc_data = {"poc": self.random_string}
print(f"\nChecking database URL: {database_url}")
# Test anonymous, authenticated legacy (Bearer), and modern (Firebase)
headers_list = [{}]
if self.id_token:
headers_list.append({"Authorization": f"Bearer {self.id_token}"})
headers_list.append({"Authorization": f"Firebase {self.id_token}"})
for i, headers in enumerate(headers_list):
if not headers:
auth_type = "anonymous"
elif "Bearer" in headers.get("Authorization", ""):
auth_type = "authenticated (Bearer)"
else:
auth_type = "authenticated (Firebase)"
# Test with /o/ directory - PUT
write_url = f"{database_url}/o/poc_{self.random_string}.json"
curl_cmd = f"curl '{write_url}' -XPUT -d '{json.dumps(poc_data)}'"
if headers:
curl_cmd += f" -H 'Authorization: {headers['Authorization']}'"
self._print_debug(f"Attempting database PUT with /o/ ({auth_type})", curl_cmd)
try:
response = requests.put(write_url, headers=headers, json=poc_data)
if response.status_code == 200:
print(f"✓ Database PUT successful with /o/ ({auth_type}) (status: {response.status_code})")
# Verify write
verify_response = requests.get(write_url, headers=headers)
if verify_response.status_code == 200:
print(f"✓ Database PUT verified ({auth_type}) (status: {verify_response.status_code})")
print(f" URL: {write_url}")
else:
print(f"✗ Database PUT verification failed ({auth_type}) (status: {verify_response.status_code})")
else:
print(f"✗ Database PUT failed with /o/ ({auth_type}) (status: {response.status_code})")
except Exception as e:
print(f"✗ Database PUT error with /o/ ({auth_type}): {e}")
# Test with /o/ directory - POST
post_url = f"{database_url}/o/poc_{self.random_string}_post.json"
curl_cmd = f"curl '{post_url}' -XPOST -d '{json.dumps(poc_data)}'"
if headers:
curl_cmd += f" -H 'Authorization: {headers['Authorization']}'"
self._print_debug(f"Attempting database POST with /o/ ({auth_type})", curl_cmd)
try:
response = requests.post(post_url, headers=headers, json=poc_data)
if response.status_code == 200:
print(f"✓ Database POST successful with /o/ ({auth_type}) (status: {response.status_code})")
# POST usually returns the new key/ID
try:
result = response.json()
print(f" Created with ID: {result}")
except:
pass
else:
print(f"✗ Database POST failed with /o/ ({auth_type}) (status: {response.status_code})")
except Exception as e:
print(f"✗ Database POST error with /o/ ({auth_type}): {e}")
# Test direct write - PUT
direct_put_url = f"{database_url}/poc_{self.random_string}.json"
curl_cmd = f"curl '{direct_put_url}' -XPUT -d '{json.dumps(poc_data)}'"
if headers:
curl_cmd += f" -H 'Authorization: {headers['Authorization']}'"
self._print_debug(f"Attempting direct database PUT ({auth_type})", curl_cmd)
try:
response = requests.put(direct_put_url, headers=headers, json=poc_data)
if response.status_code == 200:
print(f"✓ Direct database PUT successful ({auth_type}) (status: {response.status_code})")
# Verify write
verify_response = requests.get(direct_put_url, headers=headers)
if verify_response.status_code == 200:
print(f"✓ Direct database PUT verified ({auth_type}) (status: {verify_response.status_code})")
print(f" URL: {direct_put_url}")
else:
print(f"✗ Direct database PUT verification failed ({auth_type}) (status: {verify_response.status_code})")
else:
print(f"✗ Direct database PUT failed ({auth_type}) (status: {response.status_code})")
except Exception as e:
print(f"✗ Direct database PUT error ({auth_type}): {e}")
# Test direct write - POST
direct_post_url = f"{database_url}/poc_{self.random_string}_post.json"
curl_cmd = f"curl '{direct_post_url}' -XPOST -d '{json.dumps(poc_data)}'"
if headers:
curl_cmd += f" -H 'Authorization: {headers['Authorization']}'"
self._print_debug(f"Attempting direct database POST ({auth_type})", curl_cmd)
try:
response = requests.post(direct_post_url, headers=headers, json=poc_data)
if response.status_code == 200:
print(f"✓ Direct database POST successful ({auth_type}) (status: {response.status_code})")
# POST usually returns the new key/ID
try:
result = response.json()
print(f" Created with ID: {result}")
except:
pass
else:
print(f"✗ Direct database POST failed ({auth_type}) (status: {response.status_code})")
except Exception as e:
print(f"✗ Direct database POST error ({auth_type}): {e}")
def check_remote_config(self):
"""Check if remote config is accessible"""
if 'apiKey' not in self.config or 'messagingSenderId' not in self.config or 'appId' not in self.config:
print("Missing required fields for remote config check (apiKey, messagingSenderId, appId)")
return
print(f"\nChecking remote config access")
url = f"https://firebaseremoteconfig.googleapis.com/v1/projects/{self.config['messagingSenderId']}/namespaces/firebase:fetch?key={self.config['apiKey']}"
headers = {'Content-Type': 'application/json'}
data = {
"appId": self.config['appId'],
"appInstanceId": "PROD"
}
curl_cmd = f"curl -X POST '{url}' -H 'Content-Type: application/json' --data '{json.dumps(data)}'"
self._print_debug(f"Checking remote config", curl_cmd)
try:
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
result = response.json()
if 'entries' in result:
print(f"✓ Remote config accessible (status: {response.status_code})")
with open('remoteconfig.json', 'w') as f:
json.dump(result, f, indent=2)
print(f" Config saved to remoteconfig.json")
elif result.get('state') == 'NO_TEMPLATE':
print(f"- Remote config: No template configured (status: {response.status_code})")
else:
print(f"✗ Remote config check: Unknown response (status: {response.status_code})")
else:
print(f"✗ Remote config check failed (status: {response.status_code})")
except Exception as e:
print(f"✗ Remote config check error: {e}")
def check_crashlytics(self):
"""Check for Crashlytics data access (additional check)"""
if 'appId' not in self.config or 'apiKey' not in self.config:
print("Missing required fields for Crashlytics check")
return
print(f"\nChecking Crashlytics access")
url = f"https://firebasecrashlytics.googleapis.com/v1/projects/{self.config.get('projectId', 'unknown')}/apps/{self.config['appId']}/issues"
headers = {'X-Goog-Api-Key': self.config['apiKey']}
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
print(f"✓ Crashlytics data accessible (status: {response.status_code})")
else:
print(f"✗ Crashlytics not accessible (status: {response.status_code})")
except Exception as e:
print(f"✗ Crashlytics check error: {e}")
def check_firestore_collections(self):
"""Check for accessible Firestore collections"""
if 'projectId' not in self.config:
print("No projectId provided, skipping Firestore collection checks")
return
project_id = self.config['projectId']
print(f"\nChecking Firestore collections accessibility")
# Common collection names to check
collections = [
"users", "Users", "log", "Log", "logs", "Logs",
"upload", "Upload", "uploads", "Uploads", "images", "Images",
"files", "Files", "settings", "Settings", "messages", "Messages",
"config", "Config"
]
# Test anonymous, authenticated legacy (Bearer), and modern (Firebase)
headers_list = [{}]
if self.id_token:
headers_list.append({"Authorization": f"Bearer {self.id_token}"})
headers_list.append({"Authorization": f"Firebase {self.id_token}"})
for i, headers in enumerate(headers_list):
if not headers:
auth_type = "anonymous"
elif "Bearer" in headers.get("Authorization", ""):
auth_type = "authenticated (Bearer)"
else:
auth_type = "authenticated (Firebase)"
accessible_collections = []
for collection in collections:
url = f"https://firestore.googleapis.com/v1/projects/{project_id}/databases/(default)/documents/{collection}"
curl_cmd = f"curl '{url}'"
if headers:
curl_cmd += f" -H 'Authorization: {headers['Authorization']}'"
try:
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 200:
accessible_collections.append(collection)
print(f"✓ Firestore collection accessible ({auth_type}): {collection} (status: {response.status_code})")
# Save collection data if it contains content
try:
data = response.json()
if data and 'documents' in data: # Only save if there are documents
filename = f"firestore-{collection}-{auth_type.replace(' ', '-').replace('(', '').replace(')', '')}.json"
with open(filename, 'w') as f:
json.dump(data, f, indent=2)
print(f" Collection data saved to {filename}")
except Exception as e:
print(f" Could not parse/save collection data: {e}")
elif response.status_code == 401:
print(f"✗ Firestore collection requires auth ({auth_type}): {collection} (status: {response.status_code})")
elif response.status_code == 403:
print(f"✗ Firestore collection access denied ({auth_type}): {collection} (status: {response.status_code})")
elif response.status_code == 404:
# Don't print for 404s as this is expected for non-existent collections
pass
else:
print(f"- Firestore collection ({auth_type}): {collection} (status: {response.status_code})")
except requests.exceptions.Timeout:
print(f"- Firestore collection timeout ({auth_type}): {collection}")
except Exception as e:
# Silently skip connection errors for non-existent collections
pass
if accessible_collections:
print(f"\nFirestore Summary ({auth_type}): Found {len(accessible_collections)} accessible collections")
else:
print(f"\nFirestore Summary ({auth_type}): No accessible collections found")
def run_all_checks(self, email: str, password: str):
"""Run all security checks"""
print(f"Starting Firebase configuration security tests...\n")
print(f"Configuration fields found: {', '.join(self.config.keys())}\n")
# Check 1: Registration
self.check_registration(email, password)
# Check 2: Storage bucket access
self.check_storage_bucket()
# Check 3: Storage upload
self.check_storage_upload()
# Check 4: Database URL
self.check_database_url()
# Check 4.5: Database general accessibility
self.check_database_accessibility()
# Check 5: Remote config
self.check_remote_config()
# Check 6: Firestore collections
self.check_firestore_collections()
# Additional checks
self.check_crashlytics()
print(f"\nAll checks completed!")
def parse_firebase_config(config_string: str) -> Dict[str, str]:
"""Parse Firebase configuration from various formats"""
# Strip any leading/trailing whitespace
config_string = config_string.strip()
# First try to parse as valid JSON directly
try:
config = json.loads(config_string)
return config
except json.JSONDecodeError:
pass
# Remove comments and clean up the string (but preserve URLs and quoted strings)
lines = []
for line in config_string.split('\n'):
# More sophisticated comment removal that preserves URLs
cleaned_line = ""
in_quotes = False
quote_char = None
i = 0
while i < len(line):
char = line[i]
# Handle quotes
if char in ['"', "'"] and (i == 0 or line[i-1] != '\\'):
if not in_quotes:
in_quotes = True
quote_char = char
elif char == quote_char:
in_quotes = False
quote_char = None
cleaned_line += char
i += 1
# Handle // comments (only outside quotes)
elif not in_quotes and char == '/' and i + 1 < len(line) and line[i + 1] == '/':
# Check if this is part of a protocol (preceded by :)
if i > 0 and line[i-1] == ':':
# This is likely a URL, keep it
cleaned_line += char
i += 1
else:
# This is a comment, stop processing this line
break
else:
cleaned_line += char
i += 1
# Remove /* */ style comments (simple approach for now)
cleaned_line = re.sub(r'/\*.*?\*/', '', cleaned_line)
lines.append(cleaned_line)
config_string = '\n'.join(lines)
# Try robust JavaScript object parsing that handles colons in values
try:
config = _parse_js_object_string(config_string)
if config:
return config
except Exception:
pass
# Try to convert JavaScript object notation to valid JSON
# This handles multiple formats: unquoted keys, single quotes, etc.
try:
# Handle cases where the object might not be wrapped in braces
if not config_string.strip().startswith('{'):
config_string = '{' + config_string + '}'
# Step 1: Handle unquoted keys (convert to quoted keys)
# Match unquoted keys more carefully - only at the beginning of lines or after commas/braces
# This regex looks for word characters that are followed by optional whitespace and a colon,
# but only when they're at the start of a line (after whitespace) or after { or ,
config_string = re.sub(r'(^|\s|[{,])\s*(\w+)(\s*):', r'\1"\2"\3:', config_string, flags=re.MULTILINE)
# Step 2: Replace single quotes with double quotes for string values
# Be more careful - only replace single quotes that surround complete values
config_string = re.sub(r":\s*'([^']*)'", r': "\1"', config_string)
# Step 3: Remove trailing commas before closing braces/brackets
config_string = re.sub(r',(\s*[}\]])', r'\1', config_string)
# Try to parse as JSON
config = json.loads(config_string)
return config
except json.JSONDecodeError as e:
# If JSON conversion fails, fall back to regex parsing
pass
# Fallback: Extract key-value pairs using a more sophisticated line-by-line approach
config = {}
for line in config_string.split('\n'):
line = line.strip()
# Skip empty lines, comments, and braces
if not line or line.startswith('#') or line.startswith('//') or line in ['{', '}', ',']:
continue
# Remove trailing comma if present
line = line.rstrip(',')
# Find the key-value separator (first colon not inside quotes)
if ':' not in line:
continue
# Parse the line character by character to find the key-value separator
key_end = -1
in_quotes = False
quote_char = None
for i, char in enumerate(line):
if char in ['"', "'"] and (i == 0 or line[i-1] != '\\'):
if not in_quotes:
in_quotes = True
quote_char = char
elif char == quote_char:
in_quotes = False
quote_char = None
elif char == ':' and not in_quotes:
key_end = i
break
if key_end == -1:
continue
# Extract key and value parts
key_part = line[:key_end]
value_part = line[key_end + 1:]
# Clean up the key (remove quotes and whitespace)
key = key_part.strip().strip('\'"')
# Clean up the value - handle quoted strings properly
value = value_part.strip()
if (value.startswith('"') and value.endswith('"')) or (value.startswith("'") and value.endswith("'")):
# Properly quoted value - remove the outer quotes
value = value[1:-1]
# Store the key-value pair
if key:
config[key] = value
if config:
return config
# If all attempts fail, raise an error
raise ValueError("Unable to parse Firebase configuration. Please check the format.\n"
"Supported formats:\n"
'- JSON: {"apiKey":"value","authDomain":"value"}\n'
"- Unquoted keys: {apiKey:'value',authDomain:'value'}\n"
"- Mixed quotes: {apiKey:\"value\",authDomain:'value'}\n"
"- Multiline with whitespace")
def _parse_js_object_string(js_string: str) -> Dict[str, str]:
"""
Parse a JavaScript-like object string to a Python dictionary.
Handles cases where values contain colons (like URLs, paths, etc.).
Args:
js_string (str): String in format {key:"value",key2:"value:with:colons"}
Returns:
dict: Parsed key-value pairs
"""
# Remove outer braces and whitespace
content = js_string.strip()
if content.startswith('{') and content.endswith('}'):
content = content[1:-1]
# Dictionary to store results
result = {}
# Split by commas, but respect quoted strings
pairs = []
current_pair = ""
in_quotes = False
escape_next = False
for char in content:
if escape_next:
current_pair += char
escape_next = False
continue
if char == '\\':
current_pair += char
escape_next = True
continue
if char == '"':
in_quotes = not in_quotes
current_pair += char
elif char == ',' and not in_quotes:
if current_pair.strip():
pairs.append(current_pair.strip())
current_pair = ""
else:
current_pair += char
# Don't forget the last pair
if current_pair.strip():
pairs.append(current_pair.strip())
# Parse each key-value pair
for pair in pairs:
# Find the first colon that's not inside quotes
colon_pos = -1
in_quotes = False
escape_next = False
for i, char in enumerate(pair):
if escape_next:
escape_next = False
continue
if char == '\\':
escape_next = True
continue
if char == '"':
in_quotes = not in_quotes
elif char == ':' and not in_quotes:
colon_pos = i
break
if colon_pos == -1:
continue # Skip malformed pairs
# Extract key and value
key_part = pair[:colon_pos].strip()
value_part = pair[colon_pos + 1:].strip()
# Remove quotes from key if present
if key_part.startswith('"') and key_part.endswith('"'):
key = key_part[1:-1]
else:
key = key_part
# Remove quotes from value if present
if value_part.startswith('"') and value_part.endswith('"'):
value = value_part[1:-1]
else:
value = value_part
result[key] = value
return result
def main():
parser = argparse.ArgumentParser(description='Test Firebase configurations for security misconfigurations')
# Configuration input methods
parser.add_argument('--firebase-config', type=str, help='Firebase config as JSON string')
parser.add_argument('--api-key', type=str, help='Firebase API key')
parser.add_argument('--auth-domain', type=str, help='Firebase auth domain')
parser.add_argument('--database-url', type=str, help='Firebase database URL')
parser.add_argument('--project-id', type=str, help='Firebase project ID')
parser.add_argument('--storage-bucket', type=str, help='Firebase storage bucket')
parser.add_argument('--sender-id', type=str, help='Firebase messaging sender ID')
parser.add_argument('--app-id', type=str, help='Firebase app ID')
parser.add_argument('--measurement-id', type=str, help='Firebase measurement ID')
# Test options
parser.add_argument('--email', type=str, default='test@bugbounty.com', help='Email for registration test')
parser.add_argument('--password', type=str, default='TestPassword123!', help='Password for registration test')
parser.add_argument('-d', '--debug', action='store_true', help='Enable debug output with curl commands')
args = parser.parse_args()
# Build configuration dictionary
config = {}
if args.firebase_config:
try:
print(f"Parsing Firebase configuration...")
if args.debug:
print(f"Original config: {args.firebase_config}")
config = parse_firebase_config(args.firebase_config)
if args.debug:
print(f"Parsed config: {json.dumps(config, indent=2)}")
except Exception as e:
print(f"Error parsing Firebase config: {e}")
sys.exit(1)
# Override with individual arguments if provided
if args.api_key:
config['apiKey'] = args.api_key
if args.auth_domain:
config['authDomain'] = args.auth_domain
if args.database_url:
config['databaseURL'] = args.database_url
if args.project_id:
config['projectId'] = args.project_id
if args.storage_bucket:
config['storageBucket'] = args.storage_bucket
if args.sender_id:
config['messagingSenderId'] = args.sender_id
if args.app_id:
config['appId'] = args.app_id
if args.measurement_id:
config['measurementId'] = args.measurement_id
if not config:
print("No Firebase configuration provided!")
parser.print_help()
sys.exit(1)
# Create tester and run checks
tester = FirebaseConfigTester(config, debug=args.debug)
tester.run_all_checks(args.email, args.password)
if __name__ == '__main__':
main()