1 Commits

Author SHA1 Message Date
Ryan Michela
cac1ed8697 Implemented IP whitelisting 2014-07-21 23:57:09 -07:00
26 changed files with 590 additions and 941 deletions

View File

@@ -1,68 +0,0 @@
---
#BasedOnStyle: WebKit
TabWidth: '4'
IndentWidth: '4'
UseTab: 'Always'
AlignOperands: 'true'
AlignAfterOpenBracket: 'Align'
AlignConsecutiveAssignments: 'true'
AlignConsecutiveDeclarations: 'true'
AlignEscapedNewlines: 'Left'
AlignTrailingComments: 'true'
AllowAllParametersOfDeclarationOnNextLine: 'true'
AllowShortBlocksOnASingleLine: 'false'
AllowShortCaseLabelsOnASingleLine: 'false'
AllowShortFunctionsOnASingleLine: 'All'
AllowShortIfStatementsOnASingleLine: 'false'
AllowShortLoopsOnASingleLine: 'false'
AlwaysBreakAfterReturnType: 'None'
AlwaysBreakTemplateDeclarations: 'true'
AlwaysBreakBeforeMultilineStrings: 'false'
BinPackArguments: 'false'
BinPackParameters: 'false'
BreakBeforeBraces: 'Custom'
BraceWrapping:
AfterEnum: 'true'
AfterClass: 'true'
AfterControlStatement: 'true'
AfterStruct: 'true'
AfterFunction: 'true'
AfterNamespace: 'true'
AfterUnion: 'true'
AfterExternBlock: 'true'
BeforeCatch: 'true'
BeforeElse: 'true'
SplitEmptyRecord: 'false'
SplitEmptyNamespace: 'false'
SplitEmptyFunction: 'false'
BreakBeforeBinaryOperators: 'true'
BreakBeforeTernaryOperators: 'false'
BreakConstructorInitializersBeforeComma: 'false'
BreakBeforeInheritanceComma: 'false'
BreakStringLiterals: 'true'
ColumnLimit: '140'
CompactNamespaces: 'false'
Cpp11BracedListStyle: 'true'
ConstructorInitializerAllOnOneLineOrOnePerLine: 'false'
DerivePointerAlignment: 'false'
IndentCaseLabels: 'true'
IndentPPDirectives: 'AfterHash'
KeepEmptyLinesAtTheStartOfBlocks: 'true'
Language: 'Java'
NamespaceIndentation: 'All'
PointerAlignment: 'Right'
ReflowComments: 'true'
SortIncludes: 'true'
SortUsingDeclarations: 'true'
SpaceAfterCStyleCast: 'false'
SpaceAfterTemplateKeyword: 'false'
SpaceBeforeAssignmentOperators: 'true'
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: 'false'
SpacesInAngles: 'false'
SpacesInCStyleCastParentheses: 'false'
SpacesInContainerLiterals: 'false'
SpacesInParentheses: 'false'
SpacesInSquareBrackets: 'false'
Standard: 'Auto'
...

View File

@@ -1,5 +0,0 @@
sudo: false
dist: trusty
language: java
jdk:
- oraclejdk8

View File

