5 Commits

Author SHA1 Message Date
Justin Crawford
3e45f7ebf4 Tweak the SSH MOTD a bit 2019-10-03 22:16:29 -07:00
Justin Crawford
0e05bb61bc Support CTRL+D for exiting the console
Support CTRL+D for exiting the console, also support "cls" for
clearing the screen (on supported terminals).
2019-10-03 21:41:02 -07:00
Justin Crawford
0635ea7a35 Fixed a bug (open on the upstream fork), also rewote config.
Fixed a bug that caused sessions to get overwritten and some of them
would seem to freeze, the whole thing relied on undefined behavior.
This bug was a static variable that copied sessions all around globally.

Rewrote the config to support a few more options (the PasswordType is coming soon)
and explained how the new authorized_users files work.

Public key authentication now has the same number of retires that
password authentication has (this aligns with how OpenSSH does it)
and the number of retries can now be configured in the configuration.
2019-10-03 21:07:00 -07:00
Justin Crawford
25287b1580 Fix Travis 2019-10-02 19:41:31 -07:00
Justin Crawford
0458179597 Add support for authorized_keys files.
Each user can have a set of authorized keys for public key authentication.
This is better to support as it lets us use different algorithms and not
just RSA. In the age of security, it's good to have variety.

I also added additional libraries to support ed25519-based public keys.

I updated the SSH libraries so any upstream bug fixes are applied, fixed
some warnings and a few other things.
2019-10-02 19:14:56 -07:00
16 changed files with 705 additions and 527 deletions

68
.clangformat Normal file
View File

@@ -0,0 +1,68 @@
---
#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,4 +1,5 @@
sudo: false sudo: false
dist: trusty
language: java language: java
jdk: jdk:
- oraclejdk8 - oraclejdk8

View File

@@ -1,6 +1,70 @@
Bukkit-SSHD Spigot-SSHD
=========== ===========
[![Build Status](https://travis-ci.org/rmichela/Bukkit-SSHD.png)](https://travis-ci.org/rmichela/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.

55
pom.xml
View File

@@ -5,9 +5,14 @@
<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.4.1</version> <version>1.3.5</version>
<url>http://dev.bukkit.org/server-mods/sshd/</url> <url>https://github.com/Justasic/Bukkit-SSHD/</url>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- Repositories --> <!-- Repositories -->
<repositories> <repositories>
@@ -30,33 +35,59 @@
<dependency> <dependency>
<groupId>org.bukkit</groupId> <groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId> <artifactId>bukkit</artifactId>
<version>1.12.2-R0.1-SNAPSHOT</version> <version>1.14.4-R0.1-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.sshd</groupId> <groupId>org.apache.sshd</groupId>
<artifactId>sshd-core</artifactId> <artifactId>sshd-core</artifactId>
<version>1.6.0</version> <version>2.3.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> <dependency>
<groupId>org.apache.mina</groupId> <groupId>org.apache.mina</groupId>
<artifactId>mina-core</artifactId> <artifactId>mina-core</artifactId>
<version>2.0.16</version> <version>2.1.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>
<version>1.7.25</version> <version>1.7.28</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId> <artifactId>slf4j-jdk14</artifactId>
<version>1.7.25</version> <version>1.7.28</version>
</dependency> </dependency>
<dependency> <dependency>
@@ -85,10 +116,12 @@
<version>1.10</version> <version>1.10</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<!-- Build --> <!-- Build -->
<build> <build>
<defaultGoal>clean package</defaultGoal>
<resources> <resources>
<resource> <resource>
<targetPath>.</targetPath> <targetPath>.</targetPath>
@@ -104,7 +137,7 @@
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
<version>3.1.0</version> <version>3.1.1</version>
<executions> <executions>
<execution> <execution>
<phase>package</phase> <phase>package</phase>
@@ -126,7 +159,7 @@
<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.5.1</version> <version>3.7.0</version>
<configuration> <configuration>
<source>1.8</source> <source>1.8</source>
<target>1.8</target> <target>1.8</target>

View File

@@ -11,30 +11,38 @@ import java.util.Map;
*/ */
public class ConfigPasswordAuthenticator implements PasswordAuthenticator { public class ConfigPasswordAuthenticator 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 serverSession) { public boolean authenticate(String username, String password, ServerSession ss)
if (SshdPlugin.instance.getConfig().getString("credentials." + username).equals(password)) { {
failCounts.put(username, 0); if (SshdPlugin.instance.getConfig().getString("Credentials." + username).equals(password))
return true; {
} FailCounts.put(username, 0);
SshdPlugin.instance.getLogger().info("Failed login for " + username + " using password authentication."); return true;
}
SshdPlugin.instance.getLogger().info("Failed login for " + username + " using password authentication.");
try { Integer tries = SshdPlugin.instance.getConfig().getInt("LoginRetries");
Thread.sleep(3000);
if (failCounts.containsKey(username)) { try
failCounts.put(username, failCounts.get(username) + 1); {
} else { Thread.sleep(3000);
failCounts.put(username, 1); if (this.FailCounts.containsKey(username))
} this.FailCounts.put(username, this.FailCounts.get(username) + 1);
if (failCounts.get(username) >= 3) { else
failCounts.put(username, 0); this.FailCounts.put(username, 1);
serverSession.close(true);
} if (this.FailCounts.get(username) >= tries)
} catch (InterruptedException e) { {
// do nothing this.FailCounts.put(username, 0);
} ss.close(true);
return false; }
} }
catch (InterruptedException e)
{
// do nothing
}
return false;
}
} }

