2 * Copyright (c) 2023 PANTHEON.tech s.r.o. All rights reserved.
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
8 package org.opendaylight.netconf.transport.ssh;
10 import static java.util.Objects.requireNonNull;
12 import java.io.IOException;
14 import org.opendaylight.netconf.shaded.sshd.client.session.ClientSession;
15 import org.opendaylight.netconf.shaded.sshd.common.session.Session;
16 import org.opendaylight.netconf.shaded.sshd.common.session.SessionListener;
19 * Session listener responsible for session authentication for both client and server.
21 * <P>Triggers authentication flow when after server key is accepted by client,
22 * invokes associated handler on authentication success/failure.
24 public class UserAuthSessionListener implements SessionListener {
26 final Map<Long, AuthHandler> sessionAuthHandlers;
27 final Map<Long, Session> sessions;
29 public UserAuthSessionListener(final Map<Long, AuthHandler> sessionAuthHandlers,
30 final Map<Long, Session> sessions) {
31 this.sessionAuthHandlers = sessionAuthHandlers;
32 this.sessions = sessions;
36 public void sessionCreated(Session session) {
37 sessions.put(session.getIoSession().getId(), session);
41 public void sessionException(final Session session, Throwable throwable) {
42 deleteSession(session);
46 public void sessionDisconnect(Session session, int reason, String msg, String language, boolean initiator) {
47 deleteSession(session);
51 public void sessionClosed(Session session) {
52 deleteSession(session);
55 private void deleteSession(final Session session) {
56 final Long id = idOf(session);
58 final var handler = sessionAuthHandlers.remove(id);
59 if (handler != null) {
60 handler.onFailure().run();
65 public void sessionEvent(Session session, Event event) {
66 if (Event.KeyEstablished == event && session instanceof ClientSession clientSession) {
67 // server key is accepted, trigger authentication flow
69 clientSession.auth().addListener(future -> {
70 if (!future.isSuccess()) {
71 deleteSession(session);
74 } catch (IOException e) {
75 sessionException(session, e);
78 if (Event.Authenticated == event) {
79 final var handler = sessionAuthHandlers.remove(idOf(session));
80 if (handler != null) {
81 handler.onSuccess().run();
86 private static Long idOf(final Session session) {
87 return session.getIoSession().getId();
90 public record AuthHandler(Runnable onSuccess, Runnable onFailure) {
92 requireNonNull(onSuccess);
93 requireNonNull(onFailure);