Exemplo n.º 1
0
        public ActionResult Edit(Guid id, SecurityGroupModel model, string button)
        {
            using (DBEntities context = Settings.CreateDataContext())
            {
                ValidateGroup(context, model);

                if (!ModelState.IsValid)
                {
                    return View(model);
                }

                SecurityGroup target = null;
                if (model.Id != Guid.Empty)
                {
                    target = SecurityGroupHelper.Get(model.Id, context);
                    if (target == null)
                    {
                        ModelState.AddModelError("", Resources.Resource.RowNotFound);
                        return View(model);
                    }
                }
                else
                {
                    target = new SecurityGroup();
                    target.Id = Guid.NewGuid();
                    context.AddToSecurityGroup(target);
                }

                SecurityGroupModel.CreateMap();
                Mapper.Map(model, target);
                UpdateArray(context, model, target);

                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    var sb = new StringBuilder(Resources.Resource.SaveError + ": " + ex.Message);
                    if (ex.InnerException != null)
                        sb.AppendLine(ex.InnerException.Message);
                    ModelState.AddModelError("", sb.ToString());
                    return View(model);
                }

                if (button == "SaveAndExit")
                    return RedirectToAction("Index");
                else
                    return RedirectToAction("Edit", new { target.Id });
            }
        }
Exemplo n.º 2
0
        public MainSearchViewModel(ISecurityGroupServiceAgent serviceAgent)
        {
            this._serviceAgent    = serviceAgent;
            SecurityGroupTypeList = GetSecurityGroupTypes();
            SecurityGroupCodeList = GetSecurityGroupCodes();

            SearchObject = new SecurityGroup();
            ResultList   = new BindingList <SecurityGroup>();
            SelectedList = new BindingList <SecurityGroup>();
            //make sure of session authentication...
            if (ClientSessionSingleton.Instance.SessionIsAuthentic) //make sure user has rights to UI...
            {
                DoFormsAuthentication();
            }
            else
            {//User is not authenticated...
                RegisterToReceiveMessages <bool>(MessageTokens.StartUpLogInToken.ToString(), OnStartUpLogIn);
                FormIsEnabled = false;
            }
        }
Exemplo n.º 3
0
    public WebserverStack()
    {
        var group = new SecurityGroup("web-secgrp", new SecurityGroupArgs
        {
            Ingress =
            {
                // Uncomment to fail a test:
                // new SecurityGroupIngressArgs { Protocol = "tcp", FromPort = 22, ToPort = 22, CidrBlocks = { "0.0.0.0/0" } },
                new SecurityGroupIngressArgs {
                    Protocol = "tcp", FromPort = 80, ToPort = 80, CidrBlocks ={ "0.0.0.0/0"                                   }
                }
            }
        });

        var amiId = Output.Create(Pulumi.Aws.Ec2.GetAmi.InvokeAsync(new Pulumi.Aws.Ec2.GetAmiArgs
        {
            MostRecent = true,
            Owners     = { "099720109477" },
            Filters    =
            {
                new Pulumi.Aws.Ec2.Inputs.GetAmiFilterArgs
                {
                    Name   = "name",
                    Values ={ "ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-*"              },
                }
            }
        })).Apply(ami => ami.Id);

        // var userData = "#!/bin/bash echo \"Hello, World!\" > index.html nohup python -m SimpleHTTPServer 80 &";

        var server = new Instance("web-server-www", new InstanceArgs
        {
            InstanceType        = "t2.micro",
            VpcSecurityGroupIds = { group.Id }, // reference the group object above
            Ami = amiId,
            // Comment out to fail a test:
            Tags = { { "Name", "webserver" } },
            // Uncomment to fail a test:
            // UserData = userData           // start a simple webserver
        });
    }
Exemplo n.º 4
0
        public List <DirectoryEntry> GetSecurityGroupMembership(String securityGroupId)
        {
            List <DirectoryEntry> membership = new List <DirectoryEntry> ();


            System.DirectoryServices.DirectoryEntry rootDirectoryEntry;

            SecurityGroup securityGroup = new SecurityGroup();

            String objectSid;

            rootDirectoryEntry = NewDirectoryEntryByAgent(DomainRootPath).Children.Find("CN=USERS");

            foreach (System.DirectoryServices.DirectoryEntry currentEntry in rootDirectoryEntry.Children)
            {
                try {
                    if (currentEntry.Properties["groupType"].Value != null)
                    {
                        objectSid = ObjectSidToString(((byte[])currentEntry.Properties["objectSid"].Value));

                        if (securityGroupId == objectSid)
                        {
                            Object groupMembers = currentEntry.Invoke("members", null);

                            foreach (Object currentMember in (System.Collections.IEnumerable)groupMembers)
                            {
                                membership.Add(new DirectoryEntry(new System.DirectoryServices.DirectoryEntry(currentMember)));
                            }
                        }
                    } // if (currentPropertyName == "groupType") {
                }     // END TRY ENUMERATE DIRECTORY ENTRY PROPERTIES

                catch (Exception propertyException) {
                    // DO NOTHING

                    System.Diagnostics.Debug.WriteLine(propertyException.Message);
                }
            }

            return(membership);
        }
        public void securityGroupIndexFiltered()
        {
            RightScale.netClient.Core.APIClient.Instance.InitWebClient();
            RightScale.netClient.Core.APIClient.Instance.Authenticate(this.apiRefreshToken);

            List <SecurityGroup> sgList = SecurityGroup.index(this.cloudID);

            Assert.IsNotNull(sgList);
            Assert.IsTrue(sgList.Count > 0);

            List <Filter> filter = new List <Filter>();

            filter.Add(new Filter("name", FilterOperator.Equal, "default"));
            List <SecurityGroup> filteredSgList = SecurityGroup.index(this.cloudID, filter);

            Assert.IsNotNull(filteredSgList);
            Assert.IsTrue(filteredSgList.Count > 0);

            Assert.IsTrue(sgList.Count > filteredSgList.Count);

            RightScale.netClient.Core.APIClient.Instance.InitWebClient();
        }
