예제 #1
0
파일: Scanner.cs 프로젝트: 3583Bytes/RestAV
        /// <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
파일: Program.cs 프로젝트: scmccart/nClam
        static void Main(string[] args)
        {
            if(args == null || args.Length != 1)
            {
                Console.WriteLine("Invalid arguments.  Usage: nClam.ConsoleTest [FileName]");
                return;
            }

            var fileName = args[0];
            var client = new ClamClient("localhost", 3310);
            Console.WriteLine("GetVersion(): {0}", client.GetVersion());
            Console.WriteLine("GetPing(): {0}", client.Ping());
            Console.WriteLine("ScanFileOnServer(): {0}", client.ScanFileOnServer(fileName));
            Console.WriteLine("ScanFileOnServerMultithreaded(): {0}", client.ScanFileOnServerMultithreaded(fileName));

            if (!IsFolder(fileName))
            {
                try
                {
                    Console.WriteLine("SendAndScanFile(string): {0}", client.SendAndScanFile(fileName));
                    Console.WriteLine("SendAndScanFile(byte[]): {0}", client.SendAndScanFile(File.ReadAllBytes(fileName)));
                }
                catch (MaxStreamSizeExceededException msee)
                {
                    Console.WriteLine(msee.Message);
                }
            }
            else
            {
                Console.WriteLine("SendAndScanFile(): Not run because argument is a folder, not a file.");
            }
            Console.WriteLine("Finished, Press <enter> to quit.");
            Console.ReadLine();
        }
예제 #3
0
        private async void scantest()
        {
            var clam = new ClamClient("13.76.89.213", 3310);
            //var scanResult = await clam.ScanFileOnServerAsync("C:\\Users\\Desmond\\Downloads\\TeamViewer_Setup.exe");  //any file you would like!
            var scanResult = await clam.SendAndScanFileAsync("C:\\Users\\Desmond\\Downloads\\TeamViewer_Setup.exe");

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

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

            case ClamScanResults.Error:
                Console.WriteLine("Woah an error occured! Error: {0}", scanResult.RawResult);
                MessageBox.Show("Woah an error occured! Error: {0}", scanResult.RawResult);
                break;
            }
        }
        /// <inheritdoc cref="IFileManager.ScanFileAsync(byte[])" />
        public async Task <bool> ScanFileAsync(byte[] fileBytes)
        {
            ClamAV clamAvSettings = _appSettings.ClamAV;

            if (!clamAvSettings.Enable)
            {
                return(true);
            }
            else if (!string.IsNullOrEmpty(clamAvSettings.Host))
            {
                var clamClient = new ClamClient(clamAvSettings.Host, clamAvSettings.Port);

                var result = await clamClient.SendAndScanFileAsync(fileBytes);

                if (result.Result == ClamScanResults.Clean)
                {
                    return(true);
                }
                else
                {
                    string message = result.Result switch
                    {
                        ClamScanResults.VirusDetected => "Virus detected",
                        ClamScanResults.Error => "Error in the file",
                        ClamScanResults.Unknown => "Unknown file",
                        _ => "No case available"
                    };

                    _logger.LogWarning(message);
                }
            }

            return(false);
        }
예제 #5
0
        public ActionResult <string> Get()
        {
            try
            {
                ClamClient clam = new ClamClient("localhost", 3310);
                //string fileName1 = "C:\\Users\\ColtonHester\\Downloads\\eicar.com.txt";
                //string fileName2 = "C:\\Users\\ColtonHester\\Pictures\\AssurantTest\\Test.pdf";
                //string fileName1 = "C:\\Users\\ColtonHester\\Downloads\\nihongo_grammar_guide.pdf";
                string fileName1 = "C:\\Users\\ColtonHester\\Downloads\\1126072019 Council Meeting Package_Externals.pdf";
                string fileName2 = "C:\\Users\\ColtonHester\\Downloads\\eicar.com.txt";
                Task <ClamScanResult> scanResult1 = clam.SendAndScanFileAsync(fileName1);
                Task <ClamScanResult> scanResult2 = clam.SendAndScanFileAsync(fileName2);

                string output = "FileScan on " + fileName1 + " results:" + scanResult1.Result.RawResult.Replace("stream:", "") + "\n" +
                                "FileScan on " + fileName2 + " results:" + scanResult2.Result.RawResult.Replace("stream:", "");

                //using (System.IO.StreamWriter file =
                //			new System.IO.StreamWriter(@"C:\\Users\\ColtonHester\\Downloads\\load_test\\log.txt", true))
                //{
                //	file.WriteLine(logoutput);
                //}

                // test commit 1 - patch test 1 - round 4
                // test commit 2 - patch test 2 - round 5

                return(output);
            }
            catch (Exception ex) {
                return(ex.ToString());
            }
        }
