Improve global config application
[netconf.git] / netconf / callhome-provider / src / main / java / org / opendaylight / netconf / callhome / mount / CallHomeAuthProviderImpl.java
1 /*
2  * Copyright (c) 2016 Brocade Communication Systems 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 package org.opendaylight.netconf.callhome.mount;
9
10 import com.google.common.collect.Iterables;
11 import com.google.common.net.InetAddresses;
12 import java.io.IOException;
13 import java.net.InetSocketAddress;
14 import java.net.SocketAddress;
15 import java.security.GeneralSecurityException;
16 import java.security.PublicKey;
17 import java.util.Collection;
18 import java.util.concurrent.ConcurrentHashMap;
19 import java.util.concurrent.ConcurrentMap;
20 import org.opendaylight.mdsal.binding.api.DataBroker;
21 import org.opendaylight.mdsal.binding.api.DataObjectModification;
22 import org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType;
23 import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
24 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
25 import org.opendaylight.mdsal.binding.api.DataTreeModification;
26 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
27 import org.opendaylight.netconf.callhome.protocol.AuthorizedKeysDecoder;
28 import org.opendaylight.netconf.callhome.protocol.CallHomeAuthorization;
29 import org.opendaylight.netconf.callhome.protocol.CallHomeAuthorization.Builder;
30 import org.opendaylight.netconf.callhome.protocol.CallHomeAuthorizationProvider;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev161109.NetconfCallhomeServer;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev161109.credentials.Credentials;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev161109.netconf.callhome.server.AllowedDevices;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev161109.netconf.callhome.server.Global;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev161109.netconf.callhome.server.allowed.devices.Device;
36 import org.opendaylight.yangtools.concepts.ListenerRegistration;
37 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 public class CallHomeAuthProviderImpl implements CallHomeAuthorizationProvider, AutoCloseable {
42
43     private static final Logger LOG = LoggerFactory.getLogger(CallHomeAuthProviderImpl.class);
44     private static final InstanceIdentifier<Global> GLOBAL_PATH =
45             InstanceIdentifier.create(NetconfCallhomeServer.class).child(Global.class);
46     private static final DataTreeIdentifier<Global> GLOBAL =
47             DataTreeIdentifier.create(LogicalDatastoreType.CONFIGURATION, GLOBAL_PATH);
48
49     private static final InstanceIdentifier<Device> ALLOWED_DEVICES_PATH =
50             InstanceIdentifier.create(NetconfCallhomeServer.class).child(AllowedDevices.class).child(Device.class);
51     private static final DataTreeIdentifier<Device> ALLOWED_DEVICES =
52             DataTreeIdentifier.create(LogicalDatastoreType.CONFIGURATION, ALLOWED_DEVICES_PATH);
53     private static final DataTreeIdentifier<Device> ALLOWED_OP_DEVICES =
54             DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, ALLOWED_DEVICES_PATH);
55
56     private final GlobalConfig globalConfig = new GlobalConfig();
57     private final DeviceConfig deviceConfig = new DeviceConfig();
58     private final DeviceOp deviceOp = new DeviceOp();
59     private final ListenerRegistration<GlobalConfig> configReg;
60     private final ListenerRegistration<DeviceConfig> deviceReg;
61     private final ListenerRegistration<DeviceOp> deviceOpReg;
62
63     private final CallhomeStatusReporter statusReporter;
64
65     CallHomeAuthProviderImpl(final DataBroker broker) {
66         configReg = broker.registerDataTreeChangeListener(GLOBAL, globalConfig);
67         deviceReg = broker.registerDataTreeChangeListener(ALLOWED_DEVICES, deviceConfig);
68         deviceOpReg = broker.registerDataTreeChangeListener(ALLOWED_OP_DEVICES, deviceOp);
69         statusReporter = new CallhomeStatusReporter(broker);
70     }
71
72     @Override
73     public CallHomeAuthorization provideAuth(final SocketAddress remoteAddress, final PublicKey serverKey) {
74         Device deviceSpecific = deviceConfig.get(serverKey);
75         String sessionName;
76         Credentials deviceCred;
77
78         if (deviceSpecific != null) {
79             sessionName = deviceSpecific.getUniqueId();
80             deviceCred = deviceSpecific.getCredentials();
81         } else {
82             String syntheticId = fromRemoteAddress(remoteAddress);
83             if (globalConfig.allowedUnknownKeys()) {
84                 sessionName = syntheticId;
85                 deviceCred = null;
86                 statusReporter.asForceListedDevice(syntheticId, serverKey);
87             } else {
88                 Device opDevice = deviceOp.get(serverKey);
89                 if (opDevice == null) {
90                     statusReporter.asUnlistedDevice(syntheticId, serverKey);
91                 } else {
92                     LOG.info("Repeating rejection of unlisted device with id of {}", opDevice.getUniqueId());
93                 }
94                 return CallHomeAuthorization.rejected();
95             }
96         }
97
98         final Credentials credentials = deviceCred != null ? deviceCred : globalConfig.getCredentials();
99
100         if (credentials == null) {
101             LOG.info("No credentials found for {}, rejecting.", remoteAddress);
102             return CallHomeAuthorization.rejected();
103         }
104
105         Builder authBuilder = CallHomeAuthorization.serverAccepted(sessionName, credentials.getUsername());
106         for (String password : credentials.getPasswords()) {
107             authBuilder.addPassword(password);
108         }
109         return authBuilder.build();
110     }
111
112     @Override
113     public void close() {
114         configReg.close();
115         deviceReg.close();
116         deviceOpReg.close();
117     }
118
119     private static String fromRemoteAddress(final SocketAddress remoteAddress) {
120         if (remoteAddress instanceof InetSocketAddress) {
121             InetSocketAddress socketAddress = (InetSocketAddress) remoteAddress;
122             return InetAddresses.toAddrString(socketAddress.getAddress()) + ":" + socketAddress.getPort();
123         }
124         return remoteAddress.toString();
125     }
126
127     private abstract static class AbstractDeviceListener implements DataTreeChangeListener<Device> {
128
129         @Override
130         public final void onDataTreeChanged(final Collection<DataTreeModification<Device>> mods) {
131             for (DataTreeModification<Device> dataTreeModification : mods) {
132                 final DataObjectModification<Device> deviceMod = dataTreeModification.getRootNode();
133                 final ModificationType modType = deviceMod.getModificationType();
134                 switch (modType) {
135                     case DELETE:
136                         deleteDevice(deviceMod.getDataBefore());
137                         break;
138                     case SUBTREE_MODIFIED:
139                     case WRITE:
140                         deleteDevice(deviceMod.getDataBefore());
141                         writeDevice(deviceMod.getDataAfter());
142                         break;
143                     default:
144                         throw new IllegalStateException("Unhandled modification type " + modType);
145                 }
146             }
147         }
148
149         private void deleteDevice(final Device dataBefore) {
150             if (dataBefore != null) {
151                 final String publicKey = dataBefore.getSshHostKey();
152                 if (publicKey != null) {
153                     LOG.debug("Removing device {}", dataBefore.getUniqueId());
154                     removeDevice(publicKey, dataBefore);
155                 } else {
156                     LOG.debug("Ignoring removal of device {}, no host key present", dataBefore.getUniqueId());
157                 }
158             }
159         }
160
161         private void writeDevice(final Device dataAfter) {
162             final String publicKey = dataAfter.getSshHostKey();
163             if (publicKey != null) {
164                 LOG.debug("Adding device {}", dataAfter.getUniqueId());
165                 addDevice(publicKey, dataAfter);
166             } else {
167                 LOG.debug("Ignoring addition of device {}, no host key present", dataAfter.getUniqueId());
168             }
169         }
170
171         abstract void addDevice(String publicKey, Device device);
172
173         abstract void removeDevice(String publicKey, Device device);
174     }
175
176     private static class DeviceConfig extends AbstractDeviceListener {
177         private final ConcurrentMap<PublicKey, Device> byPublicKey = new ConcurrentHashMap<>();
178         private final AuthorizedKeysDecoder keyDecoder = new AuthorizedKeysDecoder();
179
180         Device get(final PublicKey key) {
181             return byPublicKey.get(key);
182         }
183
184         @Override
185         void addDevice(final String publicKey, final Device device) {
186             final PublicKey key = publicKey(publicKey, device);
187             if (key != null) {
188                 byPublicKey.put(key, device);
189             }
190         }
191
192         @Override
193         void removeDevice(final String publicKey, final Device device) {
194             final PublicKey key = publicKey(publicKey, device);
195             if (key != null) {
196                 byPublicKey.remove(key);
197             }
198         }
199
200         private PublicKey publicKey(final String hostKey, final Device device) {
201             try {
202                 return keyDecoder.decodePublicKey(hostKey);
203             } catch (GeneralSecurityException e) {
204                 LOG.error("Unable to decode SSH key for {}. Ignoring update for this device", device.getUniqueId(), e);
205                 return null;
206             }
207         }
208     }
209
210     private static class DeviceOp extends AbstractDeviceListener {
211         private final ConcurrentMap<String, Device> byPublicKey = new ConcurrentHashMap<>();
212
213         Device get(final PublicKey serverKey) {
214             final String skey;
215             try {
216                 skey = AuthorizedKeysDecoder.encodePublicKey(serverKey);
217             } catch (IOException | IllegalArgumentException e) {
218                 LOG.error("Unable to encode server key: {}", serverKey, e);
219                 return null;
220             }
221
222             return byPublicKey.get(skey);
223         }
224
225         @Override
226         void removeDevice(final String publicKey, final Device device) {
227             byPublicKey.remove(publicKey);
228         }
229
230         @Override
231         void addDevice(final String publicKey, final Device device) {
232             byPublicKey.put(publicKey, device);
233         }
234     }
235
236     private static class GlobalConfig implements DataTreeChangeListener<Global> {
237         private volatile Global current = null;
238
239         @Override
240         public void onDataTreeChanged(final Collection<DataTreeModification<Global>> mods) {
241             if (!mods.isEmpty()) {
242                 current = Iterables.getLast(mods).getRootNode().getDataAfter();
243             }
244         }
245
246         boolean allowedUnknownKeys() {
247             final Global local = current;
248             // Deal with null values.
249             return local != null && Boolean.TRUE.equals(local.isAcceptAllSshKeys());
250         }
251
252         Credentials getCredentials() {
253             final Global local = current;
254             return local != null ? local.getCredentials() : null;
255         }
256     }
257 }