-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCMS.cs
More file actions
752 lines (638 loc) · 31.3 KB
/
Copy pathCMS.cs
File metadata and controls
752 lines (638 loc) · 31.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
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
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.IO.Compression;
using System.Net;
using System.Security.Cryptography;
using System.Text.Json;
using Viper.Areas.CMS.Models;
using Viper.Classes.SQLContext;
using Viper.Classes.Utilities;
using Viper.Models;
using Viper.Models.AAUD;
using Viper.Models.VIPER;
using Viper.Services;
namespace Viper.Areas.CMS.Data
{
public class CMS : ICMS
{
#region Properties (private/public)
private readonly VIPERContext? _viperContext;
private readonly RAPSContext? _rapsContext;
private readonly IHtmlSanitizerService _sanitizerService;
private readonly ILogger<CMS>? _logger;
public IUserHelper UserHelper { get; set; }
public Dictionary<string, string> MimeTypes { get; set; } = new()
{
["pdf"] = "application/pdf",
["docx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
["doc"] = "application/msword",
["xls"] = "application/vnd.ms-excel",
["xlsx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
["csv"] = "text/csv",
["ppt"] = "application/vnd.ms-powerpoint",
["pptx"] = "application/vnd.openxmlformats-officedocument.presentationml.presentation",
["pptm"] = "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
["txt"] = "text/plain",
["html"] = "application/xhtml+xml",
["gif"] = "image/gif",
["png"] = "image/png",
["jpg"] = "image/jpeg",
["jpeg"] = "image/jpeg",
["tiff"] = "image/tiff",
["mp3"] = "audio/mpeg",
["wav"] = "audio/wav",
["mp4"] = "video/mp4",
["webm"] = "video/webm",
["oft"] = "application/vnd.ms-outlook",
["eps"] = "application/postscript",
["zip"] = "application/zip",
["7z"] = "application/x-7z-compressed",
["dmg"] = "application/x-apple-diskimage",
["exe"] = "application/vnd.microsoft.portable-executable"
};
#endregion
#region Constructors
public CMS(VIPERContext viperContext, RAPSContext rapsContext, IHtmlSanitizerService sanitizerService, ILogger<CMS>? logger = null)
{
this._viperContext = viperContext;
this._rapsContext = rapsContext;
this._sanitizerService = sanitizerService;
this._logger = logger;
UserHelper = new UserHelper();
}
#endregion
#region public IEnumerable<ContentBlock>? GetContentBlocksAllowed(int? contentBlockID, string? friendlyName, string? system, string? viperSectionPath, string? page, int? blockOrder, bool? allowPublicAccess, int? status)
/// <summary>
/// Get content blocks and filter based on permissions
/// </summary>
/// <param name="contentBlockID"></param>
/// <param name="friendlyName"></param>
/// <param name="system"></param>
/// <param name="viperSectionPath"></param>
/// <param name="page"></param>
/// <param name="blockOrder"></param>
/// <param name="allowPublicAccess"></param>
/// <param name="status"></param>
/// <returns>List of blocks</returns>
public IEnumerable<ContentBlock>? GetContentBlocksAllowed(int? contentBlockID, string? friendlyName, string? system, string? viperSectionPath, string? page, int? blockOrder, bool? allowPublicAccess, int? status)
{
// Fetch raw (no sanitization): we sanitize after the permission filter so we don't
// waste work on blocks the current user isn't allowed to see.
var blocks = FetchContentBlocks(contentBlockID, friendlyName, system, viperSectionPath, page, blockOrder, allowPublicAccess, status);
AaudUser? currentUser = UserHelper.GetCurrentUser();
List<ContentBlock> goodBlocks = new();
if (blocks != null && _rapsContext != null)
{
foreach (var b in blocks)
{
var hasAccess = b.AllowPublicAccess; //block is available without authentication
if (!hasAccess && currentUser != null)
{
hasAccess =
//CMS admin
UserHelper.HasPermission(_rapsContext, currentUser, "SVMSecure.CMS.ManageContentBlocks") ||
//available to all logged in users
b.ContentBlockToPermissions.Count == 0 && UserHelper.HasPermission(_rapsContext, currentUser, "SVMSecure") ||
//available due to having specific permission(s)
b.ContentBlockToPermissions.Count > 0 && b.ContentBlockToPermissions
.Any(cp => UserHelper.GetAllPermissions(_rapsContext, currentUser)
.Any(p => string.Compare(cp.Permission, p.Permission, true) == 0));
}
// only include blocks that the user has permission to see
if (hasAccess)
{
goodBlocks.Add(b);
}
}
SanitizeContentBlocks(goodBlocks);
return goodBlocks;
}
else
{ return null; }
}
#endregion
#region public IEnumerable<ContentBlock>? GetContentBlocks(int? contentBlockID, string? friendlyName, string? system, string? viperSectionPath, string? page, int? blockOrder, bool? allowPublicAccess, int? status)
/// <summary>
/// Get content blocks without filtering on permissions
/// </summary>
/// <param name="contentBlockID"></param>
/// <param name="friendlyName"></param>
/// <param name="system"></param>
/// <param name="viperSectionPath"></param>
/// <param name="page"></param>
/// <param name="blockOrder"></param>
/// <param name="allowPublicAccess"></param>
/// <param name="status"></param>
/// <returns>List of blocks</returns>
public IEnumerable<ContentBlock>? GetContentBlocks(int? contentBlockID = null, string? friendlyName = null, string? system = null,
string? viperSectionPath = null, string? page = null, int? blockOrder = null,
bool? allowPublicAccess = null, int? status = null)
{
var blocks = FetchContentBlocks(contentBlockID, friendlyName, system, viperSectionPath, page, blockOrder, allowPublicAccess, status);
if (blocks != null)
{
SanitizeContentBlocks(blocks);
}
return blocks;
}
#endregion
// AsNoTracking because SanitizeContentBlocks mutates b.Content; a later SaveChanges on a
// tracked entity (e.g. DeleteContentBlock setting State=Modified) would otherwise persist
// the sanitized HTML back to the DB as a side-effect of a read.
private List<ContentBlock>? FetchContentBlocks(int? contentBlockID, string? friendlyName, string? system,
string? viperSectionPath, string? page, int? blockOrder,
bool? allowPublicAccess, int? status)
{
return _viperContext?.ContentBlocks
.AsNoTracking()
.Include(p => p.ContentBlockToPermissions)
.Include(f => f.ContentBlockToFiles)
.ThenInclude(cbf => cbf.File)
.Include(h => h.ContentHistories)
.Where(c => c.ContentBlockId.Equals(contentBlockID) || contentBlockID == null)
.Where(c => string.IsNullOrEmpty(c.FriendlyName) ? string.IsNullOrEmpty(friendlyName) : c.FriendlyName.Equals(friendlyName) || string.IsNullOrEmpty(friendlyName))
.Where(c => c.System.Equals(system) || string.IsNullOrEmpty(system))
.Where(c => string.IsNullOrEmpty(c.ViperSectionPath) ? string.IsNullOrEmpty(viperSectionPath) : c.ViperSectionPath.Equals(viperSectionPath) || string.IsNullOrEmpty(viperSectionPath))
.Where(c => string.IsNullOrEmpty(c.Page) ? string.IsNullOrEmpty(page) : c.Page.Equals(page) || string.IsNullOrEmpty(page))
.Where(c => c.BlockOrder.Equals(blockOrder) || blockOrder == null)
.Where(c => c.AllowPublicAccess.Equals(allowPublicAccess) || allowPublicAccess == null)
.Where(c => (c.DeletedOn == null && status == 1) || (c.DeletedOn != null && status == 0) || status == null)
.OrderBy(c => c.BlockOrder)
.AsSplitQuery()
.ToList();
}
private void SanitizeContentBlocks(IEnumerable<ContentBlock> blocks)
{
foreach (var b in blocks)
{
b.Content = _sanitizerService.Sanitize(b.Content);
}
}
#region public CMSFile? GetFile(string? fileGUID, string? oldURL, string? friendlyName, string? folder, string? name)
/// <summary>
/// Returns the first file that matches the parameters past (or null)
/// </summary>
/// <param name="fileGUID"></param>
/// <param name="oldURL"></param>
/// <param name="friendlyName"></param>
/// <param name="folder"></param>
/// <param name="name"></param>
/// <param name="getDeleted"></param>
/// <returns>File object</returns>
public CMSFile? GetFile(string? fileGUID, string? oldURL, string? friendlyName, string? folder, string? name)
{
// Dispatch to a per-identifier method so each query shape gets its own cached plan,
// avoiding the catch-all (@P IS NULL OR col = @P) antipattern. See VPR-143.
if (!string.IsNullOrEmpty(fileGUID) && Guid.TryParse(fileGUID, out var guid))
{
return GetFileByGuid(guid);
}
if (!string.IsNullOrEmpty(oldURL))
{
return GetFileByOldUrl(oldURL);
}
if (!string.IsNullOrEmpty(friendlyName))
{
return GetFileByFriendlyName(friendlyName);
}
if (!string.IsNullOrEmpty(folder) || !string.IsNullOrEmpty(name))
{
return GetFileByFolderAndName(folder ?? string.Empty, name ?? string.Empty);
}
return null;
}
public CMSFile? GetFileByGuid(Guid fileGuid)
{
var file = _viperContext?.Files
.Include(p => p.FileToPermissions)
.Include(p => p.FileToPeople)
.AsSplitQuery()
.TagWith("CMS.GetFileByGuid")
.FirstOrDefault(f => f.FileGuid == fileGuid);
return ToCMSFile(file);
}
public CMSFile? GetFileByOldUrl(string oldUrl)
{
var file = _viperContext?.Files
.Include(p => p.FileToPermissions)
.Include(p => p.FileToPeople)
.AsSplitQuery()
.TagWith("CMS.GetFileByOldUrl")
.FirstOrDefault(f => f.OldUrl == oldUrl);
return ToCMSFile(file);
}
public CMSFile? GetFileByFriendlyName(string friendlyName)
{
var file = _viperContext?.Files
.Include(p => p.FileToPermissions)
.Include(p => p.FileToPeople)
.AsSplitQuery()
.TagWith("CMS.GetFileByFriendlyName")
.FirstOrDefault(f => f.FriendlyName == friendlyName);
return ToCMSFile(file);
}
public CMSFile? GetFileByFolderAndName(string folder, string name)
{
var filePath = folder + @"\" + name;
var file = _viperContext?.Files
.Include(p => p.FileToPermissions)
.Include(p => p.FileToPeople)
.AsSplitQuery()
.TagWith("CMS.GetFileByFolderAndName")
.FirstOrDefault(f => f.FilePath == filePath);
return ToCMSFile(file);
}
private static CMSFile? ToCMSFile(Viper.Models.VIPER.File? file)
{
if (file is null)
{
return null;
}
var cmsf = new CMSFile(file);
ReplaceRootFolder(cmsf);
return cmsf;
}
#endregion
#region public IEnumerable<CMSFile> GetAllFiles(string? folder, bool? isPublic, string? search, string? status, bool? encrypted)
/// <summary>
/// Search for matching files
/// </summary>
/// <param name="folder"></param>
/// <param name="isPublic"></param>
/// <param name="search"></param>
/// <param name="status"></param>
/// <param name="encrypted"></param>
/// <returns></returns>
public IEnumerable<CMSFile> GetAllFiles(string? folder, bool? isPublic, string? search, string? status, bool? encrypted)
{
// get files based on paramenters
var files = _viperContext?.Files
.Include(p => p.FileToPermissions)
.Include(p => p.FileToPeople)
.Where(f => (string.IsNullOrEmpty(folder) && f.FilePath.Contains(folder + @"\")) || string.IsNullOrEmpty(folder))
.Where(f => f.AllowPublicAccess.Equals(isPublic) || isPublic == null)
.Where(c => (string.IsNullOrEmpty(status) || (c.DeletedOn == null && status.ToLower() != "active") || (c.DeletedOn != null && status.ToLower() == "active")))
.Where(f => f.Encrypted.Equals(encrypted) || encrypted == null)
.Where(f => (string.IsNullOrEmpty(search) || f.FriendlyName.Contains(search, StringComparison.OrdinalIgnoreCase) ||
f.Description.Contains(search, StringComparison.OrdinalIgnoreCase) ||
string.IsNullOrEmpty(f.OldUrl) ? string.IsNullOrEmpty(search) : f.OldUrl.Contains(search, StringComparison.OrdinalIgnoreCase) ||
f.FilePath.Contains(search, StringComparison.OrdinalIgnoreCase)))
.OrderBy(c => c.FriendlyName)
.AsSplitQuery()
.ToList();
if (files != null)
{
List<CMSFile> cmslist = new();
foreach (var f in files)
{
CMSFile cmsf = new(f);
cmslist.Add(cmsf);
ReplaceRootFolder(cmsf);
}
return cmslist;
}
else
{
return new List<CMSFile>();
}
}
#endregion
#region public static string GetFriendlyURL(string friendlyName, bool allowPublicAccess = false)
/// <summary>
/// Get Friendly URL for a friendly name. Currently, always points to ColdFusion Viper
/// </summary>
/// <param name="friendlyName"></param>
/// <param name="allowPublicAccess"></param>
/// <returns></returns>
public static string GetFriendlyURL(string friendlyName, bool allowPublicAccess = false)
{
string rootURL = String.Empty;
HttpRequest? thisRequest = HttpHelper.HttpContext?.Request;
if (thisRequest != null)
{
Uri url = new(thisRequest.GetDisplayUrl());
rootURL = url.Scheme + Uri.SchemeDelimiter + url.Host;
}
return rootURL + (allowPublicAccess ? @"/public" : "") + @"/cms/files/?fn=" + WebUtility.UrlEncode(friendlyName);
}
#endregion
#region public static string GetURL(string fileGUID, bool allowPublicAccess = false)
/// <summary>
/// Get url for a fileGUID
/// </summary>
/// <param name="fileGUID"></param>
/// <param name="allowPublicAccess"></param>
/// <returns></returns>
public static string GetURL(string fileGUID, bool allowPublicAccess = false)
{
return (allowPublicAccess ? @"/public" : "") + @"/cms/files/?id=" + fileGUID;
}
#endregion
#region public static string GetRootFileFolder()
/// <summary>
/// Get the root folder for files
/// </summary>
/// <returns></returns>
public static string GetRootFileFolder()
{
if (HttpHelper.Environment?.EnvironmentName == "Development")
{
return @"C:\Sites\Files";
}
return @"S:\Files";
}
#endregion
#region public static void ReplaceRootFolder(CMSFile file)
/// <summary>
/// Replace the root folder in a file object, e.g. if the app is on secure-test but the file was added on a dev machine, or vice versa.
/// </summary>
/// <param name="file"></param>
public static void ReplaceRootFolder(CMSFile file)
{
string filePath = file.FilePath;
string rootFolder = GetRootFileFolder();
if (!filePath.StartsWith(rootFolder))
{
string endPath = filePath[(filePath.IndexOf(@"\Files", StringComparison.OrdinalIgnoreCase) + 6)..];
string fixedPath = rootFolder + endPath;
file.FilePath = fixedPath;
}
}
#endregion
#region public string FilePathToWebPath(string filePath)
/// <summary>
/// Remove root folder in the file path and change path separator to /
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public string FilePathToWebPath(string filePath)
{
return filePath.Replace(GetRootFileFolder(), "").Replace(@"\", @"/");
}
#endregion
#region public bool CheckFilePermission(CMSFile file)
public bool CheckFilePermission(CMSFile file)
{
AaudUser? currentUser = UserHelper.GetCurrentUser();
if (_rapsContext! != null && currentUser != null)
{
if (file.AllowPublicAccess ||
(file.FileToPermissions.Count == 0 && UserHelper.HasPermission(_rapsContext, currentUser, "SVMSecure")) ||
(file.FileToPermissions.Count > 0 && file.FileToPermissions.Any(fp => UserHelper.GetAllPermissions(_rapsContext, currentUser).Any(p => string.Compare(fp.Permission, p.Permission, true) == 0))) ||
(file.FileToPeople.Count > 0 && file.FileToPeople.Any(fp => fp.IamId == currentUser.IamId)))
{
return true;
}
}
else if (file.AllowPublicAccess)
{
return true;
}
return false;
}
#endregion
#region public IActionResult DownloadZip(Controller controller, string[] fileGUIDs, string fileName = "FileDownload.zip")
public IActionResult DownloadZip(Controller controller, string[] fileGUIDs, string fileName = "FileDownload.zip")
{
if (fileGUIDs.Length == 0 && fileName.Length == 0)
{
ArgumentNullException argumentNullException = new(nameof(fileGUIDs), "Missing fileGUIDs and file name parameters");
throw argumentNullException;
}
//only allow good filename characters
fileName = fileName.Replace(@"[^a-zA-Z0-9\.\-_ ]", "");
List<CMSFile> files = new();
AaudUser? currentUser = UserHelper.GetCurrentUser();
foreach (var guid in fileGUIDs)
{
CMSFile? file = GetFile(guid, null, null, null, null);
// only add files that exist and where the user has permission
if (file != null && System.IO.File.Exists(file.FilePath) && CheckFilePermission(file))
{
if (currentUser != null && _viperContext != null)
{
AuditFileAccess(_viperContext, file, currentUser, "AccessFile", string.Empty);
}
files.Add(file);
}
}
// create a temp Zip file and populate it with the files
string tempFileName = CMS.GetRootFileFolder() + @"\" + DateTime.Now.Ticks + fileName;
using (FileStream fs = System.IO.File.Open(tempFileName, FileMode.OpenOrCreate))
{
using ZipArchive archive = new(fs, ZipArchiveMode.Update);
foreach (var file in files)
{
if (file.Encrypted && !string.IsNullOrEmpty(file.Key))
{
ZipArchiveEntry fileEntry = archive.CreateEntry(file.FriendlyName);
using StreamWriter writer = new(fileEntry.Open());
byte[] filebytes = System.IO.File.ReadAllBytes(file.FilePath);
filebytes = DecryptFile(filebytes, file.Key);
if (filebytes != null)
{
writer.BaseStream.Write(filebytes, 0, filebytes.Length);
}
}
else
{
archive.CreateEntryFromFile(file.FilePath, file.FriendlyName);
}
}
}
// read the temp zip file then delete it
byte[] bytes = System.IO.File.ReadAllBytes(tempFileName);
if (bytes == null)
return controller.NotFound();
System.IO.File.Delete(tempFileName);
string extension = "zip";
return controller.File(bytes, MimeTypes[extension.ToLower()], fileName);
}
#endregion
#region public IActionResult ProvideFile(Controller controller, string id, string friendlyName, string oldURL)
public IActionResult ProvideFile(Controller controller, string id, string friendlyName, string oldURL)
{
AaudUser? currentUser = UserHelper.GetCurrentUser();
if (id.Length == 0 && friendlyName.Length == 0 && oldURL.Length == 0)
{
ArgumentNullException argumentNullException = new(nameof(id), "Missing id, file name, and old name parameters");
throw argumentNullException;
}
CMSFile? file = GetFile(id, oldURL, friendlyName, null, null);
string detail = string.Empty;
if (oldURL.Length > 0)
{
detail = "UsedOldURL#chr(13)##chr(10)#";
}
if (file == null)
{
LogFileNotFound(controller, id, friendlyName, oldURL, reason: "no-db-match");
return controller.NotFound();
}
else if (!System.IO.File.Exists(file.FilePath))
{
LogFileNotFound(controller, id, friendlyName, oldURL, reason: "missing-on-disk");
return controller.NotFound();
}
else if (!CheckFilePermission(file))
{
if (currentUser != null && _viperContext != null)
{
AuditFileAccess(_viperContext, file, currentUser, "AccessFileDenied", detail);
}
controller.Response.StatusCode = 403;
return controller.View("~/Views/Home/403.cshtml", (HttpStatusCode)403);
}
else
{
if (currentUser != null && _viperContext != null)
{
AuditFileAccess(_viperContext, file, currentUser, "AccessFile", detail);
}
byte[] bytes = System.IO.File.ReadAllBytes(file.FilePath);
if (file.Encrypted && !string.IsNullOrEmpty(file.Key))
{
bytes = DecryptFile(bytes, file.Key);
}
if (bytes == null)
return controller.NotFound();
string extension = file.FilePath[(file.FilePath.LastIndexOf('.') + 1)..];
controller.Response.Headers["Content-Disposition"] = "inline; filename=" + friendlyName;
return controller.File(bytes, MimeTypes[extension.ToLower()], true);
}
}
#endregion
// VPR-143: [CMS-FILE-404] emits a warning whenever ProvideFile can't serve a file.
// Grep the NLog output directory for the tag to see the distribution of misses
// (legacy URLs, typos, bot probes, ACME challenges, files missing on disk).
private void LogFileNotFound(Controller controller, string id, string friendlyName, string oldURL, string reason)
{
if (_logger is null)
{
return;
}
var request = controller.Request;
_logger.LogWarning(
"[CMS-FILE-404] reason={Reason} id={Id} friendlyName={FriendlyName} oldURL={OldUrl} " +
"userAgent={UserAgent} referer={Referer} remoteIp={RemoteIp}",
LogSanitizer.SanitizeString(reason),
LogSanitizer.SanitizeString(id),
LogSanitizer.SanitizeString(friendlyName),
LogSanitizer.SanitizeString(oldURL),
LogSanitizer.SanitizeString(request.Headers.UserAgent.ToString()),
LogSanitizer.SanitizeString(request.Headers.Referer.ToString()),
LogSanitizer.SanitizeString(request.HttpContext.Connection.RemoteIpAddress?.ToString() ?? string.Empty));
}
#region public static void AuditFileAccess(VIPERContext viperContext, CMSFile file, AaudUser user, string action, string detail)
public static void AuditFileAccess(VIPERContext viperContext, CMSFile file, AaudUser user, string action, string detail)
{
UserHelper userHelper = new();
FileAudit fileAudit = new()
{
Timestamp = DateTime.Now,
Loginid = user.LoginId,
Action = action,
Detail = detail,
FileGuid = file.FileGuid,
FilePath = file.FilePath,
IamId = user.IamId,
FileMetaData = JsonSerializer.Serialize<CMSFileMetaData>(file.MetaData),
ClientData = JsonSerializer.Serialize<ClientData>(userHelper.GetClientData())
};
viperContext.ChangeTracker.Clear();
viperContext.Add(fileAudit);
viperContext.SaveChanges();
}
#endregion
#region public byte[] DecryptFile(byte[] encryptedData, string keystring)
public byte[] DecryptFile(byte[] encryptedData, string keystring)
{
byte[] secretkey = GetSecretKey(keystring);
using Aes aes = Aes.Create();
aes.Mode = CipherMode.ECB;
using var ms = new MemoryStream();
using (var cs = new CryptoStream(ms, aes.CreateDecryptor(secretkey, null), CryptoStreamMode.Write))
{
cs.Write(encryptedData, 0, encryptedData.Length);
}
byte[] decryptedData = ms.ToArray();
return decryptedData;
}
#endregion
#region public string DecryptAES(string encryptedString, string Key)
/// <summary>
/// Required for Unix decoding FROM https://rextester.com/TGN19503
/// </summary>
/// <param name="encryptedString"></param>
/// <param name="Key"></param>
/// <returns>decoded string</returns>
public string DecryptAES(string encryptedString, string Key)
{
//First write to memory
using MemoryStream mmsStream = new();
using StreamWriter srwTemp = new(mmsStream);
srwTemp.Write(encryptedString);
srwTemp.Flush();
mmsStream.Position = 0;
using MemoryStream outstream = new();
//CallingUUDecode
Codecs.UUDecode(mmsStream, outstream);
//Extract the bytes of each of the values
byte[] input = outstream.ToArray();
byte[] key = Convert.FromBase64String(Key);
string? decryptedText = null;
using (Aes aes = Aes.Create())
{
// initialize settings to match those used by CF
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
aes.BlockSize = 128;
aes.KeySize = 128;
aes.Key = key;
ICryptoTransform decryptor = aes.CreateDecryptor();
using MemoryStream msDecrypt = new(input);
using CryptoStream csDecrypt = new(msDecrypt, decryptor, CryptoStreamMode.Read);
using StreamReader srDecrypt = new(csDecrypt);
decryptedText = srDecrypt.ReadToEnd();
}
return decryptedText;
}
#endregion
#region private byte[] getSecretKey(string key)
private byte[] GetSecretKey(string key)
{
string keyFileFolder = @"S:\Settings\";
if (HttpHelper.Environment?.EnvironmentName == "Development")
{
keyFileFolder = @"C:\Sites\Settings\";
}
string keyString = System.IO.File.ReadLines(keyFileFolder + "viperfiles.txt").Skip(1).Take(1).First();
byte[] hiddenKey = Convert.FromBase64String(DecryptAES(key, keyString));
return hiddenKey;
}
#endregion
}
public interface ICMS
{
IEnumerable<ContentBlock>? GetContentBlocksAllowed(int? contentBlockID, string? friendlyName, string? system, string? viperSectionPath, string? page, int? blockOrder, bool? allowPublicAccess, int? status);
IEnumerable<ContentBlock>? GetContentBlocks(int? contentBlockID = null, string? friendlyName = null, string? system = null, string? viperSectionPath = null, string? page = null, int? blockOrder = null, bool? allowPublicAccess = null, int? status = null);
CMSFile? GetFile(string? fileGUID, string? oldURL, string? friendlyName, string? folder, string? name);
CMSFile? GetFileByGuid(Guid fileGuid);
CMSFile? GetFileByOldUrl(string oldUrl);
CMSFile? GetFileByFriendlyName(string friendlyName);
CMSFile? GetFileByFolderAndName(string folder, string name);
IEnumerable<CMSFile> GetAllFiles(string? folder, bool? isPublic, string? search, string? status, bool? encrypted);
static string GetFriendlyURL(string friendlyName, bool allowPublicAccess = false) => throw new NotImplementedException();
static string GetURL(string fileGUID, bool allowPublicAccess = false) => throw new NotImplementedException();
static string GetRootFileFolder() => throw new NotImplementedException();
static void ReplaceRootFolder(CMSFile file) => throw new NotImplementedException();
string FilePathToWebPath(string filePath);
bool CheckFilePermission(CMSFile file);
IActionResult DownloadZip(Controller controller, string[] fileGUIDs, string fileName = "FileDownload.zip");
IActionResult ProvideFile(Controller controller, string id, string friendlyName, string oldURL);
static void AuditFileAccess(VIPERContext viperContext, CMSFile file, AaudUser user, string action, string detail) => throw new NotImplementedException();
byte[] DecryptFile(byte[] encryptedData, string keystring);
string DecryptAES(string encryptedString, string Key);
}
}