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

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

Moved things out of the old NGIKM package and deleted it.

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