示例#1
0
    def create_security_groups(self):
        t = self.template

        t.add_resource(
            ec2.SecurityGroup(
                ELB_SG_NAME,
                GroupDescription="Security group for load balancer",
                VpcId=Ref("VpcId")))
        t.add_resource(
            ec2.SecurityGroupIngress(
                "ELBPort80FromTrustedNetwork",
                IpProtocol="tcp", FromPort="80", ToPort="80",
                CidrIp=Ref("TrustedNetwork"),
                Condition="UseHTTP",
                GroupId=Ref(ELB_SG_NAME)))
        t.add_resource(
            ec2.SecurityGroupIngress(
                "ELBPort443FromTrustedNetwork",
                IpProtocol="tcp", FromPort="443", ToPort="443",
                CidrIp=Ref("TrustedNetwork"),
                Condition="UseHTTPS",
                GroupId=Ref(ELB_SG_NAME)))
        t.add_resource(
            ec2.SecurityGroupIngress(
                "ELBPort443GitHub",
                IpProtocol="tcp", FromPort="443", ToPort="443",
                CidrIp=Ref("GitHubCIDR"),
                Condition="UseHTTPS",
                GroupId=Ref(ELB_SG_NAME)))
        t.add_resource(
            ec2.SecurityGroupIngress(
                "80ToControllerPort8081",
                IpProtocol="tcp", FromPort="8081", ToPort="8081",
                SourceSecurityGroupId=Ref(ELB_SG_NAME),
                GroupId=Ref("InstanceSecurityGroup")))
示例#2
0
    def create_db_rules(self):
        self.template.add_resource(
            ec2.SecurityGroupIngress(
                'ClientPsqlPort5432',
                IpProtocol="tcp",
                FromPort="5432",
                ToPort="5432",
                SourceSecurityGroupId=Ref(self.CLIENT_SG_NAME),
                GroupId=Ref(self.RDS_SG_NAME),
            )
        )

        # If there is a bastion sg, add inbound access from the bastion to RDS.
        variables = self.get_variables()
        bastion_sg = variables[self.BASTION_SG_NAME]
        if bastion_sg:
            self.template.add_resource(
                ec2.SecurityGroupIngress(
                    'BastionPsqlPort5432',
                    IpProtocol="tcp",
                    FromPort="5432",
                    ToPort="5432",
                    SourceSecurityGroupId=bastion_sg,
                    GroupId=Ref(self.RDS_SG_NAME),
                )
            )
示例#3
0
    def create_security_groups(self):
        t = self.template
        t.add_resource(
            ec2.SecurityGroup(CLUSTER_SG_NAME,
                              GroupDescription='EmpireMinionSecurityGroup',
                              VpcId=Ref("VpcId")))
        t.add_output(Output('EmpireMinionSG', Value=Ref(CLUSTER_SG_NAME)))
        # Allow all ports within cluster
        t.add_resource(
            ec2.SecurityGroupIngress(
                "EmpireMinionAllTCPAccess",
                IpProtocol='-1',
                FromPort='-1',
                ToPort='-1',
                SourceSecurityGroupId=Ref(CLUSTER_SG_NAME),
                GroupId=Ref(CLUSTER_SG_NAME)))

        # Application ELB Security Groups
        # Internal
        for elb in ('public', 'private'):
            group_name = "Empire%sAppELBSG" % elb.capitalize()
            t.add_resource(
                ec2.SecurityGroup(group_name,
                                  GroupDescription=group_name,
                                  VpcId=Ref("VpcId"),
                                  Tags=Tags(Name='%s-app-elb-sg' % elb)))
            t.add_output(
                Output("%sEmpireAppELBSG" % elb.capitalize(),
                       Value=Ref(group_name)))

            # Allow ELB to talk to cluster on 9000-10000
            t.add_resource(
                ec2.SecurityGroupIngress("Empire%sAppPort9000To10000" %
                                         elb.capitalize(),
                                         IpProtocol="tcp",
                                         FromPort=9000,
                                         ToPort=10000,
                                         SourceSecurityGroupId=Ref(group_name),
                                         GroupId=Ref(CLUSTER_SG_NAME)))

            # Allow anything to talk to the ELB
            # If internal only internal hosts will be able to talk to
            # the elb
            t.add_resource(
                ec2.SecurityGroupIngress("Empire%sELBAllow80" %
                                         elb.capitalize(),
                                         IpProtocol="tcp",
                                         FromPort=80,
                                         ToPort=80,
                                         CidrIp="0.0.0.0/0",
                                         GroupId=Ref(group_name)))
            t.add_resource(
                ec2.SecurityGroupIngress("Empire%sELBAllow443" %
                                         elb.capitalize(),
                                         IpProtocol="tcp",
                                         FromPort=443,
                                         ToPort=443,
                                         CidrIp="0.0.0.0/0",
                                         GroupId=Ref(group_name)))
