James Moger
2012-11-28 579cdd4a691adbbe89f85ce679502cf5d1f045d0
src/com/gitblit/authority/GitblitAuthority.java
@@ -61,6 +61,7 @@
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
@@ -88,6 +89,7 @@
import com.gitblit.client.HeaderPanel;
import com.gitblit.client.Translation;
import com.gitblit.models.UserModel;
import com.gitblit.utils.ArrayUtils;
import com.gitblit.utils.StringUtils;
import com.gitblit.utils.TimeUtils;
import com.gitblit.utils.X509Utils;
@@ -115,7 +117,7 @@
   
   private IUserService userService;
   
   private String caKeystorePassword = null;
   private String caKeystorePassword;
   private JTable table;
   
@@ -126,6 +128,8 @@
   private MailExecutor mail;
   private JButton certificateDefaultsButton;
   private JButton newSSLCertificate;
   public static void main(String... args) {
      EventQueue.invokeLater(new Runnable() {
@@ -233,7 +237,6 @@
      }
      gitblitSettings = new FileSettings(file.getAbsolutePath());
      mail = new MailExecutor(gitblitSettings);
      caKeystorePassword = gitblitSettings.getString(Keys.server.storePassword, null);
      String us = gitblitSettings.getString(Keys.realm.userService, "users.conf");
      String ext = us.substring(us.lastIndexOf(".") + 1).toLowerCase();
      IUserService service = null;
@@ -295,13 +298,39 @@
         if (!caKeystore.exists()) {
            // show certificate defaults dialog 
            certificateDefaultsButton.doClick();
            // create "localhost" ssl certificate
            prepareX509Infrastructure();
         }
      }
   }
   
   private void prepareX509Infrastructure() {
   private boolean prepareX509Infrastructure() {
      if (caKeystorePassword == null) {
         JPasswordField pass = new JPasswordField(10){
            private static final long serialVersionUID = 1L;
            public void addNotify()
             {
                 super.addNotify();
                 requestFocusInWindow();
             }
         };
         pass.setText(caKeystorePassword);
         JPanel panel = new JPanel(new BorderLayout());
         panel.add(new JLabel(Translation.get("gb.enterKeystorePassword")), BorderLayout.NORTH);
         panel.add(pass, BorderLayout.CENTER);
         int result = JOptionPane.showConfirmDialog(GitblitAuthority.this, panel, Translation.get("gb.password"), JOptionPane.OK_CANCEL_OPTION);
         if (result == JOptionPane.OK_OPTION) {
            caKeystorePassword = new String(pass.getPassword());
         } else {
            return false;
         }
      }
      X509Metadata metadata = new X509Metadata("localhost", caKeystorePassword);
      X509Utils.prepareX509Infrastructure(metadata, folder, this);
      return true;
   }
   
   private List<X509Certificate> findCerts(File folder, String username) {
@@ -356,15 +385,21 @@
         }
         
         @Override
         public void saveUser(String username, UserCertificateModel ucm) {
            userService.updateUserModel(username, ucm.user);
         public boolean saveUser(String username, UserCertificateModel ucm) {
            return userService.updateUserModel(username, ucm.user);
         }
         
         @Override
         public void newCertificate(UserCertificateModel ucm, X509Metadata metadata, boolean sendEmail) {
            prepareX509Infrastructure();
         public boolean newCertificate(UserCertificateModel ucm, X509Metadata metadata, boolean sendEmail) {
            if (!prepareX509Infrastructure()) {
               return false;
            }
            Date notAfter = metadata.notAfter;
            metadata.serverHostname = gitblitSettings.getString(Keys.web.siteName, "localhost");
            metadata.serverHostname = gitblitSettings.getString(Keys.web.siteName, Constants.NAME);
            if (StringUtils.isEmpty(metadata.serverHostname)) {
               metadata.serverHostname = Constants.NAME;
            }
            UserModel user = ucm.user;            
            
            // set default values from config file
@@ -404,7 +439,7 @@
            File zip = X509Utils.newClientBundle(metadata, caKeystoreFile, caKeystorePassword, GitblitAuthority.this);
            // save latest expiration date
            if (ucm.expires == null || metadata.notAfter.after(ucm.expires)) {
            if (ucm.expires == null || metadata.notAfter.before(ucm.expires)) {
               ucm.expires = metadata.notAfter;
            }
            ucm.update(config);
@@ -421,43 +456,17 @@
            table.getSelectionModel().setSelectionInterval(modelIndex, modelIndex);
            
            if (sendEmail) {
               // send email
               try {
                  if (mail.isReady()) {
                     Message message = mail.createMessage(user.emailAddress);
                     message.setSubject("Your Gitblit client certificate for " + metadata.serverHostname);
                     // body of email
                     String body = X509Utils.processTemplate(new File(caKeystoreFile.getParentFile(), "mail.tmpl"), metadata);
                     if (StringUtils.isEmpty(body)) {
                        body = MessageFormat.format("Hi {0}\n\nHere is your client certificate bundle.\nInside the zip file are installation instructions.", user.getDisplayName());
                     }
                     Multipart mp = new MimeMultipart();
                     MimeBodyPart messagePart = new MimeBodyPart();
                     messagePart.setText(body);
                     mp.addBodyPart(messagePart);
                     // attach zip
                     MimeBodyPart filePart = new MimeBodyPart();
                     FileDataSource fds = new FileDataSource(zip);
                     filePart.setDataHandler(new DataHandler(fds));
                     filePart.setFileName(fds.getName());
                     mp.addBodyPart(filePart);
                     message.setContent(mp);
                     mail.sendNow(message);
                  } else {
                     JOptionPane.showMessageDialog(GitblitAuthority.this, "Sorry, the mail server settings are not configured properly.\nCan not send email.", Translation.get("gb.error"), JOptionPane.ERROR_MESSAGE);
                  }
               } catch (Exception e) {
                  Utils.showException(GitblitAuthority.this, e);
               }
               sendEmail(user, metadata, zip);
            }
            return true;
         }
         
         @Override
         public void revoke(UserCertificateModel ucm, X509Certificate cert, RevocationReason reason) {
         public boolean revoke(UserCertificateModel ucm, X509Certificate cert, RevocationReason reason) {
            if (!prepareX509Infrastructure()) {
               return false;
            }
            File caRevocationList = new File(folder, X509Utils.CA_REVOCATION_LIST);
            File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
            if (X509Utils.revoke(cert, reason, caRevocationList, caKeystoreFile, caKeystorePassword, GitblitAuthority.this)) {
@@ -485,7 +494,10 @@
               tableModel.fireTableDataChanged();
               table.getSelectionModel().setSelectionInterval(modelIndex, modelIndex);
               
               return true;
            }
            return false;
         }
      };
      
@@ -527,7 +539,7 @@
      
      certificateDefaultsButton = new JButton(new ImageIcon(getClass().getResource("/settings_16x16.png")));
      certificateDefaultsButton.setFocusable(false);
      certificateDefaultsButton.setToolTipText(Translation.get("gb.certificateDefaults"));
      certificateDefaultsButton.setToolTipText(Translation.get("gb.newCertificateDefaults"));
      certificateDefaultsButton.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
@@ -570,7 +582,7 @@
            panel.add(oids, BorderLayout.CENTER);
            int result = JOptionPane.showConfirmDialog(GitblitAuthority.this, 
                  panel, Translation.get("gb.certificateDefaults"), JOptionPane.OK_CANCEL_OPTION,
                  panel, Translation.get("gb.newCertificateDefaults"), JOptionPane.OK_CANCEL_OPTION,
                  JOptionPane.QUESTION_MESSAGE, new ImageIcon(getClass().getResource("/settings_32x32.png")));
            if (result == JOptionPane.OK_OPTION) {
               try {
@@ -578,8 +590,6 @@
                  certificateConfig.duration = Integer.parseInt(durationTF.getText());
                  certificateConfig.store(config, metadata);
                  config.save();
                  prepareX509Infrastructure();
               } catch (Exception e1) {
                  Utils.showException(GitblitAuthority.this, e1);
               }
@@ -587,33 +597,95 @@
         }
      });
      
      JButton newWebCertificate = new JButton(new ImageIcon(getClass().getResource("/rosette_16x16.png")));
      newWebCertificate.setFocusable(false);
      newWebCertificate.setToolTipText(Translation.get("gb.newWebCertificate"));
      newWebCertificate.addActionListener(new ActionListener() {
      newSSLCertificate = new JButton(new ImageIcon(getClass().getResource("/rosette_16x16.png")));
      newSSLCertificate.setFocusable(false);
      newSSLCertificate.setToolTipText(Translation.get("gb.newSSLCertificate"));
      newSSLCertificate.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            Date defaultExpiration = new Date(System.currentTimeMillis() + 10*TimeUtils.ONEYEAR);
            NewWebCertificateDialog dialog = new NewWebCertificateDialog(GitblitAuthority.this, defaultExpiration);
            NewSSLCertificateDialog dialog = new NewSSLCertificateDialog(GitblitAuthority.this, defaultExpiration);
            dialog.setModal(true);
            dialog.setVisible(true);
            if (dialog.isCanceled()) {
               return;
            }
            prepareX509Infrastructure();
            Date expires = dialog.getExpiration();
            String hostname = dialog.getHostname();
            final Date expires = dialog.getExpiration();
            final String hostname = dialog.getHostname();
            AuthorityWorker worker = new AuthorityWorker(GitblitAuthority.this) {
               @Override
               protected Boolean doRequest() throws IOException {
                  if (!prepareX509Infrastructure()) {
                     return false;
                  }
                  // read CA private key and certificate
                  File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
                  PrivateKey caPrivateKey = X509Utils.getPrivateKey(X509Utils.CA_ALIAS, caKeystoreFile, caKeystorePassword);
                  X509Certificate caCert = X509Utils.getCertificate(X509Utils.CA_ALIAS, caKeystoreFile, caKeystorePassword);
                  // generate new SSL certificate
                  X509Metadata metadata = new X509Metadata(hostname, caKeystorePassword);
                  metadata.notAfter = expires;
                  File serverKeystoreFile = new File(folder, X509Utils.SERVER_KEY_STORE);
                  X509Certificate cert = X509Utils.newSSLCertificate(metadata, caPrivateKey, caCert, serverKeystoreFile, GitblitAuthority.this);
                  return cert != null;
               }
               @Override
               protected void onSuccess() {
                  JOptionPane.showMessageDialog(GitblitAuthority.this,
                        MessageFormat.format(Translation.get("gb.sslCertificateGenerated"), hostname),
                        Translation.get("gb.newSSLCertificate"), JOptionPane.INFORMATION_MESSAGE);
               }
            };
            
            // read CA private key and certificate
            File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
            PrivateKey caPrivateKey = X509Utils.getPrivateKey(X509Utils.CA_ALIAS, caKeystoreFile, caKeystorePassword);
            X509Certificate caCert = X509Utils.getCertificate(X509Utils.CA_ALIAS, caKeystoreFile, caKeystorePassword);
            worker.execute();
         }
      });
      JButton emailBundle = new JButton(new ImageIcon(getClass().getResource("/mail_16x16.png")));
      emailBundle.setFocusable(false);
      emailBundle.setToolTipText(Translation.get("gb.emailCertificateBundle"));
      emailBundle.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            int row = table.getSelectedRow();
            if (row < 0) {
               return;
            }
            int modelIndex = table.convertRowIndexToModel(row);
            final UserCertificateModel ucm = tableModel.get(modelIndex);
            if (ArrayUtils.isEmpty(ucm.certs)) {
               JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.pleaseGenerateClientCertificate"), ucm.user.getDisplayName()));
            }
            final File zip = new File(folder, X509Utils.CERTS + File.separator + ucm.user.username + File.separator + ucm.user.username + ".zip");
            if (!zip.exists()) {
               return;
            }
            
            // generate new SSL certificate
            X509Metadata metadata = new X509Metadata(hostname, caKeystorePassword);
            metadata.notAfter = expires;
            File serverKeystoreFile = new File(folder, X509Utils.SERVER_KEY_STORE);
            X509Utils.newSSLCertificate(metadata, caPrivateKey, caCert, serverKeystoreFile, GitblitAuthority.this);
            AuthorityWorker worker = new AuthorityWorker(GitblitAuthority.this) {
               @Override
               protected Boolean doRequest() throws IOException {
                  X509Metadata metadata = new X509Metadata(ucm.user.username, "whocares");
                  metadata.serverHostname = gitblitSettings.getString(Keys.web.siteName, Constants.NAME);
                  if (StringUtils.isEmpty(metadata.serverHostname)) {
                     metadata.serverHostname = Constants.NAME;
                  }
                  metadata.userDisplayname = ucm.user.getDisplayName();
                  return sendEmail(ucm.user, metadata, zip);
               }
               @Override
               protected void onSuccess() {
                  JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.clientCertificateBundleSent"),
                        ucm.user.getDisplayName()));
               }
            };
            worker.execute();
         }
      });
      
