001    /*
002     * Copyright (C) 2012 eXo Platform SAS.
003     *
004     * This is free software; you can redistribute it and/or modify it
005     * under the terms of the GNU Lesser General Public License as
006     * published by the Free Software Foundation; either version 2.1 of
007     * the License, or (at your option) any later version.
008     *
009     * This software is distributed in the hope that it will be useful,
010     * but WITHOUT ANY WARRANTY; without even the implied warranty of
011     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012     * Lesser General Public License for more details.
013     *
014     * You should have received a copy of the GNU Lesser General Public
015     * License along with this software; if not, write to the Free
016     * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
017     * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
018     */
019    package org.crsh.ssh.term;
020    
021    import org.apache.sshd.SshServer;
022    import org.apache.sshd.common.Session;
023    import org.apache.sshd.server.PasswordAuthenticator;
024    import org.apache.sshd.server.session.ServerSession;
025    import org.crsh.plugin.PluginContext;
026    import org.crsh.auth.AuthenticationPlugin;
027    import org.crsh.ssh.term.scp.SCPCommandFactory;
028    import org.crsh.term.TermLifeCycle;
029    import org.crsh.term.spi.TermIOHandler;
030    import org.crsh.vfs.Resource;
031    
032    import java.util.logging.Level;
033    import java.util.logging.Logger;
034    
035    public class SSHLifeCycle extends TermLifeCycle {
036    
037      /** . */
038      public static final Session.AttributeKey<String> USERNAME = new Session.AttributeKey<java.lang.String>();
039    
040      /** . */
041      public static final Session.AttributeKey<String> PASSWORD = new Session.AttributeKey<java.lang.String>();
042    
043      /** . */
044      private final Logger log = Logger.getLogger(SSHLifeCycle.class.getName());
045    
046      /** . */
047      private SshServer server;
048    
049      /** . */
050      private int port;
051    
052      /** . */
053      private Resource key;
054    
055      /** . */
056      private String authentication;
057    
058      /** . */
059      private Integer localPort;
060    
061      public SSHLifeCycle(PluginContext context) {
062        super(context);
063      }
064    
065      public int getPort() {
066        return port;
067      }
068    
069      public void setPort(int port) {
070        this.port = port;
071      }
072    
073      /**
074       * Returns the local part after the ssh server has been succesfully bound or null. This is useful when
075       * the port is chosen at random by the system.
076       *
077       * @return the local port
078       */
079      public Integer getLocalPort() {
080              return localPort;
081      }
082      
083      public Resource getKey() {
084        return key;
085      }
086    
087      public void setKey(Resource key) {
088        this.key = key;
089      }
090    
091      public String getAuthentication() {
092        return authentication;
093      }
094    
095      public void setAuthentication(String authentication) {
096        this.authentication = authentication;
097      }
098    
099      @Override
100      protected void doInit() {
101        try {
102    
103          //
104          TermIOHandler handler = getHandler();
105    
106          //
107          SshServer server = SshServer.setUpDefaultServer();
108          server.setPort(port);
109          server.setShellFactory(new CRaSHCommandFactory(handler));
110          server.setCommandFactory(new SCPCommandFactory(getContext()));
111          server.setKeyPairProvider(new URLKeyPairProvider(key));
112    
113          // We never authenticate by default
114          AuthenticationPlugin plugin = new AuthenticationPlugin() {
115            public String getName() {
116              return "null";
117            }
118            public boolean authenticate(String username, String password) throws Exception {
119              return false;
120            }
121          };
122    
123          // Lookup for an authentication plugin
124          if (authentication != null) {
125            for (AuthenticationPlugin authenticationPlugin : getContext().getPlugins(AuthenticationPlugin.class)) {
126              if (authentication.equals(authenticationPlugin.getName())) {
127                plugin = authenticationPlugin;
128                break;
129              }
130            }
131          }
132    
133          //
134          final AuthenticationPlugin authPlugin = plugin;
135    
136          //
137          server.setPasswordAuthenticator(new PasswordAuthenticator() {
138            public boolean authenticate(String _username, String _password, ServerSession session) {
139              boolean auth;
140              try {
141                log.log(Level.FINE, "Using authentication plugin " + authPlugin + " to authenticate user " + _username);
142                auth = authPlugin.authenticate(_username, _password);
143              } catch (Exception e) {
144                log.log(Level.SEVERE, "Exception authenticating user " + _username + " in authentication plugin: " + authPlugin, e);
145                return false;
146              }
147    
148              // We store username and password in session for later reuse
149              session.setAttribute(USERNAME, _username);
150              session.setAttribute(PASSWORD, _password);
151    
152              //
153              return auth;
154            }
155          });
156    
157          //
158          log.log(Level.INFO, "About to start CRaSSHD");
159          server.start();
160          localPort = server.getPort();
161          log.log(Level.INFO, "CRaSSHD started on port " + localPort);
162    
163          //
164          this.server = server;
165        }
166        catch (Throwable e) {
167          log.log(Level.SEVERE, "Could not start CRaSSHD", e);
168        }
169      }
170    
171      @Override
172      protected void doDestroy() {
173        if (server != null) {
174          try {
175            server.stop();
176          }
177          catch (InterruptedException e) {
178            log.log(Level.FINE, "Got an interruption when stopping server", e);
179          }
180        }
181      }
182    }