protected override void Initialize()
        {
            base.Initialize();

            _grenadesContainer = ContainerHelpers.EnsureContainer <Container>(Owner, "cluster-flash");
        }
Beispiel #2
0
        public override void Initialize()
        {
            base.Initialize();

            _lightBulbContainer = ContainerHelpers.EnsureContainer <ContainerSlot>(Owner, "light_bulb");
        }
        public async Task InsideContainerInteractionBlockTest()
        {
            var server = StartServerDummyTicker(new ServerContentIntegrationOption
            {
                ContentBeforeIoC = () =>
                {
                    IoCManager.Resolve <IEntitySystemManager>().LoadExtraSystemType <TestInteractionSystem>();
                },
                FailureLogLevel = Robust.Shared.Log.LogLevel.Error
            });

            await server.WaitIdleAsync();

            var entityManager = server.ResolveDependency <IEntityManager>();
            var mapManager    = server.ResolveDependency <IMapManager>();

            var mapId  = MapId.Nullspace;
            var coords = MapCoordinates.Nullspace;

            server.Assert(() =>
            {
                mapId  = mapManager.CreateMap();
                coords = new MapCoordinates(Vector2.Zero, mapId);
            });

            await server.WaitIdleAsync();

            IEntity    user            = null;
            IEntity    target          = null;
            IEntity    item            = null;
            IEntity    containerEntity = null;
            IContainer container       = null;

            server.Assert(() =>
            {
                user = entityManager.SpawnEntity(null, coords);
                user.EnsureComponent <HandsComponent>().AddHand("hand", HandLocation.Left);
                target = entityManager.SpawnEntity(null, coords);
                item   = entityManager.SpawnEntity(null, coords);
                item.EnsureComponent <ItemComponent>();
                containerEntity = entityManager.SpawnEntity(null, coords);
                container       = ContainerHelpers.EnsureContainer <Container>(containerEntity, "InteractionTestContainer");
            });

            await server.WaitRunTicks(1);

            var entitySystemManager = server.ResolveDependency <IEntitySystemManager>();

            Assert.That(entitySystemManager.TryGetEntitySystem <InteractionSystem>(out var interactionSystem));
            Assert.That(entitySystemManager.TryGetEntitySystem <TestInteractionSystem>(out var testInteractionSystem));

            await server.WaitIdleAsync();

            var attack        = false;
            var interactUsing = false;
            var interactHand  = false;

            server.Assert(() =>
            {
                Assert.That(container.Insert(user));
                Assert.That(user.Transform.Parent.Owner, Is.EqualTo(containerEntity));

                testInteractionSystem.AttackEvent        = (_, _, ev) => { Assert.That(ev.Target, Is.EqualTo(containerEntity.Uid)); attack = true; };
                testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(containerEntity)); interactUsing = true; };
                testInteractionSystem.InteractHandEvent  = (ev) => { Assert.That(ev.Target, Is.EqualTo(containerEntity)); interactHand = true; };

                interactionSystem.DoAttack(user, target.Transform.Coordinates, false, target.Uid);
                interactionSystem.UserInteraction(user, target.Transform.Coordinates, target.Uid);
                Assert.That(attack, Is.False);
                Assert.That(interactUsing, Is.False);
                Assert.That(interactHand, Is.False);

                interactionSystem.DoAttack(user, containerEntity.Transform.Coordinates, false, containerEntity.Uid);
                interactionSystem.UserInteraction(user, containerEntity.Transform.Coordinates, containerEntity.Uid);
                Assert.That(attack);
                Assert.That(interactUsing, Is.False);
                Assert.That(interactHand);

                Assert.That(user.TryGetComponent <HandsComponent>(out var hands));
                Assert.That(hands.PutInHand(item.GetComponent <ItemComponent>()));

                interactionSystem.UserInteraction(user, target.Transform.Coordinates, target.Uid);
                Assert.That(interactUsing, Is.False);

                interactionSystem.UserInteraction(user, containerEntity.Transform.Coordinates, containerEntity.Uid);
                Assert.That(interactUsing, Is.True);
            });

            await server.WaitIdleAsync();
        }
Beispiel #4
0
        public async Task <HandlerResponse <bool> > Handle(DeleteFileRequest request, CancellationToken cancellationToken)
        {
            var section = await _dataContext.ApplicationSections.FirstOrDefaultAsync(sec => sec.Id == request.SectionId && sec.ApplicationId == request.ApplicationId, cancellationToken);

            if (section == null)
            {
                return(new HandlerResponse <bool>(success: false, message: $"Section {request.SectionId} in Application {request.ApplicationId} does not exist."));
            }

            var qnaData = new QnAData(section.QnAData);
            var page    = qnaData.Pages.FirstOrDefault(p => p.PageId == request.PageId);

            if (page == null)
            {
                return(new HandlerResponse <bool>(success: false, message: $"Page {request.PageId} in Application {request.ApplicationId} does not exist."));
            }

            if (page.Questions.All(q => q.Input.Type != "FileUpload"))
            {
                return(new HandlerResponse <bool>(success: false, message: $"Page {request.PageId} in Application {request.ApplicationId} does not contain any File Upload questions."));
            }

            if (page.PageOfAnswers == null || !page.PageOfAnswers.Any())
            {
                return(new HandlerResponse <bool>(success: false, message: $"Page {request.PageId} in Application {request.ApplicationId} does not contain any uploads."));
            }

            var container = await ContainerHelpers.GetContainer(_fileStorageConfig.Value.StorageConnectionString, _fileStorageConfig.Value.ContainerName);

            var directory = ContainerHelpers.GetDirectory(request.ApplicationId, section.SequenceId, request.SectionId, request.PageId, request.QuestionId, container);

            var answer = page.PageOfAnswers.SingleOrDefault(poa => poa.Answers.Any(a => a.QuestionId == request.QuestionId && a.Value == request.FileName));

            if (answer is null)
            {
                return(new HandlerResponse <bool>(success: false, message: $"Question {request.QuestionId} on Page {request.PageId} in Application {request.ApplicationId} does not contain an upload named {request.FileName}."));
            }

            page.PageOfAnswers.Remove(answer);

            if (page.PageOfAnswers.Count == 0)
            {
                page.Complete = false;
                if (page.HasFeedback)
                {
                    foreach (var feedback in page.Feedback.Where(feedback => feedback.IsNew).Select(feedback => feedback))
                    {
                        feedback.IsCompleted = false;
                    }
                }
            }
            else
            {
                var answers = page.PageOfAnswers?.SelectMany(p => p.Answers);
                if (answers != null)
                {
                    var validationErrors = _answerValidator.Validate(answers.ToList(), page);
                    if (validationErrors != null && validationErrors.Any())
                    {
                        page.Complete = false;
                    }
                }
            }

            section.QnAData = qnaData;
            await _dataContext.SaveChangesAsync(cancellationToken);

            var blobRef = directory.GetBlobReference(request.FileName);
            await blobRef.DeleteAsync(cancellationToken);

            await RemoveApplicationDataForThisQuestion(request.ApplicationId, request.QuestionId, page);

            return(new HandlerResponse <bool>(true));
        }