예제 #6
0
        private async Task ScanNClamResult(byte[] content)
        {
            var            serverUrl = _rootConfiguration.isFileScanConfiguration.ServerUrl;
            var            port      = int.Parse(_rootConfiguration.isFileScanConfiguration.Port);
            var            clam      = new ClamClient(serverUrl, port);
            ClamScanResult scanResult;

            try
            {
                scanResult = await clam.SendAndScanFileAsync(content);
            }
            catch (Exception ex)
            { _logger.LogError("File Scan Error : " + ex.Message + "\n" + ex.StackTrace); throw new BusinessRuleException("Exception raised while scanning file"); }
            switch (scanResult.Result)
            {
            case ClamScanResults.Clean:
                break;

            case ClamScanResults.VirusDetected:
                throw new BusinessRuleException(string.Format("Virus Found! Virus name: {0}", scanResult.InfectedFiles.First().VirusName));

            case ClamScanResults.Error:
                throw new BusinessRuleException(string.Format("An error occured! Error: {0}", scanResult.RawResult));
            }
        }
예제 #7
0
파일: Scanner.cs 프로젝트: 3583Bytes/RestAV
        /// <summary>
        /// Scans an array of Base64 encoded bytes
        /// </summary>
        /// <param name="fileData">The Data to be scanned</param>
        /// <param name="fileGUID">The Results GUID used to index for scan result</param>
        /// <returns></returns>
        public static async Task ScanBytes(byte[] fileData, Guid fileGUID)
        {
            try
            {
                ClamClient clam = new ClamClient(ClamAVServer, ClamAVPort);

                var scanResult = await clam.SendAndScanFileAsync(fileData);

                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);
                }
            }
        }
예제 #8
0
        public static void Run([BlobTrigger("upload/{name}", Connection = "stgblobscan_STORAGE")] Stream myBlob, string name, ILogger log)
        {
            log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
            var clam = new ClamClient(GetEnvironmentVariable("clamavserver"), Convert.ToInt32(GetEnvironmentVariable("clamavport")));

            // Scanning for viruses...
            var scanResult = clam.SendAndScanFileAsync(myBlob).Result;

            switch (scanResult.Result)
            {
            case ClamScanResults.Clean:
                log.LogInformation("The file is clean!");
                MoveFileFromBlob(name, log);
                log.LogInformation("Move File {0}", name);
                break;

            case ClamScanResults.VirusDetected:
                log.LogInformation("Virus Found!");
                log.LogInformation("Virus name: {0}", scanResult.InfectedFiles.Count > 0 ? scanResult.InfectedFiles[0].FileName.ToString() : string.Empty);
                MoveFileFromBlob(name, log);
                break;

            case ClamScanResults.Error:
                log.LogInformation("Error scanning file: {0}", scanResult.RawResult);
                break;
            }
        }
예제 #9
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);
        }
예제 #10
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));
        }
예제 #11
0
        private async void buttonServerTest_Click(object sender, EventArgs e)
        {
            string version = string.Empty;

            clam = new ClamClient(textBoxServer.Text, (int)numericUpDownServerPort.Value);

            try
            {
                logger.Info("Testing ClamAV server connection");
                version = await clam.GetVersionAsync(clamServerTestCancelToken.Token);
            }
            catch (Exception ex)
            {
                logger.Warn(
                    ex,
                    "ClamAV server connection test failed using server {0}:{1}",
                    textBoxServer.Text,
                    (int)numericUpDownServerPort.Value);

                textBoxServerPing.Text = "Connection Failed";
                return;
            }

            logger.Info("ClamAV server response: {0}", version);
            textBoxServerPing.Text = version;
        }
예제 #12
0
        /// <summary>
        /// Sends the specified bytes to the ClamAv server to be scanned for viruses
        /// </summary>
        /// <param name="fileBytes">The file bytes to scanned</param>
        /// <returns>True if a virus is detected false if file is clean</returns>
        public async Task <bool> FileContainsVirus(byte[] fileBytes)
        {
            var            clam       = new ClamClient(_config[ConfigParameters.ClamAvServerUrl]);
            ClamScanResult scanResult = await clam.SendAndScanFileAsync(fileBytes);

            return(scanResult.Result == ClamScanResults.VirusDetected);
        }
