V2.0.0 Extend this SSH server to be a XMPP Component

master
Ng Yat Yan 2 months ago
parent 9b10cbe9b7
commit 10ff309803

@ -0,0 +1,8 @@
{
"subdomainPrefix": "echo",
"domain": "vidconnect.cyou",
"host": "localhost",
"port": 5270,
"secretKey": "user-admin_secret",
"startEncrypted": false
}

@ -6,7 +6,8 @@ ssh-server:
location: "conf/hash-replies.properties" location: "conf/hash-replies.properties"
regex-mapping: regex-mapping:
location: "conf/regex-mapping.properties" location: "conf/regex-mapping.properties"
xmpp-component:
config-json: "conf/echo-component.json"
spring: spring:
datasource: datasource:
url: "jdbc:h2:file:./data/remote-ip-info-db" url: "jdbc:h2:file:./data/remote-ip-info-db"

@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.example.sshd</groupId> <groupId>com.example.sshd</groupId>
<artifactId>echo-sshd-server</artifactId> <artifactId>echo-sshd-server</artifactId>
<version>1.5.0</version> <version>2.0.0</version>
<name>ECHO SSH SERVER</name> <name>ECHO SSH SERVER</name>
<description>Learning Apache Mina SSHD library</description> <description>Learning Apache Mina SSHD library</description>
<parent> <parent>
@ -16,10 +16,23 @@
<java.version>17</java.version> <java.version>17</java.version>
<mina.version>2.0.25</mina.version> <mina.version>2.0.25</mina.version>
<sshd.version>0.14.0</sshd.version> <sshd.version>0.14.0</sshd.version>
<whack.version>2.0.1</whack.version>
<jackson.version>2.17.1</jackson.version>
<commons-io.version>2.17.0</commons-io.version> <commons-io.version>2.17.0</commons-io.version>
<commons-exec.version>1.4.0</commons-exec.version> <commons-exec.version>1.4.0</commons-exec.version>
<commons-lang3.version>3.17.0</commons-lang3.version> <commons-lang3.version>3.17.0</commons-lang3.version>
</properties> </properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson</groupId>
<artifactId>jackson-bom</artifactId>
<version>2.16.1</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
@ -31,6 +44,18 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId> <artifactId>spring-boot-starter-log4j2</artifactId>
@ -45,13 +70,13 @@
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId> <artifactId>commons-exec</artifactId>
<version>${commons-exec.version}</version> <version>${commons-exec.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-codec</groupId> <groupId>commons-codec</groupId>
@ -73,12 +98,13 @@
<version>${commons-io.version}</version> <version>${commons-io.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>httpclient5</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.httpcomponents.client5</groupId> <groupId>org.igniterealtime.whack</groupId>
<artifactId>httpclient5</artifactId> <artifactId>core</artifactId>
<version>${whack.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>

@ -10,22 +10,22 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication @SpringBootApplication
public class Boot { public class Boot {
private static final Logger logger = LoggerFactory.getLogger(Boot.class); private static final Logger logger = LoggerFactory.getLogger(Boot.class);
@Autowired @Autowired
protected SshServer sshd; protected SshServer sshd;
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
String configDirectory = "conf"; String configDirectory = "conf";
if (args.length > 0) { if (args.length > 0) {
configDirectory = args[0]; configDirectory = args[0];
} }
logger.info("config directory: {}", configDirectory); logger.info("config directory: {}", configDirectory);
if (new java.io.File(configDirectory).exists() && new java.io.File(configDirectory).isDirectory()) { if (new java.io.File(configDirectory).exists() && new java.io.File(configDirectory).isDirectory()) {
System.setProperty("spring.config.location", configDirectory + "/springboot.yml"); System.setProperty("spring.config.location", configDirectory + "/springboot.yml");
System.setProperty("logging.config", configDirectory + "/log4j2.xml"); System.setProperty("logging.config", configDirectory + "/log4j2.xml");
}
SpringApplication.run(Boot.class, args);
} }
SpringApplication.run(Boot.class, args);
}
} }

@ -1,5 +1,6 @@
package com.example.sshd.config; package com.example.sshd.config;
import java.io.IOException;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -9,36 +10,50 @@ import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.reactor.IOReactorConfig; import org.apache.hc.core5.reactor.IOReactorConfig;
import org.apache.sshd.common.Session; import org.apache.sshd.common.Session;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import com.fasterxml.jackson.core.exc.StreamReadException;
import com.fasterxml.jackson.databind.DatabindException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration @Configuration
public class AppConfig { public class AppConfig {
@Bean @Value("${xmpp-component.config-json}")
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) private String xmppComponentConfigJson;
public Map<String, Session> remoteSessionMapping() {
return new ConcurrentHashMap<>(); @Bean
} @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public XmppComponentConfig xmppComponentConfig() throws StreamReadException, DatabindException, IOException {
@Bean return new ObjectMapper().readValue(new java.io.File(xmppComponentConfigJson), XmppComponentConfig.class);
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) }
public Map<String, String> ipInfoMapping() {
return new ConcurrentHashMap<>(); @Bean
} @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public Map<String, Session> remoteSessionMapping() {
@Bean return new ConcurrentHashMap<>();
public CloseableHttpAsyncClient asyncClient() { }
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().build();
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setIOReactorConfig(ioReactorConfig).build(); @Bean
client.start(); @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
return client; public Map<String, String> ipInfoMapping() {
} return new ConcurrentHashMap<>();
}
@Bean
public CloseableHttpClient httpClient() { @Bean
return HttpClients.createDefault(); public CloseableHttpAsyncClient asyncClient() {
} final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().build();
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setIOReactorConfig(ioReactorConfig).build();
client.start();
return client;
}
@Bean
public CloseableHttpClient httpClient() {
return HttpClients.createDefault();
}
} }

