uploadshield 2.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. uploadshield-2.0.0/LICENSE +202 -0
  2. uploadshield-2.0.0/PKG-INFO +239 -0
  3. uploadshield-2.0.0/README.md +189 -0
  4. uploadshield-2.0.0/pyproject.toml +223 -0
  5. uploadshield-2.0.0/pyproject.toml.orig +194 -0
  6. uploadshield-2.0.0/src/uploadshield/__init__.py +49 -0
  7. uploadshield-2.0.0/src/uploadshield/__main__.py +17 -0
  8. uploadshield-2.0.0/src/uploadshield/checks/__init__.py +65 -0
  9. uploadshield-2.0.0/src/uploadshield/checks/archive.py +316 -0
  10. uploadshield-2.0.0/src/uploadshield/checks/basic.py +476 -0
  11. uploadshield-2.0.0/src/uploadshield/checks/image.py +107 -0
  12. uploadshield-2.0.0/src/uploadshield/checks/magika.py +129 -0
  13. uploadshield-2.0.0/src/uploadshield/checks/markup.py +181 -0
  14. uploadshield-2.0.0/src/uploadshield/checks/office.py +174 -0
  15. uploadshield-2.0.0/src/uploadshield/checks/pdf.py +277 -0
  16. uploadshield-2.0.0/src/uploadshield/checks/scanners.py +205 -0
  17. uploadshield-2.0.0/src/uploadshield/checks/xml.py +123 -0
  18. uploadshield-2.0.0/src/uploadshield/cli/__init__.py +276 -0
  19. uploadshield-2.0.0/src/uploadshield/cli/_commands.py +401 -0
  20. uploadshield-2.0.0/src/uploadshield/cli/_json.py +80 -0
  21. uploadshield-2.0.0/src/uploadshield/cli/_render.py +319 -0
  22. uploadshield-2.0.0/src/uploadshield/cli/_scan.py +106 -0
  23. uploadshield-2.0.0/src/uploadshield/cli/_style.py +95 -0
  24. uploadshield-2.0.0/src/uploadshield/cli/_verdicts.py +363 -0
  25. uploadshield-2.0.0/src/uploadshield/cli/_walk.py +159 -0
  26. uploadshield-2.0.0/src/uploadshield/core/__init__.py +4 -0
  27. uploadshield-2.0.0/src/uploadshield/core/_deconstruct.py +39 -0
  28. uploadshield-2.0.0/src/uploadshield/core/check.py +79 -0
  29. uploadshield-2.0.0/src/uploadshield/core/containers.py +131 -0
  30. uploadshield-2.0.0/src/uploadshield/core/result.py +63 -0
  31. uploadshield-2.0.0/src/uploadshield/core/sniffing.py +432 -0
  32. uploadshield-2.0.0/src/uploadshield/core/types.py +319 -0
  33. uploadshield-2.0.0/src/uploadshield/core/upload.py +192 -0
  34. uploadshield-2.0.0/src/uploadshield/core/violations.py +79 -0
  35. uploadshield-2.0.0/src/uploadshield/django/__init__.py +36 -0
  36. uploadshield-2.0.0/src/uploadshield/django/apps.py +13 -0
  37. uploadshield-2.0.0/src/uploadshield/django/checks.py +148 -0
  38. uploadshield-2.0.0/src/uploadshield/django/cli.py +36 -0
  39. uploadshield-2.0.0/src/uploadshield/django/conf.py +189 -0
  40. uploadshield-2.0.0/src/uploadshield/django/decorators.py +204 -0
  41. uploadshield-2.0.0/src/uploadshield/django/exceptions.py +39 -0
  42. uploadshield-2.0.0/src/uploadshield/django/forms.py +40 -0
  43. uploadshield-2.0.0/src/uploadshield/django/handlers.py +322 -0
  44. uploadshield-2.0.0/src/uploadshield/django/responses.py +92 -0
  45. uploadshield-2.0.0/src/uploadshield/django/service.py +473 -0
  46. uploadshield-2.0.0/src/uploadshield/django/signals.py +16 -0
  47. uploadshield-2.0.0/src/uploadshield/django/storage.py +204 -0
  48. uploadshield-2.0.0/src/uploadshield/django/templates/uploadshield/rejected.html +15 -0
  49. uploadshield-2.0.0/src/uploadshield/django/validators.py +48 -0
  50. uploadshield-2.0.0/src/uploadshield/django/views.py +40 -0
  51. uploadshield-2.0.0/src/uploadshield/engine.py +230 -0
  52. uploadshield-2.0.0/src/uploadshield/fastapi/__init__.py +23 -0
  53. uploadshield-2.0.0/src/uploadshield/fastapi/shield.py +299 -0
  54. uploadshield-2.0.0/src/uploadshield/flask/__init__.py +42 -0
  55. uploadshield-2.0.0/src/uploadshield/flask/core.py +359 -0
  56. uploadshield-2.0.0/src/uploadshield/flask/decorators.py +69 -0
  57. uploadshield-2.0.0/src/uploadshield/flask/wtforms.py +58 -0
  58. uploadshield-2.0.0/src/uploadshield/policy.py +137 -0
  59. uploadshield-2.0.0/src/uploadshield/presets.py +65 -0
  60. uploadshield-2.0.0/src/uploadshield/py.typed +0 -0
  61. uploadshield-2.0.0/src/uploadshield/sanitizers.py +132 -0
  62. uploadshield-2.0.0/src/uploadshield/web.py +218 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,239 @@
