views:

490

answers:

3

I have a text file on a unix machine containing the SSH user name and password that someone might use to connect to it.

How do I verify that the user name and password are valid using Java?

Do I try to SSH connect to the same machine by using Runtime.exec()?

I can grep for the user /etc/passwd. But, the password is shadowed.

I'd appreciate any suggestions.

A: 

If you have root access, then of course you could read /etc/shadow. I would say this is the "correct" way of doing it.

Other than that, your friggly way of calling ssh should be OK I think, but I'd use ssh to run a command that, say, created some random temporary file-- then, if the file was created (or the command carried out), you assume the user name/password was correct. Sounds icky, but you can probably get it to work in an emergency.

Oh, of course, the frig has the side effect that you actually logged in as that user. That may or not be desirable...!

Neil Coffey
+1  A: 

Maybe the question could be broadened to "Validating UNIX Credentials from Java" as the mechanism explained is not really ssh dependant.

Here is my shot as a better Expect-like alternative (e.g. with ProcessBuilder) without using the overhead of a network stack:

su -u username -c echo

Just check the exit status to know the answer. (Bonus points: su is present on all UNIX operating systems, and it's even probably on the PATH and is valid as well for other external authentication system as LDAP).

A: 

Remember that there is more to UNIX authentication than /etc/passwd and /etc/shadow. They could for instance be authenticating against Kerberos, LDAP, NIS or any other number of sources. For this reason, I would highly recommend looking into a PAM wrapper for Java. A quick google turned up http://jpam.sourceforge.net/ but I have no experience with it.

Of course sshd may be configured not to use PAM at all or to only allow certain users, etc. If you want to follow sshd's rules exactly then that changes things, but it sounds like PAM auth is more what you want.

EvilRyry