blob: fff70caebc91f2fd1a313f4338da7ec8c5e5076d (
plain) (
tree)
|
|
package org.openslx.taskmanager.tasks;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.io.FileUtils;
import org.openslx.satserver.util.Archive;
import org.openslx.satserver.util.Util;
import org.openslx.taskmanager.api.AbstractTask;
import com.google.gson.annotations.Expose;
public class SshdConfigGenerator extends AbstractTask
{
@Expose
private int listenPort = 0;
@Expose
private String allowPasswordLogin = "no";
@Expose
private String publicKey = "";
@Expose
private String filename = null;
private Output status = new Output();
@Override
protected boolean initTask()
{
this.setStatusObject( status );
if ( !Util.isAllowedDir( this.filename ) )
status.error = "Invalid directory for " + this.filename;
if ( allowPasswordLogin == null || ( !allowPasswordLogin.equals( "yes" ) && !allowPasswordLogin.equals( "no" ) ) )
status.error = "Invalid value for allowPasswordLogin: " + allowPasswordLogin;
if ( listenPort > 65535 || listenPort < 1 )
status.error = "Invalid value for listenPort: " + listenPort;
if ( publicKey != null && !publicKey.isEmpty() && !publicKey.matches( "^[a-z0-9\\-]+ [A-Za-z0-9=/\\+]+ .*" ) )
status.error = "Invalid public key: '" + publicKey + "'";
return status.error == null;
}
@Override
protected boolean execute()
{
TarArchiveOutputStream outArchive = null;
try {
// Prepare sshd config
String template;
try {
template = FileUtils.readFileToString( new File( "./data/sshd_config.template" ), StandardCharsets.UTF_8 );
} catch ( IOException e ) {
status.error = e.toString();
return false;
}
template = template.replace( "%PORT%", Integer.toString( this.listenPort ) );
template = template.replace( "%PASSWORDLOGIN%", allowPasswordLogin );
try {
outArchive = Archive.createTarArchive( this.filename );
} catch ( IOException e ) {
status.error = "Could not create archive at " + this.filename;
return false;
}
boolean ok = Archive.tarCreateFileFromString( outArchive, "/etc/ssh/sshd_config", template, 0644 );
if ( publicKey != null && !publicKey.isEmpty() ) {
String name = "sshd_conf_mod-" + publicKey.hashCode() + "-" + System.currentTimeMillis() + ".pub";
ok |= Archive.tarCreateFileFromString( outArchive, "/root/.ssh/authorized_keys.d/" + name, publicKey, 0600 );
}
ok |= Archive.tarCreateSymlink( outArchive, "../sshd.service", "/etc/systemd/system/network.target.wants/sshd.service" );
if ( !ok ) {
status.error = "Could not create module archive contents";
return false;
}
} finally {
Util.multiClose( outArchive );
}
return true;
}
/**
* Output - contains additional status data of this task
*/
private static class Output
{
protected String error = null;
}
}
|