-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathRestFramework.qll
More file actions
393 lines (359 loc) · 15.3 KB
/
RestFramework.qll
File metadata and controls
393 lines (359 loc) · 15.3 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
/**
* Provides classes modeling security-relevant aspects of the `djangorestframework` PyPI package
* (imported as `rest_framework`)
*
* See
* - https://www.django-rest-framework.org/
* - https://pypi.org/project/djangorestframework/
*/
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.internal.InstanceTaintStepsHelper
private import semmle.python.frameworks.Django
private import semmle.python.frameworks.Stdlib
private import semmle.python.frameworks.data.ModelsAsData
/**
* INTERNAL: Do not use.
*
* Provides models for the `djangorestframework` PyPI package
* (imported as `rest_framework`)
*
* See
* - https://www.django-rest-framework.org/
* - https://pypi.org/project/djangorestframework/
*/
module RestFramework {
// ---------------------------------------------------------------------------
// rest_framework.views.APIView handling
// ---------------------------------------------------------------------------
/**
* An `API::Node` representing the `rest_framework.views.APIView` class or any subclass
* that has explicitly been modeled in the CodeQL libraries.
*/
private class ModeledApiViewClasses extends Django::Views::View::ModeledSubclass {
ModeledApiViewClasses() {
this = API::moduleImport("rest_framework").getMember("views").getMember("APIView")
or
// imports generated by python/frameworks/internal/SubclassFinder.qll
this =
API::moduleImport("rest_framework")
.getMember("authtoken")
.getMember("views")
.getMember("APIView")
or
this =
API::moduleImport("rest_framework")
.getMember("authtoken")
.getMember("views")
.getMember("ObtainAuthToken")
or
this = API::moduleImport("rest_framework").getMember("decorators").getMember("APIView")
or
this = API::moduleImport("rest_framework").getMember("generics").getMember("CreateAPIView")
or
this = API::moduleImport("rest_framework").getMember("generics").getMember("DestroyAPIView")
or
this = API::moduleImport("rest_framework").getMember("generics").getMember("GenericAPIView")
or
this = API::moduleImport("rest_framework").getMember("generics").getMember("ListAPIView")
or
this =
API::moduleImport("rest_framework").getMember("generics").getMember("ListCreateAPIView")
or
this = API::moduleImport("rest_framework").getMember("generics").getMember("RetrieveAPIView")
or
this =
API::moduleImport("rest_framework")
.getMember("generics")
.getMember("RetrieveDestroyAPIView")
or
this =
API::moduleImport("rest_framework").getMember("generics").getMember("RetrieveUpdateAPIView")
or
this =
API::moduleImport("rest_framework")
.getMember("generics")
.getMember("RetrieveUpdateDestroyAPIView")
or
this = API::moduleImport("rest_framework").getMember("generics").getMember("UpdateAPIView")
or
this = API::moduleImport("rest_framework").getMember("routers").getMember("APIRootView")
or
this = API::moduleImport("rest_framework").getMember("routers").getMember("SchemaView")
or
this =
API::moduleImport("rest_framework")
.getMember("schemas")
.getMember("views")
.getMember("APIView")
or
this =
API::moduleImport("rest_framework")
.getMember("schemas")
.getMember("views")
.getMember("SchemaView")
or
this = API::moduleImport("rest_framework").getMember("viewsets").getMember("GenericViewSet")
or
this = API::moduleImport("rest_framework").getMember("viewsets").getMember("ModelViewSet")
or
this =
API::moduleImport("rest_framework").getMember("viewsets").getMember("ReadOnlyModelViewSet")
or
this = API::moduleImport("rest_framework").getMember("viewsets").getMember("ViewSet")
}
}
/**
* A class that has a super-type which is a rest_framework APIView class, therefore also
* becoming a APIView class.
*/
class RestFrameworkApiViewClass extends PrivateDjango::DjangoViewClassFromSuperClass {
RestFrameworkApiViewClass() {
this.getParent() = any(ModeledApiViewClasses c).getASubclass*().asSource().asExpr()
}
override Function getARequestHandler() {
result = super.getARequestHandler()
or
// TODO: This doesn't handle attribute assignment. Should be OK, but analysis is not as complete as with
// points-to and `.lookup`, which would handle `post = my_post_handler` inside class def
result = this.getAMethod() and
result.getName() in [
// these method names where found by looking through the APIView
// implementation in
// https://github.com/encode/django-rest-framework/blob/master/rest_framework/views.py#L104
"initial", "http_method_not_allowed", "permission_denied", "throttled",
"get_authenticate_header", "perform_content_negotiation", "perform_authentication",
"check_permissions", "check_object_permissions", "check_throttles", "determine_version",
"initialize_request", "finalize_response", "dispatch", "options",
// ModelViewSet
// https://github.com/encode/django-rest-framework/blob/master/rest_framework/viewsets.py
"create", "retrieve", "update", "partial_update", "destroy", "list"
]
}
}
// ---------------------------------------------------------------------------
// rest_framework.decorators.api_view handling
// ---------------------------------------------------------------------------
/**
* A function that is a request handler since it is decorated with `rest_framework.decorators.api_view`
*/
class RestFrameworkFunctionBasedView extends PrivateDjango::DjangoRouteHandler::Range {
RestFrameworkFunctionBasedView() {
this.getADecorator() =
API::moduleImport("rest_framework")
.getMember("decorators")
.getMember("api_view")
.getACall()
.asExpr()
}
}
/**
* Ensuring that all `RestFrameworkFunctionBasedView` are also marked as a
* `HTTP::Server::RequestHandler`. We only need this for the ones that doesn't have a
* known route setup.
*/
class RestFrameworkFunctionBasedViewWithoutKnownRoute extends Http::Server::RequestHandler::Range,
PrivateDjango::DjangoRouteHandler instanceof RestFrameworkFunctionBasedView
{
RestFrameworkFunctionBasedViewWithoutKnownRoute() {
not exists(PrivateDjango::DjangoRouteSetup setup | setup.getARequestHandler() = this)
}
override Parameter getARoutedParameter() {
// Since we don't know the URL pattern, we simply mark all parameters as a routed
// parameter. This should give us more RemoteFlowSources but could also lead to
// more FPs. If this turns out to be the wrong tradeoff, we can always change our mind.
result in [
this.getArg(_), this.getArgByName(_), //
this.getVararg().(Parameter), this.getKwarg().(Parameter), // TODO: These sources should be modeled as storing content!
] and
not result = any(int i | i < this.getFirstPossibleRoutedParamIndex() | this.getArg(i))
}
override string getFramework() { result = "Django (rest_framework)" }
}
// ---------------------------------------------------------------------------
// request modeling
// ---------------------------------------------------------------------------
/**
* A parameter that will receive a `rest_framework.request.Request` instance when a
* request handler is invoked.
*/
private class RestFrameworkRequestHandlerRequestParam extends Request::InstanceSource,
RemoteFlowSource::Range, DataFlow::ParameterNode
{
RestFrameworkRequestHandlerRequestParam() {
// rest_framework.views.APIView subclass
exists(RestFrameworkApiViewClass vc |
this.getParameter() =
vc.getARequestHandler().(PrivateDjango::DjangoRouteHandler).getRequestParam()
)
or
// annotated with @api_view decorator
exists(PrivateDjango::DjangoRouteHandler rh | rh instanceof RestFrameworkFunctionBasedView |
this.getParameter() = rh.getRequestParam()
)
}
override string getSourceType() { result = "rest_framework.request.HttpRequest" }
}
/**
* Provides models for the `rest_framework.request.Request` class
*
* See https://www.django-rest-framework.org/api-guide/requests/.
*/
module Request {
/** Gets a reference to the `rest_framework.request.Request` class. */
API::Node classRef() {
result = API::moduleImport("rest_framework").getMember("request").getMember("Request")
or
result = ModelOutput::getATypeNode("rest_framework.request.Request~Subclass").getASubclass*()
}
/**
* A source of instances of `rest_framework.request.Request`, 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 `Request::instance()` to get references to instances of `rest_framework.request.Request`.
*/
abstract class InstanceSource extends PrivateDjango::DjangoImpl::DjangoHttp::Request::HttpRequest::InstanceSource
{ }
/** A direct instantiation of `rest_framework.request.Request`. */
private class ClassInstantiation extends InstanceSource, DataFlow::CallCfgNode {
ClassInstantiation() { this = classRef().getACall() }
}
/** Gets a reference to an instance of `rest_framework.request.Request`. */
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 `rest_framework.request.Request`. */
DataFlow::Node instance() { instance(DataFlow::TypeTracker::end()).flowsTo(result) }
/**
* Taint propagation for `rest_framework.request.Request`.
*/
private class InstanceTaintSteps extends InstanceTaintStepsHelper {
InstanceTaintSteps() { this = "rest_framework.request.Request" }
override DataFlow::Node getInstance() { result = instance() }
override string getAttributeName() {
result in ["data", "query_params", "user", "auth", "content_type", "stream"]
}
override string getMethodName() { none() }
override string getAsyncMethodName() { none() }
}
/** An attribute read that is a `MultiValueDict` instance. */
private class MultiValueDictInstances extends Django::MultiValueDict::InstanceSource {
MultiValueDictInstances() {
this.(DataFlow::AttrRead).getObject() = instance() and
this.(DataFlow::AttrRead).getAttributeName() = "query_params"
}
}
/** An attribute read that is a `User` instance. */
private class UserInstances extends Django::User::InstanceSource {
UserInstances() {
this.(DataFlow::AttrRead).getObject() = instance() and
this.(DataFlow::AttrRead).getAttributeName() = "user"
}
}
/** An attribute read that is a file-like instance. */
private class FileLikeInstances extends Stdlib::FileLikeObject::InstanceSource {
FileLikeInstances() {
this.(DataFlow::AttrRead).getObject() = instance() and
this.(DataFlow::AttrRead).getAttributeName() = "stream"
}
}
}
// ---------------------------------------------------------------------------
// response modeling
// ---------------------------------------------------------------------------
/**
* Provides models for the `rest_framework.response.Response` class
*
* See https://www.django-rest-framework.org/api-guide/responses/.
*/
module Response {
/** Gets a reference to the `rest_framework.response.Response` class. */
API::Node classRef() {
result = API::moduleImport("rest_framework").getMember("response").getMember("Response")
or
result =
ModelOutput::getATypeNode("rest_framework.response.Response~Subclass").getASubclass*()
}
/** A direct instantiation of `rest_framework.response.Response`. */
private class ClassInstantiation extends PrivateDjango::DjangoImpl::DjangoHttp::Response::HttpResponse::InstanceSource,
DataFlow::CallCfgNode
{
ClassInstantiation() { this = classRef().getACall() }
override DataFlow::Node getBody() { result in [this.getArg(0), this.getArgByName("data")] }
override DataFlow::Node getMimetypeOrContentTypeArg() {
result in [this.getArg(5), this.getArgByName("content_type")]
}
override string getMimetypeDefault() { none() }
}
}
// ---------------------------------------------------------------------------
// Exception response modeling
// ---------------------------------------------------------------------------
/**
* Provides models for the `rest_framework.exceptions.APIException` class and subclasses
*
* See https://www.django-rest-framework.org/api-guide/exceptions/#api-reference
*/
module ApiException {
API::Node classRef() {
exists(string className |
className in [
"APIException", "ValidationError", "ParseError", "AuthenticationFailed",
"NotAuthenticated", "PermissionDenied", "NotFound", "NotAcceptable"
] and
result =
API::moduleImport("rest_framework")
.getMember("exceptions")
.getMember(className)
.getASubclass*()
)
or
result =
ModelOutput::getATypeNode("rest_framework.exceptions.APIException~Subclass").getASubclass*()
}
/** A direct instantiation of `rest_framework.exceptions.ApiException` or subclass. */
private class ClassInstantiation extends Http::Server::HttpResponse::Range,
DataFlow::CallCfgNode
{
string className;
ClassInstantiation() {
className in [
"APIException", "ValidationError", "ParseError", "AuthenticationFailed",
"NotAuthenticated", "PermissionDenied", "NotFound", "MethodNotAllowed", "NotAcceptable",
"UnsupportedMediaType", "Throttled"
] and
this =
API::moduleImport("rest_framework")
.getMember("exceptions")
.getMember(className)
.getACall()
or
this = classRef().getACall() and className = "APIException"
}
override DataFlow::Node getBody() {
className in [
"APIException", "ValidationError", "ParseError", "AuthenticationFailed",
"NotAuthenticated", "PermissionDenied", "NotFound", "NotAcceptable"
] and
result = this.getArg(0)
or
className in ["MethodNotAllowed", "UnsupportedMediaType", "Throttled"] and
result = this.getArg(1)
or
result = this.getArgByName("detail")
}
override DataFlow::Node getMimetypeOrContentTypeArg() { none() }
override string getMimetypeDefault() { none() }
}
}
}