forked from parse-community/parse-server
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvulnerabilities.spec.js
More file actions
2647 lines (2445 loc) · 92.1 KB
/
vulnerabilities.spec.js
File metadata and controls
2647 lines (2445 loc) · 92.1 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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const http = require('http');
const express = require('express');
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
const ws = require('ws');
const request = require('../lib/request');
const Config = require('../lib/Config');
const { ParseGraphQLServer } = require('../lib/GraphQL/ParseGraphQLServer');
describe('Vulnerabilities', () => {
describe('(GHSA-8xq9-g7ch-35hg) Custom object ID allows to acquire role privilege', () => {
beforeAll(async () => {
await reconfigureServer({ allowCustomObjectId: true });
Parse.allowCustomObjectId = true;
});
afterAll(async () => {
await reconfigureServer({ allowCustomObjectId: false });
Parse.allowCustomObjectId = false;
});
it('denies user creation with poisoned object ID', async () => {
const logger = require('../lib/logger').default;
const loggerErrorSpy = spyOn(logger, 'error').and.callThrough();
loggerErrorSpy.calls.reset();
await expectAsync(
new Parse.User({ id: 'role:a', username: 'a', password: '123' }).save()
).toBeRejectedWith(new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, 'Permission denied'));
expect(loggerErrorSpy).toHaveBeenCalledWith('Sanitized error:', jasmine.stringContaining("Invalid object ID."));
});
describe('existing sessions for users with poisoned object ID', () => {
/** @type {Parse.User} */
let poisonedUser;
/** @type {Parse.User} */
let innocentUser;
beforeAll(async () => {
const parseServer = await global.reconfigureServer();
const databaseController = parseServer.config.databaseController;
[poisonedUser, innocentUser] = await Promise.all(
['role:abc', 'abc'].map(async id => {
// Create the users directly on the db to bypass the user creation check
await databaseController.create('_User', { objectId: id });
// Use the master key to create a session for them to bypass the session check
return Parse.User.loginAs(id);
})
);
});
it('refuses session token of user with poisoned object ID', async () => {
await expectAsync(
new Parse.Query(Parse.User).find({ sessionToken: poisonedUser.getSessionToken() })
).toBeRejectedWith(new Parse.Error(Parse.Error.INTERNAL_SERVER_ERROR, 'Invalid object ID.'));
await new Parse.Query(Parse.User).find({ sessionToken: innocentUser.getSessionToken() });
});
});
describe('legacy session upgrade for user with poisoned object ID', () => {
// Legacy session tokens (_session_token on _User) are a MongoDB-only legacy feature
it_only_db('mongo')('refuses legacy session upgrade for user with poisoned object ID', async () => {
const parseServer = await global.reconfigureServer();
const databaseController = parseServer.config.databaseController;
const poisonedId = 'role:legacy';
const legacyToken = 'legacy-poisoned-token';
// Create user with poisoned ID and legacy session token directly in DB
await databaseController.create('_User', {
objectId: poisonedId,
_session_token: legacyToken,
});
await expectAsync(
request({
method: 'POST',
url: 'http://localhost:8378/1/upgradeToRevocableSession',
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
'X-Parse-Session-Token': legacyToken,
},
body: JSON.stringify({}),
})
).toBeRejected();
});
});
});
describe('Object prototype pollution', () => {
it('denies object prototype to be polluted with keyword "constructor"', async () => {
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
};
const response = await request({
headers: headers,
method: 'POST',
url: 'http://localhost:8378/1/classes/PP',
body: JSON.stringify({
obj: {
constructor: {
prototype: {
dummy: 0,
},
},
},
}),
}).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.INVALID_KEY_NAME);
expect(text.error).toBe('Prohibited keyword in request data: {"key":"constructor"}.');
expect(Object.prototype.dummy).toBeUndefined();
});
it('denies object prototype to be polluted with keypath string "constructor"', async () => {
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
};
const objResponse = await request({
headers: headers,
method: 'POST',
url: 'http://localhost:8378/1/classes/PP',
body: JSON.stringify({
obj: {},
}),
}).catch(e => e);
const pollResponse = await request({
headers: headers,
method: 'PUT',
url: `http://localhost:8378/1/classes/PP/${objResponse.data.objectId}`,
body: JSON.stringify({
'obj.constructor.prototype.dummy': {
__op: 'Increment',
amount: 1,
},
}),
}).catch(e => e);
expect(Object.prototype.dummy).toBeUndefined();
expect(pollResponse.status).toBe(400);
const text = JSON.parse(pollResponse.text);
expect(text.code).toBe(Parse.Error.INVALID_KEY_NAME);
expect(text.error).toBe('Prohibited keyword in request data: {"key":"constructor"}.');
expect(Object.prototype.dummy).toBeUndefined();
});
it('denies object prototype to be polluted with keyword "__proto__"', async () => {
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
};
const response = await request({
headers: headers,
method: 'POST',
url: 'http://localhost:8378/1/classes/PP',
body: JSON.stringify({ 'obj.__proto__.dummy': 0 }),
}).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.INVALID_KEY_NAME);
expect(text.error).toBe('Prohibited keyword in request data: {"key":"__proto__"}.');
expect(Object.prototype.dummy).toBeUndefined();
});
});
describe('(GHSA-5j86-7r7m-p8h6) Cloud function name prototype chain bypass', () => {
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
};
it('rejects "constructor" as cloud function name', async () => {
const response = await request({
headers,
method: 'POST',
url: 'http://localhost:8378/1/functions/constructor',
body: JSON.stringify({}),
}).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.SCRIPT_FAILED);
expect(text.error).toContain('Invalid function');
});
it('rejects "toString" as cloud function name', async () => {
const response = await request({
headers,
method: 'POST',
url: 'http://localhost:8378/1/functions/toString',
body: JSON.stringify({}),
}).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.SCRIPT_FAILED);
expect(text.error).toContain('Invalid function');
});
it('rejects "valueOf" as cloud function name', async () => {
const response = await request({
headers,
method: 'POST',
url: 'http://localhost:8378/1/functions/valueOf',
body: JSON.stringify({}),
}).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.SCRIPT_FAILED);
expect(text.error).toContain('Invalid function');
});
it('rejects "hasOwnProperty" as cloud function name', async () => {
const response = await request({
headers,
method: 'POST',
url: 'http://localhost:8378/1/functions/hasOwnProperty',
body: JSON.stringify({}),
}).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.SCRIPT_FAILED);
expect(text.error).toContain('Invalid function');
});
it('rejects "__proto__.toString" as cloud function name', async () => {
const response = await request({
headers,
method: 'POST',
url: 'http://localhost:8378/1/functions/__proto__.toString',
body: JSON.stringify({}),
}).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.SCRIPT_FAILED);
expect(text.error).toContain('Invalid function');
});
it('still executes a legitimately defined cloud function', async () => {
Parse.Cloud.define('legitimateFunction', () => 'hello');
const response = await request({
headers,
method: 'POST',
url: 'http://localhost:8378/1/functions/legitimateFunction',
body: JSON.stringify({}),
});
expect(response.status).toBe(200);
expect(JSON.parse(response.text).result).toBe('hello');
});
});
describe('(GHSA-3v4q-4q9g-x83q) Prototype pollution via application ID in trigger store', () => {
const prototypeProperties = ['constructor', 'toString', 'valueOf', 'hasOwnProperty', '__proto__'];
for (const prop of prototypeProperties) {
it(`rejects "${prop}" as application ID in cloud function call`, async () => {
const response = await request({
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': prop,
'X-Parse-REST-API-Key': 'rest',
},
method: 'POST',
url: 'http://localhost:8378/1/functions/testFunction',
body: JSON.stringify({}),
}).catch(e => e);
expect(response.status).toBe(403);
});
it(`rejects "${prop}" as application ID with arbitrary API key in cloud function call`, async () => {
const response = await request({
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': prop,
'X-Parse-REST-API-Key': 'ANY_KEY',
},
method: 'POST',
url: 'http://localhost:8378/1/functions/testFunction',
body: JSON.stringify({}),
}).catch(e => e);
expect(response.status).toBe(403);
});
it(`rejects "${prop}" as application ID in class query`, async () => {
const response = await request({
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': prop,
'X-Parse-REST-API-Key': 'rest',
},
method: 'GET',
url: 'http://localhost:8378/1/classes/TestClass',
}).catch(e => e);
expect(response.status).toBe(403);
});
}
});
describe('Request denylist', () => {
describe('(GHSA-q342-9w2p-57fp) Denylist bypass via sibling nested objects', () => {
it('denies _bsontype:Code after a sibling nested object', async () => {
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
};
const response = await request({
headers,
method: 'POST',
url: 'http://localhost:8378/1/classes/Bypass',
body: JSON.stringify({
obj: {
metadata: {},
_bsontype: 'Code',
code: 'malicious',
},
}),
}).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.INVALID_KEY_NAME);
expect(text.error).toBe(
'Prohibited keyword in request data: {"key":"_bsontype","value":"Code"}.'
);
});
it('denies _bsontype:Code after a sibling nested array', async () => {
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
};
const response = await request({
headers,
method: 'POST',
url: 'http://localhost:8378/1/classes/Bypass',
body: JSON.stringify({
obj: {
tags: ['safe'],
_bsontype: 'Code',
code: 'malicious',
},
}),
}).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.INVALID_KEY_NAME);
expect(text.error).toBe(
'Prohibited keyword in request data: {"key":"_bsontype","value":"Code"}.'
);
});
it('denies __proto__ after a sibling nested object', async () => {
// Cannot test via HTTP because deepcopy() strips __proto__ before the denylist
// check runs. Test objectContainsKeyValue directly with a JSON.parse'd object
// that preserves __proto__ as an own property.
const Utils = require('../lib/Utils');
const data = JSON.parse('{"profile": {"name": "alice"}, "__proto__": {"isAdmin": true}}');
expect(Utils.objectContainsKeyValue(data, '__proto__', undefined)).toBe(true);
});
it('denies constructor after a sibling nested object', async () => {
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
};
const response = await request({
headers,
method: 'POST',
url: 'http://localhost:8378/1/classes/Bypass',
body: JSON.stringify({
obj: {
data: {},
constructor: { prototype: { polluted: true } },
},
}),
}).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.INVALID_KEY_NAME);
expect(text.error).toBe(
'Prohibited keyword in request data: {"key":"constructor"}.'
);
});
it('denies _bsontype:Code nested inside a second sibling object', async () => {
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
};
const response = await request({
headers,
method: 'POST',
url: 'http://localhost:8378/1/classes/Bypass',
body: JSON.stringify({
field1: { safe: true },
field2: { _bsontype: 'Code', code: 'malicious' },
}),
}).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.INVALID_KEY_NAME);
expect(text.error).toBe(
'Prohibited keyword in request data: {"key":"_bsontype","value":"Code"}.'
);
});
it('handles circular references without infinite loop', () => {
const Utils = require('../lib/Utils');
const obj = { name: 'test', nested: { value: 1 } };
obj.nested.self = obj;
expect(Utils.objectContainsKeyValue(obj, 'nonexistent', undefined)).toBe(false);
});
it('denies _bsontype:Code in file metadata after a sibling nested object', async () => {
const str = 'Hello World!';
const data = [];
for (let i = 0; i < str.length; i++) {
data.push(str.charCodeAt(i));
}
const file = new Parse.File('hello.txt', data, 'text/plain');
file.addMetadata('nested', { safe: true });
file.addMetadata('_bsontype', 'Code');
file.addMetadata('code', 'malicious');
await expectAsync(file.save()).toBeRejectedWith(
new Parse.Error(
Parse.Error.INVALID_KEY_NAME,
'Prohibited keyword in request data: {"key":"_bsontype","value":"Code"}.'
)
);
});
});
it('denies BSON type code data in write request by default', async () => {
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
};
const params = {
headers: headers,
method: 'POST',
url: 'http://localhost:8378/1/classes/RCE',
body: JSON.stringify({
obj: {
_bsontype: 'Code',
code: 'delete Object.prototype.evalFunctions',
},
}),
};
const response = await request(params).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.INVALID_KEY_NAME);
expect(text.error).toBe(
'Prohibited keyword in request data: {"key":"_bsontype","value":"Code"}.'
);
});
it('denies expanding existing object with polluted keys', async () => {
const obj = await new Parse.Object('RCE', { a: { foo: [] } }).save();
await reconfigureServer({
requestKeywordDenylist: ['foo'],
});
obj.addUnique('a.foo', 'abc');
await expectAsync(obj.save()).toBeRejectedWith(
new Parse.Error(Parse.Error.INVALID_KEY_NAME, `Prohibited keyword in request data: "foo".`)
);
});
it('denies creating a cloud trigger with polluted data', async () => {
Parse.Cloud.beforeSave('TestObject', ({ object }) => {
object.set('obj', {
constructor: {
prototype: {
dummy: 0,
},
},
});
});
// The new Parse SDK handles prototype pollution prevention in .set()
// so no error is thrown, but the object prototype should not be polluted
await new Parse.Object('TestObject').save();
expect(Object.prototype.dummy).toBeUndefined();
});
it('denies creating global config with polluted data', async () => {
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-Master-Key': 'test',
};
const params = {
method: 'PUT',
url: 'http://localhost:8378/1/config',
json: true,
body: {
params: {
welcomeMesssage: 'Welcome to Parse',
foo: { _bsontype: 'Code', code: 'shell' },
},
},
headers,
};
const response = await request(params).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.INVALID_KEY_NAME);
expect(text.error).toBe(
'Prohibited keyword in request data: {"key":"_bsontype","value":"Code"}.'
);
});
it('denies direct database write wih prohibited keys', async () => {
const Config = require('../lib/Config');
const config = Config.get(Parse.applicationId);
const user = {
objectId: '1234567890',
username: 'hello',
password: 'pass',
_session_token: 'abc',
foo: { _bsontype: 'Code', code: 'shell' },
};
await expectAsync(config.database.create('_User', user)).toBeRejectedWith(
new Parse.Error(
Parse.Error.INVALID_KEY_NAME,
'Prohibited keyword in request data: {"key":"_bsontype","value":"Code"}.'
)
);
});
it('denies direct database update wih prohibited keys', async () => {
const Config = require('../lib/Config');
const config = Config.get(Parse.applicationId);
const user = {
objectId: '1234567890',
username: 'hello',
password: 'pass',
_session_token: 'abc',
foo: { _bsontype: 'Code', code: 'shell' },
};
await expectAsync(
config.database.update('_User', { _id: user.objectId }, user)
).toBeRejectedWith(
new Parse.Error(
Parse.Error.INVALID_KEY_NAME,
'Prohibited keyword in request data: {"key":"_bsontype","value":"Code"}.'
)
);
});
it_id('e8b5f1e1-8326-4c70-b5f4-1e8678dfff8d')(it)('denies creating a hook with polluted data', async () => {
const express = require('express');
const port = 34567;
const hookServerURL = 'http://localhost:' + port;
const app = express();
app.use(express.json({ type: '*/*' }));
const server = await new Promise(resolve => {
const res = app.listen(port, undefined, () => resolve(res));
});
app.post('/BeforeSave', function (req, res) {
const object = Parse.Object.fromJSON(req.body.object);
object.set('hello', 'world');
object.set('obj', {
constructor: {
prototype: {
dummy: 0,
},
},
});
res.json({ success: object });
});
await Parse.Hooks.createTrigger('TestObject', 'beforeSave', hookServerURL + '/BeforeSave');
// The new Parse SDK handles prototype pollution prevention in .set()
// so no error is thrown, but the object prototype should not be polluted
await new Parse.Object('TestObject').save();
expect(Object.prototype.dummy).toBeUndefined();
await new Promise(resolve => server.close(resolve));
});
it('denies write request with custom denylist of key/value', async () => {
await reconfigureServer({
requestKeywordDenylist: [{ key: 'a[K]ey', value: 'aValue[123]*' }],
});
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
};
const params = {
headers: headers,
method: 'POST',
url: 'http://localhost:8378/1/classes/RCE',
body: JSON.stringify({
obj: {
aKey: 'aValue321',
code: 'delete Object.prototype.evalFunctions',
},
}),
};
const response = await request(params).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.INVALID_KEY_NAME);
expect(text.error).toBe(
'Prohibited keyword in request data: {"key":"a[K]ey","value":"aValue[123]*"}.'
);
});
it('denies write request with custom denylist of nested key/value', async () => {
await reconfigureServer({
requestKeywordDenylist: [{ key: 'a[K]ey', value: 'aValue[123]*' }],
});
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
};
const params = {
headers: headers,
method: 'POST',
url: 'http://localhost:8378/1/classes/RCE',
body: JSON.stringify({
obj: {
nested: {
aKey: 'aValue321',
code: 'delete Object.prototype.evalFunctions',
},
},
}),
};
const response = await request(params).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.INVALID_KEY_NAME);
expect(text.error).toBe(
'Prohibited keyword in request data: {"key":"a[K]ey","value":"aValue[123]*"}.'
);
});
it('denies write request with custom denylist of key/value in array', async () => {
await reconfigureServer({
requestKeywordDenylist: [{ key: 'a[K]ey', value: 'aValue[123]*' }],
});
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
};
const params = {
headers: headers,
method: 'POST',
url: 'http://localhost:8378/1/classes/RCE',
body: JSON.stringify({
obj: [
{
aKey: 'aValue321',
code: 'delete Object.prototype.evalFunctions',
},
],
}),
};
const response = await request(params).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.INVALID_KEY_NAME);
expect(text.error).toBe(
'Prohibited keyword in request data: {"key":"a[K]ey","value":"aValue[123]*"}.'
);
});
it('denies write request with custom denylist of key', async () => {
await reconfigureServer({
requestKeywordDenylist: [{ key: 'a[K]ey' }],
});
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
};
const params = {
headers: headers,
method: 'POST',
url: 'http://localhost:8378/1/classes/RCE',
body: JSON.stringify({
obj: {
aKey: 'aValue321',
code: 'delete Object.prototype.evalFunctions',
},
}),
};
const response = await request(params).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.INVALID_KEY_NAME);
expect(text.error).toBe('Prohibited keyword in request data: {"key":"a[K]ey"}.');
});
it('denies write request with custom denylist of value', async () => {
await reconfigureServer({
requestKeywordDenylist: [{ value: 'aValue[123]*' }],
});
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
};
const params = {
headers: headers,
method: 'POST',
url: 'http://localhost:8378/1/classes/RCE',
body: JSON.stringify({
obj: {
aKey: 'aValue321',
code: 'delete Object.prototype.evalFunctions',
},
}),
};
const response = await request(params).catch(e => e);
expect(response.status).toBe(400);
const text = JSON.parse(response.text);
expect(text.code).toBe(Parse.Error.INVALID_KEY_NAME);
expect(text.error).toBe('Prohibited keyword in request data: {"value":"aValue[123]*"}.');
});
it('denies BSON type code data in file metadata', async () => {
const str = 'Hello World!';
const data = [];
for (let i = 0; i < str.length; i++) {
data.push(str.charCodeAt(i));
}
const file = new Parse.File('hello.txt', data, 'text/plain');
file.addMetadata('obj', {
_bsontype: 'Code',
code: 'delete Object.prototype.evalFunctions',
});
await expectAsync(file.save()).toBeRejectedWith(
new Parse.Error(
Parse.Error.INVALID_KEY_NAME,
`Prohibited keyword in request data: {"key":"_bsontype","value":"Code"}.`
)
);
});
it('denies BSON type code data in file tags', async () => {
const str = 'Hello World!';
const data = [];
for (let i = 0; i < str.length; i++) {
data.push(str.charCodeAt(i));
}
const file = new Parse.File('hello.txt', data, 'text/plain');
file.addTag('obj', {
_bsontype: 'Code',
code: 'delete Object.prototype.evalFunctions',
});
await expectAsync(file.save()).toBeRejectedWith(
new Parse.Error(
Parse.Error.INVALID_KEY_NAME,
`Prohibited keyword in request data: {"key":"_bsontype","value":"Code"}.`
)
);
});
});
describe('Ignore non-matches', () => {
it('ignores write request that contains only fraction of denied keyword', async () => {
await reconfigureServer({
requestKeywordDenylist: [{ key: 'abc' }],
});
// Initially saving an object executes the keyword detection in RestWrite.js
const obj = new TestObject({ a: { b: { c: 0 } } });
await expectAsync(obj.save()).toBeResolved();
// Modifying a nested key executes the keyword detection in DatabaseController.js
obj.increment('a.b.c');
await expectAsync(obj.save()).toBeResolved();
});
});
});
describe('Malformed $regex information disclosure', () => {
it('should not leak database error internals for invalid regex pattern in class query', async () => {
const logger = require('../lib/logger').default;
const loggerErrorSpy = spyOn(logger, 'error').and.callThrough();
const obj = new Parse.Object('TestObject');
await obj.save({ field: 'value' });
try {
await request({
method: 'GET',
url: `http://localhost:8378/1/classes/TestObject`,
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
},
qs: {
where: JSON.stringify({ field: { $regex: '[abc' } }),
},
});
fail('Request should have failed');
} catch (e) {
expect(e.data.code).toBe(Parse.Error.INTERNAL_SERVER_ERROR);
expect(e.data.error).toBe('An internal server error occurred');
expect(typeof e.data.error).toBe('string');
expect(JSON.stringify(e.data)).not.toContain('errmsg');
expect(JSON.stringify(e.data)).not.toContain('codeName');
expect(JSON.stringify(e.data)).not.toContain('errorResponse');
expect(loggerErrorSpy).toHaveBeenCalledWith(
'Sanitized error:',
jasmine.stringMatching(/[Rr]egular expression/i)
);
}
});
it('should not leak database error internals for invalid regex pattern in role query', async () => {
const logger = require('../lib/logger').default;
const loggerErrorSpy = spyOn(logger, 'error').and.callThrough();
const role = new Parse.Role('testrole', new Parse.ACL());
await role.save(null, { useMasterKey: true });
try {
await request({
method: 'GET',
url: `http://localhost:8378/1/roles`,
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
},
qs: {
where: JSON.stringify({ name: { $regex: '[abc' } }),
},
});
fail('Request should have failed');
} catch (e) {
expect(e.data.code).toBe(Parse.Error.INTERNAL_SERVER_ERROR);
expect(e.data.error).toBe('An internal server error occurred');
expect(typeof e.data.error).toBe('string');
expect(JSON.stringify(e.data)).not.toContain('errmsg');
expect(JSON.stringify(e.data)).not.toContain('codeName');
expect(JSON.stringify(e.data)).not.toContain('errorResponse');
expect(loggerErrorSpy).toHaveBeenCalledWith(
'Sanitized error:',
jasmine.stringMatching(/[Rr]egular expression/i)
);
}
});
});
describe('Postgres regex sanitizater', () => {
it('sanitizes the regex correctly to prevent Injection', async () => {
const user = new Parse.User();
user.set('username', 'username');
user.set('password', 'password');
user.set('email', 'email@example.com');
await user.signUp();
const response = await request({
method: 'GET',
url:
"http://localhost:8378/1/classes/_User?where[username][$regex]=A'B'%3BSELECT+PG_SLEEP(3)%3B--",
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
},
});
expect(response.status).toBe(200);
expect(response.data.results).toEqual(jasmine.any(Array));
expect(response.data.results.length).toBe(0);
});
});
describe('(GHSA-mf3j-86qx-cq5j) ReDoS via $regex in LiveQuery subscription', () => {
it('does not block event loop with catastrophic backtracking regex in LiveQuery', async () => {
await reconfigureServer({
liveQuery: { classNames: ['TestObject'] },
startLiveQueryServer: true,
});
const client = new Parse.LiveQueryClient({
applicationId: 'test',
serverURL: 'ws://localhost:1337',
javascriptKey: 'test',
});
client.open();
const query = new Parse.Query('TestObject');
// Set a catastrophic backtracking regex pattern directly
query._addCondition('field', '$regex', '(a+)+b');
const subscription = await client.subscribe(query);
// Create an object that would trigger regex evaluation
const obj = new Parse.Object('TestObject');
// With 30 'a's followed by 'c', an unprotected regex would hang for seconds
obj.set('field', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaac');
// Set a timeout to detect if the event loop is blocked
const timeout = 5000;
const start = Date.now();
const savePromise = obj.save();
const eventPromise = new Promise(resolve => {
subscription.on('create', () => resolve('matched'));
setTimeout(() => resolve('timeout'), timeout);
});
await savePromise;
const result = await eventPromise;
const elapsed = Date.now() - start;
// The regex should be rejected (not match), and the operation should complete quickly
expect(result).toBe('timeout');
expect(elapsed).toBeLessThan(timeout + 1000);
client.close();
});
});
describe('(GHSA-qpr4-jrj4-6f27) SQL Injection via sort dot-notation field name', () => {
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
};
it_only_db('postgres')('does not execute injected SQL via sort order dot-notation', async () => {
const obj = new Parse.Object('InjectionTest');
obj.set('data', { key: 'value' });
obj.set('name', 'original');
await obj.save();
// This payload would execute a stacked query if single quotes are not escaped
await request({
method: 'GET',
url: 'http://localhost:8378/1/classes/InjectionTest',
headers,
qs: {
order: "data.x' ASC; UPDATE \"InjectionTest\" SET name = 'hacked' WHERE true--",
},
}).catch(() => {});
// Verify the data was not modified by injected SQL
const verify = await new Parse.Query('InjectionTest').get(obj.id);
expect(verify.get('name')).toBe('original');
});
it_only_db('postgres')('does not execute injected SQL via sort order with pg_sleep', async () => {
const obj = new Parse.Object('InjectionTest');
obj.set('data', { key: 'value' });
await obj.save();
const start = Date.now();
await request({
method: 'GET',
url: 'http://localhost:8378/1/classes/InjectionTest',
headers,
qs: {
order: "data.x' ASC; SELECT pg_sleep(3)--",
},
}).catch(() => {});
const elapsed = Date.now() - start;
// If injection succeeded, query would take >= 3 seconds
expect(elapsed).toBeLessThan(3000);
});
it_only_db('postgres')('does not execute injection via dollar-sign quoting bypass', async () => {
// PostgreSQL supports $$string$$ as alternative to 'string'
const obj = new Parse.Object('InjectionTest');
obj.set('data', { key: 'value' });
obj.set('name', 'original');
await obj.save();
await request({
method: 'GET',
url: 'http://localhost:8378/1/classes/InjectionTest',
headers,
qs: {
order: "data.x' ASC; UPDATE \"InjectionTest\" SET name = $$hacked$$ WHERE true--",
},
}).catch(() => {});
const verify = await new Parse.Query('InjectionTest').get(obj.id);
expect(verify.get('name')).toBe('original');
});
it_only_db('postgres')('does not execute injection via tagged dollar quoting bypass', async () => {
// PostgreSQL supports $tag$string$tag$ as alternative to 'string'
const obj = new Parse.Object('InjectionTest');
obj.set('data', { key: 'value' });
obj.set('name', 'original');
await obj.save();
await request({
method: 'GET',
url: 'http://localhost:8378/1/classes/InjectionTest',
headers,
qs: {
order: "data.x' ASC; UPDATE \"InjectionTest\" SET name = $t$hacked$t$ WHERE true--",
},
}).catch(() => {});
const verify = await new Parse.Query('InjectionTest').get(obj.id);