Search in sources :

Example 11 with FirewallRule

use of com.cloud.network.rules.FirewallRule in project cloudstack by apache.

the class FirewallManagerImpl method listFirewallRules.

@Override
public Pair<List<? extends FirewallRule>, Integer> listFirewallRules(IListFirewallRulesCmd cmd) {
    Long ipId = cmd.getIpAddressId();
    Long id = cmd.getId();
    Long networkId = cmd.getNetworkId();
    Map<String, String> tags = cmd.getTags();
    FirewallRule.TrafficType trafficType = cmd.getTrafficType();
    Boolean display = cmd.getDisplay();
    Account caller = CallContext.current().getCallingAccount();
    List<Long> permittedAccounts = new ArrayList<Long>();
    if (ipId != null) {
        IPAddressVO ipAddressVO = _ipAddressDao.findById(ipId);
        if (ipAddressVO == null || !ipAddressVO.readyToUse()) {
            throw new InvalidParameterValueException("Ip address id=" + ipId + " not ready for firewall rules yet");
        }
        _accountMgr.checkAccess(caller, null, true, ipAddressVO);
    }
    Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
    Long domainId = domainIdRecursiveListProject.first();
    Boolean isRecursive = domainIdRecursiveListProject.second();
    ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    Filter filter = new Filter(FirewallRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
    SearchBuilder<FirewallRuleVO> sb = _firewallDao.createSearchBuilder();
    _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    sb.and("id", sb.entity().getId(), Op.EQ);
    sb.and("trafficType", sb.entity().getTrafficType(), Op.EQ);
    sb.and("networkId", sb.entity().getNetworkId(), Op.EQ);
    sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ);
    sb.and("purpose", sb.entity().getPurpose(), Op.EQ);
    sb.and("display", sb.entity().isDisplay(), Op.EQ);
    if (tags != null && !tags.isEmpty()) {
        SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
        for (int count = 0; count < tags.size(); count++) {
            tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
            tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
            tagSearch.cp();
        }
        tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
        sb.groupBy(sb.entity().getId());
        sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
    }
    SearchCriteria<FirewallRuleVO> sc = sb.create();
    _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    if (id != null) {
        sc.setParameters("id", id);
    }
    if (tags != null && !tags.isEmpty()) {
        int count = 0;
        sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.FirewallRule.toString());
        for (String key : tags.keySet()) {
            sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key);
            sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key));
            count++;
        }
    }
    if (display != null) {
        sc.setParameters("display", display);
    }
    if (ipId != null) {
        sc.setParameters("ip", ipId);
    }
    if (networkId != null) {
        sc.setParameters("networkId", networkId);
    }
    sc.setParameters("purpose", Purpose.Firewall);
    sc.setParameters("trafficType", trafficType);
    Pair<List<FirewallRuleVO>, Integer> result = _firewallDao.searchAndCount(sc, filter);
    return new Pair<List<? extends FirewallRule>, Integer>(result.first(), result.second());
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceTagVO(com.cloud.tags.ResourceTagVO) List(java.util.List) ArrayList(java.util.ArrayList) FirewallRule(com.cloud.network.rules.FirewallRule) Pair(com.cloud.utils.Pair) Ternary(com.cloud.utils.Ternary) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) Filter(com.cloud.utils.db.Filter) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 12 with FirewallRule

use of com.cloud.network.rules.FirewallRule 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.getEgressDefaultPolicy();
    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 13 with FirewallRule

use of com.cloud.network.rules.FirewallRule in project cloudstack by apache.

the class VirtualNetworkApplianceManagerImpl method finalizeNetworkRulesForNetwork.