Beispiel #5
0
        public async Task PerformAction(IEntity entity, IEntity?user)
        {
            if (!entity.TryGetComponent(out ContainerManagerComponent? containerManager))
            {
                Logger.Warning($"Machine frame entity {entity} did not have a container manager! Aborting build machine action.");
                return;
            }

            if (!entity.TryGetComponent(out MachineFrameComponent? machineFrame))
            {
                Logger.Warning($"Machine frame entity {entity} did not have a machine frame component! Aborting build machine action.");
                return;
            }

            if (!machineFrame.IsComplete)
            {
                Logger.Warning($"Machine frame entity {entity} doesn't have all required parts to be built! Aborting build machine action.");
                return;
            }

            if (!containerManager.TryGetContainer(MachineFrameComponent.BoardContainer, out var entBoardContainer))
            {
                Logger.Warning($"Machine frame entity {entity} did not have the '{MachineFrameComponent.BoardContainer}' container! Aborting build machine action.");
                return;
            }

            if (!containerManager.TryGetContainer(MachineFrameComponent.PartContainer, out var entPartContainer))
            {
                Logger.Warning($"Machine frame entity {entity} did not have the '{MachineFrameComponent.PartContainer}' container! Aborting build machine action.");
                return;
            }

            if (entBoardContainer.ContainedEntities.Count != 1)
            {
                Logger.Warning($"Machine frame entity {entity} did not have exactly one item in the '{MachineFrameComponent.BoardContainer}' container! Aborting build machine action.");
            }

            var board = entBoardContainer.ContainedEntities[0];

            if (!board.TryGetComponent(out MachineBoardComponent? boardComponent))
            {
                Logger.Warning($"Machine frame entity {entity} had an invalid entity in container \"{MachineFrameComponent.BoardContainer}\"! Aborting build machine action.");
                return;
            }

            var entityManager = entity.EntityManager;

            entBoardContainer.Remove(board);

            var machine = entityManager.SpawnEntity(boardComponent.Prototype, entity.Transform.Coordinates);

            machine.Transform.LocalRotation = entity.Transform.LocalRotation;

            var boardContainer = ContainerHelpers.EnsureContainer <Container>(machine, MachineFrameComponent.BoardContainer, out var existed);

            if (existed)
            {
                // Clean that up...
                boardContainer.CleanContainer();
            }

            var partContainer = ContainerHelpers.EnsureContainer <Container>(machine, MachineFrameComponent.PartContainer, out existed);

            if (existed)
            {
                // Clean that up, too...
                partContainer.CleanContainer();
            }

            boardContainer.Insert(board);

            // Now we insert all parts.
            foreach (var part in entPartContainer.ContainedEntities.ToArray())
            {
                entPartContainer.ForceRemove(part);
                partContainer.Insert(part);
            }

            if (machine.TryGetComponent(out ConstructionComponent? construction))
            {
                // We only add these two container. If some construction needs to take other containers into account, fix this.
                construction.AddContainer(MachineFrameComponent.BoardContainer);
                construction.AddContainer(MachineFrameComponent.PartContainer);
            }

            if (machine.TryGetComponent(out MachineComponent? machineComp))
            {
                machineComp.RefreshParts();
            }

            entity.Delete();
        }
Beispiel #6
0
 protected override void Initialize()
 {
     base.Initialize();
     _itemContainer = ContainerHelpers.EnsureContainer <ContainerSlot>(Owner, "stash", out _);
 }
Beispiel #7
0
 protected override void Initialize()
 {
     base.Initialize();
     _cellContainer = ContainerHelpers.EnsureContainer <ContainerSlot>(Owner, "cellslot_cell_container", out _);
 }
 private void OnInit(EntityUid uid, LightReplacerComponent replacer, ComponentInit args)
 {
     replacer.InsertedBulbs = ContainerHelpers.EnsureContainer <Container>(replacer.Owner, "light_replacer_storage");
 }
 protected override void Initialize()
 {
     base.Initialize();
     _appearance?.SetData(BodyBagVisuals.Label, false);
     LabelContainer = ContainerHelpers.EnsureContainer <ContainerSlot>(Owner, "body_bag_label", out _);
 }
 protected override void Initialize()
 {
     base.Initialize();
     Appearance?.SetData(MorgueVisuals.Open, false);
     TrayContainer = ContainerHelpers.EnsureContainer <ContainerSlot>(Owner, "morgue_tray", out _);
 }
Beispiel #11
0
        public async Task InsideContainerInteractionBlockTest()
        {
            var server = StartServerDummyTicker(new ServerContentIntegrationOption
            {
                ContentBeforeIoC = () =>
                {
                    IoCManager.Resolve <IEntitySystemManager>().LoadExtraSystemType <TestAttackEntitySystem>();
                }
            });

            await server.WaitIdleAsync();

            var entityManager = server.ResolveDependency <IEntityManager>();
            var mapManager    = server.ResolveDependency <IMapManager>();

            IEntity    origin          = null;
            IEntity    other           = null;
            IEntity    containerEntity = null;
            IContainer container       = null;

            server.Assert(() =>
            {
                var mapId       = mapManager.CreateMap();
                var coordinates = new MapCoordinates(Vector2.Zero, mapId);

                origin = entityManager.SpawnEntity(null, coordinates);
                origin.EnsureComponent <HandsComponent>();
                other           = entityManager.SpawnEntity(null, coordinates);
                containerEntity = entityManager.SpawnEntity(null, coordinates);
                container       = ContainerHelpers.EnsureContainer <Container>(containerEntity, "InteractionTestContainer");
            });

            await server.WaitIdleAsync();

            var attack        = false;
            var interactUsing = false;
            var interactHand  = false;

            server.Assert(() =>
            {
                Assert.That(container.Insert(origin));
                Assert.That(origin.Transform.Parent !.Owner, Is.EqualTo(containerEntity));

                var entitySystemManager = IoCManager.Resolve <IEntitySystemManager>();
                Assert.That(entitySystemManager.TryGetEntitySystem <InteractionSystem>(out var interactionSystem));

                Assert.That(entitySystemManager.TryGetEntitySystem <TestAttackEntitySystem>(out var testAttackEntitySystem));
                testAttackEntitySystem.AttackEvent = (ev) =>
                {
                    Assert.That(ev.Target, Is.EqualTo(containerEntity.Uid));
                    attack = true;
                };
                testAttackEntitySystem.InteractUsingEvent = (ev) =>
                {
                    Assert.That(ev.Attacked, Is.EqualTo(containerEntity));
                    interactUsing = true;
                };
                testAttackEntitySystem.InteractHandEvent = (ev) =>
                {
                    Assert.That(ev.Attacked, Is.EqualTo(containerEntity));
                    interactHand = true;
                };

                interactionSystem.DoAttack(origin, other.Transform.Coordinates, false, other.Uid);
                interactionSystem.UserInteraction(origin, other.Transform.Coordinates, other.Uid);
                Assert.That(attack, Is.False);
                Assert.That(interactUsing, Is.False);
                Assert.That(interactHand, Is.False);

                interactionSystem.DoAttack(origin, containerEntity.Transform.Coordinates, false, containerEntity.Uid);
                interactionSystem.UserInteraction(origin, containerEntity.Transform.Coordinates, containerEntity.Uid);
                Assert.That(attack);
                Assert.That(interactUsing, Is.False);
                Assert.That(interactHand);

                var itemEntity = entityManager.SpawnEntity(null, origin.Transform.Coordinates);
                var item       = itemEntity.EnsureComponent <ItemComponent>();

                Assert.That(origin.TryGetComponent <HandsComponent>(out var hands));
                hands.PutInHand(item);

                interactionSystem.UserInteraction(origin, other.Transform.Coordinates, other.Uid);
                Assert.That(interactUsing, Is.False);

                interactionSystem.UserInteraction(origin, containerEntity.Transform.Coordinates, containerEntity.Uid);
                Assert.That(interactUsing);
            });
        }
