Ignore:
Timestamp:
03/15/19 16:51:32 (5 years ago)
Author:
bln4
Message:

Alterations to how mail works to work better in a cloud environment.
General code tidying and updating to work with larger changes happening to Expeditee.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/expeditee/auth/Authenticator.java

    r1202 r1243  
    55import java.io.FileNotFoundException;
    66import java.io.FileOutputStream;
    7 import java.io.FileWriter;
    87import java.io.IOException;
    98import java.io.InputStream;
    10 import java.io.Writer;
     9import java.nio.file.Path;
     10import java.nio.file.Paths;
    1111import java.security.KeyFactory;
    1212import java.security.KeyStore;
     
    2222import java.sql.Connection;
    2323import java.sql.DriverManager;
     24import java.sql.PreparedStatement;
    2425import java.sql.ResultSet;
    2526import java.sql.SQLException;
    26 import java.sql.Statement;
    2727import java.util.Arrays;
    2828import java.util.Base64;
     
    3030import java.util.HashMap;
    3131import java.util.Map;
     32import java.util.Scanner;
    3233import java.util.stream.Stream;
    3334
     
    3637
    3738import org.expeditee.actions.Actions;
     39import org.expeditee.auth.tags.Constants;
    3840import org.expeditee.core.Dimension;
    3941import org.expeditee.core.Point;
     
    5052import org.expeditee.gui.FrameUtils;
    5153import org.expeditee.gui.MessageBay;
     54import org.expeditee.io.ExpReader;
     55import org.expeditee.items.Item;
    5256import org.expeditee.items.ItemUtils;
    5357import org.expeditee.items.Text;
    5458import org.expeditee.settings.Settings;
    5559import org.expeditee.settings.UserSettings;
    56 import org.expeditee.settings.auth.secrets.KeyList;
     60import org.expeditee.settings.identity.secrets.KeyList;
    5761import org.ngikm.cryptography.CryptographyConstants;
    5862
     
    6064       
    6165        // The frame number of the frame containing the current authenticated users public key.
    62         public static final int PUBLIC_KEY_FRAME = 4;
     66        public static int CREDENTIALS_FRAME = 13;
     67       
     68        public static boolean Authenticated = false;
    6369       
    6470        private final KeyStore keyStore = KeyStore.getInstance(KeystoreType);
     71               
    6572        private static final byte[] TRUE = "yes".getBytes();
    6673        private static final byte[] FALSE = "no".getBytes();
     
    8289
    8390                // draw the window
    84                 final GraphicsManager g = EcosystemManager.getGraphicsManager();
     91                GraphicsManager g = EcosystemManager.getGraphicsManager();
    8592                g.setWindowLocation(new Point(50, 50));
    8693                DisplayController.Init();
     
    98105               
    99106                // navigate to authentication frame
    100                 final Frame authFrame = FrameIO.LoadFrame("authentication1");
     107                Frame authFrame = FrameIO.LoadFrame("authentication1");
    101108                DisplayController.setCurrentFrame(authFrame, true);
    102109               
    103110                // set initial values
    104                 final Stream<Text> usernameItemsStream = authFrame.getTextItems().stream().filter(t -> t.getData() != null && t.getData().contains("txtUsername"));
    105                 final Stream<Text> passwordItemsStream = authFrame.getTextItems().stream().filter(t -> t.getData() != null && t.getData().contains("txtPassword"));
     111                Stream<Text> usernameItemsStream = authFrame.getTextItems().stream().filter(t -> t.getData() != null && t.getData().contains("txtUsername"));
     112                Stream<Text> passwordItemsStream = authFrame.getTextItems().stream().filter(t -> t.getData() != null && t.getData().contains("txtPassword"));
    106113                usernameItemsStream.forEach(txtUsername -> txtUsername.setText(System.getProperty("user.name", "")));
    107114                passwordItemsStream.forEach(txtPassword -> txtPassword.setText(System.getProperty("user.password", "")));
     
    109116                MessageBay.warningMessages(org.expeditee.actions.Actions.Init());
    110117               
    111                 // ensure database
     118                // class load database classes
    112119                Class.forName("org.sqlite.JDBC");
    113                 if (!mailDatabaseExists()) {
    114                         createMailDatabase();
    115                 }
    116         }
    117        
    118         private void createMailDatabase() throws ClassNotFoundException, SQLException {
    119                 Connection c = DriverManager.getConnection("jdbc:sqlite:" + FrameIO.PARENT_FOLDER + "/expmail.db");
    120                 Statement createTable = c.createStatement();
    121                 String sql = "CREATE TABLE EXPMAIL (" +
    122                                 "SND            TEXT                                    NOT NULL, " +
    123                                 "REC            TEXT                                    NOT NULL, " +
    124                                 "MSG            TEXT                                    NOT NULL, " +
    125                                 "MSG2           TEXT                                    NOT NULL, " +
    126                                 "OPTS           ARRAY                                   NOT NULL, " +
    127                                 "OPTSVAL        ARRAY                                   NOT NULL)";
    128                 createTable.executeUpdate(sql);
    129                 createTable.close();
    130                 c.close();
    131         }
    132        
    133         final void loadMailDatabase() throws SQLException {
    134                 Connection c = DriverManager.getConnection("jdbc:sqlite:" + FrameIO.PARENT_FOLDER + "/expmail.db");
    135                 Statement query = c.createStatement();
    136                 ResultSet results = query.executeQuery("SELECT * FROM EXPMAIL");
    137                 Mail.clear();
    138                 while (results.next()) {
    139                         String from = results.getString("snd");
    140                         String to = results.getString("rec");
    141                         String msg = results.getString("msg");
    142                         String msg2 = results.getString("msg2");
    143                         String[] opts = results.getString("opts").split(",");
     120        }
     121               
     122        private void loadKeystore()
     123                        throws IOException, NoSuchAlgorithmException, CertificateException, FileNotFoundException {
     124                final File keyStoreFile = new File(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME);
     125                if (!keyStoreFile.exists()) {
     126                        keyStore.load(null, Constants.CREDENTIALS_KEYSTORE_PASSWORD.toCharArray());
     127                } else {
     128                        try (final InputStream in = new FileInputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME)) {
     129                                keyStore.load(in, Constants.CREDENTIALS_KEYSTORE_PASSWORD.toCharArray());
     130                        }
     131                }
     132        }
     133       
     134        final void loadMailFromDirectory(Path contactDir) throws SQLException {
     135                // Load in all mail.
     136                Connection c = DriverManager.getConnection("jdbc:sqlite:" + contactDir.resolve("expmail.db"));
     137                String sql = "SELECT * FROM EXPMAIL";
     138                PreparedStatement query = c.prepareStatement(sql);
     139                ResultSet allMail = query.executeQuery();
     140
     141                // Construct all mail objects using content from database.
     142                while(allMail.next()) {
     143                        String timestamp = allMail.getString("time");
     144                        String from = allMail.getString("snd");
     145                        String to = allMail.getString("rec");
     146                        String msg = allMail.getString("msg");
     147                        String msg2 = allMail.getString("msg2");
     148                        String[] opts = allMail.getString("opts").split(",");
    144149                        opts[0] = opts[0].replace("[", "");
    145150                        opts[opts.length - 1] = opts[opts.length - 1].replace("]", "");
    146                         String[] optsVal = results.getString("optsval").split(",");
     151                        String[] optsVal = allMail.getString("optsval").split(",");
    147152                        optsVal[0] = optsVal[0].replace("[", "");
    148153                        optsVal[optsVal.length - 1] = optsVal[optsVal.length - 1].replace("]", "");
     
    155160                        }
    156161                       
    157                         Mail.addEntry(new Mail.MailEntry(from, to, msg, msg2, options));
    158                 }
    159                 results.close();
     162                        Mail.addEntry(new Mail.MailEntry(timestamp, from, to, msg, msg2, options));
     163                }
     164               
     165                // Disconnect from database.
     166                allMail.close();
    160167                query.close();
    161168                c.close();
    162169        }
    163170       
    164         private boolean mailDatabaseExists() {
    165                 final File file = new File(FrameIO.PARENT_FOLDER + "/expmail.db");
    166                 return file.exists();
    167         }
    168                
    169         private void loadKeystore()
    170                         throws IOException, NoSuchAlgorithmException, CertificateException, FileNotFoundException {
    171                 final File keyStoreFile = new File(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME);
    172                 if (!keyStoreFile.exists()) {
    173                         keyStore.load(null, "ExpediteeAuthPassword".toCharArray());
    174                 } else {
    175                         try (final InputStream in = new FileInputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME)) {
    176                                 keyStore.load(in, "ExpediteeAuthPassword".toCharArray());
     171        final void loadMailDatabase() throws SQLException {
     172                Path contactsPath = Paths.get(FrameIO.CONTACTS_PATH);
     173                File[] contacts = contactsPath.toFile().listFiles();
     174                for (int i = 0; i < contacts.length; i++) {
     175                        if (contacts[i].isDirectory()) {
     176                                Path contact = Paths.get(contacts[i].getAbsolutePath());
     177                                loadMailFromDirectory(contact);
    177178                        }
    178179                }
     
    195196                final KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(password.toCharArray());
    196197                keyStore.setEntry(label, entry, entryPassword);
    197                 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
    198         }
    199        
    200         final void putEmail(String username, String email) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {
    201                 // Establish location of email file
    202                 String emailFilePath = FrameIO.PROFILE_PATH + username + File.separator + username + ".email";
    203                 File emailFile = new File(emailFilePath);
    204                
    205                 // Delete old version if it exists.
    206                 if (emailFile.exists()) {
    207                         emailFile.delete();
    208                 }
    209                
    210                 // Write email to file
    211                 emailFile.createNewFile();
    212                 Writer w = new FileWriter(emailFile);
    213                 w.write(email);
    214                 w.flush();
    215                 w.close();
    216                
    217                 // TODO: set rights on file to be read only by 'owner' once installed on drive.
    218         }
    219        
    220         final boolean hasRegisteredEmail(String username) throws KeyStoreException {
    221                 String emailFilePath = FrameIO.PROFILE_PATH + username + File.separator + username + ".email";
    222                 File emailFile = new File(emailFilePath);
    223                 return emailFile.exists();
     198                keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), Constants.CREDENTIALS_KEYSTORE_PASSWORD.toCharArray());
    224199        }
    225200       
     
    232207                        } else if (entry.getSecretKey().getEncoded() == TRUE) {
    233208                                keyStore.deleteEntry(email + username);
    234                                 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
     209                                keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), Constants.CREDENTIALS_KEYSTORE_PASSWORD.toCharArray());
    235210                                return true;
    236211                        } else { return false; }
     
    251226                final KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(intergalacticNumber.toCharArray());
    252227                keyStore.setEntry(email + username, entry, entryPassword);
    253                 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
     228                keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), Constants.CREDENTIALS_KEYSTORE_PASSWORD.toCharArray());
    254229               
    255230                return intergalacticNumber;
    256231        }
    257232       
    258         final PublicKey getPublicKey(String username) throws InvalidKeySpecException, NoSuchAlgorithmException {
    259                 Frame withTargetPublic = FrameIO.LoadFrame(username + Authenticator.PUBLIC_KEY_FRAME);
    260                 Collection<Text> textItems = withTargetPublic.getTextItems();
    261                 textItems.removeIf(t -> !t.getText().startsWith("PublicKey"));
    262                
    263                 if (textItems.isEmpty()) {
     233        final PublicKey getPublicKey(String username) throws InvalidKeySpecException, NoSuchAlgorithmException, FileNotFoundException {
     234                // load in frame with public key on it.
     235                String credentialsFramesetPath = FrameIO.CONTACTS_PATH + username + "-credentials" + File.separator;
     236                if (!new File(credentialsFramesetPath).exists()) {
    264237                        return null;
    265                 } else {
    266                         String keyEncoded = textItems.stream().findFirst().get().getData().get(0);
    267                         byte[] keyBytes = Base64.getDecoder().decode(keyEncoded);
    268                         PublicKey key = KeyFactory.getInstance(AsymmetricAlgorithm).generatePublic(new X509EncodedKeySpec(keyBytes));
    269                         return key;
    270                 }
     238                }
     239                Scanner in = new Scanner(new File(credentialsFramesetPath + "credentials.inf"));
     240                String credentialsFrameNumber = in.nextLine().replace(ExpReader.EXTENTION, "");
     241                in.close();
     242                Frame frame = FrameIO.LoadFrame(username + "-credentials" + credentialsFrameNumber, FrameIO.CONTACTS_PATH);
     243                if (frame == null) {
     244                        return null;
     245                }
     246               
     247                // obtain public key from frame
     248                Collection<Item> canditates = org.expeditee.auth.Actions.getByContent(frame, "PublicKey");
     249                String keyEncoded = "";
     250                for (Item i: canditates) {
     251                        if (i.getData() != null) {
     252                                keyEncoded = i.getData().get(0);
     253                        }
     254                }
     255                if (keyEncoded.isEmpty()) {
     256                        return null;
     257                }
     258                byte[] keyBytes = Base64.getDecoder().decode(keyEncoded);
     259                return KeyFactory.getInstance(AsymmetricAlgorithm).generatePublic(new X509EncodedKeySpec(keyBytes));
    271260        }
    272261       
     
    275264                KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
    276265                keyStore.setEntry(username + "colleaguesRequested", entry, entryPassword);
    277                 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
     266                keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), Constants.CREDENTIALS_KEYSTORE_PASSWORD.toCharArray());
    278267        }
    279268       
     
    282271                KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
    283272                keyStore.setEntry(username + "colleaguesRequested", entry, entryPassword);
    284                 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
     273                keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), Constants.CREDENTIALS_KEYSTORE_PASSWORD.toCharArray());
    285274        }
    286275       
     
    296285        }
    297286       
    298         final void putColleagues(String username, String[] colleagues) throws KeyStoreException {
    299                 String alias = username + "colleagues";
    300                 final SecretKeySpec secretKeySpec = new SecretKeySpec((colleagues[0] + System.getProperty("line.separator") + colleagues[1]).getBytes(), SymmetricAlgorithm);
    301                 KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(secretKeySpec);
    302                 KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
    303                 keyStore.setEntry(alias, entry, entryPassword);
    304         }
    305        
    306         final String[] getColleagues(String username) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
    307                 String alias = username + "colleagues";
    308                 if (!keyStore.containsAlias(alias)) {
    309                         return null;
    310                 } else {
    311                         KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
    312                         KeyStore.SecretKeyEntry entry = (SecretKeyEntry) keyStore.getEntry(alias, entryPassword);
    313                         byte[] colleaguesEncoded = entry.getSecretKey().getEncoded();
    314                         String colleagues = new String(colleaguesEncoded);
    315                         return colleagues.split(System.getProperty("line.separator"));
    316                 }
    317         }
     287//      final void putColleagues(String username, String[] colleagues) throws KeyStoreException {
     288//              String alias = username + "colleagues";
     289//              final SecretKeySpec secretKeySpec = new SecretKeySpec((colleagues[0] + System.getProperty("line.separator") + colleagues[1]).getBytes(), SymmetricAlgorithm);
     290//              KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(secretKeySpec);
     291//              KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
     292//              keyStore.setEntry(alias, entry, entryPassword);
     293//      }
     294//     
     295//      final String[] getColleagues(String username) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
     296//              String alias = username + "colleagues";
     297//              if (!keyStore.containsAlias(alias)) {
     298//                      return null;
     299//              } else {
     300//                      KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
     301//                      KeyStore.SecretKeyEntry entry = (SecretKeyEntry) keyStore.getEntry(alias, entryPassword);
     302//                      byte[] colleaguesEncoded = entry.getSecretKey().getEncoded();
     303//                      String colleagues = new String(colleaguesEncoded);
     304//                      return colleagues.split(System.getProperty("line.separator"));
     305//              }
     306//      }
    318307       
    319308        private static void setInputManagerWindowRoutines()     {
Note: See TracChangeset for help on using the changeset viewer.