示例#4
0
def vpc_security_rules(inp):
    sg_spec = readify(inp)
    out = []
    for line in sg_spec.splitlines():
        if not line or line.startswith('#'):
            continue
        pieces = re.split('\s+', line)
        resource_name = pieces[0]
        sg_type = pieces[1]
        first = pieces[2]
        second = pieces[3]
        protocol = pieces[4]
        port_range = pieces[5].split(':')

        kwargs = {
            "FromPort": int(port_range[0]),
            "ToPort": int(port_range[1]),
            "IpProtocol": protocol
        }

        if sg_type == 'ingress':
            if re.match(r'^[0-9\.\/]*$', first):
                kwargs['CidrIp'] = first
            else:
                kwargs['SourceSecurityGroupId'] = Ref(first)
            kwargs['GroupId'] = Ref(second)
            out.append(ec2.SecurityGroupIngress(resource_name, **kwargs))
        else:
            if pieces[0] == 'ingress':
                kwargs["SourceSecurityGroupId"] = Ref(pieces[1])
            else:
                kwargs["DestinationSecurityGroupId"] = Ref(pieces[1])
    return out
    def add_ingress(self, sender, port):
        """
        Add an ingress rule to this SecurityEnabledObject after evaluating if it is a Security group or CIDR tuple
        ([0] = title, [1] = ip)
        Creates a Troposphere SecurityGroupIngress object
        AWS Cloud Formation:
        http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html
        Troposphere link: https://github.com/cloudtools/troposphere/blob/master/troposphere/ec2.py
        :param sender: The SecurityEnabledObject that will be sending traffic to this SecurityEnabledObject,
        sender[0] = title, sender[1] = ip
        :param port: Port to send, and receive traffic on
        """
        sender_title = sender.title if hasattr(sender, 'title') else sender['name']

        if port == '-1':
            common = {'IpProtocol': 'tcp', 'FromPort': '0', 'ToPort': '65535', 'GroupId': self.security_group}
            name = self.title + 'AllFrom' + sender_title + 'All'
        else:
            common = {'IpProtocol': 'tcp', 'FromPort': port, 'ToPort': port, 'GroupId': self.security_group}
            name = self.title + port + 'From' + sender_title + port

        ingress = self.template.add_resource(ec2.SecurityGroupIngress(get_cf_friendly_name(name), **common))

        if isinstance(sender, SecurityEnabledObject):
            ingress.SourceSecurityGroupId = sender.security_group
        else:
            ingress.CidrIp = sender['cidr']

        self.ingress.append(ingress)
示例#6
0
    def add_resources_and_output(self):
        """Add resources to template."""
        template = self.template
        variables = self.get_variables()

        ec2securitygroup = template.add_resource(
            ec2.SecurityGroup('Sg',
                              GroupName=variables['SgName'].ref,
                              GroupDescription=variables['SgDescription'].ref,
                              Tags=Tags(variables['Tags']),
                              VpcId=variables['VpcId'].ref))

        for rule, settings in variables['Rules'].iteritems():
            if 'IpProtocol' not in settings.keys():
                settings['IpProtocol'] = 'tcp'
            template.add_resource(
                ec2.SecurityGroupIngress(
                    'SgIngress{}'.format(sub('[/.-]', '', rule)),
                    GroupId=GetAtt(ec2securitygroup, 'GroupId'),
                    **settings))

        template.add_output(
            Output('{}Id'.format(ec2securitygroup.title),
                   Description='ID of the Security Group created',
                   Value=GetAtt(ec2securitygroup, 'GroupId'),
                   Export=Export(
                       Sub('${AWS::StackName}-%sId' %
                           ec2securitygroup.title))))