@@ -631,7 +703,8 @@
      
      JPanel buttonControls = new JPanel(new FlowLayout(FlowLayout.LEFT, Utils.MARGIN, Utils.MARGIN));
      buttonControls.add(certificateDefaultsButton);
      buttonControls.add(newWebCertificate);
      buttonControls.add(newSSLCertificate);
      buttonControls.add(emailBundle);
      JPanel userControls = new JPanel(new FlowLayout(FlowLayout.RIGHT, Utils.MARGIN, Utils.MARGIN));
      userControls.add(new JLabel(Translation.get("gb.filter")));
@@ -708,4 +781,41 @@
         }
      }
   }
   private boolean sendEmail(UserModel user, X509Metadata metadata, File zip) {
      // send email
      try {
         if (mail.isReady()) {
            Message message = mail.createMessage(user.emailAddress);
            message.setSubject("Your Gitblit client certificate for " + metadata.serverHostname);
            // body of email
            String body = X509Utils.processTemplate(new File(folder, X509Utils.CERTS + File.separator + "mail.tmpl"), metadata);
            if (StringUtils.isEmpty(body)) {
               body = MessageFormat.format("Hi {0}\n\nHere is your client certificate bundle.\nInside the zip file are installation instructions.", user.getDisplayName());
            }
            Multipart mp = new MimeMultipart();
            MimeBodyPart messagePart = new MimeBodyPart();
            messagePart.setText(body);
            mp.addBodyPart(messagePart);
            // attach zip
            MimeBodyPart filePart = new MimeBodyPart();
            FileDataSource fds = new FileDataSource(zip);
            filePart.setDataHandler(new DataHandler(fds));
            filePart.setFileName(fds.getName());
            mp.addBodyPart(filePart);
            message.setContent(mp);
            mail.sendNow(message);
            return true;
         } else {
            JOptionPane.showMessageDialog(GitblitAuthority.this, "Sorry, the mail server settings are not configured properly.\nCan not send email.", Translation.get("gb.error"), JOptionPane.ERROR_MESSAGE);
         }
      } catch (Exception e) {
         Utils.showException(GitblitAuthority.this, e);
      }
      return false;
   }
}