using git with apache sshd - java

I'm trying to use msysgit over an SSH server I wrote in Java using sshd and I have made great progress in that i got past some git errors, I am able to connect using putty and get a shell, I have git in my windows path, but I still can't actually use git to connect to my repository over my ssh daemon. I get the following error from msysgit:
fatal: ''/C/gitrepo'' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
I used the following to add the remote to the repo I'm trying to connect from:
git remote set-url origin "ssh://test#localhost:22/C/gitrepo".
I tried a lot of other variations as well of the path with no luck. I have two git repos set up on localhost, the one i'm running git push from and the one at c:\gitrepo.
What am I missing?
Also I had to add the path to mysysgit/bin to my windows 7 environment variable, but would also like a way to get this to work without adding it to my windows environment variables but specifying it programmatically in my ssh server, but more importantly I would like to be able to run git over this ssh server.
The code for my server is below.
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import org.apache.sshd.SshServer;
import org.apache.sshd.server.UserAuth;
import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.util.OsUtils;
import org.apache.sshd.server.Command;
import org.apache.sshd.server.CommandFactory;
import org.apache.sshd.server.ForwardingFilter;
import org.apache.sshd.server.PasswordAuthenticator;
import org.apache.sshd.server.auth.UserAuthPassword;
import org.apache.sshd.server.command.ScpCommandFactory;
import org.apache.sshd.server.filesystem.NativeFileSystemFactory;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.apache.sshd.server.session.ServerSession;
import org.apache.sshd.server.shell.ProcessShellFactory;
public class SSHD {
public SSHD() {
init();
}
public void start() throws IOException {
sshServer.start();
}
private void init() {
sshServer = SshServer.setUpDefaultServer();
sshServer.setPort(22);
sshServer.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("hostkey.ser"));
setupAuthentication();
setupCommandHandling();
}
private void setupAuthentication() {
sshServer.setPasswordAuthenticator(new SSHD.MyPasswordAuthenticator());
List<NamedFactory<UserAuth>> userAuthFactories = new ArrayList<NamedFactory<UserAuth>>();
userAuthFactories.add(new UserAuthPassword.Factory());
sshServer.setUserAuthFactories(userAuthFactories);
}
private void setupCommandHandling() {
CommandFactory myCommandFactory = new CommandFactory() {
#Override
public Command createCommand(String command) {
System.out.println("command = \"" + command + "\"");
return new ProcessShellFactory(command.split(" ")).create();
}
};
sshServer.setCommandFactory(new ScpCommandFactory(myCommandFactory));
sshServer.setFileSystemFactory(new NativeFileSystemFactory());
sshServer.setForwardingFilter(new ForwardingFilter() {
public boolean canForwardAgent(ServerSession session) {
return true;
}
public boolean canForwardX11(ServerSession session) {
return true;
}
public boolean canListen(InetSocketAddress address, ServerSession session) {
return true;
}
public boolean canConnect(InetSocketAddress address, ServerSession session) {
return true;
}
});
ProcessShellFactory shellFactory = null;
if (OsUtils.isUNIX()) {
shellFactory = new ProcessShellFactory(new String[]{"/bin/sh", "-i", "-l"},
EnumSet.of(ProcessShellFactory.TtyOptions.ONlCr));
} else {
shellFactory = new ProcessShellFactory(new String[]{"cmd.exe "},
EnumSet.of(ProcessShellFactory.TtyOptions.Echo, ProcessShellFactory.TtyOptions.ICrNl, ProcessShellFactory.TtyOptions.ONlCr));
}
sshServer.setShellFactory(shellFactory);
}
private static class MyPasswordAuthenticator implements PasswordAuthenticator {
#Override
public boolean authenticate(String username, String password, ServerSession session) {
return true;
}
}
public static void main(String[] args) {
SSHD sshd = new SSHD();
try {
sshd.start();
} catch (IOException ex) {
System.out.println("EXCEPTION: " + ex);
ex.printStackTrace();
}
}
private SshServer sshServer;
}
Does anybody know how to fix this manual parsing on the server side. Is there a different command processor I can use or something like that?

Related

Server doesn't enable my spigot plugin. (It doesn't even try)