Exemplo n.º 6
0
        /// <summary>
        /// Authorize permission
        /// </summary>
        /// <param name="permissionRecordName">Permission record name</param>
        /// <param name="securityGroup">Security Group</param>
        /// <returns>true - authorized; otherwise, false</returns>
        protected virtual bool Authorize(string permissionRecordName, SecurityGroup securityGroup)
        {
            if (String.IsNullOrEmpty(permissionRecordName))
            {
                return(false);
            }

            string key = string.Format(PERMISSIONS_ALLOWED_KEY, securityGroup.Id, permissionRecordName);

            return(_cacheManager.Get(key, () =>
            {
                foreach (var permission in securityGroup.PermissionRecords)
                {
                    if (permission.Name.Equals(permissionRecordName, StringComparison.InvariantCultureIgnoreCase))
                    {
                        return true;
                    }
                }

                return false;
            }));
        }
        public static Dictionary <int, SecurityGroup> CreateTestGroups()
        {
            SecurityGroup g;
            var           storage = new Dictionary <int, SecurityGroup>();

            g = new SecurityGroup(Id("G1"))
            {
                UserMemberIds = new List <int> {
                    Id("U1"), Id("U2")
                }
            }; storage.Add(g.Id, g);
            g = new SecurityGroup(Id("G2"))
            {
                UserMemberIds = new List <int> {
                    Id("U3"), Id("U4")
                }
            }; storage.Add(g.Id, g);
            g = new SecurityGroup(Id("G3"))
            {
                UserMemberIds = new List <int> {
                    Id("U1"), Id("U3")
                }
            }; storage.Add(g.Id, g);
            g = new SecurityGroup(Id("G4"))
            {
                UserMemberIds = new List <int> {
                    Id("U4")
                }
            }; storage.Add(g.Id, g);
            g = new SecurityGroup(Id("G5"))
            {
                UserMemberIds = new List <int> {
                    Id("U5")
                }
            }; storage.Add(g.Id, g);

            return(storage);
        }
        internal TargetInstanceStack(Construct scope, string id, Vpc vpc, string keyPairName, IStackProps props = null) : base(scope, id, props)
        {
            SecurityGroup = new SecurityGroup(this, "TargetInstance-Security-Group", new SecurityGroupProps
            {
                Vpc = vpc,
                AllowAllOutbound  = true,
                Description       = "TargetInstance-Security-Group",
                SecurityGroupName = "secgroup-" + id
            });


            Role = new Role(this, "ec2-targetinstance-role", new RoleProps
            {
                AssumedBy = new ServicePrincipal("ec2.amazonaws.com")
            });

            Role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("SecretsManagerReadWrite"));

            TargetInstance = new Instance_(this, id, new InstanceProps
            {
                InstanceType = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.MICRO),
                MachineImage = new WindowsImage(WindowsVersion.WINDOWS_SERVER_2019_ENGLISH_FULL_BASE),
                Vpc          = vpc,
                UserData     = UserData.Custom(Utils.GetResource("target_instance_user_data.ps1")),
                KeyName      = keyPairName,
                Role         = Role,
                VpcSubnets   = new SubnetSelection {
                    SubnetType = SubnetType.PRIVATE
                },
                SecurityGroup = SecurityGroup
            });

            SecurityGroup.AddIngressRule(Peer.AnyIpv4(), Port.AllTraffic(), "Allow all trafic in. In production - change this!");

            new CfnOutput(this, "target-instance", new CfnOutputProps {
                Value = TargetInstance.InstancePrivateIp
            });
        }
Exemplo n.º 9
0
        /// <summary>
        /// Adds the specified permissions to the Entity
        /// </summary>
        /// <param name="target">The entity that the permissions are applied to</param>
        /// <param name="securityGroup">The security group being granted the permissions</param>
        /// <param name="permissionTypes">The permission types to add</param>
        public void AddPermission(Guid target, SecurityGroup securityGroup, PermissionTypes permissionTypes)
        {
            if (securityGroup is null)
            {
                throw new ArgumentNullException(nameof(securityGroup));
            }

            securityGroup = this.SecurityGroupRepository.Find(securityGroup.Guid);

            EntityPermissions existing = this.GetForEntity(target);
            bool foundPermissions;

            if (existing is null)
            {
                foundPermissions = this.PermissionsCache.TryGetValue(target, out existing);
            }
            else
            {
                foundPermissions = true;
            }

            if (!foundPermissions)
            {
                existing = new EntityPermissions()
                {
                    EntityGuid = target
                };

                existing.AddPermission(securityGroup, permissionTypes);
                this.PermissionsCache.Add(target, existing);
                base.Add(existing);
            }
            else
            {
                existing.AddPermission(securityGroup, permissionTypes);
                base.AddOrUpdate(existing);
            }
        }
Exemplo n.º 10
0
        //Object.Property Scope Validation...
        private bool SecurityGroupIsValid(SecurityGroup item, _securityGroupValidationProperties validationProperties, out string errorMessage)
        {
            errorMessage = "";
            switch (validationProperties)
            {
            case _securityGroupValidationProperties.SecurityGroupID:
                //validate key
                if (string.IsNullOrEmpty(item.SecurityGroupID))
                {
                    errorMessage = "ID Is Required.";
                    return(false);
                }
                EntityStates entityState = GetSecurityGroupState(item);
                if (entityState == EntityStates.Added && SecurityGroupExists(item.SecurityGroupID))
                {
                    errorMessage = "Item All Ready Exists...";
                    return(false);
                }
                //check cached list for duplicates...
                int count = SecurityGroupList.Count(q => q.SecurityGroupID == item.SecurityGroupID);
                if (count > 1)
                {
                    errorMessage = "Item All Ready Exists...";
                    return(false);
                }
                break;

            case _securityGroupValidationProperties.Name:
                //validate Description
                if (string.IsNullOrEmpty(item.Name))
                {
                    errorMessage = "Description Is Required.";
                    return(false);
                }
                break;
            }
            return(true);
        }
Exemplo n.º 11
0
 public CPGroup CreateGroup(string groupName)
 {
     using (CPSecurityEntities context = new CPSecurityEntities())
     {
         if (!context.SecurityGroups.Any(g => g.GroupName == groupName))
         {
             SecurityGroup group = new SecurityGroup()
             {
                 GroupName = groupName
             };
             try
             {
                 context.SecurityGroups.AddObject(group);
                 context.SaveChanges();
                 return(CPGroupFactory.CreateGroup(group));
             }
             catch (ConstraintException)
             {
             }
         }
     }
     return(null);
 }
Exemplo n.º 12
0
        private void ConfigureService(Configuration settings)
        {
            if (EcsCluster == null)
            {
                throw new InvalidOperationException($"{nameof(EcsCluster)} has not been set. The {nameof(ConfigureCluster)} method should be called before {nameof(ConfigureService)}");
            }
            if (AppTaskDefinition == null)
            {
                throw new InvalidOperationException($"{nameof(AppTaskDefinition)} has not been set. The {nameof(ConfigureTaskDefinition)} method should be called before {nameof(ConfigureService)}");
            }

            var fargateServiceProps = new FargateServiceProps
            {
                Cluster        = EcsCluster,
                TaskDefinition = AppTaskDefinition,
                AssignPublicIp = settings.Vpc.IsDefault,
                DesiredCount   = settings.DesiredCount
            };


            if (!string.IsNullOrEmpty(settings.ECSServiceSecurityGroups))
            {
                var ecsServiceSecurityGroups = new List <ISecurityGroup>();
                var count = 1;
                foreach (var securityGroupId in settings.ECSServiceSecurityGroups.Split(','))
                {
                    ecsServiceSecurityGroups.Add(SecurityGroup.FromSecurityGroupId(this, $"AdditionalGroup-{count++}", securityGroupId.Trim(), new SecurityGroupImportOptions
                    {
                        Mutable = false
                    }));
                }

                fargateServiceProps.SecurityGroups = ecsServiceSecurityGroups.ToArray();
            }

            AppFargateService = new FargateService(this, nameof(AppFargateService), InvokeCustomizeCDKPropsEvent(nameof(AppFargateService), this, fargateServiceProps));
        }
Exemplo n.º 13
0
        private bool NewSecurityGroup(string itemID)
        {
            SecurityGroup newItem = new SecurityGroup();

            //all new records will be give a negative int autoid...
            //when they are updated then sql will generate one for them overiding this set value...
            //it will allow us to give uniqueness to the tempory new records...
            //Before they are updated to the entity and given an autoid...
            //we use a negative number and keep subtracting by 1 for each new item added...
            //This will allow it to alwasy be unique and never interfere with SQL's positive autoid...
            _newSecurityGroupAutoId = _newSecurityGroupAutoId - 1;
            newItem.AutoID          = _newSecurityGroupAutoId;
            newItem.SecurityGroupID = itemID;
            newItem.CompanyID       = ClientSessionSingleton.Instance.CompanyID;
            newItem.IsValid         = 1;
            newItem.NotValidMessage = "New Record Key Field/s Are Required.";
            SecurityGroupList.Add(newItem);
            _serviceAgent.AddToSecurityGroupRepository(newItem);
            SelectedSecurityGroup = SecurityGroupList.LastOrDefault();

            AllowEdit = true;
            Dirty     = false;
            return(true);
        }
