The next generation of the Teknik Services. Written in ASP.NET.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UploadController.cs 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. using nClam;
  2. using Piwik.Tracker;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data.Entity;
  6. using System.Drawing;
  7. using System.Drawing.Imaging;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Web;
  11. using System.Web.Mvc;
  12. using Teknik.Areas.Error.ViewModels;
  13. using Teknik.Areas.Upload.Models;
  14. using Teknik.Areas.Upload.ViewModels;
  15. using Teknik.Areas.Users.Utility;
  16. using Teknik.Controllers;
  17. using Teknik.Filters;
  18. using Teknik.Utilities;
  19. using Teknik.Models;
  20. using Teknik.Attributes;
  21. using System.Text;
  22. using Org.BouncyCastle.Crypto;
  23. namespace Teknik.Areas.Upload.Controllers
  24. {
  25. [TeknikAuthorize]
  26. public class UploadController : DefaultController
  27. {
  28. private TeknikEntities db = new TeknikEntities();
  29. // GET: Upload/Upload
  30. [HttpGet]
  31. [TrackPageView]
  32. [AllowAnonymous]
  33. public ActionResult Index()
  34. {
  35. ViewBag.Title = "Teknik Upload - End to End Encryption";
  36. UploadViewModel model = new UploadViewModel();
  37. model.CurrentSub = Subdomain;
  38. Users.Models.User user = UserHelper.GetUser(db, User.Identity.Name);
  39. if (user != null)
  40. {
  41. model.SaveKey = user.UploadSettings.SaveKey;
  42. model.ServerSideEncrypt = user.UploadSettings.ServerSideEncrypt;
  43. }
  44. else
  45. {
  46. model.SaveKey = true;
  47. model.ServerSideEncrypt = true;
  48. }
  49. return View(model);
  50. }
  51. [HttpPost]
  52. [AllowAnonymous]
  53. public ActionResult Upload(string fileType, string fileExt, string iv, int keySize, int blockSize, bool encrypt, bool saveKey, HttpPostedFileWrapper data, string key = null)
  54. {
  55. try
  56. {
  57. if (Config.UploadConfig.UploadEnabled)
  58. {
  59. if (data.ContentLength <= Config.UploadConfig.MaxUploadSize)
  60. {
  61. // convert file to bytes
  62. int contentLength = data.ContentLength;
  63. // Scan the file to detect a virus
  64. if (Config.UploadConfig.VirusScanEnable)
  65. {
  66. // If it was encrypted client side, decrypt it
  67. //if (!encrypt && key != null)
  68. //{
  69. // // If the IV is set, and Key is set, then decrypt it
  70. // if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(iv))
  71. // {
  72. // // Decrypt the data
  73. // scanData = AES.Decrypt(scanData, key, iv);
  74. // }
  75. //}
  76. ClamClient clam = new ClamClient(Config.UploadConfig.ClamServer, Config.UploadConfig.ClamPort);
  77. clam.MaxStreamSize = Config.UploadConfig.MaxUploadSize;
  78. ClamScanResult scanResult = clam.SendAndScanFile(data.InputStream);
  79. switch (scanResult.Result)
  80. {
  81. case ClamScanResults.Clean:
  82. break;
  83. case ClamScanResults.VirusDetected:
  84. return Json(new { error = new { message = string.Format("Virus Detected: {0}. As per our <a href=\"{1}\">Terms of Service</a>, Viruses are not permited.", scanResult.InfectedFiles.First().VirusName, Url.SubRouteUrl("tos", "TOS.Index")) } });
  85. case ClamScanResults.Error:
  86. return Json(new { error = new { message = string.Format("Error scanning the file upload for viruses. {0}", scanResult.RawResult) } });
  87. case ClamScanResults.Unknown:
  88. return Json(new { error = new { message = string.Format("Unknown result while scanning the file upload for viruses. {0}", scanResult.RawResult) } });
  89. }
  90. }
  91. Models.Upload upload = Uploader.SaveFile(db, Config, data.InputStream, fileType, contentLength, encrypt, fileExt, iv, key, saveKey, keySize, blockSize);
  92. if (upload != null)
  93. {
  94. if (User.Identity.IsAuthenticated)
  95. {
  96. Users.Models.User user = UserHelper.GetUser(db, User.Identity.Name);
  97. if (user != null)
  98. {
  99. upload.UserId = user.UserId;
  100. db.Entry(upload).State = EntityState.Modified;
  101. db.SaveChanges();
  102. }
  103. }
  104. return Json(new { result = new { name = upload.Url, url = Url.SubRouteUrl("u", "Upload.Download", new { file = upload.Url }), key = key } }, "text/plain");
  105. }
  106. return Json(new { error = new { message = "Unable to upload file" } });
  107. }
  108. else
  109. {
  110. return Json(new { error = new { message = "File Too Large" } });
  111. }
  112. }
  113. return Json(new { error = new { message = "Uploads are disabled" } });
  114. }
  115. catch (Exception ex)
  116. {
  117. return Json(new { error = new { message = "Exception while uploading file: " + ex.GetFullMessage(true) } });
  118. }
  119. }
  120. // User did not supply key
  121. [HttpGet]
  122. [TrackDownload]
  123. [AllowAnonymous]
  124. public ActionResult Download(string file)
  125. {
  126. if (Config.UploadConfig.DownloadEnabled)
  127. {
  128. ViewBag.Title = "Teknik Download - " + file;
  129. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  130. if (upload != null)
  131. {
  132. upload.Downloads += 1;
  133. db.Entry(upload).State = EntityState.Modified;
  134. db.SaveChanges();
  135. // We don't have the key, so we need to decrypt it client side
  136. if (string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
  137. {
  138. DownloadViewModel model = new DownloadViewModel();
  139. model.FileName = file;
  140. model.ContentType = upload.ContentType;
  141. model.ContentLength = upload.ContentLength;
  142. model.IV = upload.IV;
  143. return View(model);
  144. }
  145. else // We have the key, so that means server side decryption
  146. {
  147. // Are they downloading it by range?
  148. bool byRange = !string.IsNullOrEmpty(Request.ServerVariables["HTTP_RANGE"]);
  149. // Check to see if they have a cache
  150. bool isCached = !string.IsNullOrEmpty(Request.Headers["If-Modified-Since"]);
  151. if (isCached)
  152. {
  153. // The file is cached, let's just 304 this
  154. Response.StatusCode = 304;
  155. Response.StatusDescription = "Not Modified";
  156. Response.AddHeader("Content-Length", "0");
  157. return Content(string.Empty);
  158. }
  159. else
  160. {
  161. string subDir = upload.FileName[0].ToString();
  162. string filePath = Path.Combine(Config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  163. long startByte = 0;
  164. long endByte = upload.ContentLength - 1;
  165. long length = upload.ContentLength;
  166. if (System.IO.File.Exists(filePath))
  167. {
  168. // Read in the file
  169. using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
  170. {
  171. // We accept ranges
  172. Response.AddHeader("Accept-Ranges", "0-" + upload.ContentLength);
  173. // check to see if we need to pass a specified range
  174. if (byRange)
  175. {
  176. long anotherStart = startByte;
  177. long anotherEnd = endByte;
  178. string[] arr_split = Request.ServerVariables["HTTP_RANGE"].Split(new char[] { '=' });
  179. string range = arr_split[1];
  180. // Make sure the client hasn't sent us a multibyte range
  181. if (range.IndexOf(",") > -1)
  182. {
  183. // (?) Shoud this be issued here, or should the first
  184. // range be used? Or should the header be ignored and
  185. // we output the whole content?
  186. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + upload.ContentLength);
  187. throw new HttpException(416, "Requested Range Not Satisfiable");
  188. }
  189. // If the range starts with an '-' we start from the beginning
  190. // If not, we forward the file pointer
  191. // And make sure to get the end byte if spesified
  192. if (range.StartsWith("-"))
  193. {
  194. // The n-number of the last bytes is requested
  195. anotherStart = startByte - Convert.ToInt64(range.Substring(1));
  196. }
  197. else
  198. {
  199. arr_split = range.Split(new char[] { '-' });
  200. anotherStart = Convert.ToInt64(arr_split[0]);
  201. long temp = 0;
  202. anotherEnd = (arr_split.Length > 1 && Int64.TryParse(arr_split[1].ToString(), out temp)) ? Convert.ToInt64(arr_split[1]) : upload.ContentLength;
  203. }
  204. /* Check the range and make sure it's treated according to the specs.
  205. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  206. */
  207. // End bytes can not be larger than $end.
  208. anotherEnd = (anotherEnd > endByte) ? endByte : anotherEnd;
  209. // Validate the requested range and return an error if it's not correct.
  210. if (anotherStart > anotherEnd || anotherStart > upload.ContentLength - 1 || anotherEnd >= upload.ContentLength)
  211. {
  212. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + upload.ContentLength);
  213. throw new HttpException(416, "Requested Range Not Satisfiable");
  214. }
  215. startByte = anotherStart;
  216. endByte = anotherEnd;
  217. length = endByte - startByte + 1; // Calculate new content length
  218. // grab the portion of the data we want
  219. byte[] dataRange = new byte[length];
  220. //Array.Copy(data, startByte, dataRange, 0, length);
  221. //data = dataRange;
  222. // Ranges are response of 206
  223. Response.StatusCode = 206;
  224. }
  225. // Add cache parameters
  226. Response.Cache.SetCacheability(HttpCacheability.Public);
  227. Response.Cache.SetMaxAge(new TimeSpan(365, 0, 0, 0));
  228. Response.Cache.SetLastModified(upload.DateUploaded);
  229. // Notify the client the byte range we'll be outputting
  230. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + upload.ContentLength);
  231. Response.AddHeader("Content-Length", length.ToString());
  232. // Create content disposition
  233. var cd = new System.Net.Mime.ContentDisposition
  234. {
  235. FileName = upload.Url,
  236. Inline = true
  237. };
  238. Response.AppendHeader("Content-Disposition", cd.ToString());
  239. string contentType = upload.ContentType;
  240. // We need to prevent html (make cleaner later)
  241. if (contentType == "text/html")
  242. {
  243. contentType = "text/plain";
  244. }
  245. // Reset file stream to starting position
  246. fs.Seek(0, SeekOrigin.Begin);
  247. Response.BufferOutput = true;
  248. // If the IV is set, and Key is set, then decrypt it before sending
  249. if (!string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
  250. {
  251. byte[] keyBytes = Encoding.UTF8.GetBytes(upload.Key);
  252. byte[] ivBytes = Encoding.UTF8.GetBytes(upload.IV);
  253. IBufferedCipher cipher = AES.CreateCipher(false, keyBytes, ivBytes, "CTR", "NoPadding");
  254. int chunkSize = 1024;
  255. // Make sure the input stream is at the beginning
  256. fs.Seek(0, SeekOrigin.Begin);
  257. int processedBytes = 0;
  258. byte[] buffer = new byte[chunkSize];
  259. do
  260. {
  261. processedBytes = AES.ProcessCipherBlock(cipher, fs, chunkSize, buffer, 0);
  262. if (processedBytes > 0)
  263. {
  264. Response.OutputStream.Write(buffer, 0, processedBytes);
  265. // Clear the buffer
  266. Array.Clear(buffer, 0, chunkSize);
  267. }
  268. }
  269. while (processedBytes > 0);
  270. // Clear the buffer
  271. Array.Clear(buffer, 0, chunkSize);
  272. // Finalize processing of the cipher
  273. processedBytes = AES.FinalizeCipherBlock(cipher, buffer, 0);
  274. if (processedBytes > 0)
  275. {
  276. // We have bytes, lets write them to the output
  277. Response.OutputStream.Write(buffer, 0, processedBytes);
  278. }
  279. HttpContext.ApplicationInstance.CompleteRequest();
  280. return Content("");
  281. }
  282. else
  283. {
  284. // Otherwise just send it
  285. return File(fs, contentType);
  286. }
  287. }
  288. }
  289. }
  290. }
  291. }
  292. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  293. }
  294. return Redirect(Url.SubRouteUrl("error", "Error.Http403"));
  295. }
  296. [HttpPost]
  297. [AllowAnonymous]
  298. public FileResult DownloadData(string file)
  299. {
  300. if (Config.UploadConfig.DownloadEnabled)
  301. {
  302. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  303. if (upload != null)
  304. {
  305. string subDir = upload.FileName[0].ToString();
  306. string filePath = Path.Combine(Config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  307. if (System.IO.File.Exists(filePath))
  308. {
  309. byte[] buffer;
  310. FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  311. try
  312. {
  313. int length = (int)fileStream.Length; // get file length
  314. buffer = new byte[length]; // create buffer
  315. int count; // actual number of bytes read
  316. int sum = 0; // total number of bytes read
  317. // read until Read method returns 0 (end of the stream has been reached)
  318. while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
  319. sum += count; // sum is a buffer offset for next reading
  320. }
  321. finally
  322. {
  323. fileStream.Close();
  324. }
  325. return File(buffer, System.Net.Mime.MediaTypeNames.Application.Octet, file);
  326. }
  327. }
  328. Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  329. return null;
  330. }
  331. Redirect(Url.SubRouteUrl("error", "Error.Http403"));
  332. return null;
  333. }
  334. [HttpGet]
  335. [AllowAnonymous]
  336. public ActionResult Delete(string file, string key)
  337. {
  338. ViewBag.Title = "File Delete - " + file + " - " + Config.Title;
  339. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  340. if (upload != null)
  341. {
  342. DeleteViewModel model = new DeleteViewModel();
  343. model.File = file;
  344. if (!string.IsNullOrEmpty(upload.DeleteKey) && upload.DeleteKey == key)
  345. {
  346. string filePath = upload.FileName;
  347. // Delete from the DB
  348. db.Uploads.Remove(upload);
  349. db.SaveChanges();
  350. // Delete the File
  351. if (System.IO.File.Exists(filePath))
  352. {
  353. System.IO.File.Delete(filePath);
  354. }
  355. model.Deleted = true;
  356. }
  357. else
  358. {
  359. model.Deleted = false;
  360. }
  361. return View(model);
  362. }
  363. return RedirectToRoute("Error.Http404");
  364. }
  365. [HttpPost]
  366. [AllowAnonymous]
  367. public ActionResult GenerateDeleteKey(string file)
  368. {
  369. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  370. if (upload != null)
  371. {
  372. string delKey = StringHelper.RandomString(Config.UploadConfig.DeleteKeyLength);
  373. upload.DeleteKey = delKey;
  374. db.Entry(upload).State = EntityState.Modified;
  375. db.SaveChanges();
  376. return Json(new { result = Url.SubRouteUrl("upload", "Upload.Delete", new { file = file, key = delKey }) });
  377. }
  378. return Json(new { error = "Invalid URL" });
  379. }
  380. [HttpPost]
  381. [AllowAnonymous]
  382. public ActionResult SaveFileKey(string file, string key)
  383. {
  384. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  385. if (upload != null)
  386. {
  387. upload.Key = key;
  388. db.Entry(upload).State = EntityState.Modified;
  389. db.SaveChanges();
  390. return Json(new { result = Url.SubRouteUrl("upload", "Upload.Download", new { file = file }) });
  391. }
  392. return Json(new { error = "Invalid URL" });
  393. }
  394. [HttpPost]
  395. [AllowAnonymous]
  396. public ActionResult RemoveFileKey(string file, string key)
  397. {
  398. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  399. if (upload != null)
  400. {
  401. if (upload.Key == key)
  402. {
  403. upload.Key = null;
  404. db.Entry(upload).State = EntityState.Modified;
  405. db.SaveChanges();
  406. return Json(new { result = Url.SubRouteUrl("upload", "Upload.Download", new { file = file }) });
  407. }
  408. return Json(new { error = "Non-Matching Key" });
  409. }
  410. return Json(new { error = "Invalid URL" });
  411. }
  412. }
  413. }