source: trunk/src/org/expeditee/auth/AuthenticatorBrowser.java@ 1352

Last change on this file since 1352 was 1352, checked in by bln4, 5 years ago

Refactor of account creation action.
New settings frame to record a users password recovery colleagues.
This new frame is unencrypted.

File size: 19.9 KB
Line 
1package org.expeditee.auth;
2
3import java.io.File;
4import java.io.FileFilter;
5import java.io.FileInputStream;
6import java.io.FileNotFoundException;
7import java.io.FileOutputStream;
8import java.io.FileWriter;
9import java.io.IOException;
10import java.io.InputStream;
11import java.nio.file.Path;
12import java.nio.file.Paths;
13import java.security.KeyFactory;
14import java.security.KeyStore;
15import java.security.KeyStore.SecretKeyEntry;
16import java.security.KeyStoreException;
17import java.security.NoSuchAlgorithmException;
18import java.security.PublicKey;
19import java.security.SecureRandom;
20import java.security.UnrecoverableEntryException;
21import java.security.cert.CertificateException;
22import java.security.spec.InvalidKeySpecException;
23import java.security.spec.X509EncodedKeySpec;
24import java.sql.Connection;
25import java.sql.DriverManager;
26import java.sql.PreparedStatement;
27import java.sql.ResultSet;
28import java.sql.SQLException;
29import java.text.ParseException;
30import java.text.SimpleDateFormat;
31import java.util.Arrays;
32import java.util.Base64;
33import java.util.Collection;
34import java.util.Date;
35import java.util.HashMap;
36import java.util.HashSet;
37import java.util.Map;
38import java.util.Scanner;
39import java.util.Set;
40import java.util.stream.Stream;
41
42import javax.crypto.SecretKey;
43import javax.crypto.spec.SecretKeySpec;
44
45import org.expeditee.actions.Actions;
46import org.expeditee.core.Dimension;
47import org.expeditee.core.Point;
48import org.expeditee.gio.EcosystemManager;
49import org.expeditee.gio.GraphicsManager;
50import org.expeditee.gio.InputManager;
51import org.expeditee.gio.InputManager.WindowEventListener;
52import org.expeditee.gio.InputManager.WindowEventType;
53import org.expeditee.gio.gesture.StandardGestureActions;
54import org.expeditee.gui.Browser;
55import org.expeditee.gui.DisplayController;
56import org.expeditee.gui.Frame;
57import org.expeditee.gui.FrameIO;
58import org.expeditee.gui.FrameUtils;
59import org.expeditee.gui.MessageBay;
60import org.expeditee.io.ExpReader;
61import org.expeditee.items.Item;
62import org.expeditee.items.ItemUtils;
63import org.expeditee.items.Text;
64import org.expeditee.settings.Settings;
65import org.expeditee.settings.UserSettings;
66import org.expeditee.settings.identity.secrets.KeyList;
67import org.expeditee.stats.Formatter;
68import org.ngikm.cryptography.CryptographyConstants;
69
70public final class AuthenticatorBrowser extends Browser implements CryptographyConstants {
71
72 // The frame number of the frame containing the current authenticated users public key.
73 public static int CREDENTIALS_FRAME = -1;
74 public static int PASSWORD_RECOVERY_FRAME = -1;
75 public static final String ADMINACCOUNT = "authadmin";
76 public static final String PROFILEENCRYPTIONLABEL = "Profile";
77
78 public static boolean Authenticated = false;
79
80 private KeyStore keyStore = KeyStore.getInstance(KeystoreType);
81 public static String USER_NOBODY = "nobody";
82
83 private static final byte[] TRUE = "yes".getBytes();
84 private static final byte[] FALSE = "no".getBytes();
85 private static final String KEYSTOREFILENAME = "keystore.ks" + File.separator;
86
87 private static AuthenticatorBrowser instance;
88
89 public static AuthenticatorBrowser getInstance() throws KeyStoreException, FileNotFoundException, NoSuchAlgorithmException, CertificateException, IOException, ClassNotFoundException, SQLException {
90 if (instance == null) { instance = new AuthenticatorBrowser(); }
91 return instance;
92 }
93
94 public static boolean isAuthenticationRequired() {
95 return Boolean.getBoolean("expeditee.authentication");
96 }
97
98 public static boolean isAuthenticated() {
99 return isAuthenticationRequired() && !UserSettings.UserName.get().equals(AuthenticatorBrowser.USER_NOBODY);
100 }
101
102 private AuthenticatorBrowser() throws KeyStoreException, FileNotFoundException, IOException, NoSuchAlgorithmException, CertificateException, ClassNotFoundException, SQLException {
103 super("Authentication");
104 UserSettings.setupDefaultFolders();
105
106 // initialise keystore and actions
107 loadKeystore();
108 Actions.LoadMethods(org.expeditee.auth.Actions.class);
109 Actions.LoadMethods(org.expeditee.auth.sharing.Actions.class);
110
111 // Does the account Authentication.ADMINACCOUNT exist?
112 // If not then we have get the user to assign a password to it.
113 if (!keyStore.containsAlias(AuthenticatorBrowser.ADMINACCOUNT)) {
114 new File(FrameIO.PARENT_FOLDER).mkdirs();
115 protectAdmin();
116 }
117
118 // draw the window
119 GraphicsManager g = EcosystemManager.getGraphicsManager();
120 g.setWindowLocation(new Point(50, 50));
121 DisplayController.Init();
122 g.setWindowSize(new Dimension(UserSettings.InitialWidth.get(), UserSettings.InitialHeight.get()));
123 setInputManagerWindowRoutines();
124
125 // Load documentation and start pages
126 FrameUtils.extractResources(false);
127
128 // Load fonts before loading any frames so the items on the frames will be able to access their fonts
129 Text.InitFonts();
130
131 // initialing settings does not require a user profile established
132 Settings.Init();
133
134 // navigate to authentication frame
135 Frame authFrame = FrameIO.LoadFrame("authentication1");
136 DisplayController.setCurrentFrame(authFrame, true);
137
138 // set initial values
139 Stream<Text> usernameItemsStream = authFrame.getTextItems().stream().filter(t -> t.getData() != null && t.getData().contains("txtUsername"));
140 Stream<Text> passwordItemsStream = authFrame.getTextItems().stream().filter(t -> t.getData() != null && t.getData().contains("txtPassword"));
141 usernameItemsStream.forEach(txtUsername -> txtUsername.setText(System.getProperty("startinguser.name", "")));
142 passwordItemsStream.forEach(txtPassword -> { txtPassword.setText(""); txtPassword.invalidateAll(); });
143
144 MessageBay.warningMessages(org.expeditee.actions.Actions.Init());
145
146 // class load database classes
147 Class.forName("org.sqlite.JDBC");
148 }
149
150 private void protectAdmin() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
151 FileNotFoundException, IOException {
152 // Fetch desired password
153 Scanner in = new Scanner(System.in);
154 System.out.println("No administrative password set.");
155 boolean passwordIsSet = false;
156
157 for (int i = 0; i < 3; i++) {
158 System.out.print("Please enter it now: ");
159 System.out.flush();
160 String password = in.nextLine();
161 System.out.print("And again: ");
162 System.out.flush();
163 if (in.nextLine().equals(password)) {
164 // Register account.
165 putKey(ADMINACCOUNT, password, new SecretKeySpec("null".getBytes(), AsymmetricAlgorithm));
166 in.close();
167 passwordIsSet = true;
168 break;
169 } else {
170 System.out.println("Mismatched passwords, let's try that again.");
171 }
172 }
173
174 if (!passwordIsSet) {
175 System.out.println("Failed to set an admin password. Exiting Expeditee.");
176 System.exit(1);
177 }
178 }
179
180 private void loadKeystore()
181 throws IOException, NoSuchAlgorithmException, CertificateException, FileNotFoundException {
182 final File keyStoreFile = new File(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME);
183 if (!keyStoreFile.exists()) {
184 keyStore.load(null, "ExpediteeAuthPassword".toCharArray());
185 } else {
186 try (final InputStream in = new FileInputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME)) {
187 keyStore.load(in, "ExpediteeAuthPassword".toCharArray());
188 }
189 }
190 }
191
192 final void loadMailFromFile(Path dbFile) throws SQLException {
193 // Load in all mail.
194 Connection c = DriverManager.getConnection("jdbc:sqlite:" + dbFile.toAbsolutePath().toString());
195 String sql = "SELECT * FROM EXPMAIL";
196 PreparedStatement query = c.prepareStatement(sql);
197 ResultSet allMail = query.executeQuery();
198
199 // Construct all mail objects using content from database.
200 while(allMail.next()) {
201 String timestamp = allMail.getString("time");
202 String from = allMail.getString("snd");
203 String to = allMail.getString("rec");
204 String msg = allMail.getString("msg");
205 String msg2 = allMail.getString("msg2");
206 String[] opts = allMail.getString("opts").split(",");
207 opts[0] = opts[0].replace("[", "");
208 opts[opts.length - 1] = opts[opts.length - 1].replace("]", "");
209 String[] optsVal = allMail.getString("optsval").split(",");
210 optsVal[0] = optsVal[0].replace("[", "");
211 optsVal[optsVal.length - 1] = optsVal[optsVal.length - 1].replace("]", "");
212
213 Map<String, String> options = new HashMap<String, String>();
214 for (int i = 0, o = 0; i < opts.length && o < optsVal.length; i++, o++) {
215 String key = opts[i].trim();
216 String val = optsVal[o].trim();
217 options.put(key, val);
218 }
219
220 Mail.addEntry(new Mail.MailEntry(timestamp, from, to, msg, msg2, options));
221 }
222
223 // Disconnect from database.
224 allMail.close();
225 query.close();
226 c.close();
227 }
228
229 public final void loadMailDatabase() throws SQLException, FileNotFoundException, ParseException {
230 Path deadDropPath = Paths.get(FrameIO.DEAD_DROPS_PATH);
231 for (File connectionDir: deadDropPath.toFile().listFiles()) {
232 if (connectionDir.isDirectory()) {
233 Path deaddropforcontactPath = Paths.get(connectionDir.getAbsolutePath());
234 Path dbFile = deaddropforcontactPath.resolve(UserSettings.UserName.get() + ".db");
235 if (dbFile.toFile().exists()) {
236 loadMailFromFile(dbFile);
237 }
238 clearOldMailFromDatabase(deaddropforcontactPath);
239 }
240 }
241 }
242
243 public final void updateLastReadMailTime(Path deaddropforcontactPath) {
244 Path timestamp = deaddropforcontactPath.resolve(UserSettings.UserName.get() + ".last-accessed");
245 try(FileWriter out = new FileWriter(timestamp.toFile())) {
246 out.write(Formatter.getDateTime() + System.getProperty("line.separator"));
247 } catch (IOException e) {
248 e.printStackTrace();
249 }
250 }
251
252 private void clearOldMailFromDatabase(Path directory) throws FileNotFoundException, ParseException, SQLException {
253 File[] files = directory.toFile().listFiles(new FileFilter() {
254 @Override
255 public boolean accept(File file) {
256 return !file.getName().startsWith(UserSettings.UserName.get());
257 }
258 });
259
260 File dbFile = null;
261 File lastAccessedFile = null;
262 for (File file: files) {
263 if (file.getName().endsWith(".db")) {
264 dbFile = file;
265 } else {
266 lastAccessedFile = file;
267 }
268 }
269
270 if (dbFile == null || lastAccessedFile == null) {
271 return; // Not the end of the world if we cannot clear out old messages, these files may not be present yet if the others are recently new.
272 }
273
274 SimpleDateFormat format = new SimpleDateFormat("ddMMMyyyy[HH:mm]");
275 Date timestamp = null;
276 try(Scanner in = new Scanner(lastAccessedFile)) {
277 timestamp = format.parse(in.nextLine());
278 } catch (ParseException e) {
279 return; // Not the end of the world if we cannot clear out old messages, the database might be empty.
280 }
281
282 Connection c = DriverManager.getConnection("jdbc:sqlite:" + dbFile.getAbsolutePath());
283 String sql = "SELECT * FROM EXPMAIL";
284 PreparedStatement query = c.prepareStatement(sql);
285 ResultSet allMail = query.executeQuery();
286 Set<String> oldTimestamps = new HashSet<String>();
287
288 while (allMail.next()) {
289 String time = allMail.getString("time");
290 Date messageTimestamp = format.parse(time);
291 if (timestamp.after(messageTimestamp)) {
292 oldTimestamps.add(time);
293 }
294 }
295
296 if (oldTimestamps.isEmpty()) {
297 return;
298 }
299
300 for(String oldTimestamp: oldTimestamps) {
301 System.out.println("Deleting message with timestamp: " + oldTimestamp);
302 sql = "DELETE FROM EXPMAIL WHERE time='" + oldTimestamp + "'";
303 query = c.prepareStatement(sql);
304 query.executeUpdate();
305 }
306 }
307
308 public final SecretKey getSecretKey(final String label, final String password) throws NoSuchAlgorithmException, KeyStoreException {
309
310 char[] password_ca = password.toCharArray();
311
312 SecretKey secret_key;
313 try {
314 secret_key = (SecretKey) keyStore.getKey(label, password_ca);
315 } catch (final UnrecoverableEntryException e) {
316 return null;
317 }
318
319 return secret_key;
320 }
321
322 public final void putKey(final String label, final String password, final SecretKey key) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {
323 final KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(key);
324 final KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(password.toCharArray());
325 keyStore.setEntry(label, entry, entryPassword);
326 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
327 }
328
329 public final boolean confirmIntergalaticNumber(final String username, final String email, final String intergalacticNumber) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException {
330 try {
331 final KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(intergalacticNumber.toCharArray());
332 final KeyStore.SecretKeyEntry entry = (SecretKeyEntry) keyStore.getEntry(email + username, entryPassword);
333 if (entry == null) {
334 return false;
335 } else if (Arrays.equals(entry.getSecretKey().getEncoded(), TRUE)) {
336 keyStore.deleteEntry(email + username);
337 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
338 return true;
339 } else { return false; }
340 } catch (final UnrecoverableEntryException e) {
341 return false;
342 }
343 }
344
345 public final String newIntergalacticNumber(final String username, final String email) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {
346 // generate intergalactic number
347 SecureRandom rand = new SecureRandom();
348 byte[] intergalacticNumberBytes = new byte[10];
349 rand.nextBytes(intergalacticNumberBytes);
350 String intergalacticNumber = Base64.getEncoder().encodeToString(intergalacticNumberBytes);
351
352 // store intergalactic number
353 final KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(new SecretKeySpec(TRUE, SymmetricAlgorithm));
354 final KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(intergalacticNumber.toCharArray());
355 keyStore.setEntry(email + username, entry, entryPassword);
356 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
357
358 return intergalacticNumber;
359 }
360
361 public final PublicKey getPublicKey(String username) throws InvalidKeySpecException, NoSuchAlgorithmException, FileNotFoundException {
362 // load in frame with public key on it.
363 String credentialsFramesetPath = FrameIO.CONTACTS_PATH + username + "-credentials" + File.separator;
364 if (!new File(credentialsFramesetPath).exists()) {
365 return null;
366 }
367 Scanner in = new Scanner(new File(credentialsFramesetPath + "credentials.inf"));
368 String credentialsFrameNumber = in.nextLine().replace(ExpReader.EXTENTION, "");
369 in.close();
370 Frame frame = FrameIO.LoadFrame(username + "-credentials" + credentialsFrameNumber, FrameIO.CONTACTS_PATH);
371 if (frame == null) {
372 return null;
373 }
374
375 // obtain public key from frame
376 Collection<Item> canditates = org.expeditee.auth.Actions.getByContent(frame, "PublicKey");
377 String keyEncoded = "";
378 for (Item i: canditates) {
379 if (i.getData() != null) {
380 keyEncoded = i.getData().get(0);
381 }
382 }
383 if (keyEncoded.isEmpty()) {
384 return null;
385 }
386 byte[] keyBytes = Base64.getDecoder().decode(keyEncoded);
387 return KeyFactory.getInstance(AsymmetricAlgorithm).generatePublic(new X509EncodedKeySpec(keyBytes));
388 }
389
390 public final void markRequestedColleagues(String username) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {
391 KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(new SecretKeySpec(TRUE, SymmetricAlgorithm));
392 KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
393 keyStore.setEntry(username + "colleaguesRequested", entry, entryPassword);
394 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
395 }
396
397 public final void clearRequestedColleagues(String username) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {
398 KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(new SecretKeySpec(FALSE, SymmetricAlgorithm));
399 KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
400 keyStore.setEntry(username + "colleaguesRequested", entry, entryPassword);
401 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
402 }
403
404 public final boolean hasRequestedColleagues(String username) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
405 String alias = username + "colleaguesRequested";
406 if (!keyStore.containsAlias(alias)) {
407 return false;
408 } else {
409 KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
410 KeyStore.SecretKeyEntry entry = (SecretKeyEntry) keyStore.getEntry(alias, entryPassword);
411 return Arrays.equals(entry.getSecretKey().getEncoded(), TRUE);
412 }
413 }
414
415// final void putColleagues(String username, String[] colleagues) throws KeyStoreException {
416// String alias = username + "colleagues";
417// final SecretKeySpec secretKeySpec = new SecretKeySpec((colleagues[0] + System.getProperty("line.separator") + colleagues[1]).getBytes(), SymmetricAlgorithm);
418// KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(secretKeySpec);
419// KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
420// keyStore.setEntry(alias, entry, entryPassword);
421// }
422//
423// final String[] getColleagues(String username) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
424// String alias = username + "colleagues";
425// if (!keyStore.containsAlias(alias)) {
426// return null;
427// } else {
428// KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
429// KeyStore.SecretKeyEntry entry = (SecretKeyEntry) keyStore.getEntry(alias, entryPassword);
430// byte[] colleaguesEncoded = entry.getSecretKey().getEncoded();
431// String colleagues = new String(colleaguesEncoded);
432// return colleagues.split(System.getProperty("line.separator"));
433// }
434// }
435
436 private static void setInputManagerWindowRoutines() {
437 InputManager manager = EcosystemManager.getInputManager();
438
439 // Refresh the layout when the window resizes
440 manager.addWindowEventListener(new WindowEventListener() {
441 @Override
442 public void onWindowEvent(WindowEventType type)
443 {
444 if (type != WindowEventType.WINDOW_RESIZED) {
445 return;
446 }
447 DisplayController.refreshWindowSize();
448 FrameIO.RefreshCacheImages();
449 for (Frame frame : DisplayController.getFrames()) {
450 if (frame != null) {
451 ItemUtils.Justify(frame);
452 frame.refreshSize();
453 }
454 }
455 DisplayController.requestRefresh(false);
456 }
457 });
458
459 manager.addWindowEventListener(new WindowEventListener() {
460 @Override
461 public void onWindowEvent(WindowEventType type)
462 {
463 if (type != WindowEventType.MOUSE_EXITED_WINDOW) {
464 return;
465 }
466 StandardGestureActions.mouseExitedWindow();
467 }
468 });
469
470 manager.addWindowEventListener(new WindowEventListener() {
471 @Override
472 public void onWindowEvent(WindowEventType type)
473 {
474 if (type != WindowEventType.MOUSE_ENTERED_WINDOW) {
475 return;
476 }
477 StandardGestureActions.mouseEnteredWindow();
478 }
479 });
480
481 manager.addWindowEventListener(new WindowEventListener() {
482 @Override
483 public void onWindowEvent(WindowEventType type)
484 {
485 if (type != WindowEventType.WINDOW_CLOSED) {
486 return;
487 }
488 if (Browser._theBrowser != null) {
489 Browser._theBrowser.exit();
490 }
491 }
492 });
493 }
494}
Note: See TracBrowser for help on using the repository browser.