Search in sources :

Example 26 with FirewallRuleVO

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

the class FirewallManagerImpl method createFirewallRule.

@DB
protected FirewallRule createFirewallRule(final Long ipAddrId, Account caller, final String xId, final Integer portStart, final Integer portEnd, final String protocol, final List<String> sourceCidrList, final Integer icmpCode, final Integer icmpType, final Long relatedRuleId, final FirewallRule.FirewallRuleType type, final Long networkId, final FirewallRule.TrafficType trafficType, final Boolean forDisplay) throws NetworkRuleConflictException {
    IPAddressVO ipAddress = null;
    if (ipAddrId != null) {
        // this for ingress firewall rule, for egress id is null
        ipAddress = _ipAddressDao.findById(ipAddrId);
        // Validate ip address
        if (ipAddress == null && type == FirewallRule.FirewallRuleType.User) {
            throw new InvalidParameterValueException("Unable to create firewall rule; " + "couldn't locate IP address by id in the system");
        }
        _networkModel.checkIpForService(ipAddress, Service.Firewall, null);
    }
    validateFirewallRule(caller, ipAddress, portStart, portEnd, protocol, Purpose.Firewall, type, networkId, trafficType);
    // icmp code and icmp type can't be passed in for any other protocol rather than icmp
    if (!protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO) && (icmpCode != null || icmpType != null)) {
        throw new InvalidParameterValueException("Can specify icmpCode and icmpType for ICMP protocol only");
    }
    if (protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO) && (portStart != null || portEnd != null)) {
        throw new InvalidParameterValueException("Can't specify start/end port when protocol is ICMP");
    }
    Long accountId = null;
    Long domainId = null;
    if (ipAddress != null) {
        //Ingress firewall rule
        accountId = ipAddress.getAllocatedToAccountId();
        domainId = ipAddress.getAllocatedInDomainId();
    } else if (networkId != null) {
        //egress firewall rule
        Network network = _networkModel.getNetwork(networkId);
        accountId = network.getAccountId();
        domainId = network.getDomainId();
    }
    final Long accountIdFinal = accountId;
    final Long domainIdFinal = domainId;
    return Transaction.execute(new TransactionCallbackWithException<FirewallRuleVO, NetworkRuleConflictException>() {

        @Override
        public FirewallRuleVO doInTransaction(TransactionStatus status) throws NetworkRuleConflictException {
            FirewallRuleVO newRule = new FirewallRuleVO(xId, ipAddrId, portStart, portEnd, protocol.toLowerCase(), networkId, accountIdFinal, domainIdFinal, Purpose.Firewall, sourceCidrList, icmpCode, icmpType, relatedRuleId, trafficType);
            newRule.setType(type);
            if (forDisplay != null) {
                newRule.setDisplay(forDisplay);
            }
            newRule = _firewallDao.persist(newRule);
            if (type == FirewallRuleType.User)
                detectRulesConflict(newRule);
            if (!_firewallDao.setStateToAdd(newRule)) {
                throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
            }
            CallContext.current().setEventDetails("Rule Id: " + newRule.getId());
            return newRule;
        }
    });
}
Also used : InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) TransactionStatus(com.cloud.utils.db.TransactionStatus) IPAddressVO(com.cloud.network.dao.IPAddressVO) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) DB(com.cloud.utils.db.DB)

Example 27 with FirewallRuleVO

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

the class ExternalGuestNetworkGuru method implement.