示例#7
0
def configure_security_groups(vpc_subnet, vpc_id):

    node_sec_group = ec2.SecurityGroup('DustNodeSG')
    node_sec_group.GroupDescription = "Allow incoming ssh and icmp and all intracluster tcp"
    if vpc_subnet:
        node_sec_group.VpcId = vpc_id

    ssh_in_rule = ec2.SecurityGroupRule()
    ssh_in_rule.FromPort = 22
    ssh_in_rule.ToPort = 22
    ssh_in_rule.CidrIp = "0.0.0.0/0"
    ssh_in_rule.IpProtocol = 'tcp'

    icmp_in_rule = ec2.SecurityGroupRule()
    icmp_in_rule.FromPort = -1
    icmp_in_rule.ToPort = -1
    icmp_in_rule.CidrIp = "0.0.0.0/0"
    icmp_in_rule.IpProtocol = 'icmp'

    node_sec_group.SecurityGroupIngress = [ssh_in_rule, icmp_in_rule]

    intracluster_sec_group = ec2.SecurityGroupIngress('DustIntraClusterSG')
    if vpc_subnet:
        intracluster_sec_group.GroupId = Ref(node_sec_group)
    else:
        intracluster_sec_group.GroupName = Ref(node_sec_group)
    intracluster_sec_group.FromPort = 0 
    intracluster_sec_group.ToPort = 65535
    if vpc_subnet:
        intracluster_sec_group.SourceSecurityGroupId = Ref(node_sec_group)
    else:
        intracluster_sec_group.SourceSecurityGroupName = Ref(node_sec_group)
    intracluster_sec_group.IpProtocol = "-1"

    return node_sec_group, intracluster_sec_group 
示例#8
0
    def create_security_groups(self, template, sg_name):

        template.add_resource(
            ec2.SecurityGroup(sg_name,
                              GroupName=sg_name,
                              GroupDescription=sg_name,
                              VpcId=Ref("VpcId"),
                              Tags=[{
                                  'Key': 'Name',
                                  'Value': sg_name
                              }]))

        template.add_output(Output("InternalAlbSG", Value=Ref(sg_name)))

        sg_ingress_name = "SecurityGroupIngressTo443"

        # TODO: take a list of Cidr's
        # Allow Internet to connect to ALB
        template.add_resource(
            ec2.SecurityGroupIngress(
                sg_ingress_name,
                IpProtocol="tcp",
                FromPort="443",
                ToPort="443",
                CidrIp="10.0.0.0/0",
                GroupId=Ref(sg_name),
            ))
示例#9
0
    def create_security_groups(self):
        t = self.template
        cluster_rules = []
        cluster_rules.append(
            ec2.SecurityGroupRule(IpProtocol='tcp',
                                  FromPort=22,
                                  ToPort=22,
                                  CidrIp=Ref('OfficeNetwork')))
        sg = t.add_resource(
            ec2.SecurityGroup(CLUSTER_SG_NAME,
                              GroupDescription='BastionSecurityGroup',
                              SecurityGroupIngress=cluster_rules,
                              VpcId=Ref("VpcId")))

        t.add_output(Output('SecurityGroup', Value=Ref(sg)))

        # Make it so the bastion hosts can ssh into any other host.
        t.add_resource(
            ec2.SecurityGroupIngress(
                'AllowSSHAnywhere',
                IpProtocol='tcp',
                FromPort=22,
                ToPort=22,
                SourceSecurityGroupId=Ref(CLUSTER_SG_NAME),
                GroupId=Ref('DefaultSG')))
