source: trunk/src/org/expeditee/auth/Authenticator.java@ 1263

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

When starting Authenticator mode and the authadmin account has not been registered, have the user register it.

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