17b5c6be57a6d13a757e3625dc828019873600c5
[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 java.io.IOException;
12 import java.net.InetSocketAddress;
13 import java.net.SocketAddress;
14 import java.security.GeneralSecurityException;
15 import java.security.PublicKey;
16 import java.util.Collection;
17 import java.util.concurrent.ConcurrentHashMap;
18 import java.util.concurrent.ConcurrentMap;
19 import org.opendaylight.mdsal.binding.api.DataBroker;
20 import org.opendaylight.mdsal.binding.api.DataObjectModification;
21 import org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType;
22 import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
23 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
24 import org.opendaylight.mdsal.binding.api.DataTreeModification;
25 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
26 import org.opendaylight.netconf.callhome.protocol.AuthorizedKeysDecoder;
27 import org.opendaylight.netconf.callhome.protocol.CallHomeAuthorization;
28 import org.opendaylight.netconf.callhome.protocol.CallHomeAuthorization.Builder;
29 import org.opendaylight.netconf.callhome.protocol.CallHomeAuthorizationProvider;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev161109.NetconfCallhomeServer;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev161109.credentials.Credentials;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev161109.netconf.callhome.server.AllowedDevices;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev161109.netconf.callhome.server.Global;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev161109.netconf.callhome.server.Global.MountPointNamingStrategy;
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 String fromRemoteAddress(final SocketAddress remoteAddress) {
120         if (remoteAddress instanceof InetSocketAddress) {
121             InetSocketAddress socketAddress = (InetSocketAddress) remoteAddress;
122             String ip = socketAddress.getAddress().getHostAddress();
123
124             final MountPointNamingStrategy strat = globalConfig.getMountPointNamingStrategy();
125             switch (strat) {
126                 case IPONLY:
127                     return ip;
128                 case IPPORT:
129                     return ip + ":" + socketAddress.getPort();
130                 default:
131                     throw new IllegalStateException("Unhandled naming strategy " + strat);
132             }
133         }
134         return remoteAddress.toString();
135     }
136
137     private abstract static class AbstractDeviceListener implements DataTreeChangeListener<Device> {
138
139         @Override
140         public final void onDataTreeChanged(final Collection<DataTreeModification<Device>> mods) {
141             for (DataTreeModification<Device> dataTreeModification : mods) {
142                 final DataObjectModification<Device> deviceMod = dataTreeModification.getRootNode();
143                 final ModificationType modType = deviceMod.getModificationType();
144                 switch (modType) {
145                     case DELETE:
146                         deleteDevice(deviceMod.getDataBefore());
147                         break;
148                     case SUBTREE_MODIFIED:
149                     case WRITE:
150                         deleteDevice(deviceMod.getDataBefore());
151                         writeDevice(deviceMod.getDataAfter());
152                         break;
153                     default:
154                         throw new IllegalStateException("Unhandled modification type " + modType);
155                 }
156             }
157         }
158
159         private void deleteDevice(final Device dataBefore) {
160             if (dataBefore != null) {
161                 final String publicKey = dataBefore.getSshHostKey();
162                 if (publicKey != null) {
163                     LOG.debug("Removing device {}", dataBefore.getUniqueId());
164                     removeDevice(publicKey, dataBefore);
165                 } else {
166                     LOG.debug("Ignoring removal of device {}, no host key present", dataBefore.getUniqueId());
167                 }
168             }
169         }
170
171         private void writeDevice(final Device dataAfter) {
172             final String publicKey = dataAfter.getSshHostKey();
173             if (publicKey != null) {
174                 LOG.debug("Adding device {}", dataAfter.getUniqueId());
175                 addDevice(publicKey, dataAfter);
176             } else {
177                 LOG.debug("Ignoring addition of device {}, no host key present", dataAfter.getUniqueId());
178             }
179         }
180
181         abstract void addDevice(String publicKey, Device device);
182
183         abstract void removeDevice(String publicKey, Device device);
184     }
185
186     private static class DeviceConfig extends AbstractDeviceListener {
187         private final ConcurrentMap<PublicKey, Device> byPublicKey = new ConcurrentHashMap<>();
188         private final AuthorizedKeysDecoder keyDecoder = new AuthorizedKeysDecoder();
189
190         Device get(final PublicKey key) {
191             return byPublicKey.get(key);
192         }
193
194         @Override
195         void addDevice(final String publicKey, final Device device) {
196             final PublicKey key = publicKey(publicKey, device);
197             if (key != null) {
198                 byPublicKey.put(key, device);
199             }
200         }
201
202         @Override
203         void removeDevice(final String publicKey, final Device device) {
204             final PublicKey key = publicKey(publicKey, device);
205             if (key != null) {
206                 byPublicKey.remove(key);
207             }
208         }
209
210         private PublicKey publicKey(final String hostKey, final Device device) {
211             try {
212                 return keyDecoder.decodePublicKey(hostKey);
213             } catch (GeneralSecurityException e) {
214                 LOG.error("Unable to decode SSH key for {}. Ignoring update for this device", device.getUniqueId(), e);
215                 return null;
216             }
217         }
218     }
219
220     private static class DeviceOp extends AbstractDeviceListener {
221         private final ConcurrentMap<String, Device> byPublicKey = new ConcurrentHashMap<>();
222
223         Device get(final PublicKey serverKey) {
224             final String skey;
225             try {
226                 skey = AuthorizedKeysDecoder.encodePublicKey(serverKey);
227             } catch (IOException | IllegalArgumentException e) {
228                 LOG.error("Unable to encode server key: {}", serverKey, e);
229                 return null;
230             }
231
232             return byPublicKey.get(skey);
233         }
234
235         @Override
236         void removeDevice(final String publicKey, final Device device) {
237             byPublicKey.remove(publicKey);
238         }
239
240         @Override
241         void addDevice(final String publicKey, final Device device) {
242             byPublicKey.put(publicKey, device);
243         }
244     }
245
246     private static class GlobalConfig implements DataTreeChangeListener<Global> {
247         private volatile Global current = null;
248
249         @Override
250         public void onDataTreeChanged(final Collection<DataTreeModification<Global>> mods) {
251             if (!mods.isEmpty()) {
252                 current = Iterables.getLast(mods).getRootNode().getDataAfter();
253             }
254         }
255
256         boolean allowedUnknownKeys() {
257             final Global local = current;
258             // Deal with null values.
259             return local != null && Boolean.TRUE.equals(local.isAcceptAllSshKeys());
260         }
261
262         Credentials getCredentials() {
263             final Global local = current;
264             return local != null ? local.getCredentials() : null;
265         }
266
267         MountPointNamingStrategy getMountPointNamingStrategy() {
268             final Global local = current;
269             final MountPointNamingStrategy strat = local != null ? local.getMountPointNamingStrategy() : null;
270             return strat == null ? MountPointNamingStrategy.IPPORT : strat;
271         }
272     }
273 }