Search in sources :

Example 36 with FirewallRule

use of com.cloud.network.rules.FirewallRule in project cosmic by MissionCriticalCloud.

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<>();
    // 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<PortForwardingRule> pfRules = new ArrayList<>();
        final List<FirewallRule> staticNatFirewallRules = new ArrayList<>();
        final List<StaticNat> staticNats = new ArrayList<>();
        final List<FirewallRule> firewallRulesIngress = new ArrayList<>();
        // 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.StaticNat, provider)) {
                if (ip.isOneToOneNat()) {
                    final StaticNatImpl staticNat = new StaticNatImpl(ip.getAccountId(), ip.getDomainId(), guestNetworkId, ip.getId(), ip.getVmIp(), false);
                    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);
        }
        // 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<>();
            for (final FirewallRule rule : staticNatFirewallRules) {
                staticNatRules.add(_rulesMgr.buildStaticNatRule(rule, false));
            }
            _commandSetupHelper.createApplyStaticNatRulesCommands(staticNatRules, router, cmds, guestNetworkId);
        }
        final List<LoadBalancerVO> lbs = _loadBalancerDao.listByNetworkIdAndScheme(guestNetworkId, Scheme.Public);
        final List<LoadBalancingRule> lbRules = new ArrayList<>();
        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);
        }
    }
}
Also used : LbSslCert(com.cloud.network.lb.LoadBalancingRule.LbSslCert) LoadBalancingRule(com.cloud.network.lb.LoadBalancingRule) Ip(com.cloud.utils.net.Ip) PublicIp(com.cloud.network.addr.PublicIp) ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) LbStickinessPolicy(com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy) StaticNatRule(com.cloud.network.rules.StaticNatRule) PortForwardingRule(com.cloud.network.rules.PortForwardingRule) StaticNat(com.cloud.network.rules.StaticNat) LbDestination(com.cloud.network.lb.LoadBalancingRule.LbDestination) PublicIpAddress(com.cloud.network.PublicIpAddress) StaticNatImpl(com.cloud.network.rules.StaticNatImpl) LbHealthCheckPolicy(com.cloud.network.lb.LoadBalancingRule.LbHealthCheckPolicy) FirewallRule(com.cloud.network.rules.FirewallRule)

Example 37 with FirewallRule

use of com.cloud.network.rules.FirewallRule in project cosmic by MissionCriticalCloud.

the class VirtualNetworkApplianceManagerImpl method createDefaultEgressFirewallRule.

private void createDefaultEgressFirewallRule(final List<FirewallRule> rules, final long networkId) {
    final NetworkVO network = _networkDao.findById(networkId);
    final NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
    final Boolean defaultEgressPolicy = offering.getEgressDefaultPolicy();
    // The default on the router is set to Deny all. So, if the default configuration in the offering is set to true (Allow), we change the Egress here
    if (defaultEgressPolicy) {
        final List<String> sourceCidr = new ArrayList<>();
        sourceCidr.add(NetUtils.ALL_IP4_CIDRS);
        final FirewallRule rule = new FirewallRuleVO(null, null, null, null, "all", networkId, network.getAccountId(), network.getDomainId(), Purpose.Firewall, sourceCidr, null, null, null, FirewallRule.TrafficType.Egress, FirewallRule.FirewallRuleType.System);
        rules.add(rule);
    } else {
        s_logger.debug("Egress policy for the Network " + networkId + " is already defined as Deny. So, no need to default the rule to Allow. ");
    }
}
Also used : NetworkVO(com.cloud.network.dao.NetworkVO) ArrayList(java.util.ArrayList) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) FirewallRule(com.cloud.network.rules.FirewallRule) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO)

Example 38 with FirewallRule

use of com.cloud.network.rules.FirewallRule in project cosmic by MissionCriticalCloud.