@Override
public Network implement(Network config, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws InsufficientVirtualNetworkCapacityException {
    assert (config.getState() == State.Implementing) : "Why are we implementing " + config;
    if (_networkModel.areServicesSupportedInNetwork(config.getId(), Network.Service.Connectivity)) {
        return null;
    }
    if (!_networkModel.networkIsConfiguredForExternalNetworking(config.getDataCenterId(), config.getId())) {
        return super.implement(config, offering, dest, context);
    }
    DataCenter zone = dest.getDataCenter();
    NetworkVO implemented = new NetworkVO(config.getTrafficType(), config.getMode(), config.getBroadcastDomainType(), config.getNetworkOfferingId(), State.Allocated, config.getDataCenterId(), config.getPhysicalNetworkId(), offering.getRedundantRouter());
    // Get a vlan tag
    int vlanTag;
    if (config.getBroadcastUri() == null) {
        String vnet = _dcDao.allocateVnet(zone.getId(), config.getPhysicalNetworkId(), config.getAccountId(), context.getReservationId(), UseSystemGuestVlans.valueIn(config.getAccountId()));
        try {
            // when supporting more types of networks this need to become
            //              int vlantag = Integer.parseInt(BroadcastDomainType.getValue(vnet));
            vlanTag = Integer.parseInt(vnet);
        } catch (NumberFormatException e) {
            throw new CloudRuntimeException("Obtained an invalid guest vlan tag. Exception: " + e.getMessage());
        }
        implemented.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vlanTag));
        ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), config.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_ZONE_VLAN_ASSIGN, "Assigned Zone Vlan: " + vnet + " Network Id: " + config.getId(), 0);
    } else {
        vlanTag = Integer.parseInt(BroadcastDomainType.getValue(config.getBroadcastUri()));
        implemented.setBroadcastUri(config.getBroadcastUri());
    }
    // Determine the new gateway and CIDR
    String[] oldCidr = config.getCidr().split("/");
    String oldCidrAddress = oldCidr[0];
    int cidrSize = Integer.parseInt(oldCidr[1]);
    long newCidrAddress = (NetUtils.ip2Long(oldCidrAddress));
    // if the implementing network is for vpc, no need to generate newcidr, use the cidr that came from super cidr
    if (config.getVpcId() != null) {
        implemented.setGateway(config.getGateway());
        implemented.setCidr(config.getCidr());
        implemented.setState(State.Implemented);
    } else {
        // Determine the offset from the lowest vlan tag
        int offset = getVlanOffset(config.getPhysicalNetworkId(), vlanTag);
        cidrSize = getGloballyConfiguredCidrSize();
        // If the offset has more bits than there is room for, return null
        long bitsInOffset = 32 - Integer.numberOfLeadingZeros(offset);
        if (bitsInOffset > (cidrSize - 8)) {
            throw new CloudRuntimeException("The offset " + offset + " needs " + bitsInOffset + " bits, but only have " + (cidrSize - 8) + " bits to work with.");
        }
        newCidrAddress = (NetUtils.ip2Long(oldCidrAddress) & 0xff000000) | (offset << (32 - cidrSize));
        implemented.setGateway(NetUtils.long2Ip(newCidrAddress + 1));
        implemented.setCidr(NetUtils.long2Ip(newCidrAddress) + "/" + cidrSize);
        implemented.setState(State.Implemented);
    }
    // Mask the Ipv4 address of all nics that use this network with the new guest VLAN offset
    List<NicVO> nicsInNetwork = _nicDao.listByNetworkId(config.getId());
    for (NicVO nic : nicsInNetwork) {
        if (nic.getIPv4Address() != null) {
            long ipMask = getIpMask(nic.getIPv4Address(), cidrSize);
            nic.setIPv4Address(NetUtils.long2Ip(newCidrAddress | ipMask));
            _nicDao.persist(nic);
        }
    }
    // Mask the destination address of all port forwarding rules in this network with the new guest VLAN offset
    List<PortForwardingRuleVO> pfRulesInNetwork = _pfRulesDao.listByNetwork(config.getId());
    for (PortForwardingRuleVO pfRule : pfRulesInNetwork) {
        if (pfRule.getDestinationIpAddress() != null) {
            long ipMask = getIpMask(pfRule.getDestinationIpAddress().addr(), cidrSize);
            String maskedDestinationIpAddress = NetUtils.long2Ip(newCidrAddress | ipMask);
            pfRule.setDestinationIpAddress(new Ip(maskedDestinationIpAddress));
            _pfRulesDao.update(pfRule.getId(), pfRule);
        }
    }
    // Mask the destination address of all static nat rules in this network with the new guest VLAN offset
    // Here the private ip of the nic get updated. When secondary ip are present the gc will not triggered
    List<IPAddressVO> ipAddrsOfNw = _ipAddressDao.listStaticNatPublicIps(config.getId());
    for (IPAddressVO ip : ipAddrsOfNw) {
        if (ip.getVmIp() != null) {
            long ipMask = getIpMask(ip.getVmIp(), cidrSize);
            String maskedVmIp = NetUtils.long2Ip(newCidrAddress | ipMask);
            ip.setVmIp(maskedVmIp);
            _ipAddressDao.update(ip.getId(), ip);
        }
    }
    //Egress rules cidr is subset of guest nework cidr, we need to change
    List<FirewallRuleVO> fwEgressRules = _fwRulesDao.listByNetworkPurposeTrafficType(config.getId(), FirewallRule.Purpose.Firewall, FirewallRule.TrafficType.Egress);
    for (FirewallRuleVO rule : fwEgressRules) {
        //get the cidr list for this rule
        List<FirewallRulesCidrsVO> fwRuleCidrsVo = _fwRulesCidrDao.listByFirewallRuleId(rule.getId());
        for (FirewallRulesCidrsVO ruleCidrvo : fwRuleCidrsVo) {
            String cidr = ruleCidrvo.getCidr();
            String cidrAddr = cidr.split("/")[0];
            String size = cidr.split("/")[1];
            long ipMask = getIpMask(cidrAddr, cidrSize);
            String newIp = NetUtils.long2Ip(newCidrAddress | ipMask);
            String updatedCidr = newIp + "/" + size;
            ruleCidrvo.setSourceCidrList(updatedCidr);
            _fwRulesCidrDao.update(ruleCidrvo.getId(), ruleCidrvo);
        }
    }
    return implemented;
}
Also used : NetworkVO(com.cloud.network.dao.NetworkVO) PortForwardingRuleVO(com.cloud.network.rules.PortForwardingRuleVO) Ip(com.cloud.utils.net.Ip) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) DataCenter(com.cloud.dc.DataCenter) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IPAddressVO(com.cloud.network.dao.IPAddressVO) FirewallRulesCidrsVO(com.cloud.network.dao.FirewallRulesCidrsVO) NicVO(com.cloud.vm.NicVO)

