Search in sources :

Example 11 with PortForwardingRule

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

the class BasicNetworkVisitor method visit.

@SuppressWarnings("unchecked")
@Override
public boolean visit(final FirewallRules firewall) throws ResourceUnavailableException {
    final Network network = firewall.getNetwork();
    final VirtualRouter router = firewall.getRouter();
    final List<? extends FirewallRule> rules = firewall.getRules();
    final List<LoadBalancingRule> loadbalancingRules = firewall.getLoadbalancingRules();
    final Purpose purpose = firewall.getPurpose();
    final Commands cmds = new Commands(Command.OnError.Continue);
    if (purpose == Purpose.LoadBalancing) {
        _commandSetupHelper.createApplyLoadBalancingRulesCommands(loadbalancingRules, router, cmds, network.getId());
        return _networkGeneralHelper.sendCommandsToRouter(router, cmds);
    } else if (purpose == Purpose.PortForwarding) {
        _commandSetupHelper.createApplyPortForwardingRulesCommands((List<? extends PortForwardingRule>) rules, router, cmds, network.getId());
        return _networkGeneralHelper.sendCommandsToRouter(router, cmds);
    } else if (purpose == Purpose.StaticNat) {
        _commandSetupHelper.createApplyStaticNatRulesCommands((List<StaticNatRule>) rules, router, cmds, network.getId());
        return _networkGeneralHelper.sendCommandsToRouter(router, cmds);
    } else if (purpose == Purpose.Firewall) {
        _commandSetupHelper.createApplyFirewallRulesCommands(rules, router, cmds, network.getId());
        return _networkGeneralHelper.sendCommandsToRouter(router, cmds);
    }
    s_logger.warn("Unable to apply rules of purpose: " + rules.get(0).getPurpose());
    return false;
}
Also used : LoadBalancingRule(com.cloud.network.lb.LoadBalancingRule) Network(com.cloud.network.Network) Commands(com.cloud.agent.manager.Commands) Purpose(com.cloud.network.rules.FirewallRule.Purpose) List(java.util.List) ArrayList(java.util.ArrayList) StaticNatRule(com.cloud.network.rules.StaticNatRule) PortForwardingRule(com.cloud.network.rules.PortForwardingRule) VirtualRouter(com.cloud.network.router.VirtualRouter)

Example 12 with PortForwardingRule

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

the class MidoNetElement method applyPFRules.

