0bd92411cbf81dbde44e56f4db582d4ff459e1c3
[netconf.git] / apps / callhome-provider / src / main / java / org / opendaylight / netconf / callhome / mount / CallHomeMountSshAuthProvider.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 java.io.IOException;
11 import java.net.InetSocketAddress;
12 import java.net.SocketAddress;
13 import java.security.GeneralSecurityException;
14 import java.security.PublicKey;
15 import java.util.List;
16 import java.util.Set;
17 import java.util.concurrent.ConcurrentHashMap;
18 import java.util.concurrent.ConcurrentMap;
19 import javax.inject.Inject;
20 import javax.inject.Singleton;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.opendaylight.mdsal.binding.api.DataBroker;
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.server.ssh.CallHomeSshAuthProvider;
28 import org.opendaylight.netconf.callhome.server.ssh.CallHomeSshAuthSettings;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.NetconfCallhomeServer;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.SshPublicKey;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.credentials.Credentials;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.netconf.callhome.server.AllowedDevices;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.netconf.callhome.server.Global;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.netconf.callhome.server.Global.MountPointNamingStrategy;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.netconf.callhome.server.allowed.devices.Device;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.netconf.callhome.server.allowed.devices.device.transport.Ssh;
37 import org.opendaylight.yangtools.concepts.Registration;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
39 import org.osgi.service.component.annotations.Activate;
40 import org.osgi.service.component.annotations.Component;
41 import org.osgi.service.component.annotations.Reference;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 @Component(service = CallHomeSshAuthProvider.class, immediate = true)
46 @Singleton
47 public final class CallHomeMountSshAuthProvider implements CallHomeSshAuthProvider, AutoCloseable {
48     private static final Logger LOG = LoggerFactory.getLogger(CallHomeMountSshAuthProvider.class);
49
50     private final GlobalConfig globalConfig = new GlobalConfig();
51     private final DeviceConfig deviceConfig = new DeviceConfig();
52     private final DeviceOp deviceOp = new DeviceOp();
53     private final Registration configReg;
54     private final Registration deviceReg;
55     private final Registration deviceOpReg;
56
57     private final CallHomeMountStatusReporter statusReporter;
58
59     @Activate
60     @Inject
61     public CallHomeMountSshAuthProvider(final @Reference DataBroker broker,
62             final @Reference CallHomeMountStatusReporter statusReporter) {
63         configReg = broker.registerDataTreeChangeListener(
64             DataTreeIdentifier.of(LogicalDatastoreType.CONFIGURATION,
65                 InstanceIdentifier.create(NetconfCallhomeServer.class).child(Global.class)),
66             globalConfig);
67
68         final var allowedDeviceWildcard =
69             InstanceIdentifier.create(NetconfCallhomeServer.class).child(AllowedDevices.class).child(Device.class);
70
71         deviceReg = broker.registerDataTreeChangeListener(
72             DataTreeIdentifier.of(LogicalDatastoreType.CONFIGURATION, allowedDeviceWildcard),
73             deviceConfig);
74         deviceOpReg = broker.registerDataTreeChangeListener(
75             DataTreeIdentifier.of(LogicalDatastoreType.OPERATIONAL, allowedDeviceWildcard),
76             deviceOp);
77
78         this.statusReporter = statusReporter;
79     }
80
81     @Override
82     public CallHomeSshAuthSettings provideAuth(final SocketAddress remoteAddress, final PublicKey serverKey) {
83         final String id;
84         final Credentials deviceCred;
85
86         final var deviceSpecific = deviceConfig.get(serverKey);
87         if (deviceSpecific != null) {
88             id = deviceSpecific.getUniqueId();
89             deviceCred = deviceSpecific.getTransport() instanceof Ssh ssh ? ssh.getSshClientParams().getCredentials()
90                 : null;
91         } else {
92             String syntheticId = fromRemoteAddress(remoteAddress);
93             if (globalConfig.allowedUnknownKeys()) {
94                 id = syntheticId;
95                 deviceCred = null;
96                 statusReporter.reportNewSshDevice(syntheticId, serverKey, Device.DeviceStatus.DISCONNECTED);
97             } else {
98                 Device opDevice = deviceOp.get(serverKey);
99                 if (opDevice == null) {
100                     statusReporter.reportNewSshDevice(syntheticId, serverKey, Device.DeviceStatus.FAILEDNOTALLOWED);
101                 } else {
102                     LOG.info("Repeating rejection of unlisted device with id of {}", opDevice.getUniqueId());
103                 }
104                 return null;
105             }
106         }
107
108         final var credentials = deviceCred != null ? deviceCred : globalConfig.getCredentials();
109         if (credentials == null) {
110             LOG.info("No credentials found for {}, rejecting.", id);
111             return null;
112         }
113
114         return new CallHomeSshAuthSettings.DefaultAuthSettings(id, credentials.getUsername(),
115             Set.copyOf(credentials.getPasswords()), null);
116     }
117
118     @Override
119     public void close() {
120         configReg.close();
121         deviceReg.close();
122         deviceOpReg.close();
123     }
124
125     private String fromRemoteAddress(final SocketAddress remoteAddress) {
126         if (remoteAddress instanceof InetSocketAddress socketAddress) {
127             final var hostAddress = socketAddress.getAddress().getHostAddress();
128             return switch (globalConfig.getMountPointNamingStrategy()) {
129                 case IPONLY -> hostAddress;
130                 case IPPORT -> hostAddress + ":" + socketAddress.getPort();
131             };
132         }
133         return remoteAddress.toString();
134     }
135
136     private abstract static class AbstractDeviceListener implements DataTreeChangeListener<Device> {
137
138         @Override
139         public final void onDataTreeChanged(final List<DataTreeModification<Device>> mods) {
140             for (var dataTreeModification : mods) {
141                 final var deviceMod = dataTreeModification.getRootNode();
142                 final var modType = deviceMod.modificationType();
143                 switch (modType) {
144                     case DELETE:
145                         deleteDevice(deviceMod.dataBefore());
146                         break;
147                     case SUBTREE_MODIFIED:
148                     case WRITE:
149                         deleteDevice(deviceMod.dataBefore());
150                         writeDevice(deviceMod.dataAfter());
151                         break;
152                     default:
153                         throw new IllegalStateException("Unhandled modification type " + modType);
154                 }
155             }
156         }
157
158         private void deleteDevice(final Device dataBefore) {
159             if (dataBefore != null) {
160                 if (dataBefore.getTransport() instanceof Ssh ssh) {
161                     LOG.debug("Removing device {}", dataBefore.getUniqueId());
162                     removeDevice(ssh.nonnullSshClientParams().requireHostKey(), dataBefore);
163                 } else {
164                     LOG.debug("Ignoring removal of device {}, no host key present", dataBefore.getUniqueId());
165                 }
166             }
167         }
168
169         private void writeDevice(final Device dataAfter) {
170             if (dataAfter.getTransport() instanceof Ssh ssh) {
171                 LOG.debug("Adding device {}", dataAfter.getUniqueId());
172                 addDevice(ssh.nonnullSshClientParams().requireHostKey(), dataAfter);
173             } else {
174                 LOG.debug("Ignoring addition of device {}, no host key present", dataAfter.getUniqueId());
175             }
176         }
177
178         abstract void addDevice(SshPublicKey publicKey, Device device);
179
180         abstract void removeDevice(SshPublicKey publicKey, Device device);
181     }
182
183     private static final class DeviceConfig extends AbstractDeviceListener {
184         private final ConcurrentMap<PublicKey, Device> byPublicKey = new ConcurrentHashMap<>();
185         private final AuthorizedKeysDecoder keyDecoder = new AuthorizedKeysDecoder();
186
187         Device get(final PublicKey key) {
188             return byPublicKey.get(key);
189         }
190
191         @Override
192         void addDevice(final SshPublicKey publicKey, final Device device) {
193             final PublicKey key = publicKey(publicKey, device);
194             if (key != null) {
195                 byPublicKey.put(key, device);
196             }
197         }
198
199         @Override
200         void removeDevice(final SshPublicKey publicKey, final Device device) {
201             final PublicKey key = publicKey(publicKey, device);
202             if (key != null) {
203                 byPublicKey.remove(key);
204             }
205         }
206
207         private PublicKey publicKey(final SshPublicKey hostKey, final Device device) {
208             try {
209                 return keyDecoder.decodePublicKey(hostKey);
210             } catch (GeneralSecurityException e) {
211                 LOG.error("Unable to decode SSH key for {}. Ignoring update for this device", device.getUniqueId(), e);
212                 return null;
213             }
214         }
215     }
216
217     private static final class DeviceOp extends AbstractDeviceListener {
218         private final ConcurrentMap<SshPublicKey, Device> byPublicKey = new ConcurrentHashMap<>();
219
220         Device get(final PublicKey serverKey) {
221             final SshPublicKey skey;
222             try {
223                 skey = AuthorizedKeysDecoder.encodePublicKey(serverKey);
224             } catch (IOException e) {
225                 LOG.error("Unable to encode server key: {}", serverKey, e);
226                 return null;
227             }
228
229             return byPublicKey.get(skey);
230         }
231
232         @Override
233         void removeDevice(final SshPublicKey publicKey, final Device device) {
234             byPublicKey.remove(publicKey);
235         }
236
237         @Override
238         void addDevice(final SshPublicKey publicKey, final Device device) {
239             byPublicKey.put(publicKey, device);
240         }
241     }
242
243     private static final class GlobalConfig implements DataTreeChangeListener<Global> {
244         private volatile Global current = null;
245
246         @Override
247         public void onDataTreeChanged(final List<DataTreeModification<Global>> mods) {
248             if (!mods.isEmpty()) {
249                 current = mods.get(mods.size() - 1).getRootNode().dataAfter();
250             }
251         }
252
253         boolean allowedUnknownKeys() {
254             final Global local = current;
255             // Deal with null values.
256             return local != null && Boolean.TRUE.equals(local.getAcceptAllSshKeys());
257         }
258
259         Credentials getCredentials() {
260             final Global local = current;
261             return local != null ? local.getCredentials() : null;
262         }
263
264         @NonNull MountPointNamingStrategy getMountPointNamingStrategy() {
265             final Global local = current;
266             final MountPointNamingStrategy strat = local != null ? local.getMountPointNamingStrategy() : null;
267             return strat == null ? MountPointNamingStrategy.IPPORT : strat;
268         }
269     }
270 }