Example 28 with FirewallRuleVO

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

the class FirewallManagerImpl method revokeFirewallRulesForVm.

@Override
@ActionEvent(eventType = EventTypes.EVENT_FIREWALL_CLOSE, eventDescription = "revoking firewall rule", async = true)
public boolean revokeFirewallRulesForVm(long vmId) {
    boolean success = true;
    UserVmVO vm = _vmDao.findByIdIncludingRemoved(vmId);
    if (vm == null) {
        return false;
    }
    List<PortForwardingRuleVO> pfRules = _pfRulesDao.listByVm(vmId);
    List<FirewallRuleVO> staticNatRules = _firewallDao.listStaticNatByVmId(vm.getId());
    List<FirewallRuleVO> firewallRules = new ArrayList<FirewallRuleVO>();
    // Make a list of firewall rules to reprogram
    for (PortForwardingRuleVO pfRule : pfRules) {
        FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(pfRule.getId());
        if (relatedRule != null) {
            firewallRules.add(relatedRule);
        }
    }
    for (FirewallRuleVO staticNatRule : staticNatRules) {
        FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(staticNatRule.getId());
        if (relatedRule != null) {
            firewallRules.add(relatedRule);
        }
    }
    Set<Long> ipsToReprogram = new HashSet<Long>();
    if (firewallRules.isEmpty()) {
        s_logger.debug("No firewall rules are found for vm id=" + vmId);
        return true;
    } else {
        s_logger.debug("Found " + firewallRules.size() + " to cleanup for vm id=" + vmId);
    }
    for (FirewallRuleVO rule : firewallRules) {
        // Mark firewall rules as Revoked, but don't revoke it yet (apply=false)
        revokeFirewallRule(rule.getId(), false, _accountMgr.getSystemAccount(), Account.ACCOUNT_ID_SYSTEM);
        ipsToReprogram.add(rule.getSourceIpAddressId());
    }
    // apply rules for all ip addresses
    for (Long ipId : ipsToReprogram) {
        s_logger.debug("Applying firewall rules for ip address id=" + ipId + " as a part of vm expunge");
        try {
            success = success && applyIngressFirewallRules(ipId, _accountMgr.getSystemAccount());
        } catch (ResourceUnavailableException ex) {
            s_logger.warn("Failed to apply port forwarding rules for ip id=" + ipId);
            success = false;
        }
    }
    return success;
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) PortForwardingRuleVO(com.cloud.network.rules.PortForwardingRuleVO) ArrayList(java.util.ArrayList) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) HashSet(java.util.HashSet) ActionEvent(com.cloud.event.ActionEvent)

