-
Notifications
You must be signed in to change notification settings - Fork 22
/
SshShellRunnable.java
247 lines (211 loc) · 9.77 KB
/
SshShellRunnable.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
/*
* Copyright (c) 2020 François Onimus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.fonimus.ssh.shell;
import com.github.fonimus.ssh.shell.auth.SshAuthentication;
import com.github.fonimus.ssh.shell.auth.SshShellSecurityAuthenticationProvider;
import com.github.fonimus.ssh.shell.listeners.SshShellListenerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.sshd.common.Factory;
import org.apache.sshd.server.ChannelSessionAware;
import org.apache.sshd.server.ExitCallback;
import org.apache.sshd.server.Signal;
import org.apache.sshd.server.channel.ChannelSession;
import org.apache.sshd.server.command.Command;
import org.apache.sshd.server.session.ServerSession;
import org.jline.reader.EndOfFileException;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.Parser;
import org.jline.terminal.Attributes;
import org.jline.terminal.Size;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.jline.utils.AttributedString;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import org.springframework.boot.Banner;
import org.springframework.core.env.Environment;
import org.springframework.shell.ExitRequest;
import org.springframework.shell.Input;
import org.springframework.shell.Shell;
import org.springframework.shell.jline.InteractiveShellApplicationRunner;
import org.springframework.shell.jline.JLineShellAutoConfiguration;
import org.springframework.shell.jline.PromptProvider;
import org.springframework.shell.result.DefaultResultHandler;
import java.io.*;
import java.nio.charset.StandardCharsets;
import static com.github.fonimus.ssh.shell.SshShellCommandFactory.SSH_THREAD_CONTEXT;
/**
* Runnable for ssh shell session
*/
@Slf4j
public class SshShellRunnable
implements Factory<Command>, ChannelSessionAware, Runnable {
private SshShellProperties properties;
private ChannelSession session;
private SshShellListenerService shellListenerService;
private Banner shellBanner;
private PromptProvider promptProvider;
private Shell shell;
private JLineShellAutoConfiguration.CompleterAdapter completerAdapter;
private Parser parser;
private Environment environment;
private org.apache.sshd.server.Environment sshEnv;
private SshShellCommandFactory sshShellCommandFactory;
private InputStream is;
private OutputStream os;
private ExitCallback ec;
public SshShellRunnable(SshShellProperties properties, ChannelSession session,
SshShellListenerService shellListenerService, Banner shellBanner,
PromptProvider promptProvider, Shell shell,
JLineShellAutoConfiguration.CompleterAdapter completerAdapter, Parser parser,
Environment environment, org.apache.sshd.server.Environment sshEnv,
SshShellCommandFactory sshShellCommandFactory, InputStream is,
OutputStream os, ExitCallback ec) {
this.properties = properties;
this.session = session;
this.shellListenerService = shellListenerService;
this.shellBanner = shellBanner;
this.promptProvider = promptProvider;
this.shell = shell;
this.completerAdapter = completerAdapter;
this.parser = parser;
this.environment = environment;
this.sshEnv = sshEnv;
this.sshShellCommandFactory = sshShellCommandFactory;
this.is = is;
this.os = os;
this.ec = ec;
}
/**
* Run ssh session
*/
@Override
public void run() {
LOGGER.debug("{}: running...", session.toString());
Size size = new Size(Integer.parseInt(sshEnv.getEnv().get("COLUMNS")), Integer.parseInt(sshEnv.getEnv().get(
"LINES")));
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos, true, StandardCharsets.UTF_8.name());
Terminal terminal = TerminalBuilder.builder().system(false).size(size).type(sshEnv.getEnv().get("TERM"))
.streams(is, os).build()) {
try {
DefaultResultHandler resultHandler = new DefaultResultHandler();
resultHandler.setTerminal(terminal);
Attributes attr = terminal.getAttributes();
SshShellUtils.fill(attr, sshEnv.getPtyModes());
terminal.setAttributes(attr);
sshEnv.addSignalListener((channel, signal) -> {
terminal.setSize(new Size(
Integer.parseInt(sshEnv.getEnv().get("COLUMNS")),
Integer.parseInt(sshEnv.getEnv().get("LINES"))));
terminal.raise(Terminal.Signal.WINCH);
}, Signal.WINCH);
if (properties.isDisplayBanner() && shellBanner != null) {
shellBanner.printBanner(environment, this.getClass(), ps);
}
resultHandler.handleResult(new String(baos.toByteArray(), StandardCharsets.UTF_8));
resultHandler.handleResult("Please type `help` to see available commands");
LineReader reader = LineReaderBuilder.builder()
.terminal(terminal)
.appName("Spring Ssh Shell")
.completer(completerAdapter)
.highlighter((reader1, buffer) -> {
int l = 0;
String best = null;
for (String command : shell.listCommands().keySet()) {
if (buffer.startsWith(command) && command.length() > l) {
l = command.length();
best = command;
}
}
if (best != null) {
return new AttributedStringBuilder(buffer.length()).append(best,
AttributedStyle.BOLD).append(buffer.substring(l))
.toAttributedString();
} else {
return new AttributedString(buffer,
AttributedStyle.DEFAULT.foreground(AttributedStyle.RED));
}
})
.parser(parser)
.build();
Object authenticationObject = session.getSession().getIoSession().getAttribute(
SshShellSecurityAuthenticationProvider.AUTHENTICATION_ATTRIBUTE);
SshAuthentication authentication = null;
if (authenticationObject != null) {
if (!(authenticationObject instanceof SshAuthentication)) {
throw new IllegalStateException("Unknown authentication object class: " + authenticationObject.getClass().getName());
}
authentication = (SshAuthentication) authenticationObject;
}
File historyFile = properties.getHistoryFile();
if (!properties.isSharedHistory()) {
String user = authentication != null ? authentication.getName() : "unknown";
historyFile = new File(properties.getHistoryDirectory(), "sshShellHistory-" + user + ".log");
}
reader.setVariable(LineReader.HISTORY_FILE, historyFile.toPath());
SSH_THREAD_CONTEXT.set(new SshContext(this, terminal, reader, authentication));
shellListenerService.onSessionStarted(session);
shell.run(new SshShellInputProvider(reader, promptProvider));
shellListenerService.onSessionStopped(session);
LOGGER.debug("{}: closing", session.toString());
quit(0);
} catch (Throwable e) {
shellListenerService.onSessionError(session);
LOGGER.error("{}: unexpected exception", session.toString(), e);
quit(1);
}
} catch (IOException e) {
LOGGER.error("Unable to open terminal", e);
quit(1);
}
}
private void quit(int exitCode) {
if (ec != null) {
ec.onExit(exitCode);
}
}
@Override
public void setChannelSession(ChannelSession session) {
this.session = session;
}
public ServerSession getSshSession() {
return session.getSession();
}
@Override
public Command create() {
return sshShellCommandFactory;
}
static class SshShellInputProvider
extends InteractiveShellApplicationRunner.JLineInputProvider {
public SshShellInputProvider(LineReader lineReader, PromptProvider promptProvider) {
super(lineReader, promptProvider);
}
@Override
public Input readInput() {
SshContext ctx = SSH_THREAD_CONTEXT.get();
if (ctx != null) {
ctx.setPostProcessorsList(null);
}
try {
return super.readInput();
} catch (EndOfFileException e) {
throw new ExitRequest(1);
}
}
}
}