Пример #1
0
        /// <summary>
        /// Scans a local file, this is not used since the file has to be localy available on the server
        /// </summary>
        /// <param name="filePath">Local path to the file to be scanned</param>
        /// <param name="fileGUID">The Results GUID used to index for scan result</param>
        /// <returns></returns>

        private static async Task ScanFile(string filePath, Guid fileGUID)
        {
            try
            {
                ClamClient clam = new ClamClient(ClamAVServer, ClamAVPort);

                var scanResult = await clam.ScanFileOnServerAsync(filePath);  //any file you would like!

                ScanResults result = ScanHistory.Find(x => x.FileGUID == fileGUID);

                result.ScanResult = scanResult;
            }
            catch (Exception exception)
            {
                ScanResults result = ScanHistory.Find(x => x.FileGUID == fileGUID);

                if (result == null)
                {
                    result = new ScanResults(fileGUID, exception.Message);
                }
                else
                {
                    result.ScanResult = new ClamScanResult(exception.Message);
                }
            }
        }
Пример #2
0
        public string scanFile(string filepath)
        {
            string result = "Error!";

            try
            {
                Task.Run(async() =>
                {
                    var clam       = new ClamClient("localhost", 3310);
                    var scanResult = await clam.ScanFileOnServerAsync(filepath);


                    switch (scanResult.Result)
                    {
                    case ClamScanResults.Clean:
                        result = "Clean";
                        break;

                    case ClamScanResults.VirusDetected:
                        result = "Malicious file detected, " + scanResult.InfectedFiles.First().VirusName;
                        break;

                    case ClamScanResults.Error:
                        result = "Error!";
                        break;
                    }
                }).Wait();
            }
            catch (Exception e)
            {
                return(result);
            }
            return(result);
        }
Пример #3
0
    private static async Task ScanAndUploadDocument(ClamClient clam, string filePath)
    {
        //The current directory is C Drive and a text file in it.
        var scanResult = await clam.ScanFileOnServerAsync(@filePath);  //any file you would like!

        switch (scanResult.Result)
        {
        case ClamScanResults.Clean:
            Console.WriteLine("The file " + filePath + " is clean!");
            break;

        case ClamScanResults.VirusDetected:
            Console.WriteLine("Virus Found!");
            Console.WriteLine("Virus name: {0}", scanResult.InfectedFiles.First().VirusName);
            break;

        case ClamScanResults.Error:
            Console.WriteLine("Woah an error occured! Error: {0}", scanResult.RawResult);
            break;
        }
        //if condition for checking scan success.

        if (scanResult.Result == ClamScanResults.Clean)
        {
            // Retrieve storage account from connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference("container1");

            //string dateTime = DateTime.Now.ToString("MMM ddd d HH:mm yyyy");
            string dateTime = DateTime.Now.ToString("MMddHHmmss");


            string         fileName  = "file" + dateTime;
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);


            using (var fileStream = System.IO.File.OpenRead(@filePath))
            {
                blockBlob.UploadFromStream(fileStream);
            }
        }
        else if (scanResult.Result == ClamScanResults.VirusDetected)
        {
            Console.WriteLine("Virus Found! Cannot upload the document.");
            Console.WriteLine("Virus name: {0}", scanResult.InfectedFiles.First().VirusName);
        }
        else
        {
            Console.WriteLine("File not found. Select appropriate file");
        }
    }
Пример #4
0
        private async Task ExecuteOnceAsync(CancellationToken cancellationToken)
        {
            var taskFactory = new TaskFactory(TaskScheduler.Current);
            await taskFactory.StartNew(
                async() =>
            {
                try
                {
                    _logger.LogInformation("Starting daemon: ");

                    try
                    {
                        var clam       = new ClamClient("10.0.0.40", 3310);
                        var pingResult = await clam.PingAsync();

                        if (!pingResult)
                        {
                            Console.WriteLine("test failed. Exiting.");
                            _logger.LogInformation("test failed. Exiting.");
                        }

                        Console.WriteLine("connected to clam.");
                        _logger.LogInformation("connected to clam.");
                        var scanResult = await clam.ScanFileOnServerAsync("/home/tes-mvc/Final_Team.txt");      //any file you would like!

                        switch (scanResult.Result)
                        {
                        case ClamScanResults.Clean:
                            Console.WriteLine("The file is clean!");
                            _logger.LogInformation("The file is clean!");
                            break;

                        case ClamScanResults.VirusDetected:
                            Console.WriteLine("Virus Found!");
                            _logger.LogInformation("Virus Found!");
                            break;

                        case ClamScanResults.Error:
                            Console.WriteLine("Woah an error occured! Error: {0}", scanResult.RawResult);
                            _logger.LogInformation("Woah an error occured! Error: {0}", scanResult.RawResult);
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("not connected.", e);
                    }
                }
                catch (Exception ex)
                {
                }
            },
                cancellationToken);
        }
Пример #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            ClamClient client = new ClamClient(SERVER_URL, SERVER_PORT);
            bool       ping   = Task.Run(() => client.PingAsync()).Result;

            Console.WriteLine($"Ping Successful? {ping}");

            ClamScanResult result = Task.Run(() => client.ScanFileOnServerAsync(Path.Combine(Environment.CurrentDirectory, fileName))).Result;

            Console.WriteLine($"Scan Successful? {result.RawResult}");
        }