@Override
public boolean applyPFRules(Network network, List<PortForwardingRule> rules) throws ResourceUnavailableException {
    s_logger.debug("applyPFRules called with network " + network.toString());
    if (!midoInNetwork(network)) {
        return false;
    }
    if (!canHandle(network, Service.PortForwarding)) {
        return false;
    }
    String accountIdStr = getAccountUuid(network);
    String networkUUIDStr = String.valueOf(network.getId());
    RuleChain preNat = getChain(accountIdStr, networkUUIDStr, RuleChainCode.TR_PRENAT);
    RuleChain postNat = getChain(accountIdStr, networkUUIDStr, RuleChainCode.TR_POST);
    RuleChain preFilter = getChain(accountIdStr, networkUUIDStr, RuleChainCode.TR_PREFILTER);
    Router providerRouter = api.getRouter(_providerRouterId);
    Router tenantRouter = getOrCreateGuestNetworkRouter(network);
    RouterPort[] ports = getOrCreateProviderRouterPorts(tenantRouter, providerRouter);
    RouterPort providerDownlink = ports[1];
    // Rules in the preNat table
    Map<String, Rule> existingPreNatRules = new HashMap<String, Rule>();
    for (Rule existingRule : preNat.getRules()) {
        // The "port forwarding" rules we're interested in are dnat rules where src / dst ports are specified
        if (existingRule.getType().equals(DtoRule.DNAT) && existingRule.getTpDst() != null) {
            String ruleString = new SimpleFirewallRule(existingRule).toStringArray()[0];
            existingPreNatRules.put(ruleString, existingRule);
        }
    }
    /*
         * Counts of rules associated with an IP address. Use this to check
         * how many rules we have of a given IP address. When it reaches 0,
         * we can delete the route associated with it.
         */
    Map<String, Integer> ipRuleCounts = new HashMap<String, Integer>();
    for (Rule rule : preNat.getRules()) {
        String ip = rule.getNwDstAddress();
        if (ip != null && rule.getNwDstLength() == 32) {
            if (ipRuleCounts.containsKey(ip)) {
                ipRuleCounts.put(ip, new Integer(ipRuleCounts.get(ip).intValue() + 1));
            } else {
                ipRuleCounts.put(ip, new Integer(1));
            }
        }
    }
    /*
         * Routes associated with IP. When we delete all the rules associated
         * with a given IP, we can delete the route associated with it.
         */
    Map<String, Route> routes = new HashMap<String, Route>();
    for (Route route : providerRouter.getRoutes(new MultivaluedMapImpl())) {
        String ip = route.getDstNetworkAddr();
        if (ip != null && route.getDstNetworkLength() == 32) {
            routes.put(ip, route);
        }
    }
    for (PortForwardingRule rule : rules) {
        IpAddress dstIp = _networkModel.getIp(rule.getSourceIpAddressId());
        PortForwardingRuleTO ruleTO = new PortForwardingRuleTO(rule, null, dstIp.getAddress().addr());
        SimpleFirewallRule fwRule = new SimpleFirewallRule(ruleTO);
        String[] ruleStrings = fwRule.toStringArray();
        if (rule.getState() == FirewallRule.State.Revoke) {
            /*
                 * Lookup in existingRules, delete if present
                 * We need to delete from both the preNat table and the
                 * postNat table.
                 */
            for (String revokeRuleString : ruleStrings) {
                Rule foundPreNatRule = existingPreNatRules.get(revokeRuleString);
                if (foundPreNatRule != null) {
                    String ip = foundPreNatRule.getNwDstAddress();
                    // is this the last rule associated with this IP?
                    Integer cnt = ipRuleCounts.get(ip);
                    if (cnt != null) {
                        if (cnt == 1) {
                            ipRuleCounts.remove(ip);
                            // no more rules for this IP. delete the route.
                            Route route = routes.remove(ip);
                            route.delete();
                        } else {
                            ipRuleCounts.put(ip, new Integer(ipRuleCounts.get(ip).intValue() - 1));
                        }
                    }
                    foundPreNatRule.delete();
                }
            }
        } else if (rule.getState() == FirewallRule.State.Add) {
            for (int i = 0; i < ruleStrings.length; i++) {
                String ruleString = ruleStrings[i];
                Rule foundRule = existingPreNatRules.get(ruleString);
                if (foundRule == null) {
                    String vmIp = ruleTO.getDstIp();
                    String publicIp = dstIp.getAddress().addr();
                    int privPortStart = ruleTO.getDstPortRange()[0];
                    int privPortEnd = ruleTO.getDstPortRange()[1];
                    int pubPortStart = ruleTO.getSrcPortRange()[0];
                    int pubPortEnd = ruleTO.getSrcPortRange()[1];
                    DtoRule.DtoNatTarget[] preTargets = new DtoRule.DtoNatTarget[] { new DtoRule.DtoNatTarget(vmIp, vmIp, privPortStart, privPortEnd) };
                    Rule preNatRule = preNat.addRule().type(DtoRule.DNAT).flowAction(DtoRule.Accept).nwDstAddress(publicIp).nwDstLength(32).tpDst(new DtoRange(pubPortStart, pubPortEnd)).natTargets(preTargets).nwProto(SimpleFirewallRule.stringToProtocolNumber(rule.getProtocol())).position(1);
                    Integer cnt = ipRuleCounts.get(publicIp);
                    if (cnt != null) {
                        ipRuleCounts.put(publicIp, new Integer(cnt.intValue() + 1));
                    } else {
                        ipRuleCounts.put(publicIp, new Integer(1));
                    }
                    String preNatRuleStr = new SimpleFirewallRule(preNatRule).toStringArray()[0];
                    existingPreNatRules.put(preNatRuleStr, preNatRule);
                    preNatRule.create();
                    if (routes.get(publicIp) == null) {
                        Route route = providerRouter.addRoute().type("Normal").weight(100).srcNetworkAddr("0.0.0.0").srcNetworkLength(0).dstNetworkAddr(publicIp).dstNetworkLength(32).nextHopPort(providerDownlink.getId());
                        route.create();
                        routes.put(publicIp, route);
                    }
                    // default firewall rule
                    if (canHandle(network, Service.Firewall)) {
                        boolean defaultBlock = false;
                        for (Rule filterRule : preFilter.getRules()) {
                            String pfDstIp = filterRule.getNwDstAddress();
                            if (pfDstIp != null && filterRule.getNwDstAddress().equals(publicIp)) {
                                defaultBlock = true;
                                break;
                            }
                        }
                        if (!defaultBlock) {
                            preFilter.addRule().type(DtoRule.Drop).nwDstAddress(publicIp).nwDstLength(32).create();
                        }
                    }
                }
            }
        }
    }
    return true;
}
Also used : DtoRange(org.midonet.client.dto.DtoRule.DtoRange) PortForwardingRuleTO(com.cloud.agent.api.to.PortForwardingRuleTO) HashMap(java.util.HashMap) DtoRule(org.midonet.client.dto.DtoRule) Router(org.midonet.client.resource.Router) MultivaluedMapImpl(com.sun.jersey.core.util.MultivaluedMapImpl) PortForwardingRule(com.cloud.network.rules.PortForwardingRule) RuleChain(org.midonet.client.resource.RuleChain) 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) RouterPort(org.midonet.client.resource.RouterPort) Route(org.midonet.client.resource.Route)

