Skip to content

Commit 2a0f339

Browse files
committed
Security considerations for file uploads
1 parent ec9d5af commit 2a0f339

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

aspnetcore/blazor/file-uploads.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,48 @@ The maximum supported file size for the <xref:Microsoft.AspNetCore.Components.Fo
142142

143143
:::moniker-end
144144

145+
## Security considerations
146+
147+
### Avoid `IBrowserFile.Size` for file size limits
148+
149+
Avoid using <xref:Microsoft.AspNetCore.Components.Forms.IBrowserFile.Size?displayProperty=nameWithType> to impose a limit on the file size.
150+
151+
<span aria-hidden="true">❌</span> The following approach is ***insecure*** and must be avoided:
152+
153+
```diff
154+
- var fileContent = new StreamContent(file.OpenReadStream(file.Size));
155+
```
156+
157+
Instead of using the unsafe client-supplied file size, explicitly specify the maximum file size. The following example sets the maximum file size (`maxFileSize`) to 15 K:
158+
159+
```csharp
160+
long maxFileSize = 1024 * 15;
161+
162+
...
163+
164+
var fileContent = new StreamContent(file.OpenReadStream(maxFileSize));
165+
```
166+
167+
### File name security
168+
169+
Never use a client-supplied file name for saving a file to physical storage. Create a safe file name for the file using <xref:System.IO.Path.GetRandomFileName?displayProperty=nameWithType> or <xref:System.IO.Path.GetTempFileName?displayProperty=nameWithType> to create a full path (including the file name) for temporary storage.
170+
171+
Razor automatically HTML encodes property values for display. The following code is safe to use:
172+
173+
```cshtml
174+
@foreach (var file in Model.DatabaseFiles) {
175+
<tr>
176+
<td>
177+
@file.UntrustedName
178+
</td>
179+
</tr>
180+
}
181+
```
182+
183+
Outside of Razor, always use <xref:System.Net.WebUtility.HtmlEncode%2A> to safely encode file names from a user's request.
184+
185+
Many implementations must include a check that the file exists; otherwise, the file is overwritten by a file of the same name. Supply additional logic to meet your app's specifications.
186+
145187
## Examples
146188

147189
The following examples demonstrate multiple file upload in a component. <xref:Microsoft.AspNetCore.Components.Forms.InputFileChangeEventArgs.GetMultipleFiles%2A?displayProperty=nameWithType> allows reading multiple files. Specify the maximum number of files to prevent a malicious user from uploading a larger number of files than the app expects. <xref:Microsoft.AspNetCore.Components.Forms.InputFileChangeEventArgs.File?displayProperty=nameWithType> allows reading the first and only file if the file upload doesn't support multiple files.

0 commit comments

Comments
 (0)