Search in sources :

Example 1 with FirewallRuleTO

use of com.cloud.agent.api.to.FirewallRuleTO in project cloudstack by apache.

the class MidoNetElement method applyFWRules.

@Override
public boolean applyFWRules(Network config, List<? extends FirewallRule> rulesToApply) throws ResourceUnavailableException {
    if (!midoInNetwork(config)) {
        return false;
    }
    if (canHandle(config, Service.Firewall)) {
        String accountIdStr = getAccountUuid(config);
        String networkUUIDStr = String.valueOf(config.getId());
        RuleChain preFilter = getChain(accountIdStr, networkUUIDStr, RuleChainCode.TR_PREFILTER);
        RuleChain preNat = getChain(accountIdStr, networkUUIDStr, RuleChainCode.TR_PRENAT);
        // Create a map of Rule description -> Rule for quicker lookups
        Map<String, Rule> existingRules = new HashMap<String, Rule>();
        for (Rule existingRule : preFilter.getRules()) {
            // The "whitelist" rules we're interested in are the Jump rules where src address is specified
            if (existingRule.getType().equals(DtoRule.Jump) && existingRule.getNwSrcAddress() != null) {
                String ruleString = new SimpleFirewallRule(existingRule).toStringArray()[0];
                existingRules.put(ruleString, existingRule);
            }
        }
        for (FirewallRule rule : rulesToApply) {
            if (rule.getState() == FirewallRule.State.Revoke || rule.getState() == FirewallRule.State.Add) {
                IpAddress dstIp = _networkModel.getIp(rule.getSourceIpAddressId());
                FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null, dstIp.getAddress().addr());
                // Convert to string representation
                SimpleFirewallRule fwRule = new SimpleFirewallRule(ruleTO);
                String[] ruleStrings = fwRule.toStringArray();
                if (rule.getState() == FirewallRule.State.Revoke) {
                    // Lookup in existingRules, delete if present
                    for (String revokeRuleString : ruleStrings) {
                        Rule foundRule = existingRules.get(revokeRuleString);
                        if (foundRule != null) {
                            foundRule.delete();
                        }
                    }
                } else if (rule.getState() == FirewallRule.State.Add) {
                    // Lookup in existingRules, add if not present
                    for (int i = 0; i < ruleStrings.length; i++) {
                        String ruleString = ruleStrings[i];
                        Rule foundRule = existingRules.get(ruleString);
                        if (foundRule == null) {
                            // Get the cidr for the related entry in the Source Cidrs list
                            String relatedCidr = fwRule.sourceCidrs.get(i);
                            Pair<String, Integer> cidrParts = NetUtils.getCidr(relatedCidr);
                            // Create rule with correct proto, cidr, ACCEPT, dst IP
                            Rule toApply = preFilter.addRule().type(DtoRule.Jump).jumpChainId(preNat.getId()).position(1).nwSrcAddress(cidrParts.first()).nwSrcLength(cidrParts.second()).nwDstAddress(ruleTO.getSrcIp()).nwDstLength(32).nwProto(SimpleFirewallRule.stringToProtocolNumber(rule.getProtocol()));
                            if (rule.getProtocol().equals("icmp")) {
                                // (-1, -1) means "allow all ICMP", so we don't set tpSrc / tpDst
                                if (fwRule.icmpType != -1 | fwRule.icmpCode != -1) {
                                    toApply.tpSrc(new DtoRange(fwRule.icmpType, fwRule.icmpType)).tpDst(new DtoRange(fwRule.icmpCode, fwRule.icmpCode));
                                }
                            } else {
                                toApply.tpDst(new DtoRange(fwRule.dstPortStart, fwRule.dstPortEnd));
                            }
                            toApply.create();
                        }
                    }
                }
            }
        }
        return true;
    } else {
        return true;
    }
}
Also used : DtoRange(org.midonet.client.dto.DtoRule.DtoRange) RuleChain(org.midonet.client.resource.RuleChain) HashMap(java.util.HashMap) IpAddress(com.cloud.network.IpAddress) PublicIpAddress(com.cloud.network.PublicIpAddress) Rule(org.midonet.client.resource.Rule) PortForwardingRule(com.cloud.network.rules.PortForwardingRule) FirewallRule(com.cloud.network.rules.FirewallRule) DtoRule(org.midonet.client.dto.DtoRule) FirewallRuleTO(com.cloud.agent.api.to.FirewallRuleTO) FirewallRule(com.cloud.network.rules.FirewallRule) Pair(com.cloud.utils.Pair)

