Capture server key before returning from callback
[netconf.git] / netconf / callhome-protocol / src / main / java / org / opendaylight / netconf / callhome / protocol / NetconfCallHomeServer.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.protocol;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import java.io.IOException;
14 import java.net.InetSocketAddress;
15 import java.net.SocketAddress;
16 import java.security.PublicKey;
17 import org.apache.sshd.client.SshClient;
18 import org.apache.sshd.client.future.AuthFuture;
19 import org.apache.sshd.client.keyverifier.ServerKeyVerifier;
20 import org.apache.sshd.client.session.ClientSession;
21 import org.apache.sshd.client.session.SessionFactory;
22 import org.apache.sshd.common.future.SshFutureListener;
23 import org.apache.sshd.common.io.IoAcceptor;
24 import org.apache.sshd.common.io.IoServiceFactory;
25 import org.apache.sshd.common.session.Session;
26 import org.apache.sshd.common.session.SessionListener;
27 import org.apache.sshd.netty.NettyIoServiceFactory;
28 import org.opendaylight.netconf.callhome.protocol.CallHomeSessionContext.Factory;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 public class NetconfCallHomeServer implements AutoCloseable, ServerKeyVerifier {
33
34     private static final Logger LOG = LoggerFactory.getLogger(NetconfCallHomeServer.class);
35
36     private final CallHomeAuthorizationProvider authProvider;
37     private final IoServiceFactory serviceFactory;
38     private final InetSocketAddress bindAddress;
39     private final StatusRecorder recorder;
40     private final Factory sessionFactory;
41     private final IoAcceptor acceptor;
42     private final SshClient client;
43
44     NetconfCallHomeServer(final SshClient sshClient, final CallHomeAuthorizationProvider authProvider,
45             final Factory factory, final InetSocketAddress socketAddress, final StatusRecorder recorder) {
46         this(sshClient, authProvider, factory, socketAddress, recorder,
47             new NettyIoServiceFactory(factory.getNettyGroup()));
48     }
49
50     @VisibleForTesting
51     NetconfCallHomeServer(final SshClient sshClient, final CallHomeAuthorizationProvider authProvider,
52             final Factory factory, final InetSocketAddress socketAddress, final StatusRecorder recorder,
53             final IoServiceFactory serviceFactory) {
54         this.client = requireNonNull(sshClient);
55         this.authProvider = requireNonNull(authProvider);
56         this.sessionFactory = requireNonNull(factory);
57         this.bindAddress = socketAddress;
58         this.recorder = recorder;
59         this.serviceFactory = requireNonNull(serviceFactory);
60
61         sshClient.setServerKeyVerifier(this);
62         sshClient.addSessionListener(createSessionListener());
63
64         acceptor = serviceFactory.createAcceptor(new SessionFactory(sshClient));
65     }
66
67     @VisibleForTesting
68     SshClient getClient() {
69         return client;
70     }
71
72     SessionListener createSessionListener() {
73         return new SessionListener() {
74             @Override
75             public void sessionEvent(final Session session, final Event event) {
76                 ClientSession clientSession = (ClientSession) session;
77                 LOG.debug("SSH session {} event {}", session, event);
78                 switch (event) {
79                     case KeyEstablished:
80                         doAuth(clientSession);
81                         break;
82                     case Authenticated:
83                         doPostAuth(clientSession);
84                         break;
85                     default:
86                         break;
87                 }
88             }
89
90             @Override
91             public void sessionCreated(final Session session) {
92                 LOG.debug("SSH session {} created", session);
93             }
94
95             @Override
96             public void sessionClosed(final Session session) {
97                 CallHomeSessionContext ctx = CallHomeSessionContext.getFrom((ClientSession) session);
98                 if (ctx != null) {
99                     ctx.removeSelf();
100                 }
101                 LOG.debug("SSH Session {} closed", session);
102             }
103         };
104     }
105
106     private static void doPostAuth(final ClientSession session) {
107         CallHomeSessionContext.getFrom(session).openNetconfChannel();
108     }
109
110     private void doAuth(final ClientSession session) {
111         try {
112             final AuthFuture authFuture = CallHomeSessionContext.getFrom(session).authorize();
113             authFuture.addListener(newAuthSshFutureListener(session));
114         } catch (IOException e) {
115             LOG.error("Failed to authorize session {}", session, e);
116         }
117     }
118
119     private SshFutureListener<AuthFuture> newAuthSshFutureListener(final ClientSession session) {
120         final PublicKey serverKey = session.getKex().getServerKey();
121
122         return new SshFutureListener<AuthFuture>() {
123             @Override
124             public void operationComplete(final AuthFuture authFuture) {
125                 if (authFuture.isSuccess()) {
126                     onSuccess();
127                 } else if (authFuture.isFailure()) {
128                     onFailure(authFuture.getException());
129                 } else if (authFuture.isCanceled()) {
130                     onCanceled();
131                 }
132                 authFuture.removeListener(this);
133             }
134
135             private void onSuccess() {
136                 LOG.debug("Authorize success");
137             }
138
139             private void onFailure(final Throwable throwable) {
140                 LOG.error("Authorize failed for session {}", session, throwable);
141                 recorder.reportFailedAuth(serverKey);
142                 session.close(true);
143             }
144
145             private void onCanceled() {
146                 LOG.warn("Authorize cancelled");
147                 session.close(true);
148             }
149         };
150     }
151
152     @Override
153     public boolean verifyServerKey(final ClientSession sshClientSession, final SocketAddress remoteAddress,
154             final PublicKey serverKey) {
155         final CallHomeAuthorization authorization = authProvider.provideAuth(remoteAddress, serverKey);
156         // server is not authorized
157         if (!authorization.isServerAllowed()) {
158             LOG.info("Incoming session {} was rejected by Authorization Provider.", sshClientSession);
159             return false;
160         }
161         CallHomeSessionContext session = sessionFactory.createIfNotExists(
162             sshClientSession, authorization, remoteAddress);
163         // Session was created, session with same name does not exists
164         if (session != null) {
165             return true;
166         }
167         // Session was not created, session with same name exists
168         LOG.info("Incoming session {} was rejected. Session with same name {} is already active.",
169             sshClientSession, authorization.getSessionName());
170         return false;
171     }
172
173     public void bind() throws IOException {
174         try {
175             client.start();
176             acceptor.bind(bindAddress);
177         } catch (IOException e) {
178             LOG.error("Unable to start NETCONF CallHome Service on {}", bindAddress, e);
179             throw e;
180         }
181     }
182
183     @Override
184     public void close() {
185         acceptor.close(true);
186         serviceFactory.close(true);
187     }
188 }