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