I'm basically making a spigot plugin, for practice.
The server doesn't enable the server, no error in the console. It also no "INFO" for enabling the plugin.
This is my main class
package me.FarrosGaming.SpawnPillager;
import org.bukkit.plugin.java.JavaPlugin;
import me.FarrosGaming.SpawnPillager.commands.PillagerCommand;
public class Main extends JavaPlugin {
#Override
public void onEnable() {
new PillagerCommand(this);
}
#Override
public void onDisable() {
}
}
This is my command class
package me.FarrosGaming.SpawnPillager.commands;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import me.FarrosGaming.SpawnPillager.Main;
public class PillagerCommand implements CommandExecutor {
private Main plugin;
public PillagerCommand(Main plugin) {
this.plugin = plugin;
plugin.getCommand("chase").setExecutor(this);
}
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("Only players who can send this command.");
return true;
}
Player player = (Player) sender;
if (player.hasPermission("hello.use")) {
Location location = player.getLocation();
World world = player.getWorld();
for (int i = 0; i < 10; i++) {
world.spawnEntity(location, EntityType.CREEPER);
}
return true;
} else {
player.sendMessage("You do not have a permission to use this command");
}
return false;
}
}
this is my plugin.yml file
name: SpawnPillager
version: 1.0
author: FarrosGaming
description: blabla
main: me.FarrosGaming.SpawnPillager.Main
commands:
chase:
description: Spawn pillager in your location
usage: /chase
Literally, there are no spaces in the plugin.yml
I'm using the newest version of spigot.
make sure you are dropping your plugin's Jar in the right spot, i mean the right server's plugins folder, if you multiple and then reload/ restart your server,
I m telling this coz, me myself, have done this mistake too..

NotBoundException when I'm trying to connect with RMI server

I try to launch this app using RMI client-server.
Firstly, I ran it and had the error "Connection refused to host: localhost".
After that I went go system32/drivers/etc/hosts and fix it, added line:
127.0.0.1 localhost
It wasn't led me to problem solution.
Then I looked up same questions in stackoverflow about how to fix this problem, then solved it with (ran in cmd):
start rmiregistry
So, rmiregistry ran and i had got a new error - NotBoundException (but I could fix "Connection refusal" problem).
servicebrowser.java:
package servicebrowser;
import java.awt.*;
import javax.swing.*;
import java.rmi.*;
import java.awt.event.*;
public class ServiceBrowser {
JPanel mainPanel;
JComboBox serviceList;
ServiceServer server;
public void buildGUI() {
Object[] services = getServicesList();
}
Object[] getServicesList() {
Object obj = null;
Object[] services = null;
try {
obj = Naming.lookup("rmi://127.0.0.1/ServiceServer");
}
catch (Exception ex) { ex.printStackTrace(); }
server = (ServiceServer) obj;
try {
services = server.getServiceList();
}
catch (Exception ex) { ex.printStackTrace(); }
return services;
}
class MyListListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
Object selection = serviceList.getSelectedItem();
loadService(selection);
}
}
public static void main(String[] args) {
new ServiceBrowser().buildGUI();
}
}
class ServiceServerImpl:
import java.rmi.*;
import java.util.*;
import java.rmi.server.*;
public class ServiceServerImpl extends UnicastRemoteObject
implements ServiceServer {
HashMap serviceList;
public ServiceServerImpl() throws RemoteException {
setUpServices();
}
private void setUpServices() {
serviceList = new HashMap();
}
public Object[] getServiceList() {
System.out.println("in remote");
return serviceList.keySet().toArray();
}
public Service getService(Object serviceKey) throws RemoteException {
Service theService = (Service) serviceList.get(serviceKey);
return theService;
}
public static void main (String[] args) {
try {
Naming.rebind("ServiceServer", new ServiceServerImpl());
}
catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Remote service is running");
}
}
What is wrong with it? I turned off firewall too, certaintly.
Thanks a lot!
I solved my problem right this way.
Firstly, I edited classes servicebrowser, ServiceServerImpl.
class servicebrowser:
Before:
try {
obj = Naming.lookup("rmi://127.0.0.1/ServiceServer");
}
Now (plus I added import java.rmi.registry.LocateRegistry, import java.rmi.registry.Registry in top part of code):
try {
Registry registry = LocateRegistry.getRegistry("127.0.0.1", 10001);
obj = registry.lookup("ServiceServer");
}
class ServiceServerImpl:
Before:
try {
Naming.rebind("ServiceServer", new ServiceServerImpl());
}
Now (like a previous class I added import classes in top part of code):
try {
Registry registry = LocateRegistry.createRegistry(10001);
registry.bind("ServiceServer", new ServiceServerImpl());
}
Secondly, I try to ran project (F6) in Netbeans, where servicebrowser marked as main class. It was refusal connection again. After that I only ran class ServiceServerImpl (Shift + F6) then ran entire projecе. So, it works.
P.S. I didn't use cmd and try to
"start rmiregistry"
because the app works without it.

Using proxy for specific HTTPS request in java