@ -29,72 +29,72 @@ import com.example.sshd.core.OnetimeCommand;
@Configuration @Configuration
public class SshConfig { public class SshConfig {
private static final Logger loginLogger = LoggerFactory.getLogger("login"); private static final Logger loginLogger = LoggerFactory.getLogger("login");
@Value("${ssh-server.port}") @Value("${ssh-server.port}")
private int port; private int port;
@Value("${ssh-server.private-key.location}") @Value("${ssh-server.private-key.location}")
private String pkLocation; private String pkLocation;
@Value("${ssh-server.login.usernames:root}") @Value("${ssh-server.login.usernames:root}")
private String[] usernames; private String[] usernames;
@Value("${ssh-server.hash-replies.location}") @Value("${ssh-server.hash-replies.location}")
private String hashReplies; private String hashReplies;
@Value("${ssh-server.regex-mapping.location}") @Value("${ssh-server.regex-mapping.location}")
private String regexMapping; private String regexMapping;
@Autowired @Autowired
ApplicationContext applicationContext; ApplicationContext applicationContext;
@Bean @Bean
public SshServer sshd() throws IOException, NoSuchAlgorithmException { public SshServer sshd() throws IOException, NoSuchAlgorithmException {
SshServer sshd = SshServer.setUpDefaultServer(); SshServer sshd = SshServer.setUpDefaultServer();
sshd.setPort(port); sshd.setPort(port);
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File(pkLocation).getPath(), "RSA", 2048)); sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File(pkLocation).getPath(), "RSA", 2048));
sshd.setPasswordAuthenticator(new PasswordAuthenticator() { sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
@Override @Override
public boolean authenticate(final String username, final String password, final ServerSession session) { public boolean authenticate(final String username, final String password, final ServerSession session) {
if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress) { if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress) {
InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress(); InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress();
String remoteIpAddress = remoteAddress.getAddress().getHostAddress(); String remoteIpAddress = remoteAddress.getAddress().getHostAddress();
loginLogger.info("[{}] Login Attempt: username = {}, password = {}", remoteIpAddress, username, loginLogger.info("[{}] Login Attempt: username = {}, password = {}", remoteIpAddress, username,
password); password);
} else { } else {
loginLogger.info("[{}] Login Attempt: username = {}, password = {}", loginLogger.info("[{}] Login Attempt: username = {}, password = {}",
session.getIoSession().getRemoteAddress(), username, password); session.getIoSession().getRemoteAddress(), username, password);
} }
return Arrays.asList(usernames).contains(username); return Arrays.asList(usernames).contains(username);
} }
}); });
sshd.setShellFactory(applicationContext.getBean(EchoShellFactory.class)); sshd.setShellFactory(applicationContext.getBean(EchoShellFactory.class));
sshd.setCommandFactory(command -> applicationContext.getBean(OnetimeCommand.class, command)); sshd.setCommandFactory(command -> applicationContext.getBean(OnetimeCommand.class, command));
sshd.start(); sshd.start();
sshd.getSessionFactory().addListener(applicationContext.getBean(EchoSessionListener.class)); sshd.getSessionFactory().addListener(applicationContext.getBean(EchoSessionListener.class));
return sshd; return sshd;
} }
@Bean @Bean
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public Properties hashReplies() throws IOException { public Properties hashReplies() throws IOException {
Properties prop = new Properties(); Properties prop = new Properties();
File configFile = new File(hashReplies); File configFile = new File(hashReplies);
FileInputStream stream = new FileInputStream(configFile); FileInputStream stream = new FileInputStream(configFile);
prop.load(stream); prop.load(stream);
return prop; return prop;
} }
@Bean @Bean
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public Properties regexMapping() throws IOException { public Properties regexMapping() throws IOException {
Properties prop = new Properties(); Properties prop = new Properties();
File configFile = new File(regexMapping); File configFile = new File(regexMapping);
FileInputStream stream = new FileInputStream(configFile); FileInputStream stream = new FileInputStream(configFile);
prop.load(stream); prop.load(stream);
return prop; return prop;
} }
} }

@ -0,0 +1,78 @@
package com.example.sshd.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class XmppComponentConfig {
private static final Logger logger = LoggerFactory.getLogger(XmppComponentConfig.class);
private String subdomainPrefix;
private String domain;
private String host;
private int port;
private String secretKey;
private boolean startEncrypted;
public String getSubdomainPrefix() {
return subdomainPrefix;
}
public void setSubdomainPrefix(String subdomainPrefix) {
this.subdomainPrefix = subdomainPrefix;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public boolean isStartEncrypted() {
return startEncrypted;
}
public void setStartEncrypted(boolean startEncrypted) {
this.startEncrypted = startEncrypted;
}
@Override
@JsonIgnore
public String toString() {
try {
return new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this);
} catch (JsonProcessingException e) {
logger.error("convert to json error!", e);
}
return "{}";
}
}