protected void finalizeNetworkRulesForNetwork(final Commands cmds, final DomainRouterVO router, final Provider provider, final Long guestNetworkId) {
    s_logger.debug("Resending ipAssoc, port forwarding, load balancing rules as a part of Virtual router start");
    final ArrayList<? extends PublicIpAddress> publicIps = getPublicIpsToApply(router, provider, guestNetworkId);
    final List<FirewallRule> firewallRulesEgress = new ArrayList<FirewallRule>();
    // Fetch firewall Egress rules.
    if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.Firewall, provider)) {
        firewallRulesEgress.addAll(_rulesDao.listByNetworkPurposeTrafficType(guestNetworkId, Purpose.Firewall, FirewallRule.TrafficType.Egress));
        if (firewallRulesEgress.isEmpty()) {
            //create egress default rule for VR
            createDefaultEgressFirewallRule(firewallRulesEgress, guestNetworkId);
        }
    }
    // Re-apply firewall Egress rules
    s_logger.debug("Found " + firewallRulesEgress.size() + " firewall Egress rule(s) to apply as a part of domR " + router + " start.");
    if (!firewallRulesEgress.isEmpty()) {
        _commandSetupHelper.createFirewallRulesCommands(firewallRulesEgress, router, cmds, guestNetworkId);
    }
    if (publicIps != null && !publicIps.isEmpty()) {
        final List<RemoteAccessVpn> vpns = new ArrayList<RemoteAccessVpn>();
        final List<PortForwardingRule> pfRules = new ArrayList<PortForwardingRule>();
        final List<FirewallRule> staticNatFirewallRules = new ArrayList<FirewallRule>();
        final List<StaticNat> staticNats = new ArrayList<StaticNat>();
        final List<FirewallRule> firewallRulesIngress = new ArrayList<FirewallRule>();
        // StaticNatRules; PFVPN to reapply on domR start)
        for (final PublicIpAddress ip : publicIps) {
            if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.PortForwarding, provider)) {
                pfRules.addAll(_pfRulesDao.listForApplication(ip.getId()));
            }
            if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.StaticNat, provider)) {
                staticNatFirewallRules.addAll(_rulesDao.listByIpAndPurpose(ip.getId(), Purpose.StaticNat));
            }
            if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.Firewall, provider)) {
                firewallRulesIngress.addAll(_rulesDao.listByIpAndPurpose(ip.getId(), Purpose.Firewall));
            }
            if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.Vpn, provider)) {
                final RemoteAccessVpn vpn = _vpnDao.findByPublicIpAddress(ip.getId());
                if (vpn != null) {
                    vpns.add(vpn);
                }
            }
            if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.StaticNat, provider)) {
                if (ip.isOneToOneNat()) {
                    boolean revoke = false;
                    if (ip.getState() == IpAddress.State.Releasing) {
                        // for ips got struck in releasing state we need to delete the rule not add.
                        s_logger.debug("Rule revoke set to true for the ip " + ip.getAddress() + " becasue it is in releasing state");
                        revoke = true;
                    }
                    final StaticNatImpl staticNat = new StaticNatImpl(ip.getAccountId(), ip.getDomainId(), guestNetworkId, ip.getId(), ip.getVmIp(), revoke);
                    staticNats.add(staticNat);
                }
            }
        }
        // Re-apply static nats
        s_logger.debug("Found " + staticNats.size() + " static nat(s) to apply as a part of domR " + router + " start.");
        if (!staticNats.isEmpty()) {
            _commandSetupHelper.createApplyStaticNatCommands(staticNats, router, cmds, guestNetworkId);
        }
        // Re-apply firewall Ingress rules
        s_logger.debug("Found " + firewallRulesIngress.size() + " firewall Ingress rule(s) to apply as a part of domR " + router + " start.");
        if (!firewallRulesIngress.isEmpty()) {
            _commandSetupHelper.createFirewallRulesCommands(firewallRulesIngress, router, cmds, guestNetworkId);
        }
        // Re-apply port forwarding rules
        s_logger.debug("Found " + pfRules.size() + " port forwarding rule(s) to apply as a part of domR " + router + " start.");
        if (!pfRules.isEmpty()) {
            _commandSetupHelper.createApplyPortForwardingRulesCommands(pfRules, router, cmds, guestNetworkId);
        }
        // Re-apply static nat rules
        s_logger.debug("Found " + staticNatFirewallRules.size() + " static nat rule(s) to apply as a part of domR " + router + " start.");
        if (!staticNatFirewallRules.isEmpty()) {
            final List<StaticNatRule> staticNatRules = new ArrayList<StaticNatRule>();
            for (final FirewallRule rule : staticNatFirewallRules) {
                staticNatRules.add(_rulesMgr.buildStaticNatRule(rule, false));
            }
            _commandSetupHelper.createApplyStaticNatRulesCommands(staticNatRules, router, cmds, guestNetworkId);
        }
        // Re-apply vpn rules
        s_logger.debug("Found " + vpns.size() + " vpn(s) to apply as a part of domR " + router + " start.");
        if (!vpns.isEmpty()) {
            for (final RemoteAccessVpn vpn : vpns) {
                _commandSetupHelper.createApplyVpnCommands(true, vpn, router, cmds);
            }
        }
        final List<LoadBalancerVO> lbs = _loadBalancerDao.listByNetworkIdAndScheme(guestNetworkId, Scheme.Public);
        final List<LoadBalancingRule> lbRules = new ArrayList<LoadBalancingRule>();
        if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.Lb, provider)) {
            // Re-apply load balancing rules
            for (final LoadBalancerVO lb : lbs) {
                final List<LbDestination> dstList = _lbMgr.getExistingDestinations(lb.getId());
                final List<LbStickinessPolicy> policyList = _lbMgr.getStickinessPolicies(lb.getId());
                final List<LbHealthCheckPolicy> hcPolicyList = _lbMgr.getHealthCheckPolicies(lb.getId());
                final Ip sourceIp = _networkModel.getPublicIpAddress(lb.getSourceIpAddressId()).getAddress();
                final LbSslCert sslCert = _lbMgr.getLbSslCert(lb.getId());
                final LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList, hcPolicyList, sourceIp, sslCert, lb.getLbProtocol());
                lbRules.add(loadBalancing);
            }
        }
        s_logger.debug("Found " + lbRules.size() + " load balancing rule(s) to apply as a part of domR " + router + " start.");
        if (!lbRules.isEmpty()) {
            _commandSetupHelper.createApplyLoadBalancingRulesCommands(lbRules, router, cmds, guestNetworkId);
        }
    }
    // Reapply dhcp and dns configuration.
    final Network guestNetwork = _networkDao.findById(guestNetworkId);
    if (guestNetwork.getGuestType() == GuestType.Shared && _networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.Dhcp, provider)) {
        final Map<Network.Capability, String> dhcpCapabilities = _networkSvc.getNetworkOfferingServiceCapabilities(_networkOfferingDao.findById(_networkDao.findById(guestNetworkId).getNetworkOfferingId()), Service.Dhcp);
        final String supportsMultipleSubnets = dhcpCapabilities.get(Network.Capability.DhcpAccrossMultipleSubnets);
        if (supportsMultipleSubnets != null && Boolean.valueOf(supportsMultipleSubnets)) {
            final List<NicIpAliasVO> revokedIpAliasVOs = _nicIpAliasDao.listByNetworkIdAndState(guestNetworkId, NicIpAlias.State.revoked);
            s_logger.debug("Found" + revokedIpAliasVOs.size() + "ip Aliases to revoke on the router as a part of dhcp configuration");
            removeRevokedIpAliasFromDb(revokedIpAliasVOs);
            final List<NicIpAliasVO> aliasVOs = _nicIpAliasDao.listByNetworkIdAndState(guestNetworkId, NicIpAlias.State.active);
            s_logger.debug("Found" + aliasVOs.size() + "ip Aliases to apply on the router as a part of dhcp configuration");
            final List<IpAliasTO> activeIpAliasTOs = new ArrayList<IpAliasTO>();
            for (final NicIpAliasVO aliasVO : aliasVOs) {
                activeIpAliasTOs.add(new IpAliasTO(aliasVO.getIp4Address(), aliasVO.getNetmask(), aliasVO.getAliasCount().toString()));
            }
            if (activeIpAliasTOs.size() != 0) {
                _commandSetupHelper.createIpAlias(router, activeIpAliasTOs, guestNetworkId, cmds);
                _commandSetupHelper.configDnsMasq(router, _networkDao.findById(guestNetworkId), cmds);
            }
        }
    }
}
Also used : LoadBalancingRule(com.cloud.network.lb.LoadBalancingRule) PublicIp(com.cloud.network.addr.PublicIp) Ip(com.cloud.utils.net.Ip) ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) LbStickinessPolicy(com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy) StaticNatRule(com.cloud.network.rules.StaticNatRule) NicIpAliasVO(com.cloud.vm.dao.NicIpAliasVO) LbDestination(com.cloud.network.lb.LoadBalancingRule.LbDestination) PublicIpAddress(com.cloud.network.PublicIpAddress) Network(com.cloud.network.Network) FirewallRule(com.cloud.network.rules.FirewallRule) LbSslCert(com.cloud.network.lb.LoadBalancingRule.LbSslCert) PortForwardingRule(com.cloud.network.rules.PortForwardingRule) StaticNat(com.cloud.network.rules.StaticNat) StaticNatImpl(com.cloud.network.rules.StaticNatImpl) LbHealthCheckPolicy(com.cloud.network.lb.LoadBalancingRule.LbHealthCheckPolicy) IpAliasTO(com.cloud.agent.api.routing.IpAliasTO) RemoteAccessVpn(com.cloud.network.RemoteAccessVpn)

