Example #1
0
 public EliteMenu(CovenantAPI CovenantClient)
 {
     this.CovenantClient = CovenantClient;
     this.MenuStack.Add(new CovenantBaseMenuItem(this.CovenantClient, this.EventPrinter));
     this.onEventOccured = (sender, eventArgs) =>
     {
         string     context  = this.GetMenuLevelTitleStack();
         EventModel theEvent = eventArgs.theEvent;
         if (theEvent.Type == EventType.Normal)
         {
             if (this.EventPrinter.WillPrintEvent(theEvent, context))
             {
                 EliteConsole.PrintInfoLine();
                 this.EventPrinter.PrintEvent(theEvent, context);
                 this.PrintMenuLevel();
             }
         }
         else if (theEvent.Type == EventType.Download)
         {
             DownloadEvent downloadEvent = this.CovenantClient.ApiEventsDownloadByIdGet(theEvent.Id ?? default);
             string        download      = this.CovenantClient.ApiEventsDownloadByIdContentGet(downloadEvent.Id ?? default);
             System.IO.File.WriteAllBytes(System.IO.Path.Combine(Common.EliteDataFolder, theEvent.Message), Convert.FromBase64String(download));
         }
     };
 }
Example #2
0
 public ActionResult CreateDownloadEvent([FromBody] DownloadEvent downloadEvent)
 {
     downloadEvent.Time = DateTime.UtcNow;
     downloadEvent.WriteToDisk();
     _context.Events.Add(downloadEvent);
     _context.SaveChanges();
     return(CreatedAtRoute(nameof(GetEvent), new { id = downloadEvent.Id }, downloadEvent));
 }
Example #3
0
    private void OnProgress(DownloadEvent e)
    {
        evt = e;

        if (evt.status == DownloadStatus.PROGRESS)
        {
            //Debug.Log("evt progress: " + e.progress + " : " + e.downloadedBytes + ":" + e.totalBytes);
        }
    }
Example #4
0
    void OnDownloadComplete(DownloadEvent e)
    {
        evt = e;

        if (evt.error != null)
        {
            Debug.Log(evt.error);
        }
    }
Example #5
0
        public ActionResult <string> GetDownloadContent(int id)
        {
            DownloadEvent theEvent = ((DownloadEvent)_context.Events.FirstOrDefault(E => E.Id == id));

            if (theEvent == null)
            {
                return(NotFound());
            }
            return(Ok(Convert.ToBase64String(System.IO.File.ReadAllBytes(Path.Combine(Common.CovenantDownloadDirectory, theEvent.FileName)))));
        }
Example #6
0
        private void DownloadDataCallback(object s, AsyncCompletedEventArgs e)
        {
            MessageBox.Show($"Download finished successful to {label1.Text} path");
            // run delegate methods here => DownloadDataCallback and Install methods will be invoked here

            DownloadEvent?.Invoke();

            if (checkBox5.Checked)
            {
                InstallAllDownloadedTools();
            }
        }
Example #7
0
        public async Task <IActionResult> Download(int id)
        {
            try
            {
                DownloadEvent ev = await _context.GetDownloadEvent(id);

                return(File(Convert.FromBase64String(ev.FileContents), "plain/text", ev.FileName));
            }
            catch (Exception e) when(e is ControllerNotFoundException || e is ControllerBadRequestException || e is ControllerUnauthorizedException)
            {
                ModelState.AddModelError(string.Empty, e.Message);
                return(RedirectToAction(nameof(Index)));
            }
        }
Example #8
0
        private void ProcessEvent()
        {
            if (m_Event.Count > 0)
            {
                DownloadEvent de = m_Event.Pop();
                m_Event.Clear();
                switch (de)
                {
                case DownloadEvent.Downloaded:
                {
                    SavaFileFromMemory();
                }
                break;

                case DownloadEvent.Begin:
                    break;

                case DownloadEvent.DownloadOrExit:
                    break;

                case DownloadEvent.Error:
                    OnDownloadError eL = m_OnError;
                    m_IsDownloading = false;
                    Clear();
                    if (eL != null)
                    {
                        eL(m_EventMsg);
                        eL = null;
                    }
                    break;

                case DownloadEvent.Finish:
                    OnDownloadFinished fL = m_OnFinished;
                    Clear();
                    if (fL != null)
                    {
                        fL(m_SaveFile, 0, 0);
                    }
                    break;

                case DownloadEvent.Progress:
                    break;

                default:
                    break;
                }
            }
        }
