The next generation of the Teknik Services. Written in ASP.NET. Fork for blog tags.
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 20KB

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