Exemplo n.º 1
0
        public async Task <IActionResult> UploadFiles(List <IFormFile> files)
        {
            var log = new List <ScanResult>();

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    var clam = new ClamClient("clamav-server", 3310);
                    var ping = await clam.PingAsync();

                    var result = await clam.SendAndScanFileAsync(formFile.OpenReadStream());

                    log.Add(new ScanResult()
                    {
                        FileName  = formFile.FileName,
                        Result    = result.Result.ToString(),
                        Message   = result.InfectedFiles?.FirstOrDefault()?.VirusName,
                        RawResult = result.RawResult
                    });
                }
            }

            var model = new UploadFilesViewModel();

            model.Results = log;

            return(View(model));
        }
Exemplo n.º 2
0
        private async Task <ScanResultModel> SendAsync(Func <Task <ClamScanResult> > calback)
        {
            if (!await _clamClient.PingAsync())
            {
                throw new ScanFileException($"Connection refuse from {_host}:{_port}");
            }

            return(MapScanResult(await calback()));
        }
Exemplo n.º 3
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);
        }
Exemplo n.º 4
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}");
        }
Exemplo n.º 5
0
        /// <summary>
        /// Verify that ClamAV is running
        /// </summary>
        /// <returns></returns>
        public static async Task Verify()
        {
            ClamClient clam = new ClamClient(ClamAVServer, ClamAVPort);

            bool result = await clam.PingAsync();

            if (result)
            {
                ClamAVStatus = "Clam AV Running";
            }
            else
            {
                ClamAVStatus = "Failed to Communicate with Clam AV";
            }
        }
Exemplo n.º 6
0
        public void Initialize(List <SignatureElement> elements)
        {
            logger.Debug("Initializing {0} detector", this.Name);
            try
            {
                Task <bool> pingSuccess = clam.PingAsync();
                pingSuccess.Wait();
                if (pingSuccess.Result == false)
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                logger.Warn(ex, "ClamAV server not contactable; the detector will not be used.");
                return;
            }

            logger.Info("Successfully connected to ClamAV server");
            this.Status = DetectorStatus.INITIALIZED;
        }
Exemplo n.º 7
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" });
            }
        }
Exemplo n.º 8
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();
    }
Exemplo n.º 9
0
        public async Task <IActionResult> UploadFiles(List <IFormFile> files)
        {
            var log = new List <ScanResult>();

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    var extension = formFile.FileName.Contains('.')
                        ? formFile.FileName.Substring(formFile.FileName.LastIndexOf('.'), formFile.FileName.Length - formFile.FileName.LastIndexOf('.'))
                        : string.Empty;
                    var file = new File
                    {
                        Name        = $"{Guid.NewGuid()}{extension}",
                        Alias       = formFile.FileName,
                        Region      = "us-east-1",
                        Bucket      = BUCKET_NAME,
                        ContentType = formFile.ContentType,
                        Size        = formFile.Length,
                        Uploaded    = DateTime.UtcNow,
                    };
                    var ping = await _clam.PingAsync();

                    if (ping)
                    {
                        _logger.LogInformation("Successfully pinged the ClamAV server.");
                        var result = await _clam.SendAndScanFileAsync(formFile.OpenReadStream());

                        file.ScanResult = result.Result.ToString();
                        file.Infected   = result.Result == ClamScanResults.VirusDetected;
                        file.Scanned    = DateTime.UtcNow;
                        if (result.InfectedFiles != null)
                        {
                            foreach (var infectedFile in result.InfectedFiles)
                            {
                                file.Viruses.Add(new Virus
                                {
                                    Name = infectedFile.VirusName
                                });
                            }
                        }
                        var metaData = new Dictionary <string, string>
                        {
                            { "av-status", result.Result.ToString() },
                            { "av-timestamp", DateTime.UtcNow.ToString() },
                            { "alias", file.Alias }
                        };

                        try
                        {
                            var found = await _minio.BucketExistsAsync(BUCKET_NAME);

                            if (!found)
                            {
                                await _minio.MakeBucketAsync(BUCKET_NAME);
                            }
                            await _minio.PutObjectAsync(BUCKET_NAME,
                                                        file.Name,
                                                        formFile.OpenReadStream(),
                                                        formFile.Length,
                                                        formFile.ContentType,
                                                        metaData);

                            await _context.Files.AddAsync(file);

                            await _context.SaveChangesAsync();
                        }
                        catch (MinioException e)
                        {
                            _logger.LogError($"File Upload Error: {e.Message}");
                        }


                        var scanResult = new ScanResult()
                        {
                            FileName  = formFile.FileName,
                            Result    = result.Result.ToString(),
                            Message   = result.InfectedFiles?.FirstOrDefault()?.VirusName,
                            RawResult = result.RawResult
                        };
                        log.Add(scanResult);
                    }
                    else
                    {
                        _logger.LogWarning("Wasn't able to connect to the ClamAV server.");
                    }
                }
            }

            var model = new UploadFilesViewModel
            {
                Results = log
            };

            return(View("UploadResults", model));
        }