Example #9
0
        public ActionResult <string> GetDownloadContent(int id)
        {
            DownloadEvent theEvent = ((DownloadEvent)_context.Events.FirstOrDefault(E => E.Id == id));

            if (theEvent == null)
            {
                return(NotFound($"NotFound - DownloadEvent with id: {id}"));;
            }
            string filename = Path.Combine(Common.CovenantDownloadDirectory, theEvent.FileName);

            if (!System.IO.File.Exists(filename))
            {
                return(BadRequest($"BadRequest - Path does not exist on disk: {filename}"));
            }
            return(Convert.ToBase64String(System.IO.File.ReadAllBytes(filename)));
        }
Example #10
0
        public async Task <ActionResult> CreateDownloadEvent([FromBody] DownloadEvent downloadEvent)
        {
            try
            {
                DownloadEvent createdEvent = await _context.CreateDownloadEvent(downloadEvent);

                return(CreatedAtRoute(nameof(GetEvent), new { id = createdEvent.Id }, createdEvent));
            }
            catch (ControllerNotFoundException e)
            {
                return(NotFound(e.Message));
            }
            catch (ControllerBadRequestException e)
            {
                return(BadRequest(e.Message));
            }
        }
Example #11
0
    private void OnDownloadComplete(DownloadEvent e)
    {
        evt = e;

        if (evt.status == DownloadStatus.COMPLETED)
        {
            fileDownloaded = true;
        }
        else if (evt.status == DownloadStatus.CANCELLED)
        {
            downloading = false;
        }
        else if (evt.status == DownloadStatus.FAILED)
        {
            downloading = false;
            if (evt.error != null)
            {
                Debug.Log("ERROR: " + evt.error);
            }
        }
    }
Example #12
0
 public ActionResult CreateDownloadEvent([FromBody] DownloadEvent downloadEvent)
 {
     downloadEvent.Time = DateTime.Now;
     byte[] contents = Convert.FromBase64String(downloadEvent.FileContents);
     if (downloadEvent.Progress == DownloadEvent.DownloadProgress.Complete)
     {
         System.IO.File.WriteAllBytes(
             Path.Combine(Common.CovenantDownloadDirectory, downloadEvent.FileName),
             contents
             );
     }
     else
     {
         using (var stream = new FileStream(Path.Combine(Common.CovenantDownloadDirectory, downloadEvent.FileName), FileMode.Append))
         {
             stream.Write(contents, 0, contents.Length);
         }
     }
     _context.Events.Add(downloadEvent);
     _context.SaveChanges();
     return(CreatedAtRoute(nameof(GetEvent), new { id = downloadEvent.Id }, downloadEvent));
 }
Example #13
0
 public Task <DownloadEvent> CreateDownloadEvent(DownloadEvent downloadEvent)
 {
     return(_connection.InvokeAsync <DownloadEvent>("CreateDownloadEvent", downloadEvent));
 }