@ -17,66 +17,66 @@ import com.example.sshd.service.JdbcService;
@Component @Component
public class EchoSessionListener implements SessionListener { public class EchoSessionListener implements SessionListener {
private static final Logger logger = LoggerFactory.getLogger(EchoSessionListener.class); private static final Logger logger = LoggerFactory.getLogger(EchoSessionListener.class);
private static final Logger ipInfoLogger = LoggerFactory.getLogger("ip_info"); private static final Logger ipInfoLogger = LoggerFactory.getLogger("ip_info");
@Autowired @Autowired
Map<String, Session> remoteSessionMapping; Map<String, Session> remoteSessionMapping;
@Autowired @Autowired
Map<String, String> ipInfoMapping; Map<String, String> ipInfoMapping;
@Autowired @Autowired
GeoIpLocator geoIpLocator; GeoIpLocator geoIpLocator;
@Autowired @Autowired
JdbcService jdbcService; JdbcService jdbcService;
@Override @Override
public void sessionCreated(Session session) { public void sessionCreated(Session session) {
logger.info("sessionCreated: {}", session); logger.info("sessionCreated: {}", session);
if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress) { if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress) {
InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress(); InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress();
String remoteIpAddress = remoteAddress.getAddress().getHostAddress(); String remoteIpAddress = remoteAddress.getAddress().getHostAddress();
if (remoteSessionMapping.containsKey(remoteIpAddress)) { if (remoteSessionMapping.containsKey(remoteIpAddress)) {
logger.info("kill old session: {} -> {}", remoteIpAddress, remoteSessionMapping.get(remoteIpAddress)); logger.info("kill old session: {} -> {}", remoteIpAddress, remoteSessionMapping.get(remoteIpAddress));
remoteSessionMapping.get(remoteIpAddress).close(false); remoteSessionMapping.get(remoteIpAddress).close(false);
} }
logger.info("new session: {} -> {}", remoteIpAddress, session); logger.info("new session: {} -> {}", remoteIpAddress, session);
remoteSessionMapping.put(remoteIpAddress, session); remoteSessionMapping.put(remoteIpAddress, session);
if (!ipInfoMapping.containsKey(remoteIpAddress)) { if (!ipInfoMapping.containsKey(remoteIpAddress)) {
List<Map<String, Object>> ipInfoList = jdbcService.getAllRemoteIpInfo(remoteIpAddress); List<Map<String, Object>> ipInfoList = jdbcService.getAllRemoteIpInfo(remoteIpAddress);
if (!ipInfoList.isEmpty()) { if (!ipInfoList.isEmpty()) {
ipInfoMapping.put(remoteIpAddress, (String) ipInfoList.get(0).get("remote_ip_info")); ipInfoMapping.put(remoteIpAddress, (String) ipInfoList.get(0).get("remote_ip_info"));
}
}
} }
}
} }
}
@Override @Override
public void sessionEvent(Session session, Event event) { public void sessionEvent(Session session, Event event) {
logger.info("sessionEvent: {}, event: {}", session, event); logger.info("sessionEvent: {}, event: {}", session, event);
if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress && event == Event.KexCompleted) { if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress && event == Event.KexCompleted) {
InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress(); InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress();
String remoteIpAddress = remoteAddress.getAddress().getHostAddress(); String remoteIpAddress = remoteAddress.getAddress().getHostAddress();
if (!ipInfoMapping.containsKey(remoteIpAddress)) { if (!ipInfoMapping.containsKey(remoteIpAddress)) {
geoIpLocator.asyncUpdateIpLocationInfo(remoteIpAddress); geoIpLocator.asyncUpdateIpLocationInfo(remoteIpAddress);
} else { } else {
ipInfoLogger.debug("[{}] {}", remoteIpAddress, ipInfoMapping.get(remoteIpAddress)); ipInfoLogger.debug("[{}] {}", remoteIpAddress, ipInfoMapping.get(remoteIpAddress));
} }
}
} }
}
@Override @Override
public void sessionClosed(Session session) { public void sessionClosed(Session session) {
logger.info("sessionClosed: {}", session); logger.info("sessionClosed: {}", session);
if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress) { if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress) {
InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress(); InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress();
String remoteIpAddress = remoteAddress.getAddress().getHostAddress(); String remoteIpAddress = remoteAddress.getAddress().getHostAddress();
logger.info("removing session: {} -> {}", remoteIpAddress, remoteSessionMapping.get(remoteIpAddress)); logger.info("removing session: {} -> {}", remoteIpAddress, remoteSessionMapping.get(remoteIpAddress));
remoteSessionMapping.remove(remoteIpAddress); remoteSessionMapping.remove(remoteIpAddress);
ipInfoMapping.remove(remoteIpAddress); ipInfoMapping.remove(remoteIpAddress);
}
} }
}
} }

@ -28,119 +28,119 @@ import com.example.sshd.service.ReplyService;
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class EchoShell implements Command, Runnable, SessionAware { public class EchoShell implements Command, Runnable, SessionAware {
private static final Logger logger = LoggerFactory.getLogger(EchoShell.class); private static final Logger logger = LoggerFactory.getLogger(EchoShell.class);
@Autowired @Autowired
ReplyService replyUtil; ReplyService replyUtil;
@Autowired @Autowired
Properties hashReplies; Properties hashReplies;
protected InputStream in; protected InputStream in;
protected OutputStream out; protected OutputStream out;
protected OutputStream err; protected OutputStream err;
protected ExitCallback callback; protected ExitCallback callback;
protected Environment environment; protected Environment environment;
protected Thread thread; protected Thread thread;
protected ServerSession session; protected ServerSession session;
@Override @Override
public void setInputStream(InputStream in) { public void setInputStream(InputStream in) {
this.in = in; this.in = in;
} }
@Override @Override
public void setOutputStream(OutputStream out) { public void setOutputStream(OutputStream out) {
this.out = out; this.out = out;
} }
@Override @Override
public void setErrorStream(OutputStream err) { public void setErrorStream(OutputStream err) {
this.err = err; this.err = err;
} }
@Override @Override
public void setExitCallback(ExitCallback callback) { public void setExitCallback(ExitCallback callback) {
this.callback = callback; this.callback = callback;
}
@Override
public void start(Environment env) throws IOException {
environment = env;
thread = new Thread(this, remoteIpAddress());
logger.info("environment: {}, thread-name: {}", environment.getEnv(), thread.getName());
thread.start();
}
protected String remoteIpAddress() {
String remoteIpAddress = "";
if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress) {
InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress();
remoteIpAddress = remoteAddress.getAddress().getHostAddress();
} else {
remoteIpAddress = session.getIoSession().getRemoteAddress().toString();
} }
return remoteIpAddress;
}
@Override
public void destroy() {
thread.interrupt();
}
@Override
public void run() {
String prompt = hashReplies.getProperty("prompt", "$ ").replace("{user}", environment.getEnv().get("USER"));
try {
out.write(prompt.getBytes());
out.flush();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String command = "";
while (!Thread.currentThread().isInterrupted()) {
int s = r.read();
if (s == 13 || s == 10) {
boolean containsExit = Arrays.asList(StringUtils.split(command, ";|&")).stream().map(cmd -> {
boolean wantsExit = false;
try {
wantsExit = replyUtil.replyToCommand(cmd.trim(), out, prompt, session);
out.flush();
} catch (Exception e) {
logger.error("run error!", e);
}
return wantsExit;
}).reduce((a, b) -> a || b).get();
@Override if (containsExit) {
public void start(Environment env) throws IOException { break;
environment = env; }
thread = new Thread(this, remoteIpAddress()); command = "";
logger.info("environment: {}, thread-name: {}", environment.getEnv(), thread.getName());
thread.start();
}
protected String remoteIpAddress() {
String remoteIpAddress = "";
if (session.getIoSession().getRemoteAddress() instanceof InetSocketAddress) {
InetSocketAddress remoteAddress = (InetSocketAddress) session.getIoSession().getRemoteAddress();
remoteIpAddress = remoteAddress.getAddress().getHostAddress();
} else { } else {
remoteIpAddress = session.getIoSession().getRemoteAddress().toString(); logger.trace("input character: {}", s);
} if (s == 127) {
return remoteIpAddress; if (command.length() > 0) {
} command = command.substring(0, command.length() - 1);
out.write(s);
@Override
public void destroy() {
thread.interrupt();
}
@Override
public void run() {
String prompt = hashReplies.getProperty("prompt", "$ ").replace("{user}", environment.getEnv().get("USER"));
try {
out.write(prompt.getBytes());
out.flush();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String command = "";
while (!Thread.currentThread().isInterrupted()) {
int s = r.read();
if (s == 13 || s == 10) {
boolean containsExit = Arrays.asList(StringUtils.split(command, ";|&")).stream().map(cmd -> {
boolean wantsExit = false;
try {
wantsExit = replyUtil.replyToCommand(cmd.trim(), out, prompt, session);
out.flush();
} catch (Exception e) {
logger.error("run error!", e);
}
return wantsExit;
}).reduce((a, b) -> a || b).get();
if (containsExit) {
break;
}
command = "";
} else {
logger.trace("input character: {}", s);
if (s == 127) {
if (command.length() > 0) {
command = command.substring(0, command.length() - 1);
out.write(s);
}
} else if (s >= 32 && s < 127) {
command += (char) s;
out.write(s);
}
}
out.flush();
} }
} catch (Exception e) { } else if (s >= 32 && s < 127) {
logger.error("run error!", e); command += (char) s;
} finally { out.write(s);
callback.onExit(0); }
} }
out.flush();
}
} catch (Exception e) {
logger.error("run error!", e);
} finally {
callback.onExit(0);
} }
}
@Override @Override
public void setSession(ServerSession session) { public void setSession(ServerSession session) {
this.session = session; this.session = session;
} }
} }

