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

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

Fixes to permission on items.

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 @SuppressWarnings("resource")
154 Scanner in = new Scanner(System.in);
155 System.out.println("No administrative password set.");
156 boolean passwordIsSet = false;
157
158 for (int i = 0; i < 3; i++) {
159 System.out.print("Please enter it now: ");
160 System.out.flush();
161 String password = in.nextLine();
162 System.out.print("And again: ");
163 System.out.flush();
164 if (in.nextLine().equals(password)) {
165 // Register account.
166 putKey(ADMINACCOUNT, password, new SecretKeySpec("null".getBytes(), AsymmetricAlgorithm));
167 //in.close();
168 passwordIsSet = true;
169 break;
170 } else {
171 System.out.println("Mismatched passwords, let's try that again.");
172 }
173 }
174
175 if (!passwordIsSet) {
176 System.out.println("Failed to set an admin password. Exiting Expeditee.");
177 System.exit(1);
178 }
179 }
180
181 private void loadKeystore()
182 throws IOException, NoSuchAlgorithmException, CertificateException, FileNotFoundException {
183 final File keyStoreFile = new File(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME);
184 if (!keyStoreFile.exists()) {
185 keyStore.load(null, "ExpediteeAuthPassword".toCharArray());
186 } else {
187 try (final InputStream in = new FileInputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME)) {
188 keyStore.load(in, "ExpediteeAuthPassword".toCharArray());
189 }
190 }
191 }
192
193 final void loadMailFromFile(Path dbFile) throws SQLException {
194 // Load in all mail.
195 Connection c = DriverManager.getConnection("jdbc:sqlite:" + dbFile.toAbsolutePath().toString());
196 String sql = "SELECT * FROM EXPMAIL";
197 PreparedStatement query = c.prepareStatement(sql);
198 ResultSet allMail = query.executeQuery();
199
200 // Construct all mail objects using content from database.
201 while(allMail.next()) {
202 String timestamp = allMail.getString("time");
203 String from = allMail.getString("snd");
204 String to = allMail.getString("rec");
205 String msg = allMail.getString("msg");
206 String msg2 = allMail.getString("msg2");
207 String[] opts = allMail.getString("opts").split(",");
208 opts[0] = opts[0].replace("[", "");
209 opts[opts.length - 1] = opts[opts.length - 1].replace("]", "");
210 String[] optsVal = allMail.getString("optsval").split(",");
211 optsVal[0] = optsVal[0].replace("[", "");
212 optsVal[optsVal.length - 1] = optsVal[optsVal.length - 1].replace("]", "");
213
214 Map<String, String> options = new HashMap<String, String>();
215 for (int i = 0, o = 0; i < opts.length && o < optsVal.length; i++, o++) {
216 String key = opts[i].trim();
217 String val = optsVal[o].trim();
218 options.put(key, val);
219 }
220
221 Mail.addEntry(new Mail.MailEntry(timestamp, from, to, msg, msg2, options));
222 }
223
224 // Disconnect from database.
225 allMail.close();
226 query.close();
227 c.close();
228 }
229
230 public final void loadMailDatabase() throws SQLException, FileNotFoundException, ParseException {
231 Path deadDropPath = Paths.get(FrameIO.DEAD_DROPS_PATH);
232 for (File connectionDir: deadDropPath.toFile().listFiles()) {
233 if (connectionDir.isDirectory()) {
234 Path deaddropforcontactPath = Paths.get(connectionDir.getAbsolutePath());
235 Path dbFile = deaddropforcontactPath.resolve(UserSettings.UserName.get() + ".db");
236 if (dbFile.toFile().exists()) {
237 loadMailFromFile(dbFile);
238 }
239 clearOldMailFromDatabase(deaddropforcontactPath);
240 }
241 }
242 }
243
244 public final void updateLastReadMailTime(Path deaddropforcontactPath) {
245 Path timestamp = deaddropforcontactPath.resolve(UserSettings.UserName.get() + ".last-accessed");
246 try(FileWriter out = new FileWriter(timestamp.toFile())) {
247 out.write(Formatter.getDateTime() + System.getProperty("line.separator"));
248 } catch (IOException e) {
249 e.printStackTrace();
250 }
251 }
252
253 private void clearOldMailFromDatabase(Path directory) throws FileNotFoundException, ParseException, SQLException {
254 File[] files = directory.toFile().listFiles(new FileFilter() {
255 @Override
256 public boolean accept(File file) {
257 return !file.getName().startsWith(UserSettings.UserName.get());
258 }
259 });
260
261 File dbFile = null;
262 File lastAccessedFile = null;
263 for (File file: files) {
264 if (file.getName().endsWith(".db")) {
265 dbFile = file;
266 } else {
267 lastAccessedFile = file;
268 }
269 }
270
271 if (dbFile == null || lastAccessedFile == null) {
272 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.
273 }
274
275 SimpleDateFormat format = new SimpleDateFormat("ddMMMyyyy[HH:mm]");
276 Date timestamp = null;
277 try(Scanner in = new Scanner(lastAccessedFile)) {
278 timestamp = format.parse(in.nextLine());
279 } catch (ParseException e) {
280 return; // Not the end of the world if we cannot clear out old messages, the database might be empty.
281 }
282
283 Connection c = DriverManager.getConnection("jdbc:sqlite:" + dbFile.getAbsolutePath());
284 String sql = "SELECT * FROM EXPMAIL";
285 PreparedStatement query = c.prepareStatement(sql);
286 ResultSet allMail = query.executeQuery();
287 Set<String> oldTimestamps = new HashSet<String>();
288
289 while (allMail.next()) {
290 String time = allMail.getString("time");
291 Date messageTimestamp = format.parse(time);
292 if (timestamp.after(messageTimestamp)) {
293 oldTimestamps.add(time);
294 }
295 }
296
297 if (oldTimestamps.isEmpty()) {
298 return;
299 }
300
301 for(String oldTimestamp: oldTimestamps) {
302 System.out.println("Deleting message with timestamp: " + oldTimestamp);
303 sql = "DELETE FROM EXPMAIL WHERE time='" + oldTimestamp + "'";
304 query = c.prepareStatement(sql);
305 query.executeUpdate();
306 }
307 }
308
309 public final SecretKey getSecretKey(final String label, final String password) throws NoSuchAlgorithmException, KeyStoreException {
310
311 char[] password_ca = password.toCharArray();
312
313 SecretKey secret_key;
314 try {
315 secret_key = (SecretKey) keyStore.getKey(label, password_ca);
316 } catch (final UnrecoverableEntryException e) {
317 return null;
318 }
319
320 return secret_key;
321 }
322
323 public final void putKey(final String label, final String password, final SecretKey key) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {
324 final KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(key);
325 final KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(password.toCharArray());
326 keyStore.setEntry(label, entry, entryPassword);
327 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
328 }
329
330 public final boolean confirmIntergalaticNumber(final String username, final String intergalacticNumber) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException {
331 try {
332 KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(intergalacticNumber.toCharArray());
333 KeyStore.SecretKeyEntry entry = (SecretKeyEntry) keyStore.getEntry(username + "_IntergalacticNumber", entryPassword);
334 if (entry == null) {
335 return false;
336 } else if (Arrays.equals(entry.getSecretKey().getEncoded(), TRUE)) {
337 keyStore.deleteEntry(username + "_IntergalacticNumber");
338 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
339 return true;
340 } else {
341 return false;
342 }
343 } catch (final UnrecoverableEntryException e) {
344 return false;
345 }
346 }
347
348 public final String newIntergalacticNumber(final String username, final String email) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {
349 // generate intergalactic number
350 SecureRandom rand = new SecureRandom();
351 byte[] intergalacticNumberBytes = new byte[10];
352 rand.nextBytes(intergalacticNumberBytes);
353 String intergalacticNumber = Base64.getEncoder().encodeToString(intergalacticNumberBytes);
354
355 // store intergalactic number
356 KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(new SecretKeySpec(TRUE, SymmetricAlgorithm));
357 KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(intergalacticNumber.toCharArray());
358 keyStore.setEntry(username + "_IntergalacticNumber", entry, entryPassword);
359 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
360
361 return intergalacticNumber;
362 }
363
364 public final PublicKey getPublicKey(String username) throws InvalidKeySpecException, NoSuchAlgorithmException, FileNotFoundException {
365 // load in frame with public key on it.
366 String credentialsFramesetPath = FrameIO.CONTACTS_PATH + username + "-credentials" + File.separator;
367 if (!new File(credentialsFramesetPath).exists()) {
368 return null;
369 }
370 Scanner in = new Scanner(new File(credentialsFramesetPath + "credentials.inf"));
371 String credentialsFrameNumber = in.nextLine().replace(ExpReader.EXTENTION, "");
372 in.close();
373 Frame frame = FrameIO.LoadFrame(username + "-credentials" + credentialsFrameNumber, FrameIO.CONTACTS_PATH);
374 if (frame == null) {
375 return null;
376 }
377
378 // obtain public key from frame
379 Collection<Item> canditates = org.expeditee.auth.Actions.getByContent(frame, "PublicKey");
380 String keyEncoded = "";
381 for (Item i: canditates) {
382 if (i.getData() != null) {
383 keyEncoded = i.getData().get(0);
384 }
385 }
386 if (keyEncoded.isEmpty()) {
387 return null;
388 }
389 byte[] keyBytes = Base64.getDecoder().decode(keyEncoded);
390 return KeyFactory.getInstance(AsymmetricAlgorithm).generatePublic(new X509EncodedKeySpec(keyBytes));
391 }
392
393 public final void markRequestedColleagues(String username) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {
394 KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(new SecretKeySpec(TRUE, SymmetricAlgorithm));
395 KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
396 keyStore.setEntry(username + "colleaguesRequested", entry, entryPassword);
397 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
398 }
399
400 public final void clearRequestedColleagues(String username) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {
401 KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(new SecretKeySpec(FALSE, SymmetricAlgorithm));
402 KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
403 keyStore.setEntry(username + "colleaguesRequested", entry, entryPassword);
404 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
405 }
406
407 public final boolean hasRequestedColleagues(String username) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
408 String alias = username + "colleaguesRequested";
409 if (!keyStore.containsAlias(alias)) {
410 return false;
411 } else {
412 KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
413 KeyStore.SecretKeyEntry entry = (SecretKeyEntry) keyStore.getEntry(alias, entryPassword);
414 return Arrays.equals(entry.getSecretKey().getEncoded(), TRUE);
415 }
416 }
417
418// final void putColleagues(String username, String[] colleagues) throws KeyStoreException {
419// String alias = username + "colleagues";
420// final SecretKeySpec secretKeySpec = new SecretKeySpec((colleagues[0] + System.getProperty("line.separator") + colleagues[1]).getBytes(), SymmetricAlgorithm);
421// KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(secretKeySpec);
422// KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
423// keyStore.setEntry(alias, entry, entryPassword);
424// }
425//
426// final String[] getColleagues(String username) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
427// String alias = username + "colleagues";
428// if (!keyStore.containsAlias(alias)) {
429// return null;
430// } else {
431// KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
432// KeyStore.SecretKeyEntry entry = (SecretKeyEntry) keyStore.getEntry(alias, entryPassword);
433// byte[] colleaguesEncoded = entry.getSecretKey().getEncoded();
434// String colleagues = new String(colleaguesEncoded);
435// return colleagues.split(System.getProperty("line.separator"));
436// }
437// }
438
439 private static void setInputManagerWindowRoutines() {
440 InputManager manager = EcosystemManager.getInputManager();
441
442 // Refresh the layout when the window resizes
443 manager.addWindowEventListener(new WindowEventListener() {
444 @Override
445 public void onWindowEvent(WindowEventType type)
446 {
447 if (type != WindowEventType.WINDOW_RESIZED) {
448 return;
449 }
450 DisplayController.refreshWindowSize();
451 FrameIO.RefreshCacheImages();
452 for (Frame frame : DisplayController.getFrames()) {
453 if (frame != null) {
454 ItemUtils.Justify(frame);
455 frame.refreshSize();
456 }
457 }
458 DisplayController.requestRefresh(false);
459 }
460 });
461
462 manager.addWindowEventListener(new WindowEventListener() {
463 @Override
464 public void onWindowEvent(WindowEventType type)
465 {
466 if (type != WindowEventType.MOUSE_EXITED_WINDOW) {
467 return;
468 }
469 StandardGestureActions.mouseExitedWindow();
470 }
471 });
472
473 manager.addWindowEventListener(new WindowEventListener() {
474 @Override
475 public void onWindowEvent(WindowEventType type)
476 {
477 if (type != WindowEventType.MOUSE_ENTERED_WINDOW) {
478 return;
479 }
480 StandardGestureActions.mouseEnteredWindow();
481 }
482 });
483
484 manager.addWindowEventListener(new WindowEventListener() {
485 @Override
486 public void onWindowEvent(WindowEventType type)
487 {
488 if (type != WindowEventType.WINDOW_CLOSED) {
489 return;
490 }
491 if (Browser._theBrowser != null) {
492 Browser._theBrowser.exit();
493 }
494 }
495 });
496 }
497}
Note: See TracBrowser for help on using the repository browser.