How to check Unix credentials in a Java program How to check Unix credentials in a Java program unix unix

How to check Unix credentials in a Java program


sudo asks for the password of the current user, that is, the user that started the java process, so it will not check against user's password.

Instead of "/bin/sh","-c","sudo","-S","su",user).start();try "/bin/sh","-c","su",user).start();. This will just attempt to switch to that user, and as such will ask for user's password.


Based on su.c source code I've wrote a simple java program that makes the user credentials verification using JNA. It must works on all Unix based distributions that have the libc and crypt libraries, bellow a code snippet:

public static void main(String[] args) {    final Scanner scanner = new Scanner(System.in);    System.out.println("type the user");    final String user = scanner.nextLine();    System.out.println("type password");    final String password = scanner.nextLine();    System.out.println("RESULT\n===========================================");    final SPassword passwd = CLibrary.INSTANCE.getspnam(user);    if(passwd == null){        throw new RuntimeException(String.valueOf(Native.getLastError()));    }    final String encrypted = Crypt.INSTANCE.crypt(password, passwd.sp_pwdp);    System.out.printf("matches=%b%n", encrypted.equals(passwd.sp_pwdp));}interface Crypt extends Library {    Crypt INSTANCE = Native.loadLibrary("crypt", Crypt.class);    String crypt(String key, String salt);}interface CLibrary extends Library {    CLibrary INSTANCE = Native.loadLibrary("c", CLibrary.class);    Password getpwnam(String username);    SPassword getspnam(String username);}

Testing

git clone https://github.com/mageddo/java-native-examples.git &&\cd java-native-examples && git checkout -f ef4eb3e &&\./gradlew clean build fatjar &&\sudo java -jar build/libs/java-native-examples-all-*.jar

out

type the userelvistype password*********RESULT===========================================matches=true

Obs: The drawback is this application must run as root or sudo user, I can't fix that yet, anyway I think it is possible once su command don't need, for security reasons(if it is a problem in your context) I suggest to isolate this functionality to a application then call it by REST, Soap, TCP, whatever. this way your current application will not need to run as root.

If you want you can replace crypt function by apache commons codec lib function that do the same thing.

Reference