Example 2 with FirewallRuleTO

use of com.cloud.agent.api.to.FirewallRuleTO in project cloudstack by apache.

the class ExternalFirewallDeviceManagerImpl method applyFirewallRules.

@Override
public boolean applyFirewallRules(Network network, List<? extends FirewallRule> rules) throws ResourceUnavailableException {
    // Find the external firewall in this zone
    long zoneId = network.getDataCenterId();
    DataCenterVO zone = _dcDao.findById(zoneId);
    ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network);
    // During destroy, device reference may already been clean up, then we just return true
    if (fwDeviceVO == null) {
        return true;
    }
    HostVO externalFirewall = _hostDao.findById(fwDeviceVO.getHostId());
    assert (externalFirewall != null);
    if (network.getState() == Network.State.Allocated) {
        s_logger.debug("External firewall was asked to apply firewall rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands.");
        return true;
    }
    List<FirewallRuleTO> rulesTO = new ArrayList<FirewallRuleTO>();
    NetworkVO networkVO = _networkDao.findById(network.getId());
    NetworkOfferingVO offering = _networkOfferingDao.findById(networkVO.getNetworkOfferingId());
    Boolean defaultEgressPolicy = offering.isEgressDefaultPolicy();
    for (FirewallRule rule : rules) {
        if (rule.getSourceCidrList() == null && (rule.getPurpose() == Purpose.Firewall || rule.getPurpose() == Purpose.NetworkACL)) {
            _fwRulesDao.loadSourceCidrs((FirewallRuleVO) rule);
        }
        FirewallRuleTO ruleTO;
        if (rule.getPurpose() == Purpose.Firewall && rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
            String guestVlanTag = BroadcastDomainType.getValue(network.getBroadcastUri());
            String guestCidr = network.getCidr();
            ruleTO = new FirewallRuleTO(rule, guestVlanTag, rule.getTrafficType(), guestCidr, defaultEgressPolicy, rule.getType());
        } else {
            IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
            Vlan vlan = _vlanDao.findById(sourceIp.getVlanId());
            ruleTO = new FirewallRuleTO(rule, vlan.getVlanTag(), sourceIp.getAddress().addr());
        }
        rulesTO.add(ruleTO);
    }
    // Firewall rules configured for staticNAT/PF
    sendFirewallRules(rulesTO, zone, externalFirewall.getId());
    return true;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) ExternalFirewallDeviceVO(com.cloud.network.dao.ExternalFirewallDeviceVO) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) ArrayList(java.util.ArrayList) Vlan(com.cloud.dc.Vlan) FirewallRuleTO(com.cloud.agent.api.to.FirewallRuleTO) HostVO(com.cloud.host.HostVO) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) FirewallRule(com.cloud.network.rules.FirewallRule)

Example 3 with FirewallRuleTO

use of com.cloud.agent.api.to.FirewallRuleTO in project cloudstack by apache.

the class CommandSetupHelper method createFirewallRulesCommands.

