Question

Linux SSH connection failure

Asked by: shanemay

I am writing a Servlet that will SSH to a Linux machine and run a command. I am authenticating via a private key.  I am watching the SSH logs on the Linux server and my application hangs at the following:  debug1: expecting SSH2_MSG_NEWKEYS.  I am not sure what I am missing.  I am not sure what is it looking for.  Any help or guidance would be greatly appreciated.    

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-11-06 at 06:57:12ID24878005
Tags

Java

,

JSP

Topics

Java Programming Language

,

Java Server Pages (JSP)

Participating Experts
3
Points
500
Comments
33

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. SSH
    Hi,I've got several servers and all of them run ssh. I've just added another server, but I'm unable to establish an ssh connection to it. I cant connect to it from my pc, or from any of the other servers. All the other servers can connect to each other. The error Im getting w...
  2. ssh hangs on Solaris
    hi there, Some times my SSH hangs after executing a command it does not come back to the command prompt. I am executing a command like this.. $ ssh user@server "command" For most of the commands it works fine. My OS is Solaris, and login shell is kshell. Looki...
  3. SSH Upgrade
    Hi, I wanted to upgrade my SSH version on Solaris9 OS. I currently have "SSH Version Sun_SSH_1.0, protocol versions 1.5/2.0." and want to upgrade to Sun_SSH_1.1. Any help would be highly appreciated. rte
  4. Pre-testing ssh connection
    I have to administer many RHEL4 linux nodes from my desktop. I do this by passing commands from the desktop to remote nodes through a trusted ssh channel. It works fine except when the remote node is in a semi-dead state such that network is alive, remote ssh server accepts c...
  5. SSH Hangs
    Hi Freinds, I'm using Redhat 4.5 64 bits. I use ssh for remote management. Currently i'm facing an issue regarding ssh hang. In my system ssh server gets hang after 1 hours and then i need to restart the service again for that i need to access system physically. Please provi...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: CEHJPosted on 2009-11-06 at 07:07:12ID: 25759701

Are you sure that key is accessible to your app?

 

by: shanemayPosted on 2009-11-06 at 07:08:50ID: 25759717

I am, I parse a key file and load it.  I also verify that I can open the key using the pass Phrase.  I have also connected to the server with Putty and the key to make sure that it works.  I am using J2ssh SSHtools.

 

by: shanemayPosted on 2009-11-06 at 07:09:38ID: 25759725

What is the server looking for with SSH2_MSG_NEWKEYS?

 

by: CEHJPosted on 2009-11-06 at 07:30:03ID: 25759913

I think that happens during the exchange of session keys. Compare a trace of your app as client and a standard ssh client as client

 

by: shanemayPosted on 2009-11-06 at 08:00:13ID: 25760254

I am not getting much information that is useful.  I have removed the part of my code that tries to authenticate via the private key and the results are the same.  It is not finishing the hand-shake so I can pass on my authentication information.  I have searched for information on SSH2_MSG_NEWKEYS.  I am not finding much that is useful.  The problem is I am not sure if it is a setting on the server, maybe an obscure network setting, or an issue with my code.  Very Frustrating.  

 

by: CEHJPosted on 2009-11-07 at 01:19:37ID: 25765552

I had a look for info on SSH2 and i must say that's not entirely easy to find either.

I think it's probably worth looking into the the client settings of your api, as there might be something like a setting that needs to be set explicitly.

Failing that, it might be a good idea to try to contact the authors. Keep us posted!

 

by: klymptzicPosted on 2009-11-07 at 03:10:12ID: 25765803

I have used 'jsch' libraries to run a linux command from a Java desktop application. Not sure of the SSHTools.

Why dont you try http://www.jcraft.com/jsch/

 

by: shanemayPosted on 2009-11-07 at 04:21:47ID: 25766001

I may have to try Jcraft, and I agree about the settings for the api.  The properties conf that you use to manage the connection is not well documented.  I think I will try jcraft.  Also, I have reached out to a red hat engineer to see if they have any suggestions.  I will let you know.  Thank you for your time and effort on my behalf.  

 