@ -9,12 +9,12 @@ import org.springframework.stereotype.Component;
@Component @Component
public class EchoShellFactory implements Factory<Command> { public class EchoShellFactory implements Factory<Command> {
@Autowired @Autowired
ApplicationContext applicationContext; ApplicationContext applicationContext;
@Override @Override
public Command create() { public Command create() {
return (Command) applicationContext.getBean("echoShell"); return (Command) applicationContext.getBean("echoShell");
} }
} }

@ -13,29 +13,29 @@ import org.springframework.stereotype.Component;
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class OnetimeCommand extends EchoShell { public class OnetimeCommand extends EchoShell {
private static final Logger logger = LoggerFactory.getLogger(OnetimeCommand.class); private static final Logger logger = LoggerFactory.getLogger(OnetimeCommand.class);
private String command; private String command;
public OnetimeCommand(String cmd) { public OnetimeCommand(String cmd) {
command = cmd; command = cmd;
} }
@Override @Override
public void run() { public void run() {
try {
Arrays.asList(StringUtils.split(command, ";|&")).stream().forEach(cmd -> {
try { try {
Arrays.asList(StringUtils.split(command, ";|&")).stream().forEach(cmd -> { replyUtil.replyToCommand(cmd.trim(), out, "", session);
try { out.flush();
replyUtil.replyToCommand(cmd.trim(), out, "", session);
out.flush();
} catch (Exception e) {
logger.error("run error!", e);
}
});
} catch (Exception e) { } catch (Exception e) {
logger.error("run error!", e); logger.error("run error!", e);
} finally {
callback.onExit(0);
} }
});
} catch (Exception e) {
logger.error("run error!", e);
} finally {
callback.onExit(0);
} }
}
} }

@ -0,0 +1,66 @@
package com.example.sshd.service;
import org.apache.commons.lang3.StringUtils;
import org.jivesoftware.whack.ExternalComponentManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.xmpp.component.AbstractComponent;
import org.xmpp.component.ComponentException;
import org.xmpp.packet.Message;
import com.example.sshd.config.XmppComponentConfig;
import jakarta.annotation.PostConstruct;
@Component
public class EchoComponent extends AbstractComponent {
private static final Logger logger = LoggerFactory.getLogger(EchoComponent.class);
@Autowired
XmppComponentConfig xmppComponentConfig;
ExternalComponentManager externalComponentManager = null;
@PostConstruct
public void init() throws ComponentException {
logger.info("Starting up {} ...", xmppComponentConfig);
externalComponentManager = new ExternalComponentManager(xmppComponentConfig.getHost(),
xmppComponentConfig.getPort(), xmppComponentConfig.isStartEncrypted());
externalComponentManager.setMultipleAllowed(xmppComponentConfig.getSubdomainPrefix(), false);
externalComponentManager.setServerName(xmppComponentConfig.getDomain());
externalComponentManager.setSecretKey(xmppComponentConfig.getSubdomainPrefix(),
xmppComponentConfig.getSecretKey());
externalComponentManager.addComponent(xmppComponentConfig.getSubdomainPrefix(), this,
xmppComponentConfig.getPort());
}
@Override
public String getDescription() {
return "XMPP component for doing ECHO";
}
@Override
public String getName() {
return this.getClass().getName();
}
protected void handleMessage(final Message inMsg) {
logger.info("-- RECEIVED -- {}", inMsg);
Message outMsg = new Message();
outMsg.setType(inMsg.getType());
outMsg.setFrom(inMsg.getTo());
if (StringUtils.endsWith(inMsg.getSubject(), "@" + xmppComponentConfig.getDomain())) {
outMsg.setTo(inMsg.getSubject());
} else {
outMsg.setTo(inMsg.getFrom());
}
outMsg.setSubject(inMsg.getSubject());
outMsg.setBody(inMsg.getBody());
externalComponentManager.sendPacket(this, outMsg);
logger.info("-- SENT -- {}", outMsg);
}
}