View File

@@ -1,7 +1,8 @@
package com.ryanmichela.sshd; package com.ryanmichela.sshd;
import org.apache.sshd.server.Command; import org.apache.sshd.server.command.Command;
import org.apache.sshd.server.CommandFactory; import org.apache.sshd.server.command.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;
@@ -16,7 +17,7 @@ import java.io.OutputStream;
public class ConsoleCommandFactory implements CommandFactory { public class ConsoleCommandFactory implements CommandFactory {
@Override @Override
public Command createCommand(String command) { public Command createCommand(ChannelSession cs, String command) {
return new ConsoleCommand(command); return new ConsoleCommand(command);
} }
@@ -50,7 +51,7 @@ public class ConsoleCommandFactory implements CommandFactory {
} }
@Override @Override
public void start(Environment environment) throws IOException { public void start(ChannelSession cs, 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);
@@ -63,8 +64,6 @@ public class ConsoleCommandFactory implements CommandFactory {
} }
@Override @Override
public void destroy() { public void destroy(ChannelSession cn) {}
}
}
}
} }

View File

@@ -18,11 +18,55 @@ 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 { try {
Class.forName("org.bukkit.craftbukkit.command.ColouredConsoleSender"); Class.forName("org.bukkit.craftbukkit.command.ColouredConsoleSender");
@@ -50,52 +94,10 @@ public class ConsoleLogFormatter extends Formatter {
return stringbuilder.toString(); return stringbuilder.toString();
} }
private void colorize(LogRecord logrecord) { private void colorize(LogRecord logrecord)
// ORIGINAL CODE FROM org.bukkit.craftbukkit.command.ColouredConsoleSender {
final Map<ChatColor, String> replacements = new EnumMap<>(ChatColor.class); String result = ColorizeString(logrecord.getMessage());
logrecord.setMessage(result);
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 = logrecord.getMessage();
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();
logrecord.setMessage(result);
} }
} }

View File

