blob: dd8355e95f0dc8ee497cb74eb01c7251a090fbe6 [file] [log] [blame]
Pengfei Lue0c02e22015-07-07 15:41:31 +08001/*
2 * Copyright 2015 Open Networking Laboratory
3 * Originally created by Pengfei Lu, Network and Cloud Computing Laboratory, Dalian University of Technology, China
4 * Advisers: Keqiu Li and Heng Qi
5 * This work is supported by the State Key Program of National Natural Science of China(Grant No. 61432002)
6 * and Prospective Research Project on Future Networks in Jiangsu Future Networks Innovation Institute.
7 *
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 */
20package org.onos.acl.impl;
21
22import org.onos.acl.AclRule;
23import org.onos.acl.AclService;
24import org.onos.acl.AclStore;
25import org.apache.felix.scr.annotations.Activate;
26import org.apache.felix.scr.annotations.Component;
27import org.apache.felix.scr.annotations.Deactivate;
28import org.apache.felix.scr.annotations.Reference;
29import org.apache.felix.scr.annotations.ReferenceCardinality;
30import org.apache.felix.scr.annotations.Service;
31import org.onlab.packet.Ethernet;
32import org.onlab.packet.IPv4;
33import org.onlab.packet.Ip4Address;
34import org.onlab.packet.Ip4Prefix;
35import org.onlab.packet.IpAddress;
36import org.onos.acl.RuleId;
37import org.onosproject.core.ApplicationId;
38import org.onosproject.core.CoreService;
39import org.onosproject.core.IdGenerator;
40import org.onosproject.mastership.MastershipService;
41import org.onosproject.net.DeviceId;
42import org.onosproject.net.Host;
43import org.onosproject.net.MastershipRole;
44import org.onosproject.net.PortNumber;
45import org.onosproject.net.flow.DefaultFlowEntry;
46import org.onosproject.net.flow.DefaultTrafficSelector;
47import org.onosproject.net.flow.DefaultTrafficTreatment;
48import org.onosproject.net.flow.FlowEntry;
49import org.onosproject.net.flow.FlowRule;
50import org.onosproject.net.flow.FlowRuleService;
51import org.onosproject.net.flow.TrafficSelector;
52import org.onosproject.net.flow.TrafficTreatment;
53import org.onosproject.net.flow.instructions.Instructions;
54import org.onosproject.net.host.HostEvent;
55import org.onosproject.net.host.HostListener;
56import org.onosproject.net.host.HostService;
57import org.slf4j.Logger;
58
59import java.util.HashSet;
60import java.util.List;
61import java.util.Set;
62
63import static org.slf4j.LoggerFactory.getLogger;
64
65/**
66 * Implementation of the ACL service.
67 */
68@Component(immediate = true)
69@Service
70public class AclManager implements AclService {
71
72 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
73 protected CoreService coreService;
74 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
75 protected FlowRuleService flowRuleService;
76 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
77 protected HostService hostService;
78 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
79 protected MastershipService mastershipService;
80
81 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
82 protected AclStore aclStore;
83
84 private final Logger log = getLogger(getClass());
85 private ApplicationId appId;
86 private final HostListener hostListener = new InternalHostListener();
87 private IdGenerator idGenerator;
88
89 /**
90 * Checks if the given IP address is in the given CIDR address.
91 */
92 private boolean checkIpInCIDR(Ip4Address ip, Ip4Prefix cidr) {
93 int offset = 32 - cidr.prefixLength();
94 int cidrPrefix = cidr.address().toInt();
95 int ipIntValue = ip.toInt();
96 cidrPrefix = cidrPrefix >> offset;
97 ipIntValue = ipIntValue >> offset;
98 cidrPrefix = cidrPrefix << offset;
99 ipIntValue = ipIntValue << offset;
100
101 return (cidrPrefix == ipIntValue);
102 }
103
104 private class InternalHostListener implements HostListener {
105
106 /**
107 * Generate new ACL flow rules for new host following the given ACL rule.
108 */
109 private void processHostAddedEvent(HostEvent event, AclRule rule) {
110 DeviceId deviceId = event.subject().location().deviceId();
111 for (IpAddress address : event.subject().ipAddresses()) {
112 if ((rule.srcIp() != null) ?
113 (checkIpInCIDR(address.getIp4Address(), rule.srcIp())) :
114 (checkIpInCIDR(address.getIp4Address(), rule.dstIp()))) {
115 if (!aclStore.checkIfRuleWorksInDevice(rule.id(), deviceId)) {
116 List<RuleId> allowingRuleList = aclStore
117 .getAllowingRuleByDenyingRule(rule.id());
118 if (allowingRuleList != null) {
119 for (RuleId allowingRuleId : allowingRuleList) {
120 generateACLFlow(aclStore.getAclRule(allowingRuleId), deviceId);
121 }
122 }
123 generateACLFlow(rule, deviceId);
124 }
125 }
126 }
127 }
128
129 @Override
130 public void event(HostEvent event) {
131 // if a new host appears and an existing rule denies
132 // its traffic, a new ACL flow rule is generated.
133 if (event.type() == HostEvent.Type.HOST_ADDED) {
134 DeviceId deviceId = event.subject().location().deviceId();
135 if (mastershipService.getLocalRole(deviceId) == MastershipRole.MASTER) {
136 for (AclRule rule : aclStore.getAclRules()) {
137 if (rule.action() != AclRule.Action.ALLOW) {
138 processHostAddedEvent(event, rule);
139 }
140 }
141 }
142 }
143 }
144 }
145
146 @Activate
147 public void activate() {
148 appId = coreService.registerApplication("org.onos.acl");
149 hostService.addListener(hostListener);
150 idGenerator = coreService.getIdGenerator("acl-ids");
151 AclRule.bindIdGenerator(idGenerator);
152 log.info("Started");
153 }
154
155 @Deactivate
156 public void deactivate() {
157 hostService.removeListener(hostListener);
158 flowRuleService.removeFlowRulesById(appId);
159 aclStore.clearAcl();
160 log.info("Stopped");
161 }
162
163 @Override
164 public List<AclRule> getAclRules() {
165 return aclStore.getAclRules();
166 }
167
168 /**
169 * Checks if the new ACL rule matches an existing rule.
170 * If existing allowing rules matches the new denying rule, store the mappings.
171 * @return true if the new ACL rule matches an existing rule, false otherwise
172 */
173 private boolean matchCheck(AclRule newRule) {
174 for (AclRule existingRule : aclStore.getAclRules()) {
175 if (newRule.checkMatch(existingRule)) {
176 return true;
177 }
178
179 if (existingRule.action() == AclRule.Action.ALLOW
180 && newRule.action() == AclRule.Action.DENY) {
181 if (existingRule.checkMatch(newRule)) {
182 aclStore.addDenyToAllowMapping(newRule.id(), existingRule.id());
183 }
184 }
185 }
186 return false;
187 }
188
189 @Override
190 public boolean addAclRule(AclRule rule) {
191 if (matchCheck(rule)) {
192 return false;
193 }
194 aclStore.addAclRule(rule);
195 log.info("ACL rule(id:{}) is added.", rule.id());
196 if (rule.action() != AclRule.Action.ALLOW) {
197 enforceRuleAdding(rule);
198 }
199 return true;
200 }
201
202 /**
203 * Gets a set containing all devices connecting with the hosts
204 * whose IP address is in the given CIDR IP address.
205 */
206 private Set<DeviceId> getDeviceIdSet(Ip4Prefix cidrAddr) {
207 Set<DeviceId> deviceIdSet = new HashSet<>();
208 final Iterable<Host> hosts = hostService.getHosts();
209
210 if (cidrAddr.prefixLength() != 32) {
211 for (Host h : hosts) {
212 for (IpAddress a : h.ipAddresses()) {
213 if (checkIpInCIDR(a.getIp4Address(), cidrAddr)) {
214 deviceIdSet.add(h.location().deviceId());
215 }
216 }
217 }
218 } else {
219 for (Host h : hosts) {
220 for (IpAddress a : h.ipAddresses()) {
221 if (checkIpInCIDR(a.getIp4Address(), cidrAddr)) {
222 deviceIdSet.add(h.location().deviceId());
223 return deviceIdSet;
224 }
225 }
226 }
227 }
228 return deviceIdSet;
229 }
230
231 /**
232 * Enforces denying ACL rule by ACL flow rules.
233 */
234 private void enforceRuleAdding(AclRule rule) {
235 Set<DeviceId> dpidSet;
236 if (rule.srcIp() != null) {
237 dpidSet = getDeviceIdSet(rule.srcIp());
238 } else {
239 dpidSet = getDeviceIdSet(rule.dstIp());
240 }
241
242 for (DeviceId deviceId : dpidSet) {
243 List<RuleId> allowingRuleList = aclStore.getAllowingRuleByDenyingRule(rule.id());
244 if (allowingRuleList != null) {
245 for (RuleId allowingRuleId : allowingRuleList) {
246 generateACLFlow(aclStore.getAclRule(allowingRuleId), deviceId);
247 }
248 }
249 generateACLFlow(rule, deviceId);
250 }
251 }
252
253 /**
254 * Generates ACL flow rule according to ACL rule
255 * and install it into related device.
256 */
257 private void generateACLFlow(AclRule rule, DeviceId deviceId) {
258 if (rule == null || aclStore.checkIfRuleWorksInDevice(rule.id(), deviceId)) {
259 return;
260 }
261
262 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
263 TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
264 FlowEntry.Builder flowEntry = DefaultFlowEntry.builder();
265
266 selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
267 if (rule.srcIp() != null) {
268 selectorBuilder.matchIPSrc(rule.srcIp());
269 if (rule.dstIp() != null) {
270 selectorBuilder.matchIPDst(rule.dstIp());
271 }
272 } else {
273 selectorBuilder.matchIPDst(rule.dstIp());
274 }
275 if (rule.ipProto() != 0) {
276 selectorBuilder.matchIPProtocol(Integer.valueOf(rule.ipProto()).byteValue());
277 }
278 if (rule.dstTpPort() != 0) {
279 switch (rule.ipProto()) {
280 case IPv4.PROTOCOL_TCP:
281 selectorBuilder.matchTcpDst(rule.dstTpPort());
282 break;
283 case IPv4.PROTOCOL_UDP:
284 selectorBuilder.matchUdpDst(rule.dstTpPort());
285 break;
286 default:
287 break;
288 }
289 }
290 if (rule.action() == AclRule.Action.ALLOW) {
291 treatment.add(Instructions.createOutput(PortNumber.CONTROLLER));
292 }
293 flowEntry.forDevice(deviceId);
294 flowEntry.withPriority(aclStore.getPriorityByDevice(deviceId));
295 flowEntry.withSelector(selectorBuilder.build());
296 flowEntry.withTreatment(treatment.build());
297 flowEntry.fromApp(appId);
298 flowEntry.makePermanent();
299 // install flow rule
300 flowRuleService.applyFlowRules(flowEntry.build());
301 log.debug("ACL flow rule {} is installed in {}.", flowEntry.build(), deviceId);
302 aclStore.addRuleToFlowMapping(rule.id(), flowEntry.build());
303 aclStore.addRuleToDeviceMapping(rule.id(), deviceId);
304 }
305
306 @Override
307 public void removeAclRule(RuleId ruleId) {
308 aclStore.removeAclRule(ruleId);
309 log.info("ACL rule(id:{}) is removed.", ruleId);
310 enforceRuleRemoving(ruleId);
311 }
312
313 /**
314 * Enforces removing an existing ACL rule.
315 */
316 private void enforceRuleRemoving(RuleId ruleId) {
317 Set<FlowRule> flowSet = aclStore.getFlowByRule(ruleId);
318 if (flowSet != null) {
319 for (FlowRule flowRule : flowSet) {
320 flowRuleService.removeFlowRules(flowRule);
321 log.debug("ACL flow rule {} is removed from {}.", flowRule.toString(), flowRule.deviceId().toString());
322 }
323 }
324 aclStore.removeRuleToFlowMapping(ruleId);
325 aclStore.removeRuleToDeviceMapping(ruleId);
326 aclStore.removeDenyToAllowMapping(ruleId);
327 }
328
329 @Override
330 public void clearAcl() {
331 aclStore.clearAcl();
332 flowRuleService.removeFlowRulesById(appId);
333 log.info("ACL is cleared.");
334 }
335
336}