-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileManager.aspx
More file actions
506 lines (433 loc) · 20.9 KB
/
FileManager.aspx
File metadata and controls
506 lines (433 loc) · 20.9 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
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Web.Security" %>
<!DOCTYPE html>
<html>
<head>
<title>Educational File Management System</title>
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.container { max-width: 1000px; margin: 0 auto; background: white; border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,0.1); overflow: hidden; }
.header { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; padding: 20px; text-align: center; }
.content { padding: 30px; }
.section { margin-bottom: 30px; padding: 20px; border: 1px solid #e0e0e0; border-radius: 8px; background: #fafafa; }
.form-group { margin-bottom: 15px; }
label { display: block; margin-bottom: 5px; font-weight: 600; color: #333; }
input[type="text"], input[type="file"], select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px; }
.btn { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 24px; border: none; border-radius: 6px; cursor: pointer; font-size: 14px; font-weight: 600; transition: transform 0.2s; }
.btn:hover { transform: translateY(-2px); }
.btn-danger { background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%); }
.btn-success { background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%); }
.alert { padding: 15px; margin: 15px 0; border-radius: 6px; }
.alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
.alert-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
.alert-warning { background: #fff3cd; color: #856404; border: 1px solid #ffeaa7; }
.file-info { background: white; padding: 15px; border-radius: 6px; margin: 10px 0; border-left: 4px solid #667eea; }
.security-notice { background: #e74c3c; color: white; padding: 15px; border-radius: 6px; margin-bottom: 20px; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🗂️ Educational File Management System</h1>
<p>Secure file operations with comprehensive validation and logging</p>
</div>
<div class="content">
<!-- Security Notice -->
<div class="security-notice">
<strong>🔒 Security Notice:</strong> This is an educational implementation. Production systems require additional security measures including authentication, authorization, file type validation, virus scanning, and comprehensive audit logging.
</div>
<form id="fileForm" runat="server">
<!-- File Upload Section -->
<div class="section">
<h2>📤 Secure File Upload</h2>
<div class="form-group">
<label for="fuFileUpload">Select File:</label>
<asp:FileUpload ID="fuFileUpload" runat="server" />
</div>
<div class="form-group">
<label for="txtUploadPath">Upload Directory:</label>
<asp:TextBox ID="txtUploadPath" runat="server" Text="~/App_Data/Uploads/"
placeholder="Enter secure upload directory path" />
</div>
<div class="form-group">
<asp:CheckBox ID="chkOverwriteFile" runat="server" Text="Allow file overwrite" />
</div>
<asp:Button ID="btnUpload" runat="server" Text="🔼 Upload File"
CssClass="btn btn-success" OnClick="UploadFile_Click" />
</div>
<!-- File Download Section -->
<div class="section">
<h2>📥 Secure File Download</h2>
<div class="form-group">
<label for="txtDownloadPath">File Path:</label>
<asp:TextBox ID="txtDownloadPath" runat="server"
placeholder="Enter file path relative to application root" />
</div>
<asp:Button ID="btnDownload" runat="server" Text="⬇️ Download File"
CssClass="btn" OnClick="DownloadFile_Click" />
</div>
<!-- File Deletion Section -->
<div class="section">
<h2>🗑️ Secure File Deletion</h2>
<div class="form-group">
<label for="txtDeletePath">File Path:</label>
<asp:TextBox ID="txtDeletePath" runat="server"
placeholder="Enter file path to delete" />
</div>
<div class="form-group">
<asp:CheckBox ID="chkConfirmDelete" runat="server" Text="I confirm this file deletion" />
<asp:RequiredFieldValidator ID="rfvConfirmDelete" runat="server"
ControlToValidate="chkConfirmDelete"
ErrorMessage="Please confirm file deletion"
ForeColor="Red" ValidationGroup="DeleteGroup" />
</div>
<asp:Button ID="btnDelete" runat="server" Text="🗑️ Delete File"
CssClass="btn btn-danger" OnClick="DeleteFile_Click" ValidationGroup="DeleteGroup" />
</div>
<!-- File Information Section -->
<div class="section">
<h2>📋 File Information</h2>
<div class="form-group">
<label for="txtInfoPath">File Path:</label>
<asp:TextBox ID="txtInfoPath" runat="server"
placeholder="Enter file path to get information" />
</div>
<asp:Button ID="btnGetInfo" runat="server" Text="ℹ️ Get File Info"
CssClass="btn" OnClick="GetFileInfo_Click" />
</div>
<!-- Results Display -->
<asp:Panel ID="pnlResults" runat="server" Visible="false">
<asp:Label ID="lblResults" runat="server" />
</asp:Panel>
</form>
</div>
</div>
</body>
</html>
<script runat="server">
// Educational: Define allowed file extensions for security
private readonly string[] AllowedExtensions = { ".txt", ".pdf", ".doc", ".docx", ".jpg", ".png", ".gif" };
private readonly long MaxFileSize = 5 * 1024 * 1024; // 5MB limit
/// <summary>
/// Handles secure file upload with comprehensive validation
/// Educational implementation demonstrating file upload security best practices
/// </summary>
protected void UploadFile_Click(object sender, EventArgs e)
{
try
{
// Validate file selection
if (!fuFileUpload.HasFile)
{
ShowResult("❌ Please select a file to upload.", false);
return;
}
// Get and validate file information
string fileName = Path.GetFileName(fuFileUpload.FileName);
string fileExtension = Path.GetExtension(fileName).ToLower();
long fileSize = fuFileUpload.PostedFile.ContentLength;
// Security validation: Check file extension
if (!IsAllowedFileType(fileExtension))
{
ShowResult($"❌ File type '{fileExtension}' is not allowed. Allowed types: {string.Join(", ", AllowedExtensions)}", false);
return;
}
// Security validation: Check file size
if (fileSize > MaxFileSize)
{
ShowResult($"❌ File size ({fileSize / 1024 / 1024:F1}MB) exceeds maximum allowed size ({MaxFileSize / 1024 / 1024}MB).", false);
return;
}
// Validate and sanitize upload path
string uploadPath = ValidateAndSanitizePath(txtUploadPath.Text);
string fullUploadPath = Server.MapPath(uploadPath);
// Ensure upload directory exists
if (!Directory.Exists(fullUploadPath))
{
Directory.CreateDirectory(fullUploadPath);
}
// Generate secure filename to prevent path traversal attacks
string secureFileName = GenerateSecureFileName(fileName);
string fullFilePath = Path.Combine(fullUploadPath, secureFileName);
// Check for file existence
if (File.Exists(fullFilePath) && !chkOverwriteFile.Checked)
{
ShowResult($"❌ File '{secureFileName}' already exists. Enable overwrite to replace it.", false);
return;
}
// Perform the upload
fuFileUpload.SaveAs(fullFilePath);
// Log the operation
LogFileOperation("UPLOAD", secureFileName, fullFilePath, fileSize);
ShowResult($"✅ File '{secureFileName}' uploaded successfully to '{uploadPath}' ({fileSize / 1024:F1} KB)", true);
}
catch (Exception ex)
{
ShowResult($"❌ Upload failed: {ex.Message}", false);
LogError("UPLOAD_ERROR", ex);
}
}
/// <summary>
/// Handles secure file download with path validation
/// Educational implementation demonstrating secure file serving
/// </summary>
protected void DownloadFile_Click(object sender, EventArgs e)
{
try
{
// Validate and sanitize file path
string filePath = ValidateAndSanitizePath(txtDownloadPath.Text);
string fullPath = Server.MapPath(filePath);
// Security check: Ensure file exists and is within allowed directory
if (!File.Exists(fullPath))
{
ShowResult("❌ File not found or access denied.", false);
return;
}
// Security check: Prevent directory traversal
if (!IsPathSecure(fullPath))
{
ShowResult("❌ Access to this file path is not allowed.", false);
return;
}
// Get file information
FileInfo fileInfo = new FileInfo(fullPath);
// Set response headers for secure download
Response.Clear();
Response.ContentType = GetMimeType(fileInfo.Extension);
Response.AppendHeader("Content-Disposition", $"attachment; filename=\"{fileInfo.Name}\"");
Response.AppendHeader("Content-Length", fileInfo.Length.ToString());
// Educational: Add security headers
Response.AppendHeader("X-Content-Type-Options", "nosniff");
Response.AppendHeader("X-Frame-Options", "DENY");
// Stream the file
Response.TransmitFile(fullPath);
// Log the operation
LogFileOperation("DOWNLOAD", fileInfo.Name, fullPath, fileInfo.Length);
Response.End();
}
catch (Exception ex)
{
ShowResult($"❌ Download failed: {ex.Message}", false);
LogError("DOWNLOAD_ERROR", ex);
}
}
/// <summary>
/// Handles secure file deletion with confirmation
/// Educational implementation demonstrating safe file deletion
/// </summary>
protected void DeleteFile_Click(object sender, EventArgs e)
{
try
{
// Validate confirmation checkbox
if (!chkConfirmDelete.Checked)
{
ShowResult("❌ Please confirm file deletion by checking the confirmation box.", false);
return;
}
// Validate and sanitize file path
string filePath = ValidateAndSanitizePath(txtDeletePath.Text);
string fullPath = Server.MapPath(filePath);
// Security checks
if (!File.Exists(fullPath))
{
ShowResult("❌ File not found.", false);
return;
}
if (!IsPathSecure(fullPath))
{
ShowResult("❌ Access to this file path is not allowed.", false);
return;
}
// Get file info before deletion for logging
FileInfo fileInfo = new FileInfo(fullPath);
string fileName = fileInfo.Name;
long fileSize = fileInfo.Length;
// Perform secure deletion
File.Delete(fullPath);
// Log the operation
LogFileOperation("DELETE", fileName, fullPath, fileSize);
ShowResult($"✅ File '{fileName}' deleted successfully.", true);
// Clear the confirmation checkbox
chkConfirmDelete.Checked = false;
}
catch (Exception ex)
{
ShowResult($"❌ Deletion failed: {ex.Message}", false);
LogError("DELETE_ERROR", ex);
}
}
/// <summary>
/// Retrieves and displays comprehensive file information
/// Educational implementation demonstrating file system analysis
/// </summary>
protected void GetFileInfo_Click(object sender, EventArgs e)
{
try
{
// Validate and sanitize file path
string filePath = ValidateAndSanitizePath(txtInfoPath.Text);
string fullPath = Server.MapPath(filePath);
// Security checks
if (!File.Exists(fullPath))
{
ShowResult("❌ File not found.", false);
return;
}
if (!IsPathSecure(fullPath))
{
ShowResult("❌ Access to this file path is not allowed.", false);
return;
}
// Get comprehensive file information
FileInfo fileInfo = new FileInfo(fullPath);
string fileInfoHtml = $@"
<div class='file-info'>
<h3>📄 File Information</h3>
<p><strong>Name:</strong> {fileInfo.Name}</p>
<p><strong>Full Path:</strong> {fileInfo.FullName}</p>
<p><strong>Size:</strong> {fileInfo.Length:N0} bytes ({fileInfo.Length / 1024.0:F1} KB)</p>
<p><strong>Extension:</strong> {fileInfo.Extension}</p>
<p><strong>Created:</strong> {fileInfo.CreationTime:yyyy-MM-dd HH:mm:ss}</p>
<p><strong>Modified:</strong> {fileInfo.LastWriteTime:yyyy-MM-dd HH:mm:ss}</p>
<p><strong>Accessed:</strong> {fileInfo.LastAccessTime:yyyy-MM-dd HH:mm:ss}</p>
<p><strong>Attributes:</strong> {fileInfo.Attributes}</p>
<p><strong>Read Only:</strong> {fileInfo.IsReadOnly}</p>
<p><strong>MIME Type:</strong> {GetMimeType(fileInfo.Extension)}</p>
</div>";
ShowResult(fileInfoHtml, true);
// Log the operation
LogFileOperation("INFO", fileInfo.Name, fullPath, fileInfo.Length);
}
catch (Exception ex)
{
ShowResult($"❌ Failed to get file information: {ex.Message}", false);
LogError("INFO_ERROR", ex);
}
}
/// <summary>
/// Validates file type against allowed extensions
/// Educational implementation of file type security validation
/// </summary>
private bool IsAllowedFileType(string extension)
{
return AllowedExtensions.Contains(extension.ToLower());
}
/// <summary>
/// Validates and sanitizes file paths to prevent directory traversal attacks
/// Educational implementation of path security validation
/// </summary>
private string ValidateAndSanitizePath(string path)
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentException("Path cannot be empty");
// Remove dangerous characters and sequences
path = path.Replace("..", "").Replace("\\", "/").Trim();
// Ensure path starts with ~/ for application-relative paths
if (!path.StartsWith("~/"))
path = "~/" + path.TrimStart('/');
return path;
}
/// <summary>
/// Checks if a file path is within allowed directories
/// Educational implementation of path security validation
/// </summary>
private bool IsPathSecure(string fullPath)
{
try
{
// Get the application root directory
string appRoot = Server.MapPath("~/");
// Resolve the full canonical path
string canonicalPath = Path.GetFullPath(fullPath);
// Ensure the file is within the application directory
return canonicalPath.StartsWith(appRoot, StringComparison.OrdinalIgnoreCase);
}
catch
{
return false;
}
}
/// <summary>
/// Generates a secure filename to prevent various attacks
/// Educational implementation of filename sanitization
/// </summary>
private string GenerateSecureFileName(string originalFileName)
{
// Remove path information
string fileName = Path.GetFileName(originalFileName);
// Remove or replace dangerous characters
string secureFileName = System.Text.RegularExpressions.Regex.Replace(fileName, @"[^\w\-_\.]", "_");
// Add timestamp to prevent conflicts
string nameWithoutExt = Path.GetFileNameWithoutExtension(secureFileName);
string extension = Path.GetExtension(secureFileName);
return $"{nameWithoutExt}_{DateTime.Now:yyyyMMdd_HHmmss}{extension}";
}
/// <summary>
/// Gets MIME type for file extension
/// Educational implementation of MIME type determination
/// </summary>
private string GetMimeType(string extension)
{
switch (extension.ToLower())
{
case ".txt": return "text/plain";
case ".pdf": return "application/pdf";
case ".doc": return "application/msword";
case ".docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
case ".jpg":
case ".jpeg": return "image/jpeg";
case ".png": return "image/png";
case ".gif": return "image/gif";
default: return "application/octet-stream";
}
}
/// <summary>
/// Logs file operations for audit purposes
/// Educational implementation of security auditing
/// </summary>
private void LogFileOperation(string operation, string fileName, string filePath, long fileSize)
{
try
{
string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {operation}: {fileName} | Path: {filePath} | Size: {fileSize} bytes | User: {Environment.UserName} | IP: {Request.UserHostAddress}";
string logPath = Server.MapPath("~/App_Data/FileOperations.log");
Directory.CreateDirectory(Path.GetDirectoryName(logPath));
File.AppendAllText(logPath, logEntry + Environment.NewLine);
}
catch
{
// Educational: Never let logging failures break the main operation
}
}
/// <summary>
/// Logs errors for debugging and security monitoring
/// Educational implementation of error logging
/// </summary>
private void LogError(string operation, Exception ex)
{
try
{
string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] ERROR in {operation}: {ex.Message} | User: {Environment.UserName} | IP: {Request.UserHostAddress}";
string logPath = Server.MapPath("~/App_Data/Errors.log");
Directory.CreateDirectory(Path.GetDirectoryName(logPath));
File.AppendAllText(logPath, logEntry + Environment.NewLine);
}
catch
{
// Educational: Silent failure for logging
}
}
/// <summary>
/// Displays operation results with appropriate styling
/// Educational implementation of user feedback
/// </summary>
private void ShowResult(string message, bool isSuccess)
{
pnlResults.Visible = true;
string alertClass = isSuccess ? "alert-success" : "alert-error";
lblResults.Text = $"<div class='alert {alertClass}'>{message}</div>";
}
</script>