1
+ Metadata-Version: 2.4
2
+ Name: uploadshield
3
+ Version: 2.0.0
4
+ Summary: Content-aware validation and sanitization of file uploads for Django, Flask and FastAPI.
5
+ Keywords: django,flask,fastapi,upload,file,validation,sanitization,security,malware
6
+ Author: IV1T3
7
+ Author-email: IV1T3 <xandi98@web.de>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Framework :: Django
12
+ Classifier: Framework :: Django :: 4.2
13
+ Classifier: Framework :: Django :: 5.2
14
+ Classifier: Framework :: Django :: 6.0
15
+ Classifier: Framework :: FastAPI
16
+ Classifier: Framework :: Flask
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Topic :: Security
21
+ Classifier: Typing :: Typed
22
+ Requires-Dist: django>=4.2 ; extra == 'all'
23
+ Requires-Dist: flask>=2.3 ; extra == 'all'
24
+ Requires-Dist: fastapi>=0.110 ; extra == 'all'
25
+ Requires-Dist: python-multipart>=0.0.9 ; extra == 'all'
26
+ Requires-Dist: pillow>=10.0 ; extra == 'all'
27
+ Requires-Dist: yara-python>=4.3 ; extra == 'all'
28
+ Requires-Dist: python-magic>=0.4.27 ; extra == 'all'
29
+ Requires-Dist: magika>=1.0 ; python_full_version < '3.15' and extra == 'all'
30
+ Requires-Dist: django>=4.2 ; extra == 'django'
31
+ Requires-Dist: fastapi>=0.110 ; extra == 'fastapi'
32
+ Requires-Dist: python-multipart>=0.0.9 ; extra == 'fastapi'
33
+ Requires-Dist: flask>=2.3 ; extra == 'flask'
34
+ Requires-Dist: pillow>=10.0 ; extra == 'images'
35
+ Requires-Dist: python-magic>=0.4.27 ; extra == 'magic'
36
+ Requires-Dist: magika>=1.0 ; python_full_version < '3.15' and extra == 'magika'
37
+ Requires-Dist: yara-python>=4.3 ; extra == 'yara'
38
+ Requires-Python: >=3.11
39
+ Project-URL: Homepage, https://github.com/IV1T3/uploadshield
40
+ Project-URL: Issues, https://github.com/IV1T3/uploadshield/issues
41
+ Provides-Extra: all
42
+ Provides-Extra: django
43
+ Provides-Extra: fastapi
44
+ Provides-Extra: flask
45
+ Provides-Extra: images
46
+ Provides-Extra: magic
47
+ Provides-Extra: magika
48
+ Provides-Extra: yara
49
+ Description-Content-Type: text/markdown
50
+
51
+ # uploadshield
52
+
53
+ Content-aware validation and sanitization of file uploads for Django, Flask and FastAPI.
54
+
55
+ Web frameworks hand you the filename and `Content-Type` of an upload as if they were
56
+ facts. They are whatever the client sent: a PHP web shell named `cat.png` with
57
+ `Content-Type: image/png` arrives as an image in Django, Flask and FastAPI alike.
58
+ uploadshield judges the **bytes** instead. It detects the real format, checks it
59
+ against what the endpoint accepts, looks inside documents and archives for active
60
+ content, and can rewrite images so that hidden payloads and metadata are destroyed.
61
+
62
+ ## Try it in 10 seconds
63
+
64
+ No code needed; [uv](https://docs.astral.sh/uv/) runs it straight from PyPI:
65
+
66
+ ```console
67
+ $ uvx uploadshield scan uploads/
68
+ uploads/
69
+ ✗ avatar.png PHP script · 30 bytes
70
+ type_not_allowed PHP script files are not allowed.
71
+ embedded_code The file contains embedded code. <?php
72
+ ? backup.tar.gz gzip archive · 132 bytes
73
+ type_not_allowed Its contents cannot be inspected: unpack it and scan the files, or add --clamav.
74
+ ! holiday.png JPEG image · 14.6 KB
75
+ extension_mismatch The file extension '.png' does not match its content (JPEG image).
76
+ ✗ invoice.pdf PDF document · 293 bytes
77
+ pdf_active_content The PDF contains active content such as scripts or embedded files. JS, JavaScript
78
+ ✓ notes.txt Plain text · 14 bytes
79
+ ✓ report.pdf PDF document · 180 KB
80
+
81
+ 6 files in 0.0 s: 2 clean, 2 dangerous, 1 refused, 1 not verified.
82
+ ```
83
+
84
+ `uploadshield validate FILE --policy NAME` shows exactly why a policy accepts or
85
+ refuses a file. See the [command line guide](docs/cli.md).
86
+
87
+ ## What it protects against
88
+
89
+ - **Disguised files**: scripts and executables named `.png` or `.pdf`. The format
90
+ comes from the content, never from the name.
91
+ - **Dangerous names**: `shell.php.jpg`, `.htaccess`, `../../etc/passwd`, `CON.txt`,
92
+ bidi-override tricks, and their percent-encoded and fullwidth variants.
93
+ - **Active documents**: PDFs with JavaScript or embedded files, Office files with
94
+ macros, DDE fields or remote templates, SVGs with scripts, XML with entity bombs.
95
+ - **Archive attacks**: ZIP bombs, zip slip, symbolic links, deeply nested archives,
96
+ and members a server would run once extracted.
97
+ - **Hidden payloads**: PHP in image metadata, polyglots such as GIFAR, CSV cells that
98
+ run commands through DDE (`=cmd|' /C calc'!A0`).
99
+ - **Malware**, with ClamAV or your own YARA rules, and optionally Google's Magika model
100
+ for scripts disguised as data.
101
+
102
+ It fails closed: a check that crashes, a file too large to inspect, an encrypted file
103
+ or an unreachable virus scanner means a refusal. Image decoding needs Pillow, the
104
+ `images` extra (`uvx --from "uploadshield[images]" uploadshield scan ...`); without it
105
+ the command line warns that image checks are inactive. The
106
+ [checks reference](docs/checks.md) lists everything each check catches, and what it
107
+ does not.
108
+
109
+ ## Add it to your app
110
+
111
+ ```bash
112
+ uv add "uploadshield[django,images]" # or [flask,images] or [fastapi,images]
113
+ ```
114
+
115
+ **Django**: every file is checked while the request body streams in, in views, forms,
116
+ the admin and Django REST framework.
117
+
118
+ ```python
119
+ # settings.py
120
+ INSTALLED_APPS += ["uploadshield.django"]
121
+ FILE_UPLOAD_HANDLERS = ["uploadshield.django.handlers.ValidatingUploadHandler"]
122
+
123
+ # urls.py (root URLconf): answer refusals with 413/415/400, as JSON or HTML
124
+ handler400 = "uploadshield.django.views.bad_request"
125
+ ```
126
+
127
+ **Flask**: every multipart request is checked before it reaches a view.
128
+
129
+ ```python
130
+ from flask import Flask
131
+
132
+ from uploadshield.flask import UploadShield
133
+
134
+ app = Flask(__name__)
135
+ app.config["MAX_CONTENT_LENGTH"] = 50 * 1024 * 1024 # Werkzeug parses the body first
136
+ UploadShield(app)
137
+ ```
138
+
139
+ **FastAPI**: dependencies validate and sanitize uploads; `all_files()` covers the
140
+ whole app.
141
+
142
+ ```python
143
+ from typing import Annotated
144
+
145
+ from fastapi import Depends, FastAPI, UploadFile
146
+
147
+ from uploadshield.fastapi import UploadShield
148
+
149
+ shield = UploadShield()
150
+ app = FastAPI(dependencies=[Depends(shield.all_files())])
151
+
152
+
153
+ @app.post("/avatar")
154
+ async def avatar(
155
+ file: Annotated[UploadFile, Depends(shield.file("sanitized_images"))],
156
+ ): ... # re-encoded, renamed, with the content type detected from the bytes
157
+ ```
158
+
159
+ That's it: every upload is now checked against the built-in `default` policy (common
160
+ images, PDF, Office and OpenDocument files, text and CSV, audio and video, up to
161
+ 50 MB). Your code only receives files that passed; the others are answered with 413,
162
+ 415 or 400. On an existing site, start with `"MODE": "report"` to log would-be
163
+ refusals without blocking anything.
164
+
165
+ The guides cover every option: [Django](docs/django.md), [Flask](docs/flask.md),
166
+ [FastAPI](docs/fastapi.md).
167
+
168
+ ## Decide what to accept
169
+
170
+ A **policy** says which files an endpoint accepts. Pick a built-in one, or derive your
171
+ own:
172
+
173
+ ```python
174
+ from uploadshield import MB, Policy, presets
175
+
176
+ AVATARS = presets.SANITIZED_IMAGES.replace(name="avatars", max_size=2 * MB)
177
+ INVOICES = Policy(
178
+ name="invoices",
179
+ allowed_types={"application/pdf", "image/png", "image/jpeg"},
180
+ max_size=5 * MB,
181
+ )
182
+ ```
183
+
184
+ | Built-in policy | Accepts | Size limit |
185
+ |---|---|---|
186
+ | `default` | everything below | 50 MB |
187
+ | `images` | JPEG, PNG, GIF, WebP | 10 MB |
188
+ | `sanitized_images` | the same, re-encoded and randomly renamed | 10 MB |
189
+ | `pdf` | PDF | 25 MB |
190
+ | `documents` | PDF, Word, Excel, PowerPoint, OpenDocument, text, CSV | 25 MB |
191
+ | `media` | common audio and video formats | 500 MB |
192
+
193
+ Use one per view (`@validate_uploads("pdf")` in Django and Flask,
194
+ `shield.file("pdf")` in FastAPI), per URL pattern, or per form field. The
195
+ [policy guide](docs/policies.md) covers allowed types, filename rules, tuning checks,
196
+ virus scanners and sanitizers.
197
+
198
+ ## How it works
199
+
200
+ ![The client's upload is parsed by Django, Flask or FastAPI, which hands every file to
201
+ uploadshield. uploadshield checks size, filename, the type proven by the bytes, the
202
+ allow-list and the content, then sanitizes. Passing files reach your view; refused
203
+ files never do, and the client receives a 400, 413 or 415.](docs/images/upload-flow.svg)
204
+
205
+ - **Cheapest checks first.** A forbidden name is refused before any content is read;
206
+ expensive parsers only see files that passed the cheap checks.
207
+ - **Your code only sees files that passed**, sanitized if the policy says so, with the
208
+ content type detected from the bytes.
209
+ - **Every refusal is answered and recorded**: a stable code, a 400/413/415 response, a
210
+ structured log record and a signal or callback.
211
+
212
+ [Concepts](docs/concepts.md) explains the model; [Architecture](docs/ARCHITECTURE.md)
213
+ how it is built.
214
+
215
+ ## Documentation
216
+
217
+ | Page | What you find there |
218
+ |---|---|
219
+ | [Concepts](docs/concepts.md) | how uploadshield works, in one read |
220
+ | [Django](docs/django.md) · [Flask](docs/flask.md) · [FastAPI](docs/fastapi.md) | setup, every option, refusals, testing |
221
+ | [Command line](docs/cli.md) | `scan`, `validate`, JSON output for CI |
222
+ | [Policies](docs/policies.md) | choosing and configuring what to accept |
223
+ | [Checks and sanitizers](docs/checks.md) | every check with all its options |
224
+ | [Refusals](docs/refusals.md) | codes, status codes, messages, logs |
225
+ | [Python API](docs/python-api.md) | using the engine directly, custom checks and types |
226
+ | [All docs](docs/README.md) | the full map, and [`llms.txt`](llms.txt) for AI agents |
227
+
228
+ ## Security and compatibility
229
+
230
+ - **Mapped to OWASP**: every recommendation of OWASP's File Upload Cheat Sheet and
231
+ every test case of its Unrestricted File Upload page, with its coverage and the tests
232
+ that prove it, is in [docs/OWASP.md](docs/OWASP.md).
233
+ - **Supported**: Python 3.11+, Django 4.2+, Flask 2.3+, FastAPI 0.110+.
234
+ - **No required dependencies.** Pillow, YARA, Magika and libmagic are optional extras.
235
+ - **Typed** (`py.typed`), with about 2500 tests including property-based fuzzing.
236
+ - **Coming from django-middleware-fileuploadvalidation 1.x?** See
237
+ [Migrating from 1.x](docs/migrating-from-1.x.md).
238
+
239
+ Contributing: see [Development](docs/development.md). License: Apache-2.0.
@@ -0,0 +1,189 @@
1
+ # uploadshield
2
+
3
+ Content-aware validation and sanitization of file uploads for Django, Flask and FastAPI.
4
+
5
+ Web frameworks hand you the filename and `Content-Type` of an upload as if they were
6
+ facts. They are whatever the client sent: a PHP web shell named `cat.png` with
7
+ `Content-Type: image/png` arrives as an image in Django, Flask and FastAPI alike.
8
+ uploadshield judges the **bytes** instead. It detects the real format, checks it
9
+ against what the endpoint accepts, looks inside documents and archives for active
10
+ content, and can rewrite images so that hidden payloads and metadata are destroyed.
11
+
12
+ ## Try it in 10 seconds
13
+
14
+ No code needed; [uv](https://docs.astral.sh/uv/) runs it straight from PyPI:
15
+
16
+ ```console
17
+ $ uvx uploadshield scan uploads/
18
+ uploads/
19
+ ✗ avatar.png PHP script · 30 bytes
20
+ type_not_allowed PHP script files are not allowed.
21
+ embedded_code The file contains embedded code. <?php
22
+ ? backup.tar.gz gzip archive · 132 bytes
23
+ type_not_allowed Its contents cannot be inspected: unpack it and scan the files, or add --clamav.
24
+ ! holiday.png JPEG image · 14.6 KB
25
+ extension_mismatch The file extension '.png' does not match its content (JPEG image).
26
+ ✗ invoice.pdf PDF document · 293 bytes
27
+ pdf_active_content The PDF contains active content such as scripts or embedded files. JS, JavaScript
28
+ ✓ notes.txt Plain text · 14 bytes
29
+ ✓ report.pdf PDF document · 180 KB
30
+
31
+ 6 files in 0.0 s: 2 clean, 2 dangerous, 1 refused, 1 not verified.
32
+ ```
33
+
34
+ `uploadshield validate FILE --policy NAME` shows exactly why a policy accepts or
35
+ refuses a file. See the [command line guide](docs/cli.md).
36
+
37
+ ## What it protects against
38
+
39
+ - **Disguised files**: scripts and executables named `.png` or `.pdf`. The format
40
+ comes from the content, never from the name.
41
+ - **Dangerous names**: `shell.php.jpg`, `.htaccess`, `../../etc/passwd`, `CON.txt`,
42
+ bidi-override tricks, and their percent-encoded and fullwidth variants.
43
+ - **Active documents**: PDFs with JavaScript or embedded files, Office files with
44
+ macros, DDE fields or remote templates, SVGs with scripts, XML with entity bombs.
45
+ - **Archive attacks**: ZIP bombs, zip slip, symbolic links, deeply nested archives,
46
+ and members a server would run once extracted.
47
+ - **Hidden payloads**: PHP in image metadata, polyglots such as GIFAR, CSV cells that
48
+ run commands through DDE (`=cmd|' /C calc'!A0`).
49
+ - **Malware**, with ClamAV or your own YARA rules, and optionally Google's Magika model
50
+ for scripts disguised as data.
51
+
52
+ It fails closed: a check that crashes, a file too large to inspect, an encrypted file
53
+ or an unreachable virus scanner means a refusal. Image decoding needs Pillow, the
54
+ `images` extra (`uvx --from "uploadshield[images]" uploadshield scan ...`); without it
55
+ the command line warns that image checks are inactive. The
56
+ [checks reference](docs/checks.md) lists everything each check catches, and what it
57
+ does not.
58
+
59
+ ## Add it to your app
60
+
61
+ ```bash
62
+ uv add "uploadshield[django,images]" # or [flask,images] or [fastapi,images]
63
+ ```
64
+
65
+ **Django**: every file is checked while the request body streams in, in views, forms,
66
+ the admin and Django REST framework.
67
+
68
+ ```python
69
+ # settings.py
70
+ INSTALLED_APPS += ["uploadshield.django"]
71
+ FILE_UPLOAD_HANDLERS = ["uploadshield.django.handlers.ValidatingUploadHandler"]
72
+
73
+ # urls.py (root URLconf): answer refusals with 413/415/400, as JSON or HTML
74
+ handler400 = "uploadshield.django.views.bad_request"
75
+ ```
76
+
77
+ **Flask**: every multipart request is checked before it reaches a view.
78
+
79
+ ```python
80
+ from flask import Flask
81
+
82
+ from uploadshield.flask import UploadShield
83
+
84
+ app = Flask(__name__)
85
+ app.config["MAX_CONTENT_LENGTH"] = 50 * 1024 * 1024 # Werkzeug parses the body first
86
+ UploadShield(app)
87
+ ```
88
+
89
+ **FastAPI**: dependencies validate and sanitize uploads; `all_files()` covers the
90
+ whole app.
91
+
92
+ ```python
93
+ from typing import Annotated
94
+
95
+ from fastapi import Depends, FastAPI, UploadFile
96
+
97
+ from uploadshield.fastapi import UploadShield
98
+
99
+ shield = UploadShield()
100
+ app = FastAPI(dependencies=[Depends(shield.all_files())])
101
+
102
+
103
+ @app.post("/avatar")
104
+ async def avatar(
105
+ file: Annotated[UploadFile, Depends(shield.file("sanitized_images"))],
106
+ ): ... # re-encoded, renamed, with the content type detected from the bytes
107
+ ```
108
+
109
+ That's it: every upload is now checked against the built-in `default` policy (common
110
+ images, PDF, Office and OpenDocument files, text and CSV, audio and video, up to
111
+ 50 MB). Your code only receives files that passed; the others are answered with 413,
112
+ 415 or 400. On an existing site, start with `"MODE": "report"` to log would-be
113
+ refusals without blocking anything.
114
+
115
+ The guides cover every option: [Django](docs/django.md), [Flask](docs/flask.md),
116
+ [FastAPI](docs/fastapi.md).
117
+
118
+ ## Decide what to accept
119
+
120
+ A **policy** says which files an endpoint accepts. Pick a built-in one, or derive your
121
+ own:
122
+
123
+ ```python
124
+ from uploadshield import MB, Policy, presets
125
+
126
+ AVATARS = presets.SANITIZED_IMAGES.replace(name="avatars", max_size=2 * MB)
127
+ INVOICES = Policy(
128
+ name="invoices",
129
+ allowed_types={"application/pdf", "image/png", "image/jpeg"},
130
+ max_size=5 * MB,
131
+ )
132
+ ```
133
+
134
+ | Built-in policy | Accepts | Size limit |
135
+ |---|---|---|
136
+ | `default` | everything below | 50 MB |
137
+ | `images` | JPEG, PNG, GIF, WebP | 10 MB |
138
+ | `sanitized_images` | the same, re-encoded and randomly renamed | 10 MB |
139
+ | `pdf` | PDF | 25 MB |
140
+ | `documents` | PDF, Word, Excel, PowerPoint, OpenDocument, text, CSV | 25 MB |
141
+ | `media` | common audio and video formats | 500 MB |
142
+
143
+ Use one per view (`@validate_uploads("pdf")` in Django and Flask,
144
+ `shield.file("pdf")` in FastAPI), per URL pattern, or per form field. The
145
+ [policy guide](docs/policies.md) covers allowed types, filename rules, tuning checks,
146
+ virus scanners and sanitizers.
147
+
148
+ ## How it works
149
+
150
+ ![The client's upload is parsed by Django, Flask or FastAPI, which hands every file to
151
+ uploadshield. uploadshield checks size, filename, the type proven by the bytes, the
152
+ allow-list and the content, then sanitizes. Passing files reach your view; refused
153
+ files never do, and the client receives a 400, 413 or 415.](docs/images/upload-flow.svg)
154
+
155
+ - **Cheapest checks first.** A forbidden name is refused before any content is read;
156
+ expensive parsers only see files that passed the cheap checks.
157
+ - **Your code only sees files that passed**, sanitized if the policy says so, with the
158
+ content type detected from the bytes.
159
+ - **Every refusal is answered and recorded**: a stable code, a 400/413/415 response, a
160
+ structured log record and a signal or callback.
161
+
162
+ [Concepts](docs/concepts.md) explains the model; [Architecture](docs/ARCHITECTURE.md)
163
+ how it is built.
164
+
165
+ ## Documentation
166
+
167
+ | Page | What you find there |
168
+ |---|---|
169
+ | [Concepts](docs/concepts.md) | how uploadshield works, in one read |
170
+ | [Django](docs/django.md) · [Flask](docs/flask.md) · [FastAPI](docs/fastapi.md) | setup, every option, refusals, testing |
171
+ | [Command line](docs/cli.md) | `scan`, `validate`, JSON output for CI |
172
+ | [Policies](docs/policies.md) | choosing and configuring what to accept |
173
+ | [Checks and sanitizers](docs/checks.md) | every check with all its options |
174
+ | [Refusals](docs/refusals.md) | codes, status codes, messages, logs |
175
+ | [Python API](docs/python-api.md) | using the engine directly, custom checks and types |
176
+ | [All docs](docs/README.md) | the full map, and [`llms.txt`](llms.txt) for AI agents |
177
+
178
+ ## Security and compatibility
179
+
180
+ - **Mapped to OWASP**: every recommendation of OWASP's File Upload Cheat Sheet and
181
+ every test case of its Unrestricted File Upload page, with its coverage and the tests
182
+ that prove it, is in [docs/OWASP.md](docs/OWASP.md).
183
+ - **Supported**: Python 3.11+, Django 4.2+, Flask 2.3+, FastAPI 0.110+.
184
+ - **No required dependencies.** Pillow, YARA, Magika and libmagic are optional extras.
185
+ - **Typed** (`py.typed`), with about 2500 tests including property-based fuzzing.
186
+ - **Coming from django-middleware-fileuploadvalidation 1.x?** See
187
+ [Migrating from 1.x](docs/migrating-from-1.x.md).
188
+
189
+ Contributing: see [Development](docs/development.md). License: Apache-2.0.