Example #1
0
        public IActionResult Success([FromRoute] Guid id)
        {
            if (ModelState.IsValid)
            {
                Scan scan = _context.Scans.Single(s => s.Id == id);
                scan.StopTime = DateTime.UtcNow;
                scan.Status   = "Completed";
                _context.Scans.Update(scan);

                Sweep sweep = _context.Sweeps.Single(s => s.Id == scan.SweepIdentifier);
                sweep.CompleteCount++;
                if ((sweep.CompleteCount + sweep.ErrorCount) == sweep.ScanCount)
                {
                    sweep.Status = "Completed";
                }
                _context.Sweeps.Update(sweep);

                _context.SaveChanges();

                return(Ok());
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Example #2
0
        public User Delete([FromRoute] Guid id)
        {
            User requestor = _context.Users.SingleOrDefault(u => u.ApiKey == Request.Headers["X-ApiKey"]);

            if (requestor.IsAdmin)
            {
                if (id == requestor.Id)
                {
                    throw new Exception("A user cannot delete itself.");
                }
                else
                {
                    try
                    {
                        User user = _context.Users.SingleOrDefault(u => u.Id == id);
                        _context.Users.Remove(user);
                        _context.SaveChanges();
                        return(user);
                    }
                    catch
                    {
                        throw new Exception("Failed to delete account.");
                    }
                }
            }
            else
            {
                throw new Exception("Only Administrator accounts can delete accounts.");
            }
        }
Example #3
0
        public Script Delete([FromRoute]Guid id)
        {
            User requestor = _context.Users.SingleOrDefault(u => u.ApiKey == Request.Headers["X-ApiKey"]);

            if (requestor.IsAdmin)
            {
                try
                {
                    Script script = _context.Scripts.SingleOrDefault(s => s.Id == id);

                    // Delete the script from disk
                    string scriptLocation = string.Format(@"{0}\{1}", _hostingEnv.ContentRootPath, script.Uri);
                    System.IO.File.Delete(scriptLocation);

                    // Remove the script from the database
                    _context.Scripts.Remove(script);
                    _context.SaveChanges();
                    return script;
                }
                catch
                {
                    throw new Exception("Failed to delete script.");
                }
            }
            else
            {
                throw new Exception("Only administrator users can delete credentials.");
            }
        }
Example #4
0
        public IActionResult ReceiveFile([FromRoute] Guid id, [FromBody] DownloadReceiveViewModel param)
        {
            if (ModelState.IsValid)
            {
                // Create file from uploaded script
                string scriptLocation = string.Format(@"{0}/Downloads/{1}", _hostingEnv.ContentRootPath, id);
                System.IO.File.WriteAllBytes(scriptLocation, param.Content);

                // Add database entry for new script
                Download download = new Download
                {
                    Id           = id,
                    ComputerName = param.ComputerName,
                    Name         = param.Name,
                    FullPath     = param.FullPath,
                    DownloadTime = DateTime.UtcNow,
                    ModifiedTime = param.ModifiedTime,
                    AccessedTime = param.AccessedTime,
                    BornTime     = DateTime.UtcNow
                };
                _context.Downloads.Add(download);
                _context.SaveChanges();

                return(Ok(download));
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Example #5
0
        /*
         * public void Discover(DiscoveryActiveDirectoryViewModel param)
         * {
         *  Console.WriteLine("=========================");
         *  Console.WriteLine("Domain: {0}", param.Domain);
         *  Console.WriteLine("=========================");
         *
         *  List<Computer> computerList = new List<Computer>();
         *
         *  Console.WriteLine("=========================");
         *  Console.WriteLine("CredentialId: {0}", param.CredentialId);
         *  Console.WriteLine("=========================");
         *
         *  Credential credential = _context.Credentials.SingleOrDefault(cred => cred.Id == param.CredentialId);
         *
         *  Console.WriteLine("=========================");
         *  Console.WriteLine("UserName: {0}", credential.UserName);
         *  Console.WriteLine("=========================");
         *
         *  SearchResultCollection results = GetDomainComputers(param.Domain, credential);
         *
         *  foreach (SearchResult result in results)
         *  {
         *      string computername = (string)result.Properties["dnshostname"][0];
         *      //string operatingsystem = (string)result.Properties["operatingsystem"][0];
         *
         *      Console.WriteLine("=========================");
         *      Console.WriteLine("ComputerName: {0}", computername);
         *      Console.WriteLine("=========================");
         *
         *      try
         *      {
         *          Computer computer = _context.Computers.Single(c => c.ComputerName == computername);
         *
         *          computer.ComputerName = computername;
         *          //computer.OperatingSystem = operatingsystem;
         *          computer.CredentialId = param.CredentialId;
         *          computer.SSH = TestPort(computername, 22);
         *          computer.RPC = TestPort(computername, 135);
         *          computer.SMB = TestPort(computername, 445);
         *          computer.WinRM = TestPort(computername, 5985);
         *
         *          _context.Computers.Update(computer);
         *      }
         *      catch
         *      {
         *          Guid id = Guid.NewGuid();
         *          Console.WriteLine("=========================");
         *          Console.WriteLine("Id: {0}", id);
         *          Console.WriteLine("=========================");
         *
         *          computerList.Add(new Computer
         *          {
         *              Id = id,
         *              ComputerName = computername,
         *              OperatingSystem = null,
         *              CredentialId = param.CredentialId,
         *              Scanned = false,
         *              SSH = TestPort(computername, 22),
         *              RPC = TestPort(computername, 135),
         *              SMB = TestPort(computername, 445),
         *              WinRM = TestPort(computername, 5985)
         *          });
         *      }
         *  }
         *
         *  _context.Computers.AddRange(computerList);
         *  _context.SaveChanges();
         * }
         */

        /*
         * public void Discover(DiscoveryComputerListViewModel param)
         * {
         *  List<Computer> computerList = new List<Computer>();
         *
         *  foreach(string name in param.ComputerName)
         *  {
         *      Console.WriteLine("=========================");
         *      Console.WriteLine("ComputerName: {0}", name);
         *      Console.WriteLine("=========================");
         *
         *      try
         *      {
         *          Computer computer = _context.Computers.Single(c => c.ComputerName == name);
         *
         *          computer.SSH = TestPort(computer.ComputerName, 22);
         *          computer.RPC = TestPort(computer.ComputerName, 135);
         *          computer.SMB = TestPort(computer.ComputerName, 445);
         *          computer.WinRM = TestPort(computer.ComputerName, 5985);
         *
         *          _context.Computers.Update(computer);
         *      }
         *      catch
         *      {
         *          Guid id = Guid.NewGuid();
         *          Console.WriteLine("=========================");
         *          Console.WriteLine("Id: {0}", id);
         *          Console.WriteLine("=========================");
         *
         *          computerList.Add(new Computer
         *          {
         *              Id = id,
         *              ComputerName = name,
         *              OperatingSystem = null,
         *              CredentialId = param.CredentialId,
         *              Scanned = false,
         *              SSH = TestPort(name, 22),
         *              RPC = TestPort(name, 135),
         *              SMB = TestPort(name, 445),
         *              WinRM = TestPort(name, 5985)
         *          });
         *
         *          //computerList.Add(GetComputer(name, null, param.CredentialId, false));
         *      }
         *  }
         *
         *  Console.WriteLine("=========================");
         *  Console.WriteLine("Post Loop");
         *  Console.WriteLine("=========================");
         *
         *  _context.Computers.AddRange(computerList);
         *  _context.SaveChanges();
         * }
         */

        public void Discover(DiscoveryComputerListViewModel param)
        {
            var computerDictionary = new ConcurrentDictionary <string, Computer>();

            // Add all current DB entries to computerDictionary
            foreach (Computer comp in _context.Computers)
            {
                computerDictionary.TryAdd(comp.ComputerName, comp);
            }

            // Set up Threads
            var numThreads = 20;
            var collection = new BlockingCollection <Wrapper <ACEComputer> >();
            var tasks      = new Task[numThreads];

            for (var x = 0; x < numThreads; x++)
            {
                tasks[x] = CreateTask(collection, computerDictionary);
            }

            foreach (string computer in param.ComputerName)
            {
                collection.Add(new Wrapper <ACEComputer>
                {
                    Item = new ACEComputer {
                        ComputerName = computer,
                        CredentialId = param.CredentialId
                    }
                });
            }
            collection.CompleteAdding();
            Console.WriteLine("Finished adding items to queue, waiting on tasks");
            Task.WaitAll(tasks);

            // Delete all old entries from the Computer Table
            _context.Computers.RemoveRange(_context.Computers);
            _context.SaveChanges();
            // Update table with all entries from the cache
            _context.Computers.AddRange(computerDictionary.Values);
            // Save all changes done to the DB
            _context.SaveChanges();
        }
Example #6
0
        /*
         * public void Discover(DiscoveryActiveDirectoryViewModel param)
         * {
         *  Console.WriteLine("=========================");
         *  Console.WriteLine("Domain: {0}", param.Domain);
         *  Console.WriteLine("=========================");
         *
         *  List<Computer> computerList = new List<Computer>();
         *
         *  Console.WriteLine("=========================");
         *  Console.WriteLine("CredentialId: {0}", param.CredentialId);
         *  Console.WriteLine("=========================");
         *
         *  Credential credential = _context.Credentials.SingleOrDefault(cred => cred.Id == param.CredentialId);
         *
         *  Console.WriteLine("=========================");
         *  Console.WriteLine("UserName: {0}", credential.UserName);
         *  Console.WriteLine("=========================");
         *
         *  SearchResultCollection results = GetDomainComputers(param.Domain, credential);
         *
         *  foreach (SearchResult result in results)
         *  {
         *      string computername = (string)result.Properties["dnshostname"][0];
         *      //string operatingsystem = (string)result.Properties["operatingsystem"][0];
         *
         *      Console.WriteLine("=========================");
         *      Console.WriteLine("ComputerName: {0}", computername);
         *      Console.WriteLine("=========================");
         *
         *      try
         *      {
         *          Computer computer = _context.Computers.Single(c => c.ComputerName == computername);
         *
         *          computer.ComputerName = computername;
         *          //computer.OperatingSystem = operatingsystem;
         *          computer.CredentialId = param.CredentialId;
         *          computer.SSH = TestPort(computername, 22);
         *          computer.RPC = TestPort(computername, 135);
         *          computer.SMB = TestPort(computername, 445);
         *          computer.WinRM = TestPort(computername, 5985);
         *
         *          _context.Computers.Update(computer);
         *      }
         *      catch
         *      {
         *          Guid id = Guid.NewGuid();
         *          Console.WriteLine("=========================");
         *          Console.WriteLine("Id: {0}", id);
         *          Console.WriteLine("=========================");
         *
         *          computerList.Add(new Computer
         *          {
         *              Id = id,
         *              ComputerName = computername,
         *              OperatingSystem = null,
         *              CredentialId = param.CredentialId,
         *              Scanned = false,
         *              SSH = TestPort(computername, 22),
         *              RPC = TestPort(computername, 135),
         *              SMB = TestPort(computername, 445),
         *              WinRM = TestPort(computername, 5985)
         *          });
         *      }
         *  }
         *
         *  _context.Computers.AddRange(computerList);
         *  _context.SaveChanges();
         * }
         */

        public void Discover(DiscoveryComputerListViewModel param)
        {
            List <Computer> computerList = new List <Computer>();

            foreach (string name in param.ComputerName)
            {
                Console.WriteLine("=========================");
                Console.WriteLine("ComputerName: {0}", name);
                Console.WriteLine("=========================");

                try
                {
                    Computer computer = _context.Computers.Single(c => c.ComputerName == name);

                    computer.SSH   = TestPort(computer.ComputerName, 22);
                    computer.RPC   = TestPort(computer.ComputerName, 135);
                    computer.SMB   = TestPort(computer.ComputerName, 445);
                    computer.WinRM = TestPort(computer.ComputerName, 5985);

                    _context.Computers.Update(computer);
                }
                catch
                {
                    Guid id = Guid.NewGuid();
                    Console.WriteLine("=========================");
                    Console.WriteLine("Id: {0}", id);
                    Console.WriteLine("=========================");

                    computerList.Add(new Computer
                    {
                        Id              = id,
                        ComputerName    = name,
                        OperatingSystem = null,
                        CredentialId    = param.CredentialId,
                        Scanned         = false,
                        SSH             = TestPort(name, 22),
                        RPC             = TestPort(name, 135),
                        SMB             = TestPort(name, 445),
                        WinRM           = TestPort(name, 5985)
                    });

                    //computerList.Add(GetComputer(name, null, param.CredentialId, false));
                }
            }

            Console.WriteLine("=========================");
            Console.WriteLine("Post Loop");
            Console.WriteLine("=========================");

            _context.Computers.AddRange(computerList);
            _context.SaveChanges();
        }
Example #7
0
        public IActionResult Put([FromRoute] Guid id, [FromBody] Guid scanId)
        {
            if (ModelState.IsValid)
            {
                Scan scan = _context.Scans.SingleOrDefault(s => s.Id == scanId);
                scan.StopTime = DateTime.UtcNow;
                scan.Status   = "Completed";
                _context.Scans.Update(scan);
                _context.SaveChanges();

                Sweep sweep = _context.Sweeps.SingleOrDefault(sw => sw.Id == id);
                sweep.CompleteCount++;
                _context.Sweeps.Update(sweep);
                _context.SaveChanges();

                return(Ok(scanId));
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Example #8
0
        public Credential Delete([FromRoute] Guid id)
        {
            User requestor = _context.Users.SingleOrDefault(u => u.ApiKey == Request.Headers["X-ApiKey"]);

            if (requestor.IsAdmin)
            {
                try
                {
                    Credential credential = _context.Credentials.SingleOrDefault(cred => cred.Id == id);
                    _context.Credentials.Remove(credential);
                    _context.SaveChanges();
                    return(credential);
                }
                catch
                {
                    throw new Exception("Failed to delete credential");
                }
            }
            else
            {
                throw new Exception("Only administrator users can delete credentials.");
            }
        }
Example #9
0
        public IActionResult ReceiveFile([FromRoute] Guid id, [FromBody] DownloadReceiveViewModel param)
        {
            if (ModelState.IsValid)
            {
                _context.Downloads.Add(new Download {
                    Id           = id,
                    ComputerName = param.ComputerName,
                    Name         = param.Name,
                    FullPath     = param.FullPath,
                    Content      = param.Content,
                    DownloadTime = DateTime.UtcNow
                });
                _context.SaveChanges();

                return(Ok(param.FullPath));
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Example #10
0
        public Guid Sweep(SweepExecutionViewModel param)
        {
            // Generate Sweep Id and add the Sweep to the DB
            Guid Id = Guid.NewGuid();

            _context.Sweeps.Add(new Sweep
            {
                Id            = Id,
                Status        = "Running",
                StartTime     = DateTime.UtcNow,
                ScanCount     = param.ComputerId.Length,
                CompleteCount = 0
            });
            _context.SaveChanges();

            // Retrieve the target Script's data from the DB
            Script script = _context.Scripts.Single(s => s.Id == param.ScriptId);

            // Retrieve Credential objects from the DB and put in a dictionary based on the Id field
            Dictionary <Guid, Credential> credDictionary = _context.Credentials.ToDictionary(credential => credential.Id);

            // Create Parallel Tasks
            int numThreads = 20;
            var collection = new BlockingCollection <Wrapper <ACETasking> >(1000);
            var tasks      = new Task[numThreads];

            for (var x = 0; x < numThreads; x++)
            {
                tasks[x] = CreateTask(collection);
            }

            foreach (Guid compid in param.ComputerId)
            {
                // Generate Scan Id and add the Scan to the DB
                Guid scanId = Guid.NewGuid();
                _context.Scans.Add(new Scan
                {
                    Id              = scanId,
                    Status          = "Running",
                    StartTime       = DateTime.UtcNow,
                    ComputerId      = compid,
                    SweepIdentifier = Id
                });

                // Retreive Computer objects from DB
                Computer computer = _context.Computers.Single(c => c.Id == compid);

                // Add items to the task collection
                collection.Add(new Wrapper <ACETasking>
                {
                    Item = new ACETasking {
                        Computer             = computer,
                        CredentialDictionary = credDictionary,
                        Uri        = param.ExternalUri,
                        Thumbprint = _settings.Thumbprint,
                        Script     = script,
                        SweepId    = Id,
                        ScanId     = scanId
                    }
                });
            }

            _context.SaveChanges();
            collection.CompleteAdding();
            Console.WriteLine("Finished adding items to queue, waiting on tasks");
            Task.WaitAll(tasks);

            return(Id);
        }
Example #11
0
        public void Discover(DiscoveryActiveDirectoryViewModel param)
        {
            Console.WriteLine("=========================");
            Console.WriteLine("Domain: {0}", param.Domain);
            Console.WriteLine("=========================");

            List <Computer> computerList = new List <Computer>();

            Console.WriteLine("=========================");
            Console.WriteLine("CredentialId: {0}", param.CredentialId);
            Console.WriteLine("=========================");

            Credential credential = _context.Credentials.SingleOrDefault(cred => cred.Id == param.CredentialId);

            Console.WriteLine("=========================");
            Console.WriteLine("UserName: {0}", credential.UserName);
            Console.WriteLine("=========================");

            SearchResultCollection results = GetDomainComputers(param.Domain, credential);

            foreach (SearchResult result in results)
            {
                string computername = (string)result.Properties["dnshostname"][0];
                //string operatingsystem = (string)result.Properties["operatingsystem"][0];

                Console.WriteLine("=========================");
                Console.WriteLine("ComputerName: {0}", computername);
                Console.WriteLine("=========================");

                try
                {
                    Computer computer = _context.Computers.Single(c => c.ComputerName == computername);

                    computer.ComputerName = computername;
                    //computer.OperatingSystem = operatingsystem;
                    computer.CredentialId = param.CredentialId;
                    computer.SSH          = TestPort(computername, 22);
                    computer.RPC          = TestPort(computername, 135);
                    computer.SMB          = TestPort(computername, 445);
                    computer.WinRM        = TestPort(computername, 5985);

                    _context.Computers.Update(computer);
                }
                catch
                {
                    Guid id = Guid.NewGuid();
                    Console.WriteLine("=========================");
                    Console.WriteLine("Id: {0}", id);
                    Console.WriteLine("=========================");

                    computerList.Add(new Computer
                    {
                        Id              = id,
                        ComputerName    = computername,
                        OperatingSystem = null,
                        CredentialId    = param.CredentialId,
                        Scanned         = false,
                        SSH             = TestPort(computername, 22),
                        RPC             = TestPort(computername, 135),
                        SMB             = TestPort(computername, 445),
                        WinRM           = TestPort(computername, 5985)
                    });
                }
            }

            _context.Computers.AddRange(computerList);
            _context.SaveChanges();
        }
Example #12
0
        public Guid Sweep(SweepExecutionViewModel param)
        {
            Guid Id = Guid.NewGuid();

            _context.Sweeps.Add(new Sweep
            {
                Id            = Id,
                Status        = "Running",
                StartTime     = DateTime.UtcNow,
                ScanCount     = param.ComputerId.Length,
                CompleteCount = 0
            });
            _context.SaveChanges();

            List <Task> tasks = new List <Task>();

            /*
             * List<Scan> scans = new List<Scan>();
             *
             * foreach (Guid compId in param.ComputerId)
             * {
             *  // Create scan object
             *  Guid scanId = Guid.NewGuid();
             *  scans.Add(new Scan
             *  {
             *      Id = scanId,
             *      Status = "Running",
             *      StartTime = DateTime.UtcNow,
             *      ComputerId = compId,
             *      SweepIdentifier = Id
             *  });
             * }
             *
             * _context.Scans.AddRange(scans);
             */

            _context.SaveChanges();

            // Get Script object
            Script script = _context.Scripts.Single(s => s.Id == param.ScriptId);

            // Create Routing Key
            string RoutingKey = string.Format("{0}{1}", script.Enrichment, script.Output);

            // Get Thumbprint
            string thumbprint = null;

            string[] lines = System.IO.File.ReadAllLines(@"C:\inetpub\ACEWebService\appsettings.Production.json");
            foreach (string l in lines)
            {
                if (l.Contains("Thumbprint"))
                {
                    thumbprint = l.Split('"')[3];
                }
            }

            foreach (Guid compid in param.ComputerId)
            {
                Guid scanId = Guid.NewGuid();

                // Retreive Computer and Credential objects from DB
                Computer   computer   = _context.Computers.Single(c => c.Id == compid);
                Credential credential = _context.Credentials.Single(c => c.Id == computer.CredentialId);

                // Kick off scan
                if (computer.WinRM)
                {
                    Console.WriteLine("==== WINRM ====");

                    // Create a PowerShell script to run PSInvestigate
                    string executionArgs = string.Format(@"-Uri {0} -SweepId {1} -ScanId {2} -RoutingKey {3} -Thumbprint {4}", param.Uri, Id, scanId, RoutingKey, thumbprint);

                    Console.WriteLine(executionArgs);

                    string psScript = string.Format(@"iex (New-Object System.Net.WebClient).DownloadString('{0}{1}'); Start-AceScript {2}", param.Uri, script.Uri, executionArgs);

                    // Base64 Encode the PowerShell script
                    string psScriptEnc = Convert.ToBase64String(Encoding.Unicode.GetBytes(psScript));

                    // Build full powershell command line to be run
                    string commandline = string.Format(@"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -EncodedCommand {0}", psScriptEnc);

                    Console.WriteLine(commandline);

                    tasks.Add(Task.Run(() => { KickOffCimAsync(computer, credential, commandline, new WSManSessionOptions()); }));
                }
                else if (computer.RPC)
                {
                    Console.WriteLine("==== RPC ====");

                    // Create a PowerShell script to run PSInvestigate
                    string executionArgs = string.Format(@"-Uri {0} -SweepId {1} -ScanId {2} -RoutingKey {3} -Thumbprint {4}", param.Uri, Id, scanId, RoutingKey, thumbprint);
                    string psScript      = string.Format(@"iex (New-Object System.Net.WebClient).DownloadString('{0}{1}'); Start-AceScript {2}", param.Uri, script.Uri, executionArgs);

                    // Base64 Encode the PowerShell script
                    string psScriptEnc = Convert.ToBase64String(Encoding.Unicode.GetBytes(psScript));

                    // Build full powershell command line to be run
                    string commandline = string.Format(@"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle Hidden -EncodedCommand {0}", psScriptEnc);

                    Console.WriteLine(commandline);

                    tasks.Add(Task.Run(() => { KickOffCimAsync(computer, credential, commandline, new DComSessionOptions()); }));
                }
                else if (computer.SSH)
                {
                    Console.WriteLine("==== SSH ====");

                    // Build command line to be run over SSH
                    string commandline = string.Format(@"curl -k {0}{1} | sudo python /dev/stdin --Server {0} --SweepId {2} --ScanId {3} --RoutingKey {4}", param.Uri, script.Uri, Id, scanId, RoutingKey);
                    //tasks.Add(Task.Run(() => { KickOffSSHAsync(computer, credential, commandline); }));
                    using (var client = new SshClient(computer.ComputerName, credential.UserName, _cryptoService.Decrypt(credential.Password)))
                    {
                        client.Connect();
                        client.RunCommand(commandline);
                        client.Disconnect();
                    }
                }
                else if (computer.SMB)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    throw new Exception(string.Format("No valid protocols available for {0}", computer.ComputerName));
                }
            }

            Task.WaitAll(tasks.ToArray());

            IQueryable <Scan> scansCompleted = _context.Set <Scan>().Where(s => s.SweepIdentifier == Id && s.Status != "Running");
            IQueryable <Scan> scansFailed    = _context.Set <Scan>().Where(s => s.SweepIdentifier == Id && s.Status == "Failed");
            Sweep             sweep          = _context.Sweeps.Single(s => s.Id == Id);

            sweep.CompleteCount = scansCompleted.ToArray().Length;
            sweep.ErrorCount    = scansFailed.ToArray().Length;
            sweep.Status        = "Completed";
            _context.Sweeps.Update(sweep);
            _context.SaveChanges();

            return(Id);
        }