by: shanemayPosted on 2009-11-07 at 04:25:14ID: 25766011

Do you have a code sample for jsch? Thank you.

 

by: klymptzicPosted on 2009-11-07 at 05:16:55ID: 25766205

The site itself has list of examples. Please go thru it...

http://www.jcraft.com/jsch/examples/

You might be interested in Shell.java or Exec.java. Please go thru the description of each program

 

by: diepesPosted on 2009-11-08 at 01:21:31ID: 25769903

Have tried to login using ssh on a desktop to the server ?
does is work with key authentication ?

 

by: shanemayPosted on 2009-11-08 at 03:05:33ID: 25770117

Yes it does, I am using putty.  It works fine.  

 

by: CEHJPosted on 2009-11-08 at 04:13:05ID: 25770240

Could you post runnable code and i'll try it on my server as i use the same kind of authentication?

 

by: shanemayPosted on 2009-11-08 at 10:29:54ID: 25771296

Here is the code that I am using.  Here are the imports.  

import com.sshtools.j2ssh.connection.ChannelInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PublicKeyAuthenticationClient;
import com.sshtools.j2ssh.session.SessionChannelClient;
import com.sshtools.j2ssh.transport.publickey.SshPrivateKey;
import com.sshtools.j2ssh.transport.publickey.SshPrivateKeyFile;
import com.sshtools.j2ssh.configuration.ConfigurationLoader;
import com.sshtools.j2ssh.configuration.SshConnectionProperties;
import java.io.BufferedReader;
import java.io.InputStreamReader;

I am using version 0.2.9
http://sourceforge.net/projects/sshtools/

Thank you for your help, if it works for you then I know that I have a server issue.  

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter(); 
        ConfigurationLoader.initialize(false); 
        SshConnectionProperties properties = new SshConnectionProperties();
        properties.setHost("hostName");
        properties.setPort(22);
        properties.setPrefCSEncryption("blowfish-cbc"); 
        // Make a client connection
        SshClient ssh = new SshClient(); 
        // Connect to the host
        ssh.connect(properties);
        
        PublicKeyAuthenticationClient pk = new PublicKeyAuthenticationClient(); 
        // Get the users name
        String username = "username";
        pk.setUsername(username); 
        // Get the private key file
        String filename = "C:\\Path to key";
        // Open up the private key file
        SshPrivateKeyFile file = SshPrivateKeyFile.parse(new File(filename)); 
        // If the private key is passphrase protected then ask for the passphrase
        String passphrase = "passPhrase";
        
        // Get the key
        SshPrivateKey key = file.toPrivateKey(passphrase);
        pk.setKey(key); 
        // Try the authentication
        int result = ssh.authenticate(pk); 
        // Evaluate the result
        if (result == AuthenticationProtocolState.COMPLETE)
        {
            // The connection is authenticated we can now do some real work!
            SessionChannelClient session = ssh.openSessionChannel();
            if(!session.requestPseudoTerminal("vt100", 80, 24, 0, 0, ""))
            {
                out.println("Failed to allocate a pseudo terminal");
            }
            if(session.startShell())
            {
                out.println("Session Shell Started!"); 
                String line = "";
                ChannelInputStream in = session.getInputStream(); 
                session.executeCommand("date +%Y-%m-%d");
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                StringBuffer buffer = new StringBuffer(); 
                while ((line = br.readLine()) != null)
                {
                    buffer.append(line);
                } 
                String output = buffer.toString();
                out.println(output);
            }
            else
            {
                out.println("Failed to start the users shell");
            } 
            ssh.disconnect();
        }
        else if (result == AuthenticationProtocolState.PARTIAL)
        {
            out.println("Further authentication requried!");
        }
        else if (result == AuthenticationProtocolState.FAILED)
        {
            out.println("Authentication failed!");
        }
        else
        {
           out.println("Error");
        } 
        out.close();
    }
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:

Select allOpen in new window

 

by: CEHJPosted on 2009-11-08 at 10:56:41ID: 25771412

>>properties.setPrefCSEncryption("blowfish-cbc");

Are you sure that's right? My server uses RSA

 

by: shanemayPosted on 2009-11-08 at 11:12:10ID: 25771464

Yes, I verified this with our security specialist.  However, I may research using RSA.  Again, thank you for your help.

 

by: CEHJPosted on 2009-11-08 at 11:16:33ID: 25771480

What happens when you remove that line?

 

by: shanemayPosted on 2009-11-08 at 11:18:56ID: 25771488

Same result.  I believe that blowfish is the default used when one is not explicitly set.  I get the same result with DES and RSA.  I am beginning to think that it is a server issue.  I am interested to see if you are able to get this work.

 

by: CEHJPosted on 2009-11-08 at 12:59:19ID: 25771857

I see you''re in a JSP. Are you sure you've checked the log files for exceptions?

 

by: shanemayPosted on 2009-11-08 at 13:51:15ID: 25772097

That I did, I am also watching the ssh secure log to see what is happening.  The problem I am having is this is like a black hole, I am getting nothing.

 

by: CEHJPosted on 2009-11-08 at 14:55:08ID: 25772420

I get a session but then i get  a problem with 'channel request failed'

 

by: shanemayPosted on 2009-11-08 at 17:08:10ID: 25772844

ok, much further than I.  I think I might have a server issue.  I will meet with out Red Hat engineer tomorrow.  I will let you know what I find.  

 

by: shanemayPosted on 2009-11-08 at 20:52:26ID: 25773474

How did you authenticate via RSA?  What string did you place in properties.setPrefCSEncryption("")?  Thank you. Could you post the code that you used to gain a successful session?

 

by: CEHJPosted on 2009-11-09 at 01:33:26ID: 25774471

Try the following - you can probably get rid of some imports and i'm not entirely convinced cleanup is thorough. Run it without arguments first for usage