Beispiel #12
0
        public void Render()
        {
            var size = ScreenSize;

            if (size.X == 0 || size.Y == 0)
            {
                return;
            }

            _debugStats.Reset();

            // Basic pre-render busywork.
            // Clear screen to black.
            ClearFramebuffer(Color.Black);

            // Update shared UBOs.
            _updateUniformConstants();

            SetSpaceFull(CurrentSpace.ScreenSpace);

            // Short path to render only the splash.
            if (_drawingSplash)
            {
                _drawSplash(_renderHandle);
                FlushRenderQueue();
                SwapBuffers();
                return;
            }

            void RenderOverlays(OverlaySpace space)
            {
                using (DebugGroup($"Overlays: {space}"))
                {
                    foreach (var overlay in _overlayManager.AllOverlays
                             .Where(o => o.Space == space)
                             .OrderBy(o => o.ZIndex))
                    {
                        overlay.ClydeRender(_renderHandle);
                    }

                    FlushRenderQueue();
                }
            }

            RenderOverlays(OverlaySpace.ScreenSpaceBelowWorld);

            SetSpaceFull(CurrentSpace.WorldSpace);

            // Calculate world-space AABB for camera, to cull off-screen things.
            var eye         = _eyeManager.CurrentEye;
            var worldBounds = Box2.CenteredAround(eye.Position.Position,
                                                  _screenSize / EyeManager.PIXELSPERMETER * eye.Zoom);

            using (DebugGroup("Lights"))
            {
                _drawLights(worldBounds);
            }

            using (DebugGroup("Grids"))
            {
                _drawGrids(worldBounds);
            }

            using (DebugGroup("Entities"))
            {
                _sortingSpritesList.Clear();
                var map = _eyeManager.CurrentMap;

                // So we could calculate the correct size of the entities based on the contents of their sprite...
                // Or we can just assume that no entity is larger than 10x10 and get a stupid easy check.
                // TODO: Make this check more accurate.
                var widerBounds = worldBounds.Enlarged(5);

                foreach (var sprite in _componentManager.GetAllComponents <SpriteComponent>())
                {
                    var entity = sprite.Owner;
                    if (entity.Transform.MapID != map || !widerBounds.Contains(entity.Transform.WorldPosition) || !sprite.Visible)
                    {
                        continue;
                    }

                    if (ContainerHelpers.TryGetContainer(entity, out var container) && !container.ShowContents)
                    {
                        continue;
                    }

                    _sortingSpritesList.Add(sprite);
                }

                _sortingSpritesList.Sort((a, b) =>
                {
                    var cmp = ((int)a.DrawDepth).CompareTo((int)b.DrawDepth);
                    if (cmp != 0)
                    {
                        return(cmp);
                    }

                    cmp = a.RenderOrder.CompareTo(b.RenderOrder);

                    if (cmp != 0)
                    {
                        return(cmp);
                    }

                    return(a.Owner.Uid.CompareTo(b.Owner.Uid));
                });

                foreach (var sprite in _sortingSpritesList)
                {
                    Vector2i roundedPos = default;
                    if (sprite.PostShader != null)
                    {
                        _renderHandle.UseRenderTarget(EntityPostRenderTarget);
                        _renderHandle.Clear(new Color());
                        // Calculate viewport so that the entity thinks it's drawing to the same position,
                        // which is necessary for light application,
                        // but it's ACTUALLY drawing into the center of the render target.
                        var spritePos = sprite.Owner.Transform.WorldPosition;
                        var screenPos = _eyeManager.WorldToScreen(spritePos);
                        var(roundedX, roundedY) = roundedPos = (Vector2i)screenPos;
                        var flippedPos = new Vector2i(roundedX, ScreenSize.Y - roundedY);
                        flippedPos -= EntityPostRenderTarget.Size / 2;
                        _renderHandle.Viewport(Box2i.FromDimensions(-flippedPos, ScreenSize));
                    }

                    sprite.OpenGLRender(_renderHandle.DrawingHandleWorld);

                    if (sprite.PostShader != null)
                    {
                        _renderHandle.UseRenderTarget(null);
                        _renderHandle.Viewport(Box2i.FromDimensions(Vector2i.Zero, ScreenSize));

                        _renderHandle.UseShader(sprite.PostShader);
                        _renderHandle.SetSpace(CurrentSpace.ScreenSpace);
                        _renderHandle.SetModelTransform(Matrix3.Identity);

                        var rounded = roundedPos - EntityPostRenderTarget.Size / 2;

                        var box = UIBox2i.FromDimensions(rounded, EntityPostRenderTarget.Size);

                        _renderHandle.DrawTexture(EntityPostRenderTarget.Texture, box.BottomLeft,
                                                  box.TopRight, Color.White, null, 0);

                        _renderHandle.SetSpace(CurrentSpace.WorldSpace);
                        _renderHandle.UseShader(null);
                    }
                }

                FlushRenderQueue();
            }

            RenderOverlays(OverlaySpace.WorldSpace);

            _lightingReady = false;

            SetSpaceFull(CurrentSpace.ScreenSpace);

            RenderOverlays(OverlaySpace.ScreenSpace);

            using (DebugGroup("UI"))
            {
                _userInterfaceManager.Render(_renderHandle);
                FlushRenderQueue();
            }

            // And finally, swap those buffers!
            SwapBuffers();
        }
 public AzureBackupContainerContextObject(AzurePSBackupVault vault, MarsContainerResponse marsContainerResponse)
     : base(vault)
 {
     ContainerType = ContainerHelpers.GetContainerType(marsContainerResponse.Properties.CustomerType).ToString();
     //ContainerUniqueName = marsContainerResponse.UniqueName;
 }
 private static async Task <CloudBlobContainer> GetContainer(IOptions <FileStorageConfig> config)
 {
     return(await ContainerHelpers.GetContainer(config.Value.StorageConnectionString, config.Value.ContainerName));
 }