Exemplo n.º 14
0
        public IQueryable <Temp> GetMetaData(string tableName)
        {
            switch (tableName)
            {
            case "SystemUsers":
                SystemUser systemUser = new SystemUser();
                return(systemUser.GetMetaData().AsQueryable());

            case "SystemUsersTypes":
                SystemUserType systemUserTypes = new SystemUserType();
                return(systemUserTypes.GetMetaData().AsQueryable());

            case "SystemUserCodes":
                SystemUserCode systemUserCode = new SystemUserCode();
                return(systemUserCode.GetMetaData().AsQueryable());

            case "SystemUserSecurities":
                SystemUserSecurity systemUserSecurity = new SystemUserSecurity();
                return(systemUserSecurity.GetMetaData().AsQueryable());

            case "SecurityGroups":
                SecurityGroup securityGroup = new SecurityGroup();
                return(securityGroup.GetMetaData().AsQueryable());

            default:     //no table exists for the given tablename given...
                List <Temp> tempList = new List <Temp>();
                Temp        temp     = new Temp();
                temp.ID          = 0;
                temp.Int_1       = 0;
                temp.Bool_1      = true; //bool_1 will flag it as an error...
                temp.Name        = "Error";
                temp.ShortChar_1 = "Table " + tableName + " Is Not A Valid Table Within The Given Entity Collection, Or Meta Data Is Not Publc For The Given Table Name";
                tempList.Add(temp);
                return(tempList.AsQueryable());
            }
        }
Exemplo n.º 15
0
        public virtual void SaveSecurityGroup(HttpContext context)
        {
            YZRequest request   = new YZRequest(context);
            string    mode      = request.GetString("mode");
            string    groupName = request.GetString("GroupName", mode == "new", null);

            JsonSerializer serializer = new JsonSerializer();
            StreamReader   reader     = new StreamReader(context.Request.InputStream);

            using (JsonTextReader streamReader = new JsonTextReader(reader))
            {
                JArray @params = serializer.Deserialize(streamReader) as JArray;

                SecurityGroup     group = @params[0].ToObject <SecurityGroup>(serializer);
                SIDPairCollection sids  = @params[1].ToObject <SIDPairCollection>(serializer);

                using (BPMConnection cn = new BPMConnection())
                {
                    cn.WebOpen();

                    if (mode == "edit")
                    {
                        if (groupName != group.GroupName)
                        {
                            GroupManager.RenameSecurityGroup(cn, groupName, group.GroupName);
                        }

                        GroupManager.UpdateSecutiryGroup(cn, group.GroupName, sids);
                    }
                    else
                    {
                        GroupManager.AddSecutiryGroup(cn, group.GroupName, sids);
                    }
                }
            }
        }
        public InternalMessage SendMessage(string Body, string Subject, Guid Recipient, int ParentId = 0, Guid?Origin = null)
        {
            if ((Origin.HasValue ? this.SecurityGroupRepository.Find(Origin.Value) as ISecurityGroup : this.UserSession.LoggedInUser) is ISecurityGroup origin)
            {
                SecurityGroup target = this.SecurityGroupRepository.Find(Recipient);

                InternalMessage toSend = new InternalMessage()
                {
                    Body      = Body,
                    Subject   = Subject,
                    Recipient = target?.Guid ?? Recipient,
                    Parent    = ParentId == 0 ? null : this.Find(ParentId),
                    Origin    = origin.Guid,
                    To        = target?.ToString() ?? Recipient.ToString(),
                    From      = origin.ToString()
                };

                return(this.SendMessage(toSend, target is User t ? t.Email : string.Empty));
            }
            else
            {
                throw new Exception("Unable to find security group for message.");
            }
        }
Exemplo n.º 17
0
        public SecurityGroup LoadSecurityGroup(int groupId)
        {
            var group  = new SecurityGroup(groupId);
            var groups = new Dictionary <int, SecurityGroup>();

            groups.Add(group.Id, group);
            var rows = 0;

            foreach (var membership in _storage.Memberships.Where(x => x.GroupId == groupId))
            {
                rows++;
                if (membership.IsUser)
                {
                    group.UserMemberIds.Add(membership.MemberId);
                }
                else
                {
                    var memberGroup = EnsureGroup(membership.MemberId, groups);
                    group.Groups.Add(memberGroup);
                    memberGroup.ParentGroups.Add(group);
                }
            }
            return(rows == 0 ? null : group);
        }
Exemplo n.º 18
0
		//-------------------------------------------------------------------------------------
		void frm_DialogClosed(object sender, DialogResult result)
		{
			try
			{
				SimModalDualInputBox frm = (SimModalDualInputBox)sender;
				frm.DialogClosed -= new Sim.Controls.DialogClosedEventHandler(frm_DialogClosed);
				if(result == DialogResult.Cancel)
					return;
				if(frm.Tag == null)
				{
					foreach(SecurityGroup g in psec.SecurityGroups.Values)
						if(g.Name.ToLower() == frm.Value1.ToLower())
						{
							string text = String.Format("Группа безопасности \"{0}\" уже существует.\nВведите другое имя группы.",
									frm.Value1);
							SimModalMessageBox.Show(PanelBack, text, "Ошибка создания группы безопасности", MessageBoxIcon.Error);
							return;
						}
					SecurityGroup gr = new SecurityGroup();
					gr.Name = frm.Value1;
					gr.Description = frm.Value2;

					ShowProgressWindow();
					PulsarQuery q = new PulsarQuery("Security", "SecurityGroups.Add", new { Add = new object[] {gr.SID, gr } },
																																					PulsarQueryParams.Modify);
					TaskManager.Run("AddGroup", this, () => PulsarConnection.Default.Exec(q), gr);
				}
				else
				{
					SecurityGroup gr = ((SecurityGroup)frm.Tag).Clone();
					gr.Name = frm.Value1;
					gr.Description = frm.Value2;

					ShowProgressWindow();
					PulsarQuery q = new PulsarQuery("Security", "SecurityGroups.Item.Name", new { Item = gr.SID, Name = gr.Name },
																																PulsarQueryParams.Modify);
					TaskManager.Run("UpdNameGroup", this, () => PulsarConnection.Default.Exec(q), gr);
					PulsarQuery q2 = new PulsarQuery("Security", "SecurityGroups.Item.Description", 
																								new { Item = gr.SID, Description = gr.Description }, PulsarQueryParams.Modify);
					TaskManager.Run("UpdDescGroup", this, () => PulsarConnection.Default.Exec(q2), gr);
				}
			}
			catch(Exception Err)
			{
				Sim.Controls.ModalErrorBox.Show(Err, PanelBack);
			} 
		}
        public void SendMessage(string Body, string Subject, SecurityGroup Recipient, int ParentId = 0, SecurityGroup Origin = null)
        {
            if (Recipient is null)
            {
                throw new ArgumentNullException(nameof(Recipient));
            }

            this.SendMessage(Body, Subject, Recipient.Guid, ParentId, Origin?.Guid);
        }
Exemplo n.º 20
0
 public ISecurityGroup Locate(string securityId, string securityGroupId)
 {
     return(SecurityGroup.FromLookup(Scope, securityId, securityGroupId));
 }