Example 29 with FirewallRuleVO

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

the class NetworkModelImpl method getPublicIpPurposeInRules.

Set<Purpose> getPublicIpPurposeInRules(PublicIpAddress ip, boolean includeRevoked, boolean includingFirewall) {
    Set<Purpose> result = new HashSet<Purpose>();
    List<FirewallRuleVO> rules = null;
    if (includeRevoked) {
        rules = _firewallDao.listByIp(ip.getId());
    } else {
        rules = _firewallDao.listByIpAndNotRevoked(ip.getId());
    }
    if (rules == null || rules.isEmpty()) {
        return null;
    }
    for (FirewallRuleVO rule : rules) {
        if (rule.getPurpose() != Purpose.Firewall || includingFirewall) {
            result.add(rule.getPurpose());
        }
    }
    return result;
}
Also used : Purpose(com.cloud.network.rules.FirewallRule.Purpose) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) HashSet(java.util.HashSet)

Example 30 with FirewallRuleVO

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

the class FirewallRulesDaoImpl method persist.

@Override
@DB
public FirewallRuleVO persist(FirewallRuleVO firewallRule) {
    TransactionLegacy txn = TransactionLegacy.currentTxn();
    txn.start();
    FirewallRuleVO dbfirewallRule = super.persist(firewallRule);
    saveSourceCidrs(firewallRule, firewallRule.getSourceCidrList());
    loadSourceCidrs(dbfirewallRule);
    txn.commit();
    return dbfirewallRule;
}
Also used : TransactionLegacy(com.cloud.utils.db.TransactionLegacy) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) DB(com.cloud.utils.db.DB)

Aggregations

FirewallRuleVO (com.cloud.network.rules.FirewallRuleVO)32 ArrayList (java.util.ArrayList)18 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)9 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)8 IPAddressVO (com.cloud.network.dao.IPAddressVO)8 FirewallRule (com.cloud.network.rules.FirewallRule)8 DB (com.cloud.utils.db.DB)7 List (java.util.List)7 ActionEvent (com.cloud.event.ActionEvent)6 Network (com.cloud.network.Network)6 NetworkVO (com.cloud.network.dao.NetworkVO)6 Test (org.junit.Test)6 Account (com.cloud.user.Account)5 TransactionStatus (com.cloud.utils.db.TransactionStatus)5 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)5 HashSet (java.util.HashSet)5 DataCenter (com.cloud.dc.DataCenter)4 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)4 PortForwardingRuleVO (com.cloud.network.rules.PortForwardingRuleVO)4 PhysicalNetwork (com.cloud.network.PhysicalNetwork)3