Scan Uploaded File using Sophos Labs Intelix in c# - c#

I am new to SophosLabs Intelix. I am trying to build a sample in my ASP .Net Application(webforms/MVC) in which I want to run an Antivirus Scan on the uploaded file by the User. If the Uploaded file is clean I want to upload it to the server else I want to cancel the operation. I want to specifically use SophosLabs Intelix for the functionality. It would be great if someone can guide me regarding this functionality. A code sample in C# would be appreciated a lot.
Thanks in advance for your help.
Sample:
if(file.HasFile)
{
//run an antivirus scan
//result
if(result == NoThreat){
//Uploaded Successfully
}
else{
//File contains a virus. Upload failed!
}
}
else{
//Please select a file to upload!
}

I suggest to start with the implementation of OAUTH 2 authentication request. You can find some ideas here: How do I get an OAuth 2.0 authentication token in C#
As soon as you have the access_token you can use if for /reports/?sha256=... query.
It may return the report immediately.
If it does not return any data (404) this request was free and you can POST the file to the root endpoint "/" for analysis.
It can take a few seconds/minutes, during that you should poll the report from /reports/{job_id} endpoint as long as you get it.
If you cannot wait minutes for decision data, you may use the File Hash Lookup API as well that returns immediately.
It may give a reputationScore between 30..69 so cannot decide how dangerous the file is, but in this case you can still perform a static or dynamic analysis on it.

Related

How To: Open a Word document from .NET Core web application, edit, and save back to server?

I am looking for modern examples on how to create a SharePoint-like integration with Microsoft Word but in an ASP/C# (.NET Core) web application. In other words, my goal is to click on a Word document from my webpage (file stored on my on-premise server), open in Word (desktop application), makes changes, and save back to the server. When I say SharePoint-like integration, I mean, opening and saving are handled automatically without the user having to be bothered by saving the file locally and manually uploading it back to the server.
I have found others asking the same question but with no concrete response and most were nearly a decade old. Here are some of the articles I found but of no help:
C# and Office integration
How can I open, edit and save a word document with asp.net
https://social.msdn.microsoft.com/Forums/office/en-US/e1928f0b-6922-4f23-a1f9-09835e39f7da/how-to-opensave-word-documents-fromto-in-aspnet-webapi-using-ms-word-application
It looks like the Office Add-in platform (https://learn.microsoft.com/en-us/office/dev/add-ins/overview/office-add-ins#components-of-an-office-add-in) may be of use, but I don't necessarily want a Word add-in added to the ribbon. So not sure this is really what I want.
WebDAV may be what I need as discussed here (https://www.webdavsystem.com/ajaxfilebrowser/programming/opening-docs/open_save_docs_directly_to_server/) but not sure... and the article talks about Office 2007 so seems kind of dated.
Any help in guiding me to example, article, or forum that discusses current approaches to tackle this would greatly be appreciated.
A little more information: clients would be using Edge or Chrome browsers, on Windows 10 boxes, with Office 2016 (or later).
This question is very broad. There looks to be several parts.
A plugin that can be configured to communicate with a webservice
An Api that consumes data from the plugin
The plugin should be able to save automatically
Here is some related documentation though some are specific to Excel, though may be able to be repurposed for Word
Also note that Office plugin development is JavaScript and/or TypeScript.
https://learn.microsoft.com/en-us/office/dev/add-ins/excel/custom-functions-web-reqs
https://learn.microsoft.com/en-us/office/dev/add-ins/excel/custom-functions-batching
https://learn.microsoft.com/en-us/javascript/api/word/word.document?view=word-js-preview#save__
There is not any code here so even writing a specific function would be making several assumptions, but from the documentation (with a couple add ins):
// Run a batch operation against the Word object model.
Word.run(function (context) {
// Create a proxy object for the document.
var thisDocument = context.document;
// Queue a command to load the document save state (on the saved property).
context.load(thisDocument, 'saved');
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
if (thisDocument.saved === false) {
// Queue a command to save this document.
thisDocument.save();
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
//
// CODE to send your data to your server(s) via
// API (post request, or something similar)
//
console.log('Saved the document');
});
} else {
console.log('The document has not changed since the last save.');
}
});
})
.catch(function (error) {
console.log("Error: " + JSON.stringify(error));
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});