Exemplo n.º 21
0
        public List <DirectoryEntry> GetSecurityGroupMembership(String securityGroupId)
        {
            System.DirectoryServices.DirectoryEntry rootDirectoryEntry;

            List <DirectoryEntry> membership = new List <DirectoryEntry> ();

            Boolean foundRootDirectoryEntry = false;

            SecurityGroup securityGroup = new SecurityGroup();

            String objectSid;


            if ((String.IsNullOrWhiteSpace(credentials.Domain)) && (String.IsNullOrWhiteSpace(credentials.ServerName)))
            {
                return(membership);
            }


            try { // TO CONNECT TO DIRECTORY SERVICE BY DOMAIN NAME ONLY
                rootDirectoryEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + ((String.IsNullOrWhiteSpace(credentials.Domain) ? credentials.ServerName : credentials.Domain)));

                foundRootDirectoryEntry = true;
            }

            catch (Exception directoryExceptionDomainOnly) {
                System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceError, directoryExceptionDomainOnly);

                try { // TO CONNECT TO DIRECTORY SERVICE BY DOMAIN NAME AND SERVER NAME
                    rootDirectoryEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + credentials.Domain + "/" + credentials.ServerName);

                    foundRootDirectoryEntry = true;
                }

                catch (Exception directoryException) {
                    System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceError, directoryException);

                    throw new ApplicationException("Unable to retreive group list for this Domain (" + credentials.Domain + ").");
                }
            } // END TRY: CONNECT TO DIRECTORY SERVICES



            if (foundRootDirectoryEntry)
            {
                foreach (System.DirectoryServices.DirectoryEntry currentEntry in rootDirectoryEntry.Children)
                {
                    try {
                        if (currentEntry.SchemaClassName.ToLower() == "group")
                        {
                            if (currentEntry.Properties["groupType"].Value != null)
                            {
                                objectSid = ObjectSidToString(((byte[])currentEntry.Properties["objectSid"].Value));

                                if (securityGroupId == objectSid)
                                {
                                    Object groupMembers = currentEntry.Invoke("members", null);

                                    foreach (Object currentMember in (System.Collections.IEnumerable)groupMembers)
                                    {
                                        membership.Add(new DirectoryEntry(new System.DirectoryServices.DirectoryEntry(currentMember)));
                                    }
                                }
                            }
                        }
                    }

                    catch (Exception propertyException) {
                        // DO NOTHING

                        System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceError, propertyException.Message);
                    }
                }
            }

            return(membership);
        }
Exemplo n.º 22
0
        internal AutoScaledInstances(
            CdkStack stack,
            CfnParameter targetPlatform,
            Vpc vpc,
            bool publicAccess,
            SecurityGroup albSecurityGroup,
            SecurityGroup instanceSecurityGroup,
            Database database = null,
            Policy policy     = null,
            ApplicationLoadBalancer restApiLoadBalancer = null)
        {
            IMachineImage selectedImage;

            bool targetWindows = false;

            if (targetWindows)
            {
                var userData = UserData.ForWindows();
                userData.AddCommands(
                    "New-Item -Path c:\\temp -ItemType Directory -Force",
                    $"Read-S3Object -BucketName aws-codedeploy-{stack.Region}/latest -Key codedeploy-agent.msi -File c:\\temp\\codedeploy-agent.msi",
                    "Start-Process -Wait -FilePath c:\\temp\\codedeploy-agent.msi -WindowStyle Hidden"
                    );
                selectedImage = new WindowsImage(
                    WindowsVersion.WINDOWS_SERVER_2019_ENGLISH_CORE_BASE,
                    new WindowsImageProps
                {
                    UserData = userData
                }
                    );
            }
            else
            {
                var userData = UserData.ForLinux(new LinuxUserDataOptions {
                    Shebang = "#!/bin/bash -xe"
                });
                userData.AddCommands(
                    "exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1",
                    "yum install -y aws-cli ruby jq",
                    "yum -y update",
                    "cd /tmp/",
                    $"curl -O https://aws-codedeploy-{stack.Region}.s3.amazonaws.com/latest/install",
                    "chmod +x ./install",
                    "if ./install auto; then",
                    "    echo \"CodeDeploy Agent installation completed successfully!\"",
                    "    exit 0",
                    "else",
                    "    echo \"CodeDeploy Agent installation failed, please investigate.\"",
                    "    rm -f /tmp/install",
                    "    exit 1",
                    "fi",
                    "rm -rf /tmp/*"
                    );
                selectedImage = new AmazonLinuxImage(new AmazonLinuxImageProps
                {
                    Edition        = AmazonLinuxEdition.STANDARD,
                    Virtualization = AmazonLinuxVirt.HVM,
                    Generation     = AmazonLinuxGeneration.AMAZON_LINUX_2,
                    Storage        = AmazonLinuxStorage.EBS,
                    UserData       = userData
                });
            };

            var alb = new ApplicationLoadBalancer(stack, $"ApplicationLoadBalancer-{(publicAccess ? "public" : "private")}", new ApplicationLoadBalancerProps
            {
                InternetFacing = publicAccess,
                Vpc            = vpc,
                VpcSubnets     = new SubnetSelection {
                    SubnetType = publicAccess ? SubnetType.PUBLIC : SubnetType.PRIVATE
                },
                SecurityGroup = albSecurityGroup,
                IpAddressType = IpAddressType.IPV4,
                Http2Enabled  = true
            });

            var albTargetGroup = new ApplicationTargetGroup(stack, $"ApplicationTargetGroup-{(publicAccess ? "public" : "private")}", new ApplicationTargetGroupProps
            {
                Vpc         = vpc,
                Port        = 80,
                Protocol    = ApplicationProtocol.HTTP,
                TargetType  = TargetType.INSTANCE,
                HealthCheck = new Amazon.CDK.AWS.ElasticLoadBalancingV2.HealthCheck
                {
                    Timeout  = Duration.Seconds(5),
                    Interval = Duration.Seconds(10),
                    HealthyThresholdCount = 2
                }
            });
            var albListener = new ApplicationListener(stack, $"ApplicationListener-{(publicAccess ? "public" : "private")}", new ApplicationListenerProps
            {
                Port          = 80,
                Protocol      = ApplicationProtocol.HTTP,
                DefaultAction = ListenerAction.Forward(new[] { albTargetGroup }),
                LoadBalancer  = alb
            });

            var asg = new AutoScalingGroup(stack, $"ASG-{(publicAccess ? "public" : "private")}", new AutoScalingGroupProps
            {
                Vpc          = vpc,
                MinCapacity  = 2,
                InstanceType = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.MEDIUM),
                MachineImage = selectedImage,
                BlockDevices = new[] {
                    new Amazon.CDK.AWS.AutoScaling.BlockDevice()
                    {
                        DeviceName = "/dev/xvda",
                        Volume     = Amazon.CDK.AWS.AutoScaling.BlockDeviceVolume.Ebs(
                            targetWindows ? 30: 8,
                            new Amazon.CDK.AWS.AutoScaling.EbsDeviceOptions {
                            VolumeType          = Amazon.CDK.AWS.AutoScaling.EbsDeviceVolumeType.GP2,
                            DeleteOnTermination = true
                        }
                            )
                    }
                },
                AssociatePublicIpAddress = false,
                VpcSubnets = new SubnetSelection {
                    SubnetType = SubnetType.PRIVATE
                }
            });

            if (policy != null)
            {
                asg.Role.AttachInlinePolicy(policy);
            }
            asg.Role.AddToPrincipalPolicy(
                new PolicyStatement(new PolicyStatementProps
            {
                Effect    = Effect.ALLOW,
                Actions   = new[] { "ec2:DescribeTags" },
                Resources = new[] { "*" }
            })
                );
            asg.Role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AmazonSSMManagedInstanceCore"));
            asg.Role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AWSXRayDaemonWriteAccess"));
            asg.Role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("CloudWatchAgentServerPolicy"));

            Tag.Add(asg, "Application", stack.StackName);
            if (publicAccess)
            {
                Tag.Add(asg, "ApplicationRole", "Front End");
                Tag.Add(asg, "RESTAPIAddress", restApiLoadBalancer.LoadBalancerDnsName);
            }
            else
            {
                Tag.Add(asg, "ApplicationRole", "REST API");
            }
            if (database != null)
            {
                asg.Node.AddDependency(database.DatabaseResource);
                Tag.Add(asg, "DBSecretArn", database.Password.SecretArn);
            }

            // Enable access from the ALB
            asg.AddSecurityGroup(instanceSecurityGroup);
            Result = new LoadBalancedInstancesResult
            {
                AutoScalingGroup = asg,
                TargetGroup      = albTargetGroup,
                LoadBalancer     = alb
            };
        }
 public SecurityGroup Delete(SecurityGroup group)
 {
     return GroupDao.SoftDelete(group);
 }