Beispiel #15
0
        public static void Main(string[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            var options = new Options();

            if (!Parser.Default.ParseArguments(args, options))
            {
                return;
            }

            var collectionMethods = new List <CollectionMethod>();

            if (options.CollectionMethod.Length == 1)
            {
                options.CollectionMethod = options.CollectionMethod[0].Split(',');
            }

            if (options.Jitter > 100 || options.Jitter < 0)
            {
                Console.WriteLine("Jitter must be a value between 0 and 100!");
                return;
            }

            if (options.Throttle < 0)
            {
                Console.WriteLine("Throttle must be 0 or greater!");
                return;
            }

            foreach (var unparsed in options.CollectionMethod)
            {
                try
                {
                    var e = (CollectionMethod)Enum.Parse(typeof(CollectionMethod), unparsed, true);
                    collectionMethods.Add(e);
                }
                catch
                {
                    Console.WriteLine($"Failed to parse value {unparsed}. Check your values for CollectionMethods!");
                    return;
                }
            }

            if (options.Debug)
            {
                Console.WriteLine("Debug Mode activated!");
                options.Threads = 1;
            }

            if (options.MaxLoopTime != null && options.CurrentCollectionMethod.Equals(SessionLoop))
            {
                var regex     = new Regex("[0-9]+[smdh]");
                var matches   = regex.Matches(options.MaxLoopTime);
                var numregex  = new Regex("[0-9]+");
                var timeregex = new Regex("[smdh]");
                if (matches.Count == 0)
                {
                    Console.WriteLine("LoopEndTime does not match required format");
                    return;
                }

                var now   = DateTime.Now;
                var drift = 0;
                foreach (var match in matches)
                {
                    var num  = int.Parse(numregex.Match(match.ToString()).Value);
                    var spec = timeregex.Match(match.ToString());

                    switch (spec.Value)
                    {
                    case "s":
                        now    = now.AddSeconds(num);
                        drift += num;
                        break;

                    case "m":
                        now    = now.AddMinutes(num);
                        drift += num * 60;
                        break;

                    case "h":
                        now    = now.AddHours(num);
                        drift += num * 60 * 60;
                        break;

                    case "d":
                        now    = now.AddDays(num);
                        drift += num * 60 * 60 * 24;
                        break;
                    }
                }

                options.LoopEnd = now;

                if (drift == 0)
                {
                    Console.WriteLine("LoopEndTime is zero! Specify a real value");
                    return;
                }
            }

            options.CurrentUser = WindowsIdentity.GetCurrent().Name.Split('\\')[1];
            var nowtime = DateTime.Now;

            Console.WriteLine($"Initializing BloodHound at {nowtime.ToShortTimeString()} on {nowtime.ToShortDateString()}");
            Cache.CreateInstance(options);
            Utils.CreateInstance(options);

            if (!Utils.CheckWritePrivs())
            {
                Console.WriteLine("Unable to write in chosen directory. Please check privs");
                return;
            }

            SessionHelpers.Init(options);
            LocalAdminHelpers.Init();
            GroupHelpers.Init();
            AclHelpers.Init();
            DomainTrustEnumeration.Init();
            ContainerHelpers.Init();

            if (options.Test != null)
            {
                Test.DoStuff(options.Test);
                return;
            }

            //Lets test our connection to LDAP before we do anything else
            try
            {
                using (var conn = Utils.Instance.GetLdapConnection(options.Domain))
                {
                    if (conn == null)
                    {
                        Console.WriteLine("LDAP connection test failed, probably can't contact domain");
                        return;
                    }
                    conn.Bind();
                }
            }
            catch (LdapException)
            {
                Console.WriteLine("Ldap Connection Failure.");
                Console.WriteLine("Try again with the IgnoreLdapCert option if using SecureLDAP or check your DomainController option");
                return;
            }

            if (options.Uri != null)
            {
                if (!options.Uri.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                {
                    Console.WriteLine("URI must start with http:// or https://");
                    return;
                }

                using (var client = new WebClient())
                {
                    client.Headers.Add("content-type", "application/json");
                    client.Headers.Add("Accept", "application/json; charset=UTF-8");

                    if (options.UserPass != null)
                    {
                        client.Headers.Add("Authorization", options.GetEncodedUserPass());
                    }

                    try
                    {
                        client.DownloadData(options.GetCheckURI());
                        Console.WriteLine("Successfully connected to the Neo4j REST endpoint.");
                    }
                    catch
                    {
                        Console.WriteLine("Unable to connect to the Neo4j REST endpoint. Check your URI and username/password");
                        return;
                    }
                }
            }

            if (options.RemoveCSV && !options.CompressData)
            {
                Console.WriteLine("Ignoring RemoveCSV as CompressData is not set");
                options.RemoveCSV = false;
            }

            if (options.Stealth)
            {
                Console.WriteLine("Note: All stealth options are single threaded");
            }

            if (options.Throttle > 0)
            {
                Console.WriteLine(
                    $"Adding a delay of {options.Throttle} milliseconds to computer requests with a jitter of {options.Jitter}%");
            }

            foreach (var cmethod in collectionMethods)
            {
                options.CurrentCollectionMethod = cmethod;
                if (options.ComputerFile != null)
                {
                    if (!File.Exists(options.ComputerFile))
                    {
                        Console.WriteLine("Specified ComputerFile does not exist!");
                        return;
                    }

                    if (options.CurrentCollectionMethod.Equals(Default))
                    {
                        options.CurrentCollectionMethod = ComputerOnly;
                        Console.WriteLine("ComputerFile detected with default enumeration. Switching to ComputerOnly collection method");
                    }

                    if (!(options.CurrentCollectionMethod.Equals(Session) || options.CurrentCollectionMethod.Equals(SessionLoop) ||
                          options.CurrentCollectionMethod.Equals(LoggedOn) || options.CurrentCollectionMethod.Equals(LocalGroup) ||
                          options.CurrentCollectionMethod.Equals(ComputerOnly)))
                    {
                        Console.WriteLine("ComputerFile can only be used with the following collection methods: ComputerOnly, Session, SessionLoop, LocalGroup, LoggedOn");
                        continue;
                    }
                }

                if (options.CurrentCollectionMethod.Equals(LocalGroup) && options.Stealth)
                {
                    Console.WriteLine("Note: You specified Stealth and LocalGroup which is equivalent to GPOLocalGroup");
                    options.CurrentCollectionMethod = GPOLocalGroup;
                }

                var runner = new EnumerationRunner(options);

                if (options.CurrentCollectionMethod.Equals(SessionLoop))
                {
                    Console.WriteLine(options.MaxLoopTime == null
                        ? "Session Loop mode specified without MaxLoopTime, will loop indefinitely"
                        : $"Session Loop mode specified. Looping will end on {options.LoopEnd.ToShortDateString()} at {options.LoopEnd.ToShortTimeString()}");
                }

                if (options.Stealth)
                {
                    runner.StartStealthEnumeration();
                }
                else
                {
                    runner.StartEnumeration();
                }
                Console.WriteLine();
            }

            Cache.Instance.SaveCache();

            Utils.DeduplicateFiles();

            if (options.CompressData)
            {
                Utils.CompressFiles();
            }
        }
Beispiel #16
0
        public void CreateBoardAndStockParts()
        {
            // Entity might not be initialized yet.
            var boardContainer = ContainerHelpers.EnsureContainer <Container>(Owner, MachineFrameComponent.BoardContainer, out var existedBoard);
            var partContainer  = ContainerHelpers.EnsureContainer <Container>(Owner, MachineFrameComponent.PartContainer, out var existedParts);

            if (string.IsNullOrEmpty(BoardPrototype))
            {
                return;
            }

            var entityManager = Owner.EntityManager;

            if (existedBoard || existedParts)
            {
                // We're done here, let's suppose all containers are correct just so we don't screw SaveLoadSave.
                if (boardContainer.ContainedEntities.Count > 0)
                {
                    return;
                }
            }

            var board = entityManager.SpawnEntity(BoardPrototype, Owner.Transform.Coordinates);

            if (!_boardContainer.Insert(board))
            {
                throw new Exception($"Couldn't insert board with prototype {BoardPrototype} to machine with prototype {Owner.Prototype?.ID ?? "N/A"}!");
            }

            if (!board.TryGetComponent <MachineBoardComponent>(out var machineBoard))
            {
                throw new Exception($"Entity with prototype {BoardPrototype} doesn't have a {nameof(MachineBoardComponent)}!");
            }

            foreach (var(part, amount) in machineBoard.Requirements)
            {
                for (var i = 0; i < amount; i++)
                {
                    var p = entityManager.SpawnEntity(MachinePartComponent.Prototypes[part], Owner.Transform.Coordinates);

                    if (!partContainer.Insert(p))
                    {
                        throw new Exception($"Couldn't insert machine part of type {part} to machine with prototype {Owner.Prototype?.ID ?? "N/A"}!");
                    }
                }
            }

            foreach (var(stackType, amount) in machineBoard.MaterialRequirements)
            {
                var s = StackHelpers.SpawnStack(stackType, amount, Owner.Transform.Coordinates);

                if (!partContainer.Insert(s))
                {
                    throw new Exception($"Couldn't insert machine material of type {stackType} to machine with prototype {Owner.Prototype?.ID ?? "N/A"}");
                }
            }

            foreach (var(compName, info) in machineBoard.ComponentRequirements)
            {
                for (var i = 0; i < info.Amount; i++)
                {
                    var c = entityManager.SpawnEntity(info.DefaultPrototype, Owner.Transform.Coordinates);

                    if (!partContainer.Insert(c))
                    {
                        throw new Exception($"Couldn't insert machine component part with default prototype '{compName}' to machine with prototype {Owner.Prototype?.ID ?? "N/A"}");
                    }
                }
            }
        }
Beispiel #17
0
        private static void HandleMovement(IMapManager mapManager, ITileDefinitionManager tileDefinitionManager, IEntity entity, float frameTime)
        {
            if (entity.Deleted)
            {
                // Ugh let's hope this fixes the crashes.
                return;
            }

            var velocity = entity.GetComponent <PhysicsComponent>();

            if (velocity.DidMovementCalculations)
            {
                velocity.DidMovementCalculations = false;
                return;
            }

            if (velocity.AngularVelocity == 0 && velocity.LinearVelocity == Vector2.Zero)
            {
                return;
            }

            var transform = entity.Transform;

            if (ContainerHelpers.IsInContainer(transform.Owner))
            {
                transform.Parent.Owner.SendMessage(transform, new RelayMovementEntityMessage(entity));
                velocity.LinearVelocity = Vector2.Zero;
                return;
            }

            var     velocityConsumers = velocity.GetVelocityConsumers();
            var     initialMovement   = velocity.LinearVelocity;
            int     velocityConsumerCount;
            float   totalMass;
            Vector2 lowestMovement;

            do
            {
                velocityConsumerCount = velocityConsumers.Count;
                totalMass             = 0;
                lowestMovement        = initialMovement;
                var copy = new List <Vector2>(velocityConsumers.Count);
                foreach (var consumer in velocityConsumers)
                {
                    totalMass += consumer.Mass;
                    var movement = lowestMovement * velocity.Mass / (totalMass != 0 ? totalMass : 1);
                    consumer.AngularVelocity = velocity.AngularVelocity;
                    consumer.LinearVelocity  = movement;
                    copy.Add(CalculateMovement(tileDefinitionManager, mapManager, consumer, frameTime, consumer.Owner) / frameTime);
                }

                copy.Sort(LengthComparer);
                lowestMovement    = copy[0];
                velocityConsumers = velocity.GetVelocityConsumers();
            } while (velocityConsumers.Count != velocityConsumerCount);

            velocity.ClearVelocityConsumers();

            foreach (var consumer in velocityConsumers)
            {
                consumer.LinearVelocity          = lowestMovement;
                consumer.DidMovementCalculations = true;
            }

            velocity.DidMovementCalculations = false;
        }
Beispiel #18
0
        public static void Main(string[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            var options = new Options();

            if (!Parser.Default.ParseArguments(args, options))
            {
                return;
            }

            if (options.Debug)
            {
                Console.WriteLine("Debug Mode activated!");
                options.Threads = 1;
            }

            if (options.MaxLoopTime != null && options.CollectMethod.Equals(SessionLoop))
            {
                var regex     = new Regex("[0-9]+[smdh]");
                var matches   = regex.Matches(options.MaxLoopTime);
                var numregex  = new Regex("[0-9]+");
                var timeregex = new Regex("[smdh]");
                if (matches.Count == 0)
                {
                    Console.WriteLine("LoopEndTime does not match required format");
                    return;
                }

                var now   = DateTime.Now;
                var drift = 0;
                foreach (var match in matches)
                {
                    var num  = int.Parse(numregex.Match(match.ToString()).Value);
                    var spec = timeregex.Match(match.ToString());

                    switch (spec.Value)
                    {
                    case "s":
                        now    = now.AddSeconds(num);
                        drift += num;
                        break;

                    case "m":
                        now    = now.AddMinutes(num);
                        drift += num * 60;
                        break;

                    case "h":
                        now    = now.AddHours(num);
                        drift += num * 60 * 60;
                        break;

                    case "d":
                        now    = now.AddDays(num);
                        drift += num * 60 * 60 * 24;
                        break;
                    }
                }

                options.LoopEnd = now;

                if (drift == 0)
                {
                    Console.WriteLine("LoopEndTime is zero! Specify a real value");
                    return;
                }
            }



            options.CurrentUser = WindowsIdentity.GetCurrent().Name.Split('\\')[1];
            var nowtime = DateTime.Now;

            Console.WriteLine($"Initializing BloodHound at {nowtime.ToShortTimeString()} on {nowtime.ToShortDateString()}");
            Cache.CreateInstance(options);
            Utils.CreateInstance(options);

            if (!Utils.CheckWritePrivs())
            {
                Console.WriteLine("Unable to write in chosen directory. Please check privs");
                return;
            }

            SessionHelpers.Init(options);
            LocalAdminHelpers.Init();
            GroupHelpers.Init();
            AclHelpers.Init();
            DomainTrustEnumeration.Init();
            ContainerHelpers.Init();

            if (options.Test != null)
            {
                Test.DoStuff(options.Test);
                return;
            }

            if (options.ComputerFile != null)
            {
                if (!File.Exists(options.ComputerFile))
                {
                    Console.WriteLine("Specified ComputerFile does not exist!");
                    return;
                }

                if (options.CollectMethod.Equals(Default))
                {
                    options.CollectMethod = ComputerOnly;
                    Console.WriteLine("ComputerFile detected with default enumeration. Switching to ComputerOnly collection method");
                }

                if (!(options.CollectMethod.Equals(Session) || options.CollectMethod.Equals(SessionLoop) ||
                      options.CollectMethod.Equals(LoggedOn) || options.CollectMethod.Equals(LocalGroup) ||
                      options.CollectMethod.Equals(ComputerOnly)))
                {
                    Console.WriteLine("ComputerFile can only be used with the following collection methods: ComputerOnly, Session, SessionLoop, LocalGroup, LoggedOn");
                    return;
                }
            }

            //Lets test our connection to LDAP before we do anything else
            try
            {
                using (var conn = Utils.Instance.GetLdapConnection(options.Domain))
                {
                    if (conn == null)
                    {
                        Console.WriteLine("LDAP Connection Test failed. Exiting");
                        return;
                    }
                    conn.Bind();
                }
            }
            catch (LdapException)
            {
                Console.WriteLine("Ldap Connection Failure.");
                Console.WriteLine("Try again with the IgnoreLdapCert option if using SecureLDAP or check your DomainController option");
                return;
            }

            if (options.Stealth)
            {
                Console.WriteLine("Note: All stealth options are single threaded");
            }

            if (options.CollectMethod.Equals(LocalGroup) && options.Stealth)
            {
                Console.WriteLine("Note: You specified Stealth and LocalGroup which is equivalent to GPOLocalGroup");
                options.CollectMethod = GPOLocalGroup;
            }

            var runner = new EnumerationRunner(options);

            if (options.CollectMethod.Equals(SessionLoop))
            {
                if (options.MaxLoopTime == null)
                {
                    Console.WriteLine("Session Loop mode specified without MaxLoopTime, will loop indefinitely");
                }
                else
                {
                    Console.WriteLine($"Session Loop mode specified. Looping will end on {options.LoopEnd.ToShortDateString()} at {options.LoopEnd.ToShortTimeString()}");
                }
            }

            if (options.Stealth)
            {
                runner.StartStealthEnumeration();
            }
            else
            {
                runner.StartEnumeration();
            }
            Cache.Instance.SaveCache();
            if (options.CompressData)
            {
                Utils.CompressFiles();
            }
        }
Beispiel #19
0
        public static void Main(string[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            var options = new Options();

            if (!Parser.Default.ParseArguments(args, options))
            {
                return;
            }

            try
            {
                // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
                Path.Combine(options.JsonFolder, options.CacheFile);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid characters in output path. Check for trailing backslashes!");
                return;
            }

            if (options.CollectionMethod.Length == 1)
            {
                options.CollectionMethod = options.CollectionMethod[0].Split(',');
            }

            if (options.Jitter > 100 || options.Jitter < 0)
            {
                Console.WriteLine("Jitter must be a value between 0 and 100!");
                return;
            }

            if (options.Throttle < 0)
            {
                Console.WriteLine("Throttle must be 0 or greater!");
                return;
            }

            var resolved = ResolvedCollectionMethod.None;

            foreach (var unparsed in options.CollectionMethod)
            {
                try
                {
                    var e = (CollectionMethod)Enum.Parse(typeof(CollectionMethod), unparsed, true);
                    switch (e)
                    {
                    case All:
                        resolved = resolved | ResolvedCollectionMethod.ACL | ResolvedCollectionMethod.Container |
                                   ResolvedCollectionMethod.Group | ResolvedCollectionMethod.LocalAdmin |
                                   ResolvedCollectionMethod.ObjectProps | ResolvedCollectionMethod.RDP |
                                   ResolvedCollectionMethod.Session | ResolvedCollectionMethod.Trusts |
                                   ResolvedCollectionMethod.DCOM;
                        break;

                    case DcOnly:
                        resolved = resolved | ResolvedCollectionMethod.ACL | ResolvedCollectionMethod.Container |
                                   ResolvedCollectionMethod.Trusts | ResolvedCollectionMethod.ObjectProps |
                                   ResolvedCollectionMethod.GPOLocalGroup | ResolvedCollectionMethod.Group;
                        break;

                    case CollectionMethod.Group:
                        resolved = resolved | ResolvedCollectionMethod.Group;
                        break;

                    case ComputerOnly:
                        resolved = resolved | ResolvedCollectionMethod.LocalAdmin |
                                   ResolvedCollectionMethod.Session | ResolvedCollectionMethod.RDP |
                                   ResolvedCollectionMethod.DCOM;
                        break;

                    case LocalAdmin:
                        resolved = resolved | ResolvedCollectionMethod.LocalAdmin;
                        break;

                    case GPOLocalGroup:
                        resolved = resolved | ResolvedCollectionMethod.GPOLocalGroup;
                        break;

                    case Session:
                        resolved = resolved | ResolvedCollectionMethod.Session;
                        break;

                    case LoggedOn:
                        resolved = resolved | ResolvedCollectionMethod.LoggedOn;
                        break;

                    case Trusts:
                        resolved = resolved | ResolvedCollectionMethod.Trusts;
                        break;

                    case ACL:
                        resolved = resolved | ResolvedCollectionMethod.ACL;
                        break;

                    case SessionLoop:
                        resolved = resolved | ResolvedCollectionMethod.SessionLoop;
                        break;

                    case Default:
                        resolved = resolved | ResolvedCollectionMethod.LocalAdmin | ResolvedCollectionMethod.Group | ResolvedCollectionMethod.Session | ResolvedCollectionMethod.Trusts;
                        break;

                    case ObjectProps:
                        resolved = resolved | ResolvedCollectionMethod.ObjectProps;
                        break;

                    case Container:
                        resolved = resolved | ResolvedCollectionMethod.Container;
                        break;

                    case RDP:
                        resolved = resolved | ResolvedCollectionMethod.RDP;
                        break;

                    case DCOM:
                        resolved = resolved | ResolvedCollectionMethod.DCOM;
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }
                catch
                {
                    Console.WriteLine($"Failed to parse value {unparsed}. Check your values for CollectionMethods!");
                    return;
                }
            }

            if (options.Debug)
            {
                Console.WriteLine("Debug Mode activated!");
                options.Threads = 1;
            }

            if ((resolved & ResolvedCollectionMethod.SessionLoop) != 0)
            {
                if (options.MaxLoopTime != null)
                {
                    var regex     = new Regex("[0-9]+[smdh]");
                    var matches   = regex.Matches(options.MaxLoopTime);
                    var numregex  = new Regex("[0-9]+");
                    var timeregex = new Regex("[smdh]");
                    if (matches.Count == 0)
                    {
                        Console.WriteLine("LoopEndTime does not match required format");
                        return;
                    }

                    var now   = DateTime.Now;
                    var drift = 0;
                    foreach (var match in matches)
                    {
                        var num  = int.Parse(numregex.Match(match.ToString()).Value);
                        var spec = timeregex.Match(match.ToString());

                        switch (spec.Value)
                        {
                        case "s":
                            now    = now.AddSeconds(num);
                            drift += num;
                            break;

                        case "m":
                            now    = now.AddMinutes(num);
                            drift += num * 60;
                            break;

                        case "h":
                            now    = now.AddHours(num);
                            drift += num * 60 * 60;
                            break;

                        case "d":
                            now    = now.AddDays(num);
                            drift += num * 60 * 60 * 24;
                            break;
                        }
                    }

                    options.LoopEnd = now;

                    if (drift == 0)
                    {
                        Console.WriteLine("LoopEndTime is zero! Specify a real value");
                        return;
                    }
                }
                else
                {
                    options.LoopEnd = DateTime.Now + TimeSpan.FromHours(2);
                }
            }

            options.CurrentUser = WindowsIdentity.GetCurrent().Name.Split('\\')[1];
            var nowtime = DateTime.Now;

            Console.WriteLine($"Initializing BloodHound at {nowtime.ToShortTimeString()} on {nowtime.ToShortDateString()}");

            if (options.ComputerFile != null)
            {
                if (options.PingTimeout < 1000)
                {
                    Console.WriteLine("Increasing ping timeout to 1 second for ComputerFile mode");
                    options.PingTimeout = 1000;
                }
            }

            Cache.CreateInstance(options);
            Utils.CreateInstance(options);

            if (!Utils.CheckWritePrivs())
            {
                Console.WriteLine("Unable to write in chosen directory. Please check privs");
                return;
            }

            if (Utils.Instance.GetDomainList().Count == 0)
            {
                Console.WriteLine("Unable to contact domain. Try from a domain context!");
                return;
            }

            SessionHelpers.Init(options);
            LocalGroupHelpers.Init(options);
            GroupHelpers.Init();
            AclHelpers.Init();
            TrustHelpers.Init();
            ContainerHelpers.Init();

            if (options.Test != null)
            {
                Test.DoStuff(options.Test);
                return;
            }

            //Lets test our connection to LDAP before we do anything else
            try
            {
                var conn = Utils.Instance.GetLdapConnection(options.Domain);
                if (conn == null)
                {
                    Console.WriteLine("LDAP connection test failed, probably can't contact domain");
                    return;
                }
                conn.Bind();
            }
            catch (LdapException)
            {
                Console.WriteLine("Ldap Connection Failure.");
                if (options.LdapPass != null)
                {
                    Console.WriteLine("Check credentials supplied to SharpHound");
                }
                Console.WriteLine("Try again with the IgnoreLdapCert option if using SecureLDAP or check your DomainController/LdapPort option");
                return;
            }

            //if (options.Uri != null)
            //{
            //    if (!options.Uri.StartsWith("http",StringComparison.OrdinalIgnoreCase))
            //    {
            //        Console.WriteLine("URI must start with http:// or https://");
            //        return;
            //    }

            //    using (var client = new WebClient())
            //    {
            //        client.Headers.Add("content-type", "application/json");
            //        client.Headers.Add("Accept", "application/json; charset=UTF-8");

            //        if (options.UserPass != null)
            //            client.Headers.Add("Authorization", options.GetEncodedUserPass());

            //        try
            //        {
            //            client.DownloadData(options.GetCheckURI());
            //            Console.WriteLine("Successfully connected to the Neo4j REST endpoint.");
            //            Console.WriteLine("WARNING: As of BloodHound 1.5, using the REST API is unsupported and will be removed in a future release.");
            //            Console.WriteLine("WARNING: Container collection will not work with the REST API, and bugs may exist.");
            //        }
            //        catch
            //        {
            //            Console.WriteLine("Unable to connect to the Neo4j REST endpoint. Check your URI and username/password");
            //            Console.WriteLine("WARNING: As of BloodHound 1.5, using the REST API is unsupported and will be removed in a future release.");
            //            Console.WriteLine("WARNING: Container collection will not work with the REST API, and bugs may exist.");
            //            return;
            //        }
            //    }
            //}

            if (options.Stealth)
            {
                Console.WriteLine("Note: All stealth options are single threaded");
            }

            if (options.Throttle > 0)
            {
                Console.WriteLine(
                    $"Adding a delay of {options.Throttle} milliseconds to computer requests with a jitter of {options.Jitter}%");
            }

            //Do some sanity checks
            if (options.ComputerFile != null)
            {
                if (!File.Exists(options.ComputerFile))
                {
                    Console.WriteLine("Specified ComputerFile does not exist!");
                    return;
                }

                if (options.Stealth)
                {
                    Console.WriteLine("Switching to one thread for ComputerFile, removing stealth");
                    options.Stealth = false;
                    options.Threads = 1;
                }

                Console.WriteLine("ComputerFile detected! Removing non-computer collection methods");
                resolved = resolved ^ ResolvedCollectionMethod.ACL ^ ResolvedCollectionMethod.Group ^
                           ResolvedCollectionMethod.GPOLocalGroup ^ ResolvedCollectionMethod.Trusts ^
                           ResolvedCollectionMethod.Container ^ ResolvedCollectionMethod.ObjectProps;
            }

            if (options.Stealth)
            {
                if ((resolved & ResolvedCollectionMethod.LocalAdmin) != 0)
                {
                    Console.WriteLine("Note: You specified Stealth and LocalAdmin which is equivalent to GPOLocalGroup");
                    resolved = resolved ^ ResolvedCollectionMethod.LocalAdmin;
                    resolved = resolved | ResolvedCollectionMethod.GPOLocalGroup;
                }

                if ((resolved & ResolvedCollectionMethod.LoggedOn) != 0)
                {
                    Console.WriteLine("LoggedOn enumeration is not supported with Stealth");
                    resolved = resolved ^ ResolvedCollectionMethod.LoggedOn;
                }
            }

            if ((resolved & ResolvedCollectionMethod.Session) != 0 &&
                (resolved & ResolvedCollectionMethod.SessionLoop) != 0)
            {
                resolved = resolved ^ ResolvedCollectionMethod.Session;
            }

            if ((resolved & ResolvedCollectionMethod.LoggedOn) != 0 &&
                (resolved & ResolvedCollectionMethod.SessionLoop) != 0)
            {
                resolved = resolved ^ ResolvedCollectionMethod.LoggedOn;
                resolved = resolved | ResolvedCollectionMethod.LoggedOnLoop;
            }


            if ((resolved & ResolvedCollectionMethod.SessionLoop) != 0)
            {
                Console.WriteLine(options.MaxLoopTime == null
                    ? $"Session Loop mode specified without MaxLoopTime, will loop for 2 hours ({options.LoopEnd.ToShortDateString()} at {options.LoopEnd.ToShortTimeString()})"
                    : $"Session Loop mode specified. Looping will end on {options.LoopEnd.ToShortDateString()} at {options.LoopEnd.ToShortTimeString()}");
                Console.WriteLine("Looping will start after any other collection methods");
            }

            if (resolved.Equals(ResolvedCollectionMethod.None))
            {
                Console.WriteLine("No collection methods specified. Exiting");
                return;
            }

            Console.WriteLine($"Resolved Collection Methods to {resolved}");

            if ((resolved & ResolvedCollectionMethod.ACL) != 0)
            {
                Utils.Verbose("Building GUID Cache");
                AclHelpers.BuildGuidCache();
            }

            options.ResolvedCollMethods = resolved;

            var runner = new EnumerationRunner(options);

            if (options.Stealth)
            {
                runner.StartStealthEnumeration();
            }
            else
            {
                if (options.ComputerFile == null)
                {
                    runner.StartEnumeration();
                }
                else
                {
                    runner.StartCompFileEnumeration();
                }
            }
            Console.WriteLine();

            Cache.Instance.SaveCache();
            Utils.Instance.KillConnections();

            if (!options.NoZip)
            {
                Utils.CompressFiles();
            }
        }
Beispiel #20
0
        public static void Main(string[] args)
        {
            // Here's a simple spot to put dummy code to throw off the hash, process call tree, and
            // other signs that this is still sharphound... :)
            //
            // We can shift the code around withing their local/global contexts inside the function to further throw off things like cylance and crowdstrike.
            // All of these changes only get sharphound to execute, they do not prevent ATA or other monitoring tools from alarming on the sharphound enumerations.
            //
            // We should put variations of these junk code (that isn't dead code) in as many functions as possible, and use junk enumarable objects
            // within the functions so that it greatly changes the call trees so that ML can be attacked.
            //

            var tempval1 = Math.PI + 12.010020510 + 4;
            var tempval2 = 15 + tempval1;

            tempval2 -= 31;
            tempval1  = tempval2;

            // rest of the orginal sharphound code below

            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            var options = new Ingestor.Options();

            if (!Parser.Default.ParseArguments(args, options))
            {
                return;
            }

            if (options.CacheFile == null)
            {
                var sid            = Utils.GetLocalMachineSid();
                var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(sid);
                options.CacheFile = $"{Convert.ToBase64String(plainTextBytes)}.bin";
            }

            try
            {
                // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
                Path.Combine(options.JsonFolder, options.CacheFile);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid characters in output path. Check for trailing backslashes!");
                return;
            }

            if (options.CollectionMethod.Length == 1)
            {
                options.CollectionMethod = options.CollectionMethod[0].Split(',');
            }

            if (options.Jitter > 100 || options.Jitter < 0)
            {
                Console.WriteLine("Jitter must be a value between 0 and 100!");
                return;
            }

            if (options.Throttle < 0)
            {
                Console.WriteLine("Throttle must be 0 or greater!");
                return;
            }

            var resolved = ResolvedCollectionMethod.None;

            foreach (var unparsed in options.CollectionMethod)
            {
                try
                {
                    var e = (CollectionMethod)Enum.Parse(typeof(CollectionMethod), unparsed, true);
                    switch (e)
                    {
                    case All:
                        resolved = resolved | ResolvedCollectionMethod.ACL | ResolvedCollectionMethod.Container |
                                   ResolvedCollectionMethod.Group | ResolvedCollectionMethod.LocalAdmin |
                                   ResolvedCollectionMethod.ObjectProps | ResolvedCollectionMethod.RDP |
                                   ResolvedCollectionMethod.Session | ResolvedCollectionMethod.Trusts |
                                   ResolvedCollectionMethod.DCOM | ResolvedCollectionMethod.LoggedOn |
                                   ResolvedCollectionMethod.SPNTargets;
                        break;

                    case DcOnly:
                        resolved = resolved | ResolvedCollectionMethod.ACL | ResolvedCollectionMethod.Container |
                                   ResolvedCollectionMethod.Trusts | ResolvedCollectionMethod.ObjectProps |
                                   ResolvedCollectionMethod.GPOLocalGroup | ResolvedCollectionMethod.Group;
                        break;

                    case CollectionMethod.Group:
                        resolved = resolved | ResolvedCollectionMethod.Group;
                        break;

                    case ComputerOnly:
                        resolved = resolved | ResolvedCollectionMethod.LocalAdmin |
                                   ResolvedCollectionMethod.Session | ResolvedCollectionMethod.RDP |
                                   ResolvedCollectionMethod.DCOM;
                        break;

                    case LocalGroup:
                        resolved = resolved | ResolvedCollectionMethod.LocalAdmin | ResolvedCollectionMethod.RDP | ResolvedCollectionMethod.DCOM;
                        break;

                    case GPOLocalGroup:
                        resolved = resolved | ResolvedCollectionMethod.GPOLocalGroup;
                        break;

                    case Session:
                        resolved = resolved | ResolvedCollectionMethod.Session;
                        break;

                    case LoggedOn:
                        resolved = resolved | ResolvedCollectionMethod.LoggedOn;
                        break;

                    case Trusts:
                        resolved = resolved | ResolvedCollectionMethod.Trusts;
                        break;

                    case ACL:
                        resolved = resolved | ResolvedCollectionMethod.ACL;
                        break;

                    case SessionLoop:
                        resolved = resolved | ResolvedCollectionMethod.SessionLoop;
                        break;

                    case Default:
                        resolved = resolved | ResolvedCollectionMethod.RDP | ResolvedCollectionMethod.DCOM | ResolvedCollectionMethod.LocalAdmin | ResolvedCollectionMethod.Group | ResolvedCollectionMethod.Session | ResolvedCollectionMethod.Trusts;
                        break;

                    case ObjectProps:
                        resolved = resolved | ResolvedCollectionMethod.ObjectProps;
                        break;

                    case Container:
                        resolved = resolved | ResolvedCollectionMethod.Container;
                        break;

                    case LocalAdmin:
                        resolved = resolved | ResolvedCollectionMethod.LocalAdmin;
                        break;

                    case RDP:
                        resolved = resolved | ResolvedCollectionMethod.RDP;
                        break;

                    case DCOM:
                        resolved = resolved | ResolvedCollectionMethod.DCOM;
                        break;

                    case SPNTargets:
                        resolved = resolved | ResolvedCollectionMethod.SPNTargets;
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }
                catch
                {
                    Console.WriteLine($"Failed to parse value {unparsed}. Check your values for CollectionMethods!");
                    return;
                }
            }

            if (options.Debug)
            {
                Console.WriteLine("Debug Mode activated!");
                //options.Threads = 1;
            }

            if ((resolved & ResolvedCollectionMethod.SessionLoop) != 0)
            {
                if (options.MaxLoopTime != null)
                {
                    var regex     = new Regex("[0-9]+[smdh]");
                    var matches   = regex.Matches(options.MaxLoopTime);
                    var numregex  = new Regex("[0-9]+");
                    var timeregex = new Regex("[smdh]");
                    if (matches.Count == 0)
                    {
                        Console.WriteLine("LoopEndTime does not match required format");
                        return;
                    }

                    var now   = DateTime.Now;
                    var drift = 0;
                    foreach (var match in matches)
                    {
                        var num  = int.Parse(numregex.Match(match.ToString()).Value);
                        var spec = timeregex.Match(match.ToString());

                        switch (spec.Value)
                        {
                        case "s":
                            now    = now.AddSeconds(num);
                            drift += num;
                            break;

                        case "m":
                            now    = now.AddMinutes(num);
                            drift += num * 60;
                            break;

                        case "h":
                            now    = now.AddHours(num);
                            drift += num * 60 * 60;
                            break;

                        case "d":
                            now    = now.AddDays(num);
                            drift += num * 60 * 60 * 24;
                            break;
                        }
                    }

                    options.LoopEnd = now;

                    if (drift == 0)
                    {
                        Console.WriteLine("LoopEndTime is zero! Specify a real value");
                        return;
                    }
                }
                else
                {
                    options.LoopEnd = DateTime.Now + TimeSpan.FromHours(2);
                }
            }

            options.CurrentUser = options.OverrideUser ?? WindowsIdentity.GetCurrent().Name.Split('\\')[1];

            Cache.CreateInstance(options);
            Utils.CreateInstance(options);


            if (!Utils.CheckWritePrivs())
            {
                Console.WriteLine("Unable to write in chosen directory. Please check privs");
                return;
            }

            var nowtime = DateTime.Now;

            Console.WriteLine($"Initializing IngestCache at {nowtime.ToShortTimeString()} on {nowtime.ToShortDateString()}");

            if (options.ComputerFile != null)
            {
                if (options.PingTimeout < 1000)
                {
                    Console.WriteLine("Increasing ping timeout to 1 second for ComputerFile mode");
                    options.PingTimeout = 1000;
                }
            }

            if (Utils.Instance.GetDomainList().Count == 0)
            {
                Console.WriteLine("Unable to contact domain. Try from a domain context!");
                return;
            }

            if (options.DomainController != null)
            {
                Console.WriteLine("Manually specifying a domain controller will likely result in data loss. Only use this for performance/opsec reasons");
                if (options.SearchForest)
                {
                    Console.WriteLine("SearchForest is not usable with the --DomainController flag");
                    options.SearchForest = false;
                }
            }
            else
            {
                //Build our DC cache
                Utils.Instance.GetUsableDomainControllers();
            }

            SessionHelpers.Init(options);
            LocalGroupHelpers.Init(options);
            GroupHelpers.Init();
            AclHelpers.Init();
            TrustHelpers.Init();
            ContainerHelpers.Init();

            if (options.Test != null)
            {
                Test.DoStuff(options.Test);
                return;
            }

            //Lets test our connection to LDAP before we do anything else
            try
            {
                var conn = Utils.Instance.GetLdapConnection(options.Domain);
                if (conn == null)
                {
                    Console.WriteLine("LDAP connection test failed, probably can't contact domain");
                    return;
                }
                conn.Bind();
            }
            catch (LdapException)
            {
                Console.WriteLine("Ldap Connection Failure.");
                if (options.LdapPass != null)
                {
                    Console.WriteLine("Check credentials supplied to Ingestor");
                }
                Console.WriteLine("Try again with the IgnoreLdapCert option if using SecureLDAP or check your DomainController/LdapPort option");
                return;
            }

            //if (options.Uri != null)
            //{
            //    if (!options.Uri.StartsWith("http",StringComparison.OrdinalIgnoreCase))
            //    {
            //        Console.WriteLine("URI must start with http:// or https://");
            //        return;
            //    }

            //    using (var client = new WebClient())
            //    {
            //        client.Headers.Add("content-type", "application/json");
            //        client.Headers.Add("Accept", "application/json; charset=UTF-8");

            //        if (options.UserPass != null)
            //            client.Headers.Add("Authorization", options.GetEncodedUserPass());

            //        try
            //        {
            //            client.DownloadData(options.GetCheckURI());
            //            Console.WriteLine("Successfully connected to the Neo4j REST endpoint.");
            //            Console.WriteLine("WARNING: As of IngestCache 1.5, using the REST API is unsupported and will be removed in a future release.");
            //            Console.WriteLine("WARNING: Container collection will not work with the REST API, and bugs may exist.");
            //        }
            //        catch
            //        {
            //            Console.WriteLine("Unable to connect to the Neo4j REST endpoint. Check your URI and username/password");
            //            Console.WriteLine("WARNING: As of IngestCache 1.5, using the REST API is unsupported and will be removed in a future release.");
            //            Console.WriteLine("WARNING: Container collection will not work with the REST API, and bugs may exist.");
            //            return;
            //        }
            //    }
            //}

            if (options.Stealth)
            {
                Console.WriteLine("Note: All stealth options are single threaded");
            }

            if (options.Throttle > 0)
            {
                Console.WriteLine(
                    $"Adding a delay of {options.Throttle} milliseconds to computer requests with a jitter of {options.Jitter}%");
            }

            //Do some sanity checks
            if (options.ComputerFile != null)
            {
                if (!File.Exists(options.ComputerFile))
                {
                    Console.WriteLine("Specified ComputerFile does not exist!");
                    return;
                }

                if (options.Stealth)
                {
                    Console.WriteLine("Switching to one thread for ComputerFile, removing stealth");
                    options.Stealth = false;
                    options.Threads = 1;
                }

                Console.WriteLine("ComputerFile detected! Removing non-computer collection methods");
                resolved = resolved & ~ResolvedCollectionMethod.ACL & ~ResolvedCollectionMethod.Group
                           & ~ResolvedCollectionMethod.GPOLocalGroup & ~ResolvedCollectionMethod.Trusts
                           & ~ResolvedCollectionMethod.Container & ~ResolvedCollectionMethod.ObjectProps;
            }

            if (options.Stealth)
            {
                if ((resolved & ResolvedCollectionMethod.LocalAdmin) != 0)
                {
                    Console.WriteLine("Note: You specified Stealth and LocalGroup which is equivalent to GPOLocalGroup");
                    resolved = resolved & ~ResolvedCollectionMethod.LocalAdmin;
                    resolved = resolved | ResolvedCollectionMethod.GPOLocalGroup;
                }

                if ((resolved & ResolvedCollectionMethod.LoggedOn) != 0)
                {
                    Console.WriteLine("LoggedOn enumeration is not supported with Stealth");
                    resolved = resolved & ~ResolvedCollectionMethod.LoggedOn;
                }
            }

            if ((resolved & ResolvedCollectionMethod.Session) != 0 &&
                (resolved & ResolvedCollectionMethod.SessionLoop) != 0)
            {
                resolved = resolved ^ ResolvedCollectionMethod.Session;
            }

            if ((resolved & ResolvedCollectionMethod.LoggedOn) != 0 &&
                (resolved & ResolvedCollectionMethod.SessionLoop) != 0)
            {
                resolved = resolved ^ ResolvedCollectionMethod.LoggedOn;
                resolved = resolved | ResolvedCollectionMethod.LoggedOnLoop;
            }


            if ((resolved & ResolvedCollectionMethod.SessionLoop) != 0)
            {
                Console.WriteLine(options.MaxLoopTime == null
                    ? $"Session Loop mode specified without MaxLoopTime, will loop for 2 hours ({options.LoopEnd.ToShortDateString()} at {options.LoopEnd.ToShortTimeString()})"
                    : $"Session Loop mode specified. Looping will end on {options.LoopEnd.ToShortDateString()} at {options.LoopEnd.ToShortTimeString()}");
                Console.WriteLine("Looping will start after any other collection methods");
            }

            if (resolved.Equals(ResolvedCollectionMethod.None))
            {
                Console.WriteLine("No collection methods specified. Exiting");
                return;
            }

            Console.WriteLine($"Resolved Collection Methods to {resolved}");

            if ((resolved & ResolvedCollectionMethod.ACL) != 0)
            {
                Utils.Verbose("Building GUID Cache");
                AclHelpers.BuildGuidCache();
            }

            options.ResolvedCollMethods = resolved;

            var runner = new EnumerationRunner(options);

            if (options.Stealth)
            {
                runner.StartStealthEnumeration();
            }
            else
            {
                if (options.ComputerFile == null)
                {
                    runner.StartEnumeration();
                }
                else
                {
                    runner.StartCompFileEnumeration();
                }
            }
            Console.WriteLine();

            Cache.Instance.SaveCache();
            Utils.Instance.KillConnections();

            if (!options.NoZip)
            {
                Utils.CompressFiles();
            }
        }
Beispiel #21
0
        private void Cycle(bool manual = false)
        {
            if (BoltOpen)
            {
                return;
            }

            var chamberEntity = _chamberContainer.ContainedEntity;

            if (chamberEntity != null)
            {
                _chamberContainer.Remove(chamberEntity);
                var ammoComponent = chamberEntity.GetComponent <AmmoComponent>();
                if (!ammoComponent.Caseless)
                {
                    EjectCasing(chamberEntity);
                }
            }

            // Try and pull a round from the magazine to replace the chamber if possible
            var magazine  = _magazineContainer.ContainedEntity;
            var nextRound = magazine?.GetComponent <RangedMagazineComponent>().TakeAmmo();

            if (nextRound != null)
            {
                // If you're really into gunporn you could put a sound here
                _chamberContainer.Insert(nextRound);
            }

            var soundSystem = EntitySystem.Get <AudioSystem>();

            if (_autoEjectMag && magazine != null && magazine.GetComponent <RangedMagazineComponent>().ShotsLeft == 0)
            {
                if (_soundAutoEject != null)
                {
                    soundSystem.PlayAtCoords(_soundAutoEject, Owner.Transform.GridPosition, AudioParams.Default.WithVolume(-2));
                }

                _magazineContainer.Remove(magazine);
                SendNetworkMessage(new MagazineAutoEjectMessage());
            }

            if (nextRound == null && !BoltOpen)
            {
                if (_soundBoltOpen != null)
                {
                    soundSystem.PlayAtCoords(_soundBoltOpen, Owner.Transform.GridPosition, AudioParams.Default.WithVolume(-5));
                }

                if (ContainerHelpers.TryGetContainer(Owner, out var container))
                {
                    Owner.PopupMessage(container.Owner, Loc.GetString("Bolt open"));
                }
                BoltOpen = true;
                Dirty();
                UpdateAppearance();
                return;
            }

            if (manual)
            {
                if (_soundRack != null)
                {
                    soundSystem.PlayAtCoords(_soundRack, Owner.Transform.GridPosition, AudioParams.Default.WithVolume(-2));
                }
            }

            Dirty();
            UpdateAppearance();
        }
 public AzureRMBackupContainerContextObject(AzureRMBackupVault vault, CSMContainerResponse containerInfo)
     : base(vault.ResourceGroupName, vault.Name, vault.Region)
 {
     ContainerType       = ContainerHelpers.GetTypeForManagedContainer(containerInfo.Properties.ContainerType).ToString();
     ContainerUniqueName = containerInfo.Name;
 }