Пример #6
0
        public async Task <Result> Scan([FromRoute] String name)
        {
            try
            {
                name = HttpUtility.UrlDecode(name);
                var clam     = new ClamClient("localhost", 3310);
                var fileInfo = new System.IO.FileInfo(name);
                if (!fileInfo.Exists)
                {
                    return(new Result()
                    {
                        FileName = name, IsCompleted = false
                    });
                }
                var sw = Stopwatch.StartNew();

                var scanResult = await clam.ScanFileOnServerAsync(name);  //any file you would like!

                long ticks = sw.ElapsedTicks;
                var  time  = sw.ElapsedMilliseconds;

                switch (scanResult.Result)
                {
                case ClamScanResults.Clean:
                    return(new Result()
                    {
                        FileName = name, IsCompleted = true, IsClean = true, TimeTakenInMs = time, FileSize = fileInfo.Length
                    });

                case ClamScanResults.VirusDetected:
                    return(new Result()
                    {
                        FileName = name, IsCompleted = true, IsClean = false, TimeTakenInMs = time, FileSize = fileInfo.Length
                    });

                case ClamScanResults.Error:
                default:
                    return(new Result()
                    {
                        FileName = name, IsCompleted = false, FileSize = fileInfo.Length
                    });
                }
            }
            catch (Exception e)
            {
                return(new Result()
                {
                    FileName = name, IsCompleted = false
                });
            }
        }
Пример #7
0
    static async Task Main(string[] args)
    {
        var clam       = new ClamClient("localhost", 3310);
        var scanResult = await clam.ScanFileOnServerAsync("C:\\test.txt");  //any file you would like!

        switch (scanResult.Result)
        {
        case ClamScanResults.Clean:
            Console.WriteLine("The file is clean!");
            break;

        case ClamScanResults.VirusDetected:
            Console.WriteLine("Virus Found!");
            Console.WriteLine("Virus name: {0}", scanResult.InfectedFiles.First().VirusName);
            break;

        case ClamScanResults.Error:
            Console.WriteLine("Woah an error occured! Error: {0}", scanResult.RawResult);
            break;
        }
    }
Пример #8
0
        public async Task <IEnumerable <string> > Get()
        {
            try
            {
                var clam       = new ClamClient("localhost", 3310);
                var pingResult = await clam.PingAsync();

                if (!pingResult)
                {
                    Console.WriteLine("test failed. Exiting.");
                    return(null);
                }

                Console.WriteLine("connected.");
                var scanResult = await clam.ScanFileOnServerAsync("C:\\Users\\Sujit.Kadam\\Documents\\Final Team.txt");  //any file you would like!

                switch (scanResult.Result)
                {
                case ClamScanResults.Clean:
                    Console.WriteLine("The file is clean!");
                    break;

                case ClamScanResults.VirusDetected:
                    Console.WriteLine("Virus Found!");
                    Console.WriteLine("Virus name: {0}", scanResult.InfectedFiles.First().VirusName);
                    break;

                case ClamScanResults.Error:
                    Console.WriteLine("Woah an error occured! Error: {0}", scanResult.RawResult);
                    break;
                }

                return(new string[] { "Status", "Success" });
            }
            catch (Exception e)
            {
                Console.WriteLine("not connected.");
                return(new string[] { "Status", "Failed" });
            }
        }