Exemplo n.º 24
0
        public SecurityGroup GetSecurityGroup(String securityGroupId)
        {
            System.DirectoryServices.DirectoryEntry rootDirectoryEntry;

            Boolean foundRootDirectoryEntry = false;

            SecurityGroup securityGroup = new SecurityGroup();

            String objectSid;


            try { // TO CONNECT TO DIRECTORY SERVICE BY DOMAIN NAME ONLY
                rootDirectoryEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + credentials.Domain);

                foundRootDirectoryEntry = true;
            }

            catch (Exception directoryExceptionDomainOnly) {
                System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceError, directoryExceptionDomainOnly);

                try { // TO CONNECT TO DIRECTORY SERVICE BY DOMAIN NAME AND SERVER NAME
                    rootDirectoryEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + credentials.Domain + "/" + credentials.ServerName);

                    foundRootDirectoryEntry = true;
                }

                catch (Exception directoryException) {
                    System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceError, directoryException);

                    throw new ApplicationException("Unable to retreive group list for this Domain (" + credentials.Domain + ").");
                }
            } // END TRY: CONNECT TO DIRECTORY SERVICES



            if (foundRootDirectoryEntry)
            {
                foreach (System.DirectoryServices.DirectoryEntry currentEntry in rootDirectoryEntry.Children)
                {
                    try {
                        if (currentEntry.Properties["groupType"].Value != null)
                        {
                            objectSid = ObjectSidToString(((byte[])currentEntry.Properties["objectSid"].Value));

                            if (securityGroupId == objectSid)
                            {
                                securityGroup.SecurityAuthorityId = credentials.SecurityAuthorityId;

                                securityGroup.SecurityAuthorityName = credentials.SecurityAuthorityName;

                                securityGroup.SecurityGroupId = securityGroupId;

                                securityGroup.SecurityGroupName = currentEntry.Properties["name"].Value.ToString();

                                if (!String.IsNullOrEmpty((String)currentEntry.Properties["Description"].Value))
                                {
                                    securityGroup.Description = currentEntry.Properties["Description"].Value.ToString();
                                }

                                break;
                            }
                        } // if (currentPropertyName == "groupType") {
                    }     // END TRY ENUMERATE DIRECTORY ENTRY PROPERTIES

                    catch (Exception propertyException) {
                        // DO NOTHING

                        System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceError, propertyException.Message);
                    }
                }
            }

            return(securityGroup);
        }
Exemplo n.º 25
0
 public void UpdateSecurityGroup(SecurityGroup record)
 {
     record.UpdatedBy = UserInfo.CurrentUserID;
     record.UpdatedOn = DateTime.UtcNow;
     DataContext.Table <SecurityGroup>().UpdateRecord(record);
 }
Exemplo n.º 26
0
        internal CreditoWebApiStack(Construct scope, string id, CustomStackProps props = null)
            : base(scope, id, props)
        {
            var vpc = props.Vpc;

            var creditoWebApiTargetGroup = new ApplicationTargetGroup(this, "CreditoWebApiTargetGroup",
                                                                      new ApplicationTargetGroupProps
            {
                Protocol            = ApplicationProtocol.HTTP,
                Port                = 80,
                Vpc                 = vpc,
                TargetType          = TargetType.IP,
                DeregistrationDelay = Duration.Seconds(60),
                HealthCheck         =
                    new Amazon.CDK.AWS.ElasticLoadBalancingV2.HealthCheck
                {
                    Enabled  = true,
                    Path     = "/api/credito/_monitor/shallow",
                    Protocol = Amazon.CDK.AWS.ElasticLoadBalancingV2.Protocol.HTTP,
                    Port     = "traffic-port",
                    UnhealthyThresholdCount = 2,
                    Interval = Duration.Seconds(60),
                    HealthyThresholdCount = 5,
                    Timeout          = Duration.Seconds(5),
                    HealthyHttpCodes = "200"
                }
            });

            var webApiServiceSecurityGroup = SecurityGroup.FromSecurityGroupId(this,
                                                                               "WebApiServiceSecurityGroup",
                                                                               Fn.ImportValue(Globals.GetDeployEnvironment(this).PutEnvNamePrefixWithDash("WebApiServiceSecurityGroupId")));

            var appListener = ApplicationListener.FromApplicationListenerAttributes(this, "AppListener",
                                                                                    new ApplicationListenerAttributes
            {
                ListenerArn   = Fn.ImportValue(Globals.GetDeployEnvironment(this).PutEnvNamePrefixWithDash("AppListenerArn")),
                SecurityGroup = webApiServiceSecurityGroup
            });

            appListener.AddTargetGroups("CreditoWebApiTargetGroup",
                                        new AddApplicationTargetGroupsProps
            {
                Conditions =
                    new ListenerCondition[]
                {
                    ListenerCondition.PathPatterns(new string[] { "/api/credito*" })
                },
                Priority     = 100,
                TargetGroups = new ApplicationTargetGroup[] { creditoWebApiTargetGroup }
            });

            var creditoWebApiLogGroup = new LogGroup(this, "CreditoWebApiContainerLogGroup",
                                                     new LogGroupProps
            {
                LogGroupName  = $"/ecs/{Globals.GetDeployEnvironment(this).EnvName}/credito/web-api",
                Retention     = RetentionDays.FIVE_DAYS,
                RemovalPolicy = RemovalPolicy.SNAPSHOT
            });

            var creditoWebApiTaskDefinition = new FargateTaskDefinition(this, "CreditoWebApiTaskDefinition",
                                                                        new FargateTaskDefinitionProps
            {
                MemoryLimitMiB = 512,
                Cpu            = 256
            });

            var creditoWebApiLogging = new AwsLogDriver(
                new AwsLogDriverProps
            {
                StreamPrefix = "ecs",
                LogGroup     = creditoWebApiLogGroup
            });

            var creditoWebApiContainer = creditoWebApiTaskDefinition.AddContainer("CreditoWebApiContainer",
                                                                                  new ContainerDefinitionOptions
            {
                Image = ContainerImage.FromAsset(
                    Directory.GetCurrentDirectory(),
                    new AssetImageProps
                {
                    File = "src/Credito.WebApi/Dockerfile"
                }),
                Logging     = creditoWebApiLogging,
                Environment =
                    new Dictionary <string, string>()
                {
                    ["CreditoDatabase__ConnectionString"] =
                        StringParameter.ValueFromLookup(
                            this,
                            $"/{Globals.GetDeployEnvironment(this).EnvName}/credito/web-api/db/connection-string"),
                    ["CreditoDatabase__DatabaseName"] =
                        StringParameter.ValueFromLookup(
                            this,
                            $"/{Globals.GetDeployEnvironment(this).EnvName}/credito/web-api/db/database-name")
                }
            });

            creditoWebApiContainer.AddPortMappings(
                new PortMapping
            {
                ContainerPort = 80,
                HostPort      = 80,
                Protocol      = Amazon.CDK.AWS.ECS.Protocol.TCP
            });

            var cluster = Cluster.FromClusterAttributes(this, "Cluster",
                                                        new ClusterAttributes
            {
                ClusterName    = Fn.ImportValue(Globals.GetDeployEnvironment(this).PutEnvNamePrefixWithDash("ClusterName")),
                Vpc            = vpc,
                SecurityGroups = new SecurityGroup[] { }
            });

            var creditoWebApiService = new FargateService(this, "CreditoWebApiService",
                                                          new FargateServiceProps
            {
                Cluster        = cluster,
                TaskDefinition = creditoWebApiTaskDefinition,
                DesiredCount   = 1,
                CircuitBreaker = new DeploymentCircuitBreaker {
                    Rollback = true
                },
                AssignPublicIp         = false,
                HealthCheckGracePeriod = Duration.Seconds(60),
                SecurityGroups         = new ISecurityGroup[] { webApiServiceSecurityGroup },
                VpcSubnets             = new SubnetSelection {
                    SubnetType = SubnetType.PRIVATE
                }
            });

            creditoWebApiService.AttachToApplicationTargetGroup(creditoWebApiTargetGroup);
        }