示例#10
0
    def create_security_groups(self):
        t = self.template

        t.add_resource(
            ec2.SecurityGroup(CLUSTER_SG_NAME,
                              GroupDescription=CLUSTER_SG_NAME,
                              VpcId=Ref("VpcId")))
        t.add_output(Output('EmpireControllerSG', Value=Ref(CLUSTER_SG_NAME)))

        # Allow access to the DB
        t.add_resource(
            ec2.SecurityGroupIngress(
                "EmpireControllerDBAccess",
                IpProtocol='tcp',
                FromPort=5432,
                ToPort=5432,
                SourceSecurityGroupId=Ref(CLUSTER_SG_NAME),
                GroupId=Ref('EmpireDBSecurityGroup')))

        # Now setup all Empire ELB SG stuff
        t.add_resource(
            ec2.SecurityGroup(ELB_SG_NAME,
                              GroupDescription=ELB_SG_NAME,
                              VpcId=Ref("VpcId")))
        t.add_resource(
            ec2.SecurityGroupIngress("EmpireControllerELBPort80FromTrusted",
                                     IpProtocol='tcp',
                                     FromPort='80',
                                     ToPort='80',
                                     CidrIp=Ref("TrustedNetwork"),
                                     GroupId=Ref(ELB_SG_NAME)))
        t.add_resource(
            ec2.SecurityGroupIngress("EmpireControllerELBPort443FromTrusted",
                                     IpProtocol='tcp',
                                     FromPort='443',
                                     ToPort='443',
                                     CidrIp=Ref("TrustedNetwork"),
                                     GroupId=Ref(ELB_SG_NAME)))

        t.add_resource(
            ec2.SecurityGroupIngress("ELBPort80ToControllerPort8080",
                                     IpProtocol='tcp',
                                     FromPort='8080',
                                     ToPort='8080',
                                     SourceSecurityGroupId=Ref(ELB_SG_NAME),
                                     GroupId=Ref(CLUSTER_SG_NAME)))
示例#11
0
 def instance_security_group_ingress_internal(self):
     return ec2.SecurityGroupIngress(
         "PilosaInternalIngress",
         IpProtocol='tcp',
         FromPort='12000',
         ToPort='12000',
         GroupId=Ref(self.instance_security_group),
         SourceSecurityGroupId=Ref(self.instance_security_group),
     )
示例#12
0
 def create_db_rules(self):
     self.template.add_resource(
         ec2.SecurityGroupIngress(
             "MasterAPIDBMinionAccess",
             IpProtocol='tcp',
             FromPort=3306,
             ToPort=3306,
             SourceSecurityGroupId=Ref("MinionSecurityGroup"),
             GroupId=Ref('MasterAPIDBSecurityGroup')))
示例#13
0
 def create_security_groups(self):
     self.template.add_resource(
         ec2.SecurityGroupIngress(
             'EmpireMinionRedisAccess',
             IpProtocol='TCP',
             FromPort=6379,
             ToPort=6379,
             SourceSecurityGroupId=Ref('MinionSecurityGroup'),
             GroupId=Ref('RedisSecurityGroup'),
         ), )
示例#14
0
文件: vpc.py 项目: pierretr/e3-aws
 def ingress_rule(self) -> ec2.SecurityGroupIngress:
     """Return Ingress rule allowing traffic from aws VPC endpoints."""
     return ec2.SecurityGroupIngress(
         name_to_id(f"{self.name}Ingress"),
         CidrIp=self.cidr_block,
         FromPort="443",
         ToPort="443",
         IpProtocol="tcp",
         GroupId=Ref(self.security_group),
     )
示例#15
0
 def handle(self, chain_context):
     template = chain_context.template
     template.add_resource(
         ec2.SecurityGroupIngress(
             self.name,
             IpProtocol="tcp",
             FromPort=self.port_to_open,
             ToPort=self.port_to_open,
             CidrIp=self.cidr,
             GroupId=chain_context.metadata[META_SECURITY_GROUP_REF]))
示例#16
0
 def rule_adder_self(self, group, fromport, toport=None, protocol='TCP'):
     """ This function exits to create self-referencing security groups. """
     if toport is None:
         toport = fromport
     rule = ec2.SecurityGroupIngress("IngressRule",
                                     IpProtocol=protocol,
                                     FromPort=fromport,
                                     ToPort=toport,
                                     SourceSecurityGroupId=Ref(group),
                                     GroupId=Ref(group))
     self.template.add_resource(rule)