Example 14 with FirewallRule

use of com.cloud.network.rules.FirewallRule in project cloudstack by apache.

the class CreateIpForwardingRuleCmd method execute.

@Override
public void execute() throws ResourceUnavailableException {
    boolean result = true;
    FirewallRule rule = null;
    try {
        CallContext.current().setEventDetails("Rule ID: " + getEntityId());
        if (getOpenFirewall()) {
            result = result && _firewallService.applyIngressFirewallRules(ipAddressId, CallContext.current().getCallingAccount());
        }
        result = result && _rulesService.applyStaticNatRules(ipAddressId, CallContext.current().getCallingAccount());
        rule = _entityMgr.findById(FirewallRule.class, getEntityId());
        StaticNatRule staticNatRule = _rulesService.buildStaticNatRule(rule, false);
        IpForwardingRuleResponse fwResponse = _responseGenerator.createIpForwardingRuleResponse(staticNatRule);
        fwResponse.setResponseName(getCommandName());
        setResponseObject(fwResponse);
    } finally {
        if (!result || rule == null) {
            if (getOpenFirewall()) {
                _firewallService.revokeRelatedFirewallRule(getEntityId(), true);
            }
            _rulesService.revokeStaticNatRule(getEntityId(), true);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Error in creating IP forwarding rule on the domr");
        }
    }
}
Also used : ServerApiException(org.apache.cloudstack.api.ServerApiException) StaticNatRule(com.cloud.network.rules.StaticNatRule) FirewallRule(com.cloud.network.rules.FirewallRule) IpForwardingRuleResponse(org.apache.cloudstack.api.response.IpForwardingRuleResponse)