Example #14
0
 void OnProgress(DownloadEvent e)
 {
     evt = e;
 }
        private static void CopyEvents(Interaction source, Interaction target)
        {
            foreach (Event e in source.Events)
            {
                Event result;
                if (e is CampaignEvent ce)
                {
                    CampaignEvent newEvent = new CampaignEvent(ce.CampaignDefinitionId, ce.Timestamp);
                    result = newEvent;
                }
                else if (e is DownloadEvent de)
                {
                    DownloadEvent newEvent = new DownloadEvent(de.Timestamp, de.ItemId);
                    result = newEvent;
                }
                else if (e is Goal g)
                {
                    Goal newEvent = new Goal(g.DefinitionId, g.Timestamp);
                    result = newEvent;
                }
                else if (e is MVTestTriggered mvt)
                {
                    MVTestTriggered newEvent = new MVTestTriggered(mvt.Timestamp);
                    newEvent.Combination     = mvt.Combination;
                    newEvent.EligibleRules   = mvt.EligibleRules;
                    newEvent.ExposureTime    = mvt.ExposureTime;
                    newEvent.FirstExposure   = mvt.FirstExposure;
                    newEvent.IsSuspended     = mvt.IsSuspended;
                    newEvent.ValueAtExposure = mvt.ValueAtExposure;
                    result = newEvent;
                }
                else if (e is Outcome o)
                {
                    Outcome newEvent = new Outcome(o.DefinitionId, o.Timestamp, o.CurrencyCode, o.MonetaryValue);
                    result = newEvent;
                }
                else if (e is PageViewEvent pve)
                {
                    PageViewEvent newEvent = new PageViewEvent(
                        pve.Timestamp,
                        pve.ItemId,
                        pve.ItemVersion,
                        pve.ItemLanguage);
                    newEvent.SitecoreRenderingDevice = pve.SitecoreRenderingDevice;
                    newEvent.Url = pve.Url;
                    result       = newEvent;
                }
                else if (e is PersonalizationEvent pe)
                {
                    PersonalizationEvent newEvent = new PersonalizationEvent(pe.Timestamp);
                    newEvent.ExposedRules = pe.ExposedRules;
                    result = newEvent;
                }
                else if (e is SearchEvent se)
                {
                    SearchEvent newEvent = new SearchEvent(se.Timestamp);
                    newEvent.Keywords = se.Keywords;
                    result            = newEvent;
                }
                else if (e is BounceEvent be)
                {
                    BounceEvent newEvent = new BounceEvent(be.Timestamp);
                    newEvent.BounceReason = be.BounceReason;
                    newEvent.BounceType   = be.BounceType;
                    result = newEvent;
                }
                else if (e is DispatchFailedEvent dfe)
                {
                    DispatchFailedEvent newEvent = new DispatchFailedEvent(dfe.Timestamp);
                    newEvent.FailureReason = dfe.FailureReason;
                    result = newEvent;
                }
                else if (e is EmailClickedEvent ece)
                {
                    EmailClickedEvent newEvent = new EmailClickedEvent(ece.Timestamp);
                    newEvent.Url = ece.Url;
                    result       = newEvent;
                }
                else if (e is EmailOpenedEvent eoe)
                {
                    EmailOpenedEvent newEvent = new EmailOpenedEvent(eoe.Timestamp);
                    result = newEvent;
                }
                else if (e is EmailSentEvent ese)
                {
                    EmailSentEvent newEvent = new EmailSentEvent(ese.Timestamp);
                    result = newEvent;
                }
                else if (e is SpamComplaintEvent sce)
                {
                    SpamComplaintEvent newEvent = new SpamComplaintEvent(sce.Timestamp);
                    result = newEvent;
                }
                else if (e is UnsubscribedFromEmailEvent uee)
                {
                    UnsubscribedFromEmailEvent newEvent = new UnsubscribedFromEmailEvent(uee.Timestamp);
                    result = newEvent;
                }
                else
                {
                    result = new Event(e.DefinitionId, e.Timestamp);
                }

                // Many of the above are derived from EmailEvent, so only copy relevant properties once
                if (e is EmailEvent ee && result is EmailEvent nee)
                {
                    nee.EmailAddressHistoryEntryId = ee.EmailAddressHistoryEntryId;
                    nee.InstanceId      = ee.InstanceId;
                    nee.ManagerRootId   = ee.ManagerRootId;
                    nee.MessageId       = ee.MessageId;
                    nee.MessageLanguage = ee.MessageLanguage;
                    nee.TestValueIndex  = ee.TestValueIndex;
                }

                result.Data            = e.Data;
                result.DataKey         = e.DataKey;
                result.Duration        = e.Duration;
                result.EngagementValue = e.EngagementValue;
                result.Id            = e.Id;
                result.ParentEventId = e.ParentEventId;
                result.Text          = e.Text;
                foreach (KeyValuePair <string, string> customValue in e.CustomValues)
                {
                    result.CustomValues.Add(customValue.Key, customValue.Value);
                }

                if (result != null)
                {
                    target.Events.Add(result);
                }
            }
        }