@@ -1,11 +1,21 @@
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.implementations.SSHDCommandSender;
import com.ryanmichela.sshd.ConsoleLogFormatter;
import jline.console.ConsoleReader; 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.Command; import org.apache.sshd.server.shell.ShellFactory;
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;
@@ -13,128 +23,160 @@ import org.bukkit.Bukkit;
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.Level;
import java.util.logging.StreamHandler; import java.util.logging.StreamHandler;
public class ConsoleShellFactory implements Factory<Command> { public class ConsoleShellFactory implements ShellFactory {
static SSHDCommandSender sshdCommandSender = new SSHDCommandSender(); public Command createShell(ChannelSession cs) {
return new ConsoleShell();
}
public Command get() { public class ConsoleShell implements Command, Runnable {
return this.create();
}
public Command create() { private InputStream in;
return new ConsoleShell(); private OutputStream out;
} private OutputStream err;
private ExitCallback callback;
private Environment environment;
private Thread thread;
private String Username;
public static class ConsoleShell implements Command, Runnable { StreamHandlerAppender streamHandlerAppender;
public ConsoleReader ConsoleReader;
public SSHDCommandSender SshdCommandSender;
private InputStream in; public InputStream getIn() {
private OutputStream out; return in;
private OutputStream err; }
private ExitCallback callback;
private Environment environment;
private Thread thread;
StreamHandlerAppender streamHandlerAppender; public OutputStream getOut() {
public static ConsoleReader consoleReader; return out;
}
public InputStream getIn() { public OutputStream getErr() {
return in; return err;
} }
public OutputStream getOut() { public Environment getEnvironment() {
return out; return environment;
} }
public OutputStream getErr() { public void setInputStream(InputStream in) {
return err; this.in = in;
} }
public Environment getEnvironment() { public void setOutputStream(OutputStream out) {
return environment; this.out = out;
} }
public void setInputStream(InputStream in) { public void setErrorStream(OutputStream err) {
this.in = in; this.err = err;
} }
public void setOutputStream(OutputStream out) { public void setExitCallback(ExitCallback callback) {
this.out = out; this.callback = callback;
} }
public void setErrorStream(OutputStream err) { @Override
this.err = err; 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());
public void setExitCallback(ExitCallback callback) { StreamHandler streamHandler = new FlushyStreamHandler(out, new ConsoleLogFormatter(), this.ConsoleReader);
this.callback = callback; streamHandlerAppender = new StreamHandlerAppender(streamHandler);
}
public void start(Environment env) throws IOException { ((Logger)LogManager.getRootLogger()).addAppender(streamHandlerAppender);
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); this.environment = env;
streamHandlerAppender = new StreamHandlerAppender(streamHandler); this.Username = env.getEnv().get(Environment.ENV_USER);
this.SshdCommandSender = new SSHDCommandSender();
this.SshdCommandSender.console = this;
thread = new Thread(this, "SSHD ConsoleShell " + this.Username);
thread.start();
}
catch (Exception e)
{
throw new IOException("Error starting shell", e);
}
}
((Logger) LogManager.getRootLogger()).addAppender(streamHandlerAppender); @Override
public void destroy(ChannelSession cs) { ((Logger)LogManager.getRootLogger()).removeAppender(streamHandlerAppender); }
environment = env; public void run()
thread = new Thread(this, "SSHD ConsoleShell " + env.getEnv().get(Environment.ENV_USER)); {
thread.start(); try
} catch (Exception e) { {
throw new IOException("Error starting shell", e); 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;
}
public void destroy() { Bukkit.getScheduler().runTask(
((Logger) LogManager.getRootLogger()).removeAppender(streamHandlerAppender); SshdPlugin.instance, () ->
} {
if (SshdPlugin.instance.getConfig().getString("Mode").equals("RPC") && command.startsWith("rpc"))
{
// NO ECHO NO PREAMBLE AND SHIT
String cmd = command.substring("rpc".length() + 1, command.length());
Bukkit.dispatchCommand(this.SshdCommandSender, cmd);
}
else
{
SshdPlugin.instance.getLogger().info("<" + this.Username + "> " + command);
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
}
});
}
}
catch (IOException e)
{
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);
}
}
public void run() { private void printPreamble(ConsoleReader cr) throws IOException
try { {
if (!SshdPlugin.instance.getConfig().getString("mode").equals("RPC")) cr.println(" _____ _____ _ _ _____" + "\r");
printPreamble(consoleReader); cr.println(" / ____/ ____| | | | __ \\" + "\r");
while (true) { cr.println("| (___| (___ | |__| | | | |" + "\r");
String command = consoleReader.readLine("\r>", null); cr.println(" \\___ \\\\___ \\| __ | | | |" + "\r");
if (command == null) continue; cr.println(" ____) |___) | | | | |__| |" + "\r");
if (command.equals("exit") || command.equals("quit")) break; cr.println("|_____/_____/|_| |_|_____/" + "\r");
Bukkit.getScheduler().runTask(SshdPlugin.instance, () -> { // Doesn't really guarantee our actual system hostname but
if (SshdPlugin.instance.getConfig().getString("mode").equals("RPC") && // it's better than not having one at all.
command.startsWith("rpc")) { cr.println("Connected to: " + InetAddress.getLocalHost().getHostName() + " (" + Bukkit.getServer().getName() + ")\r");
//NO ECHO NO PREAMBLE AND SHIT cr.println(ConsoleLogFormatter.ColorizeString(Bukkit.getServer().getMotd()) + "\r");
String cmd = command.substring("rpc".length() + 1, command.length()); cr.println("\r");
Bukkit.dispatchCommand(sshdCommandSender, cmd); cr.println("Type 'exit' to exit the shell." + "\r");
} else { cr.println("===============================================" + "\r");
SshdPlugin.instance.getLogger() }
.info("<" + environment.getEnv().get(Environment.ENV_USER) + "> " + command); }
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
}
});
}
} catch (IOException e) {
SshdPlugin.instance.getLogger().log(Level.SEVERE, "Error processing command from SSH", e);
} finally {
callback.onExit(0);
}
}
private void printPreamble(ConsoleReader consoleReader) throws IOException {
consoleReader.println(" _____ _____ _ _ _____" + "\r");
consoleReader.println(" / ____/ ____| | | | __ \\" + "\r");
consoleReader.println("| (___| (___ | |__| | | | |" + "\r");
consoleReader.println(" \\___ \\\\___ \\| __ | | | |" + "\r");
consoleReader.println(" ____) |___) | | | | |__| |" + "\r");
consoleReader.println("|_____/_____/|_| |_|_____/" + "\r");
consoleReader.println("Connected to: " + Bukkit.getServer().getName() + "\r");
consoleReader.println("- " + Bukkit.getServer().getMotd() + "\r");
consoleReader.println("\r");
consoleReader.println("Type 'exit' to exit the shell." + "\r");
consoleReader.println("===============================================" + "\r");
}
}
} }