How to rollback S3 document upload?

I make a request to a REST API (let it be API 1) which internally calls another 2 APIs (APIs 2 & 3) synchronously.
API 1 = REST API
API 2 = Pre-signed url to upload a file into S3
API 3 = A DB update (SQL Server)
API 3 i.e., the DB update will be made only if the file is successfully uploaded (API 2) into S3.
In case the DB update (API 3) is failed, the changes API 2 did should be rolled back i.e., the uploaded file should be deleted in S3.
Please advise how to handle this scenario. Any out-of-the-box solution is welcome.
S3 services are not transactional. Basically all the rest apis are not transactional so all the operations are atomic:
What are atomic operations for newbies?
What this means is that you can't rollback the operation if it has succeeded.
It would be easy to say that it's ok. Once local db fails I can issue a delete call on s3 to delete my file. But what happens if this fails too?
Another way would be to first write to your database and then post the file. Again if the file upload fails you can rollback the db command. That is safer, but still... what happens when you send the request but you get a timeout? The file might be on the server but you just won't know.
Enter the world of eventual consistency.
While there are ways to mitigate the issue with retries (check polly library for test retries) what you can do is store the action.
You want to upload the file. Add it to a queue and run the task. Mark the task as failed. Retry as many times as you want and mark the failure reasons.
Here comes manual interventions. When all else fails, someone should intervene with some resolution strategy.
If you need to "undo" an upload to any file system (S3 is a file system) you do it like this.
Upload the new file with some temporary unique file name (a guid will do fine).
To "commit" the upload, remove the file you're replacing and rename the one you just uploaded so it has the same name as the old one.
To "roll back" the upload, remove the temp file.
An even better way, if your application allows it, is to give each version of the file a different name. Then you just upload each new one with its own name, and clean up by deleting the old ones.
In your particular scenario, it might make sense to do your database update operation first, and the upload second, if that won't open you up to a nasty race condition.

ASP .Net MVC Download Error and Require to Recycle IIS Application Pool