I have requirement to pass HTTPs calls of some specific URL via proxy and rest direct. I have written my own custom proxy implementation using ProxySelector of java.net. It is working fine for HTTP calls ( I can see in proxy access logs in that case) but in case of HTTPS calls it seems it is not using proxy).Am I missing something here.? Proxy server is configured properly and its access log is updating when some HTTPS calls passed from browser with proxy.
package com.blabla.proxy;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.vuclip.pubsub.logging.PubSubUtil;
import com.vuclip.pubsub.logging.client.GooglePubSubClient;
public class CustomProxySelector extends ProxySelector {
private static final Logger LOGGER = LogManager.getLogger(PubSubUtil.class);
private final ProxySelector def;
private final String PUB_SUB_URL = "pubsub.googleapis.com";
List<Proxy> proxyList = new ArrayList<Proxy>();
private Proxy proxy=null;
public CustomProxySelector(ProxySelector aDefault) {
this.def = aDefault;
}
#Override
public void connectFailed(URI arg0, SocketAddress soc, IOException ex) {
LOGGER.error("Error in connecting to proxcy "+soc +" for pubsub :"+ ex);
}
#Override
public List<Proxy> select(URI uri) {
if ("https".equalsIgnoreCase(uri.getScheme()) && uri.getHost().startsWith(PUB_SUB_URL)
&& GooglePubSubClient.isProxyEnabled()) {
synchronized (this) {
if (proxy == null) {
proxy = new Proxy(Proxy.Type.SOCKS,
new InetSocketAddress(GooglePubSubClient.getProxyHost(), GooglePubSubClient.getProxyPort()));
}
}
proxyList.add(proxy);
LOGGER.debug("ProxyList:" + proxyList);
return proxyList;
}
proxyList = def.select(uri);
LOGGER.debug("Default proxy list : " + proxyList);
return proxyList;
}
}
I changed Proxy.Type.SOCKS to Proxy.Type.HTTP and it worked for me.

RMI programme: Client side giving Error

I am creating RMI program for my class assignment in Netbeans. It is a simple RMI program and The server side is working properly. But as I run my client side file. It ends up giving me error
Exception in thread "main" java.security.AccessControlException: access denied ("java.net.SocketPermission" "127.0.0.1:1099" "connect,resolve")
plus it is saying some error at line 26 at client code.
For clear understanding I am giving full code of all three files.
Interface.java :
package RMI;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface DemoInterface extends Remote {
public String SayDemo() throws RemoteException;
}
Server.java
package RMI;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class Server implements Interface{
public Server()
{
super();
}
private String message;
public Server(String msg) throws RemoteException
{
message = msg;
}
public static void main(String[] args) {
try {
DemoInterface h = new Server("Hello");
DemoInterface stub = (DemoInterface) UnicastRemoteObject.exportObject(h,0);
LocateRegistry.createRegistry(4096);
Registry registry = LocateRegistry.getRegistry("127.0.0.1",4096);
registry.rebind("Hello", stub);
System.out.println("Server is connected and ready to use");
}
catch(Exception e)
{
System.out.println("server not connected\n"+e);
}
}
#Override
public String SayDemo() throws RemoteException {
System.out.println("Server.saydemo override");
return message;
}
}
Client.java
package RMI;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
public static void main(String[] args) {
if(System.getSecurityManager() == null)
{
System.setSecurityManager(new SecurityManager());
}
try {
Registry reg = LocateRegistry.getRegistry("127.0.0.1", 4096);
System.out.println("in try after reg locate");
DemoInterface h = (DemoInterface) reg.lookup("Hello");//Error Showed on this line by netbeans
System.out.println(h.SayDemo());
}
catch(RemoteException | NotBoundException e)
{
System.out.println(""+e );
}
}
}
please guide me where I am wrong. Thank You in advance.
You set a SecurityManager in your client main method. Did you also provide a security policy file? The default policy is not very permissive, and denies, among other things, Socket operations.
You can specify a policy that allows all permissions to all code bases like so.
grant {
permission java.security.AllPermission;
};
add it to your command line for invoking java. Substitute mypolicy for your policy file and SomeApp for your main class. Note the two = characters in the second argument
java -Djava.security.manager -Djava.security.policy==mypolicy SomeApp
Note that this is not a safe policy to run for RMI in a production environment (RMI can load remote code bases).
Proper use of the SecurityManager class and policy configuration is a complex topic, for further reading I suggest Java SE 7 Security Documentation and in particular Default Policy Implementation and Policy File Syntax

Getting the 'external' IP address in Java

