licensing update to APSL 2.0
[org.ibex.crypto.git] / src / org / ibex / crypto / EtcPasswd.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.crypto;
6 import org.ibex.util.*;
7 import java.util.*;
8 import java.io.*;
9
10 /**
11  *  Right now this is a big fat hack; at some point it would be nice
12  *  to try lots of different techniques (JNI/getpwent(),
13  *  Runtime.exec(),
14  *  http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/libcrypt/crypt-md5.c
15  *
16  *  Also, this currently assumes that the user has MD5 passwords
17  *  enabled and OpenSSL installed.
18  */
19 public class EtcPasswd {
20     public static boolean verify(String user, String pass) {
21         try {
22             BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("/etc/passwd")));
23             for(String s = br.readLine(); s != null; s = br.readLine()) {
24                 StringTokenizer st = new StringTokenizer(s, ":");
25                 if (!user.equals(st.nextToken())) continue;
26                 try {
27                     String stuff = st.nextToken();
28                     StringTokenizer st2 = new StringTokenizer(stuff, "$");
29                     st2.nextToken();
30                     String salt = st2.nextToken();
31                     Process p =
32                         Runtime.getRuntime().exec(new String[] {
33                             "/usr/bin/openssl",
34                             "passwd",
35                             "-1",
36                             "-stdin",
37                             "-salt",
38                             salt });
39                     PrintWriter pw = new PrintWriter(p.getOutputStream());
40                     pw.println(pass);
41                     pw.flush();
42                     pw.close();
43                     BufferedReader br2 = new BufferedReader(new InputStreamReader(p.getInputStream()));
44                     String recrypt = br2.readLine();
45                     p.waitFor();
46                     if (recrypt.equals(stuff)) return true;
47                 } catch (Exception e) { Log.warn(EtcPasswd.class, e); }
48             }
49         } catch (Exception e) { Log.warn(EtcPasswd.class, e); }
50         return false;
51     }
52 }