Search in sources :

Example 6 with FirewallRule

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

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(long ipId, Account caller, final boolean forceCleanup) 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);
    RemoteAccessVpn.State prevState = vpn.getState();
    vpn.setState(RemoteAccessVpn.State.Removed);
    _remoteAccessVpnDao.update(vpn.getId(), vpn);
    boolean success = false;
    try {
        for (RemoteAccessVPNServiceProvider element : _vpnServiceProviders) {
            if (element.stopVpn(vpn)) {
                success = true;
                break;
            }
        }
    } catch (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 || forceCleanup) {
            //Cleanup corresponding ports
            final List<? extends FirewallRule> vpnFwRules = _rulesDao.listByIpAndPurpose(ipId, Purpose.Vpn);
            boolean applyFirewall = false;
            final List<FirewallRuleVO> fwRules = new ArrayList<FirewallRuleVO>();
            //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(TransactionStatus status) {
                        for (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 || forceCleanup) {
                try {
                    Transaction.execute(new TransactionCallbackNoReturn() {

                        @Override
                        public void doInTransactionWithoutResult(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
                            List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId());
                            for (VpnUserVO user : vpnUsers) {
                                // VPN_USER_REMOVE event is already generated for users in Revoke state
                                if (user.getState() != VpnUser.State.Revoke) {
                                    UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VPN_USER_REMOVE, user.getAccountId(), 0, user.getId(), user.getUsername(), user.getClass().getName(), user.getUuid());
                                }
                            }
                            if (vpnFwRules != null) {
                                for (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 (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) VpnUserVO(com.cloud.network.VpnUserVO) 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) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ConfigurationException(javax.naming.ConfigurationException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) List(java.util.List) ArrayList(java.util.ArrayList) FirewallRule(com.cloud.network.rules.FirewallRule) RemoteAccessVpn(com.cloud.network.RemoteAccessVpn) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 7 with FirewallRule

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

the class FirewallManagerTest method testDetectRulesConflict.

@Test
public void testDetectRulesConflict() {
    List<FirewallRuleVO> ruleList = new ArrayList<FirewallRuleVO>();
    FirewallRuleVO rule1 = spy(new FirewallRuleVO("rule1", 3, 500, "UDP", 1, 2, 1, Purpose.Vpn, null, null, null, null));
    FirewallRuleVO rule2 = spy(new FirewallRuleVO("rule2", 3, 1701, "UDP", 1, 2, 1, Purpose.Vpn, null, null, null, null));
    FirewallRuleVO rule3 = spy(new FirewallRuleVO("rule3", 3, 4500, "UDP", 1, 2, 1, Purpose.Vpn, null, null, null, null));
    ruleList.add(rule1);
    ruleList.add(rule2);
    ruleList.add(rule3);
    FirewallManagerImpl firewallMgr = (FirewallManagerImpl) _firewallMgr;
    when(firewallMgr._firewallDao.listByIpAndPurposeAndNotRevoked(3, null)).thenReturn(ruleList);
    when(rule1.getId()).thenReturn(1L);
    when(rule2.getId()).thenReturn(2L);
    when(rule3.getId()).thenReturn(3L);
    FirewallRule newRule1 = new FirewallRuleVO("newRule1", 3, 500, "TCP", 1, 2, 1, Purpose.PortForwarding, null, null, null, null);
    FirewallRule newRule2 = new FirewallRuleVO("newRule2", 3, 1701, "TCP", 1, 2, 1, Purpose.PortForwarding, null, null, null, null);
    FirewallRule newRule3 = new FirewallRuleVO("newRule3", 3, 4500, "TCP", 1, 2, 1, Purpose.PortForwarding, null, null, null, null);
    try {
        firewallMgr.detectRulesConflict(newRule1);
        firewallMgr.detectRulesConflict(newRule2);
        firewallMgr.detectRulesConflict(newRule3);
    } catch (NetworkRuleConflictException ex) {
        Assert.fail();
    }
}
Also used : ArrayList(java.util.ArrayList) FirewallRule(com.cloud.network.rules.FirewallRule) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) Test(org.junit.Test)

Example 8 with FirewallRule

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

the class FirewallManagerImpl method revokeAllFirewallRulesForNetwork.

@Override
@ActionEvent(eventType = EventTypes.EVENT_FIREWALL_CLOSE, eventDescription = "revoking firewall rule", async = true)
public boolean revokeAllFirewallRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException {
    List<FirewallRule> rules = new ArrayList<FirewallRule>();
    List<FirewallRuleVO> fwRules = _firewallDao.listByNetworkAndPurposeAndNotRevoked(networkId, Purpose.Firewall);
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Releasing " + fwRules.size() + " firewall rules for network id=" + networkId);
    }
    for (FirewallRuleVO rule : fwRules) {
        // Mark all Firewall rules as Revoke, but don't revoke them yet - we have to revoke all rules for ip, no
        // need to send them one by one
        revokeFirewallRule(rule.getId(), false, caller, Account.ACCOUNT_ID_SYSTEM);
    }
    // now send everything to the backend
    List<FirewallRuleVO> rulesToApply = _firewallDao.listByNetworkAndPurpose(networkId, Purpose.Firewall);
    boolean success = applyFirewallRules(rulesToApply, true, caller);
    // Now we check again in case more rules have been inserted.
    rules.addAll(_firewallDao.listByNetworkAndPurposeAndNotRevoked(networkId, Purpose.Firewall));
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Successfully released firewall rules for network id=" + networkId + " and # of rules now = " + rules.size());
    }
    return success && rules.size() == 0;
}
Also used : ArrayList(java.util.ArrayList) FirewallRule(com.cloud.network.rules.FirewallRule) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) ActionEvent(com.cloud.event.ActionEvent)

Example 9 with FirewallRule

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

the class FirewallManagerImpl method applyRules.

@Override
public boolean applyRules(List<? extends FirewallRule> rules, boolean continueOnError, boolean updateRulesInDB) throws ResourceUnavailableException {
    boolean success = true;
    if (rules == null || rules.size() == 0) {
        s_logger.debug("There are no rules to forward to the network elements");
        return true;
    }
    Purpose purpose = rules.get(0).getPurpose();
    if (!_ipAddrMgr.applyRules(rules, purpose, this, continueOnError)) {
        s_logger.warn("Rules are not completely applied");
        return false;
    } else {
        if (updateRulesInDB) {
            for (FirewallRule rule : rules) {
                if (rule.getState() == FirewallRule.State.Revoke) {
                    FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(rule.getId());
                    if (relatedRule != null) {
                        s_logger.warn("Can't remove the firewall rule id=" + rule.getId() + " as it has related firewall rule id=" + relatedRule.getId() + "; leaving it in Revoke state");
                        success = false;
                    } else {
                        removeRule(rule);
                        if (rule.getSourceIpAddressId() != null) {
                            //if the rule is the last one for the ip address assigned to VPC, unassign it from the network
                            IpAddress ip = _ipAddressDao.findById(rule.getSourceIpAddressId());
                            _vpcMgr.unassignIPFromVpcNetwork(ip.getId(), rule.getNetworkId());
                        }
                    }
                } else if (rule.getState() == FirewallRule.State.Add) {
                    FirewallRuleVO ruleVO = _firewallDao.findById(rule.getId());
                    ruleVO.setState(FirewallRule.State.Active);
                    _firewallDao.update(ruleVO.getId(), ruleVO);
                }
            }
        }
    }
    return success;
}
Also used : Purpose(com.cloud.network.rules.FirewallRule.Purpose) IpAddress(com.cloud.network.IpAddress) FirewallRule(com.cloud.network.rules.FirewallRule) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO)