@ -22,74 +22,74 @@ import org.springframework.stereotype.Service;
@Service @Service
public class GeoIpLocator { public class GeoIpLocator {
private static final Logger logger = LoggerFactory.getLogger(GeoIpLocator.class); private static final Logger logger = LoggerFactory.getLogger(GeoIpLocator.class);
private static final Logger ipInfoLogger = LoggerFactory.getLogger("ip_info"); private static final Logger ipInfoLogger = LoggerFactory.getLogger("ip_info");
@Autowired @Autowired
Map<String, String> ipInfoMapping; Map<String, String> ipInfoMapping;
@Autowired @Autowired
JdbcService jdbcService; JdbcService jdbcService;
@Autowired @Autowired
CloseableHttpAsyncClient asyncClient; CloseableHttpAsyncClient asyncClient;
@Autowired @Autowired
CloseableHttpClient httpClient; CloseableHttpClient httpClient;
@Value("${ssh-server.ip-info-api.url:http://ip-api.com/json/%s}") @Value("${ssh-server.ip-info-api.url:http://ip-api.com/json/%s}")
private String ipInfoApiUrl; private String ipInfoApiUrl;
@Value("${ssh-server.ip-info-api.method:GET}") @Value("${ssh-server.ip-info-api.method:GET}")
private String ipInfoApiMethod; private String ipInfoApiMethod;
public String getIpLocationInfo(String remoteIpAddress) { public String getIpLocationInfo(String remoteIpAddress) {
HttpGet httpGet = new HttpGet(String.format(ipInfoApiUrl, remoteIpAddress)); HttpGet httpGet = new HttpGet(String.format(ipInfoApiUrl, remoteIpAddress));
try { try {
return httpClient.execute(httpGet, new HttpClientResponseHandler<String>() { return httpClient.execute(httpGet, new HttpClientResponseHandler<String>() {
@Override @Override
public String handleResponse(ClassicHttpResponse result) throws HttpException, IOException { public String handleResponse(ClassicHttpResponse result) throws HttpException, IOException {
String body = new String(result.getEntity().getContent().readAllBytes(), StandardCharsets.UTF_8); String body = new String(result.getEntity().getContent().readAllBytes(), StandardCharsets.UTF_8);
logger.info("[{}] httpClient.execute completed, response code: {}, body: {}", remoteIpAddress, logger.info("[{}] httpClient.execute completed, response code: {}, body: {}", remoteIpAddress,
result.getCode(), body); result.getCode(), body);
ipInfoMapping.put(remoteIpAddress, body); ipInfoMapping.put(remoteIpAddress, body);
int inserted = jdbcService.insertRemoteIpInfo(remoteIpAddress, body); int inserted = jdbcService.insertRemoteIpInfo(remoteIpAddress, body);
ipInfoLogger.info("[{}] {}, inserted = {}", remoteIpAddress, ipInfoMapping.get(remoteIpAddress), ipInfoLogger.info("[{}] {}, inserted = {}", remoteIpAddress, ipInfoMapping.get(remoteIpAddress),
inserted); inserted);
return body; return body;
}
});
} catch (IOException e) {
logger.error("[getIpLocationInfo] IO Exception has occurred!", e);
return null;
} }
}
public void asyncUpdateIpLocationInfo(String remoteIpAddress) { });
asyncClient.execute(SimpleHttpRequest.create(ipInfoApiMethod, String.format(ipInfoApiUrl, remoteIpAddress)), } catch (IOException e) {
new FutureCallback<SimpleHttpResponse>() { logger.error("[getIpLocationInfo] IO Exception has occurred!", e);
return null;
@Override
public void completed(SimpleHttpResponse result) {
logger.info("[{}] asyncClient.execute completed, result: {}, content-type: {}, body: {}",
remoteIpAddress, result, result.getContentType(), result.getBodyText());
ipInfoMapping.put(remoteIpAddress, result.getBodyText());
int inserted = jdbcService.insertRemoteIpInfo(remoteIpAddress, result.getBodyText());
ipInfoLogger.info("[{}] {}, inserted = {}", remoteIpAddress, ipInfoMapping.get(remoteIpAddress),
inserted);
}
@Override
public void failed(Exception exception) {
logger.info("[{}] asyncClient.execute failed, exception: {}", remoteIpAddress, exception);
}
@Override
public void cancelled() {
logger.info("[{}] asyncClient.execute cancelled.", remoteIpAddress);
}
});
} }
}
public void asyncUpdateIpLocationInfo(String remoteIpAddress) {
asyncClient.execute(SimpleHttpRequest.create(ipInfoApiMethod, String.format(ipInfoApiUrl, remoteIpAddress)),
new FutureCallback<SimpleHttpResponse>() {
@Override
public void completed(SimpleHttpResponse result) {
logger.info("[{}] asyncClient.execute completed, result: {}, content-type: {}, body: {}",
remoteIpAddress, result, result.getContentType(), result.getBodyText());
ipInfoMapping.put(remoteIpAddress, result.getBodyText());
int inserted = jdbcService.insertRemoteIpInfo(remoteIpAddress, result.getBodyText());
ipInfoLogger.info("[{}] {}, inserted = {}", remoteIpAddress, ipInfoMapping.get(remoteIpAddress),
inserted);
}
@Override
public void failed(Exception exception) {
logger.info("[{}] asyncClient.execute failed, exception: {}", remoteIpAddress, exception);
}
@Override
public void cancelled() {
logger.info("[{}] asyncClient.execute cancelled.", remoteIpAddress);
}
});
}
} }

