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