View File

@@ -1,98 +0,0 @@
package com.ryanmichela.sshd;
import org.apache.commons.codec.binary.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 {
StringBuilder b64 = new StringBuilder();
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,54 +1,82 @@
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.common.config.keys.PublicKeyEntryResolver;
import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator; 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 implements PublickeyAuthenticator
{
private File authorizedKeysDir;
private Map<String, Integer> FailCounts = new HashMap<String, Integer>();
private File authorizedKeysDir; public PublicKeyAuthenticator(File authorizedKeysDir) { this.authorizedKeysDir = authorizedKeysDir; }
public PublicKeyAuthenticator(File authorizedKeysDir) { @Override public boolean authenticate(String username, PublicKey key, ServerSession session)
this.authorizedKeysDir = authorizedKeysDir; {
} byte[] keyBytes = key.getEncoded();
File keyFile = new File(authorizedKeysDir, username);
Integer tries = SshdPlugin.instance.getConfig().getInt("LoginRetries");
@Override if (keyFile.exists())
public boolean authenticate(String username, PublicKey key, ServerSession session) { {
byte[] keyBytes = key.getEncoded(); try
File keyFile = new File(authorizedKeysDir, username); {
// 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);
if (keyFile.exists()) { // Validate that the logging in user has the same valid SSH key
try { if (auth.authenticate(username, key, session))
{
FailCounts.put(username, 0);
return true;
}
else
{
SshdPlugin.instance.getLogger().info(
username + " failed authentication via SSH session using key file " + keyFile.getAbsolutePath());
}
FileReader fr = new FileReader(keyFile); // If the user fails with several SSH keys, then terminate the connection.
PemDecoder pd = new PemDecoder(fr); if (this.FailCounts.containsKey(username))
PublicKey k = pd.getPemBytes(); this.FailCounts.put(username, this.FailCounts.get(username) + 1);
pd.close(); else
this.FailCounts.put(username, 1);
if (k != null) { if (this.FailCounts.get(username) >= tries)
if (ArrayUtils.isEquals(key.getEncoded(), k.getEncoded())) { {
return true; this.FailCounts.put(username, 0);
} session.close(true);
} else { }
SshdPlugin.instance.getLogger().severe("Failed to parse PEM file. " + keyFile.getAbsolutePath());
}
} 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;
} }
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;
}
} }

View File

@@ -7,13 +7,13 @@ import jline.TerminalSupport;
*/ */
public class SshTerminal extends TerminalSupport { public class SshTerminal extends TerminalSupport {
protected SshTerminal() { protected SshTerminal() {
super(true); super(true);
} }
@Override @Override
public void init() throws Exception { public void init() throws Exception {
setAnsiSupported(true); setAnsiSupported(true);
setEchoEnabled(true); setEchoEnabled(true);
} }
} }

View File

@@ -6,6 +6,8 @@ import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory; 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.nio.file.FileSystems;
@@ -15,65 +17,72 @@ import java.util.logging.Level;
/** /**
* Copyright 2013 Ryan Michela * Copyright 2013 Ryan Michela
*/ */
public class SshdPlugin extends JavaPlugin { public
class SshdPlugin extends JavaPlugin
{
private SshServer sshd; private SshServer sshd;
public static SshdPlugin instance; public static SshdPlugin instance;
@Override @Override public void onLoad()
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();
}
// Don't go any lower than INFO or SSHD will cause a stack overflow exception. // Don't go any lower than INFO or SSHD will cause a stack overflow exception.
// SSHD will log that it wrote bites to the output stream, which writes // SSHD will log that it wrote bites to the output stream, which writes
// bytes to the output stream - ad nauseaum. // bytes to the output stream - ad nauseaum.
getLogger().setLevel(Level.INFO); getLogger().setLevel(Level.INFO);
} }
@Override @Override public void onEnable()
public void onEnable() { {
instance = this; instance = this;
sshd = SshServer.setUpDefaultServer(); sshd = SshServer.setUpDefaultServer();
sshd.setPort(getConfig().getInt("port", 22)); sshd.setPort(getConfig().getInt("Port", 1025));
String host = getConfig().getString("listenAddress", "all"); String host = getConfig().getString("ListenAddress", "all");
sshd.setHost(host.equals("all") ? null : host); 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)); sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(hostKey.toPath()));
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")) { if (getConfig().getBoolean("EnableSFTP"))
sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory())); {
sshd.setFileSystemFactory(new VirtualFileSystemFactory( sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory()));
FileSystems.getDefault().getPath( sshd.setFileSystemFactory(
getDataFolder().getAbsolutePath() new VirtualFileSystemFactory(FileSystems.getDefault().getPath(getDataFolder().getAbsolutePath()).getParent().getParent()));
).getParent().getParent() }
));
}
sshd.setCommandFactory(new ConsoleCommandFactory()); sshd.setCommandFactory(new ConsoleCommandFactory());
try { try
sshd.start(); {
} catch (IOException e) { sshd.start();
getLogger().log(Level.SEVERE, "Failed to start SSH server! ", e); }
} catch (IOException e)
} {
getLogger().log(Level.SEVERE, "Failed to start SSH server! ", e);
}
}
@Override @Override public void onDisable()
public void onDisable() { {
try { try
sshd.stop(); {
} catch (Exception e) { sshd.stop();
// do nothing }
} catch (Exception e)
} {
// do nothing
}
}
} }