@ -16,59 +16,59 @@ import jakarta.annotation.PostConstruct;
@Service @Service
public class JdbcService { public class JdbcService {
private static final String createRemoteIpLookupTableSql = "CREATE TABLE IF NOT EXISTS public.remote_ip_lookup (id BIGINT not null, " private static final String createRemoteIpLookupTableSql = "CREATE TABLE IF NOT EXISTS public.remote_ip_lookup (id BIGINT not null, "
+ "remote_ip_address CHARACTER VARYING not null, remote_ip_info CHARACTER VARYING not null, PRIMARY KEY (id));"; + "remote_ip_address CHARACTER VARYING not null, remote_ip_info CHARACTER VARYING not null, PRIMARY KEY (id));";
private static final String createRemoteIpLookupIndexSql = "CREATE INDEX IF NOT EXISTS public.remote_ip_lookup_idx ON " private static final String createRemoteIpLookupIndexSql = "CREATE INDEX IF NOT EXISTS public.remote_ip_lookup_idx ON "
+ "public.remote_ip_lookup (remote_ip_address);"; + "public.remote_ip_lookup (remote_ip_address);";
@Autowired @Autowired
private JdbcTemplate jdbcTemplate; private JdbcTemplate jdbcTemplate;
@PostConstruct @PostConstruct
private void init() { private void init() {
jdbcTemplate.execute(createRemoteIpLookupTableSql); jdbcTemplate.execute(createRemoteIpLookupTableSql);
jdbcTemplate.execute(createRemoteIpLookupIndexSql); jdbcTemplate.execute(createRemoteIpLookupIndexSql);
} }
public String getRemoteIpInfo(String remoteIp) { public String getRemoteIpInfo(String remoteIp) {
var result = jdbcTemplate.query( var result = jdbcTemplate.query(
"SELECT id, remote_ip_address, remote_ip_info from public.remote_ip_lookup WHERE remote_ip_address = ? ", "SELECT id, remote_ip_address, remote_ip_info from public.remote_ip_lookup WHERE remote_ip_address = ? ",
new RowMapper<String>() { new RowMapper<String>() {
@Override @Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException { public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString(3); return rs.getString(3);
} }
}, remoteIp); }, remoteIp);
return result.isEmpty() ? null : result.get(0); return result.isEmpty() ? null : result.get(0);
} }
public List<Map<String, Object>> getAllRemoteIpInfo(String remoteIp) { public List<Map<String, Object>> getAllRemoteIpInfo(String remoteIp) {
return jdbcTemplate.query( return jdbcTemplate.query(
"SELECT id, remote_ip_address, remote_ip_info from public.remote_ip_lookup WHERE remote_ip_address = ? ", "SELECT id, remote_ip_address, remote_ip_info from public.remote_ip_lookup WHERE remote_ip_address = ? ",
new RowMapper<Map<String, Object>>() { new RowMapper<Map<String, Object>>() {
@Override @Override
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException { public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
return Map.of("insert_time", new Date(rs.getLong(1)), "remote_ip_address", rs.getString(2), return Map.of("insert_time", new Date(rs.getLong(1)), "remote_ip_address", rs.getString(2),
"remote_ip_info", rs.getString(3)); "remote_ip_info", rs.getString(3));
} }
}, remoteIp); }, remoteIp);
} }
public List<Map<String, Object>> getAllRemoteIpInfo() { public List<Map<String, Object>> getAllRemoteIpInfo() {
return jdbcTemplate.query( return jdbcTemplate.query(
"SELECT id, remote_ip_address, remote_ip_info from public.remote_ip_lookup order by id", "SELECT id, remote_ip_address, remote_ip_info from public.remote_ip_lookup order by id",
new RowMapper<Map<String, Object>>() { new RowMapper<Map<String, Object>>() {
@Override @Override
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException { public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
return Map.of("insert_time", new Date(rs.getLong(1)), "remote_ip_address", rs.getString(2), return Map.of("insert_time", new Date(rs.getLong(1)), "remote_ip_address", rs.getString(2),
"remote_ip_info", rs.getString(3)); "remote_ip_info", rs.getString(3));
} }
}); });
} }
public int insertRemoteIpInfo(String remoteIpAddress, String remoteIpInfo) { public int insertRemoteIpInfo(String remoteIpAddress, String remoteIpInfo) {
return jdbcTemplate.update( return jdbcTemplate.update(
"INSERT INTO public.remote_ip_lookup (id, remote_ip_address, remote_ip_info) VALUES (?, ?, ?)", "INSERT INTO public.remote_ip_lookup (id, remote_ip_address, remote_ip_info) VALUES (?, ?, ?)",
System.currentTimeMillis(), remoteIpAddress, remoteIpInfo); System.currentTimeMillis(), remoteIpAddress, remoteIpInfo);
} }
} }

@ -24,64 +24,65 @@ import org.springframework.stereotype.Service;
@Service @Service
public class JmxClientService { public class JmxClientService {
private static final Logger logger = LoggerFactory.getLogger(ReplyService.class); private static final Logger logger = LoggerFactory.getLogger(ReplyService.class);
public String process(String[] args) { public String process(String[] args) {
// Example // Example
// 1st parameter: service:jmx:rmi:///jndi/rmi://127.0.0.1:2020/jmxrmi // 1st parameter: service:jmx:rmi:///jndi/rmi://127.0.0.1:2020/jmxrmi
// 2nd parameter: java.lang:type=Memory // 2nd parameter: java.lang:type=Memory
StringBuilder output = new StringBuilder(); StringBuilder output = new StringBuilder();
try { try {
if (args.length > 2) { if (args.length > 2) {
Runtime.getRuntime().freeMemory(); Runtime.getRuntime().freeMemory();
System.out.println("Connection to JMX kafka..."); System.out.println("Connection to JMX kafka...");
JMXServiceURL url = new JMXServiceURL(args[1]); JMXServiceURL url = new JMXServiceURL(args[1]);
JMXConnector jmxc = JMXConnectorFactory.connect(url, null); JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection(); MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
ObjectName mbeanName = new ObjectName(args[2]); ObjectName mbeanName = new ObjectName(args[2]);
MBeanInfo info = mbsc.getMBeanInfo(mbeanName); MBeanInfo info = mbsc.getMBeanInfo(mbeanName);
MBeanAttributeInfo[] attribute = info.getAttributes(); MBeanAttributeInfo[] attribute = info.getAttributes();
logger.info("[process] args.length: {}", args.length); logger.info("[process] args.length: {}", args.length);
if (args.length > 3) { if (args.length > 3) {
for (MBeanAttributeInfo attr : attribute) { for (MBeanAttributeInfo attr : attribute) {
List<Attribute> alist = mbsc.getAttributes(mbeanName, new String[] { attr.getName() }).asList(); List<Attribute> alist = mbsc.getAttributes(mbeanName, new String[] { attr.getName() }).asList();
if (args[3].equals(attr.getName())) { if (args[3].equals(attr.getName())) {
Optional<Map<String, Object>> opt = alist.stream().filter(a -> a.getName().equals(args[3])) Optional<Map<String, Object>> opt = alist.stream().filter(a -> a.getName().equals(args[3]))
.map(a -> toMap((CompositeData) a.getValue())).findFirst(); .map(a -> toMap((CompositeData) a.getValue())).findFirst();
if (opt.isPresent()) { if (opt.isPresent()) {
output.append(attr.getName() + ": " + opt.get() + "\r\n"); output.append(attr.getName() + ": " + opt.get() + "\r\n");
} }
}
}
} else {
for (MBeanAttributeInfo attr : attribute) {
List<Attribute> alist = mbsc.getAttributes(mbeanName, new String[] { attr.getName() }).asList();
output.append(attr.getName() + ": " + alist + "\r\n");
}
}
jmxc.close();
} else {
output.append("Example: jmx_client service:jmx:rmi:///jndi/rmi://127.0.0.1:2020/jmxrmi java.lang:type=Memory HeapMemoryUsage\r\n");
} }
} catch (Exception e) { }
logger.error("process cmd failed: {}", Arrays.asList(args), e); } else {
for (MBeanAttributeInfo attr : attribute) {
List<Attribute> alist = mbsc.getAttributes(mbeanName, new String[] { attr.getName() }).asList();
output.append(attr.getName() + ": " + alist + "\r\n");
}
} }
return output.toString(); jmxc.close();
} else {
output.append(
"Example: jmx_client service:jmx:rmi:///jndi/rmi://127.0.0.1:2020/jmxrmi java.lang:type=Memory HeapMemoryUsage\r\n");
}
} catch (Exception e) {
logger.error("process cmd failed: {}", Arrays.asList(args), e);
} }
return output.toString();
}
public static Map<String, Object> toMap(CompositeData cd) { public static Map<String, Object> toMap(CompositeData cd) {
if (cd == null) if (cd == null)
throw new IllegalArgumentException("composite data should not be null"); throw new IllegalArgumentException("composite data should not be null");
Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>();
Set<String> itemNames = cd.getCompositeType().keySet(); Set<String> itemNames = cd.getCompositeType().keySet();
for (String itemName : itemNames) { for (String itemName : itemNames) {
Object item = cd.get(itemName); Object item = cd.get(itemName);
map.put(itemName, item); map.put(itemName, item);
}
return map;
} }
return map;
}
} }