@@ -1,70 +1,4 @@
Spigot-SSHD Bukkit-SSHD
=========== ===========
[![Build Status](https://travis-ci.org/Justasic/Spigot-SSHD.svg?branch=master)](https://travis-ci.org/Justasic/Spigot-SSHD) An SSHD daemon embedded in a Bukkit plugin.
Have you ever wished you could remotely access your server's admin console without having to setup a complex remote access system? Now you can with SSHD.
SSHD securely exposes your Spigot admin console using the SSH protocol - the same protocol that serves as the secure foundation for nearly all remote server administration.
- Compatible with all ssh clients, regardless of operating system.
- Remotely view your server log in real-time.
- Remotely issue commands from the server console, just as if you were on the server itself.
- Supports multiple concurrent remote connections.
- Strong identity support using public key authentication.
- Remotely script your server by issuing one-off console commands with ssh.
## Why should I use SSHD?
- Your server runs on Windows.
- You are in a shared hosting environment that only gives you access to the - log files.
- You want to share access to your server console, but don't want to give anybody access to the machine its running on.
- You always wanted to use RCON, but want to see the server log as well.
- You are tired of running your server in a Screen session.
- You just want to access your server console using SSH.
## Configuration
- **listenAddress** - The network interface(s) SSHD should listen on. (Default all)
- **port** - Specify the port SSHD should listen on. (Default 22)
- **username/password** - The credentials used to log into the server console. (Default blank)
Note: By default, only public key authentication is enabled. This is the most secure authentication mode! Setting a username and password will make your server less secure.
## Setting Up Public Key Authentication
Setting up public key authentication with SSH requires first generating a public and private key pair and then installing just the public key on your Spigot server.
On Windows
1. TODO
On Linux/OS X
1. TODO
## Commands
None - just install and go.
## Permissions
None - SSHD uses cryptographic certificates or a secure username and password to verify remote access.
## Source Code
[Get the source on GitHub](https://github.com/Justasic/Spigot-SSHD "Source Code")
## Metrics
This plugin utilizes Hidendra's plugin metrics system. the following information is collected and sent to mcstats.org unless opted out:
- A unique identifier
- The server's version of Java
- Whether the server is in offline or online mode
- Plugin's version
- Server's version
- OS version/name and architecture
- core count for the CPU
- Number of players online
- Metrics version
Opting out of this service can be done by editing plugins/Plugin Metrics/config.yml and changing opt-out to true.

140
pom.xml
View File

@@ -5,20 +5,15 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.ryanmichela</groupId> <groupId>com.ryanmichela</groupId>
<artifactId>sshd</artifactId> <artifactId>SSHD</artifactId>
<version>1.3.5</version> <version>1.2</version>
<url>https://github.com/Justasic/Bukkit-SSHD/</url> <url>http://dev.bukkit.org/server-mods/sshd/</url>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- Repositories --> <!-- Repositories -->
<repositories> <repositories>
<repository> <repository>
<id>spigot-repo</id> <id>bukkit-repo</id>
<url>https://hub.spigotmc.org/nexus/content/groups/public</url> <url>http://repo.bukkit.org/content/groups/public/</url>
</repository> </repository>
</repositories> </repositories>
@@ -34,135 +29,58 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.bukkit</groupId> <groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId> <artifactId>craftbukkit</artifactId>
<version>1.14.4-R0.1-SNAPSHOT</version> <version>1.7.9-R0.2</version>
<scope>provided</scope>
<type>jar</type>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.sshd</groupId> <groupId>org.apache.sshd</groupId>
<artifactId>sshd-core</artifactId> <artifactId>sshd-core</artifactId>
<version>2.3.0</version> <version>0.9.0</version>
<scope>compile</scope> <scope>compile</scope>
<type>jar</type> <type>jar</type>
</dependency> </dependency>
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-mina</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-common</artifactId>
<version>2.3.0</version>
<scope>compile</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-sftp</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>net.i2p.crypto</groupId>
<artifactId>eddsa</artifactId>
<version>0.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-core</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.28</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.7.28</version>
</dependency>
<dependency>
<groupId>jline</groupId>
<artifactId>jline</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
<!-- Build --> <!-- Build -->
<build> <build>
<defaultGoal>clean package</defaultGoal>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources</directory>
<includes>
<include>plugin.yml</include>
<include>config.yml</include>
</includes>
</resource>
</resources>
<plugins> <plugins>
<!-- Shade plugin -->
<plugin> <plugin>
<artifactId>maven-assembly-plugin</artifactId> <groupId>org.apache.maven.plugins</groupId>
<version>3.1.1</version> <artifactId>maven-shade-plugin</artifactId>
<version>1.5</version>
<executions> <executions>
<execution> <execution>
<phase>package</phase> <phase>package</phase>
<goals> <goals>
<goal>single</goal> <goal>shade</goal>
</goals> </goals>
</execution> </execution>
</executions> </executions>
<configuration> <configuration>
<finalName>${project.name}-${project.version}</finalName> <filters>
<appendAssemblyId>false</appendAssemblyId> <filter>
<descriptorRefs> <artifact>*:*</artifact>
<descriptorRef>jar-with-dependencies</descriptorRef> <excludes>
</descriptorRefs> <exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
<minimizeJar>true</minimizeJar>
</configuration> </configuration>
</plugin> </plugin>
<!-- Compile plugin --> <!-- Compile plugin -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version> <version>3.0</version>
<configuration> <configuration>
<source>1.8</source> <source>1.6</source>
<target>1.8</target> <target>1.6</target>
<showDeprecation>true</showDeprecation> <showDeprecation>true</showDeprecation>
</configuration> </configuration>
</plugin> </plugin>

View File

@@ -0,0 +1,142 @@
/*
* The MIT License
*
* Copyright (c) 2013 Edin Dazdarevic (edin.dazdarevic@gmail.com)
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* */
package com.ryanmichela.sshd;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* A class that enables to get an IP range from CIDR specification. It supports
* both IPv4 and IPv6.
*/
public class CIDRUtils {
private final String cidr;
private InetAddress inetAddress;
private InetAddress startAddress;
private InetAddress endAddress;
private final int prefixLength;
public CIDRUtils(String cidr) throws UnknownHostException {
this.cidr = cidr;
/* split CIDR to address and prefix part */
if (this.cidr.contains("/")) {
int index = this.cidr.indexOf("/");
String addressPart = this.cidr.substring(0, index);
String networkPart = this.cidr.substring(index + 1);
inetAddress = InetAddress.getByName(addressPart);
prefixLength = Integer.parseInt(networkPart);
calculate();
} else {
throw new IllegalArgumentException("not an valid CIDR format!");
}
}
private void calculate() throws UnknownHostException {
ByteBuffer maskBuffer;
int targetSize;
if (inetAddress.getAddress().length == 4) {
maskBuffer =
ByteBuffer
.allocate(4)
.putInt(-1);
targetSize = 4;
} else {
maskBuffer = ByteBuffer.allocate(16)
.putLong(-1L)
.putLong(-1L);
targetSize = 16;
}
BigInteger mask = (new BigInteger(1, maskBuffer.array())).not().shiftRight(prefixLength);
ByteBuffer buffer = ByteBuffer.wrap(inetAddress.getAddress());
BigInteger ipVal = new BigInteger(1, buffer.array());
BigInteger startIp = ipVal.and(mask);
BigInteger endIp = startIp.add(mask.not());
byte[] startIpArr = toBytes(startIp.toByteArray(), targetSize);
byte[] endIpArr = toBytes(endIp.toByteArray(), targetSize);
this.startAddress = InetAddress.getByAddress(startIpArr);
this.endAddress = InetAddress.getByAddress(endIpArr);
}
private byte[] toBytes(byte[] array, int targetSize) {
int counter = 0;
List<Byte> newArr = new ArrayList<Byte>();
while (counter < targetSize && (array.length - 1 - counter >= 0)) {
newArr.add(0, array[array.length - 1 - counter]);
counter++;
}
int size = newArr.size();
for (int i = 0; i < (targetSize - size); i++) {
newArr.add(0, (byte) 0);
}
byte[] ret = new byte[newArr.size()];
for (int i = 0; i < newArr.size(); i++) {
ret[i] = newArr.get(i);
}
return ret;
}
public String getNetworkAddress() {
return this.startAddress.getHostAddress();
}
public String getBroadcastAddress() {
return this.endAddress.getHostAddress();
}
public boolean isInRange(String ipAddress) throws UnknownHostException {
InetAddress address = InetAddress.getByName(ipAddress);
BigInteger start = new BigInteger(1, this.startAddress.getAddress());
BigInteger end = new BigInteger(1, this.endAddress.getAddress());
BigInteger target = new BigInteger(1, address.getAddress());
int st = start.compareTo(target);
int te = target.compareTo(end);
return (st == -1 || st == 0) && (te == -1 || te == 0);
}
}

View File

@@ -1,6 +1,6 @@
package com.ryanmichela.sshd; package com.ryanmichela.sshd;
import org.apache.sshd.server.auth.password.PasswordAuthenticator; import org.apache.sshd.server.PasswordAuthenticator;
import org.apache.sshd.server.session.ServerSession; import org.apache.sshd.server.session.ServerSession;
import java.util.HashMap; import java.util.HashMap;
@@ -9,38 +9,31 @@ import java.util.Map;
/** /**
* Copyright 2013 Ryan Michela * Copyright 2013 Ryan Michela
*/ */
public class ConfigPasswordAuthenticator implements PasswordAuthenticator { public class ConfigPasswordAuthenticator extends IpFilteredAuthenticator implements PasswordAuthenticator {
private Map<String, Integer> failCounts = new HashMap<String, Integer>();
private Map<String, Integer> FailCounts = new HashMap<String, Integer>();
@Override @Override
public boolean authenticate(String username, String password, ServerSession ss) public boolean authenticate(String username, String password, ServerSession serverSession) {
{ if (!ipAddressIsApproved(serverSession)) return false;
if (SshdPlugin.instance.getConfig().getString("Credentials." + username).equals(password))
{ if (SshdPlugin.instance.getConfig().getString("credentials." + username).equals(password)) {
FailCounts.put(username, 0); failCounts.put(username, 0);
return true; return true;
} }
SshdPlugin.instance.getLogger().info("Failed login for " + username + " using password authentication."); SshdPlugin.instance.getLogger().info("Failed login for " + username + " using password authentication.");
Integer tries = SshdPlugin.instance.getConfig().getInt("LoginRetries"); try {
try
{
Thread.sleep(3000); Thread.sleep(3000);
if (this.FailCounts.containsKey(username)) if (failCounts.containsKey(username)) {
this.FailCounts.put(username, this.FailCounts.get(username) + 1); failCounts.put(username, failCounts.get(username) + 1);
else } else {
this.FailCounts.put(username, 1); failCounts.put(username, 1);
if (this.FailCounts.get(username) >= tries)
{
this.FailCounts.put(username, 0);
ss.close(true);
} }
if (failCounts.get(username) >= 3) {
failCounts.put(username, 0);
serverSession.close(true);
} }
catch (InterruptedException e) } catch (InterruptedException e) {
{
// do nothing // do nothing
} }
return false; return false;

View File

@@ -4,16 +4,15 @@ package com.ryanmichela.sshd;
* Copyright 2013 Ryan Michela * Copyright 2013 Ryan Michela
*/ */
import jline.console.completer.Completer;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandMap; import org.bukkit.command.CommandMap;
import org.bukkit.craftbukkit.libs.jline.console.completer.Completer;
import java.util.List; import java.util.List;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.logging.Level; import java.util.logging.Level;
public class ConsoleCommandCompleter implements Completer { public class ConsoleCommandCompleter implements Completer {
public int complete(final String buffer, final int cursor, final List<CharSequence> candidates) { public int complete(final String buffer, final int cursor, final List<CharSequence> candidates) {
Waitable<List<String>> waitable = new Waitable<List<String>>() { Waitable<List<String>> waitable = new Waitable<List<String>>() {
@Override @Override

View File

@@ -1,8 +1,7 @@
package com.ryanmichela.sshd; package com.ryanmichela.sshd;
import org.apache.sshd.server.command.Command; import org.apache.sshd.server.Command;
import org.apache.sshd.server.command.CommandFactory; import org.apache.sshd.server.CommandFactory;
import org.apache.sshd.server.channel.ChannelSession;
import org.apache.sshd.server.Environment; import org.apache.sshd.server.Environment;
import org.apache.sshd.server.ExitCallback; import org.apache.sshd.server.ExitCallback;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@@ -15,14 +14,12 @@ import java.io.OutputStream;
* Copyright 2013 Ryan Michela * Copyright 2013 Ryan Michela
*/ */
public class ConsoleCommandFactory implements CommandFactory { public class ConsoleCommandFactory implements CommandFactory {
@Override @Override
public Command createCommand(ChannelSession cs, String command) { public Command createCommand(String command) {
return new ConsoleCommand(command); return new ConsoleCommand(command);
} }
public class ConsoleCommand implements Command { public class ConsoleCommand implements Command {
private String command; private String command;
private InputStream in; private InputStream in;
@@ -51,10 +48,9 @@ public class ConsoleCommandFactory implements CommandFactory {
} }
@Override @Override
public void start(ChannelSession cs, Environment environment) throws IOException { public void start(Environment environment) throws IOException {
try { try {
SshdPlugin.instance.getLogger() SshdPlugin.instance.getLogger().info("[U: " + environment.getEnv().get(Environment.ENV_USER) + "] " + command);
.info("[U: " + environment.getEnv().get(Environment.ENV_USER) + "] " + command);
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
} catch (Exception e) { } catch (Exception e) {
SshdPlugin.instance.getLogger().severe("Error processing command from SSH -" + e.getMessage()); SshdPlugin.instance.getLogger().severe("Error processing command from SSH -" + e.getMessage());
@@ -64,6 +60,8 @@ public class ConsoleCommandFactory implements CommandFactory {
} }
@Override @Override
public void destroy(ChannelSession cn) {} public void destroy() {
}
} }
} }

View File

@@ -4,80 +4,25 @@ package com.ryanmichela.sshd;
* Copyright 2013 Ryan Michela * Copyright 2013 Ryan Michela
*/ */
import org.bukkit.ChatColor;
import org.fusesource.jansi.Ansi;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.EnumMap;
import java.util.Map;
import java.util.logging.Formatter; import java.util.logging.Formatter;
import java.util.logging.LogRecord; import java.util.logging.LogRecord;
public class ConsoleLogFormatter extends Formatter { public class ConsoleLogFormatter extends Formatter {
private SimpleDateFormat dateFormat; private SimpleDateFormat dateFormat;
private static final Map<ChatColor, String> replacements = new EnumMap<ChatColor, String>(ChatColor.class);
public ConsoleLogFormatter() { public ConsoleLogFormatter() {
this.dateFormat = new SimpleDateFormat("HH:mm:ss"); this.dateFormat = new SimpleDateFormat("HH:mm:ss");
} }
public static String ColorizeString(String str)
{
// ORIGINAL CODE FROM org.bukkit.craftbukkit.command.ColouredConsoleSender
replacements.put(ChatColor.BLACK, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLACK).boldOff().toString());
replacements.put(ChatColor.DARK_BLUE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLUE).boldOff().toString());
replacements.put(ChatColor.DARK_GREEN, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.GREEN).boldOff().toString());
replacements.put(ChatColor.DARK_AQUA, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.CYAN).boldOff().toString());
replacements.put(ChatColor.DARK_RED, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.RED).boldOff().toString());
replacements.put(ChatColor.DARK_PURPLE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.MAGENTA).boldOff().toString());
replacements.put(ChatColor.GOLD, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.YELLOW).boldOff().toString());
replacements.put(ChatColor.GRAY, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.WHITE).boldOff().toString());
replacements.put(ChatColor.DARK_GRAY, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLACK).bold().toString());
replacements.put(ChatColor.BLUE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLUE).bold().toString());
replacements.put(ChatColor.GREEN, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.GREEN).bold().toString());
replacements.put(ChatColor.AQUA, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.CYAN).bold().toString());
replacements.put(ChatColor.RED, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.RED).bold().toString());
replacements.put(ChatColor.LIGHT_PURPLE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.MAGENTA).bold().toString());
replacements.put(ChatColor.YELLOW, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.YELLOW).bold().toString());
replacements.put(ChatColor.WHITE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.WHITE).bold().toString());
replacements.put(ChatColor.MAGIC, Ansi.ansi().a(Ansi.Attribute.BLINK_SLOW).toString());
replacements.put(ChatColor.BOLD, Ansi.ansi().a(Ansi.Attribute.UNDERLINE_DOUBLE).toString());
replacements.put(ChatColor.STRIKETHROUGH, Ansi.ansi().a(Ansi.Attribute.STRIKETHROUGH_ON).toString());
replacements.put(ChatColor.UNDERLINE, Ansi.ansi().a(Ansi.Attribute.UNDERLINE).toString());
replacements.put(ChatColor.ITALIC, Ansi.ansi().a(Ansi.Attribute.ITALIC).toString());
replacements.put(ChatColor.RESET, Ansi.ansi().a(Ansi.Attribute.RESET).toString());
String result = str;
for (ChatColor color : ChatColor.values())
{
if (replacements.containsKey(color))
{
result = result.replaceAll("(?i)" + color.toString(), replacements.get(color));
}
else
{
result = result.replaceAll("(?i)" + color.toString(), "");
}
}
result += Ansi.ansi().reset().toString();
return result;
}
public String format(LogRecord logrecord) { public String format(LogRecord logrecord) {
try {
Class.forName("org.bukkit.craftbukkit.command.ColouredConsoleSender");
} catch (ClassNotFoundException ignored) {
// MEANS WE'RE ON PAPER/TACO/OTHER SHIT
colorize(logrecord);
}
StringBuilder stringbuilder = new StringBuilder(); StringBuilder stringbuilder = new StringBuilder();
stringbuilder.append(" ["); stringbuilder.append(" [");
stringbuilder.append(this.dateFormat.format(logrecord.getMillis())).append(" "); stringbuilder.append(this.dateFormat.format(Long.valueOf(logrecord.getMillis()))).append(" ");
stringbuilder.append(logrecord.getLevel().getName()).append("]: "); stringbuilder.append(logrecord.getLevel().getName()).append("]: ");
stringbuilder.append(this.formatMessage(logrecord)); stringbuilder.append(this.formatMessage(logrecord));
@@ -93,11 +38,5 @@ public class ConsoleLogFormatter extends Formatter {
return stringbuilder.toString(); return stringbuilder.toString();
} }
private void colorize(LogRecord logrecord)
{
String result = ColorizeString(logrecord.getMessage());
logrecord.setMessage(result);
}
} }

