-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathDjango.qll
More file actions
2980 lines (2630 loc) · 124 KB
/
Django.qll
File metadata and controls
2980 lines (2630 loc) · 124 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
/**
* Provides classes modeling security-relevant aspects of the `django` PyPI package.
* See https://www.djangoproject.com/.
*/
private import python
private import semmle.python.dataflow.new.DataFlow
private import semmle.python.dataflow.new.RemoteFlowSources
private import semmle.python.dataflow.new.TaintTracking
private import semmle.python.Concepts
private import semmle.python.ApiGraphs
private import semmle.python.frameworks.PEP249
private import semmle.python.frameworks.Stdlib
private import semmle.python.regex
private import semmle.python.frameworks.internal.PoorMansFunctionResolution
private import semmle.python.frameworks.internal.SelfRefMixin
private import semmle.python.frameworks.internal.InstanceTaintStepsHelper
private import semmle.python.security.dataflow.UrlRedirectCustomizations
private import semmle.python.frameworks.data.ModelsAsData
/**
* INTERNAL: Do not use.
*
* Provides models for the `django` PyPI package.
* See https://www.djangoproject.com/.
*/
module Django {
/** Provides models for the `django.views` module */
module Views {
/**
* Provides models for the `django.views.generic.View` class and subclasses.
*
* See
* - https://docs.djangoproject.com/en/3.1/topics/class-based-views/
* - https://docs.djangoproject.com/en/3.1/ref/class-based-views/
*/
module View {
/**
* An `API::Node` representing the `django.views.generic.View` class or any subclass
* that has explicitly been modeled in the CodeQL libraries.
*/
abstract class ModeledSubclass extends API::Node {
override string toString() { result = this.(API::Node).toString() }
}
/** A Django view subclass in the `django` package. */
private class DjangoViewSubclassesInDjango extends ModeledSubclass {
DjangoViewSubclassesInDjango() {
exists(string moduleName, string className |
// canonical definition
this =
API::moduleImport("django")
.getMember("views")
.getMember("generic")
.getMember(moduleName)
.getMember(className)
or
// aliases from `django.views.generic`
this =
API::moduleImport("django")
.getMember("views")
.getMember("generic")
.getMember(className)
|
moduleName = "base" and
className in ["RedirectView", "TemplateView", "View"]
or
moduleName = "dates" and
className in [
"ArchiveIndexView", "DateDetailView", "DayArchiveView", "MonthArchiveView",
"TodayArchiveView", "WeekArchiveView", "YearArchiveView"
]
or
moduleName = "detail" and
className = "DetailView"
or
moduleName = "edit" and
className in ["CreateView", "DeleteView", "FormView", "UpdateView"]
or
moduleName = "list" and
className = "ListView"
)
or
// `django.views.View` alias
this = API::moduleImport("django").getMember("views").getMember("View")
}
}
private class MaDSubclass extends ModeledSubclass {
MaDSubclass() { this = ModelOutput::getATypeNode("Django.Views.View~Subclass") }
}
/** Gets a reference to the `django.views.generic.View` class or any subclass. */
API::Node subclassRef() { result = any(ModeledSubclass subclass).getASubclass*() }
}
}
/** Provides models for django forms (defined in the `django.forms` module) */
module Forms {
/**
* Provides models for the `django.forms.forms.BaseForm` class and subclasses. This
* is usually used by the `django.forms.forms.Form` class, which is also available
* under the more commonly used alias `django.forms.Form`.
*
* See https://docs.djangoproject.com/en/3.1/ref/forms/api/
*/
module Form {
/**
* An `API::Node` representing the `django.forms.forms.BaseForm` class or any subclass
* that has explicitly been modeled in the CodeQL libraries.
*/
abstract class ModeledSubclass extends API::Node {
override string toString() { result = this.(API::Node).toString() }
}
/** A Django form subclass in the `django` package. */
private class DjangoFormSubclassesInDjango extends ModeledSubclass {
DjangoFormSubclassesInDjango() {
// canonical definition
this =
API::moduleImport("django")
.getMember("forms")
.getMember("forms")
.getMember(["BaseForm", "Form"])
or
this =
API::moduleImport("django")
.getMember("forms")
.getMember("models")
.getMember(["BaseModelForm", "ModelForm"])
or
// aliases from `django.forms`
this =
API::moduleImport("django")
.getMember("forms")
.getMember(["BaseForm", "Form", "BaseModelForm", "ModelForm"])
or
// other Form subclasses defined in Django
this =
API::moduleImport("django")
.getMember("contrib")
.getMember("admin")
.getMember("forms")
.getMember(["AdminAuthenticationForm", "AdminPasswordChangeForm"])
or
this =
API::moduleImport("django")
.getMember("contrib")
.getMember("admin")
.getMember("helpers")
.getMember("ActionForm")
or
this =
API::moduleImport("django")
.getMember("contrib")
.getMember("admin")
.getMember("views")
.getMember("main")
.getMember("ChangeListSearchForm")
or
this =
API::moduleImport("django")
.getMember("contrib")
.getMember("auth")
.getMember("forms")
.getMember([
"PasswordResetForm", "UserChangeForm", "SetPasswordForm",
"AdminPasswordChangeForm", "PasswordChangeForm", "AuthenticationForm",
"UserCreationForm"
])
or
this =
API::moduleImport("django")
.getMember("contrib")
.getMember("flatpages")
.getMember("forms")
.getMember("FlatpageForm")
or
this =
API::moduleImport("django")
.getMember("forms")
.getMember("formsets")
.getMember("ManagementForm")
or
this =
API::moduleImport("django")
.getMember("forms")
.getMember("models")
.getMember(["ModelForm", "BaseModelForm"])
}
}
private class MaDSubclass extends ModeledSubclass {
MaDSubclass() { this = ModelOutput::getATypeNode("django.forms.BaseForm~Subclass") }
}
/** Gets a reference to the `django.forms.forms.BaseForm` class or any subclass. */
API::Node subclassRef() { result = any(ModeledSubclass subclass).getASubclass*() }
}
/**
* Provides models for the `django.forms.fields.Field` class and subclasses. This is
* also available under the more commonly used alias `django.forms.Field`.
*
* See https://docs.djangoproject.com/en/3.1/ref/forms/fields/
*/
module Field {
/**
* An `API::Node` representing the `django.forms.fields.Field` class or any subclass
* that has explicitly been modeled in the CodeQL libraries.
*/
abstract class ModeledSubclass extends API::Node {
override string toString() { result = this.(API::Node).toString() }
}
/** A Django field subclass in the `django` package. */
private class DjangoFieldSubclassesInDjango extends ModeledSubclass {
DjangoFieldSubclassesInDjango() {
exists(string moduleName, string className |
// canonical definition
this =
API::moduleImport("django")
.getMember("forms")
.getMember(moduleName)
.getMember(className)
or
// aliases from `django.forms`
this = API::moduleImport("django").getMember("forms").getMember(className)
|
moduleName = "fields" and
className in [
"Field",
// Known subclasses
"BooleanField", "IntegerField", "CharField", "SlugField", "DateTimeField",
"EmailField", "DateField", "TimeField", "DurationField", "DecimalField",
"FloatField", "GenericIPAddressField", "UUIDField", "JSONField", "FilePathField",
"NullBooleanField", "URLField", "TypedChoiceField", "FileField", "ImageField",
"RegexField", "ChoiceField", "MultipleChoiceField", "ComboField", "MultiValueField",
"SplitDateTimeField", "TypedMultipleChoiceField", "BaseTemporalField"
]
or
// Known subclasses from `django.forms.models`
moduleName = "models" and
className in ["ModelChoiceField", "ModelMultipleChoiceField", "InlineForeignKeyField"]
)
or
// other Field subclasses defined in Django
this =
API::moduleImport("django")
.getMember("contrib")
.getMember("auth")
.getMember("forms")
.getMember(["ReadOnlyPasswordHashField", "UsernameField"])
or
this =
API::moduleImport("django")
.getMember("contrib")
.getMember("gis")
.getMember("forms")
.getMember("fields")
.getMember([
"GeometryCollectionField", "GeometryField", "LineStringField",
"MultiLineStringField", "MultiPointField", "MultiPolygonField", "PointField",
"PolygonField"
])
or
this =
API::moduleImport("django")
.getMember("contrib")
.getMember("postgres")
.getMember("forms")
.getMember("array")
.getMember(["SimpleArrayField", "SplitArrayField"])
or
this =
API::moduleImport("django")
.getMember("contrib")
.getMember("postgres")
.getMember("forms")
.getMember("hstore")
.getMember("HStoreField")
or
this =
API::moduleImport("django")
.getMember("contrib")
.getMember("postgres")
.getMember("forms")
.getMember("ranges")
.getMember([
"BaseRangeField", "DateRangeField", "DateTimeRangeField", "DecimalRangeField",
"IntegerRangeField"
])
or
this =
API::moduleImport("django")
.getMember("forms")
.getMember("models")
.getMember(["InlineForeignKeyField", "ModelChoiceField", "ModelMultipleChoiceField"])
}
}
private class MaDSubclass extends ModeledSubclass {
MaDSubclass() { this = ModelOutput::getATypeNode("Django.Forms.Field~Subclass") }
}
/** Gets a reference to the `django.forms.fields.Field` class or any subclass. */
API::Node subclassRef() { result = any(ModeledSubclass subclass).getASubclass*() }
}
}
/**
* Provides models for the `django.utils.datastructures.MultiValueDict` class
*
* See
* - https://docs.djangoproject.com/en/3.0/ref/request-response/#django.http.QueryDict (subclass that has proper docs)
* - https://www.kite.com/python/docs/django.utils.datastructures.MultiValueDict
*/
module MultiValueDict {
/** Gets a reference to the `django.utils.datastructures.MultiValueDict` class. */
private API::Node classRef() {
result =
API::moduleImport("django")
.getMember("utils")
.getMember("datastructures")
.getMember("MultiValueDict")
}
/**
* A source of instances of `django.utils.datastructures.MultiValueDict`, extend this class to model new instances.
*
* This can include instantiations of the class, return values from function
* calls, or a special parameter that will be set when functions are called by an external
* library.
*
* Use the predicate `MultiValueDict::instance()` to get references to instances of `django.utils.datastructures.MultiValueDict`.
*/
abstract class InstanceSource extends DataFlow::LocalSourceNode { }
/** A direct instantiation of `django.utils.datastructures.MultiValueDict`. */
private class ClassInstantiation extends InstanceSource, DataFlow::CallCfgNode {
ClassInstantiation() { this = classRef().getACall() }
}
/** Gets a reference to an instance of `django.utils.datastructures.MultiValueDict`. */
private DataFlow::TypeTrackingNode instance(DataFlow::TypeTracker t) {
t.start() and
result instanceof InstanceSource
or
exists(DataFlow::TypeTracker t2 | result = instance(t2).track(t2, t))
}
/** Gets a reference to an instance of `django.utils.datastructures.MultiValueDict`. */
DataFlow::Node instance() { instance(DataFlow::TypeTracker::end()).flowsTo(result) }
/**
* Taint propagation for `django.utils.datastructures.MultiValueDict`.
*/
private class InstanceTaintSteps extends InstanceTaintStepsHelper {
InstanceTaintSteps() { this = "django.utils.datastructures.MultiValueDict" }
override DataFlow::Node getInstance() { result = instance() }
override string getAttributeName() { none() }
override string getMethodName() {
result in ["getlist", "lists", "popitem", "dict", "urlencode"]
}
override string getAsyncMethodName() { none() }
}
/**
* Extra taint propagation for `django.utils.datastructures.MultiValueDict`, not covered by `InstanceTaintSteps`.
*/
private class AdditionalTaintStep extends TaintTracking::AdditionalTaintStep {
override predicate step(DataFlow::Node nodeFrom, DataFlow::Node nodeTo) {
// class instantiation
exists(ClassInstantiation call |
nodeFrom = call.getArg(0) and
nodeTo = call
)
}
}
}
/**
* Provides models for the `django.contrib.auth.models.User` class
*
* See https://docs.djangoproject.com/en/3.2/ref/contrib/auth/#user-model.
*/
module User {
/**
* A source of instances of `django.contrib.auth.models.User`, extend this class to model new instances.
*
* This can include instantiations of the class, return values from function
* calls, or a special parameter that will be set when functions are called by an external
* library.
*
* Use the predicate `User::instance()` to get references to instances of `django.contrib.auth.models.User`.
*/
abstract class InstanceSource extends DataFlow::LocalSourceNode { }
/** Gets a reference to an instance of `django.contrib.auth.models.User`. */
private DataFlow::TypeTrackingNode instance(DataFlow::TypeTracker t) {
t.start() and
result instanceof InstanceSource
or
exists(DataFlow::TypeTracker t2 | result = instance(t2).track(t2, t))
}
/** Gets a reference to an instance of `django.contrib.auth.models.User`. */
DataFlow::Node instance() { instance(DataFlow::TypeTracker::end()).flowsTo(result) }
/**
* Taint propagation for `django.contrib.auth.models.User`.
*/
private class InstanceTaintSteps extends InstanceTaintStepsHelper {
InstanceTaintSteps() { this = "django.contrib.auth.models.User" }
override DataFlow::Node getInstance() { result = instance() }
override string getAttributeName() {
result in ["username", "first_name", "last_name", "email"]
}
override string getMethodName() { none() }
override string getAsyncMethodName() { none() }
}
}
/**
* Provides models for the `django.core.files.uploadedfile.UploadedFile` class
*
* See https://docs.djangoproject.com/en/3.0/ref/files/uploads/#django.core.files.uploadedfile.UploadedFile.
*/
module UploadedFile {
/**
* A source of instances of `django.core.files.uploadedfile.UploadedFile`, extend this class to model new instances.
*
* This can include instantiations of the class, return values from function
* calls, or a special parameter that will be set when functions are called by an external
* library.
*
* Use the predicate `UploadedFile::instance()` to get references to instances of `django.core.files.uploadedfile.UploadedFile`.
*/
abstract class InstanceSource extends DataFlow::LocalSourceNode { }
/** Gets a reference to an instance of `django.core.files.uploadedfile.UploadedFile`. */
private DataFlow::TypeTrackingNode instance(DataFlow::TypeTracker t) {
t.start() and
result instanceof InstanceSource
or
exists(DataFlow::TypeTracker t2 | result = instance(t2).track(t2, t))
}
/** Gets a reference to an instance of `django.core.files.uploadedfile.UploadedFile`. */
DataFlow::Node instance() { instance(DataFlow::TypeTracker::end()).flowsTo(result) }
/**
* Taint propagation for `django.core.files.uploadedfile.UploadedFile`.
*/
private class InstanceTaintSteps extends InstanceTaintStepsHelper {
InstanceTaintSteps() { this = "django.core.files.uploadedfile.UploadedFile" }
override DataFlow::Node getInstance() { result = instance() }
override string getAttributeName() {
result in [
"content_type", "content_type_extra", "content_type_extra", "charset", "name", "file"
]
}
override string getMethodName() { none() }
override string getAsyncMethodName() { none() }
}
/** A file-like object instance that originates from a `UploadedFile`. */
class UploadedFileFileLikeInstances extends Stdlib::FileLikeObject::InstanceSource {
UploadedFileFileLikeInstances() {
// in the bottom of
// https://docs.djangoproject.com/en/4.0/ref/files/file/#django.core.files.File
// it's mentioned that the File object itself has proxy methods for
// `read`/`write`/... that forwards to the underlying file object.
this = instance()
or
this.(DataFlow::AttrRead).accesses(instance(), "file")
}
}
}
/**
* Provides models for the `django.urls.ResolverMatch` class
*
* See https://docs.djangoproject.com/en/3.0/ref/urlresolvers/#django.urls.ResolverMatch.
*/
module ResolverMatch {
/**
* A source of instances of `django.urls.ResolverMatch`, extend this class to model new instances.
*
* This can include instantiations of the class, return values from function
* calls, or a special parameter that will be set when functions are called by an external
* library.
*
* Use the predicate `ResolverMatch::instance()` to get references to instances of `django.urls.ResolverMatch`.
*/
abstract class InstanceSource extends DataFlow::LocalSourceNode { }
/** Gets a reference to an instance of `django.urls.ResolverMatch`. */
private DataFlow::TypeTrackingNode instance(DataFlow::TypeTracker t) {
t.start() and
result instanceof InstanceSource
or
exists(DataFlow::TypeTracker t2 | result = instance(t2).track(t2, t))
}
/** Gets a reference to an instance of `django.urls.ResolverMatch`. */
DataFlow::Node instance() { instance(DataFlow::TypeTracker::end()).flowsTo(result) }
/**
* Taint propagation for `django.urls.ResolverMatch`.
*/
private class InstanceTaintSteps extends InstanceTaintStepsHelper {
InstanceTaintSteps() { this = "django.urls.ResolverMatch" }
override DataFlow::Node getInstance() { result = instance() }
override string getAttributeName() { result in ["args", "kwargs"] }
override string getMethodName() { none() }
override string getAsyncMethodName() { none() }
}
}
}
/**
* INTERNAL: Do not use.
*
* Provides models for the `django` PyPI package (that we are not quite ready to publicly expose yet).
* See https://www.djangoproject.com/.
*/
module PrivateDjango {
// ---------------------------------------------------------------------------
// django
// ---------------------------------------------------------------------------
/** Gets a reference to the `django` module. */
API::Node django() { result = API::moduleImport("django") }
/** Provides models for the `django` module. */
module DjangoImpl {
// -------------------------------------------------------------------------
// django.db
// -------------------------------------------------------------------------
/** Gets a reference to the `django.db` module. */
API::Node db() { result = django().getMember("db") }
/**
* `django.db` implements PEP249, providing ways to execute SQL statements against a database.
*/
private class DjangoDb extends PEP249::PEP249ModuleApiNode {
DjangoDb() { this = API::moduleImport("django").getMember("db") }
}
/** Provides models for the `django.db` module. */
module DB {
/** Gets a reference to the `django.db.connection` object. */
API::Node connection() { result = db().getMember("connection") }
/** A `django.db.connection` is a PEP249 compliant DB connection. */
class DjangoDbConnection extends PEP249::DatabaseConnection {
DjangoDbConnection() { this = connection() }
}
// -------------------------------------------------------------------------
// django.db.models
// -------------------------------------------------------------------------
/** Gets a reference to the `django.db.models` module. */
API::Node models() { result = db().getMember("models") }
/** Provides models for the `django.db.models` module. */
module Models {
/**
* Provides models for the `django.db.models.Model` class and subclasses.
*
* See https://docs.djangoproject.com/en/3.1/topics/db/models/.
*/
module Model {
/** Gets a reference to the `django.db.models.Model` class or any subclass. */
API::Node subclassRef() {
result =
API::moduleImport("django")
.getMember("db")
.getMember("models")
.getMember("Model")
.getASubclass*()
or
result =
API::moduleImport("django")
.getMember("db")
.getMember("models")
.getMember("base")
.getMember("Model")
.getASubclass*()
or
result =
API::moduleImport("polymorphic")
.getMember("models")
.getMember("PolymorphicModel")
.getASubclass*()
or
result = ModelOutput::getATypeNode("Django.db.models.Model~Subclass").getASubclass*()
}
/**
* A source of instances of `django.db.models.Model` class or any subclass, extend this class to model new instances.
*
* This can include instantiations of the class, return values from function
* calls, or a special parameter that will be set when functions are called by an external
* library.
*
* Use the predicate `Model::instance()` to get references to instances of `django.db.models.Model` class or any subclass.
*/
abstract class InstanceSource extends DataFlow::LocalSourceNode {
/** Gets the model class that this is an instance source of. */
abstract API::Node getModelClass();
/** Holds if this instance-source is fetching data from the DB. */
abstract predicate isDbFetch();
}
/** A direct instantiation of `django.db.models.Model` class or any subclass. */
private class ClassInstantiation extends InstanceSource, DataFlow::CallCfgNode {
API::Node modelClass;
ClassInstantiation() {
modelClass = subclassRef() and
this = modelClass.getACall()
}
override API::Node getModelClass() { result = modelClass }
override predicate isDbFetch() { none() }
}
/** A method call on a query-set or manager that returns an instance of a django model. */
private class QuerySetMethod extends InstanceSource, DataFlow::CallCfgNode {
API::Node modelClass;
string methodName;
QuerySetMethod() {
modelClass = subclassRef() and
methodName in ["get", "create", "earliest", "latest", "first", "last"] and
this = [manager(modelClass), querySet(modelClass)].getMember(methodName).getACall()
}
override API::Node getModelClass() { result = modelClass }
override predicate isDbFetch() { not methodName = "create" }
}
/**
* A method call on a query-set or manager that returns a collection
* containing instances of a django model.
*/
class QuerySetMethodInstanceCollection extends DataFlow::CallCfgNode {
API::Node modelClass;
string methodName;
QuerySetMethodInstanceCollection() {
modelClass = subclassRef() and
this = querySetReturningMethod(modelClass, methodName).getACall() and
not methodName in ["none", "datetimes", "dates", "values", "values_list"]
or
// TODO: When we have flow-summaries, we should be able to model `values` and `values_list`
// Potentially by doing `synthetic ===store of list element==> <Model>.objects`, and then
// `.all()` just keeps that content, and `.first()` will do a read step (of the list element).
//
// So for `Model.objects.filter().exclude().first()` we would have
// 1: <Synthetic node for Model> ===store of list element==> Model.objects
// 2: Model.objects ==> Model.objects.filter()
// 3: Model.objects.filter() ==> Model.objects.filter().exclude()
// 4: Model.objects.filter().exclude() ===read of list element==> Model.objects.filter().exclude().first()
//
// This also means that `.none()` could clear contents. Right now we
// think that the result of `Model.objects.none().all()` can contain
// Model objects, but it will be empty due to the `.none()` part. Not
// that this is important, since no-one would need to write
// `.none().all()` code anyway, but it would be cool to be able to model it properly :D
//
//
// The big benefit is for how we could then model `values`/`values_list`. For example,
// `Model.objects.value_list(name, description)` would result in (for the attribute description)
// 0: <Synthetic node for Model> -- [attr description]
// 1: ==> Model.objects [ListElement, attr description]
// 2: ==> .value_list(...) [ListElement, TupleIndex 1]
//
// but for now, we just model a store step directly from the synthetic
// node to the method call.
//
// extra method on query-set/manager that does _not_ return a query-set,
// but a collection of instances.
modelClass = subclassRef() and
methodName in ["iterator", "bulk_create"] and
this = [manager(modelClass), querySet(modelClass)].getMember(methodName).getACall()
}
/** Gets the model class that this is an instance source of. */
API::Node getModelClass() { result = modelClass }
/** Holds if this instance-source is fetching data from the DB. */
predicate isDbFetch() { not methodName = "bulk_create" }
}
/**
* A method call on a query-set or manager that returns a dictionary
* containing instances of a django models as the values.
*/
class QuerySetMethodInstanceDictValue extends DataFlow::CallCfgNode {
API::Node modelClass;
QuerySetMethodInstanceDictValue() {
modelClass = subclassRef() and
this = [manager(modelClass), querySet(modelClass)].getMember("in_bulk").getACall()
}
/** Gets the model class that this is an instance source of. */
API::Node getModelClass() { result = modelClass }
/** Holds if this instance-source is fetching data from the DB. */
predicate isDbFetch() { any() }
}
/**
* Gets a reference to an instance of `django.db.models.Model` class or any subclass,
* where `modelClass` specifies the class.
*/
private DataFlow::TypeTrackingNode instance(DataFlow::TypeTracker t, API::Node modelClass) {
t.start() and
modelClass = result.(InstanceSource).getModelClass()
or
exists(DataFlow::TypeTracker t2 | result = instance(t2, modelClass).track(t2, t))
}
/**
* Gets a reference to an instance of `django.db.models.Model` class or any subclass,
* where `modelClass` specifies the class.
*/
DataFlow::Node instance(API::Node modelClass) {
instance(DataFlow::TypeTracker::end(), modelClass).flowsTo(result)
}
}
/**
* Provides models for the `django.db.models.FileField` class and `ImageField` subclasses.
*
* See
* - https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.FileField
* - https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.ImageField
*/
module FileField {
/** Gets a reference to the `django.db.models.FileField` or the `django.db.models.ImageField` class or any subclass. */
API::Node subclassRef() {
exists(string className | className in ["FileField", "ImageField"] |
// commonly used alias
result =
API::moduleImport("django")
.getMember("db")
.getMember("models")
.getMember(className)
.getASubclass*()
or
// actual class definition
result =
API::moduleImport("django")
.getMember("db")
.getMember("models")
.getMember("fields")
.getMember("files")
.getMember(className)
.getASubclass*()
)
or
result =
ModelOutput::getATypeNode("django.db.models.FileField~Subclass").getASubclass*()
}
}
/**
* Gets a reference to the Manager (django.db.models.Manager) for the django Model `modelClass`,
* accessed by `<modelClass>.objects`.
*/
API::Node manager(API::Node modelClass) {
modelClass = Model::subclassRef() and
result = modelClass.getMember("objects")
}
/**
* Gets a method with `name` that returns a QuerySet.
* This method can originate on a QuerySet or a Manager.
* `modelClass` specifies the django Model that this query-set originates from.
*
* See https://docs.djangoproject.com/en/3.1/ref/models/querysets/
*/
API::Node querySetReturningMethod(API::Node modelClass, string name) {
name in [
"none", "all", "filter", "exclude", "complex_filter", "union", "intersection",
"difference", "select_for_update", "select_related", "prefetch_related", "order_by",
"distinct", "reverse", "defer", "only", "using", "annotate", "extra", "raw",
"datetimes", "dates", "values", "values_list", "alias"
] and
result = [manager(modelClass), querySet(modelClass)].getMember(name)
or
name = "get_queryset" and
result = manager(modelClass).getMember(name)
}
/**
* Gets a reference to a QuerySet (django.db.models.query.QuerySet).
* `modelClass` specifies the django Model that this query-set originates from.
*
* See https://docs.djangoproject.com/en/3.1/ref/models/querysets/
*/
API::Node querySet(API::Node modelClass) {
result = querySetReturningMethod(modelClass, _).getReturn()
}
/** Gets a reference to the `django.db.models.expressions` module. */
API::Node expressions() { result = models().getMember("expressions") }
/** Provides models for the `django.db.models.expressions` module. */
module Expressions {
/** Provides models for the `django.db.models.expressions.RawSql` class. */
module RawSql {
/**
* Gets an reference to the `django.db.models.expressions.RawSQL` class.
*/
API::Node classRef() {
result = expressions().getMember("RawSQL")
or
// Commonly used alias
result = models().getMember("RawSQL")
or
result =
ModelOutput::getATypeNode("django.db.models.expressions.RawSQL~Subclass")
.getASubclass*()
}
/**
* Gets an instance of the `django.db.models.expressions.RawSQL` class,
* that was initiated with the SQL represented by `sql`.
*/
private DataFlow::TypeTrackingNode instance(DataFlow::TypeTracker t, DataFlow::Node sql) {
t.start() and
exists(DataFlow::CallCfgNode c | result = c |
c = classRef().getACall() and
c.getArg(0) = sql
)
or
exists(DataFlow::TypeTracker t2 | result = instance(t2, sql).track(t2, t))
}
/**
* Gets an instance of the `django.db.models.expressions.RawSQL` class,
* that was initiated with the SQL represented by `sql`.
*/
DataFlow::Node instance(DataFlow::Node sql) {
instance(DataFlow::TypeTracker::end(), sql).flowsTo(result)
}
}
}
/** This internal module provides data-flow modeling of Django ORM. */
private module OrmDataflow {
private import semmle.python.dataflow.new.internal.DataFlowPrivate::Orm
/** Gets the (AST) class of the Django model class `modelClass`. */
Class getModelClassClass(API::Node modelClass) {
result.getParent() = modelClass.asSource().asExpr() and
modelClass = Model::subclassRef()
}
/** A synthetic node representing the data for an Django ORM model saved in a DB. */
class SyntheticDjangoOrmModelNode extends SyntheticOrmModelNode {
API::Node modelClass;
SyntheticDjangoOrmModelNode() { this.getClass() = getModelClassClass(modelClass) }
/** Gets the API node for this Django model class. */
API::Node getModelClass() { result = modelClass }
}
/**
* Gets a synthetic node where the data in the attribute `fieldName` can flow
* to, when a DB store is made on `subModel`, taking ORM inheritance into
* account.
*
* If `fieldName` is defined in class `base`, the results will include the
* synthetic node for `base` itself, the synthetic node for `subModel`, as
* well as all the classes in-between (in the class hierarchy).
*/
SyntheticDjangoOrmModelNode nodeToStoreIn(API::Node subModel, string fieldName) {
exists(Class base, API::Node baseModel, API::Node resultModel |
baseModel = Model::subclassRef() and
resultModel = Model::subclassRef() and
baseModel.getASubclass*() = subModel and
base = getModelClassClass(baseModel) and
exists(Variable v |
base.getBody().getAnItem().(AssignStmt).defines(v) and
v.getId() = fieldName
)
|
baseModel.getASubclass*() = resultModel and
resultModel.getASubclass*() = subModel and
result.getModelClass() = resultModel
)
}
/**
* Gets the synthetic node where data could be loaded from, when a fetch is
* made on `modelClass`.
*
* In vanilla Django inheritance, this is simply the model itself, but if a
* model is based on `polymorphic.models.PolymorphicModel`, a fetch of the
* base-class can also yield instances of its subclasses.
*/
SyntheticDjangoOrmModelNode nodeToLoadFrom(API::Node modelClass) {
result.getModelClass() = modelClass
or
exists(API::Node polymorphicModel |
polymorphicModel =
API::moduleImport("polymorphic").getMember("models").getMember("PolymorphicModel")
|
polymorphicModel.getASubclass+() = modelClass and
modelClass.getASubclass+() = result.getModelClass()
)
}
/** Additional data-flow steps for Django ORM models. */
class DjangOrmSteps extends AdditionalOrmSteps {
override predicate storeStep(
DataFlow::Node nodeFrom, DataFlow::Content c, DataFlow::Node nodeTo
) {
// attribute value from constructor call -> object created
exists(DataFlow::CallCfgNode call, string fieldName |
// Note: Currently only supports kwargs, which should by far be the most
// common way to do things. We _should_ investigate how often
// positional-args are used.
call = Model::subclassRef().getACall() and
nodeFrom = call.getArgByName(fieldName) and
c.(DataFlow::AttributeContent).getAttribute() = fieldName and
nodeTo = call
)
or
// attribute store in `<Model>.objects.create`, `get_or_create`, and `update_or_create`
// see https://docs.djangoproject.com/en/4.0/ref/models/querysets/#create
// see https://docs.djangoproject.com/en/4.0/ref/models/querysets/#get-or-create
// see https://docs.djangoproject.com/en/4.0/ref/models/querysets/#update-or-create
// TODO: This does currently not handle values passed in the `defaults` dictionary
exists(
DataFlow::CallCfgNode call, API::Node modelClass, string fieldName,
string methodName
|
modelClass = Model::subclassRef() and
methodName in ["create", "get_or_create", "update_or_create"] and
call = modelClass.getMember("objects").getMember(methodName).getACall() and
nodeFrom = call.getArgByName(fieldName) and
c.(DataFlow::AttributeContent).getAttribute() = fieldName and
(
// -> object created
(
methodName = "create" and nodeTo = call
or
// TODO: for these two methods, the result is a tuple `(<Model>, bool)`,
// which we need flow-summaries to model properly
methodName in ["get_or_create", "update_or_create"] and none()
)
or
// -> DB store on synthetic node
nodeTo = nodeToStoreIn(modelClass, fieldName)
)
)
or
// attribute store in `<Model>.objects.[<QuerySet>].update()` -> synthetic
// see https://docs.djangoproject.com/en/4.0/ref/models/querysets/#update
exists(DataFlow::CallCfgNode call, API::Node modelClass, string fieldName |
call = [manager(modelClass), querySet(modelClass)].getMember("update").getACall() and
nodeFrom = call.getArgByName(fieldName) and
c.(DataFlow::AttributeContent).getAttribute() = fieldName and
nodeTo = nodeToStoreIn(modelClass, fieldName)
)
or
// synthetic -> method-call that returns collection of ORM models (all/filter/...)
exists(API::Node modelClass |
nodeFrom = nodeToLoadFrom(modelClass) and
nodeTo.(Model::QuerySetMethodInstanceCollection).getModelClass() = modelClass and
nodeTo.(Model::QuerySetMethodInstanceCollection).isDbFetch() and
c instanceof DataFlow::ListElementContent
)