Exemplo n.º 10
0
        public static async Task Run([BlobTrigger("staging/{name}")] Stream blob, string name, Uri uri,
                                     BlobProperties properties, IDictionary <string, string> metadata, TraceWriter log)
        {
            try
            {
                var clam        = new ClamClient("localhost", 3310);
                var clamVersion = await clam.GetVersionAsync();

                //Make sure we can connect to the ClamAV Server
                var pingResult = await clam.PingAsync();

                if (!pingResult)
                {
                    throw new ApplicationException(
                              "The client failed to connect to the ClamAV Server.  Please check to see if the server is running and accessible on the configured port.");
                }

                //Dont exceed this value.  ClamAV server can be increased to 4GB, but you must have the resources available.
                var maxStreamSize = clam.MaxStreamSize;
                if (blob.Length > maxStreamSize)
                {
                    log.Info($"Blob {name} is too large to be scanned in memory.  Moving to deadletter container");
                    throw new InsufficientMemoryException(
                              $"Blob {name} is too large to be scanned in memory.  Moving to deadletter container");
                }

                //We are going to limit ourselves to block blobs, append blobs, and unspecified blobs.
                var cloudBlob = new CloudBlob(uri);
                if (cloudBlob.BlobType == BlobType.PageBlob)
                {
                    throw new ApplicationException(
                              $"Blob {cloudBlob.Name} has an unsupported type. BlobType = {cloudBlob.BlobType.ToString()}");
                }

                var scanResult = await clam.SendAndScanFileAsync(blob);

                switch (scanResult.Result)
                {
                case ClamScanResults.Clean:
                    //The blob is clean.  Move to production
                    log.Info($"Blob {name}. ScannResult = Clean, ClamVersion = {0}", clamVersion);
                    break;

                case ClamScanResults.VirusDetected:
                    //Bad blob.  Move to quarantine.
                    log.Warning($"Blob {name} has a virus! Name = {0}", scanResult.InfectedFiles.First().VirusName);
                    break;

                case ClamScanResults.Unknown:
                    //Unknown.  Moving to deadletter
                    log.Warning($"Blob {name} scan results unknown! Name = {0}",
                                scanResult.InfectedFiles.First().VirusName);
                    break;

                case ClamScanResults.Error:
                    //Unknown.  Moving to deadletter
                    log.Warning($"Blob {name} has a virus! Name = {0}", scanResult.InfectedFiles.First().VirusName);
                    break;
                }

                log.Info($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {blob.Length} Bytes");
            }
            catch (SocketException ex)
            {
                log.Error(ex.Message, ex);
            }
            catch (InsufficientMemoryException ex)
            {
                log.Error(ex.Message, ex);
                //Todo: Move to deadletter
            }
            catch (ApplicationException ex)
            {
                log.Error(ex.Message, ex);
            }
            catch (Exception ex)
            {
            }
        }