Example 15 with FirewallRule

use of com.cloud.network.rules.FirewallRule in project cloudstack by apache.

the class ListIpForwardingRulesCmd method execute.

@Override
public void execute() {
    Pair<List<? extends FirewallRule>, Integer> result = _rulesService.searchStaticNatRules(publicIpAddressId, id, vmId, this.getStartIndex(), this.getPageSizeVal(), this.getAccountName(), this.getDomainId(), this.getProjectId(), this.isRecursive(), this.listAll());
    ListResponse<IpForwardingRuleResponse> response = new ListResponse<IpForwardingRuleResponse>();
    List<IpForwardingRuleResponse> ipForwardingResponses = new ArrayList<IpForwardingRuleResponse>();
    for (FirewallRule rule : result.first()) {
        StaticNatRule staticNatRule = _rulesService.buildStaticNatRule(rule, false);
        IpForwardingRuleResponse resp = _responseGenerator.createIpForwardingRuleResponse(staticNatRule);
        if (resp != null) {
            ipForwardingResponses.add(resp);
        }
    }
    response.setResponses(ipForwardingResponses, result.second());
    response.setResponseName(getCommandName());
    this.setResponseObject(response);
}
Also used : ListResponse(org.apache.cloudstack.api.response.ListResponse) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) StaticNatRule(com.cloud.network.rules.StaticNatRule) FirewallRule(com.cloud.network.rules.FirewallRule) IpForwardingRuleResponse(org.apache.cloudstack.api.response.IpForwardingRuleResponse)

Aggregations

FirewallRule (com.cloud.network.rules.FirewallRule)33 ArrayList (java.util.ArrayList)18 IpAddress (com.cloud.network.IpAddress)7 FirewallRuleVO (com.cloud.network.rules.FirewallRuleVO)7 FirewallResponse (org.apache.cloudstack.api.response.FirewallResponse)7 FirewallRuleTO (com.cloud.agent.api.to.FirewallRuleTO)5 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)5 PublicIpAddress (com.cloud.network.PublicIpAddress)5 StaticNatRule (com.cloud.network.rules.StaticNatRule)5 List (java.util.List)5 ServerApiException (org.apache.cloudstack.api.ServerApiException)5 SetFirewallRulesCommand (com.cloud.agent.api.routing.SetFirewallRulesCommand)4 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)4 HostVO (com.cloud.host.HostVO)4 NetworkVO (com.cloud.network.dao.NetworkVO)4 NetworkOfferingVO (com.cloud.offerings.NetworkOfferingVO)4 Answer (com.cloud.agent.api.Answer)3 ServerApiException (com.cloud.api.ServerApiException)3 DataCenterVO (com.cloud.dc.DataCenterVO)3 ActionEvent (com.cloud.event.ActionEvent)3