Exemplo n.º 27
0
 public void AddNewSecurityGroup(SecurityGroup record)
 {
     DataContext.Table <SecurityGroup>().AddNewRecord(record);
 }
Exemplo n.º 28
0
 /// <inheritdoc cref="SecurityGroup.AddRuleAsync"/>
 public static SecurityGroupRule AddRule(this SecurityGroup securityGroup, SecurityGroupRuleDefinition rule)
 {
     return(securityGroup.AddRuleAsync(rule).ForceSynchronous());
 }
 public SecurityGroup Save(SecurityGroup group)
 {
     return GroupDao.SaveOrUpdate(group);
 }
Exemplo n.º 30
0
        public void Create(Company newReseller)
        {
            OrganizationalUnits organizationalUnits = null;
            Groups groups = null;

            ReverseActions reverse = new ReverseActions();
            try
            {
                organizationalUnits = new OrganizationalUnits(Settings.Username, Settings.DecryptedPassword, Settings.PrimaryDC);
                groups = new Groups(Settings.Username, Settings.DecryptedPassword, Settings.PrimaryDC);

                // Check if the user provided a company code or not
                // If they didn't then we will automatically generate one
                if (string.IsNullOrEmpty(newReseller.CompanyCode))
                    newReseller.CompanyCode = OtherStatics.FindAvailableCompanyCode(newReseller.CompanyName, this.db);

                OrganizationalUnit newOrg = new OrganizationalUnit();
                newOrg.Name = newReseller.CompanyCode;
                newOrg.DisplayName = newReseller.CompanyName;
                newOrg.City = newReseller.City;
                newOrg.State = newReseller.State;
                newOrg.PostalCode = newReseller.ZipCode;
                newOrg.Country = newReseller.Country;
                newOrg.UPNSuffixes = null; // Do not allow UPNSuffixes on the reseller OU
                newOrg.Description = newReseller.Description;

                var createdReseller = organizationalUnits.Create(Settings.HostingOU, newOrg);
                reverse.AddAction(Actions.CreateOrganizationalUnit, createdReseller.DistinguishedName);

                //
                // Create GPOAccess Group
                //
                SecurityGroup newGroup = new SecurityGroup();
                newGroup.Name = string.Format("GPOAccess@{0}", newReseller.CompanyCode.Replace(" ", string.Empty));
                newGroup.SamAccountName = newGroup.Name.Length > 19 ? newGroup.Name.Substring(0, 18) : newGroup.Name;

                groups.Create(createdReseller.DistinguishedName, newGroup);
                reverse.AddAction(Actions.CreateSecurityGroup, newGroup.Name);

                //
                // Add group to hoster GPOAccess group
                //
                groups.AddGroup("GPOAccess@Hosting", newGroup.Name);

                // Add to SQL
                log.DebugFormat("Saving new reseller {0} to the database.", newReseller.CompanyName);
                newReseller.Created = DateTime.Now;
                newReseller.DistinguishedName = createdReseller.DistinguishedName;
                newReseller.IsReseller = true;

                db.Companies.Add(newReseller);
                db.SaveChanges();

                log.InfoFormat("Successfully created new reseller {0}", newReseller.CompanyName);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Error creating new reseller: {0}", ex.ToString());
                reverse.RollbackNow();
                throw;
            }
            finally
            {
                if (groups != null)
                    groups.Dispose();

                if (organizationalUnits != null)
                    organizationalUnits.Dispose();
            }
        }
Exemplo n.º 31
0
        public SecurityGroup Create(string parentOU, SecurityGroup group)
        {
            PrincipalContext ctx = null;
            GroupPrincipal grp = null;

            try
            {
                log.DebugFormat("Creating a new group {0}", group.Name);

                if (string.IsNullOrEmpty(parentOU))
                    throw new MissingFieldException("Create", "parentOU");

                if (string.IsNullOrEmpty(group.Name))
                    throw new MissingFieldException("SecurityGroup", "Name");

                if (string.IsNullOrEmpty(group.SamAccountName))
                    throw new MissingFieldException("SecurityGroup", "SamAccountName");

                if (group.SamAccountName.Length > 19)
                    throw new ArgumentOutOfRangeException(group.SamAccountName);

                ctx = new PrincipalContext(ContextType.Domain, _domainController, parentOU, _username, _password);
                grp = new GroupPrincipal(ctx, group.SamAccountName);
                grp.Name = group.Name;
                grp.IsSecurityGroup = true;

                if (!string.IsNullOrEmpty(group.Description))
                    grp.Description = group.Description;

                if (!string.IsNullOrEmpty(group.DisplayName))
                    grp.DisplayName = group.DisplayName;

                grp.Save();

                log.DebugFormat("Successfully created new group {0}", group.Name);

                // Update the values
                group.DistinguishedName = grp.DistinguishedName;
                group.ObjectGUID = (Guid)grp.Guid;

                return group;
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Error creating new group {0}. Exception: {1}", group.Name, ex.ToString());
                throw;
            }
            finally
            {
                if (grp != null)
                    grp.Dispose();

                if (ctx != null)
                    ctx.Dispose();
            }
        }
Exemplo n.º 32
0
 public void UpdateSecurityGroup(SecurityGroup record)
 {
     DataContext.Table <SecurityGroup>().UpdateRecord(record);
 }
Exemplo n.º 33
0
        private void UpdateArray(DBEntities context, SecurityGroupModel model, SecurityGroup target)
        {
            if (System.Configuration.ConfigurationManager.AppSettings["BlockChangeSecurity"] == "true")
                return;

            model.Roles = model.Roles ?? new List<Guid>();
            foreach (SecurityRole item in target.SecurityRole.ToList())
            {
                if (!model.Roles.Contains(item.Id))
                    target.SecurityRole.Remove(item);
            }

            foreach (SecurityRole item in context.SecurityRole.Where(
                s => model.Roles.Contains(s.Id)).ToList())
            {
                if (!target.SecurityRole.Any(any => item.Id == any.Id))
                    target.SecurityRole.Add(item);
            }
        }