Example 10 with FirewallRule

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

the class FirewallManagerImpl method revokeFirewallRulesForIp.

@Override
@ActionEvent(eventType = EventTypes.EVENT_FIREWALL_CLOSE, eventDescription = "revoking firewall rule", async = true)
public boolean revokeFirewallRulesForIp(long ipId, long userId, Account caller) throws ResourceUnavailableException {
    List<FirewallRule> rules = new ArrayList<FirewallRule>();
    List<FirewallRuleVO> fwRules = _firewallDao.listByIpAndPurposeAndNotRevoked(ipId, Purpose.Firewall);
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Releasing " + fwRules.size() + " firewall rules for ip id=" + ipId);
    }
    for (FirewallRuleVO rule : fwRules) {
        // Mark all Firewall rules as Revoke, but don't revoke them yet - we have to revoke all rules for ip, no
        // need to send them one by one
        revokeFirewallRule(rule.getId(), false, caller, Account.ACCOUNT_ID_SYSTEM);
    }
    // now send everything to the backend
    List<FirewallRuleVO> rulesToApply = _firewallDao.listByIpAndPurpose(ipId, Purpose.Firewall);
    //apply rules
    if (!applyFirewallRules(rulesToApply, rulesContinueOnErrFlag, caller)) {
        if (!rulesContinueOnErrFlag) {
            return false;
        }
    }
    // Now we check again in case more rules have been inserted.
    rules.addAll(_firewallDao.listByIpAndPurposeAndNotRevoked(ipId, Purpose.Firewall));
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Successfully released firewall rules for ip id=" + ipId + " and # of rules now = " + rules.size());
    }
    return rules.size() == 0;
}
Also used : ArrayList(java.util.ArrayList) FirewallRule(com.cloud.network.rules.FirewallRule) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) ActionEvent(com.cloud.event.ActionEvent)

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