I currently maintain a nearly 3 years old ASP .Net MVC website, the application is running above IIS (now in IIS 7) and using ASP .Net 4 Framework. It used by client almost everyday and had a lot of upload-download file transaction. It also use ELMAH as Unhandled Exception Handling. The application running well until a few past month, there are a lot of report from user that they cannot do download the file, but without any error message, the download process just not doing anything while there is also no log in Browser Console. After doing several checking, all menu that have download function are using http response
Response.Clear();
Response.Cache.SetCacheability(HttpCacheability.Private);
Response.Expires = -1;
Response.Buffer = true;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Length", Convert.ToString(file_in_bytes.Length));
Response.AddHeader("Content-Disposition"
, string.Format("{0};FileName=\"{1}\"", "attachment", fileName));
Response.AddHeader("Set-Cookie", "fileDownload=true; path=/");
Response.BinaryWrite(hasil);
Response.End();
And nothing seems wrong (there are no Compile or Runtime Error in Development Server). We've also checked Elmah's log, but there no related error message appear in there. And This problem is temporarily disappear after our Server Management Team do Recycling the Application Pool in IIS.
This Web is also share Application Pool with another web, and when that error occurred, both application are affected, only the download function that affected, the other function like data retrieval from database, insert/edit/delete data is working fine.
I also checked the Web Server Event Viewer but there is nothing error in there. The very odd thing for us is that this error temporary disappear after we Recycling the Application Pool and after several days or weeks or months the error suddenly appear again.
Is there any log that we've missed to trace? or perhaps there is wrong with the Download code? And why its temporarily fixed after Recycling Application Pool?
Another Note : The data that need to be download by user is at average 500kb to 2MB in zip format contains several PDF files
Update : After few more hour investigating, I found that this web application using different method to Download, some are using the Http.Response like above code, and some are use FileContentResult as return value. But both using jquery.FileDownload in client-side. I also found this method in several Controller that has Download File method in this app,
private void CheckAndHandleFileResult(ActionExecutedContext filterContext)
{
var httpContext = filterContext.HttpContext;
var response = httpContext.Response;
if (filterContext.Result is FileContentResult)
{
//jquery.fileDownload uses this cookie to determine that
//a file download has completed successfully
response.AppendCookie(new HttpCookie(CookieName, "true")
{ Path = CookiePath });
}
else
{
//ensure that the cookie is removed in case someone did
//a file download without using jquery.fileDownload
if (httpContext.Request.Cookies[CookieName] != null)
{
response.AppendCookie(new HttpCookie(CookieName, "true")
{ Expires = DateTime.Now.AddYears(-1), Path = CookiePath });
}
}
}
Actually I'm not really sure is that method related to this error or not, but it is called in a method that override System.Web.MVC.Controller OnActionExecuted, and it contain the line off adding Cookie for file download if using FileContentResult or delete Cookie if is not using FileContentResult and file Download Cookie is exists. It is Possible if Cookie is Accidentally not deleted / cleared after it created? And because the download method is frequently called by nearly 100 user everyday, it is possible that the Cookie is pile up and cause IIS Worker Process Crash?
I've also checked some references about Cookie and its relation to IIS Session State (My Apps using In-Proc State). Am I Close? Or did I miss something?
Is there a reason why Response.Buffer is set to true? When buffering is enabled, the response is sent only after all processing is completed. Can you disable it by setting to false and see if this works? This could be the reason for having to recycle the app pool. You can also check if you are facing these issues - Help link

Get last modified date of a remote file

I have an app with which at startup it downloads a file from a remote location (through the net) and parses it's contents.
I am trying to speed up the process of startup as the bigger the file gets the slower the app starts.
As a way to speed up the process I thought of getting the last modified date of the file and if it is newer from the file on the user's pc then and only then download it.
I have found many ways to do it online but none of them are in C# (for windows store apps). Does anybody here know of a way of doing this without the need to download the file? If I am to download the file then the process is sped up at all.
My C# code for downloading the file currently is this
const string fileLocation = "link to dropbox";
var uri = new Uri(fileLocation);
var downloader = new BackgroundDownloader();
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("feedlist.txt",CreationCollisionOption.ReplaceExisting);
DownloadOperation download = downloader.CreateDownload(uri, file);
await download.StartAsync();
If it helps the file is stored in dropbox but if any of you guys have a suggestion for another free file hosting service I am open to suggestions
Generally, you can check the file time by sending HEAD request and parsing/looking HTTP header response for a Last-Modified filed. The remote server should support it and DropBox does not support this feature for direct links (only via API). But DropBox have another feature, the headers have the etag field. You should store it and check in the next request. If it changed - the file has been changed too. You can use this tool to check the remote file headers.

Google Drive Sdk .net upload and download [duplicate]

My requirement is to upload a single file which will be selected by the user during runtime to Google drive. I am getting email id and password from user. How to do it? If i any other requirement get from users? any feasible solution is there?
You can use the Google Drive SDK/API, it's fairly simple stuff if you read through the documentation,
https://developers.google.com/drive/
https://developers.google.com/drive/manage-uploads
There's a .NET API available for download, although it's in beta I've used it without problem.
https://developers.google.com/drive/downloads
DocumentsService myService = new DocumentsService("application name");
myService.setUserCredentials("email", "password");
DocumentEntry newEntrys = myService.UploadDocument("pdf path", #"upload file name");
But I have take exception
Execution of request failed: https://docs.google.com/feeds/default/private/full?convert=false

Categories