예제 #13
0
        public static async Task <bool> FileScan(HttpPostedFileBase image)
        {
            return(true);

            try
            {
                var clam       = new ClamClient("localhost", 3310);
                var scanResult = await clam.SendAndScanFileAsync(image.InputStream).ConfigureAwait(false);


                switch (scanResult.Result)
                {
                case ClamScanResults.Clean:
                    return(true);

                    break;

                case ClamScanResults.VirusDetected:
                    return(false);

                    break;

                case ClamScanResults.Error:
                    return(false);

                    break;
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
예제 #14
0
        public void TestSendIPAsyncTest()
        {
            string Eicartestcase = @"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*";
            var    client        = new ClamClient(IPAddress.Parse("127.0.0.1"));
            var    result        = client.SendAndScanFileAsync(new MemoryStream(System.Text.Encoding.Default.GetBytes(Eicartestcase)));

            Assert.Equal(ClamScanResults.VirusDetected, result.Result.Result);
        }
예제 #15
0
 public Scanner(string hostNameOrAddress)
 {
     if (string.IsNullOrEmpty(hostNameOrAddress))
     {
         throw new Exception("Must provide a host name or address to server");
     }
     _hostNameOrAddress = hostNameOrAddress;
     _scanner           = new ClamClient(Dns.GetHostEntry(_hostNameOrAddress).AddressList.FirstOrDefault().ToString());
 }
예제 #16
0
 public static void TestClamd() => Task.Run(async() =>
 {
     try
     {
         clam = new ClamClient(Settings.Current.ClamdHost, Settings.Current.ClamdPort);
         Context.ClamdVersion = await clam.GetVersionAsync();
     }
     catch (SocketException) {}
 }).Wait();
예제 #17
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");
        }
    }
예제 #18
0
 public HomeController(UploadsDbContext context,
                       MinioClient minio,
                       ClamClient clam,
                       ILogger <HomeController> logger)
 {
     _context = context;
     _minio   = minio;
     _clam    = clam;
     _logger  = logger;
 }
예제 #19
0
        public async Task <IActionResult> Scan([FromForm] FileUpload fileUpload)
        {
            var ms = new MemoryStream();

            fileUpload.file.OpenReadStream().CopyTo(ms);
            byte[] fileBytes   = ms.ToArray();
            bool   isFileClean = false;

            try
            {
                this._logger.LogInformation("ClamAV scan begin for file {0}", fileUpload.file.FileName);
                // var clam = new ClamClient(this._configuration["ClamAVServer:URL"],
                //   Convert.ToInt32(this._configuration["ClamAVServer:Port"]));

                //var clam = new ClamClient("0.0.0.0", 3310);

                // First parameter could be the container ip (if link via network) or container name.
                var clam = new ClamClient("172.17.0.2", 3310);


                var scanResult = await clam.SendAndScanFileAsync(fileBytes);

                switch (scanResult.Result)
                {
                case ClamScanResults.Clean:
                    this._logger.LogInformation("The file is clean! ScanResult:{1}", scanResult.RawResult);
                    break;

                case ClamScanResults.VirusDetected:
                    this._logger.LogError("Virus Found! Virus name: {1}", scanResult.InfectedFiles.FirstOrDefault().VirusName);
                    break;

                case ClamScanResults.Error:
                    this._logger.LogError("An error occured while scaning the file! ScanResult: {1}", scanResult.RawResult);
                    break;

                case ClamScanResults.Unknown:
                    this._logger.LogError("Unknown scan result while scaning the file! ScanResult: {0}", scanResult.RawResult);
                    break;
                }

                if (scanResult.Result == ClamScanResults.Clean)
                {
                    isFileClean = true;
                }
            }
            catch (Exception ex)
            {
                this._logger.LogError("ClamAV Scan Exception: {0}", ex.ToString());
            }
            this._logger.LogInformation("ClamAV scan completed for file {0}", fileUpload.file.FileName);

            return(Ok(isFileClean));
        }
        //scan the folder or file
        private int ScanFile(string loc, bool silent)
        {
            if (av_service_error)
            {
                MetroFramework.MetroMessageBox.Show(this, "Antivirus services are not running, kindly restart the software or see the help manual to troubleshoot", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(0);
            }

            int ret = 0;

            if (File.Exists(loc))
            {
                var clam       = new ClamClient("localhost", 3310);
                var scanResult = clam.ScanFileOnServer(loc);
                switch (scanResult.Result)
                {
                case ClamScanResults.Clean:
                    if (!silent)
                    {
                        MetroFramework.MetroMessageBox.Show(this, "The file is clean, it's not infected!", "Fine", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    ret = 0;
                    break;

                case ClamScanResults.VirusDetected:
                {
                    if (!silent)
                    {
                        DialogResult dr = MetroFramework.MetroMessageBox.Show(this, "The file is infected\nVirus: " + scanResult.InfectedFiles.First().VirusName + "\nDo you want to delete?", "Virus Found", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dr == DialogResult.Yes)
                        {
                            try
                            {
                                File.Delete(loc);
                            }
                            catch { }
                        }
                    }
                    ret = 1;
                }
                break;
                }
                return(ret);
            }
            else
            {
                if (!silent)
                {
                    MetroFramework.MetroMessageBox.Show(this, "Invalid file to scan", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                ret = 3;
                return(ret);
            }
        }
예제 #21
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);
        }
예제 #22
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}");
        }
예제 #23
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
                });
            }
        }