public void createFirewallRulesCommands(final List<? extends FirewallRule> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId) {
    final List<FirewallRuleTO> rulesTO = new ArrayList<FirewallRuleTO>();
    String systemRule = null;
    Boolean defaultEgressPolicy = false;
    if (rules != null) {
        if (rules.size() > 0) {
            if (rules.get(0).getTrafficType() == FirewallRule.TrafficType.Egress && rules.get(0).getType() == FirewallRule.FirewallRuleType.System) {
                systemRule = String.valueOf(FirewallRule.FirewallRuleType.System);
            }
        }
        for (final FirewallRule rule : rules) {
            _rulesDao.loadSourceCidrs((FirewallRuleVO) rule);
            _rulesDao.loadDestinationCidrs((FirewallRuleVO) rule);
            final FirewallRule.TrafficType traffictype = rule.getTrafficType();
            if (traffictype == FirewallRule.TrafficType.Ingress) {
                final IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
                final FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null, sourceIp.getAddress().addr(), Purpose.Firewall, traffictype);
                rulesTO.add(ruleTO);
            } else if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
                final NetworkVO network = _networkDao.findById(guestNetworkId);
                final NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
                defaultEgressPolicy = offering.isEgressDefaultPolicy();
                assert rule.getSourceIpAddressId() == null : "ipAddressId should be null for egress firewall rule. ";
                final FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null, "", Purpose.Firewall, traffictype, defaultEgressPolicy);
                rulesTO.add(ruleTO);
            }
        }
    }
    final SetFirewallRulesCommand cmd = new SetFirewallRulesCommand(rulesTO);
    cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
    cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(guestNetworkId, router.getId()));
    cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
    final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
    cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
    if (systemRule != null) {
        cmd.setAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT, systemRule);
    } else {
        cmd.setAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT, String.valueOf(defaultEgressPolicy));
    }
    cmds.addCommand(cmd);
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) NetworkVO(com.cloud.network.dao.NetworkVO) ArrayList(java.util.ArrayList) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) PrivateIpAddress(com.cloud.network.vpc.PrivateIpAddress) IpAddress(com.cloud.network.IpAddress) PublicIpAddress(com.cloud.network.PublicIpAddress) FirewallRuleTO(com.cloud.agent.api.to.FirewallRuleTO) FirewallRule(com.cloud.network.rules.FirewallRule) SetFirewallRulesCommand(com.cloud.agent.api.routing.SetFirewallRulesCommand)

Example 4 with FirewallRuleTO

use of com.cloud.agent.api.to.FirewallRuleTO in project cloudstack by apache.

the class SetFirewallRulesCommand method generateFwRules.

public String[][] generateFwRules() {
    String[][] result = new String[2][];
    Set<String> toAdd = new HashSet<String>();
    for (FirewallRuleTO fwTO : rules) {
        /* example  :  172.16.92.44:tcp:80:80:0.0.0.0/0:,200.16.92.44:tcp:220:220:0.0.0.0/0:,
             *  each entry format      <ip>:protocol:srcport:destport:scidr:
             *  reverted entry format  <ip>:reverted:0:0:0:
             */
        if (fwTO.revoked()) {
            StringBuilder sb = new StringBuilder();
            /* This entry is added just to make sure atleast there will one entry in the list to get the ipaddress */
            sb.append(fwTO.getSrcIp()).append(":reverted:0:0:0:0:").append(fwTO.getId()).append(":");
            String fwRuleEntry = sb.toString();
            toAdd.add(fwRuleEntry);
            continue;
        }
        List<String> sCidr, dCidr;
        StringBuilder sb = new StringBuilder();
        sb.append(fwTO.getSrcIp()).append(":").append(fwTO.getProtocol()).append(":");
        if ("icmp".compareTo(fwTO.getProtocol()) == 0) {
            sb.append(fwTO.getIcmpType()).append(":").append(fwTO.getIcmpCode()).append(":");
        } else if (fwTO.getStringSrcPortRange() == null)
            sb.append("0:0").append(":");
        else
            sb.append(fwTO.getStringSrcPortRange()).append(":");
        sCidr = fwTO.getSourceCidrList();
        dCidr = fwTO.getDestCidrList();
        if (sCidr == null || sCidr.isEmpty()) {
            // check if this is necessary because we are providing the source cidr by default???
            sb.append("0.0.0.0/0");
        } else {
            boolean firstEntry = true;
            for (String tag : sCidr) {
                if (!firstEntry)
                    sb.append("-");
                sb.append(tag);
                firstEntry = false;
            }
        }
        sb.append(":");
        if (dCidr == null || dCidr.isEmpty()) {
            sb.append("");
        } else {
            boolean firstEntry = true;
            for (String cidr : dCidr) {
                if (!firstEntry)
                    sb.append("-");
                sb.append(cidr);
                firstEntry = false;
            }
        }
        sb.append(":");
        sb.append(fwTO.getId());
        sb.append(":");
        String fwRuleEntry = sb.toString();
        toAdd.add(fwRuleEntry);
    }
    result[0] = toAdd.toArray(new String[toAdd.size()]);
    return result;
}
Also used : FirewallRuleTO(com.cloud.agent.api.to.FirewallRuleTO) HashSet(java.util.HashSet)