import com.sshtools.j2ssh.configuration.*;
import java.util.Scanner;
import java.io.*; 
import com.sshtools.j2ssh.*;
import com.sshtools.j2ssh.agent.*;
import com.sshtools.j2ssh.authentication.*;
import com.sshtools.j2ssh.configuration.*;
import com.sshtools.j2ssh.connection.*;
import com.sshtools.j2ssh.forwarding.*;
import com.sshtools.j2ssh.io.*;
import com.sshtools.j2ssh.net.*;
import com.sshtools.j2ssh.openssh.*;
import com.sshtools.j2ssh.session.*;
import com.sshtools.j2ssh.sftp.*;
import com.sshtools.j2ssh.subsystem.*;
import com.sshtools.j2ssh.transport.*;
import com.sshtools.j2ssh.transport.cipher.*;
import com.sshtools.j2ssh.transport.compression.*;
import com.sshtools.j2ssh.transport.hmac.*;
import com.sshtools.j2ssh.transport.kex.*;
import com.sshtools.j2ssh.transport.publickey.*;
import com.sshtools.j2ssh.transport.publickey.dsa.*;
import com.sshtools.j2ssh.transport.publickey.rsa.*;
import com.sshtools.j2ssh.util.*; 
public class SshTest {
    public static void main(String[] args) throws Exception {
	if (args.length < 4) {
	    SshTest.printUsage();
	    System.exit(-1);
	}
	String host = args[0];
	String user = args[1];
	String pkFile = args[2];
	String passphrase = args[3];
	PrintStream out = System.out;
	ConfigurationLoader.initialize(false); 
	SshConnectionProperties properties = new SshConnectionProperties();
	properties.setHost("hpbrio");
	properties.setPort(22);
	// Make a client connection
	SshClient ssh = new SshClient(); 
	// Connect to the host
	ssh.connect(properties); 
	PublicKeyAuthenticationClient pk = new PublicKeyAuthenticationClient(); 
	// Get the users name
	String username = user;
	pk.setUsername(username); 
	// Get the private key file
	String filename = pkFile;
	// Open up the private key file
	SshPrivateKeyFile file = SshPrivateKeyFile.parse(new File(filename)); 
	// If the private key is passphrase protected then ask for the passphrase 
	// Get the key
	SshPrivateKey key = file.toPrivateKey(passphrase);
	pk.setKey(key); 
	// Try the authentication
	int result = ssh.authenticate(pk); 
	// Evaluate the result
	if (result == AuthenticationProtocolState.COMPLETE)
	{
	    // The connection is authenticated we can now do some real work!
	    SessionChannelClient session = ssh.openSessionChannel();
	    if(!session.requestPseudoTerminal("vt100", 80, 24, 0, 0, ""))
	    {
		out.println("Failed to allocate a pseudo terminal");
	    }
	    if(session.startShell())
	    {
		out.println("Session Shell Started!"); 
		String line = "";
		ChannelInputStream in = session.getInputStream(); 
		new Thread(new ResponseReader(in)).start();
		session.executeCommand("/bin/bash date");
	    }
	    else
	    {
		out.println("Failed to start the users shell");
	    } 
	    ssh.disconnect();
	}
	else if (result == AuthenticationProtocolState.PARTIAL)
	{
	    out.println("Further authentication requried!");
	}
	else if (result == AuthenticationProtocolState.FAILED)
	{
	    out.println("Authentication failed!");
	}
	else
	{
	    out.println("Error");
	} 
	out.close();
    } 
    static class ResponseReader implements Runnable {
	private boolean stop;
	private InputStream in; 
	public ResponseReader(InputStream in) {
	    this.in = in;
	} 
	public void halt() {
	    stop = true;
	} 
	public void run() {
	    Scanner s = new Scanner(in);
	    while(s.hasNextLine() && !stop) {
		System.out.println(s.nextLine());
	    }
	}
    } 
    private static void printUsage() {
	System.err.println("Usage: java SshText <host> <user> <private key file> <passphrase>");
    }
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:

Select allOpen in new window

 

by: CEHJPosted on 2009-11-09 at 01:34:40ID: 25774477

Sorry, replace line 38 with

>>properties.setHost(host);

 

by: shanemayPosted on 2009-11-09 at 05:47:31ID: 25775828

I cannot thank you enough for your time and effort on my behalf.  It is greatly appreciated.  If I may ask: What did you use to generate the key pair?  

 

by: shanemayPosted on 2009-11-09 at 07:15:38ID: 25776572

I have spoken with our Engineer and we think the problem might be related to the version of openSSH on the server.  If possible may I ask what version you are running.  Ours is 4.3p2.  Again, thank you kindly for your help.  

 

by: CEHJPosted on 2009-11-09 at 09:37:45ID: 25778100

Debian version 1:5.1p1-5 , which is probably 5.1

 

by: shanemayPosted on 2009-11-09 at 12:42:12ID: 25779821

SOLVED.  Thank you for you outstanding help and support in this matter.  The issue is related to the fact that the code does not allow me to verify the Host fingerprint.  That is what is causing the hold up.  

Ok, glad this is done.  Again, thank you for your help.

 

by: shanemayPosted on 2009-11-09 at 12:43:04ID: 31651042

I cannot thank you enough for your time and consideration on my behalf.  Thank you kindly.  

 

by: CEHJPosted on 2009-11-09 at 12:46:34ID: 25779872

>>The issue is related to the fact that the code does not allow me to verify the Host fingerprint

Tell me more ... ;-)

 

by: shanemayPosted on 2009-11-23 at 06:22:21ID: 25887688

Sorry for the late reply.  I do not have a known host file, therefore every time I connect, it wants me to verify the host.  I chose the option to ignore host verification and it worked fine.  I created a known host file so I can avoid the issue in the future.  Again, I really appreciated your help trouble shooting this.  

 

by: CEHJPosted on 2009-11-23 at 07:52:44ID: 25888628

No problem :-)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...