View File

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

View File

@@ -9,70 +9,70 @@ import java.util.LinkedList;
import java.util.logging.Level; import java.util.logging.Level;
public class SSHDConversationTracker { public class SSHDConversationTracker {
private LinkedList<Conversation> conversationQueue = new LinkedList<>(); private LinkedList<Conversation> conversationQueue = new LinkedList<>();
synchronized boolean beginConversation(Conversation conversation) { synchronized boolean beginConversation(Conversation conversation) {
if (!this.conversationQueue.contains(conversation)) { if (!this.conversationQueue.contains(conversation)) {
this.conversationQueue.addLast(conversation); this.conversationQueue.addLast(conversation);
if (this.conversationQueue.getFirst() == conversation) { if (this.conversationQueue.getFirst() == conversation) {
conversation.begin(); conversation.begin();
conversation.outputNextPrompt(); conversation.outputNextPrompt();
return true; return true;
} }
} }
return true; return true;
} }
synchronized void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) { synchronized void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) {
if (!this.conversationQueue.isEmpty()) { if (!this.conversationQueue.isEmpty()) {
if (this.conversationQueue.getFirst() == conversation) { if (this.conversationQueue.getFirst() == conversation) {
conversation.abandon(details); conversation.abandon(details);
} }
if (this.conversationQueue.contains(conversation)) { if (this.conversationQueue.contains(conversation)) {
this.conversationQueue.remove(conversation); this.conversationQueue.remove(conversation);
} }
if (!this.conversationQueue.isEmpty()) { if (!this.conversationQueue.isEmpty()) {
this.conversationQueue.getFirst().outputNextPrompt(); this.conversationQueue.getFirst().outputNextPrompt();
} }
} }
} }
public synchronized void abandonAllConversations() { public synchronized void abandonAllConversations() {
LinkedList<Conversation> oldQueue = this.conversationQueue; LinkedList<Conversation> oldQueue = this.conversationQueue;
this.conversationQueue = new LinkedList<>(); this.conversationQueue = new LinkedList<>();
for (Conversation conversation : oldQueue) { for (Conversation conversation : oldQueue) {
try { try {
conversation.abandon(new ConversationAbandonedEvent(conversation, new ManuallyAbandonedConversationCanceller())); conversation.abandon(new ConversationAbandonedEvent(conversation, new ManuallyAbandonedConversationCanceller()));
} catch (Throwable var5) { } catch (Throwable var5) {
Bukkit.getLogger().log(Level.SEVERE, "Unexpected exception while abandoning a conversation", var5); Bukkit.getLogger().log(Level.SEVERE, "Unexpected exception while abandoning a conversation", var5);
} }
} }
} }
synchronized void acceptConversationInput(String input) { synchronized void acceptConversationInput(String input) {
if (this.isConversing()) { if (this.isConversing()) {
Conversation conversation = this.conversationQueue.getFirst(); Conversation conversation = this.conversationQueue.getFirst();
try { try {
conversation.acceptInput(input); conversation.acceptInput(input);
} catch (Throwable var4) { } 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); 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() { synchronized boolean isConversing() {
return !this.conversationQueue.isEmpty(); return !this.conversationQueue.isEmpty();
} }
public synchronized boolean isConversingModaly() { public synchronized boolean isConversingModaly() {
return this.isConversing() && this.conversationQueue.getFirst().isModal(); return this.isConversing() && this.conversationQueue.getFirst().isModal();
} }
} }

View File

@@ -1,22 +1,35 @@
# The IP addresses(s) the SSH server will listen on. Use a comma separated list for multiple addresses. # The IP addresses(s) the SSH server will listen on. Use a comma separated list for multiple addresses.
# Leave as "all" for all addresses. # Leave as "all" for all addresses.
listenAddress: all ListenAddress: all
# The port the SSH server will listen on. # The port the SSH server will listen on. Note that anything above 1024 will require you to run
port: 22 # 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 # Operational mode. Don't touch if you don't know what you're doing. Can be either DEFAULT or RPC
mode: DEFAULT Mode: DEFAULT
# Enable built-in SFTP server or not. You'll be able to connect and upload/download files via SFTP protocol. # 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. # Might be useful for testing purposes as well , i. e. docker containers.
enableSFTP: true 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 log in with public key authentication, install their public # To authorize a user to login with their public key, install their key using the
# PEM certificate in the authorized_users directory. Name the key file with user's user # OpenSSH authorized_keys file format in the authorized_users directory. Name the key
# name (no file extension). # file with the user's username and no extension. Note: If you want to let a user have
# 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

View File

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