Example #16
0
 private void HandleEvent(DownloadEvent eventID, string msg)
 {
     m_EventMsg = msg;
     m_Event.Push(eventID);
 }
        public ActionResult <GruntTasking> EditGruntTasking(int id, int tid, [FromBody] GruntTasking gruntTasking)
        {
            Grunt grunt = _context.Grunts.FirstOrDefault(G => G.Id == id);

            if (grunt == null)
            {
                return(NotFound($"NotFound - Grunt with id: {id}"));
            }
            GruntTasking updatingGruntTasking = _context.GruntTaskings.FirstOrDefault(GT => grunt.Id == GT.GruntId && tid == GT.Id);

            if (updatingGruntTasking == null)
            {
                return(NotFound($"NotFound - GruntTasking with id: {tid}"));
            }
            GruntTask gruntTask = _context.GruntTasks.FirstOrDefault(G => G.Id == gruntTasking.TaskId);

            if (gruntTask == null)
            {
                return(NotFound($"NotFound - GruntTask with id: {gruntTasking.TaskId}"));
            }
            GruntTask DownloadTask = _context.GruntTasks.FirstOrDefault(GT => GT.Name == "Download");

            if (DownloadTask == null)
            {
                return(NotFound($"NotFound - GruntTask DownloadTask"));
            }

            List <CapturedCredential> capturedCredentials = CapturedCredential.ParseCredentials(gruntTasking.GruntTaskOutput);

            foreach (CapturedCredential cred in capturedCredentials)
            {
                if (!ContextContainsCredentials(cred))
                {
                    _context.Credentials.Add(cred);
                    _context.SaveChanges();
                }
            }

            GruntTaskingStatus newStatus      = gruntTasking.Status;
            GruntTaskingStatus originalStatus = updatingGruntTasking.Status;

            if ((originalStatus == GruntTaskingStatus.Tasked || originalStatus == GruntTaskingStatus.Progressed) &&
                newStatus == GruntTaskingStatus.Completed)
            {
                if (gruntTasking.Type == GruntTaskingType.Kill)
                {
                    grunt.Status = Grunt.GruntStatus.Killed;
                }
                else if (gruntTasking.Type == GruntTaskingType.SetDelay || gruntTasking.Type == GruntTaskingType.SetJitter || gruntTasking.Type == GruntTaskingType.SetConnectAttempts)
                {
                    bool parsed = int.TryParse(gruntTasking.TaskingMessage, out int n);
                    if (parsed)
                    {
                        if (gruntTasking.Type == GruntTaskingType.SetDelay)
                        {
                            grunt.Delay = n;
                        }
                        else if (gruntTasking.Type == GruntTaskingType.SetJitter)
                        {
                            grunt.JitterPercent = n;
                        }
                        else if (gruntTasking.Type == GruntTaskingType.SetConnectAttempts)
                        {
                            grunt.ConnectAttempts = n;
                        }
                    }
                }
                else if (gruntTasking.Type == GruntTaskingType.Connect)
                {
                    if (originalStatus == GruntTaskingStatus.Tasked)
                    {
                        // Check if this Grunt was already connected
                        string hostname = gruntTasking.GruntTaskingMessage.Message.Split(",")[0];
                        string pipename = gruntTasking.GruntTaskingMessage.Message.Split(",")[1];
                        Grunt  previouslyConnectedGrunt = _context.Grunts.FirstOrDefault(G =>
                                                                                         G.CommType == Grunt.CommunicationType.SMB &&
                                                                                         (G.IPAddress == hostname || G.Hostname == hostname) &&
                                                                                         G.SMBPipeName == pipename &&
                                                                                         (G.Status == Grunt.GruntStatus.Disconnected || G.Status == Grunt.GruntStatus.Lost || G.Status == Grunt.GruntStatus.Active)
                                                                                         );
                        if (previouslyConnectedGrunt != null)
                        {
                            if (previouslyConnectedGrunt.Status != Grunt.GruntStatus.Disconnected)
                            {
                                // If already connected, disconnect to avoid cycles
                                Grunt previouslyConnectedGruntPrevParent = null;
                                foreach (Grunt g in _context.Grunts)
                                {
                                    if (g.Children.Contains(previouslyConnectedGrunt.GUID))
                                    {
                                        previouslyConnectedGruntPrevParent = g;
                                    }
                                }
                                if (previouslyConnectedGruntPrevParent != null)
                                {
                                    previouslyConnectedGruntPrevParent.RemoveChild(previouslyConnectedGrunt);
                                    _context.Grunts.Update(previouslyConnectedGruntPrevParent);
                                }
                            }

                            // Connect to tasked Grunt, no need to "Progress", as Grunt is already staged
                            grunt.AddChild(previouslyConnectedGrunt);
                            previouslyConnectedGrunt.Status = Grunt.GruntStatus.Active;
                            _context.Grunts.Update(previouslyConnectedGrunt);
                        }
                        else
                        {
                            // If not already connected, the Grunt is going to stage, set status to Progressed
                            newStatus = GruntTaskingStatus.Progressed;
                        }
                    }
                    else if (originalStatus == GruntTaskingStatus.Progressed)
                    {
                        // Connecting Grunt has staged, add as Child
                        string hostname     = gruntTasking.GruntTaskingMessage.Message.Split(",")[0];
                        string pipename     = gruntTasking.GruntTaskingMessage.Message.Split(",")[1];
                        Grunt  stagingGrunt = _context.Grunts.FirstOrDefault(G =>
                                                                             G.CommType == Grunt.CommunicationType.SMB &&
                                                                             ((G.IPAddress == hostname || G.Hostname == hostname) || (G.IPAddress == "" && G.Hostname == "")) &&
                                                                             G.SMBPipeName == pipename &&
                                                                             G.Status == Grunt.GruntStatus.Stage0
                                                                             );
                        if (stagingGrunt == null)
                        {
                            return(NotFound($"NotFound - Grunt staging from {hostname}:{pipename}"));
                        }
                        grunt.AddChild(stagingGrunt);
                    }
                }
                else if (gruntTasking.Type == GruntTaskingType.Disconnect)
                {
                    Grunt disconnectFromGrunt = _context.Grunts.FirstOrDefault(G => G.GUID == gruntTasking.GruntTaskingMessage.Message);
                    if (disconnectFromGrunt == null)
                    {
                        return(NotFound($"NotFound - Grunt with GUID: {gruntTasking.GruntTaskingMessage.Message}"));
                    }

                    disconnectFromGrunt.Status = Grunt.GruntStatus.Disconnected;
                    _context.Grunts.Update(disconnectFromGrunt);
                    grunt.RemoveChild(disconnectFromGrunt);
                }
            }

            if ((newStatus == GruntTaskingStatus.Completed || newStatus == GruntTaskingStatus.Progressed) && originalStatus != newStatus)
            {
                if (newStatus == GruntTaskingStatus.Completed)
                {
                    updatingGruntTasking.CompletionTime = DateTime.UtcNow;
                }
                string verb = newStatus == GruntTaskingStatus.Completed ? "completed" : "progressed";
                if (gruntTasking.TaskId == DownloadTask.Id)
                {
                    _context.Events.Add(new Event
                    {
                        Time          = updatingGruntTasking.CompletionTime,
                        MessageHeader = "[" + updatingGruntTasking.CompletionTime + " UTC] Grunt: " + grunt.Name + " has " + verb + " GruntTasking: " + gruntTasking.Name,
                        Level         = Event.EventLevel.Highlight,
                        Context       = grunt.Name
                    });
                    string        FileName      = Common.CovenantEncoding.GetString(Convert.FromBase64String(gruntTasking.TaskingMessage.Split(",")[1]));
                    DownloadEvent downloadEvent = new DownloadEvent
                    {
                        Time          = updatingGruntTasking.CompletionTime,
                        MessageHeader = "Downloaded: " + FileName + "\r\n" + "Syncing to Elite...",
                        Level         = Event.EventLevel.Highlight,
                        Context       = grunt.Name,
                        FileName      = FileName,
                        FileContents  = gruntTasking.GruntTaskOutput,
                        Progress      = DownloadEvent.DownloadProgress.Complete
                    };
                    downloadEvent.WriteToDisk();
                    _context.Events.Add(downloadEvent);
                }
                else
                {
                    _context.Events.Add(new Event
                    {
                        Time          = updatingGruntTasking.CompletionTime,
                        MessageHeader = "[" + updatingGruntTasking.CompletionTime + " UTC] Grunt: " + grunt.Name + " has " + verb + " GruntTasking: " + gruntTasking.Name,
                        MessageBody   = "(" + gruntTasking.TaskingUser + ") > " + gruntTasking.TaskingCommand + Environment.NewLine + gruntTasking.GruntTaskOutput,
                        Level         = Event.EventLevel.Highlight,
                        Context       = grunt.Name
                    });
                }
            }

            updatingGruntTasking.Status          = newStatus;
            updatingGruntTasking.GruntTaskOutput = gruntTasking.GruntTaskOutput;
            _context.GruntTaskings.Update(updatingGruntTasking);
            _context.Grunts.Update(grunt);
            _context.SaveChanges();

            return(updatingGruntTasking);
        }
