Code improvements for FDS scenarios
[groupbasedpolicy.git] / renderers / vpp / src / main / java / org / opendaylight / groupbasedpolicy / renderer / vpp / policy / acl / AccessListUtil.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.groupbasedpolicy.renderer.vpp.policy.acl;
10
11 import java.net.Inet4Address;
12 import java.net.Inet6Address;
13 import java.net.InetAddress;
14 import java.net.UnknownHostException;
15 import java.util.ArrayList;
16 import java.util.Arrays;
17 import java.util.HashMap;
18 import java.util.List;
19 import java.util.Map;
20
21 import javax.annotation.Nonnull;
22
23 import org.opendaylight.groupbasedpolicy.api.sf.AllowActionDefinition;
24 import org.opendaylight.groupbasedpolicy.renderer.util.AddressEndpointUtils;
25 import org.opendaylight.groupbasedpolicy.renderer.vpp.policy.PolicyContext;
26 import org.opendaylight.groupbasedpolicy.renderer.vpp.policy.RendererResolvedPolicy;
27 import org.opendaylight.groupbasedpolicy.renderer.vpp.sf.SubjectFeatures;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160708.access.lists.acl.access.list.entries.ace.Actions;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160708.access.lists.acl.access.list.entries.ace.ActionsBuilder;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160708.access.lists.acl.access.list.entries.ace.actions.packet.handling.PermitBuilder;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Prefix;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.RuleName;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.forwarding.l2_l3.rev170511.SubnetAugmentRenderer;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.forwarding.l2_l3.rev170511.has.subnet.Subnet;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.HasDirection.Direction;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.subject.feature.instance.ParameterValue;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.renderer.rev151103.EndpointPolicyParticipation;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.renderer.rev151103.renderers.renderer.renderer.policy.configuration.endpoints.AddressEndpointWithLocation;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.renderer.rev151103.renderers.renderer.renderer.policy.configuration.renderer.endpoints.RendererEndpointKey;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.renderer.rev151103.renderers.renderer.renderer.policy.configuration.renderer.endpoints.renderer.endpoint.PeerEndpointKey;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.renderer.rev151103.renderers.renderer.renderer.policy.configuration.renderer.forwarding.RendererForwardingByTenant;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.has.actions.Action;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.has.classifiers.Classifier;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.has.resolved.rules.ResolvedRule;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 import com.google.common.base.Optional;
51
52 /*
53  * Transforms Renderer policy into access-list configuration for Honeycomb.
54  *
55  */
56
57 public class AccessListUtil {
58
59     private static final Logger LOG = LoggerFactory.getLogger(AccessListUtil.class);
60     static final String UNDERSCORE = "_";
61     private static final String PERMIT_EXTERNAL_INGRESS = "permit_external_ingress";
62     private static final String PERMIT_EXTERNAL_EGRESS = "permit_external_egress";
63     private static final String DENY_INGRESS_IPV4 = "deny_ingress_ipv4";
64     private static final String DENY_INGRESS_IPV6 = "deny_ingress_ipv6";
65     private static final String DENY_EGRESS_IPV4 = "deny_egress_ipv4";
66     private static final String DENY_EGRESS_IPV6 = "deny_egress_ipv6";
67
68     public enum ACE_DIRECTION {
69         INGRESS, EGRESS
70     }
71
72     // hiding default public constructor
73     private AccessListUtil() {}
74
75     static void configureLocalRules(PolicyContext ctx, RendererEndpointKey rEpKey, ACE_DIRECTION policyDirection,
76             AccessListWrapper aclWrapper) {
77         ctx.getPolicyTable()
78             .row(rEpKey)
79             .keySet()
80             .stream()
81             .filter(peerEpKey -> peerHasLocation(ctx, peerEpKey))
82             .forEach(peerEpKey -> {
83                 ctx.getPolicyTable().get(rEpKey, peerEpKey).forEach(resolvedRules -> {
84                     List<GbpAceBuilder> rules = new ArrayList<>();
85                     Direction classifDir = calculateClassifDirection(resolvedRules.getRendererEndpointParticipation(),
86                             policyDirection);
87                     rules.addAll(resolveAclRulesFromPolicy(resolvedRules, classifDir, rEpKey, peerEpKey));
88                     updateAddressesInRules(rules, rEpKey, peerEpKey, ctx, policyDirection, true);
89                     aclWrapper.writeRules(rules);
90
91                 });
92             });
93     }
94
95     /**
96      * Resolves direction for classifiers that will be applied to INBOUND or OUTBOUND direction.
97      * </p>
98      * Rule is applied in INGRESS direction when participation is PROVIDER and classifier direction
99      * is OUT
100      * </p>
101      * Rule is applied in INGRESS direction when participation is CONSUMER and classifier direction
102      * is IN
103      * </p>
104      * INBOUND direction is applied otherwise.
105      * </p>
106      * Based on this
107      * </p>
108      * OUT classifier direction is resolved for INGRESS traffic when participation is PROVIDER
109      * </p>
110      * OUT classifier direction is resolved for EGRESS traffic when participation is CONSUMER
111      * </p>
112      * IN is resolved otherwise.
113      * </p>
114      * 
115      * @param participation provider or consumer
116      * @param direction EGRESS or INGRESS
117      * @return Direction that classifiers should match for given policy direction.
118      */
119     static Direction calculateClassifDirection(EndpointPolicyParticipation participation, ACE_DIRECTION direction) {
120         if (EndpointPolicyParticipation.PROVIDER.equals(participation) && ACE_DIRECTION.INGRESS.equals(direction)) {
121             return Direction.Out;
122         }
123         if (EndpointPolicyParticipation.CONSUMER.equals(participation) && ACE_DIRECTION.EGRESS.equals(direction)) {
124             return Direction.Out;
125         }
126         return Direction.In;
127     }
128
129     static void updateAddressesInRules(List<GbpAceBuilder> rules, RendererEndpointKey rEpKey, PeerEndpointKey peerEpKey,
130             PolicyContext ctx, ACE_DIRECTION policyDirection, boolean resolveForLocationPeers) {
131         for (AddressMapper addrMapper : Arrays.asList(new SourceMapper(policyDirection),
132                 new DestinationMapper(policyDirection))) {
133             if (peerHasLocation(ctx, peerEpKey) && resolveForLocationPeers) {
134                 addrMapper.updateRules(rules, findAddrEp(ctx, rEpKey), findAddrEp(ctx, peerEpKey));
135             } else if (!peerHasLocation(ctx, peerEpKey) && !resolveForLocationPeers) {
136                 addrMapper.updateExtRules(rules, findAddrEp(ctx, rEpKey), null);
137             }
138         }
139     }
140
141     private static boolean peerHasLocation(PolicyContext ctx, PeerEndpointKey peerEpKey) {
142         return ctx.getAddrEpByKey().get(AddressEndpointUtils.fromPeerEpKey(peerEpKey)) != null;
143     }
144
145     static AddressEndpointWithLocation findAddrEp(PolicyContext ctx, RendererEndpointKey rEpKey) {
146         return ctx.getAddrEpByKey().get(AddressEndpointUtils.fromRendererEpKey(rEpKey));
147     }
148
149     private static AddressEndpointWithLocation findAddrEp(PolicyContext ctx, PeerEndpointKey rEpKey) {
150         return ctx.getAddrEpByKey().get(AddressEndpointUtils.fromPeerEpKey(rEpKey));
151     }
152
153     /**
154      * Transform a resolved rule to ACE with corresponding classification and action fields
155      *
156      * @param resolvedPolicy resolved rules, with the same participation - provider or consumer
157      * @param direction rules matching corresponding direction will be collected
158      * @return resolved ACE entries
159      */
160
161     static @Nonnull String resolveAceName(@Nonnull RuleName ruleName, @Nonnull RendererEndpointKey key,
162             @Nonnull PeerEndpointKey peer) {
163         return ruleName.getValue() + "_" + key.getAddress() + "_" + peer.getAddress();
164     }
165
166     private static List<GbpAceBuilder> resolveAclRulesFromPolicy(RendererResolvedPolicy resolvedPolicy,
167             Direction direction, RendererEndpointKey r, PeerEndpointKey p) {
168         List<GbpAceBuilder> aclRules = new ArrayList<>();
169         for (ResolvedRule resolvedRule : resolvedPolicy.getRuleGroup().getRules()) {
170             Optional<GbpAceBuilder> resolveAce = resolveAceClassifersAndAction(resolvedRule, direction,
171                     resolveAceName(resolvedRule.getName(), r, p));
172             if (resolveAce.isPresent()) {
173                 aclRules.add(resolveAce.get());
174             }
175         }
176         return aclRules;
177     }
178
179     public static Optional<GbpAceBuilder> resolveAceClassifersAndAction(ResolvedRule resolvedRule, Direction direction,
180             String ruleName) {
181         Map<String, ParameterValue> params = resolveClassifParamsForDir(direction, resolvedRule.getClassifier());
182         if (params.isEmpty()) {
183             return Optional.absent();
184         }
185         org.opendaylight.groupbasedpolicy.renderer.vpp.sf.Classifier classif =
186                 resolveImplementedClassifForDir(direction, resolvedRule.getClassifier());
187         GbpAceBuilder aclRuleBuilder = new GbpAceBuilder(ruleName);
188         // new GbpAceBuilder(resolvedRule.getName().getValue() + UNDERSCORE + namePasphrase);
189         boolean updated = classif != null && classif.updateMatch(aclRuleBuilder, params);
190         Optional<Actions> optAction = resolveActions(resolvedRule.getAction());
191         if (!optAction.isPresent() || !updated) {
192             LOG.error("Failed to process rule {}. Resolved parameters {}, resolved classifier. Actions resolved: {}"
193                     + "{}.", resolvedRule.getName().getValue(), params, classif, optAction.isPresent());
194             return Optional.absent();
195         }
196         aclRuleBuilder.setAction(optAction.get());
197         return Optional.of(aclRuleBuilder);
198     }
199
200     private static org.opendaylight.groupbasedpolicy.renderer.vpp.sf.Classifier resolveImplementedClassifForDir(
201             @Nonnull Direction direction, @Nonnull List<Classifier> classifiers) {
202         org.opendaylight.groupbasedpolicy.renderer.vpp.sf.Classifier feasibleClassifier = null;
203         for (Classifier cl : classifiers) {
204             if (direction.equals(cl.getDirection()) || direction.equals(Direction.Bidirectional)) {
205                 org.opendaylight.groupbasedpolicy.renderer.vpp.sf.Classifier classif =
206                         SubjectFeatures.getClassifier(cl.getClassifierDefinitionId());
207                 if (feasibleClassifier == null) {
208                     feasibleClassifier = classif;
209                 }
210                 if (classif.getParent() != null && classif.getParent().equals(feasibleClassifier)) {
211                     feasibleClassifier = classif;
212                 }
213             }
214         }
215         return feasibleClassifier;
216     }
217
218     private static Map<String, ParameterValue> resolveClassifParamsForDir(Direction direction,
219             List<Classifier> classifier) {
220         Map<String, ParameterValue> params = new HashMap<>();
221         classifier.stream()
222             .filter(classif -> direction.equals(classif.getDirection()) || direction.equals(Direction.Bidirectional))
223             .forEach(classif -> {
224                 classif.getParameterValue()
225                     .stream()
226                     .filter(v -> params.get(v.getName().getValue()) == null) // not unique
227                     .filter(v -> v.getIntValue() != null || v.getStringValue() != null || v.getRangeValue() != null)
228                     .forEach(v -> params.put(v.getName().getValue(), v));
229             });
230         return params;
231     }
232
233     private static Optional<Actions> resolveActions(List<Action> actions) {
234         for (Action action : actions) {
235             if (AllowActionDefinition.ID.equals(action.getActionDefinitionId())) {
236                 return Optional
237                     .of(new ActionsBuilder().setPacketHandling(new PermitBuilder().setPermit(true).build()).build());
238             }
239         }
240         return Optional.absent();
241     }
242
243     /*
244      * so far any traffic heading to/from outside of managed domain is permitted for demonstration
245      * purposes
246      * TODO initial workaround for external networking
247      */
248     static GbpAceBuilder allowExternalNetworksForEp(@Nonnull RendererEndpointKey rendEp,
249             AccessListUtil.ACE_DIRECTION dir) {
250         InetAddress byName;
251         try {
252             byName = InetAddress.getByName(substringBeforeSlash(rendEp.getAddress()));
253         } catch (UnknownHostException e) {
254             LOG.error("Failed to parse IP address {}", e);
255             return null;
256         }
257         if (byName instanceof Inet4Address) {
258             if (AccessListUtil.ACE_DIRECTION.INGRESS.equals(dir)) {
259                 return new GbpAceBuilder(PERMIT_EXTERNAL_INGRESS)
260                     .setIpAddresses(new Ipv4Prefix(rendEp.getAddress()), null).setPermit();
261             } else {
262                 return new GbpAceBuilder(PERMIT_EXTERNAL_EGRESS)
263                     .setIpAddresses(null, new Ipv4Prefix(rendEp.getAddress())).setPermit();
264             }
265         } else if (byName instanceof Inet6Address) {
266             if (AccessListUtil.ACE_DIRECTION.INGRESS.equals(dir)) {
267                 new GbpAceBuilder(PERMIT_EXTERNAL_INGRESS).setIpAddresses(new Ipv6Prefix(rendEp.getAddress()), null)
268                     .setPermit();
269             } else {
270                 new GbpAceBuilder(PERMIT_EXTERNAL_EGRESS).setIpAddresses(null, new Ipv6Prefix(rendEp.getAddress()))
271                     .setPermit();
272             }
273         }
274         return null;
275     }
276
277     /**
278      * Helps stripping address part of a CIDR
279      */
280     private static String substringBeforeSlash(String address) {
281         return (address.contains("/") && address.split("/").length > 0) ? address.split("/")[0] : address;
282     }
283
284     static List<GbpAceBuilder> denyDomainSubnets(@Nonnull PolicyContext ctx, @Nonnull ACE_DIRECTION policyDirection) {
285         List<GbpAceBuilder> aclRuleBuilders = new ArrayList<>();
286         for (RendererForwardingByTenant rf : ctx.getPolicy()
287             .getConfiguration()
288             .getRendererForwarding()
289             .getRendererForwardingByTenant()) {
290             rf.getRendererNetworkDomain()
291                 .stream()
292                 .filter(rnd -> org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.forwarding.l2_l3.rev170511.Subnet.class
293                     .equals(rnd.getNetworkDomainType()))
294                 .forEach(rnd -> {
295                     SubnetAugmentRenderer subnetAug = rnd.getAugmentation(SubnetAugmentRenderer.class);
296                     // subnetAug should not be null
297                     subnetAug.getSubnet();
298                     if (policyDirection.equals(ACE_DIRECTION.INGRESS) && subnetAug.getSubnet().isIsTenant()) {
299                         aclRuleBuilders.add(denyIngressTrafficForPrefix(subnetAug.getSubnet()));
300                     } else if (subnetAug.getSubnet().isIsTenant()) {
301                         aclRuleBuilders.add(denyEgressTrafficForPrefix(subnetAug.getSubnet()));
302                     }
303                 });
304         }
305         return aclRuleBuilders;
306     }
307
308     private static GbpAceBuilder denyEgressTrafficForPrefix(Subnet subnet) {
309         IpPrefix ipPrefix = subnet.getIpPrefix();
310         if (ipPrefix.getIpv4Prefix() != null) {
311             return new GbpAceBuilder(DENY_EGRESS_IPV4 + UNDERSCORE + String.valueOf(ipPrefix.getValue()))
312                 .setIpAddresses(ipPrefix.getIpv4Prefix(), null).setDeny();
313         } else if (ipPrefix.getIpv6Prefix() != null) {
314             return new GbpAceBuilder(DENY_EGRESS_IPV6 + UNDERSCORE + String.valueOf(ipPrefix.getValue()))
315                 .setIpAddresses(ipPrefix.getIpv6Prefix(), null).setDeny();
316         }
317         throw new IllegalStateException("Unknown prefix type " + subnet.getIpPrefix());
318     }
319
320     static void setSourceL3Address(GbpAceBuilder rule, String address) throws UnknownHostException {
321         InetAddress addr = InetAddress.getByName(substringBeforeSlash(address));
322         if (addr instanceof Inet6Address) {
323             rule.setIpAddresses(new Ipv6Prefix(address), null);
324         } else {
325             rule.setIpAddresses(new Ipv4Prefix(address), null);
326         }
327     }
328
329     static void setDestinationL3Address(GbpAceBuilder rule, String address) throws UnknownHostException {
330         InetAddress addr = InetAddress.getByName(substringBeforeSlash(address));
331         if (addr instanceof Inet6Address) {
332             rule.setIpAddresses(null, new Ipv6Prefix(address));
333         } else {
334             rule.setIpAddresses(null, new Ipv4Prefix(address));
335         }
336     }
337
338     static GbpAceBuilder denyIngressTrafficForPrefix(Subnet subnet) {
339         IpPrefix ipPrefix = subnet.getIpPrefix();
340         if (ipPrefix.getIpv4Prefix() != null) {
341             return new GbpAceBuilder(DENY_INGRESS_IPV4 + UNDERSCORE + String.valueOf(ipPrefix.getValue()))
342                 .setIpAddresses(null, ipPrefix.getIpv4Prefix()).setDeny();
343         } else if (ipPrefix.getIpv6Prefix() != null) {
344             return new GbpAceBuilder(DENY_INGRESS_IPV6 + UNDERSCORE + String.valueOf(ipPrefix.getValue()))
345                 .setIpAddresses(null, ipPrefix.getIpv6Prefix()).setDeny();
346         }
347         throw new IllegalStateException("Unknown prefix type " + subnet.getIpPrefix());
348     }
349 }