Exemplo n.º 34
0
        internal void LaunchServer(ref bool actionSucceeded, ref string actionMessage)
        {
            try
            {
                string keyPairPath = string.Empty;
                LaunchRequest.KeyPairName = $"KeyPair-{Guid.NewGuid().ToString()}";
                while (!CreateKeyPair(LaunchRequest.KeyPairName, ref keyPairPath))
                {
                    LaunchRequest.KeyPairName = Guid.NewGuid().ToString();
                }

                DescribeVpcsRequest  vpcRequest  = new DescribeVpcsRequest();
                DescribeVpcsResponse vpcResponse = Ec2Client.DescribeVpcsAsync(vpcRequest).GetAwaiter().GetResult();

                Vpc defaultVPC = vpcResponse.Vpcs.Find(x => x.IsDefault); //get the default vpc

                List <Filter> subnetFilter = new List <Filter>()
                {
                    new Filter()
                    {
                        Name = "availability-zone", Values = new List <string>()
                        {
                            LaunchRequest.AvailabilityZone
                        }
                    },
                    new Filter()
                    {
                        Name = "vpc-id", Values = new List <string>()
                        {
                            defaultVPC.VpcId
                        }
                    }
                };

                DescribeSubnetsRequest subnetRequest = new DescribeSubnetsRequest();
                subnetRequest.Filters = subnetFilter;
                DescribeSubnetsResponse subnetResponse = Ec2Client.DescribeSubnetsAsync(subnetRequest).GetAwaiter().GetResult();
                Subnet defaultSubnet = subnetResponse.Subnets.FirstOrDefault();

                Filter SGFilter = new Filter
                {
                    Name   = "vpc-id",
                    Values = new List <string>()
                    {
                        defaultVPC.VpcId
                    }
                };

                DescribeSecurityGroupsRequest SGrequest = new DescribeSecurityGroupsRequest();
                SGrequest.Filters.Add(SGFilter);
                DescribeSecurityGroupsResponse SGresponse = Ec2Client.DescribeSecurityGroupsAsync(SGrequest).GetAwaiter().GetResult();
                SecurityGroup defaultSG = SGresponse.SecurityGroups.FirstOrDefault();

                InstanceNetworkInterfaceSpecification defaultENI = new InstanceNetworkInterfaceSpecification()
                {
                    DeviceIndex = 0,
                    SubnetId    = defaultSubnet.SubnetId,
                    Groups      = new List <string>()
                    {
                        defaultSG.GroupId
                    },
                    AssociatePublicIpAddress = true
                };

                List <InstanceNetworkInterfaceSpecification> enis = new List <InstanceNetworkInterfaceSpecification>()
                {
                    defaultENI
                };

                EbsBlockDevice ebsBlockDevice = new EbsBlockDevice
                {
                    VolumeSize = 10,
                    VolumeType = GetActualStorageType(LaunchRequest.StorageType)
                };
                BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping
                {
                    DeviceName = "/dev/xvda"
                };
                blockDeviceMapping.Ebs = ebsBlockDevice;

                var launchRequest = new RunInstancesRequest()
                {
                    ImageId             = GetImageID(LaunchRequest.AMIType),
                    InstanceType        = GetActualInstanceType(LaunchRequest.InstanceType),
                    MinCount            = LaunchRequest.NumOfInstances,
                    MaxCount            = LaunchRequest.NumOfInstances,
                    KeyName             = LaunchRequest.KeyPairName,
                    Placement           = new Placement(LaunchRequest.AvailabilityZone),
                    NetworkInterfaces   = enis,
                    BlockDeviceMappings = new List <BlockDeviceMapping>()
                    {
                        blockDeviceMapping
                    }
                };

                RunInstancesResponse launchResponse = Ec2Client.RunInstancesAsync(launchRequest).GetAwaiter().GetResult();

                List <String> instanceIds = new List <string>();
                foreach (Instance instance in launchResponse.Reservation.Instances)
                {
                    Console.WriteLine(instance.InstanceId);
                    instanceIds.Add(instance.InstanceId);
                }

                actionSucceeded = true;
                actionMessage   = $"The instance(s) are being launched. Please check the AWS Console to verify. {keyPairPath}";
            }
            catch (Exception ex)
            {
                context.Logger.LogLine($"ServerOperationsHelper::LaunchServer {ex.Message}");
                context.Logger.LogLine($"ServerOperationsHelper::LaunchServer {ex.StackTrace}");
                actionSucceeded = false;
                actionMessage   = $"Could not launch the server . Please contact your administrator.";
            }
        }
Exemplo n.º 35
0
        internal NorthwindCdkStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var vpc = new Vpc(this, "LabVpc", new VpcProps
            {
                MaxAzs = 2
            });



            // SQL Server

            var sg = new SecurityGroup(this, "NorthwindDatabaseSecurityGroup", new SecurityGroupProps
            {
                Vpc = vpc,

                SecurityGroupName = "Northwind-DB-SG",
                AllowAllOutbound  = false
            });

            // !!!!!!!!!! replace IP according to the instructions above
            sg.AddIngressRule(Peer.Ipv4("35.171.193.180/32"), Port.Tcp(1433)); // SQL Server
            // !!!!!!!!!!

            var sql = new DatabaseInstance(this, "NorthwindSQLServer", new DatabaseInstanceProps
            {
                Vpc = vpc,

                InstanceIdentifier = "northwind-sqlserver",
                Engine             = DatabaseInstanceEngine.SqlServerEx(new SqlServerExInstanceEngineProps {
                    Version = SqlServerEngineVersion.VER_14
                }),                                                                                                                          // SQL Server Express

                Credentials = Credentials.FromUsername("adminuser", new CredentialsFromUsernameOptions()
                {
                    Password = new SecretValue("Admin12345?")
                }),


                //MasterUsername = "******",
                //MasterUserPassword = new SecretValue("Admin12345?"),

                InstanceType   = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.SMALL), // t3.small
                SecurityGroups = new ISecurityGroup[] { sg },
                MultiAz        = false,
                VpcSubnets     = new SubnetSelection()
                {
                    SubnetType = SubnetType.PUBLIC
                },                              // public subnet

                DeletionProtection     = false, // you need to be able to delete database
                DeleteAutomatedBackups = true,
                BackupRetention        = Duration.Days(0),
                RemovalPolicy          = RemovalPolicy.DESTROY // you need to be able to delete database
            });;

            new CfnOutput(this, "SQLServerEndpointAddress", new CfnOutputProps
            {
                Value = sql.DbInstanceEndpointAddress
            });

            // SQL Server connection string in Systems Manager Parameter Store

            new StringParameter(this, "NorthwindDatabaseConnectionString", new StringParameterProps
            {
                ParameterName = "/Northwind/ConnectionStrings/NorthwindDatabase",
                Type          = ParameterType.STRING,
                Description   = "SQL Server connection string",
                StringValue   = string.Format("Server={0},1433;Integrated Security=false;User ID=adminuser;Password=Admin12345?;Initial Catalog=NorthwindTraders;", sql.DbInstanceEndpointAddress)
            });



            // PostgreSQL setup

            // !!!!!!!!!! add 2 rules when you use provided VM, add 1 rule when you use your computer
            sg.AddIngressRule(Peer.Ipv4("35.171.193.180/32"), Port.Tcp(5432)); // PostgreSQL
            sg.AddIngressRule(Peer.Ipv4("3.238.53.13/32"), Port.Tcp(5432));    // PostgreSQL
            // !!!!!!!!!!

            var postgreSql = new DatabaseCluster(this, "NorthwindPostgreSQL", new DatabaseClusterProps
            {
                InstanceProps = new Amazon.CDK.AWS.RDS.InstanceProps
                {
                    Vpc            = vpc,
                    InstanceType   = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.MEDIUM), // t3.medium
                    SecurityGroups = new ISecurityGroup[] { sg },
                    VpcSubnets     = new SubnetSelection()
                    {
                        SubnetType = SubnetType.PUBLIC
                    },                                                                     // you need to access database from your developer PC
                    ParameterGroup = ParameterGroup.FromParameterGroupName(this, "DBInstanceParameterGroup", "default.aurora-postgresql11"),
                },
                ParameterGroup    = ParameterGroup.FromParameterGroupName(this, "DBClusterParameterGroup", "default.aurora-postgresql11"),
                ClusterIdentifier = "northwind-postgresql",
                Engine            = DatabaseClusterEngine.AuroraPostgres(new AuroraPostgresClusterEngineProps
                {
                    Version = AuroraPostgresEngineVersion.VER_11_6
                }),                                                  // Aurora PostgreSQL
                Credentials = Credentials.FromUsername("adminuser", new CredentialsFromUsernameOptions
                {
                    Password = new SecretValue("Admin12345?")
                }),
                //MasterUser = new Login
                //{
                //    Username = "******",
                //    Password = new SecretValue("Admin12345?")
                //},
                Instances = 1,
                Port      = 5432,

                Backup = new BackupProps
                {
                    Retention = Duration.Days(1) // minimum is 1
                },

                DefaultDatabaseName    = "NorthwindTraders",
                InstanceIdentifierBase = "northwind-postgresql-instance",

                RemovalPolicy = RemovalPolicy.DESTROY // you need to be able to delete database,
            });;

            new CfnOutput(this, "PostgreSQLEndpointAddress", new CfnOutputProps
            {
                Value = postgreSql.ClusterEndpoint.Hostname
            });


            // Aurora PostgreSQL connection string in Systems Manager Parameter Store

            new StringParameter(this, "NorthwindPostgreSQLDatabaseConnectionString", new StringParameterProps
            {
                ParameterName = "/Northwind/ConnectionStrings/NorthwindPostgreDatabase",
                Type          = ParameterType.STRING,
                Description   = "PostgreSQL connection string",
                StringValue   = string.Format("Server={0};Database=NorthwindTraders;Username=adminuser;Password=Admin12345?", postgreSql.ClusterEndpoint.Hostname)
            });
        }