the class RemoteAccessVpnManagerImpl method destroyRemoteAccessVpnForIp.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, eventDescription = "removing remote access vpn", async = true)
public boolean destroyRemoteAccessVpnForIp(final long ipId, final Account caller) throws ResourceUnavailableException {
    final RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findByPublicIpAddress(ipId);
    if (vpn == null) {
        s_logger.debug("there are no Remote access vpns for public ip address id=" + ipId);
        return true;
    }
    _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, vpn);
    final RemoteAccessVpn.State prevState = vpn.getState();
    vpn.setState(RemoteAccessVpn.State.Removed);
    _remoteAccessVpnDao.update(vpn.getId(), vpn);
    boolean success = false;
    try {
        for (final RemoteAccessVPNServiceProvider element : _vpnServiceProviders) {
            if (element.stopVpn(vpn)) {
                success = true;
                break;
            }
        }
    } catch (final ResourceUnavailableException ex) {
        vpn.setState(prevState);
        _remoteAccessVpnDao.update(vpn.getId(), vpn);
        s_logger.debug("Failed to stop the vpn " + vpn.getId() + " , so reverted state to " + RemoteAccessVpn.State.Running);
        success = false;
    } finally {
        if (success) {
            // Cleanup corresponding ports
            final List<? extends FirewallRule> vpnFwRules = _rulesDao.listByIpAndPurpose(ipId, Purpose.Vpn);
            boolean applyFirewall = false;
            final List<FirewallRuleVO> fwRules = new ArrayList<>();
            // if related firewall rule is created for the first vpn port, it would be created for the 2 other ports as well, so need to cleanup the backend
            if (vpnFwRules.size() != 0 && _rulesDao.findByRelatedId(vpnFwRules.get(0).getId()) != null) {
                applyFirewall = true;
            }
            if (applyFirewall) {
                Transaction.execute(new TransactionCallbackNoReturn() {

                    @Override
                    public void doInTransactionWithoutResult(final TransactionStatus status) {
                        for (final FirewallRule vpnFwRule : vpnFwRules) {
                            // don't apply on the backend yet; send all 3 rules in a banch
                            _firewallMgr.revokeRelatedFirewallRule(vpnFwRule.getId(), false);
                            fwRules.add(_rulesDao.findByRelatedId(vpnFwRule.getId()));
                        }
                        s_logger.debug("Marked " + fwRules.size() + " firewall rules as Revoked as a part of disable remote access vpn");
                    }
                });
                // now apply vpn rules on the backend
                s_logger.debug("Reapplying firewall rules for ip id=" + ipId + " as a part of disable remote access vpn");
                success = _firewallMgr.applyIngressFirewallRules(ipId, caller);
            }
            if (success) {
                try {
                    Transaction.execute(new TransactionCallbackNoReturn() {

                        @Override
                        public void doInTransactionWithoutResult(final TransactionStatus status) {
                            _remoteAccessVpnDao.remove(vpn.getId());
                            // Stop billing of VPN users when VPN is removed. VPN_User_ADD events will be generated when VPN is created again
                            if (vpnFwRules != null) {
                                for (final FirewallRule vpnFwRule : vpnFwRules) {
                                    _rulesDao.remove(vpnFwRule.getId());
                                    s_logger.debug("Successfully removed firewall rule with ip id=" + vpnFwRule.getSourceIpAddressId() + " and port " + vpnFwRule.getSourcePortStart().intValue() + " as a part of vpn cleanup");
                                }
                            }
                        }
                    });
                } catch (final Exception ex) {
                    s_logger.warn("Unable to release the three vpn ports from the firewall rules", ex);
                }
            }
        }
    }
    return success;
}
Also used : RemoteAccessVPNServiceProvider(com.cloud.network.element.RemoteAccessVPNServiceProvider) RemoteAccessVpnVO(com.cloud.network.dao.RemoteAccessVpnVO) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) AccountLimitException(com.cloud.exception.AccountLimitException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ConfigurationException(javax.naming.ConfigurationException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) FirewallRule(com.cloud.network.rules.FirewallRule) RemoteAccessVpn(com.cloud.network.RemoteAccessVpn) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 39 with FirewallRule

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

the class CreateFirewallRuleCmd method execute.

@Override
public void execute() throws ResourceUnavailableException {
    CallContext callerContext = CallContext.current();
    boolean success = false;
    FirewallRule rule = _entityMgr.findById(FirewallRule.class, getEntityId());
    try {
        CallContext.current().setEventDetails("Rule ID: " + getEntityId());
        success = _firewallService.applyIngressFwRules(rule.getSourceIpAddressId(), callerContext.getCallingAccount());
        // State is different after the rule is applied, so get new object here
        rule = _entityMgr.findById(FirewallRule.class, getEntityId());
        FirewallResponse fwResponse = new FirewallResponse();
        if (rule != null) {
            fwResponse = _responseGenerator.createFirewallResponse(rule);
            setResponseObject(fwResponse);
        }
        fwResponse.setResponseName(getCommandName());
    } finally {
        if (!success || rule == null) {
            _firewallService.revokeIngressFwRule(getEntityId(), true);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create firewall rule");
        }
    }
}
Also used : ServerApiException(org.apache.cloudstack.api.ServerApiException) CallContext(org.apache.cloudstack.context.CallContext) FirewallRule(com.cloud.network.rules.FirewallRule) FirewallResponse(org.apache.cloudstack.api.response.FirewallResponse)

Example 40 with FirewallRule

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

the class CreateFirewallRuleCmd method create.

@Override
public void create() {
    if (getSourceCidrList() != null) {
        for (String cidr : getSourceCidrList()) {
            if (!NetUtils.isValidIp4Cidr(cidr) && !NetUtils.isValidIp6Cidr(cidr)) {
                throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Source CIDRs formatting error " + cidr);
            }
        }
    }
    try {
        FirewallRule result = _firewallService.createIngressFirewallRule(this);
        if (result != null) {
            setEntityId(result.getId());
            setEntityUuid(result.getUuid());
        }
    } catch (NetworkRuleConflictException ex) {
        s_logger.trace("Network Rule Conflict: ", ex);
        throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage(), ex);
    }
}
Also used : ServerApiException(org.apache.cloudstack.api.ServerApiException) FirewallRule(com.cloud.network.rules.FirewallRule) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException)

Aggregations

FirewallRule (com.cloud.network.rules.FirewallRule)59 ArrayList (java.util.ArrayList)32 FirewallRuleVO (com.cloud.network.rules.FirewallRuleVO)16 IpAddress (com.cloud.network.IpAddress)13 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)10 FirewallResponse (com.cloud.api.response.FirewallResponse)9 List (java.util.List)9 ServerApiException (com.cloud.api.ServerApiException)8 PublicIpAddress (com.cloud.network.PublicIpAddress)8 NetworkVO (com.cloud.network.dao.NetworkVO)8 StaticNatRule (com.cloud.network.rules.StaticNatRule)8 FirewallRuleTO (com.cloud.agent.api.to.FirewallRuleTO)7 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)7 NetworkOfferingVO (com.cloud.offerings.NetworkOfferingVO)7 FirewallResponse (org.apache.cloudstack.api.response.FirewallResponse)7 SetFirewallRulesCommand (com.cloud.agent.api.routing.SetFirewallRulesCommand)6 ActionEvent (com.cloud.event.ActionEvent)6 ListResponse (com.cloud.api.response.ListResponse)5 ServerApiException (org.apache.cloudstack.api.ServerApiException)5 IpForwardingRuleResponse (com.cloud.api.response.IpForwardingRuleResponse)4