def add_secgroup(t):
    sg_in = []
    sg_out = []

    #Ingress TCP ports
    for port in ['21', '80', '111', '443', '445', '2049', '3712', '8000']:
        sg_in.append(
            ec2.SecurityGroupRule(
                Description=
                "TCP ports for NFS, SMB, FTP, Management, and Replication",
                IpProtocol='tcp',
                FromPort=port,
                ToPort=port,
                CidrIp='0.0.0.0/0'))

    #Ingress UDP ports
    for port in ['111', '2049']:
        sg_in.append(
            ec2.SecurityGroupRule(Description="UDP ports for NFS",
                                  IpProtocol='udp',
                                  FromPort=port,
                                  ToPort=port,
                                  CidrIp='0.0.0.0/0'))

    #Egress rule for all ports and protocols
    sg_out.append(
        ec2.SecurityGroupRule(Description="Outbound traffic",
                              IpProtocol='-1',
                              FromPort=0,
                              ToPort=0,
                              CidrIp='0.0.0.0/0'))

    t.add_resource(
        ec2.SecurityGroup(
            "QumuloSecurityGroup",
            GroupDescription=
            "Enable ports for NFS/SMB/FTP, Management, Replication, and Clustering.",
            SecurityGroupIngress=sg_in,
            SecurityGroupEgress=sg_out,
            VpcId=Ref("VpcId")))

    # Self referencing security rules need to be added after the group is created.
    # This rule is enabling all traffic between members of the security group for
    # clustering.
    t.add_resource(
        ec2.SecurityGroupIngress(
            "QumuloSecurityGroupNodeRule",
            DependsOn="QumuloSecurityGroup",
            Description="Qumulo Internode Communication",
            GroupId=Ref("QumuloSecurityGroup"),
            IpProtocol='-1',
            FromPort=0,
            ToPort=0,
            SourceSecurityGroupId=Ref("QumuloSecurityGroup")))
示例#18
0
    def create_reciprocal_sg(self,
                             source_group,
                             source_group_name,
                             destination_group,
                             destination_group_name,
                             from_port,
                             to_port=None,
                             ip_protocol='tcp'):
        '''
        Helper method creates reciprocal ingress and egress rules given two existing security groups and a set of ports
        @param source_group [Troposphere.ec2.SecurityGroup] Object reference to the source security group
        @param source_group_name [string] friendly name of the source security group used for labels
        @param destination_group [Troposphere.ec2.SecurityGroup] Object reference to the destination security group
        @param destination_group_name [string] friendly name of the destination security group used for labels
        @param from_port [string] lower boundary of the port range to set for the secuirty group rules
        @param to_port [string] upper boundary of the port range to set for the security group rules
        @param ip_protocol [string] name of the IP protocol to set this rule for
        '''
        if to_port == None:
            to_port = from_port
        if isinstance(from_port, unicode):
            from_port = from_port.encode('ascii', 'ignore')
        if isinstance(to_port, unicode):
            to_port = to_port.encode('ascii', 'ignore')
        if from_port == to_port:
            if isinstance(from_port, str):
                label_suffix = ip_protocol.capitalize() + from_port
            else:
                label_suffix = ip_protocol.capitalize() + 'Mapped'
        else:
            if isinstance(from_port, str) and isinstance(to_port, str):
                label_suffix = ip_protocol.capitalize(
                ) + from_port + 'To' + to_port
            else:
                label_suffix = ip_protocol.capitalize() + 'MappedPorts'

        self.template.add_resource(
            ec2.SecurityGroupIngress(destination_group_name + 'Ingress' +
                                     source_group_name + label_suffix,
                                     SourceSecurityGroupId=Ref(source_group),
                                     GroupId=Ref(destination_group),
                                     FromPort=from_port,
                                     ToPort=to_port,
                                     IpProtocol=ip_protocol))

        self.template.add_resource(
            ec2.SecurityGroupEgress(
                source_group_name + 'Egress' + destination_group_name +
                label_suffix,
                DestinationSecurityGroupId=Ref(destination_group),
                GroupId=Ref(source_group),
                FromPort=from_port,
                ToPort=to_port,
                IpProtocol=ip_protocol))