I'm not too sure how to go about getting the external IP address of the machine as a computer outside of a network would see it.
My following IPAddress class only gets the local IP address of the machine.
public class IPAddress {
private InetAddress thisIp;
private String thisIpAddress;
private void setIpAdd() {
try {
InetAddress thisIp = InetAddress.getLocalHost();
thisIpAddress = thisIp.getHostAddress().toString();
} catch (Exception e) {
}
}
protected String getIpAddress() {
setIpAdd();
return thisIpAddress;
}
}
I am not sure if you can grab that IP from code that runs on the local machine.
You can however build code that runs on a website, say in JSP, and then use something that returns the IP of where the request came from:
request.getRemoteAddr()
Or simply use already-existing services that do this, then parse the answer from the service to find out the IP.
Use a webservice like AWS and others
import java.net.*;
import java.io.*;
URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);
One of the comments by #stivlo deserves to be an answer:
You can use the Amazon service http://checkip.amazonaws.com
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class IpChecker {
public static String getIp() throws Exception {
URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
String ip = in.readLine();
return ip;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
The truth is: 'you can't' in the sense that you posed the question. NAT happens outside of the protocol. There is no way for your machine's kernel to know how your NAT box is mapping from external to internal IP addresses. Other answers here offer tricks involving methods of talking to outside web sites.
All this are still up and working smoothly! (as of 10 Feb 2022)
http://checkip.amazonaws.com/
https://ipv4.icanhazip.com/
http://myexternalip.com/raw
http://ipecho.net/plain
http://www.trackip.net/ip
http://bot.whatismyipaddress.com (10 Feb 2022)
http://curlmyip.com/ (17 Dec 2016)
Piece of advice: Do not direcly depend only on one of them; try to use one but have a contigency plan considering others! The more you use, the better!
Good luck!
As #Donal Fellows wrote, you have to query the network interface instead of the machine. This code from the javadocs worked for me:
The following example program lists all the network interfaces and their addresses on a machine:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;
public class ListNets {
public static void main(String args[]) throws SocketException {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
out.printf("Display name: %s\n", netint.getDisplayName());
out.printf("Name: %s\n", netint.getName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
out.printf("InetAddress: %s\n", inetAddress);
}
out.printf("\n");
}
}
The following is sample output from the example program:
Display name: TCP Loopback interface
Name: lo
InetAddress: /127.0.0.1
Display name: Wireless Network Connection
Name: eth0
InetAddress: /192.0.2.0
From docs.oracle.com
Make a HttpURLConnection to some site like www.whatismyip.com and parse that :-)
How about this? It's simple and worked the best for me :)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class IP {
public static void main(String args[]) {
new IP();
}
public IP() {
URL ipAdress;
try {
ipAdress = new URL("http://myexternalip.com/raw");
BufferedReader in = new BufferedReader(new InputStreamReader(ipAdress.openStream()));
String ip = in.readLine();
System.out.println(ip);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
http://jstun.javawi.de/ will do it - provided your gateway device does STUN )most do)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.regex.Pattern;
public class ExternalIPUtil {
private static final Pattern IPV4_PATTERN = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
private static final String[] IPV4_SERVICES = {
"http://checkip.amazonaws.com/",
"https://ipv4.icanhazip.com/",
"http://bot.whatismyipaddress.com/"
// and so on ...
};
public static String get() throws ExecutionException, InterruptedException {
List<Callable<String>> callables = new ArrayList<>();
for (String ipService : IPV4_SERVICES) {
callables.add(() -> get(ipService));
}
ExecutorService executorService = Executors.newCachedThreadPool();
try {
return executorService.invokeAny(callables);
} finally {
executorService.shutdown();
}
}
private static String get(String url) throws IOException {
try (BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream()))) {
String ip = in.readLine();
if (IPV4_PATTERN.matcher(ip).matches()) {
return ip;
} else {
throw new IOException("invalid IPv4 address: " + ip);
}
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("IP: " + get());
}
}
Get from multiple IP services concurrently such as:
http://checkip.amazonaws.com/
https://ipv4.icanhazip.com/
http://bot.whatismyipaddress.com/
and so on ...
and ExecutorService.invokeAny(tasks) return the result of the first successfully thread. Other tasks that have not completed will be cancelled.
It's not that easy since a machine inside a LAN usually doesn't care about the external IP of its router to the internet.. it simply doesn't need it!
I would suggest you to exploit this by opening a site like http://www.whatismyip.com/ and getting the IP number by parsing the html results.. it shouldn't be that hard!
If you are using JAVA based webapp and if you want to grab the client's (One who makes the request via a browser) external ip try deploying the app in a public domain and use request.getRemoteAddr() to read the external IP address.
System.out.println(pageCrawling.getHtmlFromURL("http://ipecho.net/plain"));
An alternative solution is to execute an external command, obviously, this solution limits the portability of the application.
For example, for an application that runs on Windows, a PowerShell command can be executed through jPowershell, as shown in the following code:
public String getMyPublicIp() {
// PowerShell command
String command = "(Invoke-WebRequest ifconfig.me/ip).Content.Trim()";
String powerShellOut = PowerShell.executeSingleCommand(command).getCommandOutput();
// Connection failed
if (powerShellOut.contains("InvalidOperation")) {
powerShellOut = null;
}
return powerShellOut;
}

Categories

Resources