Example 13 with PortForwardingRule

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

the class ExternalFirewallDeviceManagerImpl method applyPortForwardingRules.

@Override
public boolean applyPortForwardingRules(Network network, List<? extends PortForwardingRule> rules) throws ResourceUnavailableException {
    // Find the external firewall in this zone
    long zoneId = network.getDataCenterId();
    DataCenterVO zone = _dcDao.findById(zoneId);
    ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network);
    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<PortForwardingRuleTO> pfRules = new ArrayList<PortForwardingRuleTO>();
    for (PortForwardingRule rule : rules) {
        IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
        Vlan vlan = _vlanDao.findById(sourceIp.getVlanId());
        PortForwardingRuleTO ruleTO = new PortForwardingRuleTO(rule, vlan.getVlanTag(), sourceIp.getAddress().addr());
        pfRules.add(ruleTO);
    }
    sendPortForwardingRules(pfRules, zone, externalFirewall.getId());
    return true;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) ExternalFirewallDeviceVO(com.cloud.network.dao.ExternalFirewallDeviceVO) PortForwardingRuleTO(com.cloud.agent.api.to.PortForwardingRuleTO) ArrayList(java.util.ArrayList) Vlan(com.cloud.dc.Vlan) PortForwardingRule(com.cloud.network.rules.PortForwardingRule) HostVO(com.cloud.host.HostVO)

Example 14 with PortForwardingRule

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

the class CreatePortForwardingRuleCmd method create.

@Override
public void create() {
    // cidr list parameter is deprecated
    if (cidrlist != null) {
        throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command");
    }
    Ip privateIp = getVmSecondaryIp();
    if (privateIp != null) {
        if (!NetUtils.isValidIp(privateIp.toString())) {
            throw new InvalidParameterValueException("Invalid vm ip address");
        }
    }
    try {
        PortForwardingRule result = _rulesService.createPortForwardingRule(this, virtualMachineId, privateIp, getOpenFirewall(), isDisplay());
        setEntityId(result.getId());
        setEntityUuid(result.getUuid());
    } catch (NetworkRuleConflictException ex) {
        s_logger.info("Network rule conflict: ", ex);
        s_logger.trace("Network Rule Conflict: ", ex);
        throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage());
    }
}
Also used : ServerApiException(org.apache.cloudstack.api.ServerApiException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Ip(com.cloud.utils.net.Ip) PortForwardingRule(com.cloud.network.rules.PortForwardingRule) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException)

Example 15 with PortForwardingRule

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

the class ListPortForwardingRulesCmd method execute.

@Override
public void execute() {
    Pair<List<? extends PortForwardingRule>, Integer> result = _rulesService.listPortForwardingRules(this);
    ListResponse<FirewallRuleResponse> response = new ListResponse<FirewallRuleResponse>();
    List<FirewallRuleResponse> fwResponses = new ArrayList<FirewallRuleResponse>();
    for (PortForwardingRule fwRule : result.first()) {
        FirewallRuleResponse ruleData = _responseGenerator.createPortForwardingRuleResponse(fwRule);
        ruleData.setObjectName("portforwardingrule");
        fwResponses.add(ruleData);
    }
    response.setResponses(fwResponses, result.second());
    response.setResponseName(getCommandName());
    setResponseObject(response);
}
Also used : ListResponse(org.apache.cloudstack.api.response.ListResponse) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) PortForwardingRule(com.cloud.network.rules.PortForwardingRule) FirewallRuleResponse(org.apache.cloudstack.api.response.FirewallRuleResponse)

Aggregations

PortForwardingRule (com.cloud.network.rules.PortForwardingRule)15 ArrayList (java.util.ArrayList)9 PortForwardingRuleTO (com.cloud.agent.api.to.PortForwardingRuleTO)5 IpAddress (com.cloud.network.IpAddress)5 PublicIpAddress (com.cloud.network.PublicIpAddress)5 HostVO (com.cloud.host.HostVO)4 SetPortForwardingRulesCommand (com.cloud.agent.api.routing.SetPortForwardingRulesCommand)3 Vlan (com.cloud.dc.Vlan)3 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)3 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)3 Network (com.cloud.network.Network)3 Ip (com.cloud.utils.net.Ip)3 FirewallRuleResponse (org.apache.cloudstack.api.response.FirewallRuleResponse)3 Answer (com.cloud.agent.api.Answer)2 ServerApiException (com.cloud.api.ServerApiException)2 FirewallRuleResponse (com.cloud.api.response.FirewallRuleResponse)2 DataCenterVO (com.cloud.dc.DataCenterVO)2 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)2 PublicIp (com.cloud.network.addr.PublicIp)2 CiscoVnmcControllerVO (com.cloud.network.cisco.CiscoVnmcControllerVO)2