示例#19
0
 def create_security_groups(self):
     t = self.template
     asg_sg = CLUSTER_SG_NAME % self.name
     elb_sg = ELB_SG_NAME % self.name
     t.add_resource(
         ec2.SecurityGroup(asg_sg,
                           GroupDescription=asg_sg,
                           VpcId=Ref("VpcId")))
     # ELB Security group, if ELB is used
     t.add_resource(
         ec2.SecurityGroup(elb_sg,
                           GroupDescription=elb_sg,
                           VpcId=Ref("VpcId"),
                           Condition="CreateELB"))
     # Add SG rules here
     # Allow ELB to connect to ASG on port 80
     t.add_resource(
         ec2.SecurityGroupIngress("%sElbToASGPort80" % self.name,
                                  IpProtocol="tcp",
                                  FromPort="80",
                                  ToPort="80",
                                  SourceSecurityGroupId=Ref(elb_sg),
                                  GroupId=Ref(asg_sg),
                                  Condition="CreateELB"))
     # Allow Internet to connect to ELB on port 80
     t.add_resource(
         ec2.SecurityGroupIngress("InternetTo%sElbPort80" % self.name,
                                  IpProtocol="tcp",
                                  FromPort="80",
                                  ToPort="80",
                                  CidrIp="0.0.0.0/0",
                                  GroupId=Ref(elb_sg),
                                  Condition="CreateELB"))
     t.add_resource(
         ec2.SecurityGroupIngress("InternetTo%sElbPort443" % self.name,
                                  IpProtocol="tcp",
                                  FromPort="443",
                                  ToPort="443",
                                  CidrIp="0.0.0.0/0",
                                  GroupId=Ref(elb_sg),
                                  Condition="CreateSSLELB"))
示例#20
0
 def create_security_groups(self):
     # Add rules to access RDS and Redis databases from the empire minions
     # that will run the API
     self.template.add_resource(
         ec2.SecurityGroupIngress(
             'EmpireMinionDatabaseAccess',
             IpProtocol='TCP',
             FromPort=5432,
             ToPort=5432,
             SourceSecurityGroupId=Ref('MinionSecurityGroup'),
             GroupId=Ref('RDSSecurityGroup'),
         ), )
示例#21
0
def buildMySQL(t, args):
    t.add_resource(
        ec2.SecurityGroup('DBSecurityGroup',
                          GroupDescription='Patient Records',
                          VpcId=Ref('VPC'),
                          Tags=Tags(Name='MySQL Access')))

    t.add_resource(
        ec2.SecurityGroupIngress(
            'DBSGIngress',
            GroupId=Ref('DBSecurityGroup'),
            IpProtocol='-1',
            SourceSecurityGroupId=Ref('ApplicationSecurityGroup')))

    t.add_resource(
        rds.DBSubnetGroup(
            'RDSSubnetGroup',
            DBSubnetGroupDescription='MySQL node locations',
            SubnetIds=[Ref('PrivateSubnet1'),
                       Ref('PrivateSubnet2')]))

    if (args.recovery):
        t.add_resource(
            rds.DBInstance('RDSInstance',
                           DeletionPolicy='Delete' if args.dev else 'Snapshot',
                           DBSnapshotIdentifier=Ref('RecoveryRDSSnapshotARN'),
                           DBInstanceClass=Ref('RDSInstanceSize'),
                           PubliclyAccessible=False,
                           DBSubnetGroupName=Ref('RDSSubnetGroup'),
                           VPCSecurityGroups=[Ref('DBSecurityGroup')],
                           MultiAZ=not args.dev,
                           Tags=Tags(Name='Patient Records')))
    else:
        t.add_resource(
            rds.DBInstance('RDSInstance',
                           DeletionPolicy='Delete' if args.dev else 'Snapshot',
                           DBName='openemr',
                           AllocatedStorage=Ref('PatientRecords'),
                           DBInstanceClass=Ref('RDSInstanceSize'),
                           Engine='MySQL',
                           EngineVersion=FindInMap('RegionData', ref_region,
                                                   'MySQLVersion'),
                           MasterUsername='******',
                           MasterUserPassword=Ref('RDSPassword'),
                           PubliclyAccessible=False,
                           DBSubnetGroupName=Ref('RDSSubnetGroup'),
                           VPCSecurityGroups=[Ref('DBSecurityGroup')],
                           KmsKeyId=OpenEMRKeyID,
                           StorageEncrypted=True,
                           MultiAZ=not args.dev,
                           Tags=Tags(Name='Patient Records')))

    return t
示例#22
0
    def add_resources(self):
        """Add resources to template."""
        template = self.template
        variables = self.get_variables()

        for rule, settings in variables['Rules'].iteritems():
            if 'IpProtocol' not in settings.keys():
                settings['IpProtocol'] = 'tcp'
            template.add_resource(
                ec2.SecurityGroupIngress('SgIngress{}'.format(
                    sub('[/.-]', '', rule)),
                                         GroupId=variables['GroupId'].ref,
                                         **settings))