View File

@@ -1,39 +1,26 @@
package com.ryanmichela.sshd; package com.ryanmichela.sshd;
import com.ryanmichela.sshd.ConsoleCommandCompleter;
import com.ryanmichela.sshd.ConsoleLogFormatter;
import com.ryanmichela.sshd.FlushyOutputStream;
import com.ryanmichela.sshd.FlushyStreamHandler;
import com.ryanmichela.sshd.SshTerminal;
import com.ryanmichela.sshd.SshdPlugin;
import com.ryanmichela.sshd.StreamHandlerAppender;
import com.ryanmichela.sshd.implementations.SSHDCommandSender;
import com.ryanmichela.sshd.ConsoleLogFormatter;
import jline.console.ConsoleReader;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.core.Logger;
import org.apache.sshd.common.Factory; import org.apache.sshd.common.Factory;
import org.apache.sshd.server.shell.ShellFactory; import org.apache.sshd.server.Command;
import org.apache.sshd.server.command.Command;
import org.apache.sshd.server.channel.ChannelSession;
import org.apache.sshd.server.Environment; import org.apache.sshd.server.Environment;
import org.apache.sshd.server.ExitCallback; import org.apache.sshd.server.ExitCallback;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.libs.jline.console.ConsoleReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.InetAddress;
import java.util.logging.Level;
import java.util.logging.StreamHandler; import java.util.logging.StreamHandler;
public class ConsoleShellFactory implements ShellFactory { public class ConsoleShellFactory implements Factory<Command> {
public Command createShell(ChannelSession cs) { public Command create() {
return new ConsoleShell(); return new ConsoleShell();
} }
public class ConsoleShell implements Command, Runnable { public static class ConsoleShell implements Command, Runnable {
private InputStream in; private InputStream in;
private OutputStream out; private OutputStream out;
@@ -41,11 +28,9 @@ public class ConsoleShellFactory implements ShellFactory {
private ExitCallback callback; private ExitCallback callback;
private Environment environment; private Environment environment;
private Thread thread; private Thread thread;
private String Username;
StreamHandlerAppender streamHandlerAppender; StreamHandlerAppender streamHandlerAppender;
public ConsoleReader ConsoleReader; ConsoleReader consoleReader;
public SSHDCommandSender SshdCommandSender;
public InputStream getIn() { public InputStream getIn() {
return in; return in;
@@ -79,104 +64,63 @@ public class ConsoleShellFactory implements ShellFactory {
this.callback = callback; this.callback = callback;
} }
@Override public void start(Environment env) throws IOException {
public void start(ChannelSession cs, Environment env) throws IOException
{
try
{
this.ConsoleReader = new ConsoleReader(in, new FlushyOutputStream(out), new SshTerminal());
this.ConsoleReader.setExpandEvents(true);
this.ConsoleReader.addCompleter(new ConsoleCommandCompleter());
StreamHandler streamHandler = new FlushyStreamHandler(out, new ConsoleLogFormatter(), this.ConsoleReader); try {
consoleReader = new ConsoleReader(in, new FlushyOutputStream(out), new SshTerminal());
consoleReader.setExpandEvents(true);
consoleReader.addCompleter(new ConsoleCommandCompleter());
StreamHandler streamHandler = new FlushyStreamHandler(out, new ConsoleLogFormatter(), consoleReader);
streamHandlerAppender = new StreamHandlerAppender(streamHandler); streamHandlerAppender = new StreamHandlerAppender(streamHandler);
((Logger) LogManager.getRootLogger()).addAppender(streamHandlerAppender); ((Logger) LogManager.getRootLogger()).addAppender(streamHandlerAppender);
this.environment = env; environment = env;
this.Username = env.getEnv().get(Environment.ENV_USER); thread = new Thread(this, "SSHD ConsoleShell " + env.getEnv().get(Environment.ENV_USER));
this.SshdCommandSender = new SSHDCommandSender();
this.SshdCommandSender.console = this;
thread = new Thread(this, "SSHD ConsoleShell " + this.Username);
thread.start(); thread.start();
} } catch (Exception e) {
catch (Exception e)
{
throw new IOException("Error starting shell", e); throw new IOException("Error starting shell", e);
} }
} }
@Override public void destroy() {
public void destroy(ChannelSession cs) { ((Logger)LogManager.getRootLogger()).removeAppender(streamHandlerAppender); } ((Logger) LogManager.getRootLogger()).removeAppender(streamHandlerAppender);
public void run()
{
try
{
if (!SshdPlugin.instance.getConfig().getString("Mode").equals("RPC"))
printPreamble(this.ConsoleReader);
while (true)
{
String command = this.ConsoleReader.readLine("\r>", null);
// The user sent CTRL+D to close the shell, terminate the session.
if (command == null)
break;
// Skip someone spamming enter
if (command.trim().isEmpty())
continue;
// User wants to exit
if (command.equals("exit") || command.equals("quit"))
break;
// Clear the text from the screen (on supported terminals)
if (command.equals("cls"))
{
this.ConsoleReader.clearScreen();
continue;
} }
Bukkit.getScheduler().runTask( public void run() {
SshdPlugin.instance, () -> String command;
{ try {
if (SshdPlugin.instance.getConfig().getString("Mode").equals("RPC") && command.startsWith("rpc")) printPreamble(consoleReader);
{ while(true) {
// NO ECHO NO PREAMBLE AND SHIT command = consoleReader.readLine("\r>", null);
String cmd = command.substring("rpc".length() + 1, command.length()); if (command != null) {
Bukkit.dispatchCommand(this.SshdCommandSender, cmd); if (command.equals("exit")) {
break;
} }
else SshdPlugin.instance.getLogger().info("<" + environment.getEnv().get(Environment.ENV_USER) + "> " + command);
{
SshdPlugin.instance.getLogger().info("<" + this.Username + "> " + command);
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
} }
});
} }
} } catch (IOException e) {
catch (IOException e) SshdPlugin.instance.getLogger().severe("Error processing command from SSH");
{ } finally {
SshdPlugin.instance.getLogger().log(Level.SEVERE, "Error processing command from SSH", e);
}
finally
{
SshdPlugin.instance.getLogger().log(Level.INFO, this.Username + " disconnected from SSH.");
callback.onExit(0); callback.onExit(0);
} }
} }
private void printPreamble(ConsoleReader cr) throws IOException private void printPreamble(ConsoleReader consoleReader) throws IOException{
{ consoleReader.println(" _____ _____ _ _ _____");
cr.println(" _____ _____ _ _ _____" + "\r"); consoleReader.println(" / ____/ ____| | | | __ \\");
cr.println(" / ____/ ____| | | | __ \\" + "\r"); consoleReader.println("| (___| (___ | |__| | | | |");
cr.println("| (___| (___ | |__| | | | |" + "\r"); consoleReader.println(" \\___ \\\\___ \\| __ | | | |");
cr.println(" \\___ \\\\___ \\| __ | | | |" + "\r"); consoleReader.println(" ____) |___) | | | | |__| |");
cr.println(" ____) |___) | | | | |__| |" + "\r"); consoleReader.println("|_____/_____/|_| |_|_____/");
cr.println("|_____/_____/|_| |_|_____/" + "\r"); consoleReader.println("Connected to: " + Bukkit.getServer().getName());
// Doesn't really guarantee our actual system hostname but consoleReader.println("- " + Bukkit.getServer().getMotd());
// it's better than not having one at all. consoleReader.println();
cr.println("Connected to: " + InetAddress.getLocalHost().getHostName() + " (" + Bukkit.getServer().getName() + ")\r"); consoleReader.println("Type 'exit' to exit the shell.");
cr.println(ConsoleLogFormatter.ColorizeString(Bukkit.getServer().getMotd()) + "\r"); consoleReader.println("===============================================");
cr.println("\r");
cr.println("Type 'exit' to exit the shell." + "\r");
cr.println("===============================================" + "\r");
} }
} }
} }

View File

@@ -1,7 +1,5 @@
package com.ryanmichela.sshd; package com.ryanmichela.sshd;
import org.apache.sshd.common.SshException;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
@@ -9,9 +7,7 @@ import java.io.OutputStream;
* Copyright 2013 Ryan Michela * Copyright 2013 Ryan Michela
*/ */
public class FlushyOutputStream extends OutputStream { public class FlushyOutputStream extends OutputStream {
private OutputStream base; private OutputStream base;
private boolean isClosed = false;
public FlushyOutputStream(OutputStream base) { public FlushyOutputStream(OutputStream base) {
this.base = base; this.base = base;
@@ -19,31 +15,19 @@ public class FlushyOutputStream extends OutputStream {
@Override @Override
public void write(int b) throws IOException { public void write(int b) throws IOException {
if (isClosed) return;
base.write(b); base.write(b);
base.flush(); base.flush();
} }
@Override @Override
public void write(byte[] b) throws IOException { public void write(byte[] b) throws IOException {
if (isClosed) return;
base.write(b); base.write(b);
base.flush(); base.flush();
} }
@Override @Override
public void write(byte[] b, int off, int len) throws IOException { public void write(byte[] b, int off, int len) throws IOException {
if (isClosed) return;
try {
base.write(b, off, len); base.write(b, off, len);
base.flush(); base.flush();
} catch (SshException e) {
if (!e.getMessage().contains("channel already closed")) throw e;
}
}
@Override
public void close() {
isClosed = true;
} }
} }

View File

@@ -1,7 +1,7 @@
package com.ryanmichela.sshd; package com.ryanmichela.sshd;
import jline.console.ConsoleReader;
import org.apache.sshd.common.SshException; import org.apache.sshd.common.SshException;
import org.bukkit.craftbukkit.libs.jline.console.ConsoleReader;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
@@ -11,7 +11,6 @@ import java.util.logging.*;
* Copyright 2013 Ryan Michela * Copyright 2013 Ryan Michela
*/ */
public class FlushyStreamHandler extends StreamHandler { public class FlushyStreamHandler extends StreamHandler {
private ConsoleReader reader; private ConsoleReader reader;
public FlushyStreamHandler(OutputStream out, Formatter formatter, ConsoleReader reader) { public FlushyStreamHandler(OutputStream out, Formatter formatter, ConsoleReader reader) {

View File

@@ -0,0 +1,28 @@
package com.ryanmichela.sshd;
import org.apache.sshd.server.session.ServerSession;
import java.net.InetSocketAddress;
import java.util.List;
/**
* Copyright 2014 Ryan Michela
*/
public class IpFilteredAuthenticator {
private NetworkAddressValidator addressValidator;
public IpFilteredAuthenticator() {
List<String> whitelist = SshdPlugin.instance.getConfig().getStringList("whitelist");
if (whitelist.size() > 0) {
addressValidator = new NetworkAddressValidator(whitelist);
}
}
public boolean ipAddressIsApproved(ServerSession serverSession) {
if (addressValidator != null) {
String ip = ((InetSocketAddress)serverSession.getIoSession().getRemoteAddress()).getAddress().getHostAddress();
return addressValidator.isApproved(ip);
}
return true;
}
}

View File

@@ -0,0 +1,42 @@
package com.ryanmichela.sshd;
/**
* Copyright 2014 Ryan Michela
*/
import java.net.UnknownHostException;
import java.util.List;
public class NetworkAddressValidator {
private CIDRUtils[] approvedAddressList = null;
public NetworkAddressValidator(List<String> approvedAddressList) {
this.approvedAddressList = new CIDRUtils[approvedAddressList.size()];
for (int i = 0; i < approvedAddressList.size(); i++) {
String whitelistEntry = approvedAddressList.get(i);
try {
if (approvedAddressList.get(i).indexOf("/") > 0) {
this.approvedAddressList[i] = new CIDRUtils(whitelistEntry);
} else {
this.approvedAddressList[i] = new CIDRUtils(whitelistEntry + "/32");
}
} catch (UnknownHostException e) {
SshdPlugin.instance.getLogger().severe(whitelistEntry + " is not a valid IPv4 or IPv6 address or CIDR formatted address.");
}
}
}
public boolean isApproved(String ipAddress) {
try {
for (CIDRUtils approvedAddress : approvedAddressList) {
if (approvedAddress.isInRange(ipAddress)) {
return true;
}
}
return false;
} catch (UnknownHostException e) {
return false;
}
}
}

View File

@@ -0,0 +1,97 @@
package com.ryanmichela.sshd;
import org.apache.mina.util.Base64;
import java.io.Reader;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.DSAPublicKeySpec;
import java.security.spec.RSAPublicKeySpec;
/**
* Copyright 2013 Ryan Michela
*/
public class PemDecoder extends java.io.BufferedReader {
private static final String BEGIN = "^-+\\s*BEGIN.+";
private static final String END = "^-+\\s*END.+";
private static final String COMMENT = "Comment:";
public PemDecoder(Reader in) {
super(in);
}
public PublicKey getPemBytes() throws Exception {
StringBuffer b64 = new StringBuffer();
String line = readLine();
if (!line.matches(BEGIN)) {
return null;
}
for(line = readLine(); line != null; line = readLine()) {
if (!line.matches(END) && !line.startsWith(COMMENT)) {
b64.append(line.trim());
}
}
return decodePublicKey(b64.toString());
}
private byte[] bytes;
private int pos;
private PublicKey decodePublicKey(String keyLine) throws Exception {
bytes = null;
pos = 0;
// look for the Base64 encoded part of the line to decode
// both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes
for (String part : keyLine.split(" ")) {
if (part.startsWith("AAAA")) {
bytes = Base64.decodeBase64(part.getBytes());
break;
}
}
if (bytes == null) {
throw new IllegalArgumentException("no Base64 part to decode");
}
String type = decodeType();
if (type.equals("ssh-rsa")) {
BigInteger e = decodeBigInt();
BigInteger m = decodeBigInt();
RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);
return KeyFactory.getInstance("RSA").generatePublic(spec);
} else if (type.equals("ssh-dss")) {
BigInteger p = decodeBigInt();
BigInteger q = decodeBigInt();
BigInteger g = decodeBigInt();
BigInteger y = decodeBigInt();
DSAPublicKeySpec spec = new DSAPublicKeySpec(y, p, q, g);
return KeyFactory.getInstance("DSA").generatePublic(spec);
} else {
throw new IllegalArgumentException("unknown type " + type);
}
}
private String decodeType() {
int len = decodeInt();
String type = new String(bytes, pos, len);
pos += len;
return type;
}
private int decodeInt() {
return ((bytes[pos++] & 0xFF) << 24) | ((bytes[pos++] & 0xFF) << 16)
| ((bytes[pos++] & 0xFF) << 8) | (bytes[pos++] & 0xFF);
}
private BigInteger decodeBigInt() {
int len = decodeInt();
byte[] bigIntBytes = new byte[len];
System.arraycopy(bytes, pos, bigIntBytes, 0, len);
pos += len;
return new BigInteger(bigIntBytes);
}
}

View File

@@ -1,80 +1,50 @@
package com.ryanmichela.sshd; package com.ryanmichela.sshd;
import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.ArrayUtils;
import org.apache.sshd.common.config.keys.AuthorizedKeyEntry; import org.apache.sshd.server.PublickeyAuthenticator;
import org.apache.sshd.common.config.keys.PublicKeyEntryResolver;
import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator;
import org.apache.sshd.server.session.ServerSession; import org.apache.sshd.server.session.ServerSession;
import java.io.File; import java.io.File;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.io.FileReader; import java.io.FileReader;
import java.security.PublicKey; import java.security.PublicKey;
/** /**
* Copyright 2013 Ryan Michela * Copyright 2013 Ryan Michela
*/ */
public class PublicKeyAuthenticator implements PublickeyAuthenticator public class PublicKeyAuthenticator extends IpFilteredAuthenticator implements PublickeyAuthenticator {
{
private File authorizedKeysDir; private File authorizedKeysDir;
private Map<String, Integer> FailCounts = new HashMap<String, Integer>();
public PublicKeyAuthenticator(File authorizedKeysDir) { this.authorizedKeysDir = authorizedKeysDir; } public PublicKeyAuthenticator(File authorizedKeysDir) {
this.authorizedKeysDir = authorizedKeysDir;
}
@Override
public boolean authenticate(String username, PublicKey key, ServerSession session) {
if (!ipAddressIsApproved(session)) return false;
@Override public boolean authenticate(String username, PublicKey key, ServerSession session)
{
byte[] keyBytes = key.getEncoded(); byte[] keyBytes = key.getEncoded();
File keyFile = new File(authorizedKeysDir, username); File keyFile = new File(authorizedKeysDir, username);
Integer tries = SshdPlugin.instance.getConfig().getInt("LoginRetries");
if (keyFile.exists()) if (keyFile.exists()) {
{ try {
try
{
// Read all the public key entries
List<AuthorizedKeyEntry> pklist = AuthorizedKeyEntry.readAuthorizedKeys(keyFile.toPath());
// Get an authenticator
PublickeyAuthenticator auth = PublickeyAuthenticator.fromAuthorizedEntries(username, session, pklist,
PublicKeyEntryResolver.IGNORING);
// Validate that the logging in user has the same valid SSH key FileReader fr = new FileReader(keyFile);
if (auth.authenticate(username, key, session)) PemDecoder pd = new PemDecoder(fr);
{ PublicKey k = pd.getPemBytes();
FailCounts.put(username, 0); pd.close();
if (k != null) {
if (ArrayUtils.isEquals(key.getEncoded(), k.getEncoded())) {
return true; return true;
} }
else } else {
{ SshdPlugin.instance.getLogger().severe("Failed to parse PEM file. " + keyFile.getAbsolutePath());
SshdPlugin.instance.getLogger().info(
username + " failed authentication via SSH session using key file " + keyFile.getAbsolutePath());
} }
} catch (Exception e) {
// If the user fails with several SSH keys, then terminate the connection. SshdPlugin.instance.getLogger().severe("Failed to process public key " + keyFile.getAbsolutePath() + ". " + e.getMessage());
if (this.FailCounts.containsKey(username))
this.FailCounts.put(username, this.FailCounts.get(username) + 1);
else
this.FailCounts.put(username, 1);
if (this.FailCounts.get(username) >= tries)
{
this.FailCounts.put(username, 0);
session.close(true);
} }
} else {
return false; SshdPlugin.instance.getLogger().warning("Could not locate public key for " + username + ". Make sure the user's key is named the same as their user name without a file extension.");
}
catch (Exception e)
{
SshdPlugin.instance.getLogger().severe("Failed to process public key " + keyFile.getAbsolutePath() + " " + e.getMessage());
}
}
else
{
SshdPlugin.instance.getLogger().warning("Could not locate public key for " + username
+ ". Make sure the user's key is named the same as their user name "
+ "without a file extension.");
} }
return false; return false;

View File

@@ -8,7 +8,6 @@ import java.lang.reflect.Modifier;
* Copyright 2013 Ryan Michela * Copyright 2013 Ryan Michela
*/ */
public class ReflectionUtil { public class ReflectionUtil {
public static void setProtectedValue(Object o, String field, Object newValue) { public static void setProtectedValue(Object o, String field, Object newValue) {
setProtectedValue(o.getClass(), o, field, newValue); setProtectedValue(o.getClass(), o, field, newValue);
} }
@@ -29,7 +28,9 @@ public class ReflectionUtil {
modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL); modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL);
f.set(o, newValue); f.set(o, newValue);
} catch (NoSuchFieldException | IllegalAccessException ex) { } catch (NoSuchFieldException ex) {
System.out.println("*** " + c.getName() + ":" + ex);
} catch (IllegalAccessException ex) {
System.out.println("*** " + c.getName() + ":" + ex); System.out.println("*** " + c.getName() + ":" + ex);
} }
} }
@@ -88,7 +89,8 @@ public class ReflectionUtil {
Method m = c.getDeclaredMethod(method, pTypes); Method m = c.getDeclaredMethod(method, pTypes);
m.setAccessible(true); m.setAccessible(true);
return m.invoke(o, args); return m.invoke(o, args);
} catch (Exception ex) { }
catch (Exception ex) {
System.out.println("*** " + c.getName() + "." + method + "(): " + ex); System.out.println("*** " + c.getName() + "." + method + "(): " + ex);
return null; return null;
} }

View File

@@ -1,6 +1,6 @@
package com.ryanmichela.sshd; package com.ryanmichela.sshd;
import jline.TerminalSupport; import org.bukkit.craftbukkit.libs.jline.TerminalSupport;
/** /**
* Copyright 2013 Ryan Michela * Copyright 2013 Ryan Michela

View File

@@ -1,35 +1,25 @@
package com.ryanmichela.sshd; package com.ryanmichela.sshd;
import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory; import org.apache.sshd.SshServer;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider; import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import com.ryanmichela.sshd.ConsoleShellFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileSystems;
import java.util.Collections;
import java.util.logging.Level; import java.util.logging.Level;
/** /**
* Copyright 2013 Ryan Michela * Copyright 2013 Ryan Michela
*/ */
public public class SshdPlugin extends JavaPlugin {
class SshdPlugin extends JavaPlugin
{
private SshServer sshd; private SshServer sshd;
public static SshdPlugin instance; public static SshdPlugin instance;
@Override public void onLoad() @Override
{ public void onLoad() {
saveDefaultConfig(); saveDefaultConfig();
File authorizedKeys = new File(getDataFolder(), "authorized_keys"); File authorizedKeys = new File(getDataFolder(), "authorized_keys");
if (!authorizedKeys.exists()) if (!authorizedKeys.exists()) {
{
authorizedKeys.mkdirs(); authorizedKeys.mkdirs();
} }
@@ -39,49 +29,33 @@ class SshdPlugin extends JavaPlugin
getLogger().setLevel(Level.INFO); getLogger().setLevel(Level.INFO);
} }
@Override public void onEnable() @Override
{ public void onEnable() {
instance = this; instance = this;
sshd = SshServer.setUpDefaultServer(); sshd = SshServer.setUpDefaultServer();
sshd.setPort(getConfig().getInt("Port", 1025)); sshd.setPort(getConfig().getInt("port", 22));
String host = getConfig().getString("ListenAddress", "all");
sshd.setHost(host.equals("all") ? null : host);
File hostKey = new File(getDataFolder(), "hostkey"); File hostKey = new File(getDataFolder(), "hostkey");
File authorizedKeys = new File(getDataFolder(), "authorized_keys"); File authorizedKeys = new File(getDataFolder(), "authorized_keys");
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(hostKey.toPath())); sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(hostKey.getPath()));
sshd.setShellFactory(new ConsoleShellFactory()); sshd.setShellFactory(new ConsoleShellFactory());
sshd.setPasswordAuthenticator(new ConfigPasswordAuthenticator()); sshd.setPasswordAuthenticator(new ConfigPasswordAuthenticator());
sshd.setPublickeyAuthenticator(new PublicKeyAuthenticator(authorizedKeys)); sshd.setPublickeyAuthenticator(new PublicKeyAuthenticator(authorizedKeys));
if (getConfig().getBoolean("EnableSFTP"))
{
sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory()));
sshd.setFileSystemFactory(
new VirtualFileSystemFactory(FileSystems.getDefault().getPath(getDataFolder().getAbsolutePath()).getParent().getParent()));
}
sshd.setCommandFactory(new ConsoleCommandFactory()); sshd.setCommandFactory(new ConsoleCommandFactory());
try try {
{
sshd.start(); sshd.start();
} } catch (IOException e) {
catch (IOException e) getLogger().severe("Failed to start SSH server! " + e.getMessage());
{
getLogger().log(Level.SEVERE, "Failed to start SSH server! ", e);
} }
} }
@Override public void onDisable() @Override
{ public void onDisable() {
try try {
{
sshd.stop(); sshd.stop();
} } catch (Exception e) {
catch (Exception e)
{
// do nothing // do nothing
} }
} }

View File

@@ -14,7 +14,6 @@ import java.util.logging.StreamHandler;
* Copyright 2014 Ryan Michela * Copyright 2014 Ryan Michela
*/ */
public class StreamHandlerAppender implements Appender { public class StreamHandlerAppender implements Appender {
private StreamHandler streamHandler; private StreamHandler streamHandler;
private UUID uuid; private UUID uuid;
@@ -26,18 +25,15 @@ public class StreamHandlerAppender implements Appender {
@Override @Override
public void append(LogEvent logEvent) { public void append(LogEvent logEvent) {
java.util.logging.Level level; java.util.logging.Level level;
switch (logEvent.getLevel())
if (logEvent.getLevel().equals(org.apache.logging.log4j.Level.DEBUG)) { {
level = java.util.logging.Level.FINE; case DEBUG: level = java.util.logging.Level.FINE; break;
} else if (logEvent.getLevel().equals(org.apache.logging.log4j.Level.INFO)) { case INFO: level = java.util.logging.Level.INFO; break;
level = java.util.logging.Level.INFO; case WARN: level = java.util.logging.Level.WARNING; break;
} else if (logEvent.getLevel().equals(org.apache.logging.log4j.Level.WARN)) { case ERROR: level = java.util.logging.Level.SEVERE; break;
level = java.util.logging.Level.WARNING; default: level = java.util.logging.Level.INFO; break;
} else if (logEvent.getLevel().equals(org.apache.logging.log4j.Level.ERROR)) {
level = java.util.logging.Level.SEVERE;
} else {
level = java.util.logging.Level.INFO;
} }
String message = logEvent.getMessage().getFormattedMessage(); String message = logEvent.getMessage().getFormattedMessage();
@@ -84,9 +80,4 @@ public class StreamHandlerAppender implements Appender {
public boolean isStarted() { public boolean isStarted() {
return true; return true;
} }
@Override
public boolean isStopped() {
return false;
}
} }

View File

@@ -6,13 +6,11 @@ import java.util.concurrent.ExecutionException;
* Copyright 2013 Ryan Michela * Copyright 2013 Ryan Michela
*/ */
public abstract class Waitable<T> implements Runnable { public abstract class Waitable<T> implements Runnable {
private enum Status { private enum Status {
WAITING, WAITING,
RUNNING, RUNNING,
FINISHED, FINISHED,
} }
Throwable t = null; Throwable t = null;
T value = null; T value = null;
Status status = Status.WAITING; Status status = Status.WAITING;

View File

@@ -1,139 +0,0 @@
package com.ryanmichela.sshd.implementations;
import com.ryanmichela.sshd.SshdPlugin;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.conversations.Conversation;
import org.bukkit.conversations.ConversationAbandonedEvent;
import org.bukkit.conversations.ManuallyAbandonedConversationCanceller;
import org.bukkit.permissions.PermissibleBase;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionAttachment;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.Plugin;
import com.ryanmichela.sshd.ConsoleShellFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.Set;
import java.util.logging.Level;
public class SSHDCommandSender implements ConsoleCommandSender, CommandSender {
private final PermissibleBase perm = new PermissibleBase(this);
private final SSHDConversationTracker conversationTracker = new SSHDConversationTracker();
// Set by the upstream allocating function
public ConsoleShellFactory.ConsoleShell console;
public void sendMessage(String message) {
this.sendRawMessage(message);
}
public void sendRawMessage(String message)
{
// What the fuck does this code even do? Are we sending to one client or all of them?
if (this.console.ConsoleReader == null)
return;
try
{
this.console.ConsoleReader.println(ChatColor.stripColor(message));
}
catch (IOException e)
{
SshdPlugin.instance.getLogger().log(Level.SEVERE, "Error sending message to SSHDCommandSender", e);
}
}
public void sendMessage(String[] messages) {
Arrays.asList(messages).forEach(this::sendMessage);
}
public String getName() {
return "SSHD Console";
}
public boolean isOp() {
return true;
}
public void setOp(boolean value) {
throw new UnsupportedOperationException("Cannot change operator status of server console");
}
public boolean beginConversation(Conversation conversation) {
return this.conversationTracker.beginConversation(conversation);
}
public void abandonConversation(Conversation conversation) {
this.conversationTracker.abandonConversation(conversation, new ConversationAbandonedEvent(conversation, new ManuallyAbandonedConversationCanceller()));
}
public void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) {
this.conversationTracker.abandonConversation(conversation, details);
}
public void acceptConversationInput(String input) {
this.conversationTracker.acceptConversationInput(input);
}
public boolean isConversing() {
return this.conversationTracker.isConversing();
}
public boolean isPermissionSet(String name) {
return this.perm.isPermissionSet(name);
}
public boolean isPermissionSet(Permission perm) {
return this.perm.isPermissionSet(perm);
}
public boolean hasPermission(String name) {
return this.perm.hasPermission(name);
}
public boolean hasPermission(Permission perm) {
return this.perm.hasPermission(perm);
}
public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) {
return this.perm.addAttachment(plugin, name, value);
}
public PermissionAttachment addAttachment(Plugin plugin) {
return this.perm.addAttachment(plugin);
}
public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) {
return this.perm.addAttachment(plugin, name, value, ticks);
}
public PermissionAttachment addAttachment(Plugin plugin, int ticks) {
return this.perm.addAttachment(plugin, ticks);
}
public void removeAttachment(PermissionAttachment attachment) {
this.perm.removeAttachment(attachment);
}
public void recalculatePermissions() {
this.perm.recalculatePermissions();
}
public Set<PermissionAttachmentInfo> getEffectivePermissions() {
return this.perm.getEffectivePermissions();
}
public boolean isPlayer() {
return false;
}
public Server getServer() {
return Bukkit.getServer();
}
}

View File

@@ -1,78 +0,0 @@
package com.ryanmichela.sshd.implementations;
import org.bukkit.Bukkit;
import org.bukkit.conversations.Conversation;
import org.bukkit.conversations.ConversationAbandonedEvent;
import org.bukkit.conversations.ManuallyAbandonedConversationCanceller;
import java.util.LinkedList;
import java.util.logging.Level;
public class SSHDConversationTracker {
private LinkedList<Conversation> conversationQueue = new LinkedList<>();
synchronized boolean beginConversation(Conversation conversation) {
if (!this.conversationQueue.contains(conversation)) {
this.conversationQueue.addLast(conversation);
if (this.conversationQueue.getFirst() == conversation) {
conversation.begin();
conversation.outputNextPrompt();
return true;
}
}
return true;
}
synchronized void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) {
if (!this.conversationQueue.isEmpty()) {
if (this.conversationQueue.getFirst() == conversation) {
conversation.abandon(details);
}
if (this.conversationQueue.contains(conversation)) {
this.conversationQueue.remove(conversation);
}
if (!this.conversationQueue.isEmpty()) {
this.conversationQueue.getFirst().outputNextPrompt();
}
}
}
public synchronized void abandonAllConversations() {
LinkedList<Conversation> oldQueue = this.conversationQueue;
this.conversationQueue = new LinkedList<>();
for (Conversation conversation : oldQueue) {
try {
conversation.abandon(new ConversationAbandonedEvent(conversation, new ManuallyAbandonedConversationCanceller()));
} catch (Throwable var5) {
Bukkit.getLogger().log(Level.SEVERE, "Unexpected exception while abandoning a conversation", var5);
}
}
}
synchronized void acceptConversationInput(String input) {
if (this.isConversing()) {
Conversation conversation = this.conversationQueue.getFirst();
try {
conversation.acceptInput(input);
} catch (Throwable var4) {
conversation.getContext().getPlugin().getLogger().log(Level.WARNING, String.format("Plugin %s generated an exception whilst handling conversation input", conversation.getContext().getPlugin().getDescription().getFullName()), var4);
}
}
}
synchronized boolean isConversing() {
return !this.conversationQueue.isEmpty();
}
public synchronized boolean isConversingModaly() {
return this.isConversing() && this.conversationQueue.getFirst().isModal();
}
}

View File

@@ -22,7 +22,10 @@ public class PluginSlf4jFactory implements ILoggerFactory {
private String name; private String name;
private boolean isEnabled(Level level) { private boolean isEnabled(Level level) {
return SshdPlugin.instance != null && SshdPlugin.instance.getLogger().isLoggable(level); if (SshdPlugin.instance != null) {
return SshdPlugin.instance.getLogger().isLoggable(level);
}
return false;
} }
private void log(Level level, String s, Object[] objects) { private void log(Level level, String s, Object[] objects) {

View File

@@ -1,35 +1,19 @@
# The IP addresses(s) the SSH server will listen on. Use a comma separated list for multiple addresses. # This is the port the SSH server will listen on.
# Leave as "all" for all addresses. port: 22
ListenAddress: all
# The port the SSH server will listen on. Note that anything above 1024 will require you to run
# the whole minecraft server with elevated privileges, this is not recommended and you should
# use iptables to route packets from a lower port.
Port: 1025
# Operational mode. Don't touch if you don't know what you're doing. Can be either DEFAULT or RPC
Mode: DEFAULT
# Enable built-in SFTP server or not. You'll be able to connect and upload/download files via SFTP protocol.
# Might be useful for testing purposes as well , i. e. docker containers.
EnableSFTP: true
# Number of times a person can fail to use an SSH key or enter a password
# before it terminates the connection.
LoginRetries: 3
# By default, only public key authentication is enabled. This is the most secure mode. # By default, only public key authentication is enabled. This is the most secure mode.
# To authorize a user to login with their public key, install their key using the # To authorize a user to log in with public key authentication, install their public
# OpenSSH authorized_keys file format in the authorized_users directory. Name the key # PEM certificate in the authorized_users directory. Name the key file with user's user
# file with the user's username and no extension. Note: If you want to let a user have # name (no file extension).
# many keys, you can append the keys to their file in authorized_users.
# For less secure username and password based authentication, complete the sections below. # For less secure username and password based authentication, complete the sections below.
credentials:
# Type of hashing to use for the passwords below.
# Options are: PLAIN (insecure), bcrypt, pbkdf, sha256
PasswordType: bcrypt
# Associate each username with a password hash (or the password if the PasswordType is set to PLAIN)
Credentials:
# user1: password1 # user1: password1
# user2: password2 # user2: password2
# To enable the IP whitelist, add more lines below. Whitelist entries can be expressed
# in CIDR notation (ip address/mask) for whitelisting a range of IP addresses.
whitelist:
# - ::1/128
# - 127.0.0.0/8
# - 192.168.0.0/16

View File

@@ -1,4 +1,4 @@
name: SSHD name: SSHD
version: ${project.version} version: "1.2"
author: Ryan Michela, Haarolean, toxuin, Justin Crawford author: Ryan Michela
main: com.ryanmichela.sshd.SshdPlugin main: com.ryanmichela.sshd.SshdPlugin