Exemplo n.º 36
0
        /// <summary>
        /// Creates a new company in AD and the database
        /// </summary>
        /// <param name="newCompany"></param>
        /// <param name="domainName"></param>
        /// <param name="resellerCode"></param>
        public void Create(Company newCompany, string domainName, string resellerCode)
        {
            OrganizationalUnits organizationalUnits = null;
            Groups groups = null;

            ReverseActions reverse = new ReverseActions();
            try
            {
                if (string.IsNullOrEmpty(domainName))
                    throw new MissingFieldException("", "DomainName");

                if (string.IsNullOrEmpty(resellerCode))
                    throw new MissingFieldException("", "ResellerCode");

                organizationalUnits = new OrganizationalUnits(Settings.Username, Settings.DecryptedPassword, Settings.PrimaryDC);
                groups = new Groups(Settings.Username, Settings.DecryptedPassword, Settings.PrimaryDC);

                // Check if the user provided a company code or not
                // If they didn't then we will automatically generate one
                if (string.IsNullOrEmpty(newCompany.CompanyCode))
                    newCompany.CompanyCode = OtherStatics.FindAvailableCompanyCode(newCompany.CompanyName, this.db);

                OrganizationalUnit newOrg = new OrganizationalUnit();
                newOrg.Name = newCompany.CompanyCode;
                newOrg.DisplayName = newCompany.CompanyName;
                newOrg.City = newCompany.City;
                newOrg.State = newCompany.State;
                newOrg.PostalCode = newCompany.ZipCode;
                newOrg.Country = newCompany.Country;
                newOrg.UPNSuffixes = new[] { domainName };
                newOrg.Description = newCompany.Description;

                var createdCompany = organizationalUnits.Create(Settings.HostingOU, newOrg);
                reverse.AddAction(Actions.CreateOrganizationalUnit, createdCompany.DistinguishedName);

                //
                // Create security groups
                //
                string strippedCompanyCode = newCompany.CompanyCode.Replace(" ", string.Empty);

                // Create Admins@ group
                SecurityGroup newGroup = new SecurityGroup();
                newGroup.Name = string.Format("Admins@", strippedCompanyCode);
                newGroup.SamAccountName = newGroup.Name.Length > 19 ? newGroup.Name.Substring(0, 18) : newGroup.Name;
                groups.Create(createdCompany.DistinguishedName, newGroup);
                reverse.AddAction(Actions.CreateSecurityGroup, newGroup.Name);

                // Create AllUsers@ group
                newGroup.Name = string.Format("AllUsers@", strippedCompanyCode);
                newGroup.SamAccountName = newGroup.Name.Length > 19 ? newGroup.Name.Substring(0, 18) : newGroup.Name;
                groups.Create(createdCompany.DistinguishedName, newGroup);
                reverse.AddAction(Actions.CreateSecurityGroup, newGroup.Name);

                // Create AllTSUsers@ group
                newGroup.Name = string.Format("AllTSUsers@", strippedCompanyCode);
                newGroup.SamAccountName = newGroup.Name.Length > 19 ? newGroup.Name.Substring(0, 18) : newGroup.Name;
                groups.Create(createdCompany.DistinguishedName, newGroup);
                reverse.AddAction(Actions.CreateSecurityGroup, newGroup.Name);
                groups.AddGroup("GPOAccess@" + resellerCode, newGroup.Name); // Add group to the GPOAccess group in resellers OU

                //
                // Create Exchange and Applications OU
                //
                newOrg = new OrganizationalUnit();
                newOrg.Name = Settings.ExchangeOU;
                newOrg.DisplayName = Settings.ExchangeOU;
                newOrg.UPNSuffixes = new[] { domainName };

                var createdOrg = organizationalUnits.Create(createdCompany.DistinguishedName, newOrg);
                reverse.AddAction(Actions.CreateOrganizationalUnit, createdOrg.DistinguishedName);

                newOrg = new OrganizationalUnit();
                newOrg.Name = Settings.ApplicationsOU;
                newOrg.DisplayName = Settings.ApplicationsOU;
                newOrg.UPNSuffixes = new[] { domainName };

                createdOrg = organizationalUnits.Create(createdCompany.DistinguishedName, newOrg);
                reverse.AddAction(Actions.CreateOrganizationalUnit, createdOrg.DistinguishedName);

                // Add to SQL
                log.DebugFormat("Saving new company {0} to the database.", newCompany.CompanyName);
                newCompany.Created = DateTime.Now;
                newCompany.DistinguishedName = createdCompany.DistinguishedName;
                newCompany.IsReseller = false;

                db.Companies.Add(newCompany);
                db.SaveChanges();

                log.InfoFormat("Successfully created new company {0}", newCompany.CompanyName);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Error creating new company: {0}", ex.ToString());
                reverse.RollbackNow();
                throw;
            }
            finally
            {
                if (groups != null)
                    groups.Dispose();

                if (organizationalUnits != null)
                    organizationalUnits.Dispose();
            }
        }
Exemplo n.º 37
0
		public static SecurityItem FromGroup(SecurityGroup group)
		{
			SecurityItem ch = new SecurityItem();
			ch.SID = group.SID;
			ch.Image = global::Sim.AdminForms.Properties.Resources.Group;
			ch.Name = group.Name;
			ch.Desc = group.Description;
			return ch;
		}
Exemplo n.º 38
0
 /// <inheritdoc cref="SecurityGroupReference.DeleteAsync"/>
 public static void Update(this SecurityGroup securityGroup)
 {
     securityGroup.UpdateAsync().ForceSynchronous();
 }
Exemplo n.º 39
0
 private BindingList <SecurityGroup> GetSecurityGroups(SecurityGroup itemQueryObject, string companyID)
 {//note this get is to the singleton repository...
     return(new BindingList <SecurityGroup>(_serviceAgent.GetSecurityGroups(itemQueryObject, companyID).ToList()));
 }