示例#23
0
    def handle(self, chain_context):
        template = chain_context.template

        clean_cidr = re.compile('[\W_]+').sub('', self.cidr)

        template.add_resource(ec2.SecurityGroupIngress(
            "Cidr%sToASGPort%s" % (clean_cidr, self.port_to_open),
            IpProtocol="tcp",
            FromPort=self.port_to_open,
            ToPort=self.port_to_open,
            CidrIp=self.cidr,
            GroupId=chain_context.metadata[META_SECURITY_GROUP_REF]
        ))
示例#24
0
    def add_resources(self):
        """Add resources to template."""
        template = self.template
        variables = self.get_variables()

        for rule in variables['Rules']:
            if 'IpProtocol' in rule.keys():
                ipprotocol = rule['IpProtocol']
            else:
                ipprotocol = 'tcp'
            if 'FromCidr' in rule.keys():
                template.add_resource(
                    ec2.SecurityGroupIngress(
                        'SgIngress{}To{}{}FromCidr{}'.format(
                            rule['FromPort'], rule['ToPort'],
                            ipprotocol, sub('[/.]', '', rule['FromCidr'])
                        ),
                        FromPort=rule['FromPort'],
                        ToPort=rule['ToPort'],
                        IpProtocol=ipprotocol,
                        CidrIp=rule['FromCidr'],
                        GroupId=variables['GroupId'].ref,
                    )
                )
            if 'FromSgId' in rule.keys():
                template.add_resource(
                    ec2.SecurityGroupIngress(
                        'SgIngress{}To{}{}FromSg{}'.format(
                            rule['FromPort'], rule['ToPort'],
                            ipprotocol, sub('-', '', rule['FromSgId'])
                        ),
                        FromPort=rule['FromPort'],
                        ToPort=rule['ToPort'],
                        IpProtocol=ipprotocol,
                        SourceSecurityGroupId=rule['FromSgId'],
                        GroupId=variables['GroupId'].ref,
                    )
                )
    def add_resources(self):
        self.jmeter_security_group = self.template.add_resource(
            ec2.SecurityGroup(
                "JMeterSecurityGroup",
                VpcId=Ref(self.jmeter_vpc),
                GroupDescription="jmeter_security_group",
                Tags=Tags(Name="jmeter_security_group"),
            ))

        self.jmeter_ingress_rule_01 = self.template.add_resource(
            ec2.SecurityGroupIngress(
                "JMeterIngressRule01",
                GroupId=Ref(self.jmeter_security_group),
                ToPort="22",
                IpProtocol="tcp",
                CidrIp=Ref(self.jmeter_allowed_ip),
                FromPort="22",
            ))

        self.jmeter_ingress_rule_02 = self.template.add_resource(
            ec2.SecurityGroupIngress(
                "JMeterIngressRule02",
                GroupId=Ref(self.jmeter_security_group),
                ToPort="1099",
                IpProtocol="tcp",
                SourceSecurityGroupId=Ref(self.jmeter_security_group),
                FromPort="1099",
            ))

        self.jmeter_ingress_rule_03 = self.template.add_resource(
            ec2.SecurityGroupIngress(
                "JMeterIngressRule03",
                GroupId=Ref(self.jmeter_security_group),
                ToPort="65535",
                IpProtocol="tcp",
                SourceSecurityGroupId=Ref(self.jmeter_security_group),
                FromPort="30000",
            ))
示例#26
0
    def add_resources(self):
        """Add resources to template."""
        template = self.template
        variables = self.get_variables()

        template.add_resource(
            ec2.SecurityGroupIngress('SecurityGroupIngressFromCidr',
                                     FromPort=variables['FromPort'].ref,
                                     ToPort=variables['ToPort'].ref,
                                     IpProtocol=variables['IpProtocol'].ref,
                                     CidrIp=variables['FromCidr'].ref,
                                     GroupId=variables['GroupId'].ref,
                                     Condition='CidrDefined'))

        template.add_resource(
            ec2.SecurityGroupIngress(
                'SecurityGroupIngressFromSg',
                FromPort=variables['FromPort'].ref,
                ToPort=variables['ToPort'].ref,
                IpProtocol=variables['IpProtocol'].ref,
                SourceSecurityGroupId=variables['FromSgId'].ref,
                GroupId=variables['GroupId'].ref,
                Condition='SrcSgDefined'))