Example #18
0
        private bool Login(string CovenantUsername, string CovenantPassword, string CovenantHash)
        {
            HttpClientHandler clientHandler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (sender, cert, chain, errors) =>
                {
                    // Cert Pinning - Trusts only the Covenant API certificate
                    return(CovenantHash == "" || cert.GetCertHashString() == CovenantHash);
                }
            };

            CovenantAPI LoginCovenantClient = new CovenantAPI(this.CovenantURI, new BasicAuthenticationCredentials {
                UserName = "", Password = ""
            }, clientHandler);

            try
            {
                CovenantUserLoginResult result = LoginCovenantClient.ApiUsersLoginPost(new CovenantUserLogin {
                    UserName = CovenantUsername, Password = CovenantPassword
                });
                if (result.Success ?? default)
                {
                    TokenCredentials creds          = new TokenCredentials(result.Token);
                    CovenantAPI      CovenantClient = new CovenantAPI(CovenantURI, creds, clientHandler);
                    this.EliteMenu = new EliteMenu(CovenantClient);
                    ReadLine.AutoCompletionHandler = this.EliteMenu.GetCurrentMenuItem().TabCompletionHandler;
                    this.EventPoller = new Task(() =>
                    {
                        int DelayMilliSeconds = 2000;
                        DateTime toDate       = DateTime.FromBinary(CovenantClient.ApiEventsTimeGet().Value);
                        DateTime fromDate;
                        while (true)
                        {
                            try
                            {
                                fromDate = toDate;
                                toDate   = DateTime.FromBinary(CovenantClient.ApiEventsTimeGet().Value);
                                IList <EventModel> events = CovenantClient.ApiEventsRangeByFromdateByTodateGet(fromDate.ToBinary(), toDate.ToBinary());
                                foreach (var anEvent in events)
                                {
                                    string context = this.EliteMenu.GetMenuLevelTitleStack();
                                    if (anEvent.Type == EventType.Normal)
                                    {
                                        if (this.EventPrinter.PrintEvent(anEvent, context))
                                        {
                                            this.EliteMenu.PrintMenuLevel();
                                        }
                                    }
                                    else if (anEvent.Type == EventType.Download)
                                    {
                                        DownloadEvent downloadEvent = CovenantClient.ApiEventsDownloadByIdGet(anEvent.Id ?? default);
                                        File.WriteAllBytes(Path.Combine(Common.EliteDownloadsFolder, downloadEvent.FileName), Convert.FromBase64String(downloadEvent.FileContents));
                                    }
                                }
                                Thread.Sleep(DelayMilliSeconds);
                            }
                            catch (Exception) { }
                        }
                    }, this.CancelEventPoller.Token);
                }
                else
                {
                    return(false);
                }
            }
            catch (HttpOperationException)
            {
                return(false);
            }
            return(true);
        }