Example 5 with FirewallRuleTO

use of com.cloud.agent.api.to.FirewallRuleTO in project cloudstack by apache.

the class VirtualRoutingResourceTest method generateSetFirewallRulesCommand.

protected SetFirewallRulesCommand generateSetFirewallRulesCommand() {
    final List<FirewallRuleTO> rules = new ArrayList<>();
    final List<String> sourceCidrs = new ArrayList<>();
    sourceCidrs.add("10.10.1.1/24");
    sourceCidrs.add("10.10.1.2/24");
    rules.add(new FirewallRuleTO(1, "64.10.10.10", "TCP", 22, 80, false, false, Purpose.Firewall, sourceCidrs, 0, 0));
    rules.add(new FirewallRuleTO(2, "64.10.10.10", "ICMP", 0, 0, false, false, Purpose.Firewall, sourceCidrs, -1, -1));
    rules.add(new FirewallRuleTO(3, "64.10.10.10", "ICMP", 0, 0, true, true, Purpose.Firewall, sourceCidrs, -1, -1));
    final SetFirewallRulesCommand cmd = new SetFirewallRulesCommand(rules);
    cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
    return cmd;
}
Also used : ArrayList(java.util.ArrayList) FirewallRuleTO(com.cloud.agent.api.to.FirewallRuleTO) SetFirewallRulesCommand(com.cloud.agent.api.routing.SetFirewallRulesCommand)

Aggregations

FirewallRuleTO (com.cloud.agent.api.to.FirewallRuleTO)28 ArrayList (java.util.ArrayList)23 SetFirewallRulesCommand (com.cloud.agent.api.routing.SetFirewallRulesCommand)13 Answer (com.cloud.agent.api.Answer)11 IpAssocAnswer (com.cloud.agent.api.routing.IpAssocAnswer)9 FirewallRule (com.cloud.network.rules.FirewallRule)9 IpAddress (com.cloud.network.IpAddress)6 PublicIpAddress (com.cloud.network.PublicIpAddress)6 ExternalNetworkResourceUsageAnswer (com.cloud.agent.api.ExternalNetworkResourceUsageAnswer)5 MaintainAnswer (com.cloud.agent.api.MaintainAnswer)5 ReadyAnswer (com.cloud.agent.api.ReadyAnswer)5 NetworkVO (com.cloud.network.dao.NetworkVO)5 NetworkOfferingVO (com.cloud.offerings.NetworkOfferingVO)5 ExecutionException (com.cloud.utils.exception.ExecutionException)5 Test (org.junit.Test)5 HashMap (java.util.HashMap)4 DataCenterVO (com.cloud.dc.DataCenterVO)3 HashSet (java.util.HashSet)3 PortForwardingRuleTO (com.cloud.agent.api.to.PortForwardingRuleTO)2 StaticNatRuleTO (com.cloud.agent.api.to.StaticNatRuleTO)2