示例#27
0
    def handle(self, chain_context):
        template = chain_context.template

        name = '%sElbToASGPort%s' % (chain_context.instance_name,
                                     self.port_to_open)

        template.add_resource(
            ec2.SecurityGroupIngress(
                name,
                IpProtocol="tcp",
                FromPort=self.port_to_open,
                ToPort=self.port_to_open,
                SourceSecurityGroupId=Ref(self.alb_sg_name),
                GroupId=chain_context.metadata[META_SECURITY_GROUP_REF]))
示例#28
0
 def __add_ingress_rule(self, template, rule, sg):
     if 'sg' in rule:
         template.add_resource(
             ec2.SecurityGroupIngress(rule['name'],
                                      ToPort=rule['to_port'],
                                      FromPort=rule['from_port'],
                                      IpProtocol='tcp',
                                      GroupId=Ref(sg),
                                      Description=rule['description'],
                                      SourceSecurityGroupId=Ref(
                                          rule['sg'])))
     elif 'cidr_ip' in rule:
         template.add_resource(
             ec2.SecurityGroupIngress(rule['name'],
                                      ToPort=rule['to_port'],
                                      FromPort=rule['from_port'],
                                      IpProtocol='tcp',
                                      CidrIp=rule['cidr_ip'],
                                      GroupId=Ref(sg),
                                      Description=rule['description']))
     elif 'instances' in rule:
         count = 0
         instance_ids = self.ec2op.get_instance_ids_from_tag(
             tag_name="Name", tag_value=rule['instances'])
         for instance_id in instance_ids:
             instance_ip = str(
                 self.ec2op.get_external_ip_from_instance_id(
                     instance_id=instance_id)) + "/32"
             template.add_resource(
                 ec2.SecurityGroupIngress(rule['name'] + str(count),
                                          ToPort=rule['to_port'],
                                          FromPort=rule['from_port'],
                                          IpProtocol='tcp',
                                          CidrIp=instance_ip,
                                          GroupId=Ref(sg),
                                          Description=rule['description']))
             count += 1
示例#29
0
    def create_security_groups_ingress(self):
        """ Creates ingress rule for elb security groups """
        template = self.template
        variables = self.get_variables()

        cidringress = template.add_resource(
            ec2.SecurityGroupIngress('SecurityGroupIngressCidr',
                                     FromPort=variables['FromPort'].ref,
                                     ToPort=variables['ToPort'].ref,
                                     GroupId=variables['GroupId'].ref,
                                     IpProtocol=variables['IpProtocol'].ref,
                                     CidrIp=variables['CidrIp'].ref,
                                     Condition='UseCidrIp'))
        securitygroupingress = template.add_resource(
            ec2.SecurityGroupIngress(
                'SecurityGroupIngressSecurityGroupId',
                FromPort=variables['FromPort'].ref,
                ToPort=variables['ToPort'].ref,
                GroupId=variables['GroupId'].ref,
                IpProtocol=variables['IpProtocol'].ref,
                SourceSecurityGroupId=variables['SourceSecurityGroupId'].ref,
                Condition='UseSourceSecurityGroupId'))
        template.add_output(
            Output(
                cidringress.title,
                Description='Security group ingres rule for client',
                Export=Export(Sub('${AWS::StackName}-%s' % cidringress.title)),  # nopep8 pylint: disable=C0301
                Value=Ref(cidringress),
                Condition='UseCidrIp'))
        template.add_output(
            Output(
                securitygroupingress.title,
                Description='Security group ingres rule for client',
                Export=Export(
                    Sub('${AWS::StackName}-%s' % securitygroupingress.title)),  # nopep8 pylint: disable=C0301
                Value=Ref(securitygroupingress),
                Condition='UseSourceSecurityGroupId'))
示例#30
0
    def https_ingress_rule(
            self,
            security_group: ec2.SecurityGroup) -> ec2.SecurityGroupIngress:
        """Return Ingress rule allowing HTTPS traffic from a given security group.

        :param security_group: authorize https inbound access from this sg.
        """
        return ec2.SecurityGroupIngress(
            name_to_id(f"{self.name}Ingress{security_group.title}"),
            SourceSecurityGroupId=Ref(security_group),
            FromPort="443",
            ToPort="443",
            IpProtocol="tcp",
            GroupId=Ref(self.security_group),
        )