@ -25,118 +25,118 @@ import org.springframework.stereotype.Service;
@Service @Service
public class ReplyService { public class ReplyService {
private static final Logger logger = LoggerFactory.getLogger(ReplyService.class); private static final Logger logger = LoggerFactory.getLogger(ReplyService.class);
private static final Logger notFoundLogger = LoggerFactory.getLogger("not_found"); private static final Logger notFoundLogger = LoggerFactory.getLogger("not_found");
@Autowired @Autowired
Properties hashReplies; Properties hashReplies;
@Autowired @Autowired
Properties regexMapping; Properties regexMapping;
@Autowired @Autowired
Map<String, String> ipInfoMapping; Map<String, String> ipInfoMapping;
@Autowired @Autowired
JdbcService jdbcService; JdbcService jdbcService;
@Autowired @Autowired
GeoIpLocator geoIpLocator; GeoIpLocator geoIpLocator;
@Autowired @Autowired
JmxClientService jmxClientService; JmxClientService jmxClientService;
public boolean replyToCommand(String command, OutputStream out, String prompt, ServerSession session) public boolean replyToCommand(String command, OutputStream out, String prompt, ServerSession session)
throws IOException { throws IOException {
String cmdHash = DigestUtils.md5Hex(command.trim()).toUpperCase(); String cmdHash = DigestUtils.md5Hex(command.trim()).toUpperCase();
if (StringUtils.equalsIgnoreCase(command.trim(), "my_geolocation")) { if (StringUtils.equalsIgnoreCase(command.trim(), "my_geolocation")) {
logger.info("[{}] my_geolocation command detected: {}", cmdHash, command.trim()); logger.info("[{}] my_geolocation command detected: {}", cmdHash, command.trim());
out.write(String.format("\r\n%s\r\n%s", ipInfoMapping.get(Thread.currentThread().getName()), prompt) out.write(String.format("\r\n%s\r\n%s", ipInfoMapping.get(Thread.currentThread().getName()), prompt)
.getBytes()); .getBytes());
} else if (StringUtils.equalsIgnoreCase(command.trim(), "whoami")) { } else if (StringUtils.equalsIgnoreCase(command.trim(), "whoami")) {
logger.info("[{}] whoami command detected: {}", cmdHash, command.trim()); logger.info("[{}] whoami command detected: {}", cmdHash, command.trim());
out.write(String.format("\r\n%s\r\n%s", session.getUsername(), prompt).getBytes()); out.write(String.format("\r\n%s\r\n%s", session.getUsername(), prompt).getBytes());
} else if (StringUtils.equalsIgnoreCase(command.trim(), "online_geolocations")) { } else if (StringUtils.equalsIgnoreCase(command.trim(), "online_geolocations")) {
logger.info("[{}] online_geolocations command detected: {}", cmdHash, command.trim()); logger.info("[{}] online_geolocations command detected: {}", cmdHash, command.trim());
out.write(String.format("\r\n%s\r\n%s", ipInfoMapping.toString(), prompt).getBytes()); out.write(String.format("\r\n%s\r\n%s", ipInfoMapping.toString(), prompt).getBytes());
} else if (StringUtils.equalsIgnoreCase(StringUtils.split(command.trim(), " ")[0], "jmx_client")) { } else if (StringUtils.equalsIgnoreCase(StringUtils.split(command.trim(), " ")[0], "jmx_client")) {
String remoteJmxResponse = jmxClientService.process(StringUtils.split(command.trim(), " ")); String remoteJmxResponse = jmxClientService.process(StringUtils.split(command.trim(), " "));
logger.info("[{}] jmx_client command detected: {}", cmdHash, command.trim()); logger.info("[{}] jmx_client command detected: {}", cmdHash, command.trim());
out.write(String.format("\r\n%s\r\n%s", remoteJmxResponse, prompt).getBytes()); out.write(String.format("\r\n%s\r\n%s", remoteJmxResponse, prompt).getBytes());
} else if (StringUtils.split(command.trim(), " ").length == 2 } else if (StringUtils.split(command.trim(), " ").length == 2
&& StringUtils.equalsIgnoreCase(StringUtils.split(command.trim(), " ")[0], "get_geolocation")) { && StringUtils.equalsIgnoreCase(StringUtils.split(command.trim(), " ")[0], "get_geolocation")) {
String remoteIpInfo = StringUtils.getIfBlank( String remoteIpInfo = StringUtils.getIfBlank(
jdbcService.getRemoteIpInfo(StringUtils.split(command.trim(), " ")[1]), jdbcService.getRemoteIpInfo(StringUtils.split(command.trim(), " ")[1]),
() -> geoIpLocator.getIpLocationInfo(StringUtils.split(command.trim(), " ")[1])); () -> geoIpLocator.getIpLocationInfo(StringUtils.split(command.trim(), " ")[1]));
logger.info("[{}] get_geolocation command detected: {}", cmdHash, command.trim()); logger.info("[{}] get_geolocation command detected: {}", cmdHash, command.trim());
out.write(String.format("\r\n%s\r\n%s", remoteIpInfo, prompt).getBytes()); out.write(String.format("\r\n%s\r\n%s", remoteIpInfo, prompt).getBytes());
} else if (StringUtils.equalsIgnoreCase(command.trim(), "all_geolocations")) { } else if (StringUtils.equalsIgnoreCase(command.trim(), "all_geolocations")) {
logger.info("[{}] all_geolocations command detected: {}", cmdHash, command.trim()); logger.info("[{}] all_geolocations command detected: {}", cmdHash, command.trim());
out.write(String.format("\r\n%s\r\n%s", jdbcService.getAllRemoteIpInfo(), prompt).getBytes()); out.write(String.format("\r\n%s\r\n%s", jdbcService.getAllRemoteIpInfo(), prompt).getBytes());
} else if (StringUtils.equalsIgnoreCase(command.trim(), "exit") } else if (StringUtils.equalsIgnoreCase(command.trim(), "exit")
|| StringUtils.equalsIgnoreCase(command.trim(), "quit")) { || StringUtils.equalsIgnoreCase(command.trim(), "quit")) {
logger.info("[{}] Exiting command detected: {}", cmdHash, command.trim()); logger.info("[{}] Exiting command detected: {}", cmdHash, command.trim());
out.write(String.format("\r\nExiting...\r\n%s", prompt).getBytes()); out.write(String.format("\r\nExiting...\r\n%s", prompt).getBytes());
return true; return true;
} else if (hashReplies.containsKey(command.trim())) { } else if (hashReplies.containsKey(command.trim())) {
logger.info("[{}] Known command detected: {}", cmdHash, command.trim()); logger.info("[{}] Known command detected: {}", cmdHash, command.trim());
String reply = hashReplies.getProperty(command.trim()).replace("\\r", "\r").replace("\\n", "\n") String reply = hashReplies.getProperty(command.trim()).replace("\\r", "\r").replace("\\n", "\n")
.replace("\\t", "\t"); .replace("\\t", "\t");
out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes()); out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes());
} else if (hashReplies.containsKey(cmdHash)) { } else if (hashReplies.containsKey(cmdHash)) {
logger.info("[{}] Known command-hash detected: {}", cmdHash, command.trim()); logger.info("[{}] Known command-hash detected: {}", cmdHash, command.trim());
String reply = hashReplies.getProperty(cmdHash).replace("\\r", "\r").replace("\\n", "\n").replace("\\t", String reply = hashReplies.getProperty(cmdHash).replace("\\r", "\r").replace("\\n", "\n").replace("\\t",
"\t"); "\t");
out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes()); out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes());
} else if (hashReplies.containsKey(String.format("base64(%s)", cmdHash))) { } else if (hashReplies.containsKey(String.format("base64(%s)", cmdHash))) {
logger.info("[{}] Known base64-hash detected: {}", cmdHash, command.trim()); logger.info("[{}] Known base64-hash detected: {}", cmdHash, command.trim());
String reply = hashReplies.getProperty(String.format("base64(%s)", cmdHash)); String reply = hashReplies.getProperty(String.format("base64(%s)", cmdHash));
reply = new String(Base64.decodeBase64(reply)); reply = new String(Base64.decodeBase64(reply));
out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes()); out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes());
} else {
Optional<Pair<String, String>> o = regexMapping.entrySet().stream()
.filter(e -> command.trim().matches(((String) e.getKey())))
.map(e -> Pair.of((String) e.getKey(), (String) e.getValue())).findAny();
if (o.isPresent()) {
String reply = hashReplies.getProperty(o.get().getRight(), "").replace("\\r", "\r").replace("\\n", "\n")
.replace("\\t", "\t");
if (reply.isEmpty()) {
logger.info("[{}] Execute cmd for real: {} ({})", cmdHash, command.trim(), o.get());
ByteArrayOutputStream tempOut = new ByteArrayOutputStream();
try {
CommandLine cmdLine = CommandLine.parse(command.trim());
DefaultExecutor executor = DefaultExecutor.builder().get();
PumpStreamHandler streamHandler = new PumpStreamHandler(tempOut);
executor.setStreamHandler(streamHandler);
int exitValue = executor.execute(cmdLine);
logger.info("[{}] Result: {} ({})", cmdHash, command.trim(), exitValue);
reply = new String(tempOut.toByteArray()).replace("\n", "\r\n");
} catch (ExecuteException e) {
logger.info("[{}] Execute cmd failed: {} ({})", cmdHash, command.trim(), o.get(), e);
}
out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes());
} else { } else {
Optional<Pair<String, String>> o = regexMapping.entrySet().stream() logger.info("[{}] Known pattern detected: {} ({})", cmdHash, command.trim(), o.get());
.filter(e -> command.trim().matches(((String) e.getKey()))) out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes());
.map(e -> Pair.of((String) e.getKey(), (String) e.getValue())).findAny();
if (o.isPresent()) {
String reply = hashReplies.getProperty(o.get().getRight(), "").replace("\\r", "\r").replace("\\n", "\n")
.replace("\\t", "\t");
if (reply.isEmpty()) {
logger.info("[{}] Execute cmd for real: {} ({})", cmdHash, command.trim(), o.get());
ByteArrayOutputStream tempOut = new ByteArrayOutputStream();
try {
CommandLine cmdLine = CommandLine.parse(command.trim());
DefaultExecutor executor = DefaultExecutor.builder().get();
PumpStreamHandler streamHandler = new PumpStreamHandler(tempOut);
executor.setStreamHandler(streamHandler);
int exitValue = executor.execute(cmdLine);
logger.info("[{}] Result: {} ({})", cmdHash, command.trim(), exitValue);
reply = new String(tempOut.toByteArray()).replace("\n", "\r\n");
} catch (ExecuteException e) {
logger.info("[{}] Execute cmd failed: {} ({})", cmdHash, command.trim(), o.get(), e);
}
out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes());
} else {
logger.info("[{}] Known pattern detected: {} ({})", cmdHash, command.trim(), o.get());
out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes());
}
} else {
logger.info("[{}] Command not found: {}", cmdHash, command.trim());
notFoundLogger.info("[{}] Command not found: {}", cmdHash, command.trim());
out.write(String.format("\r\nCommand '%s' not found. Try 'exit'.\r\n%s", command.trim(), prompt)
.getBytes());
}
} }
return false; } else {
logger.info("[{}] Command not found: {}", cmdHash, command.trim());
notFoundLogger.info("[{}] Command not found: {}", cmdHash, command.trim());
out.write(String.format("\r\nCommand '%s' not found. Try 'exit'.\r\n%s", command.trim(), prompt)
.getBytes());
}
} }
return false;
}
} }

Loading…
Cancel
Save