Пример #9
0
    static async Task Main(string[] args)
    {
        Console.WriteLine("nClam Test Application");
        Console.WriteLine();

        Console.Write("\t• Testing connectivity: ");

        var clam       = new ClamClient("localhost", 3310);
        var pingResult = await clam.PingAsync();

        if (!pingResult)
        {
            Console.WriteLine("test failed. Exiting.");
            return;
        }

        Console.WriteLine("connected.");

        Console.Write("\t• Scanning file: ");
        var scanResult = await clam.ScanFileOnServerAsync("C:\\test.txt");  //any file you would like!

        switch (scanResult.Result)
        {
        case ClamScanResults.Clean:
            Console.WriteLine("The file is clean!");
            break;

        case ClamScanResults.VirusDetected:
            Console.WriteLine("Virus Found!");
            Console.WriteLine("Virus name: {0}", scanResult.InfectedFiles.First().VirusName);
            break;

        case ClamScanResults.Error:
            Console.WriteLine("Woah an error occured! Error: {0}", scanResult.RawResult);
            break;
        }
        Console.ReadLine();
    }
Пример #10
0
        public override void Execute()
        {
            var eventModel = CurrentActionProperties(TargetCollection, this.GetType().Name);

            OnTrigger(new PreingestEventArgs {
                Description = String.Format("Start scanning for virus in '{0}'.", TargetFolder), Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Started, PreingestAction = eventModel
            });

            var  anyMessages = new List <String>();
            var  scanResults = new List <VirusScanItem>();
            bool isSucces    = false;

            try
            {
                string[] files = Directory.GetFiles(TargetFolder, "*.*", SearchOption.AllDirectories);
                eventModel.Summary.Processed = files.Count();

                int port = 3310;
                Int32.TryParse(ApplicationSettings.ClamServerPort, out port);
                string server = ApplicationSettings.ClamServerNameOrIp;

                var clam = new ClamClient(server, port);

                foreach (var fullFilename in files)
                {
                    this.Logger.LogInformation("Scanning file '{0}'", fullFilename);

                    var scanResult = clam.ScanFileOnServerAsync(fullFilename).Result;

                    string message = string.Empty;
                    switch (scanResult.Result)
                    {
                    case ClamScanResults.Clean:
                        message = String.Format("Bestand '{0}' is schoon.", fullFilename);
                        break;

                    case ClamScanResults.VirusDetected:
                        message = String.Format("Een virus ({0}) is gevonden in bestand {1}.", scanResult.InfectedFiles.First().VirusName, fullFilename);
                        break;

                    case ClamScanResults.Error:
                        message = String.Format("Er is een fout opgetreden in '{0}'. Fout : {1}", fullFilename, scanResult.RawResult);
                        break;

                    case ClamScanResults.Unknown:
                    default:
                        message = String.Format("Er is een onbekende fout opgetreden in '{0}'. {1}", fullFilename, scanResult.RawResult);
                        break;
                    }

                    scanResults.Add(new VirusScanItem {
                        IsClean = (scanResult.Result == ClamScanResults.Clean), Description = message, Filename = fullFilename
                    });
                    OnTrigger(new PreingestEventArgs {
                        Description = String.Format("Scan file '{0}'.", fullFilename), Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Executing, PreingestAction = eventModel
                    });

                    this.Logger.LogInformation("Scan virus result: '{0}'", message);
                }

                eventModel.Summary.Accepted = scanResults.Where(item => item.IsClean).Count();
                eventModel.Summary.Rejected = scanResults.Where(item => !item.IsClean).Count();

                eventModel.ActionData = scanResults.ToArray();

                if (eventModel.Summary.Rejected > 0)
                {
                    eventModel.ActionResult.ResultValue = PreingestActionResults.Error;
                }
                else
                {
                    eventModel.ActionResult.ResultValue = PreingestActionResults.Success;
                }

                isSucces = true;
            }
            catch (Exception e)
            {
                isSucces = false;
                Logger.LogError(e, "An exception occured in scan virus!");
                anyMessages.Clear();
                anyMessages.Add("An exception occured in scan virus!");
                anyMessages.Add(e.Message);
                anyMessages.Add(e.StackTrace);

                eventModel.Summary.Processed = -1;
                eventModel.Summary.Accepted  = -1;
                eventModel.Summary.Rejected  = eventModel.Summary.Processed;

                eventModel.ActionResult.ResultValue = PreingestActionResults.Failed;
                eventModel.Properties.Messages      = anyMessages.ToArray();

                OnTrigger(new PreingestEventArgs {
                    Description = "An exception occured in scan virus!", Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Failed, PreingestAction = eventModel
                });
            }
            finally
            {
                if (isSucces)
                {
                    OnTrigger(new PreingestEventArgs {
                        Description = "Scanning in folder for virus is done.", Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Completed, PreingestAction = eventModel
                    });
                }
            }
        }