예제 #24
0
    static async Task Main(string[] args)
    {
        var    clam      = new ClamClient("localhost", 3310);
        string filePath  = "C:\\test.txt";
        string filePath2 = "C:\\test.docx";


        await ScanAndUploadDocument(clam, filePath);

        Thread.Sleep(2000);
        await ScanAndUploadDocument(clam, filePath2);

        Console.ReadLine();
    }
예제 #25
0
파일: Scanner.cs 프로젝트: 3583Bytes/RestAV
        /// <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";
            }
        }
예제 #26
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            ScanResultModel scr    = new ScanResultModel();
            Stream          stream = new MemoryStream();

            if (req.Body == null)
            {
                stream = GenerateStreamFromString("a,b \n c,d");
            }
            else
            {
                await req.Body.CopyToAsync(stream);

                stream.Seek(0, SeekOrigin.Begin);
            }

            string clamip = Environment.GetEnvironmentVariable("clamip", EnvironmentVariableTarget.Process);
            //var clam = new ClamClient("13.86.246.40", 3310); // "clamav -server",
            // clam = new ClamClient("172.17.0.2", 3310); // "clamav -server",
            var clam = new ClamClient(clamip, 3310);

            scr.InfectedFilesCount = 0;
            var scanResult = await clam.SendAndScanFileAsync(stream);

            if (scanResult.InfectedFiles != null)
            {
                scr.InfectedFilesCount = scanResult.InfectedFiles.Count;
            }


            scr.RawResult = scanResult.RawResult;
            scr.Result    = scanResult.Result.ToString();

            scr.IsComplete = true;

            //return CreatedAtAction("xyz", scr);
            string jsonData = JsonConvert.SerializeObject(scr);

            return(new OkObjectResult(jsonData));
        }
예제 #27
0
파일: Program.cs 프로젝트: zalois/nClam
    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;
        }
    }
예제 #28
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" });
            }
        }
예제 #29
0
        public async Task <IActionResult> UploadFile(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return(Content("file not selected"));
            }

            var ms = new MemoryStream();

            file.OpenReadStream().CopyTo(ms);
            byte[] fileBytes = ms.ToArray();
            string Result    = string.Empty;

            try
            {
                // Scan with Docker image
                var clam = new ClamClient(this._configuration["ClamAVServer:URL"],
                                          Convert.ToInt32(this._configuration["ClamAVServer:Port"]));

                // Scan with Clam Av server
                //var clam = new ClamClient(IPAddress.Parse("127.0.0.1"), 3310);
                var scanResult = await clam.SendAndScanFileAsync(fileBytes);

                // Switch Expression C# 8.0
                Result = scanResult.Result switch
                {
                    ClamScanResults.Clean => "Clean",
                    ClamScanResults.VirusDetected => "Virus Detected",
                    ClamScanResults.Error => "Error in File",
                    ClamScanResults.Unknown => "Unknown File",
                    _ => "No case available"
                };
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(Ok(Result));
        }
예제 #30
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();
    }
예제 #31
0
        private async Task <bool> PerformClamAVScan()
        {
            var isInfected = false;

            var clamAVServiceURI = Environment.GetEnvironmentVariable("ClamAVServiceURI");

            var clam = new ClamClient(clamAVServiceURI, 3310);

            ClamScanResult scanResult = null;

            var timeTaken = await TimedExecutionAsync(async() =>
            {
                scanResult = await clam.SendAndScanFileAsync(blobStream.ReadAllBytes());
            });

            logger.LogInformation($"Time taken to perform virus scan {timeTaken} ms");

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

            case ClamScanResults.VirusDetected:
                logger.LogInformation("Virus Found!");
                logger.LogInformation("Virus name: {0}", scanResult.InfectedFiles.First().VirusName);
                isInfected = true;
                break;

            case ClamScanResults.Error:
                logger.LogInformation("Error scanning file: {0}", scanResult.RawResult);
                break;
            }

            return(isInfected);
        }